org-tempo.el: New file for expansion of templates
[org-mode.git] / lisp / org.el
bloba5c1182dae6adfa494bbe2a251f711ba81a20e6c
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 (defun org-unlogged-message (&rest args)
6596 "Display a message, but avoid logging it in the *Messages* buffer."
6597 (let ((message-log-max nil))
6598 (apply 'message args)))
6600 ;;;###autoload
6601 (defun org-cycle (&optional arg)
6602 "TAB-action and visibility cycling for Org mode.
6604 This is the command invoked in Org mode by the `TAB' key. Its main
6605 purpose is outline visibility cycling, but it also invokes other actions
6606 in special contexts.
6608 When this function is called with a `\\[universal-argument]' prefix, rotate \
6609 the entire
6610 buffer through 3 states (global cycling)
6611 1. OVERVIEW: Show only top-level headlines.
6612 2. CONTENTS: Show all headlines of all levels, but no body text.
6613 3. SHOW ALL: Show everything.
6615 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6616 switch to the startup visibility,
6617 determined by the variable `org-startup-folded', and by any VISIBILITY
6618 properties in the buffer.
6620 With a `\\[universal-argument] \\[universal-argument] \
6621 \\[universal-argument]' prefix argument, show the entire buffer, including
6622 any drawers.
6624 When inside a table, re-align the table and move to the next field.
6626 When point is at the beginning of a headline, rotate the subtree started
6627 by this line through 3 different states (local cycling)
6628 1. FOLDED: Only the main headline is shown.
6629 2. CHILDREN: The main headline and the direct children are shown.
6630 From this state, you can move to one of the children
6631 and zoom in further.
6632 3. SUBTREE: Show the entire subtree, including body text.
6633 If there is no subtree, switch directly from CHILDREN to FOLDED.
6635 When point is at the beginning of an empty headline and the variable
6636 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6637 of the headline by demoting and promoting it to likely levels. This
6638 speeds up creation document structure by pressing `TAB' once or several
6639 times right after creating a new headline.
6641 When there is a numeric prefix, go up to a heading with level ARG, do
6642 a `show-subtree' and return to the previous cursor position. If ARG
6643 is negative, go up that many levels.
6645 When point is not at the beginning of a headline, execute the global
6646 binding for `TAB', which is re-indenting the line. See the option
6647 `org-cycle-emulate-tab' for details.
6649 As a special case, if point is at the beginning of the buffer and there is
6650 no headline in line 1, this function will act as if called with prefix arg
6651 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6652 prefix arg, but only
6653 if the variable `org-cycle-global-at-bob' is t."
6654 (interactive "P")
6655 (org-load-modules-maybe)
6656 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6657 (and org-cycle-level-after-item/entry-creation
6658 (or (org-cycle-level)
6659 (org-cycle-item-indentation))))
6660 (let* ((limit-level
6661 (or org-cycle-max-level
6662 (and (boundp 'org-inlinetask-min-level)
6663 org-inlinetask-min-level
6664 (1- org-inlinetask-min-level))))
6665 (nstars (and limit-level
6666 (if org-odd-levels-only
6667 (and limit-level (1- (* limit-level 2)))
6668 limit-level)))
6669 (org-outline-regexp
6670 (if (not (derived-mode-p 'org-mode))
6671 outline-regexp
6672 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6673 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6674 (not (looking-at org-outline-regexp))))
6675 (org-cycle-hook
6676 (if bob-special
6677 (delq 'org-optimize-window-after-visibility-change
6678 (copy-sequence org-cycle-hook))
6679 org-cycle-hook))
6680 (pos (point)))
6682 (cond
6684 ((equal arg '(16))
6685 (setq last-command 'dummy)
6686 (org-set-startup-visibility)
6687 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6689 ((equal arg '(64))
6690 (outline-show-all)
6691 (org-unlogged-message "Entire buffer visible, including drawers"))
6693 ((equal arg '(4)) (org-cycle-internal-global))
6695 ;; Try hiding block at point.
6696 ((org-hide-block-toggle-maybe))
6698 ;; Try cdlatex TAB completion
6699 ((org-try-cdlatex-tab))
6701 ;; Table: enter it or move to the next field.
6702 ((org-at-table-p 'any)
6703 (if (org-at-table.el-p)
6704 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6705 Use `\\[org-edit-special]' to edit table.el tables"))
6706 (if arg (org-table-edit-field t)
6707 (org-table-justify-field-maybe)
6708 (call-interactively 'org-table-next-field))))
6710 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6712 ;; Global cycling: delegate to `org-cycle-internal-global'.
6713 (bob-special (org-cycle-internal-global))
6715 ;; Drawers: delegate to `org-flag-drawer'.
6716 ((save-excursion
6717 (beginning-of-line 1)
6718 (looking-at org-drawer-regexp))
6719 (org-flag-drawer ; toggle block visibility
6720 (not (get-char-property (match-end 0) 'invisible))))
6722 ;; Show-subtree, ARG levels up from here.
6723 ((integerp arg)
6724 (save-excursion
6725 (org-back-to-heading)
6726 (outline-up-heading (if (< arg 0) (- arg)
6727 (- (funcall outline-level) arg)))
6728 (org-show-subtree)))
6730 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6731 ((and (featurep 'org-inlinetask)
6732 (org-inlinetask-at-task-p)
6733 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6734 (org-inlinetask-toggle-visibility))
6736 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6737 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6738 (save-excursion (move-beginning-of-line 1)
6739 (looking-at org-outline-regexp)))
6740 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6741 (org-cycle-internal-local))
6743 ;; From there: TAB emulation and template completion.
6744 (buffer-read-only (org-back-to-heading))
6746 ((run-hook-with-args-until-success
6747 'org-tab-after-check-for-cycling-hook))
6749 ((run-hook-with-args-until-success
6750 'org-tab-before-tab-emulation-hook))
6752 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6753 (or (not (bolp))
6754 (not (looking-at org-outline-regexp))))
6755 (call-interactively (global-key-binding "\t")))
6757 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6758 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6759 (or (and (eq org-cycle-emulate-tab 'white)
6760 (= (match-end 0) (point-at-eol)))
6761 (and (eq org-cycle-emulate-tab 'whitestart)
6762 (>= (match-end 0) pos))))
6764 (eq org-cycle-emulate-tab t))
6765 (call-interactively (global-key-binding "\t")))
6767 (t (save-excursion
6768 (org-back-to-heading)
6769 (org-cycle)))))))
6771 (defun org-cycle-internal-global ()
6772 "Do the global cycling action."
6773 ;; Hack to avoid display of messages for .org attachments in Gnus
6774 (let ((ga (string-match "\\*fontification" (buffer-name))))
6775 (cond
6776 ((and (eq last-command this-command)
6777 (eq org-cycle-global-status 'overview))
6778 ;; We just created the overview - now do table of contents
6779 ;; This can be slow in very large buffers, so indicate action
6780 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6781 (unless ga (org-unlogged-message "CONTENTS..."))
6782 (org-content)
6783 (unless ga (org-unlogged-message "CONTENTS...done"))
6784 (setq org-cycle-global-status 'contents)
6785 (run-hook-with-args 'org-cycle-hook 'contents))
6787 ((and (eq last-command this-command)
6788 (eq org-cycle-global-status 'contents))
6789 ;; We just showed the table of contents - now show everything
6790 (run-hook-with-args 'org-pre-cycle-hook 'all)
6791 (outline-show-all)
6792 (unless ga (org-unlogged-message "SHOW ALL"))
6793 (setq org-cycle-global-status 'all)
6794 (run-hook-with-args 'org-cycle-hook 'all))
6797 ;; Default action: go to overview
6798 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6799 (org-overview)
6800 (unless ga (org-unlogged-message "OVERVIEW"))
6801 (setq org-cycle-global-status 'overview)
6802 (run-hook-with-args 'org-cycle-hook 'overview)))))
6804 (defvar org-called-with-limited-levels nil
6805 "Non-nil when `org-with-limited-levels' is currently active.")
6807 (defun org-cycle-internal-local ()
6808 "Do the local cycling action."
6809 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6810 ;; First, determine end of headline (EOH), end of subtree or item
6811 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6812 (save-excursion
6813 (if (org-at-item-p)
6814 (progn
6815 (beginning-of-line)
6816 (setq struct (org-list-struct))
6817 (setq eoh (point-at-eol))
6818 (setq eos (org-list-get-item-end-before-blank (point) struct))
6819 (setq has-children (org-list-has-child-p (point) struct)))
6820 (org-back-to-heading)
6821 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6822 (setq eos (save-excursion (org-end-of-subtree t t)
6823 (when (bolp) (backward-char)) (point)))
6824 (setq has-children
6825 (or (save-excursion
6826 (let ((level (funcall outline-level)))
6827 (outline-next-heading)
6828 (and (org-at-heading-p t)
6829 (> (funcall outline-level) level))))
6830 (save-excursion
6831 (org-list-search-forward (org-item-beginning-re) eos t)))))
6832 ;; Determine end invisible part of buffer (EOL)
6833 (beginning-of-line 2)
6834 (while (and (not (eobp)) ;This is like `next-line'.
6835 (get-char-property (1- (point)) 'invisible))
6836 (goto-char (next-single-char-property-change (point) 'invisible))
6837 (and (eolp) (beginning-of-line 2)))
6838 (setq eol (point)))
6839 ;; Find out what to do next and set `this-command'
6840 (cond
6841 ((= eos eoh)
6842 ;; Nothing is hidden behind this heading
6843 (unless (org-before-first-heading-p)
6844 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6845 (org-unlogged-message "EMPTY ENTRY")
6846 (setq org-cycle-subtree-status nil)
6847 (save-excursion
6848 (goto-char eos)
6849 (outline-next-heading)
6850 (when (org-invisible-p) (org-flag-heading nil))))
6851 ((and (or (>= eol eos)
6852 (not (string-match "\\S-" (buffer-substring eol eos))))
6853 (or has-children
6854 (not (setq children-skipped
6855 org-cycle-skip-children-state-if-no-children))))
6856 ;; Entire subtree is hidden in one line: children view
6857 (unless (org-before-first-heading-p)
6858 (run-hook-with-args 'org-pre-cycle-hook 'children))
6859 (if (org-at-item-p)
6860 (org-list-set-item-visibility (point-at-bol) struct 'children)
6861 (org-show-entry)
6862 (org-with-limited-levels (org-show-children))
6863 ;; FIXME: This slows down the func way too much.
6864 ;; How keep drawers hidden in subtree anyway?
6865 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6866 ;; (org-cycle-hide-drawers 'subtree))
6868 ;; Fold every list in subtree to top-level items.
6869 (when (eq org-cycle-include-plain-lists 'integrate)
6870 (save-excursion
6871 (org-back-to-heading)
6872 (while (org-list-search-forward (org-item-beginning-re) eos t)
6873 (beginning-of-line 1)
6874 (let* ((struct (org-list-struct))
6875 (prevs (org-list-prevs-alist struct))
6876 (end (org-list-get-bottom-point struct)))
6877 (dolist (e (org-list-get-all-items (point) struct prevs))
6878 (org-list-set-item-visibility e struct 'folded))
6879 (goto-char (if (< end eos) end eos)))))))
6880 (org-unlogged-message "CHILDREN")
6881 (save-excursion
6882 (goto-char eos)
6883 (outline-next-heading)
6884 (when (org-invisible-p) (org-flag-heading nil)))
6885 (setq org-cycle-subtree-status 'children)
6886 (unless (org-before-first-heading-p)
6887 (run-hook-with-args 'org-cycle-hook 'children)))
6888 ((or children-skipped
6889 (and (eq last-command this-command)
6890 (eq org-cycle-subtree-status 'children)))
6891 ;; We just showed the children, or no children are there,
6892 ;; now show everything.
6893 (unless (org-before-first-heading-p)
6894 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6895 (outline-flag-region eoh eos nil)
6896 (org-unlogged-message
6897 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6898 (setq org-cycle-subtree-status 'subtree)
6899 (unless (org-before-first-heading-p)
6900 (run-hook-with-args 'org-cycle-hook 'subtree)))
6902 ;; Default action: hide the subtree.
6903 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6904 (outline-flag-region eoh eos t)
6905 (org-unlogged-message "FOLDED")
6906 (setq org-cycle-subtree-status 'folded)
6907 (unless (org-before-first-heading-p)
6908 (run-hook-with-args 'org-cycle-hook 'folded))))))
6910 ;;;###autoload
6911 (defun org-global-cycle (&optional arg)
6912 "Cycle the global visibility. For details see `org-cycle'.
6913 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6914 With a numeric prefix, show all headlines up to that level."
6915 (interactive "P")
6916 (let ((org-cycle-include-plain-lists
6917 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6918 (cond
6919 ((integerp arg)
6920 (outline-show-all)
6921 (outline-hide-sublevels arg)
6922 (setq org-cycle-global-status 'contents))
6923 ((equal arg '(4))
6924 (org-set-startup-visibility)
6925 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6927 (org-cycle '(4))))))
6929 (defun org-set-startup-visibility ()
6930 "Set the visibility required by startup options and properties."
6931 (cond
6932 ((eq org-startup-folded t)
6933 (org-overview))
6934 ((eq org-startup-folded 'content)
6935 (org-content))
6936 ((or (eq org-startup-folded 'showeverything)
6937 (eq org-startup-folded nil))
6938 (outline-show-all)))
6939 (unless (eq org-startup-folded 'showeverything)
6940 (when org-hide-block-startup (org-hide-block-all))
6941 (org-set-visibility-according-to-property 'no-cleanup)
6942 (org-cycle-hide-archived-subtrees 'all)
6943 (org-cycle-hide-drawers 'all)
6944 (org-cycle-show-empty-lines t)))
6946 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6947 "Switch subtree visibilities according to :VISIBILITY: property."
6948 (interactive)
6949 (org-with-wide-buffer
6950 (goto-char (point-min))
6951 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6952 (if (not (org-at-property-p)) (outline-next-heading)
6953 (let ((state (match-string 3)))
6954 (save-excursion
6955 (org-back-to-heading t)
6956 (outline-hide-subtree)
6957 (org-reveal)
6958 (cond
6959 ((equal state "folded")
6960 (outline-hide-subtree))
6961 ((equal state "children")
6962 (org-show-hidden-entry)
6963 (org-show-children))
6964 ((equal state "content")
6965 (save-excursion
6966 (save-restriction
6967 (org-narrow-to-subtree)
6968 (org-content))))
6969 ((member state '("all" "showall"))
6970 (outline-show-subtree)))))))
6971 (unless no-cleanup
6972 (org-cycle-hide-archived-subtrees 'all)
6973 (org-cycle-hide-drawers 'all)
6974 (org-cycle-show-empty-lines 'all))))
6976 ;; This function uses outline-regexp instead of the more fundamental
6977 ;; org-outline-regexp so that org-cycle-global works outside of Org
6978 ;; buffers, where outline-regexp is needed.
6979 (defun org-overview ()
6980 "Switch to overview mode, showing only top-level headlines.
6981 This shows all headlines with a level equal or greater than the level
6982 of the first headline in the buffer. This is important, because if the
6983 first headline is not level one, then (hide-sublevels 1) gives confusing
6984 results."
6985 (interactive)
6986 (save-excursion
6987 (let ((level
6988 (save-excursion
6989 (goto-char (point-min))
6990 (when (re-search-forward (concat "^" outline-regexp) nil t)
6991 (goto-char (match-beginning 0))
6992 (funcall outline-level)))))
6993 (and level (outline-hide-sublevels level)))))
6995 (defun org-content (&optional arg)
6996 "Show all headlines in the buffer, like a table of contents.
6997 With numerical argument N, show content up to level N."
6998 (interactive "P")
6999 (org-overview)
7000 (save-excursion
7001 ;; Visit all headings and show their offspring
7002 (and (integerp arg) (org-overview))
7003 (goto-char (point-max))
7004 (catch 'exit
7005 (while (and (progn (condition-case nil
7006 (outline-previous-visible-heading 1)
7007 (error (goto-char (point-min))))
7009 (looking-at org-outline-regexp))
7010 (if (integerp arg)
7011 (org-show-children (1- arg))
7012 (outline-show-branches))
7013 (when (bobp) (throw 'exit nil))))))
7015 (defun org-optimize-window-after-visibility-change (state)
7016 "Adjust the window after a change in outline visibility.
7017 This function is the default value of the hook `org-cycle-hook'."
7018 (when (get-buffer-window (current-buffer))
7019 (cond
7020 ((eq state 'content) nil)
7021 ((eq state 'all) nil)
7022 ((eq state 'folded) nil)
7023 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7024 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7026 (defun org-remove-empty-overlays-at (pos)
7027 "Remove outline overlays that do not contain non-white stuff."
7028 (dolist (o (overlays-at pos))
7029 (and (eq 'outline (overlay-get o 'invisible))
7030 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7031 (overlay-end o))))
7032 (delete-overlay o))))
7034 (defun org-clean-visibility-after-subtree-move ()
7035 "Fix visibility issues after moving a subtree."
7036 ;; First, find a reasonable region to look at:
7037 ;; Start two siblings above, end three below
7038 (let* ((beg (save-excursion
7039 (and (org-get-last-sibling)
7040 (org-get-last-sibling))
7041 (point)))
7042 (end (save-excursion
7043 (and (org-get-next-sibling)
7044 (org-get-next-sibling)
7045 (org-get-next-sibling))
7046 (if (org-at-heading-p)
7047 (point-at-eol)
7048 (point))))
7049 (level (looking-at "\\*+"))
7050 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7051 (save-excursion
7052 (save-restriction
7053 (narrow-to-region beg end)
7054 (when re
7055 ;; Properly fold already folded siblings
7056 (goto-char (point-min))
7057 (while (re-search-forward re nil t)
7058 (when (and (not (org-invisible-p))
7059 (save-excursion
7060 (goto-char (point-at-eol)) (org-invisible-p)))
7061 (outline-hide-entry))))
7062 (org-cycle-show-empty-lines 'overview)
7063 (org-cycle-hide-drawers 'overview)))))
7065 (defun org-cycle-show-empty-lines (state)
7066 "Show empty lines above all visible headlines.
7067 The region to be covered depends on STATE when called through
7068 `org-cycle-hook'. Lisp program can use t for STATE to get the
7069 entire buffer covered. Note that an empty line is only shown if there
7070 are at least `org-cycle-separator-lines' empty lines before the headline."
7071 (when (/= org-cycle-separator-lines 0)
7072 (save-excursion
7073 (let* ((n (abs org-cycle-separator-lines))
7074 (re (cond
7075 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7076 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7077 (t (let ((ns (number-to-string (- n 2))))
7078 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7079 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7080 beg end)
7081 (cond
7082 ((memq state '(overview contents t))
7083 (setq beg (point-min) end (point-max)))
7084 ((memq state '(children folded))
7085 (setq beg (point)
7086 end (progn (org-end-of-subtree t t)
7087 (line-beginning-position 2)))))
7088 (when beg
7089 (goto-char beg)
7090 (while (re-search-forward re end t)
7091 (unless (get-char-property (match-end 1) 'invisible)
7092 (let ((e (match-end 1))
7093 (b (if (>= org-cycle-separator-lines 0)
7094 (match-beginning 1)
7095 (save-excursion
7096 (goto-char (match-beginning 0))
7097 (skip-chars-backward " \t\n")
7098 (line-end-position)))))
7099 (outline-flag-region b e nil))))))))
7100 ;; Never hide empty lines at the end of the file.
7101 (save-excursion
7102 (goto-char (point-max))
7103 (outline-previous-heading)
7104 (outline-end-of-heading)
7105 (when (and (looking-at "[ \t\n]+")
7106 (= (match-end 0) (point-max)))
7107 (outline-flag-region (point) (match-end 0) nil))))
7109 (defun org-show-empty-lines-in-parent ()
7110 "Move to the parent and re-show empty lines before visible headlines."
7111 (save-excursion
7112 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7113 (org-cycle-show-empty-lines context))))
7115 (defun org-files-list ()
7116 "Return `org-agenda-files' list, plus all open Org files.
7117 This is useful for operations that need to scan all of a user's
7118 open and agenda-wise Org files."
7119 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7120 (dolist (buf (buffer-list))
7121 (with-current-buffer buf
7122 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7123 (cl-pushnew (expand-file-name (buffer-file-name)) files
7124 :test #'equal))))
7125 files))
7127 (defsubst org-entry-beginning-position ()
7128 "Return the beginning position of the current entry."
7129 (save-excursion (org-back-to-heading t) (point)))
7131 (defsubst org-entry-end-position ()
7132 "Return the end position of the current entry."
7133 (save-excursion (outline-next-heading) (point)))
7135 (defun org-cycle-hide-drawers (state &optional exceptions)
7136 "Re-hide all drawers after a visibility state change.
7137 STATE should be one of the symbols listed in the docstring of
7138 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7139 a list of strings specifying which drawers should not be hidden."
7140 (when (and (derived-mode-p 'org-mode)
7141 (not (memq state '(overview folded contents))))
7142 (save-excursion
7143 (let* ((globalp (eq state 'all))
7144 (beg (if globalp (point-min) (point)))
7145 (end (if globalp (point-max)
7146 (if (eq state 'children)
7147 (save-excursion (outline-next-heading) (point))
7148 (org-end-of-subtree t)))))
7149 (goto-char beg)
7150 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7151 (unless (member-ignore-case (match-string 1) exceptions)
7152 (let ((drawer (org-element-at-point)))
7153 (when (memq (org-element-type drawer) '(drawer property-drawer))
7154 (org-flag-drawer t drawer)
7155 ;; Make sure to skip drawer entirely or we might flag
7156 ;; it another time when matching its ending line with
7157 ;; `org-drawer-regexp'.
7158 (goto-char (org-element-property :end drawer))))))))))
7160 (defun org-flag-drawer (flag &optional element)
7161 "When FLAG is non-nil, hide the drawer we are at.
7162 Otherwise make it visible. When optional argument ELEMENT is
7163 a parsed drawer, as returned by `org-element-at-point', hide or
7164 show that drawer instead."
7165 (let ((drawer (or element
7166 (and (save-excursion
7167 (beginning-of-line)
7168 (looking-at-p org-drawer-regexp))
7169 (org-element-at-point)))))
7170 (when (memq (org-element-type drawer) '(drawer property-drawer))
7171 (let ((post (org-element-property :post-affiliated drawer)))
7172 (save-excursion
7173 (outline-flag-region
7174 (progn (goto-char post) (line-end-position))
7175 (progn (goto-char (org-element-property :end drawer))
7176 (skip-chars-backward " \r\t\n")
7177 (line-end-position))
7178 flag))
7179 ;; When the drawer is hidden away, make sure point lies in
7180 ;; a visible part of the buffer.
7181 (when (and flag (> (line-beginning-position) post))
7182 (goto-char post))))))
7184 (defun org-subtree-end-visible-p ()
7185 "Is the end of the current subtree visible?"
7186 (pos-visible-in-window-p
7187 (save-excursion (org-end-of-subtree t) (point))))
7189 (defun org-first-headline-recenter ()
7190 "Move cursor to the first headline and recenter the headline."
7191 (let ((window (get-buffer-window)))
7192 (when window
7193 (goto-char (point-min))
7194 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7195 (set-window-start window (line-beginning-position))))))
7197 ;;; Saving and restoring visibility
7199 (defun org-outline-overlay-data (&optional use-markers)
7200 "Return a list of the locations of all outline overlays.
7201 These are overlays with the `invisible' property value `outline'.
7202 The return value is a list of cons cells, with start and stop
7203 positions for each overlay.
7204 If USE-MARKERS is set, return the positions as markers."
7205 (let (beg end)
7206 (org-with-wide-buffer
7207 (delq nil
7208 (mapcar (lambda (o)
7209 (when (eq (overlay-get o 'invisible) 'outline)
7210 (setq beg (overlay-start o)
7211 end (overlay-end o))
7212 (and beg end (> end beg)
7213 (if use-markers
7214 (cons (copy-marker beg)
7215 (copy-marker end t))
7216 (cons beg end)))))
7217 (overlays-in (point-min) (point-max)))))))
7219 (defun org-set-outline-overlay-data (data)
7220 "Create visibility overlays for all positions in DATA.
7221 DATA should have been made by `org-outline-overlay-data'."
7222 (org-with-wide-buffer
7223 (outline-show-all)
7224 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7226 ;;; Folding of blocks
7228 (defvar-local org-hide-block-overlays nil
7229 "Overlays hiding blocks.")
7231 (defun org-block-map (function &optional start end)
7232 "Call FUNCTION at the head of all source blocks in the current buffer.
7233 Optional arguments START and END can be used to limit the range."
7234 (let ((start (or start (point-min)))
7235 (end (or end (point-max))))
7236 (save-excursion
7237 (goto-char start)
7238 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7239 (save-excursion
7240 (save-match-data
7241 (goto-char (match-beginning 0))
7242 (funcall function)))))))
7244 (defun org-hide-block-toggle-all ()
7245 "Toggle the visibility of all blocks in the current buffer."
7246 (org-block-map 'org-hide-block-toggle))
7248 (defun org-hide-block-all ()
7249 "Fold all blocks in the current buffer."
7250 (interactive)
7251 (org-show-block-all)
7252 (org-block-map 'org-hide-block-toggle-maybe))
7254 (defun org-show-block-all ()
7255 "Unfold all blocks in the current buffer."
7256 (interactive)
7257 (mapc #'delete-overlay org-hide-block-overlays)
7258 (setq org-hide-block-overlays nil))
7260 (defun org-hide-block-toggle-maybe ()
7261 "Toggle visibility of block at point.
7262 Unlike to `org-hide-block-toggle', this function does not throw
7263 an error. Return a non-nil value when toggling is successful."
7264 (interactive)
7265 (ignore-errors (org-hide-block-toggle)))
7267 (defun org-hide-block-toggle (&optional force)
7268 "Toggle the visibility of the current block.
7269 When optional argument FORCE is `off', make block visible. If it
7270 is non-nil, hide it unconditionally. Throw an error when not at
7271 a block. Return a non-nil value when toggling is successful."
7272 (interactive)
7273 (let ((element (org-element-at-point)))
7274 (unless (memq (org-element-type element)
7275 '(center-block comment-block dynamic-block example-block
7276 export-block quote-block special-block
7277 src-block verse-block))
7278 (user-error "Not at a block"))
7279 (let* ((start (save-excursion
7280 (goto-char (org-element-property :post-affiliated element))
7281 (line-end-position)))
7282 (end (save-excursion
7283 (goto-char (org-element-property :end element))
7284 (skip-chars-backward " \r\t\n")
7285 (line-end-position)))
7286 (overlays (overlays-at start)))
7287 (cond
7288 ;; Do nothing when not before or at the block opening line or
7289 ;; at the block closing line.
7290 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7291 ((and (not (eq force 'off))
7292 (not (memq t (mapcar
7293 (lambda (o)
7294 (eq (overlay-get o 'invisible) 'org-hide-block))
7295 overlays))))
7296 (let ((ov (make-overlay start end)))
7297 (overlay-put ov 'invisible 'org-hide-block)
7298 ;; Make the block accessible to `isearch'.
7299 (overlay-put
7300 ov 'isearch-open-invisible
7301 (lambda (ov)
7302 (when (memq ov org-hide-block-overlays)
7303 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7304 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7305 (delete-overlay ov))))
7306 (push ov org-hide-block-overlays)
7307 ;; When the block is hidden away, make sure point is left in
7308 ;; a visible part of the buffer.
7309 (when (> (line-beginning-position) start)
7310 (goto-char start)
7311 (beginning-of-line))
7312 ;; Signal successful toggling.
7314 ((or (not force) (eq force 'off))
7315 (dolist (ov overlays t)
7316 (when (memq ov org-hide-block-overlays)
7317 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7318 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7319 (delete-overlay ov))))))))
7321 ;; Remove overlays when changing major mode
7322 (add-hook 'org-mode-hook
7323 (lambda () (add-hook 'change-major-mode-hook
7324 'org-show-block-all 'append 'local)))
7326 ;;; Indirect buffer display of subtrees
7328 (defvar org-indirect-dedicated-frame nil
7329 "This is the frame being used for indirect tree display.")
7330 (defvar org-last-indirect-buffer nil)
7332 (defun org-tree-to-indirect-buffer (&optional arg)
7333 "Create indirect buffer and narrow it to current subtree.
7335 With a numerical prefix ARG, go up to this level and then take that tree.
7336 If ARG is negative, go up that many levels.
7338 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7339 indirect buffer previously made with this command, to avoid proliferation of
7340 indirect buffers. However, when you call the command with a \
7341 `\\[universal-argument]' prefix, or
7342 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7343 so that you can work with several indirect buffers at the same time. If
7344 `org-indirect-buffer-display' is `dedicated-frame', the \
7345 `\\[universal-argument]' prefix also
7346 requests that a new frame be made for the new buffer, so that the dedicated
7347 frame is not changed."
7348 (interactive "P")
7349 (let ((cbuf (current-buffer))
7350 (cwin (selected-window))
7351 (pos (point))
7352 beg end level heading ibuf)
7353 (save-excursion
7354 (org-back-to-heading t)
7355 (when (numberp arg)
7356 (setq level (org-outline-level))
7357 (when (< arg 0) (setq arg (+ level arg)))
7358 (while (> (setq level (org-outline-level)) arg)
7359 (org-up-heading-safe)))
7360 (setq beg (point)
7361 heading (org-get-heading 'no-tags))
7362 (org-end-of-subtree t t)
7363 (when (org-at-heading-p) (backward-char 1))
7364 (setq end (point)))
7365 (when (and (buffer-live-p org-last-indirect-buffer)
7366 (not (eq org-indirect-buffer-display 'new-frame))
7367 (not arg))
7368 (kill-buffer org-last-indirect-buffer))
7369 (setq ibuf (org-get-indirect-buffer cbuf heading)
7370 org-last-indirect-buffer ibuf)
7371 (cond
7372 ((or (eq org-indirect-buffer-display 'new-frame)
7373 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7374 (select-frame (make-frame))
7375 (delete-other-windows)
7376 (pop-to-buffer-same-window ibuf)
7377 (org-set-frame-title heading))
7378 ((eq org-indirect-buffer-display 'dedicated-frame)
7379 (raise-frame
7380 (select-frame (or (and org-indirect-dedicated-frame
7381 (frame-live-p org-indirect-dedicated-frame)
7382 org-indirect-dedicated-frame)
7383 (setq org-indirect-dedicated-frame (make-frame)))))
7384 (delete-other-windows)
7385 (pop-to-buffer-same-window ibuf)
7386 (org-set-frame-title (concat "Indirect: " heading)))
7387 ((eq org-indirect-buffer-display 'current-window)
7388 (pop-to-buffer-same-window ibuf))
7389 ((eq org-indirect-buffer-display 'other-window)
7390 (pop-to-buffer ibuf))
7391 (t (error "Invalid value")))
7392 (narrow-to-region beg end)
7393 (outline-show-all)
7394 (goto-char pos)
7395 (run-hook-with-args 'org-cycle-hook 'all)
7396 (and (window-live-p cwin) (select-window cwin))))
7398 (defun org-get-indirect-buffer (&optional buffer heading)
7399 (setq buffer (or buffer (current-buffer)))
7400 (let ((n 1) (base (buffer-name buffer)) bname)
7401 (while (buffer-live-p
7402 (get-buffer
7403 (setq bname
7404 (concat base "-"
7405 (if heading (concat heading "-" (number-to-string n))
7406 (number-to-string n))))))
7407 (setq n (1+ n)))
7408 (condition-case nil
7409 (make-indirect-buffer buffer bname 'clone)
7410 (error (make-indirect-buffer buffer bname)))))
7412 (defun org-set-frame-title (title)
7413 "Set the title of the current frame to the string TITLE."
7414 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7416 ;;;; Structure editing
7418 ;;; Inserting headlines
7420 (defun org--line-empty-p (n)
7421 "Is the Nth next line empty?
7423 Counts the current line as N = 1 and the previous line as N = 0;
7424 see `beginning-of-line'."
7425 (save-excursion
7426 (and (not (bobp))
7427 (or (beginning-of-line n) t)
7428 (save-match-data
7429 (looking-at "[ \t]*$")))))
7431 (defun org-previous-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 0))
7436 (defun org-next-line-empty-p ()
7437 "Is the previous line a blank line?
7438 When NEXT is non-nil, check the next line instead."
7439 (org--line-empty-p 2))
7441 (defun org--blank-before-heading-p (&optional parent)
7442 "Non-nil when an empty line should precede a new heading here.
7443 When optional argument PARENT is non-nil, consider parent
7444 headline instead of current one."
7445 (pcase (assq 'heading org-blank-before-new-entry)
7446 (`(heading . auto)
7447 (save-excursion
7448 (org-with-limited-levels
7449 (unless (and (org-before-first-heading-p)
7450 (not (outline-next-heading)))
7451 (org-back-to-heading t)
7452 (when parent (org-up-heading-safe))
7453 (cond ((not (bobp))
7454 (org-previous-line-empty-p))
7455 ((outline-next-heading)
7456 (org-previous-line-empty-p))
7457 ;; Ignore trailing spaces on last buffer line.
7458 ((progn (skip-chars-backward " \t") (bolp))
7459 (org-previous-line-empty-p))
7460 (t nil))))))
7461 (`(heading . ,value) value)
7462 (_ nil)))
7464 (defun org-insert-heading (&optional arg invisible-ok top)
7465 "Insert a new heading or an item with the same depth at point.
7467 If point is at the beginning of a heading, insert a new heading
7468 or a new headline above the current one. When at the beginning
7469 of a regular line of text, turn it into a heading.
7471 If point is in the middle of a line, split it and create a new
7472 headline with the text in the current line after point (see
7473 `org-M-RET-may-split-line' on how to modify this behavior). As
7474 a special case, on a headline, splitting can only happen on the
7475 title itself. E.g., this excludes breaking stars or tags.
7477 With a `\\[universal-argument]' prefix, set \
7478 `org-insert-heading-respect-content' to
7479 a non-nil value for the duration of the command. This forces the
7480 insertion of a heading after the current subtree, independently
7481 on the location of point.
7483 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7484 insert the heading at the end of the tree
7485 above the current heading. For example, if point is within a
7486 2nd-level heading, then it will insert a 2nd-level heading at
7487 the end of the 1st-level parent subtree.
7489 When INVISIBLE-OK is set, stop at invisible headlines when going
7490 back. This is important for non-interactive uses of the
7491 command.
7493 When optional argument TOP is non-nil, insert a level 1 heading,
7494 unconditionally."
7495 (interactive "P")
7496 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7497 (level (org-current-level))
7498 (stars (make-string (if (and level (not top)) level 1) ?*)))
7499 (cond
7500 ((or org-insert-heading-respect-content
7501 (member arg '((4) (16)))
7502 (and (not invisible-ok)
7503 (invisible-p (max (1- (point)) (point-min)))))
7504 ;; Position point at the location of insertion.
7505 (if (not level) ;before first headline
7506 (org-with-limited-levels (outline-next-heading))
7507 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7508 ;; is nil.
7509 (org-with-limited-levels (org-back-to-heading invisible-ok))
7510 (cond ((equal arg '(16))
7511 (org-up-heading-safe)
7512 (org-end-of-subtree t t))
7514 (org-end-of-subtree t t))))
7515 (unless (bolp) (insert "\n")) ;ensure final newline
7516 (unless (and blank? (org-previous-line-empty-p))
7517 (org-N-empty-lines-before-current (if blank? 1 0)))
7518 (insert stars " \n")
7519 (forward-char -1))
7520 ;; At a headline...
7521 ((org-at-heading-p)
7522 (cond ((bolp)
7523 (when blank? (save-excursion (insert "\n")))
7524 (save-excursion (insert stars " \n"))
7525 (unless (and blank? (org-previous-line-empty-p))
7526 (org-N-empty-lines-before-current (if blank? 1 0)))
7527 (end-of-line))
7528 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7529 (org-match-line org-complex-heading-regexp)
7530 (org-pos-in-match-range (point) 4))
7531 ;; Grab the text that should moved to the new headline.
7532 ;; Preserve tags.
7533 (let ((split (delete-and-extract-region (point) (match-end 4))))
7534 (if (looking-at "[ \t]*$") (replace-match "")
7535 (org-set-tags nil t))
7536 (end-of-line)
7537 (when blank? (insert "\n"))
7538 (insert "\n" stars " ")
7539 (when (org-string-nw-p split) (insert split))
7540 (when (eobp) (save-excursion (insert "\n")))))
7542 (end-of-line)
7543 (when blank? (insert "\n"))
7544 (insert "\n" stars " ")
7545 (when (eobp) (save-excursion (insert "\n"))))))
7546 ;; On regular text, turn line into a headline or split, if
7547 ;; appropriate.
7548 ((bolp)
7549 (insert stars " ")
7550 (unless (and blank? (org-previous-line-empty-p))
7551 (org-N-empty-lines-before-current (if blank? 1 0))))
7553 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7554 (end-of-line))
7555 (insert "\n" stars " ")
7556 (unless (and blank? (org-previous-line-empty-p))
7557 (org-N-empty-lines-before-current (if blank? 1 0))))))
7558 (run-hooks 'org-insert-heading-hook))
7560 (defun org-N-empty-lines-before-current (n)
7561 "Make the number of empty lines before current exactly N.
7562 So this will delete or add empty lines."
7563 (let ((column (current-column)))
7564 (beginning-of-line)
7565 (unless (bobp)
7566 (let ((start (save-excursion
7567 (skip-chars-backward " \r\t\n")
7568 (line-end-position))))
7569 (delete-region start (line-end-position 0))))
7570 (insert (make-string n ?\n))
7571 (move-to-column column)))
7573 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7574 "Return the heading of the current entry, without the stars.
7575 When NO-TAGS is non-nil, don't include tags.
7576 When NO-TODO is non-nil, don't include TODO keywords.
7577 When NO-PRIORITY is non-nil, don't include priority cookie.
7578 When NO-COMMENT is non-nil, don't include COMMENT string."
7579 (save-excursion
7580 (org-back-to-heading t)
7581 (let ((case-fold-search nil))
7582 (looking-at org-complex-heading-regexp)
7583 (let ((todo (and (not no-todo) (match-string 2)))
7584 (priority (and (not no-priority) (match-string 3)))
7585 (headline (pcase (match-string 4)
7586 (`nil "")
7587 ((and (guard no-comment) h)
7588 (replace-regexp-in-string
7589 (eval-when-compile
7590 (format "\\`%s[ \t]+" org-comment-string))
7591 "" h))
7592 (h h)))
7593 (tags (and (not no-tags) (match-string 5))))
7594 (mapconcat #'identity
7595 (delq nil (list todo priority headline tags))
7596 " ")))))
7598 (defvar orgstruct-mode) ; defined below
7600 (defun org-heading-components ()
7601 "Return the components of the current heading.
7602 This is a list with the following elements:
7603 - the level as an integer
7604 - the reduced level, different if `org-odd-levels-only' is set.
7605 - the TODO keyword, or nil
7606 - the priority character, like ?A, or nil if no priority is given
7607 - the headline text itself, or the tags string if no headline text
7608 - the tags string, or nil."
7609 (save-excursion
7610 (org-back-to-heading t)
7611 (when (let (case-fold-search)
7612 (looking-at
7613 (if orgstruct-mode
7614 org-heading-regexp
7615 org-complex-heading-regexp)))
7616 (if orgstruct-mode
7617 (list (length (match-string 1))
7618 (org-reduced-level (length (match-string 1)))
7621 (match-string 2)
7622 nil)
7623 (list (length (match-string 1))
7624 (org-reduced-level (length (match-string 1)))
7625 (match-string-no-properties 2)
7626 (and (match-end 3) (aref (match-string 3) 2))
7627 (match-string-no-properties 4)
7628 (match-string-no-properties 5))))))
7630 (defun org-get-entry ()
7631 "Get the entry text, after heading, entire subtree."
7632 (save-excursion
7633 (org-back-to-heading t)
7634 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7636 (defun org-edit-headline (&optional heading)
7637 "Edit the current headline.
7638 Set it to HEADING when provided."
7639 (interactive)
7640 (org-with-wide-buffer
7641 (org-back-to-heading t)
7642 (let ((case-fold-search nil))
7643 (when (looking-at org-complex-heading-regexp)
7644 (let* ((old (match-string-no-properties 4))
7645 (new (save-match-data
7646 (org-trim (or heading (read-string "Edit: " old))))))
7647 (unless (equal old new)
7648 (if old (replace-match new t t nil 4)
7649 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7650 (insert " " new))
7651 (org-set-tags nil t)
7652 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7654 (defun org-insert-heading-after-current ()
7655 "Insert a new heading with same level as current, after current subtree."
7656 (interactive)
7657 (org-back-to-heading)
7658 (org-insert-heading)
7659 (org-move-subtree-down)
7660 (end-of-line 1))
7662 (defun org-insert-heading-respect-content (&optional invisible-ok)
7663 "Insert heading with `org-insert-heading-respect-content' set to t."
7664 (interactive)
7665 (org-insert-heading '(4) invisible-ok))
7667 (defun org-insert-todo-heading-respect-content (&optional force-state)
7668 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7669 (interactive)
7670 (org-insert-todo-heading force-state '(4)))
7672 (defun org-insert-todo-heading (arg &optional force-heading)
7673 "Insert a new heading with the same level and TODO state as current heading.
7675 If the heading has no TODO state, or if the state is DONE, use
7676 the first state (TODO by default). Also with one prefix arg,
7677 force first state. With two prefix args, force inserting at the
7678 end of the parent subtree.
7680 When called at a plain list item, insert a new item with an
7681 unchecked check box."
7682 (interactive "P")
7683 (when (or force-heading (not (org-insert-item 'checkbox)))
7684 (org-insert-heading (or (and (equal arg '(16)) '(16))
7685 force-heading))
7686 (save-excursion
7687 (org-forward-heading-same-level -1)
7688 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7689 (let* ((new-mark-x
7690 (if (or (equal arg '(4))
7691 (not (match-beginning 2))
7692 (member (match-string 2) org-done-keywords))
7693 (car org-todo-keywords-1)
7694 (match-string 2)))
7695 (new-mark
7697 (run-hook-with-args-until-success
7698 'org-todo-get-default-hook new-mark-x nil)
7699 new-mark-x)))
7700 (beginning-of-line 1)
7701 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7702 (if org-treat-insert-todo-heading-as-state-change
7703 (org-todo new-mark)
7704 (insert new-mark " "))))
7705 (when org-provide-todo-statistics
7706 (org-update-parent-todo-statistics))))
7708 (defun org-insert-subheading (arg)
7709 "Insert a new subheading and demote it.
7710 Works for outline headings and for plain lists alike."
7711 (interactive "P")
7712 (org-insert-heading arg)
7713 (cond
7714 ((org-at-heading-p) (org-do-demote))
7715 ((org-at-item-p) (org-indent-item))))
7717 (defun org-insert-todo-subheading (arg)
7718 "Insert a new subheading with TODO keyword or checkbox and demote it.
7719 Works for outline headings and for plain lists alike."
7720 (interactive "P")
7721 (org-insert-todo-heading arg)
7722 (cond
7723 ((org-at-heading-p) (org-do-demote))
7724 ((org-at-item-p) (org-indent-item))))
7726 ;;; Promotion and Demotion
7728 (defvar org-after-demote-entry-hook nil
7729 "Hook run after an entry has been demoted.
7730 The cursor will be at the beginning of the entry.
7731 When a subtree is being demoted, the hook will be called for each node.")
7733 (defvar org-after-promote-entry-hook nil
7734 "Hook run after an entry has been promoted.
7735 The cursor will be at the beginning of the entry.
7736 When a subtree is being promoted, the hook will be called for each node.")
7738 (defun org-promote-subtree ()
7739 "Promote the entire subtree.
7740 See also `org-promote'."
7741 (interactive)
7742 (save-excursion
7743 (org-with-limited-levels (org-map-tree 'org-promote)))
7744 (org-fix-position-after-promote))
7746 (defun org-demote-subtree ()
7747 "Demote the entire subtree.
7748 See `org-demote' and `org-promote'."
7749 (interactive)
7750 (save-excursion
7751 (org-with-limited-levels (org-map-tree 'org-demote)))
7752 (org-fix-position-after-promote))
7754 (defun org-do-promote ()
7755 "Promote the current heading higher up the tree.
7756 If the region is active in `transient-mark-mode', promote all
7757 headings in the region."
7758 (interactive)
7759 (save-excursion
7760 (if (org-region-active-p)
7761 (org-map-region 'org-promote (region-beginning) (region-end))
7762 (org-promote)))
7763 (org-fix-position-after-promote))
7765 (defun org-do-demote ()
7766 "Demote the current heading lower down the tree.
7767 If the region is active in `transient-mark-mode', demote all
7768 headings in the region."
7769 (interactive)
7770 (save-excursion
7771 (if (org-region-active-p)
7772 (org-map-region 'org-demote (region-beginning) (region-end))
7773 (org-demote)))
7774 (org-fix-position-after-promote))
7776 (defun org-fix-position-after-promote ()
7777 "Fix cursor position and indentation after demoting/promoting."
7778 (let ((pos (point)))
7779 (when (save-excursion
7780 (beginning-of-line)
7781 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7782 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7783 (cond ((eobp) (insert " "))
7784 ((eolp) (insert " "))
7785 ((equal (char-after) ?\s) (forward-char 1))))))
7787 (defun org-current-level ()
7788 "Return the level of the current entry, or nil if before the first headline.
7789 The level is the number of stars at the beginning of the
7790 headline. Use `org-reduced-level' to remove the effect of
7791 `org-odd-levels'. Unlike to `org-outline-level', this function
7792 ignores inlinetasks."
7793 (let ((level (org-with-limited-levels (org-outline-level))))
7794 (and (> level 0) level)))
7796 (defun org-get-previous-line-level ()
7797 "Return the outline depth of the last headline before the current line.
7798 Returns 0 for the first headline in the buffer, and nil if before the
7799 first headline."
7800 (and (org-current-level)
7801 (or (and (/= (line-beginning-position) (point-min))
7802 (save-excursion (beginning-of-line 0) (org-current-level)))
7803 0)))
7805 (defun org-reduced-level (l)
7806 "Compute the effective level of a heading.
7807 This takes into account the setting of `org-odd-levels-only'."
7808 (cond
7809 ((zerop l) 0)
7810 (org-odd-levels-only (1+ (floor (/ l 2))))
7811 (t l)))
7813 (defun org-level-increment ()
7814 "Return the number of stars that will be added or removed at a
7815 time to headlines when structure editing, based on the value of
7816 `org-odd-levels-only'."
7817 (if org-odd-levels-only 2 1))
7819 (defun org-get-valid-level (level &optional change)
7820 "Rectify a level change under the influence of `org-odd-levels-only'.
7821 LEVEL is a current level, CHANGE is by how much the level should
7822 be modified. Even if CHANGE is nil, LEVEL may be returned
7823 modified because even level numbers will become the next higher
7824 odd number. Returns values greater than 0."
7825 (if org-odd-levels-only
7826 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7827 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7828 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7829 (max 1 (+ level (or change 0)))))
7831 (defun org-promote ()
7832 "Promote the current heading higher up the tree."
7833 (org-with-wide-buffer
7834 (org-back-to-heading t)
7835 (let* ((after-change-functions (remq 'flyspell-after-change-function
7836 after-change-functions))
7837 (level (save-match-data (funcall outline-level)))
7838 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7839 (diff (abs (- level (length up-head) -1))))
7840 (cond
7841 ((and (= level 1) org-allow-promoting-top-level-subtree)
7842 (replace-match "# " nil t))
7843 ((= level 1)
7844 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7845 (t (replace-match up-head nil t)))
7846 (unless (= level 1)
7847 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7848 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7849 (run-hooks 'org-after-promote-entry-hook))))
7851 (defun org-demote ()
7852 "Demote the current heading lower down the tree."
7853 (org-with-wide-buffer
7854 (org-back-to-heading t)
7855 (let* ((after-change-functions (remq 'flyspell-after-change-function
7856 after-change-functions))
7857 (level (save-match-data (funcall outline-level)))
7858 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7859 (diff (abs (- level (length down-head) -1))))
7860 (replace-match down-head nil t)
7861 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7862 (when org-adapt-indentation (org-fixup-indentation diff))
7863 (run-hooks 'org-after-demote-entry-hook))))
7865 (defun org-cycle-level ()
7866 "Cycle the level of an empty headline through possible states.
7867 This goes first to child, then to parent, level, then up the hierarchy.
7868 After top level, it switches back to sibling level."
7869 (interactive)
7870 (let ((org-adapt-indentation nil))
7871 (when (org-point-at-end-of-empty-headline)
7872 (setq this-command 'org-cycle-level) ; Only needed for caching
7873 (let ((cur-level (org-current-level))
7874 (prev-level (org-get-previous-line-level)))
7875 (cond
7876 ;; If first headline in file, promote to top-level.
7877 ((= prev-level 0)
7878 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7879 do (org-do-promote)))
7880 ;; If same level as prev, demote one.
7881 ((= prev-level cur-level)
7882 (org-do-demote))
7883 ;; If parent is top-level, promote to top level if not already.
7884 ((= prev-level 1)
7885 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7886 do (org-do-promote)))
7887 ;; If top-level, return to prev-level.
7888 ((= cur-level 1)
7889 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7890 do (org-do-demote)))
7891 ;; If less than prev-level, promote one.
7892 ((< cur-level prev-level)
7893 (org-do-promote))
7894 ;; If deeper than prev-level, promote until higher than
7895 ;; prev-level.
7896 ((> cur-level prev-level)
7897 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7898 do (org-do-promote))))
7899 t))))
7901 (defun org-map-tree (fun)
7902 "Call FUN for every heading underneath the current one."
7903 (org-back-to-heading t)
7904 (let ((level (funcall outline-level)))
7905 (save-excursion
7906 (funcall fun)
7907 (while (and (progn
7908 (outline-next-heading)
7909 (> (funcall outline-level) level))
7910 (not (eobp)))
7911 (funcall fun)))))
7913 (defun org-map-region (fun beg end)
7914 "Call FUN for every heading between BEG and END."
7915 (let ((org-ignore-region t))
7916 (save-excursion
7917 (setq end (copy-marker end))
7918 (goto-char beg)
7919 (when (and (re-search-forward org-outline-regexp-bol nil t)
7920 (< (point) end))
7921 (funcall fun))
7922 (while (and (progn
7923 (outline-next-heading)
7924 (< (point) end))
7925 (not (eobp)))
7926 (funcall fun)))))
7928 (defun org-fixup-indentation (diff)
7929 "Change the indentation in the current entry by DIFF.
7931 DIFF is an integer. Indentation is done according to the
7932 following rules:
7934 - Planning information and property drawers are always indented
7935 according to the new level of the headline;
7937 - Footnote definitions and their contents are ignored;
7939 - Inlinetasks' boundaries are not shifted;
7941 - Empty lines are ignored;
7943 - Other lines' indentation are shifted by DIFF columns, unless
7944 it would introduce a structural change in the document, in
7945 which case no shifting is done at all.
7947 Assume point is at a heading or an inlinetask beginning."
7948 (org-with-wide-buffer
7949 (narrow-to-region (line-beginning-position)
7950 (save-excursion
7951 (if (org-with-limited-levels (org-at-heading-p))
7952 (org-with-limited-levels (outline-next-heading))
7953 (org-inlinetask-goto-end))
7954 (point)))
7955 (forward-line)
7956 ;; Indent properly planning info and property drawer.
7957 (when (looking-at-p org-planning-line-re)
7958 (org-indent-line)
7959 (forward-line))
7960 (when (looking-at org-property-drawer-re)
7961 (goto-char (match-end 0))
7962 (forward-line)
7963 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7964 (catch 'no-shift
7965 (when (zerop diff) (throw 'no-shift nil))
7966 ;; If DIFF is negative, first check if a shift is possible at all
7967 ;; (e.g., it doesn't break structure). This can only happen if
7968 ;; some contents are not properly indented.
7969 (let ((case-fold-search t))
7970 (when (< diff 0)
7971 (let ((diff (- diff))
7972 (forbidden-re (concat org-outline-regexp
7973 "\\|"
7974 (substring org-footnote-definition-re 1))))
7975 (save-excursion
7976 (while (not (eobp))
7977 (cond
7978 ((looking-at-p "[ \t]*$") (forward-line))
7979 ((and (looking-at-p org-footnote-definition-re)
7980 (let ((e (org-element-at-point)))
7981 (and (eq (org-element-type e) 'footnote-definition)
7982 (goto-char (org-element-property :end e))))))
7983 ((looking-at-p org-outline-regexp) (forward-line))
7984 ;; Give up if shifting would move before column 0 or
7985 ;; if it would introduce a headline or a footnote
7986 ;; definition.
7988 (skip-chars-forward " \t")
7989 (let ((ind (current-column)))
7990 (when (or (< ind diff)
7991 (and (= ind diff) (looking-at-p forbidden-re)))
7992 (throw 'no-shift nil)))
7993 ;; Ignore contents of example blocks and source
7994 ;; blocks if their indentation is meant to be
7995 ;; preserved. Jump to block's closing line.
7996 (beginning-of-line)
7997 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7998 (let ((e (org-element-at-point)))
7999 (and (memq (org-element-type e)
8000 '(example-block src-block))
8001 (or org-src-preserve-indentation
8002 (org-element-property :preserve-indent e))
8003 (goto-char (org-element-property :end e))
8004 (progn (skip-chars-backward " \r\t\n")
8005 (beginning-of-line)
8006 t))))
8007 (forward-line))))))))
8008 ;; Shift lines but footnote definitions, inlinetasks boundaries
8009 ;; by DIFF. Also skip contents of source or example blocks
8010 ;; when indentation is meant to be preserved.
8011 (while (not (eobp))
8012 (cond
8013 ((and (looking-at-p org-footnote-definition-re)
8014 (let ((e (org-element-at-point)))
8015 (and (eq (org-element-type e) 'footnote-definition)
8016 (goto-char (org-element-property :end e))))))
8017 ((looking-at-p org-outline-regexp) (forward-line))
8018 ((looking-at-p "[ \t]*$") (forward-line))
8020 (indent-line-to (+ (org-get-indentation) diff))
8021 (beginning-of-line)
8022 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8023 (let ((e (org-element-at-point)))
8024 (and (memq (org-element-type e)
8025 '(example-block src-block))
8026 (or org-src-preserve-indentation
8027 (org-element-property :preserve-indent e))
8028 (goto-char (org-element-property :end e))
8029 (progn (skip-chars-backward " \r\t\n")
8030 (beginning-of-line)
8031 t))))
8032 (forward-line)))))))))
8034 (defun org-convert-to-odd-levels ()
8035 "Convert an Org file with all levels allowed to one with odd levels.
8036 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8037 level 5 etc."
8038 (interactive)
8039 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8040 (let ((outline-level 'org-outline-level)
8041 (org-odd-levels-only nil) n)
8042 (save-excursion
8043 (goto-char (point-min))
8044 (while (re-search-forward "^\\*\\*+ " nil t)
8045 (setq n (- (length (match-string 0)) 2))
8046 (while (>= (setq n (1- n)) 0)
8047 (org-demote))
8048 (end-of-line 1))))))
8050 (defun org-convert-to-oddeven-levels ()
8051 "Convert an Org file with only odd levels to one with odd/even levels.
8052 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8053 file contains a section with an even level, conversion would
8054 destroy the structure of the file. An error is signaled in this
8055 case."
8056 (interactive)
8057 (goto-char (point-min))
8058 ;; First check if there are no even levels
8059 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8060 (org-show-set-visibility 'canonical)
8061 (error "Not all levels are odd in this file. Conversion not possible"))
8062 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8063 (let ((outline-regexp org-outline-regexp)
8064 (outline-level 'org-outline-level)
8065 (org-odd-levels-only nil) n)
8066 (save-excursion
8067 (goto-char (point-min))
8068 (while (re-search-forward "^\\*\\*+ " nil t)
8069 (setq n (/ (1- (length (match-string 0))) 2))
8070 (while (>= (setq n (1- n)) 0)
8071 (org-promote))
8072 (end-of-line 1))))))
8074 (defun org-tr-level (n)
8075 "Make N odd if required."
8076 (if org-odd-levels-only (1+ (/ n 2)) n))
8078 ;;; Vertical tree motion, cutting and pasting of subtrees
8080 (defun org-move-subtree-up (&optional arg)
8081 "Move the current subtree up past ARG headlines of the same level."
8082 (interactive "p")
8083 (org-move-subtree-down (- (prefix-numeric-value arg))))
8085 (defun org-move-subtree-down (&optional arg)
8086 "Move the current subtree down past ARG headlines of the same level."
8087 (interactive "p")
8088 (setq arg (prefix-numeric-value arg))
8089 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8090 'org-get-last-sibling))
8091 (ins-point (make-marker))
8092 (cnt (abs arg))
8093 (col (current-column))
8094 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8095 ;; Select the tree
8096 (org-back-to-heading)
8097 (setq beg0 (point))
8098 (save-excursion
8099 (setq ne-beg (org-back-over-empty-lines))
8100 (setq beg (point)))
8101 (save-match-data
8102 (save-excursion (outline-end-of-heading)
8103 (setq folded (org-invisible-p)))
8104 (progn (org-end-of-subtree nil t)
8105 (unless (eobp) (backward-char))))
8106 (outline-next-heading)
8107 (setq ne-end (org-back-over-empty-lines))
8108 (setq end (point))
8109 (goto-char beg0)
8110 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8111 ;; include less whitespace
8112 (save-excursion
8113 (goto-char beg)
8114 (forward-line (- ne-beg ne-end))
8115 (setq beg (point))))
8116 ;; Find insertion point, with error handling
8117 (while (> cnt 0)
8118 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8119 (progn (goto-char beg0)
8120 (user-error "Cannot move past superior level or buffer limit")))
8121 (setq cnt (1- cnt)))
8122 (when (> arg 0)
8123 ;; Moving forward - still need to move over subtree
8124 (org-end-of-subtree t t)
8125 (save-excursion
8126 (org-back-over-empty-lines)
8127 (or (bolp) (newline))))
8128 (setq ne-ins (org-back-over-empty-lines))
8129 (move-marker ins-point (point))
8130 (setq txt (buffer-substring beg end))
8131 (org-save-markers-in-region beg end)
8132 (delete-region beg end)
8133 (org-remove-empty-overlays-at beg)
8134 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8135 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8136 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8137 (let ((bbb (point)))
8138 (insert-before-markers txt)
8139 (org-reinstall-markers-in-region bbb)
8140 (move-marker ins-point bbb))
8141 (or (bolp) (insert "\n"))
8142 (setq ins-end (point))
8143 (goto-char ins-point)
8144 (org-skip-whitespace)
8145 (when (and (< arg 0)
8146 (org-first-sibling-p)
8147 (> ne-ins ne-beg))
8148 ;; Move whitespace back to beginning
8149 (save-excursion
8150 (goto-char ins-end)
8151 (let ((kill-whole-line t))
8152 (kill-line (- ne-ins ne-beg)) (point)))
8153 (insert (make-string (- ne-ins ne-beg) ?\n)))
8154 (move-marker ins-point nil)
8155 (if folded
8156 (outline-hide-subtree)
8157 (org-show-entry)
8158 (org-show-children)
8159 (org-cycle-hide-drawers 'children))
8160 (org-clean-visibility-after-subtree-move)
8161 ;; move back to the initial column we were at
8162 (move-to-column col)))
8164 (defvar org-subtree-clip ""
8165 "Clipboard for cut and paste of subtrees.
8166 This is actually only a copy of the kill, because we use the normal kill
8167 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8169 (defvar org-subtree-clip-folded nil
8170 "Was the last copied subtree folded?
8171 This is used to fold the tree back after pasting.")
8173 (defun org-cut-subtree (&optional n)
8174 "Cut the current subtree into the clipboard.
8175 With prefix arg N, cut this many sequential subtrees.
8176 This is a short-hand for marking the subtree and then cutting it."
8177 (interactive "p")
8178 (org-copy-subtree n 'cut))
8180 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8181 "Copy the current subtree it in the clipboard.
8182 With prefix arg N, copy this many sequential subtrees.
8183 This is a short-hand for marking the subtree and then copying it.
8184 If CUT is non-nil, actually cut the subtree.
8185 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8186 of some markers in the region, even if CUT is non-nil. This is
8187 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8188 (interactive "p")
8189 (let (beg end folded (beg0 (point)))
8190 (if (called-interactively-p 'any)
8191 (org-back-to-heading nil) ; take what looks like a subtree
8192 (org-back-to-heading t)) ; take what is really there
8193 (setq beg (point))
8194 (skip-chars-forward " \t\r\n")
8195 (save-match-data
8196 (if nosubtrees
8197 (outline-next-heading)
8198 (save-excursion (outline-end-of-heading)
8199 (setq folded (org-invisible-p)))
8200 (ignore-errors (org-forward-heading-same-level (1- n) t))
8201 (org-end-of-subtree t t)))
8202 ;; Include the end of an inlinetask
8203 (when (and (featurep 'org-inlinetask)
8204 (looking-at-p (concat (org-inlinetask-outline-regexp)
8205 "END[ \t]*$")))
8206 (end-of-line))
8207 (setq end (point))
8208 (goto-char beg0)
8209 (when (> end beg)
8210 (setq org-subtree-clip-folded folded)
8211 (when (or cut force-store-markers)
8212 (org-save-markers-in-region beg end))
8213 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8214 (setq org-subtree-clip (current-kill 0))
8215 (message "%s: Subtree(s) with %d characters"
8216 (if cut "Cut" "Copied")
8217 (length org-subtree-clip)))))
8219 (defun org-paste-subtree (&optional level tree for-yank remove)
8220 "Paste the clipboard as a subtree, with modification of headline level.
8221 The entire subtree is promoted or demoted in order to match a new headline
8222 level.
8224 If the cursor is at the beginning of a headline, the same level as
8225 that headline is used to paste the tree.
8227 If not, the new level is derived from the *visible* headings
8228 before and after the insertion point, and taken to be the inferior headline
8229 level of the two. So if the previous visible heading is level 3 and the
8230 next is level 4 (or vice versa), level 4 will be used for insertion.
8231 This makes sure that the subtree remains an independent subtree and does
8232 not swallow low level entries.
8234 You can also force a different level, either by using a numeric prefix
8235 argument, or by inserting the heading marker by hand. For example, if the
8236 cursor is after \"*****\", then the tree will be shifted to level 5.
8238 If optional TREE is given, use this text instead of the kill ring.
8240 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8241 move back over whitespace before inserting, and move point to the end of
8242 the inserted text when done.
8244 When REMOVE is non-nil, remove the subtree from the clipboard."
8245 (interactive "P")
8246 (setq tree (or tree (and kill-ring (current-kill 0))))
8247 (unless (org-kill-is-subtree-p tree)
8248 (user-error "%s"
8249 (substitute-command-keys
8250 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8251 (org-with-limited-levels
8252 (let* ((visp (not (org-invisible-p)))
8253 (txt tree)
8254 (^re_ "\\(\\*+\\)[ \t]*")
8255 (old-level (if (string-match org-outline-regexp-bol txt)
8256 (- (match-end 0) (match-beginning 0) 1)
8257 -1))
8258 (force-level (cond (level (prefix-numeric-value level))
8259 ((and (looking-at "[ \t]*$")
8260 (string-match
8261 "^\\*+$" (buffer-substring
8262 (point-at-bol) (point))))
8263 (- (match-end 0) (match-beginning 0)))
8264 ((and (bolp)
8265 (looking-at org-outline-regexp))
8266 (- (match-end 0) (point) 1))))
8267 (previous-level (save-excursion
8268 (condition-case nil
8269 (progn
8270 (outline-previous-visible-heading 1)
8271 (if (looking-at ^re_)
8272 (- (match-end 0) (match-beginning 0) 1)
8274 (error 1))))
8275 (next-level (save-excursion
8276 (condition-case nil
8277 (progn
8278 (or (looking-at org-outline-regexp)
8279 (outline-next-visible-heading 1))
8280 (if (looking-at ^re_)
8281 (- (match-end 0) (match-beginning 0) 1)
8283 (error 1))))
8284 (new-level (or force-level (max previous-level next-level)))
8285 (shift (if (or (= old-level -1)
8286 (= new-level -1)
8287 (= old-level new-level))
8289 (- new-level old-level)))
8290 (delta (if (> shift 0) -1 1))
8291 (func (if (> shift 0) 'org-demote 'org-promote))
8292 (org-odd-levels-only nil)
8293 beg end newend)
8294 ;; Remove the forced level indicator
8295 (when force-level
8296 (delete-region (point-at-bol) (point)))
8297 ;; Paste
8298 (beginning-of-line (if (bolp) 1 2))
8299 (setq beg (point))
8300 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8301 (insert-before-markers txt)
8302 (unless (string-suffix-p "\n" txt) (insert "\n"))
8303 (setq newend (point))
8304 (org-reinstall-markers-in-region beg)
8305 (setq end (point))
8306 (goto-char beg)
8307 (skip-chars-forward " \t\n\r")
8308 (setq beg (point))
8309 (when (and (org-invisible-p) visp)
8310 (save-excursion (outline-show-heading)))
8311 ;; Shift if necessary
8312 (unless (= shift 0)
8313 (save-restriction
8314 (narrow-to-region beg end)
8315 (while (not (= shift 0))
8316 (org-map-region func (point-min) (point-max))
8317 (setq shift (+ delta shift)))
8318 (goto-char (point-min))
8319 (setq newend (point-max))))
8320 (when (or (called-interactively-p 'interactive) for-yank)
8321 (message "Clipboard pasted as level %d subtree" new-level))
8322 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8323 kill-ring
8324 (eq org-subtree-clip (current-kill 0))
8325 org-subtree-clip-folded)
8326 ;; The tree was folded before it was killed/copied
8327 (outline-hide-subtree))
8328 (and for-yank (goto-char newend))
8329 (and remove (setq kill-ring (cdr kill-ring))))))
8331 (defun org-kill-is-subtree-p (&optional txt)
8332 "Check if the current kill is an outline subtree, or a set of trees.
8333 Returns nil if kill does not start with a headline, or if the first
8334 headline level is not the largest headline level in the tree.
8335 So this will actually accept several entries of equal levels as well,
8336 which is OK for `org-paste-subtree'.
8337 If optional TXT is given, check this string instead of the current kill."
8338 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8339 (re (org-get-limited-outline-regexp))
8340 (^re (concat "^" re))
8341 (start-level (and kill
8342 (string-match
8343 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8344 kill)
8345 (- (match-end 2) (match-beginning 2) 1)))
8346 (start (1+ (or (match-beginning 2) -1))))
8347 (if (not start-level)
8348 (progn
8349 nil) ;; does not even start with a heading
8350 (catch 'exit
8351 (while (setq start (string-match ^re kill (1+ start)))
8352 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8353 (throw 'exit nil)))
8354 t))))
8356 (defvar org-markers-to-move nil
8357 "Markers that should be moved with a cut-and-paste operation.
8358 Those markers are stored together with their positions relative to
8359 the start of the region.")
8361 (defun org-save-markers-in-region (beg end)
8362 "Check markers in region.
8363 If these markers are between BEG and END, record their position relative
8364 to BEG, so that after moving the block of text, we can put the markers back
8365 into place.
8366 This function gets called just before an entry or tree gets cut from the
8367 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8368 called immediately, to move the markers with the entries."
8369 (setq org-markers-to-move nil)
8370 (when (featurep 'org-clock)
8371 (org-clock-save-markers-for-cut-and-paste beg end))
8372 (when (featurep 'org-agenda)
8373 (org-agenda-save-markers-for-cut-and-paste beg end)))
8375 (defun org-check-and-save-marker (marker beg end)
8376 "Check if MARKER is between BEG and END.
8377 If yes, remember the marker and the distance to BEG."
8378 (when (and (marker-buffer marker)
8379 (equal (marker-buffer marker) (current-buffer))
8380 (>= marker beg) (< marker end))
8381 (push (cons marker (- marker beg)) org-markers-to-move)))
8383 (defun org-reinstall-markers-in-region (beg)
8384 "Move all remembered markers to their position relative to BEG."
8385 (dolist (x org-markers-to-move)
8386 (move-marker (car x) (+ beg (cdr x))))
8387 (setq org-markers-to-move nil))
8389 (defun org-narrow-to-subtree ()
8390 "Narrow buffer to the current subtree."
8391 (interactive)
8392 (save-excursion
8393 (save-match-data
8394 (org-with-limited-levels
8395 (narrow-to-region
8396 (progn (org-back-to-heading t) (point))
8397 (progn (org-end-of-subtree t t)
8398 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8399 (point)))))))
8401 (defun org-narrow-to-block ()
8402 "Narrow buffer to the current block."
8403 (interactive)
8404 (let* ((case-fold-search t)
8405 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8406 "^[ \t]*#\\+end_.*")))
8407 (if blockp
8408 (narrow-to-region (car blockp) (cdr blockp))
8409 (user-error "Not in a block"))))
8411 (defun org-clone-subtree-with-time-shift (n &optional shift)
8412 "Clone the task (subtree) at point N times.
8413 The clones will be inserted as siblings.
8415 In interactive use, the user will be prompted for the number of
8416 clones to be produced. If the entry has a timestamp, the user
8417 will also be prompted for a time shift, which may be a repeater
8418 as used in time stamps, for example `+3d'. To disable this,
8419 you can call the function with a universal prefix argument.
8421 When a valid repeater is given and the entry contains any time
8422 stamps, the clones will become a sequence in time, with time
8423 stamps in the subtree shifted for each clone produced. If SHIFT
8424 is nil or the empty string, time stamps will be left alone. The
8425 ID property of the original subtree is removed.
8427 In each clone, all the CLOCK entries will be removed. This
8428 prevents Org from considering that the clocked times overlap.
8430 If the original subtree did contain time stamps with a repeater,
8431 the following will happen:
8432 - the repeater will be removed in each clone
8433 - an additional clone will be produced, with the current, unshifted
8434 date(s) in the entry.
8435 - the original entry will be placed *after* all the clones, with
8436 repeater intact.
8437 - the start days in the repeater in the original entry will be shifted
8438 to past the last clone.
8439 In this way you can spell out a number of instances of a repeating task,
8440 and still retain the repeater to cover future instances of the task.
8442 As described above, N+1 clones are produced when the original
8443 subtree has a repeater. Setting N to 0, then, can be used to
8444 remove the repeater from a subtree and create a shifted clone
8445 with the original repeater."
8446 (interactive "nNumber of clones to produce: ")
8447 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8448 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8449 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8450 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8451 (shift
8452 (or shift
8453 (if (and (not (equal current-prefix-arg '(4)))
8454 (save-excursion
8455 (goto-char beg)
8456 (re-search-forward org-ts-regexp-both end-of-tree t)))
8457 (read-from-minibuffer
8458 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8459 ""))) ;No time shift
8460 (doshift
8461 (and (org-string-nw-p shift)
8462 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8463 shift)
8464 (user-error "Invalid shift specification %s" shift)))))
8465 (goto-char end-of-tree)
8466 (unless (bolp) (insert "\n"))
8467 (let* ((end (point))
8468 (template (buffer-substring beg end))
8469 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8470 (shift-what (pcase (and doshift (match-string 2 shift))
8471 (`nil nil)
8472 ("d" 'day)
8473 ("w" (setq shift-n (* 7 shift-n)) 'day)
8474 ("m" 'month)
8475 ("y" 'year)
8476 (_ (error "Unsupported time unit"))))
8477 (nmin 1)
8478 (nmax n)
8479 (n-no-remove -1)
8480 (idprop (org-entry-get nil "ID")))
8481 (when (and doshift
8482 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8483 template))
8484 (delete-region beg end)
8485 (setq end beg)
8486 (setq nmin 0)
8487 (setq nmax (1+ nmax))
8488 (setq n-no-remove nmax))
8489 (goto-char end)
8490 (cl-loop for n from nmin to nmax do
8491 (insert
8492 ;; Prepare clone.
8493 (with-temp-buffer
8494 (insert template)
8495 (org-mode)
8496 (goto-char (point-min))
8497 (org-show-subtree)
8498 (and idprop (if org-clone-delete-id
8499 (org-entry-delete nil "ID")
8500 (org-id-get-create t)))
8501 (unless (= n 0)
8502 (while (re-search-forward org-clock-line-re nil t)
8503 (delete-region (line-beginning-position)
8504 (line-beginning-position 2)))
8505 (goto-char (point-min))
8506 (while (re-search-forward org-drawer-regexp nil t)
8507 (org-remove-empty-drawer-at (point))))
8508 (goto-char (point-min))
8509 (when doshift
8510 (while (re-search-forward org-ts-regexp-both nil t)
8511 (org-timestamp-change (* n shift-n) shift-what))
8512 (unless (= n n-no-remove)
8513 (goto-char (point-min))
8514 (while (re-search-forward org-ts-regexp nil t)
8515 (save-excursion
8516 (goto-char (match-beginning 0))
8517 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8518 (delete-region (match-beginning 1) (match-end 1)))))))
8519 (buffer-string)))))
8520 (goto-char beg)))
8522 ;;; Outline Sorting
8524 (defun org-sort (&optional with-case)
8525 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8526 Optional argument WITH-CASE means sort case-sensitively."
8527 (interactive "P")
8528 (org-call-with-arg
8529 (cond ((org-at-table-p) #'org-table-sort-lines)
8530 ((org-at-item-p) #'org-sort-list)
8531 (t #'org-sort-entries))
8532 with-case))
8534 (defun org-sort-remove-invisible (s)
8535 "Remove invisible part of links and emphasis markers from string S."
8536 (remove-text-properties 0 (length s) org-rm-props s)
8537 (replace-regexp-in-string
8538 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8539 (replace-regexp-in-string
8540 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8541 (org-link-display-format s)
8542 t t) t t))
8544 (defvar org-priority-regexp) ; defined later in the file
8546 (defvar org-after-sorting-entries-or-items-hook nil
8547 "Hook that is run after a bunch of entries or items have been sorted.
8548 When children are sorted, the cursor is in the parent line when this
8549 hook gets called. When a region or a plain list is sorted, the cursor
8550 will be in the first entry of the sorted region/list.")
8552 (defun org-sort-entries
8553 (&optional with-case sorting-type getkey-func compare-func property
8554 interactive?)
8555 "Sort entries on a certain level of an outline tree.
8556 If there is an active region, the entries in the region are sorted.
8557 Else, if the cursor is before the first entry, sort the top-level items.
8558 Else, the children of the entry at point are sorted.
8560 Sorting can be alphabetically, numerically, by date/time as given by
8561 a time stamp, by a property, by priority order, or by a custom function.
8563 The command prompts for the sorting type unless it has been given to the
8564 function through the SORTING-TYPE argument, which needs to be a character,
8565 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8566 the precise meaning of each character:
8568 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8569 c By creation time, which is assumed to be the first inactive time stamp
8570 at the beginning of a line.
8571 d By deadline date/time.
8572 k By clocking time.
8573 n Numerically, by converting the beginning of the entry/item to a number.
8574 o By order of TODO keywords.
8575 p By priority according to the cookie.
8576 r By the value of a property.
8577 s By scheduled date/time.
8578 t By date/time, either the first active time stamp in the entry, or, if
8579 none exist, by the first inactive one.
8581 Capital letters will reverse the sort order.
8583 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8584 called with point at the beginning of the record. It must return a
8585 value that is compatible with COMPARE-FUNC, the function used to
8586 compare entries.
8588 Comparing entries ignores case by default. However, with an optional argument
8589 WITH-CASE, the sorting considers case as well.
8591 Sorting is done against the visible part of the headlines, it ignores hidden
8592 links.
8594 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8596 A non-nil value for INTERACTIVE? is used to signal that this
8597 function is being called interactively."
8598 (interactive (list current-prefix-arg nil nil nil nil t))
8599 (let ((case-func (if with-case 'identity 'downcase))
8600 start beg end stars re re2
8601 txt what tmp)
8602 ;; Find beginning and end of region to sort
8603 (cond
8604 ((org-region-active-p)
8605 ;; we will sort the region
8606 (setq end (region-end)
8607 what "region")
8608 (goto-char (region-beginning))
8609 (unless (org-at-heading-p) (outline-next-heading))
8610 (setq start (point)))
8611 ((or (org-at-heading-p)
8612 (ignore-errors (progn (org-back-to-heading) t)))
8613 ;; we will sort the children of the current headline
8614 (org-back-to-heading)
8615 (setq start (point)
8616 end (progn (org-end-of-subtree t t)
8617 (or (bolp) (insert "\n"))
8618 (when (>= (org-back-over-empty-lines) 1)
8619 (forward-line 1))
8620 (point))
8621 what "children")
8622 (goto-char start)
8623 (outline-show-subtree)
8624 (outline-next-heading))
8626 ;; we will sort the top-level entries in this file
8627 (goto-char (point-min))
8628 (or (org-at-heading-p) (outline-next-heading))
8629 (setq start (point))
8630 (goto-char (point-max))
8631 (beginning-of-line 1)
8632 (when (looking-at ".*?\\S-")
8633 ;; File ends in a non-white line
8634 (end-of-line 1)
8635 (insert "\n"))
8636 (setq end (point-max))
8637 (setq what "top-level")
8638 (goto-char start)
8639 (outline-show-all)))
8641 (setq beg (point))
8642 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8644 (looking-at "\\(\\*+\\)")
8645 (setq stars (match-string 1)
8646 re (concat "^" (regexp-quote stars) " +")
8647 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8648 txt (buffer-substring beg end))
8649 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8650 (when (and (not (equal stars "*")) (string-match re2 txt))
8651 (user-error "Region to sort contains a level above the first entry"))
8653 (unless sorting-type
8654 (message
8655 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8656 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8657 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8658 what)
8659 (setq sorting-type (read-char-exclusive)))
8661 (unless getkey-func
8662 (and (= (downcase sorting-type) ?f)
8663 (setq getkey-func
8664 (or (and interactive?
8665 (org-read-function
8666 "Function for extracting keys: "))
8667 (error "Missing key extractor")))))
8669 (and (= (downcase sorting-type) ?r)
8670 (not property)
8671 (setq property
8672 (completing-read "Property: "
8673 (mapcar #'list (org-buffer-property-keys t))
8674 nil t)))
8676 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8677 (message "Sorting entries...")
8679 (save-restriction
8680 (narrow-to-region start end)
8681 (let ((restore-clock?
8682 ;; The clock marker is lost when using `sort-subr'; mark
8683 ;; the clock with temporary `:org-clock-marker-backup'
8684 ;; text property.
8685 (when (and (eq (org-clock-is-active) (current-buffer))
8686 (<= start (marker-position org-clock-marker))
8687 (>= end (marker-position org-clock-marker)))
8688 (org-with-silent-modifications
8689 (put-text-property (1- org-clock-marker) org-clock-marker
8690 :org-clock-marker-backup t))
8692 (dcst (downcase sorting-type))
8693 (case-fold-search nil)
8694 (now (current-time)))
8695 (sort-subr
8696 (/= dcst sorting-type)
8697 ;; This function moves to the beginning character of the "record" to
8698 ;; be sorted.
8699 (lambda nil
8700 (if (re-search-forward re nil t)
8701 (goto-char (match-beginning 0))
8702 (goto-char (point-max))))
8703 ;; This function moves to the last character of the "record" being
8704 ;; sorted.
8705 (lambda nil
8706 (save-match-data
8707 (condition-case nil
8708 (outline-forward-same-level 1)
8709 (error
8710 (goto-char (point-max))))))
8711 ;; This function returns the value that gets sorted against.
8712 (lambda nil
8713 (cond
8714 ((= dcst ?n)
8715 (if (looking-at org-complex-heading-regexp)
8716 (string-to-number (org-sort-remove-invisible (match-string 4)))
8717 nil))
8718 ((= dcst ?a)
8719 (if (looking-at org-complex-heading-regexp)
8720 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8721 nil))
8722 ((= dcst ?k)
8723 (or (get-text-property (point) :org-clock-minutes) 0))
8724 ((= dcst ?t)
8725 (let ((end (save-excursion (outline-next-heading) (point))))
8726 (if (or (re-search-forward org-ts-regexp end t)
8727 (re-search-forward org-ts-regexp-both end t))
8728 (org-time-string-to-seconds (match-string 0))
8729 (float-time now))))
8730 ((= dcst ?c)
8731 (let ((end (save-excursion (outline-next-heading) (point))))
8732 (if (re-search-forward
8733 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8734 end t)
8735 (org-time-string-to-seconds (match-string 0))
8736 (float-time now))))
8737 ((= dcst ?s)
8738 (let ((end (save-excursion (outline-next-heading) (point))))
8739 (if (re-search-forward org-scheduled-time-regexp end t)
8740 (org-time-string-to-seconds (match-string 1))
8741 (float-time now))))
8742 ((= dcst ?d)
8743 (let ((end (save-excursion (outline-next-heading) (point))))
8744 (if (re-search-forward org-deadline-time-regexp end t)
8745 (org-time-string-to-seconds (match-string 1))
8746 (float-time now))))
8747 ((= dcst ?p)
8748 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8749 (string-to-char (match-string 2))
8750 org-default-priority))
8751 ((= dcst ?r)
8752 (or (org-entry-get nil property) ""))
8753 ((= dcst ?o)
8754 (when (looking-at org-complex-heading-regexp)
8755 (let* ((m (match-string 2))
8756 (s (if (member m org-done-keywords) '- '+)))
8757 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8758 ((= dcst ?f)
8759 (if getkey-func
8760 (progn
8761 (setq tmp (funcall getkey-func))
8762 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8763 tmp)
8764 (error "Invalid key function `%s'" getkey-func)))
8765 (t (error "Invalid sorting type `%c'" sorting-type))))
8767 (cond
8768 ((= dcst ?a) 'string<)
8769 ((= dcst ?f)
8770 (or compare-func
8771 (and interactive?
8772 (org-read-function
8773 (concat "Function for comparing keys "
8774 "(empty for default `sort-subr' predicate): ")
8775 'allow-empty))))
8776 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
8777 (when restore-clock?
8778 (move-marker org-clock-marker
8779 (1+ (next-single-property-change
8780 start :org-clock-marker-backup)))
8781 (remove-text-properties (1- org-clock-marker) org-clock-marker
8782 '(:org-clock-marker-backup t)))))
8783 (run-hooks 'org-after-sorting-entries-or-items-hook)
8784 (message "Sorting entries...done")))
8786 ;;; The orgstruct minor mode
8788 ;; Define a minor mode which can be used in other modes in order to
8789 ;; integrate the Org mode structure editing commands.
8791 ;; This is really a hack, because the Org mode structure commands use
8792 ;; keys which normally belong to the major mode. Here is how it
8793 ;; works: The minor mode defines all the keys necessary to operate the
8794 ;; structure commands, but wraps the commands into a function which
8795 ;; tests if the cursor is currently at a headline or a plain list
8796 ;; item. If that is the case, the structure command is used,
8797 ;; temporarily setting many Org mode variables like regular
8798 ;; expressions for filling etc. However, when any of those keys is
8799 ;; used at a different location, function uses `key-binding' to look
8800 ;; up if the key has an associated command in another currently active
8801 ;; keymap (minor modes, major mode, global), and executes that
8802 ;; command. There might be problems if any of the keys is otherwise
8803 ;; used as a prefix key.
8805 (defcustom orgstruct-heading-prefix-regexp ""
8806 "Regexp that matches the custom prefix of Org headlines in
8807 orgstruct(++)-mode."
8808 :group 'org
8809 :version "26.1"
8810 :package-version '(Org . "8.3")
8811 :type 'regexp)
8812 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8814 (defcustom orgstruct-setup-hook nil
8815 "Hook run after orgstruct-mode-map is filled."
8816 :group 'org
8817 :version "24.4"
8818 :package-version '(Org . "8.0")
8819 :type 'hook)
8821 (defvar orgstruct-initialized nil)
8823 (defvar org-local-vars nil
8824 "List of local variables, for use by `orgstruct-mode'.")
8826 ;;;###autoload
8827 (define-minor-mode orgstruct-mode
8828 "Toggle the minor mode `orgstruct-mode'.
8829 This mode is for using Org mode structure commands in other
8830 modes. The following keys behave as if Org mode were active, if
8831 the cursor is on a headline, or on a plain list item (both as
8832 defined by Org mode)."
8833 nil " OrgStruct" (make-sparse-keymap)
8834 (funcall (if orgstruct-mode
8835 'add-to-invisibility-spec
8836 'remove-from-invisibility-spec)
8837 '(outline . t))
8838 (when orgstruct-mode
8839 (org-load-modules-maybe)
8840 (unless orgstruct-initialized
8841 (orgstruct-setup)
8842 (setq orgstruct-initialized t))))
8844 ;;;###autoload
8845 (defun turn-on-orgstruct ()
8846 "Unconditionally turn on `orgstruct-mode'."
8847 (orgstruct-mode 1))
8849 (defvar-local orgstruct-is-++ nil
8850 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8851 (defvar-local org-fb-vars nil)
8852 (defun orgstruct++-mode (&optional arg)
8853 "Toggle `orgstruct-mode', the enhanced version of it.
8854 In addition to setting orgstruct-mode, this also exports all
8855 indentation and autofilling variables from Org mode into the
8856 buffer. It will also recognize item context in multiline items."
8857 (interactive "P")
8858 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8859 (if (< arg 1)
8860 (progn (orgstruct-mode -1)
8861 (dolist (v org-fb-vars)
8862 (set (make-local-variable (car v))
8863 (if (eq (car-safe (cadr v)) 'quote)
8864 (cl-cadadr v)
8865 (nth 1 v)))))
8866 (orgstruct-mode 1)
8867 (setq org-fb-vars nil)
8868 (unless org-local-vars
8869 (setq org-local-vars (org-get-local-variables)))
8870 (let (var val)
8871 (dolist (x org-local-vars)
8872 (when (string-match
8873 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
8874 \\|fill-prefix\\|indent-\\)"
8875 (symbol-name (car x)))
8876 (setq var (car x) val (nth 1 x))
8877 (push (list var `(quote ,(eval var))) org-fb-vars)
8878 (set (make-local-variable var)
8879 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8880 (setq-local orgstruct-is-++ t))))
8882 ;;;###autoload
8883 (defun turn-on-orgstruct++ ()
8884 "Unconditionally turn on `orgstruct++-mode'."
8885 (orgstruct++-mode 1))
8887 (defun orgstruct-error ()
8888 "Error when there is no default binding for a structure key."
8889 (interactive)
8890 (funcall (if (fboundp 'user-error)
8891 'user-error
8892 'error)
8893 "This key has no function outside structure elements"))
8895 (defun orgstruct-setup ()
8896 "Setup orgstruct keymap."
8897 (dolist (cell '((org-demote . t)
8898 (org-metaleft . t)
8899 (org-metaright . t)
8900 (org-promote . t)
8901 (org-shiftmetaleft . t)
8902 (org-shiftmetaright . t)
8903 org-backward-element
8904 org-backward-heading-same-level
8905 org-ctrl-c-ret
8906 org-ctrl-c-minus
8907 org-ctrl-c-star
8908 org-cycle
8909 org-force-cycle-archived
8910 org-forward-heading-same-level
8911 org-insert-heading
8912 org-insert-heading-respect-content
8913 org-kill-note-or-show-branches
8914 org-mark-subtree
8915 org-meta-return
8916 org-metadown
8917 org-metaup
8918 org-narrow-to-subtree
8919 org-promote-subtree
8920 org-reveal
8921 org-shiftdown
8922 org-shiftleft
8923 org-shiftmetadown
8924 org-shiftmetaup
8925 org-shiftright
8926 org-shifttab
8927 org-shifttab
8928 org-shiftup
8929 org-show-children
8930 org-show-subtree
8931 org-sort
8932 org-up-element
8933 outline-demote
8934 outline-next-visible-heading
8935 outline-previous-visible-heading
8936 outline-promote
8937 outline-up-heading))
8938 (let ((f (or (car-safe cell) cell))
8939 (disable-when-heading-prefix (cdr-safe cell)))
8940 (when (fboundp f)
8941 (let ((new-bindings))
8942 (dolist (binding (nconc (where-is-internal f org-mode-map)
8943 (where-is-internal f outline-mode-map)))
8944 (push binding new-bindings)
8945 ;; TODO use local-function-key-map
8946 (dolist (rep '(("<tab>" . "TAB")
8947 ("<return>" . "RET")
8948 ("<escape>" . "ESC")
8949 ("<delete>" . "DEL")))
8950 (setq binding (read-kbd-macro
8951 (let ((case-fold-search))
8952 (replace-regexp-in-string
8953 (regexp-quote (cdr rep))
8954 (car rep)
8955 (key-description binding)))))
8956 (cl-pushnew binding new-bindings :test 'equal)))
8957 (dolist (binding new-bindings)
8958 (let ((key (lookup-key orgstruct-mode-map binding)))
8959 (when (or (not key) (numberp key))
8960 (ignore-errors
8961 (org-defkey orgstruct-mode-map
8962 binding
8963 (orgstruct-make-binding
8964 f binding disable-when-heading-prefix))))))))))
8965 (run-hooks 'orgstruct-setup-hook))
8967 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8968 "Create a function for binding in the structure minor mode.
8969 FUN is the command to call inside a table. KEY is the key that
8970 should be checked in for a command to execute outside of tables.
8971 Non-nil `disable-when-heading-prefix' means to disable the command
8972 if `orgstruct-heading-prefix-regexp' is not empty."
8973 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8974 (let ((nname name)
8975 (i 0))
8976 (while (fboundp (intern nname))
8977 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8978 (setq name (intern nname)))
8979 (eval
8980 (let ((bindings '((org-heading-regexp
8981 (concat "^"
8982 orgstruct-heading-prefix-regexp
8983 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8984 (org-outline-regexp
8985 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8986 (org-outline-regexp-bol
8987 (concat "^" org-outline-regexp))
8988 (outline-regexp org-outline-regexp)
8989 (outline-heading-end-regexp "\n")
8990 (outline-level 'org-outline-level)
8991 (outline-heading-alist))))
8992 `(defun ,name (arg)
8993 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8994 "Outside of structure, run the binding of `"
8995 (key-description key) "'."
8996 (when disable-when-heading-prefix
8997 (concat
8998 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
8999 "back to the default binding due to limitations of Org's implementation of\n"
9000 "`" (symbol-name fun) "'.")))
9001 (interactive "p")
9002 (let* ((disable
9003 ,(and disable-when-heading-prefix
9004 '(not (string= orgstruct-heading-prefix-regexp ""))))
9005 (fallback
9006 (or disable
9007 (not
9008 (let* ,bindings
9009 (org-context-p 'headline 'item
9010 ,(when (memq fun
9011 '(org-insert-heading
9012 org-insert-heading-respect-content
9013 org-meta-return))
9014 '(when orgstruct-is-++
9015 'item-body))))))))
9016 (if fallback
9017 (let* ((orgstruct-mode)
9018 (binding
9019 (let ((key ,key))
9020 (catch 'exit
9021 (dolist
9022 (rep
9023 '(nil
9024 ("<\\([^>]*\\)tab>" . "\\1TAB")
9025 ("<\\([^>]*\\)return>" . "\\1RET")
9026 ("<\\([^>]*\\)escape>" . "\\1ESC")
9027 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9028 nil)
9029 (when rep
9030 (setq key (read-kbd-macro
9031 (let ((case-fold-search))
9032 (replace-regexp-in-string
9033 (car rep)
9034 (cdr rep)
9035 (key-description key))))))
9036 (when (key-binding key)
9037 (throw 'exit (key-binding key))))))))
9038 (if (keymapp binding)
9039 (org-set-transient-map binding)
9040 (let ((func (or binding
9041 (unless disable
9042 'orgstruct-error))))
9043 (when func
9044 (call-interactively func)))))
9045 (org-run-like-in-org-mode
9046 (lambda ()
9047 (interactive)
9048 (let* ,bindings
9049 (call-interactively ',fun)))))))))
9050 name))
9052 (defun org-contextualize-keys (alist contexts)
9053 "Return valid elements in ALIST depending on CONTEXTS.
9055 `org-agenda-custom-commands' or `org-capture-templates' are the
9056 values used for ALIST, and `org-agenda-custom-commands-contexts'
9057 or `org-capture-templates-contexts' are the associated contexts
9058 definitions."
9059 (let ((contexts
9060 ;; normalize contexts
9061 (mapcar
9062 (lambda(c) (cond ((listp (cadr c))
9063 (list (car c) (car c) (nth 1 c)))
9064 ((string= "" (cadr c))
9065 (list (car c) (car c) (nth 2 c)))
9066 (t c)))
9067 contexts))
9068 (a alist) r s)
9069 ;; loop over all commands or templates
9070 (dolist (c a)
9071 (let (vrules repl)
9072 (cond
9073 ((not (assoc (car c) contexts))
9074 (push c r))
9075 ((and (assoc (car c) contexts)
9076 (setq vrules (org-contextualize-validate-key
9077 (car c) contexts)))
9078 (mapc (lambda (vr)
9079 (unless (equal (car vr) (cadr vr))
9080 (setq repl vr)))
9081 vrules)
9082 (if (not repl) (push c r)
9083 (push (cadr repl) s)
9084 (push
9085 (cons (car c)
9086 (cdr (or (assoc (cadr repl) alist)
9087 (error "Undefined key `%s' as contextual replacement for `%s'"
9088 (cadr repl) (car c)))))
9089 r))))))
9090 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9091 (delq
9093 (delete-dups
9094 (mapcar (lambda (x)
9095 (let ((tpl (car x)))
9096 (unless (delq
9098 (mapcar (lambda (y)
9099 (equal y tpl))
9101 x)))
9102 (reverse r))))))
9104 (defun org-contextualize-validate-key (key contexts)
9105 "Check CONTEXTS for agenda or capture KEY."
9106 (let (res)
9107 (dolist (r contexts)
9108 (dolist (rr (car (last r)))
9109 (when
9110 (and (equal key (car r))
9111 (if (functionp rr) (funcall rr)
9112 (or (and (eq (car rr) 'in-file)
9113 (buffer-file-name)
9114 (string-match (cdr rr) (buffer-file-name)))
9115 (and (eq (car rr) 'in-mode)
9116 (string-match (cdr rr) (symbol-name major-mode)))
9117 (and (eq (car rr) 'in-buffer)
9118 (string-match (cdr rr) (buffer-name)))
9119 (when (and (eq (car rr) 'not-in-file)
9120 (buffer-file-name))
9121 (not (string-match (cdr rr) (buffer-file-name))))
9122 (when (eq (car rr) 'not-in-mode)
9123 (not (string-match (cdr rr) (symbol-name major-mode))))
9124 (when (eq (car rr) 'not-in-buffer)
9125 (not (string-match (cdr rr) (buffer-name)))))))
9126 (push r res))))
9127 (delete-dups (delq nil res))))
9129 (defun org-context-p (&rest contexts)
9130 "Check if local context is any of CONTEXTS.
9131 Possible values in the list of contexts are `table', `headline', and `item'."
9132 (let ((pos (point)))
9133 (goto-char (point-at-bol))
9134 (prog1 (or (and (memq 'table contexts)
9135 (looking-at "[ \t]*|"))
9136 (and (memq 'headline contexts)
9137 (looking-at org-outline-regexp))
9138 (and (memq 'item contexts)
9139 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9140 (and (memq 'item-body contexts)
9141 (org-in-item-p)))
9142 (goto-char pos))))
9144 ;;;###autoload
9145 (defun org-run-like-in-org-mode (cmd)
9146 "Run a command, pretending that the current buffer is in Org mode.
9147 This will temporarily bind local variables that are typically bound in
9148 Org mode to the values they have in Org mode, and then interactively
9149 call CMD."
9150 (org-load-modules-maybe)
9151 (unless org-local-vars
9152 (setq org-local-vars (org-get-local-variables)))
9153 (let (binds)
9154 (dolist (var org-local-vars)
9155 (when (or (not (boundp (car var)))
9156 (eq (symbol-value (car var))
9157 (default-value (car var))))
9158 (push (list (car var) `(quote ,(cadr var))) binds)))
9159 (eval `(let ,binds
9160 (call-interactively (quote ,cmd))))))
9162 (defun org-get-category (&optional pos force-refresh)
9163 "Get the category applying to position POS."
9164 (save-match-data
9165 (when force-refresh (org-refresh-category-properties))
9166 (let ((pos (or pos (point))))
9167 (or (get-text-property pos 'org-category)
9168 (progn (org-refresh-category-properties)
9169 (get-text-property pos 'org-category))))))
9171 ;;; Refresh properties
9173 (defun org-refresh-properties (dprop tprop)
9174 "Refresh buffer text properties.
9175 DPROP is the drawer property and TPROP is either the
9176 corresponding text property to set, or an alist with each element
9177 being a text property (as a symbol) and a function to apply to
9178 the value of the drawer property."
9179 (let* ((case-fold-search t)
9180 (inhibit-read-only t)
9181 (inherit? (org-property-inherit-p dprop))
9182 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9183 (global (and inherit? (org--property-global-value dprop nil))))
9184 (org-with-silent-modifications
9185 (org-with-point-at 1
9186 ;; Set global values (e.g., values defined through
9187 ;; "#+PROPERTY:" keywords) to the whole buffer.
9188 (when global (put-text-property (point-min) (point-max) tprop global))
9189 ;; Set local values.
9190 (while (re-search-forward property-re nil t)
9191 (when (org-at-property-p)
9192 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9193 (outline-next-heading))))))
9195 (defun org-refresh-property (tprop p &optional inherit)
9196 "Refresh the buffer text property TPROP from the drawer property P.
9197 The refresh happens only for the current headline, or the whole
9198 sub-tree if optional argument INHERIT is non-nil."
9199 (unless (org-before-first-heading-p)
9200 (save-excursion
9201 (org-back-to-heading t)
9202 (let ((start (point))
9203 (end (save-excursion
9204 (if inherit (org-end-of-subtree t t)
9205 (or (outline-next-heading) (point-max))))))
9206 (if (symbolp tprop)
9207 ;; TPROP is a text property symbol.
9208 (put-text-property start end tprop p)
9209 ;; TPROP is an alist with (property . function) elements.
9210 (pcase-dolist (`(,prop . ,f) tprop)
9211 (put-text-property start end prop (funcall f p))))))))
9213 (defun org-refresh-category-properties ()
9214 "Refresh category text properties in the buffer."
9215 (let ((case-fold-search t)
9216 (inhibit-read-only t)
9217 (default-category
9218 (cond ((null org-category)
9219 (if buffer-file-name
9220 (file-name-sans-extension
9221 (file-name-nondirectory buffer-file-name))
9222 "???"))
9223 ((symbolp org-category) (symbol-name org-category))
9224 (t org-category))))
9225 (org-with-silent-modifications
9226 (org-with-wide-buffer
9227 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9228 ;; This is the default category for the buffer. If none is
9229 ;; found, fall-back to `org-category' or buffer file name.
9230 (put-text-property
9231 (point-min) (point-max)
9232 'org-category
9233 (catch 'buffer-category
9234 (goto-char (point-max))
9235 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9236 (let ((element (org-element-at-point)))
9237 (when (eq (org-element-type element) 'keyword)
9238 (throw 'buffer-category
9239 (org-element-property :value element)))))
9240 default-category))
9241 ;; Set sub-tree specific categories.
9242 (goto-char (point-min))
9243 (let ((regexp (org-re-property "CATEGORY")))
9244 (while (re-search-forward regexp nil t)
9245 (let ((value (match-string-no-properties 3)))
9246 (when (org-at-property-p)
9247 (put-text-property
9248 (save-excursion (org-back-to-heading t) (point))
9249 (save-excursion (org-end-of-subtree t t) (point))
9250 'org-category
9251 value)))))))))
9253 (defun org-refresh-stats-properties ()
9254 "Refresh stats text properties in the buffer."
9255 (org-with-silent-modifications
9256 (org-with-point-at 1
9257 (let ((regexp (concat org-outline-regexp-bol
9258 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9259 (while (re-search-forward regexp nil t)
9260 (let* ((numerator (string-to-number (match-string 1)))
9261 (denominator (and (match-end 2)
9262 (string-to-number (match-string 2))))
9263 (stats (cond ((not denominator) numerator) ;percent
9264 ((= denominator 0) 0)
9265 (t (/ (* numerator 100) denominator)))))
9266 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9267 'org-stats stats)))))))
9269 (defun org-refresh-effort-properties ()
9270 "Refresh effort properties"
9271 (org-refresh-properties
9272 org-effort-property
9273 '((effort . identity)
9274 (effort-minutes . org-duration-to-minutes))))
9276 ;;;; Link Stuff
9278 ;;; Link abbreviations
9280 (defun org-link-expand-abbrev (link)
9281 "Apply replacements as defined in `org-link-abbrev-alist'."
9282 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9283 (let* ((key (match-string 1 link))
9284 (as (or (assoc key org-link-abbrev-alist-local)
9285 (assoc key org-link-abbrev-alist)))
9286 (tag (and (match-end 2) (match-string 3 link)))
9287 rpl)
9288 (if (not as)
9289 link
9290 (setq rpl (cdr as))
9291 (cond
9292 ((symbolp rpl) (funcall rpl tag))
9293 ((string-match "%(\\([^)]+\\))" rpl)
9294 (replace-match
9295 (save-match-data
9296 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9297 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9298 ((string-match "%h" rpl)
9299 (replace-match (url-hexify-string (or tag "")) t t rpl))
9300 (t (concat rpl tag)))))
9301 link))
9303 ;;; Storing and inserting links
9305 (defvar org-insert-link-history nil
9306 "Minibuffer history for links inserted with `org-insert-link'.")
9308 (defvar org-stored-links nil
9309 "Contains the links stored with `org-store-link'.")
9311 (defvar org-store-link-plist nil
9312 "Plist with info about the most recently link created with `org-store-link'.")
9314 (defun org-store-link-functions ()
9315 "Return a list of functions that are called to create and store a link.
9316 The functions defined in the :store property of
9317 `org-link-parameters'.
9319 Each function will be called in turn until one returns a non-nil
9320 value. Each function should check if it is responsible for
9321 creating this link (for example by looking at the major mode).
9322 If not, it must exit and return nil. If yes, it should return
9323 a non-nil value after calling `org-store-link-props' with a list
9324 of properties and values. Special properties are:
9326 :type The link prefix, like \"http\". This must be given.
9327 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9328 This is obligatory as well.
9329 :description Optional default description for the second pair
9330 of brackets in an Org mode link. The user can still change
9331 this when inserting this link into an Org mode buffer.
9333 In addition to these, any additional properties can be specified
9334 and then used in capture templates."
9335 (cl-loop for link in org-link-parameters
9336 with store-func
9337 do (setq store-func (org-link-get-parameter (car link) :store))
9338 if store-func
9339 collect store-func))
9341 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9342 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9344 ;;;###autoload
9345 (defun org-store-link (arg)
9346 "Store an org-link to the current location.
9347 \\<org-mode-map>
9348 This link is added to `org-stored-links' and can later be inserted
9349 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9351 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9352 A single
9353 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9354 `org-gnus-prefer-web-links' for links to Usenet articles.
9356 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9357 skipping storing functions that are not
9358 part of Org core.
9360 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9361 prefix ARG forces storing a link for each line in the
9362 active region."
9363 (interactive "P")
9364 (org-load-modules-maybe)
9365 (if (and (equal arg '(64)) (org-region-active-p))
9366 (save-excursion
9367 (let ((end (region-end)))
9368 (goto-char (region-beginning))
9369 (set-mark (point))
9370 (while (< (point-at-eol) end)
9371 (move-end-of-line 1) (activate-mark)
9372 (let (current-prefix-arg)
9373 (call-interactively 'org-store-link))
9374 (move-beginning-of-line 2)
9375 (set-mark (point)))))
9376 (setq org-store-link-plist nil)
9377 (let (link cpltxt desc description search txt custom-id agenda-link)
9378 (cond
9379 ;; Store a link using an external link type, if any function is
9380 ;; available. If more than one can generate a link from current
9381 ;; location, ask which one to use.
9382 ((and (not (equal arg '(16)))
9383 (let ((results-alist nil))
9384 (dolist (f (org-store-link-functions))
9385 (when (funcall f)
9386 ;; XXX: return value is not link's plist, so we
9387 ;; store the new value before it is modified. It
9388 ;; would be cleaner to ask store link functions to
9389 ;; return the plist instead.
9390 (push (cons f (copy-sequence org-store-link-plist))
9391 results-alist)))
9392 (pcase results-alist
9393 (`nil nil)
9394 (`((,_ . ,_)) t) ;single choice: nothing to do
9395 (`((,name . ,_) . ,_)
9396 ;; Reinstate link plist associated to the chosen
9397 ;; function.
9398 (apply #'org-store-link-props
9399 (cdr (assoc-string
9400 (completing-read
9401 "Which function for creating the link? "
9402 (mapcar #'car results-alist) nil t name)
9403 results-alist)))
9404 t))))
9405 (setq link (plist-get org-store-link-plist :link))
9406 (setq desc (or (plist-get org-store-link-plist :description)
9407 link)))
9409 ;; Store a link from a source code buffer.
9410 ((org-src-edit-buffer-p)
9411 (let ((coderef-format (org-src-coderef-format)))
9412 (cond ((save-excursion
9413 (beginning-of-line)
9414 (looking-at (org-src-coderef-regexp coderef-format)))
9415 (setq link (format "(%s)" (match-string-no-properties 3))))
9416 ((called-interactively-p 'any)
9417 (let ((label (read-string "Code line label: ")))
9418 (end-of-line)
9419 (setq link (format coderef-format label))
9420 (let ((gc (- 79 (length link))))
9421 (if (< (current-column) gc)
9422 (org-move-to-column gc t)
9423 (insert " ")))
9424 (insert link)
9425 (setq link (concat "(" label ")"))
9426 (setq desc nil)))
9427 (t (setq link nil)))))
9429 ;; We are in the agenda, link to referenced location
9430 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9431 (let ((m (or (get-text-property (point) 'org-hd-marker)
9432 (get-text-property (point) 'org-marker))))
9433 (when m
9434 (org-with-point-at m
9435 (setq agenda-link
9436 (if (called-interactively-p 'any)
9437 (call-interactively 'org-store-link)
9438 (org-store-link nil)))))))
9440 ((eq major-mode 'calendar-mode)
9441 (let ((cd (calendar-cursor-to-date)))
9442 (setq link
9443 (format-time-string
9444 (car org-time-stamp-formats)
9445 (apply 'encode-time
9446 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9447 nil nil nil))))
9448 (org-store-link-props :type "calendar" :date cd)))
9450 ((eq major-mode 'help-mode)
9451 (setq link (concat "help:" (save-excursion
9452 (goto-char (point-min))
9453 (looking-at "^[^ ]+")
9454 (match-string 0))))
9455 (org-store-link-props :type "help"))
9457 ((eq major-mode 'w3-mode)
9458 (setq cpltxt (if (and (buffer-name)
9459 (not (string-match "Untitled" (buffer-name))))
9460 (buffer-name)
9461 (url-view-url t))
9462 link (url-view-url t))
9463 (org-store-link-props :type "w3" :url (url-view-url t)))
9465 ((eq major-mode 'image-mode)
9466 (setq cpltxt (concat "file:"
9467 (abbreviate-file-name buffer-file-name))
9468 link cpltxt)
9469 (org-store-link-props :type "image" :file buffer-file-name))
9471 ;; In dired, store a link to the file of the current line
9472 ((derived-mode-p 'dired-mode)
9473 (let ((file (dired-get-filename nil t)))
9474 (setq file (if file
9475 (abbreviate-file-name
9476 (expand-file-name (dired-get-filename nil t)))
9477 ;; otherwise, no file so use current directory.
9478 default-directory))
9479 (setq cpltxt (concat "file:" file)
9480 link cpltxt)))
9482 ((setq search (run-hook-with-args-until-success
9483 'org-create-file-search-functions))
9484 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9485 "::" search))
9486 (setq cpltxt (or description link)))
9488 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9489 (org-with-limited-levels
9490 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9491 (cond
9492 ;; Store a link using the target at point
9493 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9494 (setq cpltxt
9495 (concat "file:"
9496 (abbreviate-file-name
9497 (buffer-file-name (buffer-base-buffer)))
9498 "::" (match-string 1))
9499 link cpltxt))
9500 ((and (featurep 'org-id)
9501 (or (eq org-id-link-to-org-use-id t)
9502 (and (called-interactively-p 'any)
9503 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9504 (and (eq org-id-link-to-org-use-id
9505 'create-if-interactive-and-no-custom-id)
9506 (not custom-id))))
9507 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9508 ;; Store a link using the ID at point
9509 (setq link (condition-case nil
9510 (prog1 (org-id-store-link)
9511 (setq desc (or (plist-get org-store-link-plist
9512 :description)
9513 "")))
9514 (error
9515 ;; Probably before first headline, link only to file
9516 (concat "file:"
9517 (abbreviate-file-name
9518 (buffer-file-name (buffer-base-buffer))))))))
9520 ;; Just link to current headline
9521 (setq cpltxt (concat "file:"
9522 (abbreviate-file-name
9523 (buffer-file-name (buffer-base-buffer)))))
9524 ;; Add a context search string
9525 (when (org-xor org-context-in-file-links
9526 (equal arg '(4)))
9527 (let* ((element (org-element-at-point))
9528 (name (org-element-property :name element)))
9529 (setq txt (cond
9530 ((org-at-heading-p) nil)
9531 (name)
9532 ((org-region-active-p)
9533 (buffer-substring (region-beginning) (region-end)))))
9534 (when (or (null txt) (string-match "\\S-" txt))
9535 (setq cpltxt
9536 (concat cpltxt "::"
9537 (condition-case nil
9538 (org-make-org-heading-search-string txt)
9539 (error "")))
9540 desc (or name
9541 (nth 4 (ignore-errors (org-heading-components)))
9542 "NONE")))))
9543 (when (string-match "::\\'" cpltxt)
9544 (setq cpltxt (substring cpltxt 0 -2)))
9545 (setq link cpltxt)))))
9547 ((buffer-file-name (buffer-base-buffer))
9548 ;; Just link to this file here.
9549 (setq cpltxt (concat "file:"
9550 (abbreviate-file-name
9551 (buffer-file-name (buffer-base-buffer)))))
9552 ;; Add a context string.
9553 (when (org-xor org-context-in-file-links
9554 (equal arg '(4)))
9555 (setq txt (if (org-region-active-p)
9556 (buffer-substring (region-beginning) (region-end))
9557 (buffer-substring (point-at-bol) (point-at-eol))))
9558 ;; Only use search option if there is some text.
9559 (when (string-match "\\S-" txt)
9560 (setq cpltxt
9561 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9562 desc "NONE")))
9563 (setq link cpltxt))
9565 ((called-interactively-p 'interactive)
9566 (user-error "No method for storing a link from this buffer"))
9568 (t (setq link nil)))
9570 ;; We're done setting link and desc, clean up
9571 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9572 (setq link (or link cpltxt)
9573 desc (or desc cpltxt))
9574 (cond ((not desc))
9575 ((equal desc "NONE") (setq desc nil))
9576 (t (setq desc
9577 (replace-regexp-in-string
9578 org-bracket-link-analytic-regexp
9579 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9580 desc))))
9581 ;; Return the link
9582 (if (not (and (or (called-interactively-p 'any)
9583 executing-kbd-macro)
9584 link))
9585 (or agenda-link (and link (org-make-link-string link desc)))
9586 (push (list link desc) org-stored-links)
9587 (message "Stored: %s" (or desc link))
9588 (when custom-id
9589 (setq link (concat "file:" (abbreviate-file-name
9590 (buffer-file-name)) "::#" custom-id))
9591 (push (list link desc) org-stored-links))
9592 (car org-stored-links)))))
9594 (defun org-store-link-props (&rest plist)
9595 "Store link properties.
9596 The properties are pre-processed by extracting names, addresses
9597 and dates."
9598 (let ((x (plist-get plist :from)))
9599 (when x
9600 (let ((adr (mail-extract-address-components x)))
9601 (setq plist (plist-put plist :fromname (car adr)))
9602 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9603 (let ((x (plist-get plist :to)))
9604 (when x
9605 (let ((adr (mail-extract-address-components x)))
9606 (setq plist (plist-put plist :toname (car adr)))
9607 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9608 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9609 (when x
9610 (setq plist (plist-put plist :date-timestamp
9611 (format-time-string
9612 (org-time-stamp-format t) x)))
9613 (setq plist (plist-put plist :date-timestamp-inactive
9614 (format-time-string
9615 (org-time-stamp-format t t) x)))))
9616 (let ((from (plist-get plist :from))
9617 (to (plist-get plist :to)))
9618 (when (and from to org-from-is-user-regexp)
9619 (setq plist
9620 (plist-put plist :fromto
9621 (if (string-match org-from-is-user-regexp from)
9622 (concat "to %t")
9623 (concat "from %f"))))))
9624 (setq org-store-link-plist plist))
9626 (defun org-add-link-props (&rest plist)
9627 "Add these properties to the link property list."
9628 (let (key value)
9629 (while plist
9630 (setq key (pop plist) value (pop plist))
9631 (setq org-store-link-plist
9632 (plist-put org-store-link-plist key value)))))
9634 (defun org-email-link-description (&optional fmt)
9635 "Return the description part of an email link.
9636 This takes information from `org-store-link-plist' and formats it
9637 according to FMT (default from `org-email-link-description-format')."
9638 (setq fmt (or fmt org-email-link-description-format))
9639 (let* ((p org-store-link-plist)
9640 (to (plist-get p :toaddress))
9641 (from (plist-get p :fromaddress))
9642 (table
9643 (list
9644 (cons "%c" (plist-get p :fromto))
9645 (cons "%F" (plist-get p :from))
9646 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9647 (cons "%T" (plist-get p :to))
9648 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9649 (cons "%s" (plist-get p :subject))
9650 (cons "%d" (plist-get p :date))
9651 (cons "%m" (plist-get p :message-id)))))
9652 (when (string-match "%c" fmt)
9653 ;; Check if the user wrote this message
9654 (if (and org-from-is-user-regexp from to
9655 (save-match-data (string-match org-from-is-user-regexp from)))
9656 (setq fmt (replace-match "to %t" t t fmt))
9657 (setq fmt (replace-match "from %f" t t fmt))))
9658 (org-replace-escapes fmt table)))
9660 (defun org-make-org-heading-search-string (&optional string)
9661 "Make search string for the current headline or STRING."
9662 (let ((s (or string
9663 (and (derived-mode-p 'org-mode)
9664 (save-excursion
9665 (org-back-to-heading t)
9666 (org-element-property :raw-value (org-element-at-point))))))
9667 (lines org-context-in-file-links))
9668 (unless string (setq s (concat "*" s))) ;Add * for headlines
9669 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9670 (when (and string (integerp lines) (> lines 0))
9671 (let ((slines (org-split-string s "\n")))
9672 (when (< lines (length slines))
9673 (setq s (mapconcat
9674 'identity
9675 (reverse (nthcdr (- (length slines) lines)
9676 (reverse slines))) "\n")))))
9677 (mapconcat #'identity (split-string s) " ")))
9679 (defun org-make-link-string (link &optional description)
9680 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9681 (unless (org-string-nw-p link) (error "Empty link"))
9682 (let ((uri (cond ((string-match org-link-types-re link)
9683 (concat (match-string 1 link)
9684 (org-link-escape (substring link (match-end 1)))))
9685 ;; For readability, url-encode internal links only
9686 ;; when absolutely needed (i.e, when they contain
9687 ;; square brackets). File links however, are
9688 ;; encoded since, e.g., spaces are significant.
9689 ((or (file-name-absolute-p link)
9690 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9691 (org-link-escape link))
9692 (t link)))
9693 (description
9694 (and (org-string-nw-p description)
9695 ;; Remove brackets from description, as they are fatal.
9696 (replace-regexp-in-string
9697 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9698 (org-trim description)))))
9699 (format "[[%s]%s]"
9701 (if description (format "[%s]" description) ""))))
9703 (defconst org-link-escape-chars
9704 ;;%20 %5B %5D %25
9705 '(?\s ?\[ ?\] ?%)
9706 "List of characters that should be escaped in a link when stored to Org.
9707 This is the list that is used for internal purposes.")
9709 (defun org-link-escape (text &optional table merge)
9710 "Return percent escaped representation of TEXT.
9711 TEXT is a string with the text to escape.
9712 Optional argument TABLE is a list with characters that should be
9713 escaped. When nil, `org-link-escape-chars' is used.
9714 If optional argument MERGE is set, merge TABLE into
9715 `org-link-escape-chars'."
9716 (let ((characters-to-encode
9717 (cond ((null table) org-link-escape-chars)
9718 (merge (append org-link-escape-chars table))
9719 (t table))))
9720 (mapconcat
9721 (lambda (c)
9722 (if (or (memq c characters-to-encode)
9723 (and org-url-hexify-p (or (< c 32) (> c 126))))
9724 (mapconcat (lambda (e) (format "%%%.2X" e))
9725 (or (encode-coding-char c 'utf-8)
9726 (error "Unable to percent escape character: %c" c))
9728 (char-to-string c)))
9729 text "")))
9731 (defun org-link-unescape (str)
9732 "Unhex hexified Unicode parts in string STR.
9733 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9734 reciprocal of `org-link-escape', which see."
9735 (if (org-string-nw-p str)
9736 (replace-regexp-in-string
9737 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9738 str))
9740 (defun org-link-unescape-compound (hex)
9741 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9742 Note: this function also decodes single byte encodings like
9743 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9744 (save-match-data
9745 (let* ((bytes (cdr (split-string hex "%")))
9746 (ret "")
9747 (eat 0)
9748 (sum 0))
9749 (while bytes
9750 (let* ((val (string-to-number (pop bytes) 16))
9751 (shift-xor
9752 (if (= 0 eat)
9753 (cond
9754 ((>= val 252) (cons 6 252))
9755 ((>= val 248) (cons 5 248))
9756 ((>= val 240) (cons 4 240))
9757 ((>= val 224) (cons 3 224))
9758 ((>= val 192) (cons 2 192))
9759 (t (cons 0 0)))
9760 (cons 6 128))))
9761 (when (>= val 192) (setq eat (car shift-xor)))
9762 (setq val (logxor val (cdr shift-xor)))
9763 (setq sum (+ (lsh sum (car shift-xor)) val))
9764 (when (> eat 0) (setq eat (- eat 1)))
9765 (cond
9766 ((= 0 eat) ;multi byte
9767 (setq ret (concat ret (char-to-string sum)))
9768 (setq sum 0))
9769 ((not bytes) ; single byte(s)
9770 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9771 ret)))
9773 (defun org-link-unescape-single-byte-sequence (hex)
9774 "Unhexify hex-encoded single byte character sequences."
9775 (mapconcat (lambda (byte)
9776 (char-to-string (string-to-number byte 16)))
9777 (cdr (split-string hex "%")) ""))
9779 (defun org-fixup-message-id-for-http (s)
9780 "Replace special characters in a message id, so it can be used in an http query."
9781 (when (string-match "%" s)
9782 (setq s (mapconcat (lambda (c)
9783 (if (eq c ?%)
9784 "%25"
9785 (char-to-string c)))
9786 s "")))
9787 (while (string-match "<" s)
9788 (setq s (replace-match "%3C" t t s)))
9789 (while (string-match ">" s)
9790 (setq s (replace-match "%3E" t t s)))
9791 (while (string-match "@" s)
9792 (setq s (replace-match "%40" t t s)))
9795 (defun org-link-prettify (link)
9796 "Return a human-readable representation of LINK.
9797 The car of LINK must be a raw link.
9798 The cdr of LINK must be either a link description or nil."
9799 (let ((desc (or (cadr link) "<no description>")))
9800 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9801 "<" (car link) ">")))
9803 ;;;###autoload
9804 (defun org-insert-link-global ()
9805 "Insert a link like Org mode does.
9806 This command can be called in any mode to insert a link in Org syntax."
9807 (interactive)
9808 (org-load-modules-maybe)
9809 (org-run-like-in-org-mode 'org-insert-link))
9811 (defun org-insert-all-links (arg &optional pre post)
9812 "Insert all links in `org-stored-links'.
9813 When a universal prefix, do not delete the links from `org-stored-links'.
9814 When `ARG' is a number, insert the last N link(s).
9815 `PRE' and `POST' are optional arguments to define a string to
9816 prepend or to append."
9817 (interactive "P")
9818 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9819 (links (copy-sequence org-stored-links))
9820 (pr (or pre "- "))
9821 (po (or post "\n"))
9822 (cnt 1) l)
9823 (if (null org-stored-links)
9824 (message "No link to insert")
9825 (while (and (or (listp arg) (>= arg cnt))
9826 (setq l (if (listp arg)
9827 (pop links)
9828 (pop org-stored-links))))
9829 (setq cnt (1+ cnt))
9830 (insert pr)
9831 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9832 (insert po)))))
9834 (defun org-insert-last-stored-link (arg)
9835 "Insert the last link stored in `org-stored-links'."
9836 (interactive "p")
9837 (org-insert-all-links arg "" "\n"))
9839 (defun org-link-fontify-links-to-this-file ()
9840 "Fontify links to the current file in `org-stored-links'."
9841 (let ((f (buffer-file-name)) a b)
9842 (setq a (mapcar (lambda(l)
9843 (let ((ll (car l)))
9844 (when (and (string-match "^file:\\(.+\\)::" ll)
9845 (equal f (expand-file-name (match-string 1 ll))))
9846 ll)))
9847 org-stored-links))
9848 (when (featurep 'org-id)
9849 (setq b (mapcar (lambda(l)
9850 (let ((ll (car l)))
9851 (when (and (string-match "^id:\\(.+\\)$" ll)
9852 (equal f (expand-file-name
9853 (or (org-id-find-id-file
9854 (match-string 1 ll)) ""))))
9855 ll)))
9856 org-stored-links)))
9857 (mapcar (lambda(l)
9858 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9859 (delq nil (append a b)))))
9861 (defvar org--links-history nil)
9862 (defun org-insert-link (&optional complete-file link-location default-description)
9863 "Insert a link. At the prompt, enter the link.
9865 Completion can be used to insert any of the link protocol prefixes in use.
9867 The history can be used to select a link previously stored with
9868 `org-store-link'. When the empty string is entered (i.e. if you just
9869 press `RET' at the prompt), the link defaults to the most recently
9870 stored link. As `SPC' triggers completion in the minibuffer, you need to
9871 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9873 You will also be prompted for a description, and if one is given, it will
9874 be displayed in the buffer instead of the link.
9876 If there is already a link at point, this command will allow you to edit
9877 link and description parts.
9879 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9880 file name can be
9881 selected using completion. The path to the file will be relative to the
9882 current directory if the file is in the current directory or a subdirectory.
9883 Otherwise, the link will be the absolute path as completed in the minibuffer
9884 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9885 option `org-link-file-path-type'.
9887 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9888 absolute path even if the file is in
9889 the current directory or below.
9891 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9892 prefix negates `org-keep-stored-link-after-insertion'.
9894 If the LINK-LOCATION parameter is non-nil, this value will be used as
9895 the link location instead of reading one interactively.
9897 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9898 be used as the default description. Otherwise, if
9899 `org-make-link-description-function' is non-nil, this function
9900 will be called with the link target, and the result will be the
9901 default link description."
9902 (interactive "P")
9903 (let* ((wcf (current-window-configuration))
9904 (origbuf (current-buffer))
9905 (region (when (org-region-active-p)
9906 (buffer-substring (region-beginning) (region-end))))
9907 (remove (and region (list (region-beginning) (region-end))))
9908 (desc region)
9909 (link link-location)
9910 (abbrevs org-link-abbrev-alist-local)
9911 entry all-prefixes auto-desc)
9912 (cond
9913 (link-location) ; specified by arg, just use it.
9914 ((org-in-regexp org-bracket-link-regexp 1)
9915 ;; We do have a link at point, and we are going to edit it.
9916 (setq remove (list (match-beginning 0) (match-end 0)))
9917 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9918 (setq link (read-string "Link: "
9919 (org-link-unescape
9920 (match-string-no-properties 1)))))
9921 ((or (org-in-regexp org-angle-link-re)
9922 (org-in-regexp org-plain-link-re))
9923 ;; Convert to bracket link
9924 (setq remove (list (match-beginning 0) (match-end 0))
9925 link (read-string "Link: "
9926 (org-unbracket-string "<" ">" (match-string 0)))))
9927 ((member complete-file '((4) (16)))
9928 ;; Completing read for file names.
9929 (setq link (org-file-complete-link complete-file)))
9931 ;; Read link, with completion for stored links.
9932 (org-link-fontify-links-to-this-file)
9933 (org-switch-to-buffer-other-window "*Org Links*")
9934 (with-current-buffer "*Org Links*"
9935 (erase-buffer)
9936 (insert "Insert a link.
9937 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9938 (when org-stored-links
9939 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9940 (insert (mapconcat 'org-link-prettify
9941 (reverse org-stored-links) "\n")))
9942 (goto-char (point-min)))
9943 (let ((cw (selected-window)))
9944 (select-window (get-buffer-window "*Org Links*" 'visible))
9945 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9946 (unless (pos-visible-in-window-p (point-max))
9947 (org-fit-window-to-buffer))
9948 (and (window-live-p cw) (select-window cw)))
9949 (setq all-prefixes (append (mapcar 'car abbrevs)
9950 (mapcar 'car org-link-abbrev-alist)
9951 (org-link-types)))
9952 (unwind-protect
9953 ;; Fake a link history, containing the stored links.
9954 (let ((org--links-history
9955 (append (mapcar #'car org-stored-links)
9956 org-insert-link-history)))
9957 (setq link
9958 (org-completing-read
9959 "Link: "
9960 (append
9961 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9962 (mapcar #'car org-stored-links))
9963 nil nil nil
9964 'org--links-history
9965 (caar org-stored-links)))
9966 (unless (org-string-nw-p link) (user-error "No link selected"))
9967 (dolist (l org-stored-links)
9968 (when (equal link (cadr l))
9969 (setq link (car l))
9970 (setq auto-desc t)))
9971 (when (or (member link all-prefixes)
9972 (and (equal ":" (substring link -1))
9973 (member (substring link 0 -1) all-prefixes)
9974 (setq link (substring link 0 -1))))
9975 (setq link (with-current-buffer origbuf
9976 (org-link-try-special-completion link)))))
9977 (set-window-configuration wcf)
9978 (kill-buffer "*Org Links*"))
9979 (setq entry (assoc link org-stored-links))
9980 (or entry (push link org-insert-link-history))
9981 (setq desc (or desc (nth 1 entry)))))
9983 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9984 (not org-keep-stored-link-after-insertion))
9985 (setq org-stored-links (delq (assoc link org-stored-links)
9986 org-stored-links)))
9988 (when (and (string-match org-plain-link-re link)
9989 (not (string-match org-ts-regexp link)))
9990 ;; URL-like link, normalize the use of angular brackets.
9991 (setq link (org-unbracket-string "<" ">" link)))
9993 ;; Check if we are linking to the current file with a search
9994 ;; option If yes, simplify the link by using only the search
9995 ;; option.
9996 (when (and buffer-file-name
9997 (let ((case-fold-search nil))
9998 (string-match "\\`file:\\(.+?\\)::" link)))
9999 (let ((path (match-string-no-properties 1 link))
10000 (search (substring-no-properties link (match-end 0))))
10001 (save-match-data
10002 (when (equal (file-truename buffer-file-name) (file-truename path))
10003 ;; We are linking to this same file, with a search option
10004 (setq link search)))))
10006 ;; Check if we can/should use a relative path. If yes, simplify the link
10007 (let ((case-fold-search nil))
10008 (when (string-match "\\`\\(file\\|docview\\):" link)
10009 (let* ((type (match-string-no-properties 0 link))
10010 (path (substring-no-properties link (match-end 0)))
10011 (origpath path))
10012 (cond
10013 ((or (eq org-link-file-path-type 'absolute)
10014 (equal complete-file '(16)))
10015 (setq path (abbreviate-file-name (expand-file-name path))))
10016 ((eq org-link-file-path-type 'noabbrev)
10017 (setq path (expand-file-name path)))
10018 ((eq org-link-file-path-type 'relative)
10019 (setq path (file-relative-name path)))
10021 (save-match-data
10022 (if (string-match (concat "^" (regexp-quote
10023 (expand-file-name
10024 (file-name-as-directory
10025 default-directory))))
10026 (expand-file-name path))
10027 ;; We are linking a file with relative path name.
10028 (setq path (substring (expand-file-name path)
10029 (match-end 0)))
10030 (setq path (abbreviate-file-name (expand-file-name path)))))))
10031 (setq link (concat type path))
10032 (when (equal desc origpath)
10033 (setq desc path)))))
10035 (unless auto-desc
10036 (let ((initial-input
10037 (cond
10038 (default-description)
10039 ((not org-make-link-description-function) desc)
10040 (t (condition-case nil
10041 (funcall org-make-link-description-function link desc)
10042 (error
10043 (message "Can't get link description from `%s'"
10044 (symbol-name org-make-link-description-function))
10045 (sit-for 2)
10046 nil))))))
10047 (setq desc (read-string "Description: " initial-input))))
10049 (unless (string-match "\\S-" desc) (setq desc nil))
10050 (when remove (apply 'delete-region remove))
10051 (insert (org-make-link-string link desc))
10052 ;; Redisplay so as the new link has proper invisible characters.
10053 (sit-for 0)))
10055 (defun org-link-try-special-completion (type)
10056 "If there is completion support for link type TYPE, offer it."
10057 (let ((fun (org-link-get-parameter type :complete)))
10058 (if (functionp fun)
10059 (funcall fun)
10060 (read-string "Link (no completion support): " (concat type ":")))))
10062 (defun org-file-complete-link (&optional arg)
10063 "Create a file link using completion."
10064 (let ((file (read-file-name "File: "))
10065 (pwd (file-name-as-directory (expand-file-name ".")))
10066 (pwd1 (file-name-as-directory (abbreviate-file-name
10067 (expand-file-name ".")))))
10068 (cond ((equal arg '(16))
10069 (concat "file:"
10070 (abbreviate-file-name (expand-file-name file))))
10071 ((string-match
10072 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10073 (concat "file:" (match-string 1 file)))
10074 ((string-match
10075 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10076 (expand-file-name file))
10077 (concat "file:"
10078 (match-string 1 (expand-file-name file))))
10079 (t (concat "file:" file)))))
10082 ;;; Opening/following a link
10084 (defvar org-link-search-failed nil)
10086 (defvar org-open-link-functions nil
10087 "Hook for functions finding a plain text link.
10088 These functions must take a single argument, the link content.
10089 They will be called for links that look like [[link text][description]]
10090 when LINK TEXT does not have a protocol like \"http:\" and does not look
10091 like a filename (e.g. \"./blue.png\").
10093 These functions will be called *before* Org attempts to resolve the
10094 link by doing text searches in the current buffer - so if you want a
10095 link \"[[target]]\" to still find \"<<target>>\", your function should
10096 handle this as a special case.
10098 When the function does handle the link, it must return a non-nil value.
10099 If it decides that it is not responsible for this link, it must return
10100 nil to indicate that that Org can continue with other options like
10101 exact and fuzzy text search.")
10103 (defun org-next-link (&optional search-backward)
10104 "Move forward to the next link.
10105 If the link is in hidden text, expose it."
10106 (interactive "P")
10107 (when (and org-link-search-failed (eq this-command last-command))
10108 (goto-char (point-min))
10109 (message "Link search wrapped back to beginning of buffer"))
10110 (setq org-link-search-failed nil)
10111 (let* ((pos (point))
10112 (ct (org-context))
10113 (a (assq :link ct))
10114 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10115 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10116 ((looking-at org-any-link-re)
10117 ;; Don't stay stuck at link without an org-link face
10118 (forward-char (if search-backward -1 1))))
10119 (if (funcall srch-fun org-any-link-re nil t)
10120 (progn
10121 (goto-char (match-beginning 0))
10122 (when (org-invisible-p) (org-show-context)))
10123 (goto-char pos)
10124 (setq org-link-search-failed t)
10125 (message "No further link found"))))
10127 (defun org-previous-link ()
10128 "Move backward to the previous link.
10129 If the link is in hidden text, expose it."
10130 (interactive)
10131 (funcall 'org-next-link t))
10133 (defun org-translate-link (s)
10134 "Translate a link string if a translation function has been defined."
10135 (with-temp-buffer
10136 (insert (org-trim s))
10137 (org-trim (org-element-interpret-data (org-element-context)))))
10139 (defun org-translate-link-from-planner (type path)
10140 "Translate a link from Emacs Planner syntax so that Org can follow it.
10141 This is still an experimental function, your mileage may vary."
10142 (cond
10143 ((member type '("http" "https" "news" "ftp"))
10144 ;; standard Internet links are the same.
10145 nil)
10146 ((and (equal type "irc") (string-match "^//" path))
10147 ;; Planner has two / at the beginning of an irc link, we have 1.
10148 ;; We should have zero, actually....
10149 (setq path (substring path 1)))
10150 ((and (equal type "lisp") (string-match "^/" path))
10151 ;; Planner has a slash, we do not.
10152 (setq type "elisp" path (substring path 1)))
10153 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10154 ;; A typical message link. Planner has the id after the final slash,
10155 ;; we separate it with a hash mark
10156 (setq path (concat (match-string 1 path) "#"
10157 (org-unbracket-string "<" ">" (match-string 2 path))))))
10158 (cons type path))
10160 (defun org-find-file-at-mouse (ev)
10161 "Open file link or URL at mouse."
10162 (interactive "e")
10163 (mouse-set-point ev)
10164 (org-open-at-point 'in-emacs))
10166 (defun org-open-at-mouse (ev)
10167 "Open file link or URL at mouse.
10168 See the docstring of `org-open-file' for details."
10169 (interactive "e")
10170 (mouse-set-point ev)
10171 (when (eq major-mode 'org-agenda-mode)
10172 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10173 (org-open-at-point))
10175 (defvar org-window-config-before-follow-link nil
10176 "The window configuration before following a link.
10177 This is saved in case the need arises to restore it.")
10179 ;;;###autoload
10180 (defun org-open-at-point-global ()
10181 "Follow a link or time-stamp like Org mode does.
10182 This command can be called in any mode to follow an external link
10183 or a time-stamp that has Org mode syntax. Its behavior is
10184 undefined when called on internal links (e.g., fuzzy links).
10185 Raise an error when there is nothing to follow. "
10186 (interactive)
10187 (cond ((org-in-regexp org-any-link-re)
10188 (org-open-link-from-string (match-string-no-properties 0)))
10189 ((or (org-in-regexp org-ts-regexp-both nil t)
10190 (org-in-regexp org-tsr-regexp-both nil t))
10191 (org-follow-timestamp-link))
10192 (t (user-error "No link found"))))
10194 ;;;###autoload
10195 (defun org-open-link-from-string (s &optional arg reference-buffer)
10196 "Open a link in the string S, as if it was in Org mode."
10197 (interactive "sLink: \nP")
10198 (let ((reference-buffer (or reference-buffer (current-buffer))))
10199 (with-temp-buffer
10200 (let ((org-inhibit-startup (not reference-buffer)))
10201 (org-mode)
10202 (insert s)
10203 (goto-char (point-min))
10204 (when reference-buffer
10205 (setq org-link-abbrev-alist-local
10206 (with-current-buffer reference-buffer
10207 org-link-abbrev-alist-local)))
10208 (org-open-at-point arg reference-buffer)))))
10210 (defvar org-open-at-point-functions nil
10211 "Hook that is run when following a link at point.
10213 Functions in this hook must return t if they identify and follow
10214 a link at point. If they don't find anything interesting at point,
10215 they must return nil.")
10217 (defvar org-link-search-inhibit-query nil)
10218 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10219 (defun org--open-doi-link (path)
10220 "Open a \"doi\" type link.
10221 PATH is a the path to search for, as a string."
10222 (browse-url (url-encode-url (concat org-doi-server-url path))))
10224 (defun org--open-elisp-link (path)
10225 "Open a \"elisp\" type link.
10226 PATH is the sexp to evaluate, as a string."
10227 (let ((cmd path))
10228 (if (or (and (org-string-nw-p
10229 org-confirm-elisp-link-not-regexp)
10230 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10231 (not org-confirm-elisp-link-function)
10232 (funcall org-confirm-elisp-link-function
10233 (format "Execute \"%s\" as elisp? "
10234 (org-add-props cmd nil 'face 'org-warning))))
10235 (message "%s => %s" cmd
10236 (if (eq (string-to-char cmd) ?\()
10237 (eval (read cmd))
10238 (call-interactively (read cmd))))
10239 (user-error "Abort"))))
10241 (defun org--open-help-link (path)
10242 "Open a \"help\" type link.
10243 PATH is a symbol name, as a string."
10244 (pcase (intern path)
10245 ((and (pred fboundp) variable) (describe-function variable))
10246 ((and (pred boundp) function) (describe-variable function))
10247 (name (user-error "Unknown function or variable: %s" name))))
10249 (defun org--open-shell-link (path)
10250 "Open a \"shell\" type link.
10251 PATH is the command to execute, as a string."
10252 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10253 (cmd path))
10254 (if (or (and (org-string-nw-p
10255 org-confirm-shell-link-not-regexp)
10256 (string-match
10257 org-confirm-shell-link-not-regexp cmd))
10258 (not org-confirm-shell-link-function)
10259 (funcall org-confirm-shell-link-function
10260 (format "Execute \"%s\" in shell? "
10261 (org-add-props cmd nil
10262 'face 'org-warning))))
10263 (progn
10264 (message "Executing %s" cmd)
10265 (shell-command cmd buf)
10266 (when (featurep 'midnight)
10267 (setq clean-buffer-list-kill-buffer-names
10268 (cons (buffer-name buf)
10269 clean-buffer-list-kill-buffer-names))))
10270 (user-error "Abort"))))
10272 (defun org-open-at-point (&optional arg reference-buffer)
10273 "Open link, timestamp, footnote or tags at point.
10275 When point is on a link, follow it. Normally, files will be
10276 opened by an appropriate application. If the optional prefix
10277 argument ARG is non-nil, Emacs will visit the file. With
10278 a double prefix argument, try to open outside of Emacs, in the
10279 application the system uses for this file type.
10281 When point is on a timestamp, open the agenda at the day
10282 specified.
10284 When point is a footnote definition, move to the first reference
10285 found. If it is on a reference, move to the associated
10286 definition.
10288 When point is on a headline, display a list of every link in the
10289 entry, so it is possible to pick one, or all, of them. If point
10290 is on a tag, call `org-tags-view' instead.
10292 When optional argument REFERENCE-BUFFER is non-nil, it should
10293 specify a buffer from where the link search should happen. This
10294 is used internally by `org-open-link-from-string'.
10296 On top of syntactically correct links, this function will also
10297 try to open links and time-stamps in comments, example
10298 blocks... i.e., whenever point is on something looking like
10299 a timestamp or a link."
10300 (interactive "P")
10301 ;; On a code block, open block's results.
10302 (unless (call-interactively 'org-babel-open-src-block-result)
10303 (org-load-modules-maybe)
10304 (setq org-window-config-before-follow-link (current-window-configuration))
10305 (org-remove-occur-highlights nil nil t)
10306 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10307 (let* ((context
10308 ;; Only consider supported types, even if they are not
10309 ;; the closest one.
10310 (org-element-lineage
10311 (org-element-context)
10312 '(clock footnote-definition footnote-reference headline
10313 inlinetask link timestamp)
10315 (type (org-element-type context))
10316 (value (org-element-property :value context)))
10317 (cond
10318 ;; On a headline or an inlinetask, but not on a timestamp,
10319 ;; a link, a footnote reference.
10320 ((memq type '(headline inlinetask))
10321 (org-match-line org-complex-heading-regexp)
10322 (if (and (match-beginning 5)
10323 (>= (point) (match-beginning 5))
10324 (< (point) (match-end 5)))
10325 ;; On tags.
10326 (org-tags-view arg (substring (match-string 5) 0 -1))
10327 ;; Not on tags.
10328 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10329 (`(nil . ,_)
10330 (require 'org-attach)
10331 (org-attach-reveal 'if-exists))
10332 (`(,links . ,links-end)
10333 (dolist (link (if (stringp links) (list links) links))
10334 (search-forward link nil links-end)
10335 (goto-char (match-beginning 0))
10336 (org-open-at-point))))))
10337 ;; On a footnote reference or at definition's label.
10338 ((or (eq type 'footnote-reference)
10339 (and (eq type 'footnote-definition)
10340 (save-excursion
10341 ;; Do not validate action when point is on the
10342 ;; spaces right after the footnote label, in
10343 ;; order to be on par with behaviour on links.
10344 (skip-chars-forward " \t")
10345 (let ((begin
10346 (org-element-property :contents-begin context)))
10347 (if begin (< (point) begin)
10348 (= (org-element-property :post-affiliated context)
10349 (line-beginning-position)))))))
10350 (org-footnote-action))
10351 ;; No valid context. Ignore catch-all types like `headline'.
10352 ;; If point is on something looking like a link or
10353 ;; a time-stamp, try opening it. It may be useful in
10354 ;; comments, example blocks...
10355 ((memq type '(footnote-definition headline inlinetask nil))
10356 (call-interactively #'org-open-at-point-global))
10357 ;; On a clock line, make sure point is on the timestamp
10358 ;; before opening it.
10359 ((and (eq type 'clock)
10360 value
10361 (>= (point) (org-element-property :begin value))
10362 (<= (point) (org-element-property :end value)))
10363 (org-follow-timestamp-link))
10364 ;; Do nothing on white spaces after an object.
10365 ((>= (point)
10366 (save-excursion
10367 (goto-char (org-element-property :end context))
10368 (skip-chars-backward " \t")
10369 (point)))
10370 (user-error "No link found"))
10371 ((eq type 'timestamp) (org-follow-timestamp-link))
10372 ((eq type 'link)
10373 (let ((type (org-element-property :type context))
10374 (path (org-link-unescape (org-element-property :path context))))
10375 ;; Switch back to REFERENCE-BUFFER needed when called in
10376 ;; a temporary buffer through `org-open-link-from-string'.
10377 (with-current-buffer (or reference-buffer (current-buffer))
10378 (cond
10379 ((equal type "file")
10380 (if (string-match "[*?{]" (file-name-nondirectory path))
10381 (dired path)
10382 ;; Look into `org-link-parameters' in order to find
10383 ;; a DEDICATED-FUNCTION to open file. The function
10384 ;; will be applied on raw link instead of parsed
10385 ;; link due to the limitation in `org-add-link-type'
10386 ;; ("open" function called with a single argument).
10387 ;; If no such function is found, fallback to
10388 ;; `org-open-file'.
10389 (let* ((option (org-element-property :search-option context))
10390 (app (org-element-property :application context))
10391 (dedicated-function
10392 (org-link-get-parameter
10393 (if app (concat type "+" app) type)
10394 :follow)))
10395 (if dedicated-function
10396 (funcall dedicated-function
10397 (concat path
10398 (and option (concat "::" option))))
10399 (apply #'org-open-file
10400 path
10401 (cond (arg)
10402 ((equal app "emacs") 'emacs)
10403 ((equal app "sys") 'system))
10404 (cond ((not option) nil)
10405 ((string-match-p "\\`[0-9]+\\'" option)
10406 (list (string-to-number option)))
10407 (t (list nil
10408 (org-link-unescape option)))))))))
10409 ((functionp (org-link-get-parameter type :follow))
10410 (funcall (org-link-get-parameter type :follow) path))
10411 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10412 (unless (run-hook-with-args-until-success
10413 'org-open-link-functions path)
10414 (if (not arg) (org-mark-ring-push)
10415 (switch-to-buffer-other-window
10416 (org-get-buffer-for-internal-link (current-buffer))))
10417 (let ((destination
10418 (org-with-wide-buffer
10419 (if (equal type "radio")
10420 (org-search-radio-target
10421 (org-element-property :path context))
10422 (org-link-search
10423 (if (member type '("custom-id" "coderef"))
10424 (org-element-property :raw-link context)
10425 path)
10426 ;; Prevent fuzzy links from matching
10427 ;; themselves.
10428 (and (equal type "fuzzy")
10429 (+ 2 (org-element-property :begin context)))))
10430 (point))))
10431 (unless (and (<= (point-min) destination)
10432 (>= (point-max) destination))
10433 (widen))
10434 (goto-char destination))))
10435 (t (browse-url-at-point))))))
10436 (t (user-error "No link found")))))
10437 (run-hook-with-args 'org-follow-link-hook)))
10439 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10440 "Offer links in the current entry and return the selected link.
10441 If there is only one link, return it.
10442 If NTH is an integer, return the NTH link found.
10443 If ZERO is a string, check also this string for a link, and if
10444 there is one, return it."
10445 (with-current-buffer buffer
10446 (org-with-wide-buffer
10447 (goto-char marker)
10448 (let ((cnt ?0)
10449 have-zero end links link c)
10450 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10451 (push (match-string 0 zero) links)
10452 (setq cnt (1- cnt) have-zero t))
10453 (save-excursion
10454 (org-back-to-heading t)
10455 (setq end (save-excursion (outline-next-heading) (point)))
10456 (while (re-search-forward org-any-link-re end t)
10457 (push (match-string 0) links))
10458 (setq links (org-uniquify (reverse links))))
10459 (cond
10460 ((null links)
10461 (message "No links"))
10462 ((equal (length links) 1)
10463 (setq link (car links)))
10464 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10465 (setq link (nth (if have-zero nth (1- nth)) links)))
10466 (t ; we have to select a link
10467 (save-excursion
10468 (save-window-excursion
10469 (delete-other-windows)
10470 (with-output-to-temp-buffer "*Select Link*"
10471 (dolist (l links)
10472 (cond
10473 ((not (string-match org-bracket-link-regexp l))
10474 (princ (format "[%c] %s\n" (cl-incf cnt)
10475 (org-unbracket-string "<" ">" l))))
10476 ((match-end 3)
10477 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10478 (match-string 3 l) (match-string 1 l))))
10479 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10480 (match-string 1 l)))))))
10481 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10482 (message "Select link to open, RET to open all:")
10483 (setq c (read-char-exclusive))
10484 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10485 (when (equal c ?q) (user-error "Abort"))
10486 (if (equal c ?\C-m)
10487 (setq link links)
10488 (setq nth (- c ?0))
10489 (when have-zero (setq nth (1+ nth)))
10490 (unless (and (integerp nth) (>= (length links) nth))
10491 (user-error "Invalid link selection"))
10492 (setq link (nth (1- nth) links)))))
10493 (cons link end)))))
10495 ;; TODO: These functions are deprecated since `org-open-at-point'
10496 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10497 (defun org-open-file-with-system (path)
10498 "Open file at PATH using the system way of opening it."
10499 (org-open-file path 'system))
10500 (defun org-open-file-with-emacs (path)
10501 "Open file at PATH in Emacs."
10502 (org-open-file path 'emacs))
10505 ;;; File search
10507 (defvar org-create-file-search-functions nil
10508 "List of functions to construct the right search string for a file link.
10509 These functions are called in turn with point at the location to
10510 which the link should point.
10512 A function in the hook should first test if it would like to
10513 handle this file type, for example by checking the `major-mode'
10514 or the file extension. If it decides not to handle this file, it
10515 should just return nil to give other functions a chance. If it
10516 does handle the file, it must return the search string to be used
10517 when following the link. The search string will be part of the
10518 file link, given after a double colon, and `org-open-at-point'
10519 will automatically search for it. If special measures must be
10520 taken to make the search successful, another function should be
10521 added to the companion hook `org-execute-file-search-functions',
10522 which see.
10524 A function in this hook may also use `setq' to set the variable
10525 `description' to provide a suggestion for the descriptive text to
10526 be used for this link when it gets inserted into an Org buffer
10527 with \\[org-insert-link].")
10529 (defvar org-execute-file-search-functions nil
10530 "List of functions to execute a file search triggered by a link.
10532 Functions added to this hook must accept a single argument, the
10533 search string that was part of the file link, the part after the
10534 double colon. The function must first check if it would like to
10535 handle this search, for example by checking the `major-mode' or
10536 the file extension. If it decides not to handle this search, it
10537 should just return nil to give other functions a chance. If it
10538 does handle the search, it must return a non-nil value to keep
10539 other functions from trying.
10541 Each function can access the current prefix argument through the
10542 variable `current-prefix-arg'. Note that a single prefix is used
10543 to force opening a link in Emacs, so it may be good to only use a
10544 numeric or double prefix to guide the search function.
10546 In case this is needed, a function in this hook can also restore
10547 the window configuration before `org-open-at-point' was called using:
10549 (set-window-configuration org-window-config-before-follow-link)")
10551 (defun org-search-radio-target (target)
10552 "Search a radio target matching TARGET in current buffer.
10553 White spaces are not significant."
10554 (let ((re (format "<<<%s>>>"
10555 (mapconcat #'regexp-quote
10556 (split-string target)
10557 "[ \t]+\\(?:\n[ \t]*\\)?")))
10558 (origin (point)))
10559 (goto-char (point-min))
10560 (catch :radio-match
10561 (while (re-search-forward re nil t)
10562 (backward-char)
10563 (let ((object (org-element-context)))
10564 (when (eq (org-element-type object) 'radio-target)
10565 (goto-char (org-element-property :begin object))
10566 (org-show-context 'link-search)
10567 (throw :radio-match nil))))
10568 (goto-char origin)
10569 (user-error "No match for radio target: %s" target))))
10571 (defun org-link-search (s &optional avoid-pos stealth)
10572 "Search for a search string S.
10574 If S starts with \"#\", it triggers a custom ID search.
10576 If S is enclosed within parenthesis, it initiates a coderef
10577 search.
10579 If S is surrounded by forward slashes, it is interpreted as
10580 a regular expression. In Org mode files, this will create an
10581 `org-occur' sparse tree. In ordinary files, `occur' will be used
10582 to list matches. If the current buffer is in `dired-mode', grep
10583 will be used to search in all files.
10585 When AVOID-POS is given, ignore matches near that position.
10587 When optional argument STEALTH is non-nil, do not modify
10588 visibility around point, thus ignoring `org-show-context-detail'
10589 variable.
10591 Search is case-insensitive and ignores white spaces. Return type
10592 of matched result, which is either `dedicated' or `fuzzy'."
10593 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10594 (let* ((case-fold-search t)
10595 (origin (point))
10596 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10597 (starred (eq (string-to-char normalized) ?*))
10598 (words (split-string (if starred (substring s 1) s)))
10599 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10600 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10601 type)
10602 (cond
10603 ;; Check if there are any special search functions.
10604 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10605 ((eq (string-to-char s) ?#)
10606 ;; Look for a custom ID S if S starts with "#".
10607 (let* ((id (substring normalized 1))
10608 (match (org-find-property "CUSTOM_ID" id)))
10609 (if match (progn (goto-char match) (setf type 'dedicated))
10610 (error "No match for custom ID: %s" id))))
10611 ((string-match "\\`(\\(.*\\))\\'" normalized)
10612 ;; Look for coderef targets if S is enclosed within parenthesis.
10613 (let ((coderef (match-string-no-properties 1 normalized))
10614 (re (substring s-single-re 1 -1)))
10615 (goto-char (point-min))
10616 (catch :coderef-match
10617 (while (re-search-forward re nil t)
10618 (let ((element (org-element-at-point)))
10619 (when (and (memq (org-element-type element)
10620 '(example-block src-block))
10621 ;; Build proper regexp according to current
10622 ;; block's label format.
10623 (let ((label-fmt
10624 (regexp-quote
10625 (or (org-element-property :label-fmt element)
10626 org-coderef-label-format))))
10627 (save-excursion
10628 (beginning-of-line)
10629 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10630 (format label-fmt coderef))))))
10631 (setq type 'dedicated)
10632 (goto-char (match-beginning 1))
10633 (throw :coderef-match nil))))
10634 (goto-char origin)
10635 (error "No match for coderef: %s" coderef))))
10636 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10637 ;; Look for a regular expression.
10638 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10639 (match-string 1 s)))
10640 ;; From here, we handle fuzzy links.
10642 ;; Look for targets, only if not in a headline search.
10643 ((and (not starred)
10644 (let ((target (format "<<%s>>" s-multi-re)))
10645 (catch :target-match
10646 (goto-char (point-min))
10647 (while (re-search-forward target nil t)
10648 (backward-char)
10649 (let ((context (org-element-context)))
10650 (when (eq (org-element-type context) 'target)
10651 (setq type 'dedicated)
10652 (goto-char (org-element-property :begin context))
10653 (throw :target-match t))))
10654 nil))))
10655 ;; Look for elements named after S, only if not in a headline
10656 ;; search.
10657 ((and (not starred)
10658 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10659 (catch :name-match
10660 (goto-char (point-min))
10661 (while (re-search-forward name nil t)
10662 (let ((element (org-element-at-point)))
10663 (when (equal words
10664 (split-string
10665 (org-element-property :name element)))
10666 (setq type 'dedicated)
10667 (beginning-of-line)
10668 (throw :name-match t))))
10669 nil))))
10670 ;; Regular text search. Prefer headlines in Org mode buffers.
10671 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10672 ;; statistics cookies and tags.
10673 ((and (derived-mode-p 'org-mode)
10674 (let ((title-re
10675 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10676 org-outline-regexp-bol
10677 org-comment-string
10678 (mapconcat #'regexp-quote words ".+")))
10679 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10680 (comment-re (eval-when-compile
10681 (format "\\`%s[ \t]+" org-comment-string))))
10682 (goto-char (point-min))
10683 (catch :found
10684 (while (re-search-forward title-re nil t)
10685 (when (equal words
10686 (split-string
10687 (replace-regexp-in-string
10688 cookie-re ""
10689 (replace-regexp-in-string
10690 comment-re "" (org-get-heading t t t)))))
10691 (throw :found t)))
10692 nil)))
10693 (beginning-of-line)
10694 (setq type 'dedicated))
10695 ;; Offer to create non-existent headline depending on
10696 ;; `org-link-search-must-match-exact-headline'.
10697 ((and (derived-mode-p 'org-mode)
10698 (not org-link-search-inhibit-query)
10699 (eq org-link-search-must-match-exact-headline 'query-to-create)
10700 (yes-or-no-p "No match - create this as a new heading? "))
10701 (goto-char (point-max))
10702 (unless (bolp) (newline))
10703 (org-insert-heading nil t t)
10704 (insert s "\n")
10705 (beginning-of-line 0))
10706 ;; Only headlines are looked after. No need to process
10707 ;; further: throw an error.
10708 ((and (derived-mode-p 'org-mode)
10709 (or starred org-link-search-must-match-exact-headline))
10710 (goto-char origin)
10711 (error "No match for fuzzy expression: %s" normalized))
10712 ;; Regular text search.
10713 ((catch :fuzzy-match
10714 (goto-char (point-min))
10715 (while (re-search-forward s-multi-re nil t)
10716 ;; Skip match if it contains AVOID-POS or it is included in
10717 ;; a link with a description but outside the description.
10718 (unless (or (and avoid-pos
10719 (<= (match-beginning 0) avoid-pos)
10720 (> (match-end 0) avoid-pos))
10721 (and (save-match-data
10722 (org-in-regexp org-bracket-link-regexp))
10723 (match-beginning 3)
10724 (or (> (match-beginning 3) (point))
10725 (<= (match-end 3) (point)))
10726 (org-element-lineage
10727 (save-match-data (org-element-context))
10728 '(link) t)))
10729 (goto-char (match-beginning 0))
10730 (setq type 'fuzzy)
10731 (throw :fuzzy-match t)))
10732 nil))
10733 ;; All failed. Throw an error.
10734 (t (goto-char origin)
10735 (error "No match for fuzzy expression: %s" normalized)))
10736 ;; Disclose surroundings of match, if appropriate.
10737 (when (and (derived-mode-p 'org-mode) (not stealth))
10738 (org-show-context 'link-search))
10739 type))
10741 (defun org-get-buffer-for-internal-link (buffer)
10742 "Return a buffer to be used for displaying the link target of internal links."
10743 (cond
10744 ((not org-display-internal-link-with-indirect-buffer)
10745 buffer)
10746 ((string-suffix-p "(Clone)" (buffer-name buffer))
10747 (message "Buffer is already a clone, not making another one")
10748 ;; we also do not modify visibility in this case
10749 buffer)
10750 (t ; make a new indirect buffer for displaying the link
10751 (let* ((bn (buffer-name buffer))
10752 (ibn (concat bn "(Clone)"))
10753 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10754 (with-current-buffer ib (org-overview))
10755 ib))))
10757 (defun org-do-occur (regexp &optional cleanup)
10758 "Call the Emacs command `occur'.
10759 If CLEANUP is non-nil, remove the printout of the regular expression
10760 in the *Occur* buffer. This is useful if the regex is long and not useful
10761 to read."
10762 (occur regexp)
10763 (when cleanup
10764 (let ((cwin (selected-window)) win beg end)
10765 (when (setq win (get-buffer-window "*Occur*"))
10766 (select-window win))
10767 (goto-char (point-min))
10768 (when (re-search-forward "match[a-z]+" nil t)
10769 (setq beg (match-end 0))
10770 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10771 (setq end (1- (match-beginning 0)))))
10772 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10773 (goto-char (point-min))
10774 (select-window cwin))))
10776 ;;; The mark ring for links jumps
10778 (defvar org-mark-ring nil
10779 "Mark ring for positions before jumps in Org mode.")
10780 (defvar org-mark-ring-last-goto nil
10781 "Last position in the mark ring used to go back.")
10782 ;; Fill and close the ring
10783 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10784 (dotimes (_ org-mark-ring-length)
10785 (push (make-marker) org-mark-ring))
10786 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10787 org-mark-ring)
10789 (defun org-mark-ring-push (&optional pos buffer)
10790 "Put the current position or POS into the mark ring and rotate it."
10791 (interactive)
10792 (setq pos (or pos (point)))
10793 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10794 (move-marker (car org-mark-ring)
10795 (or pos (point))
10796 (or buffer (current-buffer)))
10797 (message "%s"
10798 (substitute-command-keys
10799 "Position saved to mark ring, go back with \
10800 `\\[org-mark-ring-goto]'.")))
10802 (defun org-mark-ring-goto (&optional n)
10803 "Jump to the previous position in the mark ring.
10804 With prefix arg N, jump back that many stored positions. When
10805 called several times in succession, walk through the entire ring.
10806 Org mode commands jumping to a different position in the current file,
10807 or to another Org file, automatically push the old position onto the ring."
10808 (interactive "p")
10809 (let (p m)
10810 (if (eq last-command this-command)
10811 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10812 (setq p org-mark-ring))
10813 (setq org-mark-ring-last-goto p)
10814 (setq m (car p))
10815 (pop-to-buffer-same-window (marker-buffer m))
10816 (goto-char m)
10817 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10819 (defun org-add-angle-brackets (s)
10820 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10821 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10824 ;;; Following specific links
10826 (defvar org-agenda-buffer-tmp-name)
10827 (defvar org-agenda-start-on-weekday)
10828 (defun org-follow-timestamp-link ()
10829 "Open an agenda view for the time-stamp date/range at point."
10830 (cond
10831 ((org-at-date-range-p t)
10832 (let ((org-agenda-start-on-weekday)
10833 (t1 (match-string 1))
10834 (t2 (match-string 2)) tt1 tt2)
10835 (setq tt1 (time-to-days (org-time-string-to-time t1))
10836 tt2 (time-to-days (org-time-string-to-time t2)))
10837 (let ((org-agenda-buffer-tmp-name
10838 (format "*Org Agenda(a:%s)"
10839 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10840 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10841 ((org-at-timestamp-p 'lax)
10842 (let ((org-agenda-buffer-tmp-name
10843 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10844 (org-agenda-list nil (time-to-days (org-time-string-to-time
10845 (substring (match-string 1) 0 10)))
10846 1)))
10847 (t (error "This should not happen"))))
10850 ;;; Following file links
10851 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10852 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10853 (declare-function mailcap-mime-info
10854 "mailcap" (string &optional request no-decode))
10855 (defvar org-wait nil)
10856 (defun org-open-file (path &optional in-emacs line search)
10857 "Open the file at PATH.
10858 First, this expands any special file name abbreviations. Then the
10859 configuration variable `org-file-apps' is checked if it contains an
10860 entry for this file type, and if yes, the corresponding command is launched.
10862 If no application is found, Emacs simply visits the file.
10864 With optional prefix argument IN-EMACS, Emacs will visit the file.
10865 With a double \\[universal-argument] \\[universal-argument] \
10866 prefix arg, Org tries to avoid opening in Emacs
10867 and to use an external application to visit the file.
10869 Optional LINE specifies a line to go to, optional SEARCH a string
10870 to search for. If LINE or SEARCH is given, the file will be
10871 opened in Emacs, unless an entry from org-file-apps that makes
10872 use of groups in a regexp matches.
10874 If you want to change the way frames are used when following a
10875 link, please customize `org-link-frame-setup'.
10877 If the file does not exist, an error is thrown."
10878 (let* ((file (if (equal path "")
10879 buffer-file-name
10880 (substitute-in-file-name (expand-file-name path))))
10881 (file-apps (append org-file-apps (org-default-apps)))
10882 (apps (cl-remove-if
10883 'org-file-apps-entry-match-against-dlink-p file-apps))
10884 (apps-dlink (cl-remove-if-not
10885 'org-file-apps-entry-match-against-dlink-p file-apps))
10886 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10887 (dirp (unless remp (file-directory-p file)))
10888 (file (if (and dirp org-open-directory-means-index-dot-org)
10889 (concat (file-name-as-directory file) "index.org")
10890 file))
10891 (a-m-a-p (assq 'auto-mode apps))
10892 (dfile (downcase file))
10893 ;; Reconstruct the original link from the PATH, LINE and
10894 ;; SEARCH args.
10895 (link (cond (line (concat file "::" (number-to-string line)))
10896 (search (concat file "::" search))
10897 (t file)))
10898 (dlink (downcase link))
10899 (ext
10900 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10901 (match-string 1 dfile)))
10902 (save-position-maybe
10903 (let ((old-buffer (current-buffer))
10904 (old-pos (point))
10905 (old-mode major-mode))
10906 (lambda ()
10907 (and (derived-mode-p 'org-mode)
10908 (eq old-mode 'org-mode)
10909 (or (not (eq old-buffer (current-buffer)))
10910 (not (eq old-pos (point))))
10911 (org-mark-ring-push old-pos old-buffer)))))
10912 cmd link-match-data)
10913 (cond
10914 ((member in-emacs '((16) system))
10915 (setq cmd (cdr (assq 'system apps))))
10916 (in-emacs (setq cmd 'emacs))
10918 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10919 (and dirp (cdr (assq 'directory apps)))
10920 ;; First, try matching against apps-dlink if we
10921 ;; get a match here, store the match data for
10922 ;; later.
10923 (let ((match (assoc-default dlink apps-dlink
10924 'string-match)))
10925 (if match
10926 (progn (setq link-match-data (match-data))
10927 match)
10928 (progn (setq in-emacs (or in-emacs line search))
10929 nil))) ; if we have no match in apps-dlink,
10930 ; always open the file in emacs if line or search
10931 ; is given (for backwards compatibility)
10932 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10933 'string-match)
10934 (cdr (assoc ext apps))
10935 (cdr (assq t apps))))))
10936 (when (eq cmd 'system)
10937 (setq cmd (cdr (assq 'system apps))))
10938 (when (eq cmd 'default)
10939 (setq cmd (cdr (assoc t apps))))
10940 (when (eq cmd 'mailcap)
10941 (require 'mailcap)
10942 (mailcap-parse-mailcaps)
10943 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10944 (command (mailcap-mime-info mime-type)))
10945 (if (stringp command)
10946 (setq cmd command)
10947 (setq cmd 'emacs))))
10948 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10949 (not (file-exists-p file))
10950 (not org-open-non-existing-files))
10951 (user-error "No such file: %s" file))
10952 (cond
10953 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10954 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10955 (while (string-match "['\"]%s['\"]" cmd)
10956 (setq cmd (replace-match "%s" t t cmd)))
10957 (setq cmd (replace-regexp-in-string
10958 "%s"
10959 (shell-quote-argument (convert-standard-filename file))
10961 nil t))
10963 ;; Replace "%1", "%2" etc. in command with group matches from regex
10964 (save-match-data
10965 (let ((match-index 1)
10966 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10967 (set-match-data link-match-data)
10968 (while (<= match-index number-of-groups)
10969 (let ((regex (concat "%" (number-to-string match-index)))
10970 (replace-with (match-string match-index dlink)))
10971 (while (string-match regex cmd)
10972 (setq cmd (replace-match replace-with t t cmd))))
10973 (setq match-index (+ match-index 1)))))
10975 (save-window-excursion
10976 (message "Running %s...done" cmd)
10977 (start-process-shell-command cmd nil cmd)
10978 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10979 ((or (stringp cmd)
10980 (eq cmd 'emacs))
10981 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10982 (widen)
10983 (cond (line (org-goto-line line)
10984 (when (derived-mode-p 'org-mode) (org-reveal)))
10985 (search (condition-case err
10986 (org-link-search search)
10987 ;; Save position before error-ing out so user
10988 ;; can easily move back to the original buffer.
10989 (error (funcall save-position-maybe)
10990 (error (nth 1 err)))))))
10991 ((functionp cmd)
10992 (save-match-data
10993 (set-match-data link-match-data)
10994 (condition-case nil
10995 (funcall cmd file link)
10996 ;; FIXME: Remove this check when most default installations
10997 ;; of Emacs have at least Org 9.0.
10998 ((debug wrong-number-of-arguments wrong-type-argument
10999 invalid-function)
11000 (user-error "Please see Org News for version 9.0 about \
11001 `org-file-apps'--Lisp error: %S" cmd)))))
11002 ((consp cmd)
11003 ;; FIXME: Remove this check when most default installations of
11004 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11005 ;; fall back to `org-link-frame-setup' for an old usage of
11006 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11007 (user-error "Please see Org News for version 9.0 about \
11008 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11009 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11010 (funcall save-position-maybe)))
11012 (defun org-file-apps-entry-match-against-dlink-p (entry)
11013 "This function returns non-nil if `entry' uses a regular
11014 expression which should be matched against the whole link by
11015 org-open-file.
11017 It assumes that is the case when the entry uses a regular
11018 expression which has at least one grouping construct and the
11019 action is either a lisp form or a command string containing
11020 `%1', i.e. using at least one subexpression match as a
11021 parameter."
11022 (let ((selector (car entry))
11023 (action (cdr entry)))
11024 (if (stringp selector)
11025 (and (> (regexp-opt-depth selector) 0)
11026 (or (and (stringp action)
11027 (string-match "%[0-9]" action))
11028 (consp action)))
11029 nil)))
11031 (defun org-default-apps ()
11032 "Return the default applications for this operating system."
11033 (cond
11034 ((eq system-type 'darwin)
11035 org-file-apps-defaults-macosx)
11036 ((eq system-type 'windows-nt)
11037 org-file-apps-defaults-windowsnt)
11038 (t org-file-apps-defaults-gnu)))
11040 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11041 "Convert extensions to regular expressions in the cars of LIST.
11042 Also, weed out any non-string entries, because the return value is used
11043 only for regexp matching.
11044 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11045 point to the symbol `emacs', indicating that the file should
11046 be opened in Emacs."
11047 (append
11048 (delq nil
11049 (mapcar (lambda (x)
11050 (unless (not (stringp (car x)))
11051 (if (string-match "\\W" (car x))
11053 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11054 list))
11055 (when add-auto-mode
11056 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11058 (defvar ange-ftp-name-format)
11059 (defun org-file-remote-p (file)
11060 "Test whether FILE specifies a location on a remote system.
11061 Return non-nil if the location is indeed remote.
11063 For example, the filename \"/user@host:/foo\" specifies a location
11064 on the system \"/user@host:\"."
11065 (cond ((fboundp 'file-remote-p)
11066 (file-remote-p file))
11067 ((fboundp 'tramp-handle-file-remote-p)
11068 (tramp-handle-file-remote-p file))
11069 ((and (boundp 'ange-ftp-name-format)
11070 (string-match (car ange-ftp-name-format) file))
11071 t)))
11074 ;;;; Refiling
11076 (defun org-get-org-file ()
11077 "Read a filename, with default directory `org-directory'."
11078 (let ((default (or org-default-notes-file remember-data-file)))
11079 (read-file-name (format "File name [%s]: " default)
11080 (file-name-as-directory org-directory)
11081 default)))
11083 (defun org-notes-order-reversed-p ()
11084 "Check if the current file should receive notes in reversed order."
11085 (cond
11086 ((not org-reverse-note-order) nil)
11087 ((eq t org-reverse-note-order) t)
11088 ((not (listp org-reverse-note-order)) nil)
11089 (t (catch 'exit
11090 (dolist (entry org-reverse-note-order)
11091 (when (string-match (car entry) buffer-file-name)
11092 (throw 'exit (cdr entry))))))))
11094 (defvar org-refile-target-table nil
11095 "The list of refile targets, created by `org-refile'.")
11097 (defvar org-agenda-new-buffers nil
11098 "Buffers created to visit agenda files.")
11100 (defvar org-refile-cache nil
11101 "Cache for refile targets.")
11103 (defvar org-refile-markers nil
11104 "All the markers used for caching refile locations.")
11106 (defun org-refile-marker (pos)
11107 "Get a new refile marker, but only if caching is in use."
11108 (if (not org-refile-use-cache)
11110 (let ((m (make-marker)))
11111 (move-marker m pos)
11112 (push m org-refile-markers)
11113 m)))
11115 (defun org-refile-cache-clear ()
11116 "Clear the refile cache and disable all the markers."
11117 (dolist (m org-refile-markers) (move-marker m nil))
11118 (setq org-refile-markers nil)
11119 (setq org-refile-cache nil)
11120 (message "Refile cache has been cleared"))
11122 (defun org-refile-cache-check-set (set)
11123 "Check if all the markers in the cache still have live buffers."
11124 (let (marker)
11125 (catch 'exit
11126 (while (and set (setq marker (nth 3 (pop set))))
11127 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11128 (when (and marker (null (marker-buffer marker)))
11129 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11130 (sit-for 3)
11131 (throw 'exit nil)))
11132 t)))
11134 (defun org-refile-cache-put (set &rest identifiers)
11135 "Push the refile targets SET into the cache, under IDENTIFIERS."
11136 (let* ((key (sha1 (prin1-to-string identifiers)))
11137 (entry (assoc key org-refile-cache)))
11138 (if entry
11139 (setcdr entry set)
11140 (push (cons key set) org-refile-cache))))
11142 (defun org-refile-cache-get (&rest identifiers)
11143 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11144 (cond
11145 ((not org-refile-cache) nil)
11146 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11148 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11149 org-refile-cache))))
11150 (and set (org-refile-cache-check-set set) set)))))
11152 (defvar org-outline-path-cache nil
11153 "Alist between buffer positions and outline paths.
11154 It value is an alist (POSITION . PATH) where POSITION is the
11155 buffer position at the beginning of an entry and PATH is a list
11156 of strings describing the outline path for that entry, in reverse
11157 order.")
11159 (defun org-refile-get-targets (&optional default-buffer)
11160 "Produce a table with refile targets."
11161 (let ((case-fold-search nil)
11162 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11163 (entries (or org-refile-targets '((nil . (:level . 1)))))
11164 targets tgs files desc descre)
11165 (message "Getting targets...")
11166 (with-current-buffer (or default-buffer (current-buffer))
11167 (dolist (entry entries)
11168 (setq files (car entry) desc (cdr entry))
11169 (cond
11170 ((null files) (setq files (list (current-buffer))))
11171 ((eq files 'org-agenda-files)
11172 (setq files (org-agenda-files 'unrestricted)))
11173 ((and (symbolp files) (fboundp files))
11174 (setq files (funcall files)))
11175 ((and (symbolp files) (boundp files))
11176 (setq files (symbol-value files))))
11177 (when (stringp files) (setq files (list files)))
11178 (cond
11179 ((eq (car desc) :tag)
11180 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11181 ((eq (car desc) :todo)
11182 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11183 ((eq (car desc) :regexp)
11184 (setq descre (cdr desc)))
11185 ((eq (car desc) :level)
11186 (setq descre (concat "^\\*\\{" (number-to-string
11187 (if org-odd-levels-only
11188 (1- (* 2 (cdr desc)))
11189 (cdr desc)))
11190 "\\}[ \t]")))
11191 ((eq (car desc) :maxlevel)
11192 (setq descre (concat "^\\*\\{1," (number-to-string
11193 (if org-odd-levels-only
11194 (1- (* 2 (cdr desc)))
11195 (cdr desc)))
11196 "\\}[ \t]")))
11197 (t (error "Bad refiling target description %s" desc)))
11198 (dolist (f files)
11199 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11201 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11202 (progn
11203 (when (bufferp f)
11204 (setq f (buffer-file-name (buffer-base-buffer f))))
11205 (setq f (and f (expand-file-name f)))
11206 (when (eq org-refile-use-outline-path 'file)
11207 (push (list (file-name-nondirectory f) f nil nil) tgs))
11208 (when (eq org-refile-use-outline-path 'buffer-name)
11209 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11210 (when (eq org-refile-use-outline-path 'full-file-path)
11211 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11212 (org-with-wide-buffer
11213 (goto-char (point-min))
11214 (setq org-outline-path-cache nil)
11215 (while (re-search-forward descre nil t)
11216 (beginning-of-line)
11217 (let ((case-fold-search nil))
11218 (looking-at org-complex-heading-regexp))
11219 (let ((begin (point))
11220 (heading (match-string-no-properties 4)))
11221 (unless (or (and
11222 org-refile-target-verify-function
11223 (not
11224 (funcall org-refile-target-verify-function)))
11225 (not heading))
11226 (let ((re (format org-complex-heading-regexp-format
11227 (regexp-quote heading)))
11228 (target
11229 (if (not org-refile-use-outline-path) heading
11230 (mapconcat
11231 #'identity
11232 (append
11233 (pcase org-refile-use-outline-path
11234 (`file (list (file-name-nondirectory
11235 (buffer-file-name
11236 (buffer-base-buffer)))))
11237 (`full-file-path
11238 (list (buffer-file-name
11239 (buffer-base-buffer))))
11240 (`buffer-name
11241 (list (buffer-name
11242 (buffer-base-buffer))))
11243 (_ nil))
11244 (mapcar (lambda (s) (replace-regexp-in-string
11245 "/" "\\/" s nil t))
11246 (org-get-outline-path t t)))
11247 "/"))))
11248 (push (list target f re (org-refile-marker (point)))
11249 tgs)))
11250 (when (= (point) begin)
11251 ;; Verification function has not moved point.
11252 (end-of-line)))))))
11253 (when org-refile-use-cache
11254 (org-refile-cache-put tgs (buffer-file-name) descre))
11255 (setq targets (append tgs targets))))))
11256 (message "Getting targets...done")
11257 (delete-dups (nreverse targets))))
11259 (defun org--get-outline-path-1 (&optional use-cache)
11260 "Return outline path to current headline.
11262 Outline path is a list of strings, in reverse order. When
11263 optional argument USE-CACHE is non-nil, make use of a cache. See
11264 `org-get-outline-path' for details.
11266 Assume buffer is widened and point is on a headline."
11267 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11268 (let ((p (point))
11269 (heading (let ((case-fold-search nil))
11270 (looking-at org-complex-heading-regexp)
11271 (if (not (match-end 4)) ""
11272 ;; Remove statistics cookies.
11273 (org-trim
11274 (org-link-display-format
11275 (replace-regexp-in-string
11276 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11277 (match-string-no-properties 4))))))))
11278 (if (org-up-heading-safe)
11279 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11280 (when use-cache
11281 (push (cons p path) org-outline-path-cache))
11282 path)
11283 ;; This is a new root node. Since we assume we are moving
11284 ;; forward, we can drop previous cache so as to limit number
11285 ;; of associations there.
11286 (let ((path (list heading)))
11287 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11288 path)))))
11290 (defun org-get-outline-path (&optional with-self use-cache)
11291 "Return the outline path to the current entry.
11293 An outline path is a list of ancestors for current headline, as
11294 a list of strings. Statistics cookies are removed and links are
11295 replaced with their description, if any, or their path otherwise.
11297 When optional argument WITH-SELF is non-nil, the path also
11298 includes the current headline.
11300 When optional argument USE-CACHE is non-nil, cache outline paths
11301 between calls to this function so as to avoid backtracking. This
11302 argument is useful when planning to find more than one outline
11303 path in the same document. In that case, there are two
11304 conditions to satisfy:
11305 - `org-outline-path-cache' is set to nil before starting the
11306 process;
11307 - outline paths are computed by increasing buffer positions."
11308 (org-with-wide-buffer
11309 (and (or (and with-self (org-back-to-heading t))
11310 (org-up-heading-safe))
11311 (reverse (org--get-outline-path-1 use-cache)))))
11313 (defun org-format-outline-path (path &optional width prefix separator)
11314 "Format the outline path PATH for display.
11315 WIDTH is the maximum number of characters that is available.
11316 PREFIX is a prefix to be included in the returned string,
11317 such as the file name.
11318 SEPARATOR is inserted between the different parts of the path,
11319 the default is \"/\"."
11320 (setq width (or width 79))
11321 (setq path (delq nil path))
11322 (unless (> width 0)
11323 (user-error "Argument `width' must be positive"))
11324 (setq separator (or separator "/"))
11325 (let* ((org-odd-levels-only nil)
11326 (fpath (concat
11327 prefix (and prefix path separator)
11328 (mapconcat
11329 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11330 (cl-loop for head in path
11331 for n from 0
11332 collect (org-add-props
11333 head nil 'face
11334 (nth (% n org-n-level-faces) org-level-faces)))
11335 separator))))
11336 (when (> (length fpath) width)
11337 (if (< width 7)
11338 ;; It's unlikely that `width' will be this small, but don't
11339 ;; waste characters by adding ".." if it is.
11340 (setq fpath (substring fpath 0 width))
11341 (setf (substring fpath (- width 2)) "..")))
11342 fpath))
11344 (defun org-display-outline-path (&optional file current separator just-return-string)
11345 "Display the current outline path in the echo area.
11347 If FILE is non-nil, prepend the output with the file name.
11348 If CURRENT is non-nil, append the current heading to the output.
11349 SEPARATOR is passed through to `org-format-outline-path'. It separates
11350 the different parts of the path and defaults to \"/\".
11351 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11352 (interactive "P")
11353 (let* (case-fold-search
11354 (bfn (buffer-file-name (buffer-base-buffer)))
11355 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11356 res)
11357 (when current (setq path (append path
11358 (save-excursion
11359 (org-back-to-heading t)
11360 (when (looking-at org-complex-heading-regexp)
11361 (list (match-string 4)))))))
11362 (setq res
11363 (org-format-outline-path
11364 path
11365 (1- (frame-width))
11366 (and file bfn (concat (file-name-nondirectory bfn) separator))
11367 separator))
11368 (if just-return-string
11369 (org-no-properties res)
11370 (org-unlogged-message "%s" res))))
11372 (defvar org-refile-history nil
11373 "History for refiling operations.")
11375 (defvar org-after-refile-insert-hook nil
11376 "Hook run after `org-refile' has inserted its stuff at the new location.
11377 Note that this is still *before* the stuff will be removed from
11378 the *old* location.")
11380 (defvar org-capture-last-stored-marker)
11381 (defvar org-refile-keep nil
11382 "Non-nil means `org-refile' will copy instead of refile.")
11384 (defun org-copy ()
11385 "Like `org-refile', but copy."
11386 (interactive)
11387 (let ((org-refile-keep t))
11388 (funcall 'org-refile nil nil nil "Copy")))
11390 (defun org-refile (&optional arg default-buffer rfloc msg)
11391 "Move the entry or entries at point to another heading.
11393 The list of target headings is compiled using the information in
11394 `org-refile-targets', which see.
11396 At the target location, the entry is filed as a subitem of the
11397 target heading. Depending on `org-reverse-note-order', the new
11398 subitem will either be the first or the last subitem.
11400 If there is an active region, all entries in that region will be
11401 refiled. However, the region must fulfill the requirement that
11402 the first heading sets the top-level of the moved text.
11404 With a `\\[universal-argument]' ARG, the command will only visit the target \
11405 location
11406 and not actually move anything.
11408 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11409 location where the last
11410 refiling operation has put the subtree.
11412 With a numeric prefix argument of `2', refile to the running clock.
11414 With a numeric prefix argument of `3', emulate `org-refile-keep'
11415 being set to t and copy to the target location, don't move it.
11416 Beware that keeping refiled entries may result in duplicated ID
11417 properties.
11419 RFLOC can be a refile location obtained in a different way.
11421 MSG is a string to replace \"Refile\" in the default prompt with
11422 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11424 See also `org-refile-use-outline-path'.
11426 If you are using target caching (see `org-refile-use-cache'), you
11427 have to clear the target cache in order to find new targets.
11428 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11429 prefix argument (`C-u C-u C-u C-c C-w')."
11430 (interactive "P")
11431 (if (member arg '(0 (64)))
11432 (org-refile-cache-clear)
11433 (let* ((actionmsg (cond (msg msg)
11434 ((equal arg 3) "Refile (and keep)")
11435 (t "Refile")))
11436 (regionp (org-region-active-p))
11437 (region-start (and regionp (region-beginning)))
11438 (region-end (and regionp (region-end)))
11439 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11440 pos it nbuf file level reversed)
11441 (setq last-command nil)
11442 (when regionp
11443 (goto-char region-start)
11444 (or (bolp) (goto-char (point-at-bol)))
11445 (setq region-start (point))
11446 (unless (or (org-kill-is-subtree-p
11447 (buffer-substring region-start region-end))
11448 (prog1 org-refile-active-region-within-subtree
11449 (let ((s (point-at-eol)))
11450 (org-toggle-heading)
11451 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11452 (user-error "The region is not a (sequence of) subtree(s)")))
11453 (if (equal arg '(16))
11454 (org-refile-goto-last-stored)
11455 (when (or
11456 (and (equal arg 2)
11457 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11458 (prog1
11459 (setq it (list (or org-clock-heading "running clock")
11460 (buffer-file-name
11461 (marker-buffer org-clock-hd-marker))
11463 (marker-position org-clock-hd-marker)))
11464 (setq arg nil)))
11465 (setq it
11466 (or rfloc
11467 (let (heading-text)
11468 (save-excursion
11469 (unless (and arg (listp arg))
11470 (org-back-to-heading t)
11471 (setq heading-text
11472 (replace-regexp-in-string
11473 org-bracket-link-regexp
11474 "\\3"
11475 (or (nth 4 (org-heading-components))
11476 ""))))
11477 (org-refile-get-location
11478 (cond ((and arg (listp arg)) "Goto")
11479 (regionp (concat actionmsg " region to"))
11480 (t (concat actionmsg " subtree \""
11481 heading-text "\" to")))
11482 default-buffer
11483 (and (not (equal '(4) arg))
11484 org-refile-allow-creating-parent-nodes)))))))
11485 (setq file (nth 1 it)
11486 pos (nth 3 it))
11487 (when (and (not arg)
11489 (equal (buffer-file-name) file)
11490 (if regionp
11491 (and (>= pos region-start)
11492 (<= pos region-end))
11493 (and (>= pos (point))
11494 (< pos (save-excursion
11495 (org-end-of-subtree t t))))))
11496 (error "Cannot refile to position inside the tree or region"))
11497 (setq nbuf (or (find-buffer-visiting file)
11498 (find-file-noselect file)))
11499 (if (and arg (not (equal arg 3)))
11500 (progn
11501 (pop-to-buffer-same-window nbuf)
11502 (goto-char (cond (pos)
11503 ((org-notes-order-reversed-p) (point-min))
11504 (t (point-max))))
11505 (org-show-context 'org-goto))
11506 (if regionp
11507 (progn
11508 (org-kill-new (buffer-substring region-start region-end))
11509 (org-save-markers-in-region region-start region-end))
11510 (org-copy-subtree 1 nil t))
11511 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11512 (find-file-noselect file)))
11513 (setq reversed (org-notes-order-reversed-p))
11514 (org-with-wide-buffer
11515 (if pos
11516 (progn
11517 (goto-char pos)
11518 (setq level (org-get-valid-level (funcall outline-level) 1))
11519 (goto-char
11520 (if reversed
11521 (or (outline-next-heading) (point-max))
11522 (or (save-excursion (org-get-next-sibling))
11523 (org-end-of-subtree t t)
11524 (point-max)))))
11525 (setq level 1)
11526 (if (not reversed)
11527 (goto-char (point-max))
11528 (goto-char (point-min))
11529 (or (outline-next-heading) (goto-char (point-max)))))
11530 (unless (bolp) (newline))
11531 (org-paste-subtree level nil nil t)
11532 (when org-log-refile
11533 (org-add-log-setup 'refile nil nil org-log-refile)
11534 (unless (eq org-log-refile 'note)
11535 (save-excursion (org-add-log-note))))
11536 (and org-auto-align-tags
11537 (let ((org-loop-over-headlines-in-active-region nil))
11538 (org-set-tags nil t)))
11539 (let ((bookmark-name (plist-get org-bookmark-names-plist
11540 :last-refile)))
11541 (when bookmark-name
11542 (with-demoted-errors
11543 (bookmark-set bookmark-name))))
11544 ;; If we are refiling for capture, make sure that the
11545 ;; last-capture pointers point here
11546 (when (bound-and-true-p org-capture-is-refiling)
11547 (let ((bookmark-name (plist-get org-bookmark-names-plist
11548 :last-capture-marker)))
11549 (when bookmark-name
11550 (with-demoted-errors
11551 (bookmark-set bookmark-name))))
11552 (move-marker org-capture-last-stored-marker (point)))
11553 (when (fboundp 'deactivate-mark) (deactivate-mark))
11554 (run-hooks 'org-after-refile-insert-hook)))
11555 (unless org-refile-keep
11556 (if regionp
11557 (delete-region (point) (+ (point) (- region-end region-start)))
11558 (delete-region
11559 (and (org-back-to-heading t) (point))
11560 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11561 (when (featurep 'org-inlinetask)
11562 (org-inlinetask-remove-END-maybe))
11563 (setq org-markers-to-move nil)
11564 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11566 (defun org-refile-goto-last-stored ()
11567 "Go to the location where the last refile was stored."
11568 (interactive)
11569 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11570 (message "This is the location of the last refile"))
11572 (defun org-refile--get-location (refloc tbl)
11573 "When user refile to REFLOC, find the associated target in TBL.
11574 Also check `org-refile-target-table'."
11575 (car (delq
11577 (mapcar
11578 (lambda (r) (or (assoc r tbl)
11579 (assoc r org-refile-target-table)))
11580 (list (replace-regexp-in-string "/$" "" refloc)
11581 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11583 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11584 "Prompt the user for a refile location, using PROMPT.
11585 PROMPT should not be suffixed with a colon and a space, because
11586 this function appends the default value from
11587 `org-refile-history' automatically, if that is not empty."
11588 (let ((org-refile-targets org-refile-targets)
11589 (org-refile-use-outline-path org-refile-use-outline-path))
11590 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11591 (unless org-refile-target-table
11592 (user-error "No refile targets"))
11593 (let* ((cbuf (current-buffer))
11594 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11595 (cfunc (if (and org-refile-use-outline-path
11596 org-outline-path-complete-in-steps)
11597 #'org-olpath-completing-read
11598 #'completing-read))
11599 (extra (if org-refile-use-outline-path "/" ""))
11600 (cbnex (concat (buffer-name) extra))
11601 (filename (and cfn (expand-file-name cfn)))
11602 (tbl (mapcar
11603 (lambda (x)
11604 (if (and (not (member org-refile-use-outline-path
11605 '(file full-file-path)))
11606 (not (equal filename (nth 1 x))))
11607 (cons (concat (car x) extra " ("
11608 (file-name-nondirectory (nth 1 x)) ")")
11609 (cdr x))
11610 (cons (concat (car x) extra) (cdr x))))
11611 org-refile-target-table))
11612 (completion-ignore-case t)
11613 cdef
11614 (prompt (concat prompt
11615 (or (and (car org-refile-history)
11616 (concat " (default " (car org-refile-history) ")"))
11617 (and (assoc cbnex tbl) (setq cdef cbnex)
11618 (concat " (default " cbnex ")"))) ": "))
11619 pa answ parent-target child parent old-hist)
11620 (setq old-hist org-refile-history)
11621 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11622 nil 'org-refile-history (or cdef (car org-refile-history))))
11623 (if (setq pa (org-refile--get-location answ tbl))
11624 (progn
11625 (org-refile-check-position pa)
11626 (when (or (not org-refile-history)
11627 (not (eq old-hist org-refile-history))
11628 (not (equal (car pa) (car org-refile-history))))
11629 (setq org-refile-history
11630 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11631 org-refile-history
11632 (cdr org-refile-history))))
11633 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11634 (pop org-refile-history)))
11636 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11637 (progn
11638 (setq parent (match-string 1 answ)
11639 child (match-string 2 answ))
11640 (setq parent-target (org-refile--get-location parent tbl))
11641 (when (and parent-target
11642 (or (eq new-nodes t)
11643 (and (eq new-nodes 'confirm)
11644 (y-or-n-p (format "Create new node \"%s\"? "
11645 child)))))
11646 (org-refile-new-child parent-target child)))
11647 (user-error "Invalid target location")))))
11649 (declare-function org-string-nw-p "org-macs" (s))
11650 (defun org-refile-check-position (refile-pointer)
11651 "Check if the refile pointer matches the headline to which it points."
11652 (let* ((file (nth 1 refile-pointer))
11653 (re (nth 2 refile-pointer))
11654 (pos (nth 3 refile-pointer))
11655 buffer)
11656 (if (and (not (markerp pos)) (not file))
11657 (user-error "Please indicate a target file in the refile path")
11658 (when (org-string-nw-p re)
11659 (setq buffer (if (markerp pos)
11660 (marker-buffer pos)
11661 (or (find-buffer-visiting file)
11662 (find-file-noselect file))))
11663 (with-current-buffer buffer
11664 (org-with-wide-buffer
11665 (goto-char pos)
11666 (beginning-of-line 1)
11667 (unless (looking-at-p re)
11668 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11670 (defun org-refile-new-child (parent-target child)
11671 "Use refile target PARENT-TARGET to add new CHILD below it."
11672 (unless parent-target
11673 (error "Cannot find parent for new node"))
11674 (let ((file (nth 1 parent-target))
11675 (pos (nth 3 parent-target))
11676 level)
11677 (with-current-buffer (or (find-buffer-visiting file)
11678 (find-file-noselect file))
11679 (org-with-wide-buffer
11680 (if pos
11681 (goto-char pos)
11682 (goto-char (point-max))
11683 (unless (bolp) (newline)))
11684 (when (looking-at org-outline-regexp)
11685 (setq level (funcall outline-level))
11686 (org-end-of-subtree t t))
11687 (org-back-over-empty-lines)
11688 (insert "\n" (make-string
11689 (if pos (org-get-valid-level level 1) 1) ?*)
11690 " " child "\n")
11691 (beginning-of-line 0)
11692 (list (concat (car parent-target) "/" child) file "" (point))))))
11694 (defun org-olpath-completing-read (prompt collection &rest args)
11695 "Read an outline path like a file name."
11696 (let ((thetable collection))
11697 (apply #'completing-read
11698 prompt
11699 (lambda (string predicate &optional flag)
11700 (cond
11701 ((eq flag nil) (try-completion string thetable))
11702 ((eq flag t)
11703 (let ((l (length string)))
11704 (mapcar (lambda (x)
11705 (let ((r (substring x l))
11706 (f (if (string-match " ([^)]*)$" x)
11707 (match-string 0 x)
11708 "")))
11709 (if (string-match "/" r)
11710 (concat string (substring r 0 (match-end 0)) f)
11711 x)))
11712 (all-completions string thetable predicate))))
11713 ;; Exact match?
11714 ((eq flag 'lambda) (assoc string thetable))))
11715 args)))
11717 ;;;; Dynamic blocks
11719 (defun org-find-dblock (name)
11720 "Find the first dynamic block with name NAME in the buffer.
11721 If not found, stay at current position and return nil."
11722 (let ((case-fold-search t) pos)
11723 (save-excursion
11724 (goto-char (point-min))
11725 (setq pos (and (re-search-forward
11726 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11727 (match-beginning 0))))
11728 (when pos (goto-char pos))
11729 pos))
11731 (defun org-create-dblock (plist)
11732 "Create a dynamic block section, with parameters taken from PLIST.
11733 PLIST must contain a :name entry which is used as the name of the block."
11734 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11735 (end-of-line 1)
11736 (newline))
11737 (let ((col (current-column))
11738 (name (plist-get plist :name)))
11739 (insert "#+BEGIN: " name)
11740 (while plist
11741 (if (eq (car plist) :name)
11742 (setq plist (cddr plist))
11743 (insert " " (prin1-to-string (pop plist)))))
11744 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11745 (beginning-of-line -2)))
11747 (defun org-prepare-dblock ()
11748 "Prepare dynamic block for refresh.
11749 This empties the block, puts the cursor at the insert position and returns
11750 the property list including an extra property :name with the block name."
11751 (unless (looking-at org-dblock-start-re)
11752 (user-error "Not at a dynamic block"))
11753 (let* ((begdel (1+ (match-end 0)))
11754 (name (org-no-properties (match-string 1)))
11755 (params (append (list :name name)
11756 (read (concat "(" (match-string 3) ")")))))
11757 (save-excursion
11758 (beginning-of-line 1)
11759 (skip-chars-forward " \t")
11760 (setq params (plist-put params :indentation-column (current-column))))
11761 (unless (re-search-forward org-dblock-end-re nil t)
11762 (error "Dynamic block not terminated"))
11763 (setq params
11764 (append params
11765 (list :content (buffer-substring
11766 begdel (match-beginning 0)))))
11767 (delete-region begdel (match-beginning 0))
11768 (goto-char begdel)
11769 (open-line 1)
11770 params))
11772 (defun org-map-dblocks (&optional command)
11773 "Apply COMMAND to all dynamic blocks in the current buffer.
11774 If COMMAND is not given, use `org-update-dblock'."
11775 (let ((cmd (or command 'org-update-dblock)))
11776 (save-excursion
11777 (goto-char (point-min))
11778 (while (re-search-forward org-dblock-start-re nil t)
11779 (goto-char (match-beginning 0))
11780 (save-excursion
11781 (condition-case nil
11782 (funcall cmd)
11783 (error (message "Error during update of dynamic block"))))
11784 (unless (re-search-forward org-dblock-end-re nil t)
11785 (error "Dynamic block not terminated"))))))
11787 (defun org-dblock-update (&optional arg)
11788 "User command for updating dynamic blocks.
11789 Update the dynamic block at point. With prefix ARG, update all dynamic
11790 blocks in the buffer."
11791 (interactive "P")
11792 (if arg
11793 (org-update-all-dblocks)
11794 (or (looking-at org-dblock-start-re)
11795 (org-beginning-of-dblock))
11796 (org-update-dblock)))
11798 (defun org-update-dblock ()
11799 "Update the dynamic block at point.
11800 This means to empty the block, parse for parameters and then call
11801 the correct writing function."
11802 (interactive)
11803 (save-excursion
11804 (let* ((win (selected-window))
11805 (pos (point))
11806 (line (org-current-line))
11807 (params (org-prepare-dblock))
11808 (name (plist-get params :name))
11809 (indent (plist-get params :indentation-column))
11810 (cmd (intern (concat "org-dblock-write:" name))))
11811 (message "Updating dynamic block `%s' at line %d..." name line)
11812 (funcall cmd params)
11813 (message "Updating dynamic block `%s' at line %d...done" name line)
11814 (goto-char pos)
11815 (when (and indent (> indent 0))
11816 (setq indent (make-string indent ?\ ))
11817 (save-excursion
11818 (select-window win)
11819 (org-beginning-of-dblock)
11820 (forward-line 1)
11821 (while (not (looking-at org-dblock-end-re))
11822 (insert indent)
11823 (beginning-of-line 2))
11824 (when (looking-at org-dblock-end-re)
11825 (and (looking-at "[ \t]+")
11826 (replace-match ""))
11827 (insert indent)))))))
11829 (defun org-beginning-of-dblock ()
11830 "Find the beginning of the dynamic block at point.
11831 Error if there is no such block at point."
11832 (let ((pos (point))
11833 beg)
11834 (end-of-line 1)
11835 (if (and (re-search-backward org-dblock-start-re nil t)
11836 (setq beg (match-beginning 0))
11837 (re-search-forward org-dblock-end-re nil t)
11838 (> (match-end 0) pos))
11839 (goto-char beg)
11840 (goto-char pos)
11841 (error "Not in a dynamic block"))))
11843 (defun org-update-all-dblocks ()
11844 "Update all dynamic blocks in the buffer.
11845 This function can be used in a hook."
11846 (interactive)
11847 (when (derived-mode-p 'org-mode)
11848 (org-map-dblocks 'org-update-dblock)))
11851 ;;;; Completion
11853 (declare-function org-export-backend-options "ox" (cl-x) t)
11854 (defun org-get-export-keywords ()
11855 "Return a list of all currently understood export keywords.
11856 Export keywords include options, block names, attributes and
11857 keywords relative to each registered export back-end."
11858 (let (keywords)
11859 (dolist (backend
11860 (bound-and-true-p org-export-registered-backends)
11861 (delq nil keywords))
11862 ;; Back-end name (for keywords, like #+LATEX:)
11863 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11864 (dolist (option-entry (org-export-backend-options backend))
11865 ;; Back-end options.
11866 (push (nth 1 option-entry) keywords)))))
11868 (defconst org-options-keywords
11869 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11870 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11871 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11872 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11873 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11875 (defcustom org-structure-template-alist
11876 '((?a . "export ascii")
11877 (?c . "center")
11878 (?C . "comment")
11879 (?e . "example")
11880 (?E . "export")
11881 (?h . "export html")
11882 (?l . "export latex")
11883 (?q . "quote")
11884 (?s . "src")
11885 (?v . "verse"))
11886 "Structure completion elements.
11887 This is an alist of characters and values. When
11888 `org-insert-structure-template' is called, an additional key is
11889 read. The key is first looked up in this alist, and the
11890 corresponding structure is inserted, with \"#+BEGIN_\" and
11891 \"#+END_\" added automatically."
11892 :group 'org-completion
11893 :type '(repeat
11894 (cons (character :tag "Key")
11895 (string :tag "Template")))
11896 :package-version '(Org . "9.2"))
11898 (defun org-insert-structure-template (type)
11899 "Insert a block structure of the type #+begin_foo/#+end_foo.
11900 First read a character, which can be one of the keys in
11901 `org-structure-template-alist'. When it is <TAB>, prompt the
11902 user for a string to use. With an active region, wrap the region
11903 in the block. Otherwise, insert an empty block."
11904 (interactive
11905 (list
11906 (let* ((key (read-key "Key: "))
11907 (struct-string
11908 (or (cdr (assq key org-structure-template-alist))
11909 (and (= key ?\t)
11910 (read-string "Structure type: "))
11911 (user-error "`%c' has no structure definition" key))))
11912 struct-string)))
11913 (let* ((region? (use-region-p))
11914 (s (if region? (region-beginning) (point)))
11915 (e (copy-marker (if region? (region-end) (point)) t))
11916 column)
11917 (when (string-match-p
11918 (concat "\\`" (regexp-opt '("example" "export" "src")))
11919 type)
11920 (org-escape-code-in-region s e))
11921 (goto-char s)
11922 (setq column (current-indentation))
11923 (beginning-of-line)
11924 (indent-to column)
11925 (insert (format "#+begin_%s\n" type))
11926 (goto-char e)
11927 (if (bolp)
11928 (progn
11929 (skip-chars-backward " \n\t")
11930 (forward-line))
11931 (end-of-line)
11932 (insert "\n"))
11933 (indent-to column)
11934 (insert (format "#+end_%s\n"
11935 (car (split-string type))))
11936 (when (or (not region?)
11937 (string-match-p "src\\|\\`export\\'" type))
11938 (goto-char s)
11939 (end-of-line))
11940 (set-marker e nil)))
11942 ;;;; TODO, DEADLINE, Comments
11944 (defun org-toggle-comment ()
11945 "Change the COMMENT state of an entry."
11946 (interactive)
11947 (save-excursion
11948 (org-back-to-heading)
11949 (let ((case-fold-search nil))
11950 (looking-at org-complex-heading-regexp))
11951 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11952 (skip-chars-forward " \t")
11953 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11954 (if (org-in-commented-heading-p t)
11955 (delete-region (point)
11956 (progn (search-forward " " (line-end-position) 'move)
11957 (skip-chars-forward " \t")
11958 (point)))
11959 (insert org-comment-string)
11960 (unless (eolp) (insert " ")))))
11962 (defvar org-last-todo-state-is-todo nil
11963 "This is non-nil when the last TODO state change led to a TODO state.
11964 If the last change removed the TODO tag or switched to DONE, then
11965 this is nil.")
11967 (defvar org-setting-tags nil) ; dynamically skipped
11969 (defvar org-todo-setup-filter-hook nil
11970 "Hook for functions that pre-filter todo specs.
11971 Each function takes a todo spec and returns either nil or the spec
11972 transformed into canonical form." )
11974 (defvar org-todo-get-default-hook nil
11975 "Hook for functions that get a default item for todo.
11976 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11977 nil or a string to be used for the todo mark." )
11979 (defvar org-agenda-headline-snapshot-before-repeat)
11981 (defun org-current-effective-time ()
11982 "Return current time adjusted for `org-extend-today-until' variable."
11983 (let* ((ct (org-current-time))
11984 (dct (decode-time ct))
11985 (ct1
11986 (cond
11987 (org-use-last-clock-out-time-as-effective-time
11988 (or (org-clock-get-last-clock-out-time) ct))
11989 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11990 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11991 (t ct))))
11992 ct1))
11994 (defun org-todo-yesterday (&optional arg)
11995 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11996 (interactive "P")
11997 (if (eq major-mode 'org-agenda-mode)
11998 (apply 'org-agenda-todo-yesterday arg)
11999 (let* ((org-use-effective-time t)
12000 (hour (nth 2 (decode-time (org-current-time))))
12001 (org-extend-today-until (1+ hour)))
12002 (org-todo arg))))
12004 (defvar org-block-entry-blocking ""
12005 "First entry preventing the TODO state change.")
12007 (defun org-cancel-repeater ()
12008 "Cancel a repeater by setting its numeric value to zero."
12009 (interactive)
12010 (save-excursion
12011 (org-back-to-heading t)
12012 (let ((bound1 (point))
12013 (bound0 (save-excursion (outline-next-heading) (point))))
12014 (when (and (re-search-forward
12015 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12016 org-deadline-time-regexp "\\)\\|\\("
12017 org-ts-regexp "\\)")
12018 bound0 t)
12019 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12020 bound1 t))
12021 (replace-match "0" t nil nil 1)))))
12023 (defvar org-state)
12024 (defvar org-blocked-by-checkboxes)
12025 (defun org-todo (&optional arg)
12026 "Change the TODO state of an item.
12028 The state of an item is given by a keyword at the start of the heading,
12029 like
12030 *** TODO Write paper
12031 *** DONE Call mom
12033 The different keywords are specified in the variable `org-todo-keywords'.
12034 By default the available states are \"TODO\" and \"DONE\". So, for this
12035 example: when the item starts with TODO, it is changed to DONE.
12036 When it starts with DONE, the DONE is removed. And when neither TODO nor
12037 DONE are present, add TODO at the beginning of the heading.
12039 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12040 state.
12041 With numeric prefix ARG, switch to that state.
12042 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12043 next set of TODO \
12044 keywords (nextset).
12045 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12046 prefix, circumvent any state blocking.
12047 With a numeric prefix arg of 0, inhibit note taking for the change.
12048 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12050 When called through ELisp, arg is also interpreted in the following way:
12051 `none' -> empty state
12052 \"\" -> switch to empty state
12053 `done' -> switch to DONE
12054 `nextset' -> switch to the next set of keywords
12055 `previousset' -> switch to the previous set of keywords
12056 \"WAITING\" -> switch to the specified keyword, but only if it
12057 really is a member of `org-todo-keywords'."
12058 (interactive "P")
12059 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12060 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12061 'region-start-level 'region))
12062 org-loop-over-headlines-in-active-region)
12063 (org-map-entries
12064 `(org-todo ,arg)
12065 org-loop-over-headlines-in-active-region
12066 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12067 (when (equal arg '(16)) (setq arg 'nextset))
12068 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12069 (let ((org-blocker-hook org-blocker-hook)
12070 commentp
12071 case-fold-search)
12072 (when (equal arg '(64))
12073 (setq arg nil org-blocker-hook nil))
12074 (when (and org-blocker-hook
12075 (or org-inhibit-blocking
12076 (org-entry-get nil "NOBLOCKING")))
12077 (setq org-blocker-hook nil))
12078 (save-excursion
12079 (catch 'exit
12080 (org-back-to-heading t)
12081 (when (org-in-commented-heading-p t)
12082 (org-toggle-comment)
12083 (setq commentp t))
12084 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12085 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12086 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12087 (let* ((match-data (match-data))
12088 (startpos (point-at-bol))
12089 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12090 (org-log-done org-log-done)
12091 (org-log-repeat org-log-repeat)
12092 (org-todo-log-states org-todo-log-states)
12093 (org-inhibit-logging
12094 (if (equal arg 0)
12095 (progn (setq arg nil) 'note) org-inhibit-logging))
12096 (this (match-string 1))
12097 (hl-pos (match-beginning 0))
12098 (head (org-get-todo-sequence-head this))
12099 (ass (assoc head org-todo-kwd-alist))
12100 (interpret (nth 1 ass))
12101 (done-word (nth 3 ass))
12102 (final-done-word (nth 4 ass))
12103 (org-last-state (or this ""))
12104 (completion-ignore-case t)
12105 (member (member this org-todo-keywords-1))
12106 (tail (cdr member))
12107 (org-state (cond
12108 ((and org-todo-key-trigger
12109 (or (and (equal arg '(4))
12110 (eq org-use-fast-todo-selection 'prefix))
12111 (and (not arg) org-use-fast-todo-selection
12112 (not (eq org-use-fast-todo-selection
12113 'prefix)))))
12114 ;; Use fast selection.
12115 (org-fast-todo-selection))
12116 ((and (equal arg '(4))
12117 (or (not org-use-fast-todo-selection)
12118 (not org-todo-key-trigger)))
12119 ;; Read a state with completion.
12120 (completing-read
12121 "State: " (mapcar #'list org-todo-keywords-1)
12122 nil t))
12123 ((eq arg 'right)
12124 (if this
12125 (if tail (car tail) nil)
12126 (car org-todo-keywords-1)))
12127 ((eq arg 'left)
12128 (unless (equal member org-todo-keywords-1)
12129 (if this
12130 (nth (- (length org-todo-keywords-1)
12131 (length tail) 2)
12132 org-todo-keywords-1)
12133 (org-last org-todo-keywords-1))))
12134 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12135 (setq arg nil))) ;hack to fall back to cycling
12136 (arg
12137 ;; User or caller requests a specific state.
12138 (cond
12139 ((equal arg "") nil)
12140 ((eq arg 'none) nil)
12141 ((eq arg 'done) (or done-word (car org-done-keywords)))
12142 ((eq arg 'nextset)
12143 (or (car (cdr (member head org-todo-heads)))
12144 (car org-todo-heads)))
12145 ((eq arg 'previousset)
12146 (let ((org-todo-heads (reverse org-todo-heads)))
12147 (or (car (cdr (member head org-todo-heads)))
12148 (car org-todo-heads))))
12149 ((car (member arg org-todo-keywords-1)))
12150 ((stringp arg)
12151 (user-error "State `%s' not valid in this file" arg))
12152 ((nth (1- (prefix-numeric-value arg))
12153 org-todo-keywords-1))))
12154 ((null member) (or head (car org-todo-keywords-1)))
12155 ((equal this final-done-word) nil) ;-> make empty
12156 ((null tail) nil) ;-> first entry
12157 ((memq interpret '(type priority))
12158 (if (eq this-command last-command)
12159 (car tail)
12160 (if (> (length tail) 0)
12161 (or done-word (car org-done-keywords))
12162 nil)))
12164 (car tail))))
12165 (org-state (or
12166 (run-hook-with-args-until-success
12167 'org-todo-get-default-hook org-state org-last-state)
12168 org-state))
12169 (next (if org-state (concat " " org-state " ") " "))
12170 (change-plist (list :type 'todo-state-change :from this :to org-state
12171 :position startpos))
12172 dolog now-done-p)
12173 (when org-blocker-hook
12174 (let (org-blocked-by-checkboxes block-reason)
12175 (setq org-last-todo-state-is-todo
12176 (not (member this org-done-keywords)))
12177 (unless (save-excursion
12178 (save-match-data
12179 (org-with-wide-buffer
12180 (run-hook-with-args-until-failure
12181 'org-blocker-hook change-plist))))
12182 (setq block-reason (if org-blocked-by-checkboxes
12183 "contained checkboxes"
12184 (format "\"%s\"" org-block-entry-blocking)))
12185 (if (called-interactively-p 'interactive)
12186 (user-error "TODO state change from %s to %s blocked (by %s)"
12187 this org-state block-reason)
12188 ;; Fail silently.
12189 (message "TODO state change from %s to %s blocked (by %s)"
12190 this org-state block-reason)
12191 (throw 'exit nil)))))
12192 (store-match-data match-data)
12193 (replace-match next t t)
12194 (cond ((equal this org-state)
12195 (message "TODO state was already %s" (org-trim next)))
12196 ((not (pos-visible-in-window-p hl-pos))
12197 (message "TODO state changed to %s" (org-trim next))))
12198 (unless head
12199 (setq head (org-get-todo-sequence-head org-state)
12200 ass (assoc head org-todo-kwd-alist)
12201 interpret (nth 1 ass)
12202 done-word (nth 3 ass)
12203 final-done-word (nth 4 ass)))
12204 (when (memq arg '(nextset previousset))
12205 (message "Keyword-Set %d/%d: %s"
12206 (- (length org-todo-sets) -1
12207 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12208 (length org-todo-sets)
12209 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12210 (setq org-last-todo-state-is-todo
12211 (not (member org-state org-done-keywords)))
12212 (setq now-done-p (and (member org-state org-done-keywords)
12213 (not (member this org-done-keywords))))
12214 (and logging (org-local-logging logging))
12215 (when (and (or org-todo-log-states org-log-done)
12216 (not (eq org-inhibit-logging t))
12217 (not (memq arg '(nextset previousset))))
12218 ;; We need to look at recording a time and note.
12219 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12220 (nth 2 (assoc this org-todo-log-states))))
12221 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12222 (setq dolog 'time))
12223 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12224 (and org-state
12225 (member org-state org-not-done-keywords)
12226 (not (member this org-not-done-keywords))))
12227 ;; This is now a todo state and was not one before
12228 ;; If there was a CLOSED time stamp, get rid of it.
12229 (org-add-planning-info nil nil 'closed))
12230 (when (and now-done-p org-log-done)
12231 ;; It is now done, and it was not done before.
12232 (org-add-planning-info 'closed (org-current-effective-time))
12233 (when (and (not dolog) (eq 'note org-log-done))
12234 (org-add-log-setup 'done org-state this 'note)))
12235 (when (and org-state dolog)
12236 ;; This is a non-nil state, and we need to log it.
12237 (org-add-log-setup 'state org-state this dolog)))
12238 ;; Fixup tag positioning.
12239 (org-todo-trigger-tag-changes org-state)
12240 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12241 (when org-provide-todo-statistics
12242 (org-update-parent-todo-statistics))
12243 (run-hooks 'org-after-todo-state-change-hook)
12244 (when (and arg (not (member org-state org-done-keywords)))
12245 (setq head (org-get-todo-sequence-head org-state)))
12246 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12247 ;; Do we need to trigger a repeat?
12248 (when now-done-p
12249 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12250 ;; This is for the agenda, take a snapshot of the headline.
12251 (save-match-data
12252 (setq org-agenda-headline-snapshot-before-repeat
12253 (org-get-heading))))
12254 (org-auto-repeat-maybe org-state))
12255 ;; Fixup cursor location if close to the keyword.
12256 (when (and (outline-on-heading-p)
12257 (not (bolp))
12258 (save-excursion (beginning-of-line 1)
12259 (looking-at org-todo-line-regexp))
12260 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12261 (goto-char (or (match-end 2) (match-end 1)))
12262 (and (looking-at " ") (just-one-space)))
12263 (when org-trigger-hook
12264 (save-excursion
12265 (run-hook-with-args 'org-trigger-hook change-plist)))
12266 (when commentp (org-toggle-comment))))))))
12268 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12269 "Block turning an entry into a TODO, using the hierarchy.
12270 This checks whether the current task should be blocked from state
12271 changes. Such blocking occurs when:
12273 1. The task has children which are not all in a completed state.
12275 2. A task has a parent with the property :ORDERED:, and there
12276 are siblings prior to the current task with incomplete
12277 status.
12279 3. The parent of the task is blocked because it has siblings that should
12280 be done first, or is child of a block grandparent TODO entry."
12282 (if (not org-enforce-todo-dependencies)
12283 t ; if locally turned off don't block
12284 (catch 'dont-block
12285 ;; If this is not a todo state change, or if this entry is already DONE,
12286 ;; do not block
12287 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12288 (member (plist-get change-plist :from)
12289 (cons 'done org-done-keywords))
12290 (member (plist-get change-plist :to)
12291 (cons 'todo org-not-done-keywords))
12292 (not (plist-get change-plist :to)))
12293 (throw 'dont-block t))
12294 ;; If this task has children, and any are undone, it's blocked
12295 (save-excursion
12296 (org-back-to-heading t)
12297 (let ((this-level (funcall outline-level)))
12298 (outline-next-heading)
12299 (let ((child-level (funcall outline-level)))
12300 (while (and (not (eobp))
12301 (> child-level this-level))
12302 ;; this todo has children, check whether they are all
12303 ;; completed
12304 (when (and (not (org-entry-is-done-p))
12305 (org-entry-is-todo-p))
12306 (setq org-block-entry-blocking (org-get-heading))
12307 (throw 'dont-block nil))
12308 (outline-next-heading)
12309 (setq child-level (funcall outline-level))))))
12310 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12311 ;; any previous siblings are undone, it's blocked
12312 (save-excursion
12313 (org-back-to-heading t)
12314 (let* ((pos (point))
12315 (parent-pos (and (org-up-heading-safe) (point)))
12316 (case-fold-search nil))
12317 (unless parent-pos (throw 'dont-block t)) ; no parent
12318 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12319 (forward-line 1)
12320 (re-search-forward org-not-done-heading-regexp pos t))
12321 (setq org-block-entry-blocking (match-string 0))
12322 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12323 ;; Search further up the hierarchy, to see if an ancestor is blocked
12324 (while t
12325 (goto-char parent-pos)
12326 (unless (looking-at org-not-done-heading-regexp)
12327 (throw 'dont-block t)) ; do not block, parent is not a TODO
12328 (setq pos (point))
12329 (setq parent-pos (and (org-up-heading-safe) (point)))
12330 (unless parent-pos (throw 'dont-block t)) ; no parent
12331 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12332 (forward-line 1)
12333 (re-search-forward org-not-done-heading-regexp pos t)
12334 (setq org-block-entry-blocking (org-get-heading)))
12335 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12337 (defcustom org-track-ordered-property-with-tag nil
12338 "Should the ORDERED property also be shown as a tag?
12339 The ORDERED property decides if an entry should require subtasks to be
12340 completed in sequence. Since a property is not very visible, setting
12341 this option means that toggling the ORDERED property with the command
12342 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12343 not relevant for the behavior, but it makes things more visible.
12345 Note that toggling the tag with tags commands will not change the property
12346 and therefore not influence behavior!
12348 This can be t, meaning the tag ORDERED should be used, It can also be a
12349 string to select a different tag for this task."
12350 :group 'org-todo
12351 :type '(choice
12352 (const :tag "No tracking" nil)
12353 (const :tag "Track with ORDERED tag" t)
12354 (string :tag "Use other tag")))
12356 (defun org-toggle-ordered-property ()
12357 "Toggle the ORDERED property of the current entry.
12358 For better visibility, you can track the value of this property with a tag.
12359 See variable `org-track-ordered-property-with-tag'."
12360 (interactive)
12361 (let* ((t1 org-track-ordered-property-with-tag)
12362 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12363 (save-excursion
12364 (org-back-to-heading)
12365 (if (org-entry-get nil "ORDERED")
12366 (progn
12367 (org-delete-property "ORDERED")
12368 (and tag (org-toggle-tag tag 'off))
12369 (message "Subtasks can be completed in arbitrary order"))
12370 (org-entry-put nil "ORDERED" "t")
12371 (and tag (org-toggle-tag tag 'on))
12372 (message "Subtasks must be completed in sequence")))))
12374 (defun org-block-todo-from-checkboxes (change-plist)
12375 "Block turning an entry into a TODO, using checkboxes.
12376 This checks whether the current task should be blocked from state
12377 changes because there are unchecked boxes in this entry."
12378 (if (not org-enforce-todo-checkbox-dependencies)
12379 t ; if locally turned off don't block
12380 (catch 'dont-block
12381 ;; If this is not a todo state change, or if this entry is already DONE,
12382 ;; do not block
12383 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12384 (member (plist-get change-plist :from)
12385 (cons 'done org-done-keywords))
12386 (member (plist-get change-plist :to)
12387 (cons 'todo org-not-done-keywords))
12388 (not (plist-get change-plist :to)))
12389 (throw 'dont-block t))
12390 ;; If this task has checkboxes that are not checked, it's blocked
12391 (save-excursion
12392 (org-back-to-heading t)
12393 (let ((beg (point)) end)
12394 (outline-next-heading)
12395 (setq end (point))
12396 (goto-char beg)
12397 (when (org-list-search-forward
12398 (concat (org-item-beginning-re)
12399 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12400 "\\[[- ]\\]")
12401 end t)
12402 (when (boundp 'org-blocked-by-checkboxes)
12403 (setq org-blocked-by-checkboxes t))
12404 (throw 'dont-block nil))))
12405 t))) ; do not block
12407 (defun org-entry-blocked-p ()
12408 "Non-nil if entry at point is blocked."
12409 (and (not (org-entry-get nil "NOBLOCKING"))
12410 (member (org-entry-get nil "TODO") org-not-done-keywords)
12411 (not (run-hook-with-args-until-failure
12412 'org-blocker-hook
12413 (list :type 'todo-state-change
12414 :position (point)
12415 :from 'todo
12416 :to 'done)))))
12418 (defun org-update-statistics-cookies (all)
12419 "Update the statistics cookie, either from TODO or from checkboxes.
12420 This should be called with the cursor in a line with a statistics
12421 cookie. When called with a \\[universal-argument] prefix, update
12422 all statistics cookies in the buffer."
12423 (interactive "P")
12424 (if all
12425 (progn
12426 (org-update-checkbox-count 'all)
12427 (org-map-entries 'org-update-parent-todo-statistics))
12428 (if (not (org-at-heading-p))
12429 (org-update-checkbox-count)
12430 (let ((pos (point-marker))
12431 end l1 l2)
12432 (ignore-errors (org-back-to-heading t))
12433 (if (not (org-at-heading-p))
12434 (org-update-checkbox-count)
12435 (setq l1 (org-outline-level))
12436 (setq end (save-excursion
12437 (outline-next-heading)
12438 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12439 (point)))
12440 (if (and (save-excursion
12441 (re-search-forward
12442 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12443 (not (save-excursion (re-search-forward
12444 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12445 (org-update-checkbox-count)
12446 (if (and l2 (> l2 l1))
12447 (progn
12448 (goto-char end)
12449 (org-update-parent-todo-statistics))
12450 (goto-char pos)
12451 (beginning-of-line 1)
12452 (while (re-search-forward
12453 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12454 (point-at-eol) t)
12455 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12456 (goto-char pos)
12457 (move-marker pos nil)))))
12459 (defvar org-entry-property-inherited-from) ;; defined below
12460 (defun org-update-parent-todo-statistics ()
12461 "Update any statistics cookie in the parent of the current headline.
12462 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12463 the entire subtree and this will travel up the hierarchy and update
12464 statistics everywhere."
12465 (let* ((prop (save-excursion (org-up-heading-safe)
12466 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12467 (recursive (or (not org-hierarchical-todo-statistics)
12468 (and prop (string-match "\\<recursive\\>" prop))))
12469 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12471 (first t)
12472 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12473 level ltoggle l1 new ndel
12474 (cnt-all 0) (cnt-done 0) is-percent kwd
12475 checkbox-beg cookie-present)
12476 (catch 'exit
12477 (save-excursion
12478 (beginning-of-line 1)
12479 (setq ltoggle (funcall outline-level))
12480 ;; Three situations are to consider:
12482 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12483 ;; to the top-level ancestor on the headline;
12485 ;; 2. If parent has "recursive" property, repeat up to the
12486 ;; headline setting that property, taking inheritance into
12487 ;; account;
12489 ;; 3. Else, move up to direct parent and proceed only once.
12490 (while (and (setq level (org-up-heading-safe))
12491 (or recursive first)
12492 (>= (point) lim))
12493 (setq first nil cookie-present nil)
12494 (unless (and level
12495 (not (string-match
12496 "\\<checkbox\\>"
12497 (downcase (or (org-entry-get nil "COOKIE_DATA")
12498 "")))))
12499 (throw 'exit nil))
12500 (while (re-search-forward box-re (point-at-eol) t)
12501 (setq cnt-all 0 cnt-done 0 cookie-present t)
12502 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12503 (save-match-data
12504 (unless (outline-next-heading) (throw 'exit nil))
12505 (while (and (looking-at org-complex-heading-regexp)
12506 (> (setq l1 (length (match-string 1))) level))
12507 (setq kwd (and (or recursive (= l1 ltoggle))
12508 (match-string 2)))
12509 (if (or (eq org-provide-todo-statistics 'all-headlines)
12510 (and (eq org-provide-todo-statistics t)
12511 (or (member kwd org-done-keywords)))
12512 (and (listp org-provide-todo-statistics)
12513 (stringp (car org-provide-todo-statistics))
12514 (or (member kwd org-provide-todo-statistics)
12515 (member kwd org-done-keywords)))
12516 (and (listp org-provide-todo-statistics)
12517 (listp (car org-provide-todo-statistics))
12518 (or (member kwd (car org-provide-todo-statistics))
12519 (and (member kwd org-done-keywords)
12520 (member kwd (cadr org-provide-todo-statistics))))))
12521 (setq cnt-all (1+ cnt-all))
12522 (and (eq org-provide-todo-statistics t)
12524 (setq cnt-all (1+ cnt-all))))
12525 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12526 (member kwd org-done-keywords))
12527 (and (listp org-provide-todo-statistics)
12528 (listp (car org-provide-todo-statistics))
12529 (member kwd org-done-keywords)
12530 (member kwd (cadr org-provide-todo-statistics)))
12531 (and (listp org-provide-todo-statistics)
12532 (stringp (car org-provide-todo-statistics))
12533 (member kwd org-done-keywords)))
12534 (setq cnt-done (1+ cnt-done)))
12535 (outline-next-heading)))
12536 (setq new
12537 (if is-percent
12538 (format "[%d%%]" (floor (* 100.0 cnt-done)
12539 (max 1 cnt-all)))
12540 (format "[%d/%d]" cnt-done cnt-all))
12541 ndel (- (match-end 0) checkbox-beg))
12542 (goto-char checkbox-beg)
12543 (insert new)
12544 (delete-region (point) (+ (point) ndel))
12545 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12546 (when cookie-present
12547 (run-hook-with-args 'org-after-todo-statistics-hook
12548 cnt-done (- cnt-all cnt-done))))))
12549 (run-hooks 'org-todo-statistics-hook)))
12551 (defvar org-after-todo-statistics-hook nil
12552 "Hook that is called after a TODO statistics cookie has been updated.
12553 Each function is called with two arguments: the number of not-done entries
12554 and the number of done entries.
12556 For example, the following function, when added to this hook, will switch
12557 an entry to DONE when all children are done, and back to TODO when new
12558 entries are set to a TODO status. Note that this hook is only called
12559 when there is a statistics cookie in the headline!
12561 (defun org-summary-todo (n-done n-not-done)
12562 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12563 (let (org-log-done org-log-states) ; turn off logging
12564 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12567 (defvar org-todo-statistics-hook nil
12568 "Hook that is run whenever Org thinks TODO statistics should be updated.
12569 This hook runs even if there is no statistics cookie present, in which case
12570 `org-after-todo-statistics-hook' would not run.")
12572 (defun org-todo-trigger-tag-changes (state)
12573 "Apply the changes defined in `org-todo-state-tags-triggers'."
12574 (let ((l org-todo-state-tags-triggers)
12575 changes)
12576 (when (or (not state) (equal state ""))
12577 (setq changes (append changes (cdr (assoc "" l)))))
12578 (when (and (stringp state) (> (length state) 0))
12579 (setq changes (append changes (cdr (assoc state l)))))
12580 (when (member state org-not-done-keywords)
12581 (setq changes (append changes (cdr (assq 'todo l)))))
12582 (when (member state org-done-keywords)
12583 (setq changes (append changes (cdr (assq 'done l)))))
12584 (dolist (c changes)
12585 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12587 (defun org-local-logging (value)
12588 "Get logging settings from a property VALUE."
12589 ;; Directly set the variables, they are already local.
12590 (setq org-log-done nil
12591 org-log-repeat nil
12592 org-todo-log-states nil)
12593 (dolist (w (split-string value))
12594 (let (a)
12595 (cond
12596 ((setq a (assoc w org-startup-options))
12597 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12598 (set (nth 1 a) (nth 2 a))))
12599 ((setq a (org-extract-log-state-settings w))
12600 (and (member (car a) org-todo-keywords-1)
12601 (push a org-todo-log-states)))))))
12603 (defun org-get-todo-sequence-head (kwd)
12604 "Return the head of the TODO sequence to which KWD belongs.
12605 If KWD is not set, check if there is a text property remembering the
12606 right sequence."
12607 (let (p)
12608 (cond
12609 ((not kwd)
12610 (or (get-text-property (point-at-bol) 'org-todo-head)
12611 (progn
12612 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12613 nil (point-at-eol)))
12614 (get-text-property p 'org-todo-head))))
12615 ((not (member kwd org-todo-keywords-1))
12616 (car org-todo-keywords-1))
12617 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12619 (defun org-fast-todo-selection ()
12620 "Fast TODO keyword selection with single keys.
12621 Returns the new TODO keyword, or nil if no state change should occur."
12622 (let* ((fulltable org-todo-key-alist)
12623 (done-keywords org-done-keywords) ;; needed for the faces.
12624 (maxlen (apply 'max (mapcar
12625 (lambda (x)
12626 (if (stringp (car x)) (string-width (car x)) 0))
12627 fulltable)))
12628 (expert nil)
12629 (fwidth (+ maxlen 3 1 3))
12630 (ncol (/ (- (window-width) 4) fwidth))
12631 tg cnt e c tbl
12632 groups ingroup)
12633 (save-excursion
12634 (save-window-excursion
12635 (if expert
12636 (set-buffer (get-buffer-create " *Org todo*"))
12637 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12638 (erase-buffer)
12639 (setq-local org-done-keywords done-keywords)
12640 (setq tbl fulltable cnt 0)
12641 (while (setq e (pop tbl))
12642 (cond
12643 ((equal e '(:startgroup))
12644 (push '() groups) (setq ingroup t)
12645 (unless (= cnt 0)
12646 (setq cnt 0)
12647 (insert "\n"))
12648 (insert "{ "))
12649 ((equal e '(:endgroup))
12650 (setq ingroup nil cnt 0)
12651 (insert "}\n"))
12652 ((equal e '(:newline))
12653 (unless (= cnt 0)
12654 (setq cnt 0)
12655 (insert "\n")
12656 (setq e (car tbl))
12657 (while (equal (car tbl) '(:newline))
12658 (insert "\n")
12659 (setq tbl (cdr tbl)))))
12661 (setq tg (car e) c (cdr e))
12662 (when ingroup (push tg (car groups)))
12663 (setq tg (org-add-props tg nil 'face
12664 (org-get-todo-face tg)))
12665 (when (and (= cnt 0) (not ingroup)) (insert " "))
12666 (insert "[" c "] " tg (make-string
12667 (- fwidth 4 (length tg)) ?\ ))
12668 (when (= (setq cnt (1+ cnt)) ncol)
12669 (insert "\n")
12670 (when ingroup (insert " "))
12671 (setq cnt 0)))))
12672 (insert "\n")
12673 (goto-char (point-min))
12674 (unless expert (org-fit-window-to-buffer))
12675 (message "[a-z..]:Set [SPC]:clear")
12676 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12677 (cond
12678 ((or (= c ?\C-g)
12679 (and (= c ?q) (not (rassoc c fulltable))))
12680 (setq quit-flag t))
12681 ((= c ?\ ) nil)
12682 ((setq e (rassoc c fulltable) tg (car e))
12684 (t (setq quit-flag t)))))))
12686 (defun org-entry-is-todo-p ()
12687 (member (org-get-todo-state) org-not-done-keywords))
12689 (defun org-entry-is-done-p ()
12690 (member (org-get-todo-state) org-done-keywords))
12692 (defun org-get-todo-state ()
12693 "Return the TODO keyword of the current subtree."
12694 (save-excursion
12695 (org-back-to-heading t)
12696 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12697 (match-end 2)
12698 (match-string 2))))
12700 (defun org-at-date-range-p (&optional inactive-ok)
12701 "Non-nil if point is inside a date range.
12703 When optional argument INACTIVE-OK is non-nil, also consider
12704 inactive time ranges.
12706 When this function returns a non-nil value, match data is set
12707 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12708 on INACTIVE-OK."
12709 (interactive)
12710 (save-excursion
12711 (catch 'exit
12712 (let ((pos (point)))
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 (skip-chars-backward "^<[\r\n")
12719 (skip-chars-backward "<[")
12720 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12721 (>= (match-end 0) pos)
12722 (throw 'exit t)))
12723 nil)))
12725 (defun org-get-repeat (&optional timestamp)
12726 "Check if there is a time-stamp with repeater in this entry.
12728 Return the repeater, as a string, or nil. Also return nil when
12729 this function is called before first heading.
12731 When optional argument TIMESTAMP is a string, extract the
12732 repeater from there instead."
12733 (save-match-data
12734 (cond (timestamp
12735 (and (string-match org-repeat-re timestamp)
12736 (match-string-no-properties 1 timestamp)))
12737 ((org-before-first-heading-p) nil)
12739 (save-excursion
12740 (org-back-to-heading t)
12741 (let ((end (org-entry-end-position)))
12742 (catch :repeat
12743 (while (re-search-forward org-repeat-re end t)
12744 (when (save-match-data (org-at-timestamp-p 'agenda))
12745 (throw :repeat (match-string-no-properties 1)))))))))))
12747 (defvar org-last-changed-timestamp)
12748 (defvar org-last-inserted-timestamp)
12749 (defvar org-log-post-message)
12750 (defvar org-log-note-purpose)
12751 (defvar org-log-note-how nil)
12752 (defvar org-log-note-extra)
12753 (defun org-auto-repeat-maybe (done-word)
12754 "Check if the current headline contains a repeated time-stamp.
12756 If yes, set TODO state back to what it was and change the base date
12757 of repeating deadline/scheduled time stamps to new date.
12759 This function is run automatically after each state change to a DONE state."
12760 (let* ((repeat (org-get-repeat))
12761 (aa (assoc org-last-state org-todo-kwd-alist))
12762 (interpret (nth 1 aa))
12763 (head (nth 2 aa))
12764 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12765 (msg "Entry repeats: ")
12766 (org-log-done nil)
12767 (org-todo-log-states nil)
12768 (end (copy-marker (org-entry-end-position))))
12769 (unwind-protect
12770 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12771 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12772 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12773 org-todo-repeat-to-state)))
12774 (org-todo (cond
12775 ((and to-state (member to-state org-todo-keywords-1))
12776 to-state)
12777 ((eq interpret 'type) org-last-state)
12778 (head)
12779 (t 'none))))
12780 (org-back-to-heading t)
12781 (org-add-planning-info nil nil 'closed)
12782 ;; When `org-log-repeat' is non-nil or entry contains
12783 ;; a clock, set LAST_REPEAT property.
12784 (when (or org-log-repeat
12785 (catch :clock
12786 (save-excursion
12787 (while (re-search-forward org-clock-line-re end t)
12788 (when (org-at-clock-log-p) (throw :clock t))))))
12789 (org-entry-put nil "LAST_REPEAT" (format-time-string
12790 (org-time-stamp-format t t)
12791 (current-time))))
12792 (when org-log-repeat
12793 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12794 (memq 'org-add-log-note post-command-hook))
12795 ;; We are already setup for some record.
12796 (when (eq org-log-repeat 'note)
12797 ;; Make sure we take a note, not only a time stamp.
12798 (setq org-log-note-how 'note))
12799 ;; Set up for taking a record.
12800 (org-add-log-setup 'state
12801 (or done-word (car org-done-keywords))
12802 org-last-state
12803 org-log-repeat)))
12804 (let ((planning-re (regexp-opt
12805 (list org-scheduled-string org-deadline-string))))
12806 (while (re-search-forward org-ts-regexp end t)
12807 (let* ((ts (match-string 0))
12808 (planning? (org-at-planning-p))
12809 (type (if (not planning?) "Plain:"
12810 (save-excursion
12811 (re-search-backward
12812 planning-re (line-beginning-position) t)
12813 (match-string 0)))))
12814 (cond
12815 ;; Ignore fake time-stamps (e.g., within comments).
12816 ((not (org-at-timestamp-p 'agenda)))
12817 ;; Time-stamps without a repeater are usually
12818 ;; skipped. However, a SCHEDULED time-stamp without
12819 ;; one is removed, as they are no longer relevant.
12820 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12821 ts))
12822 (when (equal type org-scheduled-string)
12823 (org-remove-timestamp-with-keyword type)))
12825 (let ((n (string-to-number (match-string 2 ts)))
12826 (what (match-string 3 ts)))
12827 (when (equal what "w") (setq n (* n 7) what "d"))
12828 (when (and (equal what "h")
12829 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12830 ts)))
12831 (user-error
12832 "Cannot repeat in Repeat in %d hour(s) because no hour \
12833 has been set"
12835 ;; Preparation, see if we need to modify the start
12836 ;; date for the change.
12837 (when (match-end 1)
12838 (let ((time (save-match-data
12839 (org-time-string-to-time ts))))
12840 (cond
12841 ((equal (match-string 1 ts) ".")
12842 ;; Shift starting date to today
12843 (org-timestamp-change
12844 (- (org-today) (time-to-days time))
12845 'day))
12846 ((equal (match-string 1 ts) "+")
12847 (let ((nshiftmax 10)
12848 (nshift 0))
12849 (while (or (= nshift 0)
12850 (not (time-less-p (current-time) time)))
12851 (when (= (cl-incf nshift) nshiftmax)
12852 (or (y-or-n-p
12853 (format "%d repeater intervals were not \
12854 enough to shift date past today. Continue? "
12855 nshift))
12856 (user-error "Abort")))
12857 (org-timestamp-change n (cdr (assoc what whata)))
12858 (org-in-regexp org-ts-regexp3)
12859 (setq ts (match-string 1))
12860 (setq time
12861 (save-match-data
12862 (org-time-string-to-time ts)))))
12863 (org-timestamp-change (- n) (cdr (assoc what whata)))
12864 ;; Rematch, so that we have everything in place
12865 ;; for the real shift.
12866 (org-in-regexp org-ts-regexp3)
12867 (setq ts (match-string 1))
12868 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12869 ts)))))
12870 (save-excursion
12871 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12872 (setq msg
12873 (concat
12874 msg type " " org-last-changed-timestamp " "))))))))
12875 (setq org-log-post-message msg)
12876 (message "%s" msg))
12877 (set-marker end nil))))
12879 (defun org-show-todo-tree (arg)
12880 "Make a compact tree which shows all headlines marked with TODO.
12881 The tree will show the lines where the regexp matches, and all higher
12882 headlines above the match.
12883 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12884 With a numeric prefix N, construct a sparse tree for the Nth element
12885 of `org-todo-keywords-1'."
12886 (interactive "P")
12887 (let ((case-fold-search nil)
12888 (kwd-re
12889 (cond ((null arg) org-not-done-regexp)
12890 ((equal arg '(4))
12891 (let ((kwd
12892 (completing-read "Keyword (or KWD1|KWD2|...): "
12893 (mapcar #'list org-todo-keywords-1))))
12894 (concat "\\("
12895 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12896 "\\)\\>")))
12897 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12898 (regexp-quote (nth (1- (prefix-numeric-value arg))
12899 org-todo-keywords-1)))
12900 (t (user-error "Invalid prefix argument: %s" arg)))))
12901 (message "%d TODO entries found"
12902 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12904 (defun org--deadline-or-schedule (arg type time)
12905 "Insert DEADLINE or SCHEDULE information in current entry.
12906 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12907 `org-schedule' for information about ARG and TIME arguments."
12908 (let* ((deadline? (eq type 'deadline))
12909 (keyword (if deadline? org-deadline-string org-scheduled-string))
12910 (log (if deadline? org-log-redeadline org-log-reschedule))
12911 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12912 (old-date-time (and old-date (org-time-string-to-time old-date)))
12913 ;; Save repeater cookie from either TIME or current scheduled
12914 ;; time stamp. We are going to insert it back at the end of
12915 ;; the process.
12916 (repeater (or (and (org-string-nw-p time)
12917 ;; We use `org-repeat-re' because we need
12918 ;; to tell the difference between a real
12919 ;; repeater and a time delta, e.g. "+2d".
12920 (string-match org-repeat-re time)
12921 (match-string 1 time))
12922 (and (org-string-nw-p old-date)
12923 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12924 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12925 old-date)
12926 (match-string 1 old-date)))))
12927 (pcase arg
12928 (`(4)
12929 (when (and old-date log)
12930 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12931 nil old-date log))
12932 (org-remove-timestamp-with-keyword keyword)
12933 (message (if deadline? "Item no longer has a deadline."
12934 "Item is no longer scheduled.")))
12935 (`(16)
12936 (save-excursion
12937 (org-back-to-heading t)
12938 (let ((regexp (if deadline? org-deadline-time-regexp
12939 org-scheduled-time-regexp)))
12940 (if (not (re-search-forward regexp (line-end-position 2) t))
12941 (user-error (if deadline? "No deadline information to update"
12942 "No scheduled information to update"))
12943 (let* ((rpl0 (match-string 1))
12944 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12945 (msg (if deadline? "Warn starting from" "Delay until")))
12946 (replace-match
12947 (concat keyword
12948 " <" rpl
12949 (format " -%dd"
12950 (abs (- (time-to-days
12951 (save-match-data
12952 (org-read-date
12953 nil t nil msg old-date-time)))
12954 (time-to-days old-date-time))))
12955 ">") t t))))))
12957 (org-add-planning-info type time 'closed)
12958 (when (and old-date
12960 (not (equal old-date org-last-inserted-timestamp)))
12961 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12962 org-last-inserted-timestamp
12963 old-date
12964 log))
12965 (when repeater
12966 (save-excursion
12967 (org-back-to-heading t)
12968 (when (re-search-forward
12969 (concat keyword " " org-last-inserted-timestamp)
12970 (line-end-position 2)
12972 (goto-char (1- (match-end 0)))
12973 (insert " " repeater)
12974 (setq org-last-inserted-timestamp
12975 (concat (substring org-last-inserted-timestamp 0 -1)
12976 " " repeater
12977 (substring org-last-inserted-timestamp -1))))))
12978 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12979 org-last-inserted-timestamp)))))
12981 (defun org-deadline (arg &optional time)
12982 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12983 With one universal prefix argument, remove any deadline from the item.
12984 With two universal prefix arguments, prompt for a warning delay.
12985 With argument TIME, set the deadline at the corresponding date. TIME
12986 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12987 (interactive "P")
12988 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12989 (org-map-entries
12990 (lambda () (org--deadline-or-schedule arg 'deadline time))
12992 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12993 'region-start-level
12994 'region)
12995 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12996 (org--deadline-or-schedule arg 'deadline time)))
12998 (defun org-schedule (arg &optional time)
12999 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13000 With one universal prefix argument, remove any scheduling date from the item.
13001 With two universal prefix arguments, prompt for a delay cookie.
13002 With argument TIME, scheduled at the corresponding date. TIME can
13003 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13004 (interactive "P")
13005 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13006 (org-map-entries
13007 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13009 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13010 'region-start-level
13011 'region)
13012 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13013 (org--deadline-or-schedule arg 'scheduled time)))
13015 (defun org-get-scheduled-time (pom &optional inherit)
13016 "Get the scheduled time as a time tuple, of a format suitable
13017 for calling org-schedule with, or if there is no scheduling,
13018 returns nil."
13019 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13020 (when time
13021 (apply 'encode-time (org-parse-time-string time)))))
13023 (defun org-get-deadline-time (pom &optional inherit)
13024 "Get the deadline as a time tuple, of a format suitable for
13025 calling org-deadline with, or if there is no scheduling, returns
13026 nil."
13027 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13028 (when time
13029 (apply 'encode-time (org-parse-time-string time)))))
13031 (defun org-remove-timestamp-with-keyword (keyword)
13032 "Remove all time stamps with KEYWORD in the current entry."
13033 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13034 beg)
13035 (save-excursion
13036 (org-back-to-heading t)
13037 (setq beg (point))
13038 (outline-next-heading)
13039 (while (re-search-backward re beg t)
13040 (replace-match "")
13041 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13042 (equal (char-before) ?\ ))
13043 (backward-delete-char 1)
13044 (when (string-match "^[ \t]*$" (buffer-substring
13045 (point-at-bol) (point-at-eol)))
13046 (delete-region (point-at-bol)
13047 (min (point-max) (1+ (point-at-eol))))))))))
13049 (defvar org-time-was-given) ; dynamically scoped parameter
13050 (defvar org-end-time-was-given) ; dynamically scoped parameter
13052 (defun org-at-planning-p ()
13053 "Non-nil when point is on a planning info line."
13054 ;; This is as accurate and faster than `org-element-at-point' since
13055 ;; planning info location is fixed in the section.
13056 (org-with-wide-buffer
13057 (beginning-of-line)
13058 (and (looking-at-p org-planning-line-re)
13059 (eq (point)
13060 (ignore-errors
13061 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13062 (org-back-to-heading t)
13063 (org-with-limited-levels (org-back-to-heading t)))
13064 (line-beginning-position 2))))))
13066 (defun org-add-planning-info (what &optional time &rest remove)
13067 "Insert new timestamp with keyword in the planning line.
13068 WHAT indicates what kind of time stamp to add. It is a symbol
13069 among `closed', `deadline', `scheduled' and nil. TIME indicates
13070 the time to use. If none is given, the user is prompted for
13071 a date. REMOVE indicates what kind of entries to remove. An old
13072 WHAT entry will also be removed."
13073 (let (org-time-was-given org-end-time-was-given default-time default-input)
13074 (catch 'exit
13075 (when (and (memq what '(scheduled deadline))
13076 (or (not time)
13077 (and (stringp time)
13078 (string-match "^[-+]+[0-9]" time))))
13079 ;; Try to get a default date/time from existing timestamp
13080 (save-excursion
13081 (org-back-to-heading t)
13082 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13083 (when (re-search-forward (if (eq what 'scheduled)
13084 org-scheduled-time-regexp
13085 org-deadline-time-regexp)
13086 end t)
13087 (setq ts (match-string 1)
13088 default-time (apply 'encode-time (org-parse-time-string ts))
13089 default-input (and ts (org-get-compact-tod ts)))))))
13090 (when what
13091 (setq time
13092 (if (stringp time)
13093 ;; This is a string (relative or absolute), set
13094 ;; proper date.
13095 (apply #'encode-time
13096 (org-read-date-analyze
13097 time default-time (decode-time default-time)))
13098 ;; If necessary, get the time from the user
13099 (or time (org-read-date nil 'to-time nil nil
13100 default-time default-input)))))
13102 (org-with-wide-buffer
13103 (org-back-to-heading t)
13104 (forward-line)
13105 (unless (bolp) (insert "\n"))
13106 (cond ((looking-at-p org-planning-line-re)
13107 ;; Move to current indentation.
13108 (skip-chars-forward " \t")
13109 ;; Check if we have to remove something.
13110 (dolist (type (if what (cons what remove) remove))
13111 (save-excursion
13112 (when (re-search-forward
13113 (cl-case type
13114 (closed org-closed-time-regexp)
13115 (deadline org-deadline-time-regexp)
13116 (scheduled org-scheduled-time-regexp)
13117 (otherwise
13118 (error "Invalid planning type: %s" type)))
13119 (line-end-position) t)
13120 ;; Delete until next keyword or end of line.
13121 (delete-region
13122 (match-beginning 0)
13123 (if (re-search-forward org-keyword-time-not-clock-regexp
13124 (line-end-position)
13126 (match-beginning 0)
13127 (line-end-position))))))
13128 ;; If there is nothing more to add and no more keyword
13129 ;; is left, remove the line completely.
13130 (if (and (looking-at-p "[ \t]*$") (not what))
13131 (delete-region (line-beginning-position)
13132 (line-beginning-position 2))
13133 ;; If we removed last keyword, do not leave trailing
13134 ;; white space at the end of line.
13135 (let ((p (point)))
13136 (save-excursion
13137 (end-of-line)
13138 (unless (= (skip-chars-backward " \t" p) 0)
13139 (delete-region (point) (line-end-position)))))))
13140 ((not what) (throw 'exit nil)) ; Nothing to do.
13141 (t (insert-before-markers "\n")
13142 (backward-char 1)
13143 (when org-adapt-indentation
13144 (indent-to-column (1+ (org-outline-level))))))
13145 (when what
13146 ;; Insert planning keyword.
13147 (insert (cl-case what
13148 (closed org-closed-string)
13149 (deadline org-deadline-string)
13150 (scheduled org-scheduled-string)
13151 (otherwise (error "Invalid planning type: %s" what)))
13152 " ")
13153 ;; Insert associated timestamp.
13154 (let ((ts (org-insert-time-stamp
13155 time
13156 (or org-time-was-given
13157 (and (eq what 'closed) org-log-done-with-time))
13158 (eq what 'closed)
13159 nil nil (list org-end-time-was-given))))
13160 (unless (eolp) (insert " "))
13161 ts))))))
13163 (defvar org-log-note-marker (make-marker)
13164 "Marker pointing at the entry where the note is to be inserted.")
13165 (defvar org-log-note-purpose nil)
13166 (defvar org-log-note-state nil)
13167 (defvar org-log-note-previous-state nil)
13168 (defvar org-log-note-extra nil)
13169 (defvar org-log-note-window-configuration nil)
13170 (defvar org-log-note-return-to (make-marker))
13171 (defvar org-log-note-effective-time nil
13172 "Remembered current time so that dynamically scoped
13173 `org-extend-today-until' affects timestamps in state change log")
13175 (defvar org-log-post-message nil
13176 "Message to be displayed after a log note has been stored.
13177 The auto-repeater uses this.")
13179 (defun org-add-note ()
13180 "Add a note to the current entry.
13181 This is done in the same way as adding a state change note."
13182 (interactive)
13183 (org-add-log-setup 'note))
13185 (defun org-log-beginning (&optional create)
13186 "Return expected start of log notes in current entry.
13187 When optional argument CREATE is non-nil, the function creates
13188 a drawer to store notes, if necessary. Returned position ignores
13189 narrowing."
13190 (org-with-wide-buffer
13191 (let ((drawer (org-log-into-drawer)))
13192 (cond
13193 (drawer
13194 (org-end-of-meta-data)
13195 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13196 (end (if (org-at-heading-p) (point)
13197 (save-excursion (outline-next-heading) (point))))
13198 (case-fold-search t))
13199 (catch 'exit
13200 ;; Try to find existing drawer.
13201 (while (re-search-forward regexp end t)
13202 (let ((element (org-element-at-point)))
13203 (when (eq (org-element-type element) 'drawer)
13204 (let ((cend (org-element-property :contents-end element)))
13205 (when (and (not org-log-states-order-reversed) cend)
13206 (goto-char cend)))
13207 (throw 'exit nil))))
13208 ;; No drawer found. Create one, if permitted.
13209 (when create
13210 (unless (bolp) (insert "\n"))
13211 (let ((beg (point)))
13212 (insert ":" drawer ":\n:END:\n")
13213 (org-indent-region beg (point)))
13214 (end-of-line -1)))))
13216 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13217 (skip-chars-forward " \t\n")
13218 (beginning-of-line)
13219 (unless org-log-states-order-reversed
13220 (org-skip-over-state-notes)
13221 (skip-chars-backward " \t\n")
13222 (forward-line)))))
13223 (if (bolp) (point) (line-beginning-position 2))))
13225 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13226 "Set up the post command hook to take a note.
13227 If this is about to TODO state change, the new state is expected in STATE.
13228 HOW is an indicator what kind of note should be created.
13229 EXTRA is additional text that will be inserted into the notes buffer."
13230 (move-marker org-log-note-marker (point))
13231 (setq org-log-note-purpose purpose
13232 org-log-note-state state
13233 org-log-note-previous-state prev-state
13234 org-log-note-how how
13235 org-log-note-extra extra
13236 org-log-note-effective-time (org-current-effective-time))
13237 (add-hook 'post-command-hook 'org-add-log-note 'append))
13239 (defun org-skip-over-state-notes ()
13240 "Skip past the list of State notes in an entry."
13241 (when (ignore-errors (goto-char (org-in-item-p)))
13242 (let* ((struct (org-list-struct))
13243 (prevs (org-list-prevs-alist struct))
13244 (regexp
13245 (concat "[ \t]*- +"
13246 (replace-regexp-in-string
13247 " +" " +"
13248 (org-replace-escapes
13249 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13250 `(("%d" . ,org-ts-regexp-inactive)
13251 ("%D" . ,org-ts-regexp)
13252 ("%s" . "\"\\S-+\"")
13253 ("%S" . "\"\\S-+\"")
13254 ("%t" . ,org-ts-regexp-inactive)
13255 ("%T" . ,org-ts-regexp)
13256 ("%u" . ".*?")
13257 ("%U" . ".*?")))))))
13258 (while (looking-at-p regexp)
13259 (goto-char (or (org-list-get-next-item (point) struct prevs)
13260 (org-list-get-item-end (point) struct)))))))
13262 (defun org-add-log-note (&optional _purpose)
13263 "Pop up a window for taking a note, and add this note later."
13264 (remove-hook 'post-command-hook 'org-add-log-note)
13265 (setq org-log-note-window-configuration (current-window-configuration))
13266 (delete-other-windows)
13267 (move-marker org-log-note-return-to (point))
13268 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13269 (goto-char org-log-note-marker)
13270 (org-switch-to-buffer-other-window "*Org Note*")
13271 (erase-buffer)
13272 (if (memq org-log-note-how '(time state))
13273 (org-store-log-note)
13274 (let ((org-inhibit-startup t)) (org-mode))
13275 (insert (format "# Insert note for %s.
13276 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13277 (cond
13278 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13279 ((eq org-log-note-purpose 'done) "closed todo item")
13280 ((eq org-log-note-purpose 'state)
13281 (format "state change from \"%s\" to \"%s\""
13282 (or org-log-note-previous-state "")
13283 (or org-log-note-state "")))
13284 ((eq org-log-note-purpose 'reschedule)
13285 "rescheduling")
13286 ((eq org-log-note-purpose 'delschedule)
13287 "no longer scheduled")
13288 ((eq org-log-note-purpose 'redeadline)
13289 "changing deadline")
13290 ((eq org-log-note-purpose 'deldeadline)
13291 "removing deadline")
13292 ((eq org-log-note-purpose 'refile)
13293 "refiling")
13294 ((eq org-log-note-purpose 'note)
13295 "this entry")
13296 (t (error "This should not happen")))))
13297 (when org-log-note-extra (insert org-log-note-extra))
13298 (setq-local org-finish-function 'org-store-log-note)
13299 (run-hooks 'org-log-buffer-setup-hook)))
13301 (defvar org-note-abort nil) ; dynamically scoped
13302 (defun org-store-log-note ()
13303 "Finish taking a log note, and insert it to where it belongs."
13304 (let ((txt (prog1 (buffer-string)
13305 (kill-buffer)))
13306 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13307 lines)
13308 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13309 (setq txt (replace-match "" t t txt)))
13310 (when (string-match "\\s-+\\'" txt)
13311 (setq txt (replace-match "" t t txt)))
13312 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13313 (when (org-string-nw-p note)
13314 (setq note
13315 (org-replace-escapes
13316 note
13317 (list (cons "%u" (user-login-name))
13318 (cons "%U" user-full-name)
13319 (cons "%t" (format-time-string
13320 (org-time-stamp-format 'long 'inactive)
13321 org-log-note-effective-time))
13322 (cons "%T" (format-time-string
13323 (org-time-stamp-format 'long nil)
13324 org-log-note-effective-time))
13325 (cons "%d" (format-time-string
13326 (org-time-stamp-format nil 'inactive)
13327 org-log-note-effective-time))
13328 (cons "%D" (format-time-string
13329 (org-time-stamp-format nil nil)
13330 org-log-note-effective-time))
13331 (cons "%s" (cond
13332 ((not org-log-note-state) "")
13333 ((string-match-p org-ts-regexp
13334 org-log-note-state)
13335 (format "\"[%s]\""
13336 (substring org-log-note-state 1 -1)))
13337 (t (format "\"%s\"" org-log-note-state))))
13338 (cons "%S"
13339 (cond
13340 ((not org-log-note-previous-state) "")
13341 ((string-match-p org-ts-regexp
13342 org-log-note-previous-state)
13343 (format "\"[%s]\""
13344 (substring
13345 org-log-note-previous-state 1 -1)))
13346 (t (format "\"%s\""
13347 org-log-note-previous-state)))))))
13348 (when lines (setq note (concat note " \\\\")))
13349 (push note lines))
13350 (when (and lines (not org-note-abort))
13351 (with-current-buffer (marker-buffer org-log-note-marker)
13352 (org-with-wide-buffer
13353 ;; Find location for the new note.
13354 (goto-char org-log-note-marker)
13355 (set-marker org-log-note-marker nil)
13356 ;; Note associated to a clock is to be located right after
13357 ;; the clock. Do not move point.
13358 (unless (eq org-log-note-purpose 'clock-out)
13359 (goto-char (org-log-beginning t)))
13360 ;; Make sure point is at the beginning of an empty line.
13361 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13362 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13363 ;; In an existing list, add a new item at the top level.
13364 ;; Otherwise, indent line like a regular one.
13365 (let ((itemp (org-in-item-p)))
13366 (if itemp
13367 (indent-line-to
13368 (let ((struct (save-excursion
13369 (goto-char itemp) (org-list-struct))))
13370 (org-list-get-ind (org-list-get-top-point struct) struct)))
13371 (org-indent-line)))
13372 (insert (org-list-bullet-string "-") (pop lines))
13373 (let ((ind (org-list-item-body-column (line-beginning-position))))
13374 (dolist (line lines)
13375 (insert "\n")
13376 (indent-line-to ind)
13377 (insert line)))
13378 (message "Note stored")
13379 (org-back-to-heading t)
13380 (org-cycle-hide-drawers 'children))
13381 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13382 ;; from within `org-add-log-note' because `buffer-undo-list'
13383 ;; is then modified outside of `org-with-remote-undo'.
13384 (when (eq this-command 'org-agenda-todo)
13385 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13386 ;; Don't add undo information when called from `org-agenda-todo'.
13387 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13388 (set-window-configuration org-log-note-window-configuration)
13389 (with-current-buffer (marker-buffer org-log-note-return-to)
13390 (goto-char org-log-note-return-to))
13391 (move-marker org-log-note-return-to nil)
13392 (when org-log-post-message (message "%s" org-log-post-message))))
13394 (defun org-remove-empty-drawer-at (pos)
13395 "Remove an empty drawer at position POS.
13396 POS may also be a marker."
13397 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13398 (org-with-wide-buffer
13399 (goto-char pos)
13400 (let ((drawer (org-element-at-point)))
13401 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13402 (not (org-element-property :contents-begin drawer)))
13403 (delete-region (org-element-property :begin drawer)
13404 (progn (goto-char (org-element-property :end drawer))
13405 (skip-chars-backward " \r\t\n")
13406 (forward-line)
13407 (point))))))))
13409 (defvar org-ts-type nil)
13410 (defun org-sparse-tree (&optional arg type)
13411 "Create a sparse tree, prompt for the details.
13412 This command can create sparse trees. You first need to select the type
13413 of match used to create the tree:
13415 t Show all TODO entries.
13416 T Show entries with a specific TODO keyword.
13417 m Show entries selected by a tags/property match.
13418 p Enter a property name and its value (both with completion on existing
13419 names/values) and show entries with that property.
13420 r Show entries matching a regular expression (`/' can be used as well).
13421 b Show deadlines and scheduled items before a date.
13422 a Show deadlines and scheduled items after a date.
13423 d Show deadlines due within `org-deadline-warning-days'.
13424 D Show deadlines and scheduled items between a date range."
13425 (interactive "P")
13426 (setq type (or type org-sparse-tree-default-date-type))
13427 (setq org-ts-type type)
13428 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13429 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13430 \[c]ycle through date types: %s"
13431 (cl-case type
13432 (all "all timestamps")
13433 (scheduled "only scheduled")
13434 (deadline "only deadline")
13435 (active "only active timestamps")
13436 (inactive "only inactive timestamps")
13437 (closed "with a closed time-stamp")
13438 (otherwise "scheduled/deadline")))
13439 (let ((answer (read-char-exclusive)))
13440 (cl-case answer
13442 (org-sparse-tree
13444 (cadr
13445 (memq type '(nil all scheduled deadline active inactive closed)))))
13446 (?d (call-interactively 'org-check-deadlines))
13447 (?b (call-interactively 'org-check-before-date))
13448 (?a (call-interactively 'org-check-after-date))
13449 (?D (call-interactively 'org-check-dates-range))
13450 (?t (call-interactively 'org-show-todo-tree))
13451 (?T (org-show-todo-tree '(4)))
13452 (?m (call-interactively 'org-match-sparse-tree))
13453 ((?p ?P)
13454 (let* ((kwd (completing-read
13455 "Property: " (mapcar #'list (org-buffer-property-keys))))
13456 (value (completing-read
13457 "Value: " (mapcar #'list (org-property-values kwd)))))
13458 (unless (string-match "\\`{.*}\\'" value)
13459 (setq value (concat "\"" value "\"")))
13460 (org-match-sparse-tree arg (concat kwd "=" value))))
13461 ((?r ?R ?/) (call-interactively 'org-occur))
13462 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13464 (defvar-local org-occur-highlights nil
13465 "List of overlays used for occur matches.")
13466 (defvar-local org-occur-parameters nil
13467 "Parameters of the active org-occur calls.
13468 This is a list, each call to org-occur pushes as cons cell,
13469 containing the regular expression and the callback, onto the list.
13470 The list can contain several entries if `org-occur' has been called
13471 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13472 will only contain one set of parameters. When the highlights are
13473 removed (for example with `C-c C-c', or with the next edit (depending
13474 on `org-remove-highlights-with-change'), this variable is emptied
13475 as well.")
13477 (defun org-occur (regexp &optional keep-previous callback)
13478 "Make a compact tree which shows all matches of REGEXP.
13480 The tree will show the lines where the regexp matches, and any other context
13481 defined in `org-show-context-detail', which see.
13483 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13484 done by a previous call to `org-occur' will be kept, to allow stacking of
13485 calls to this command.
13487 Optional argument CALLBACK can be a function of no argument. In this case,
13488 it is called with point at the end of the match, match data being set
13489 accordingly. Current match is shown only if the return value is non-nil.
13490 The function must neither move point nor alter narrowing."
13491 (interactive "sRegexp: \nP")
13492 (when (equal regexp "")
13493 (user-error "Regexp cannot be empty"))
13494 (unless keep-previous
13495 (org-remove-occur-highlights nil nil t))
13496 (push (cons regexp callback) org-occur-parameters)
13497 (let ((cnt 0))
13498 (save-excursion
13499 (goto-char (point-min))
13500 (when (or (not keep-previous) ; do not want to keep
13501 (not org-occur-highlights)) ; no previous matches
13502 ;; hide everything
13503 (org-overview))
13504 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13505 (isearch-no-upper-case-p regexp t)
13506 org-occur-case-fold-search)))
13507 (while (re-search-forward regexp nil t)
13508 (when (or (not callback)
13509 (save-match-data (funcall callback)))
13510 (setq cnt (1+ cnt))
13511 (when org-highlight-sparse-tree-matches
13512 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13513 (org-show-context 'occur-tree)))))
13514 (when org-remove-highlights-with-change
13515 (add-hook 'before-change-functions 'org-remove-occur-highlights
13516 nil 'local))
13517 (unless org-sparse-tree-open-archived-trees
13518 (org-hide-archived-subtrees (point-min) (point-max)))
13519 (run-hooks 'org-occur-hook)
13520 (when (called-interactively-p 'interactive)
13521 (message "%d match(es) for regexp %s" cnt regexp))
13522 cnt))
13524 (defun org-occur-next-match (&optional n _reset)
13525 "Function for `next-error-function' to find sparse tree matches.
13526 N is the number of matches to move, when negative move backwards.
13527 This function always goes back to the starting point when no
13528 match is found."
13529 (let* ((limit (if (< n 0) (point-min) (point-max)))
13530 (search-func (if (< n 0)
13531 'previous-single-char-property-change
13532 'next-single-char-property-change))
13533 (n (abs n))
13534 (pos (point))
13536 (catch 'exit
13537 (while (setq p1 (funcall search-func (point) 'org-type))
13538 (when (equal p1 limit)
13539 (goto-char pos)
13540 (user-error "No more matches"))
13541 (when (equal (get-char-property p1 'org-type) 'org-occur)
13542 (setq n (1- n))
13543 (when (= n 0)
13544 (goto-char p1)
13545 (throw 'exit (point))))
13546 (goto-char p1))
13547 (goto-char p1)
13548 (user-error "No more matches"))))
13550 (defun org-show-context (&optional key)
13551 "Make sure point and context are visible.
13552 Optional argument KEY, when non-nil, is a symbol. See
13553 `org-show-context-detail' for allowed values and how much is to
13554 be shown."
13555 (org-show-set-visibility
13556 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13557 ((cdr (assq key org-show-context-detail)))
13558 (t (cdr (assq 'default org-show-context-detail))))))
13560 (defun org-show-set-visibility (detail)
13561 "Set visibility around point according to DETAIL.
13562 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13563 `tree', `canonical' or t. See `org-show-context-detail' for more
13564 information."
13565 ;; Show current heading and possibly its entry, following headline
13566 ;; or all children.
13567 (if (and (org-at-heading-p) (not (eq detail 'local)))
13568 (org-flag-heading nil)
13569 (org-show-entry)
13570 ;; If point is hidden within a drawer or a block, make sure to
13571 ;; expose it.
13572 (dolist (o (overlays-at (point)))
13573 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13574 (delete-overlay o)))
13575 (unless (org-before-first-heading-p)
13576 (org-with-limited-levels
13577 (cl-case detail
13578 ((tree canonical t) (org-show-children))
13579 ((nil minimal ancestors))
13580 (t (save-excursion
13581 (outline-next-heading)
13582 (org-flag-heading nil)))))))
13583 ;; Show all siblings.
13584 (when (eq detail 'lineage) (org-show-siblings))
13585 ;; Show ancestors, possibly with their children.
13586 (when (memq detail '(ancestors lineage tree canonical t))
13587 (save-excursion
13588 (while (org-up-heading-safe)
13589 (org-flag-heading nil)
13590 (when (memq detail '(canonical t)) (org-show-entry))
13591 (when (memq detail '(tree canonical t)) (org-show-children))))))
13593 (defvar org-reveal-start-hook nil
13594 "Hook run before revealing a location.")
13596 (defun org-reveal (&optional siblings)
13597 "Show current entry, hierarchy above it, and the following headline.
13599 This can be used to show a consistent set of context around
13600 locations exposed with `org-show-context'.
13602 With optional argument SIBLINGS, on each level of the hierarchy all
13603 siblings are shown. This repairs the tree structure to what it would
13604 look like when opened with hierarchical calls to `org-cycle'.
13606 With a \\[universal-argument] \\[universal-argument] prefix, \
13607 go to the parent and show the entire tree."
13608 (interactive "P")
13609 (run-hooks 'org-reveal-start-hook)
13610 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13611 ((equal siblings '(16))
13612 (save-excursion
13613 (when (org-up-heading-safe)
13614 (org-show-subtree)
13615 (run-hook-with-args 'org-cycle-hook 'subtree))))
13616 (t (org-show-set-visibility 'lineage))))
13618 (defun org-highlight-new-match (beg end)
13619 "Highlight from BEG to END and mark the highlight is an occur headline."
13620 (let ((ov (make-overlay beg end)))
13621 (overlay-put ov 'face 'secondary-selection)
13622 (overlay-put ov 'org-type 'org-occur)
13623 (push ov org-occur-highlights)))
13625 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13626 "Remove the occur highlights from the buffer.
13627 BEG and END are ignored. If NOREMOVE is nil, remove this function
13628 from the `before-change-functions' in the current buffer."
13629 (interactive)
13630 (unless org-inhibit-highlight-removal
13631 (mapc #'delete-overlay org-occur-highlights)
13632 (setq org-occur-highlights nil)
13633 (setq org-occur-parameters nil)
13634 (unless noremove
13635 (remove-hook 'before-change-functions
13636 'org-remove-occur-highlights 'local))))
13638 ;;;; Priorities
13640 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13641 "Regular expression matching the priority indicator.")
13643 (defvar org-remove-priority-next-time nil)
13645 (defun org-priority-up ()
13646 "Increase the priority of the current item."
13647 (interactive)
13648 (org-priority 'up))
13650 (defun org-priority-down ()
13651 "Decrease the priority of the current item."
13652 (interactive)
13653 (org-priority 'down))
13655 (defun org-priority (&optional action _show)
13656 "Change the priority of an item.
13657 ACTION can be `set', `up', `down', or a character."
13658 (interactive "P")
13659 (if (equal action '(4))
13660 (org-show-priority)
13661 (unless org-enable-priority-commands
13662 (user-error "Priority commands are disabled"))
13663 (setq action (or action 'set))
13664 (let (current new news have remove)
13665 (save-excursion
13666 (org-back-to-heading t)
13667 (when (looking-at org-priority-regexp)
13668 (setq current (string-to-char (match-string 2))
13669 have t))
13670 (cond
13671 ((eq action 'remove)
13672 (setq remove t new ?\ ))
13673 ((or (eq action 'set)
13674 (integerp action))
13675 (if (not (eq action 'set))
13676 (setq new action)
13677 (message "Priority %c-%c, SPC to remove: "
13678 org-highest-priority org-lowest-priority)
13679 (save-match-data
13680 (setq new (read-char-exclusive))))
13681 (when (and (= (upcase org-highest-priority) org-highest-priority)
13682 (= (upcase org-lowest-priority) org-lowest-priority))
13683 (setq new (upcase new)))
13684 (cond ((equal new ?\ ) (setq remove t))
13685 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13686 (user-error "Priority must be between `%c' and `%c'"
13687 org-highest-priority org-lowest-priority))))
13688 ((eq action 'up)
13689 (setq new (if have
13690 (1- current) ; normal cycling
13691 ;; last priority was empty
13692 (if (eq last-command this-command)
13693 org-lowest-priority ; wrap around empty to lowest
13694 ;; default
13695 (if org-priority-start-cycle-with-default
13696 org-default-priority
13697 (1- org-default-priority))))))
13698 ((eq action 'down)
13699 (setq new (if have
13700 (1+ current) ; normal cycling
13701 ;; last priority was empty
13702 (if (eq last-command this-command)
13703 org-highest-priority ; wrap around empty to highest
13704 ;; default
13705 (if org-priority-start-cycle-with-default
13706 org-default-priority
13707 (1+ org-default-priority))))))
13708 (t (user-error "Invalid action")))
13709 (when (or (< (upcase new) org-highest-priority)
13710 (> (upcase new) org-lowest-priority))
13711 (if (and (memq action '(up down))
13712 (not have) (not (eq last-command this-command)))
13713 ;; `new' is from default priority
13714 (error
13715 "The default can not be set, see `org-default-priority' why")
13716 ;; normal cycling: `new' is beyond highest/lowest priority
13717 ;; and is wrapped around to the empty priority
13718 (setq remove t)))
13719 (setq news (format "%c" new))
13720 (if have
13721 (if remove
13722 (replace-match "" t t nil 1)
13723 (replace-match news t t nil 2))
13724 (if remove
13725 (user-error "No priority cookie found in line")
13726 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13727 (if (match-end 2)
13728 (progn
13729 (goto-char (match-end 2))
13730 (insert " [#" news "]"))
13731 (goto-char (match-beginning 3))
13732 (insert "[#" news "] "))))
13733 (org-set-tags nil 'align))
13734 (if remove
13735 (message "Priority removed")
13736 (message "Priority of current item set to %s" news)))))
13738 (defun org-show-priority ()
13739 "Show the priority of the current item.
13740 This priority is composed of the main priority given with the [#A] cookies,
13741 and by additional input from the age of a schedules or deadline entry."
13742 (interactive)
13743 (let ((pri (if (eq major-mode 'org-agenda-mode)
13744 (org-get-at-bol 'priority)
13745 (save-excursion
13746 (save-match-data
13747 (beginning-of-line)
13748 (and (looking-at org-heading-regexp)
13749 (org-get-priority (match-string 0))))))))
13750 (message "Priority is %d" (if pri pri -1000))))
13752 (defun org-get-priority (s)
13753 "Find priority cookie and return priority."
13754 (save-match-data
13755 (if (functionp org-get-priority-function)
13756 (funcall org-get-priority-function)
13757 (if (not (string-match org-priority-regexp s))
13758 (* 1000 (- org-lowest-priority org-default-priority))
13759 (* 1000 (- org-lowest-priority
13760 (string-to-char (match-string 2 s))))))))
13762 ;;;; Tags
13764 (defvar org-agenda-archives-mode)
13765 (defvar org-map-continue-from nil
13766 "Position from where mapping should continue.
13767 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13769 (defvar org-scanner-tags nil
13770 "The current tag list while the tags scanner is running.")
13772 (defvar org-trust-scanner-tags nil
13773 "Should `org-get-tags-at' use the tags for the scanner.
13774 This is for internal dynamical scoping only.
13775 When this is non-nil, the function `org-get-tags-at' will return the value
13776 of `org-scanner-tags' instead of building the list by itself. This
13777 can lead to large speed-ups when the tags scanner is used in a file with
13778 many entries, and when the list of tags is retrieved, for example to
13779 obtain a list of properties. Building the tags list for each entry in such
13780 a file becomes an N^2 operation - but with this variable set, it scales
13781 as N.")
13783 (defvar org--matcher-tags-todo-only nil)
13785 (defun org-scan-tags (action matcher todo-only &optional start-level)
13786 "Scan headline tags with inheritance and produce output ACTION.
13788 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13789 or `agenda' to produce an entry list for an agenda view. It can also be
13790 a Lisp form or a function that should be called at each matched headline, in
13791 this case the return value is a list of all return values from these calls.
13793 MATCHER is a function accepting three arguments, returning
13794 a non-nil value whenever a given set of tags qualifies a headline
13795 for inclusion. See `org-make-tags-matcher' for more information.
13796 As a special case, it can also be set to t (respectively nil) in
13797 order to match all (respectively none) headline.
13799 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13800 included in the output.
13802 START-LEVEL can be a string with asterisks, reducing the scope to
13803 headlines matching this string."
13804 (require 'org-agenda)
13805 (let* ((re (concat "^"
13806 (if start-level
13807 ;; Get the correct level to match
13808 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13809 org-outline-regexp)
13810 " *\\(\\<\\("
13811 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13812 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13813 (props (list 'face 'default
13814 'done-face 'org-agenda-done
13815 'undone-face 'default
13816 'mouse-face 'highlight
13817 'org-not-done-regexp org-not-done-regexp
13818 'org-todo-regexp org-todo-regexp
13819 'org-complex-heading-regexp org-complex-heading-regexp
13820 'help-echo
13821 (format "mouse-2 or RET jump to org file %s"
13822 (abbreviate-file-name
13823 (or (buffer-file-name (buffer-base-buffer))
13824 (buffer-name (buffer-base-buffer)))))))
13825 (org-map-continue-from nil)
13826 lspos tags tags-list
13827 (tags-alist (list (cons 0 org-file-tags)))
13828 (llast 0) rtn rtn1 level category i txt
13829 todo marker entry priority
13830 ts-date ts-date-type ts-date-pair)
13831 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13832 (setq action (list 'lambda nil action)))
13833 (save-excursion
13834 (goto-char (point-min))
13835 (when (eq action 'sparse-tree)
13836 (org-overview)
13837 (org-remove-occur-highlights))
13838 (while (let (case-fold-search)
13839 (re-search-forward re nil t))
13840 (setq org-map-continue-from nil)
13841 (catch :skip
13842 (setq todo
13843 ;; TODO: is the 1-2 difference a bug?
13844 (when (match-end 1) (match-string-no-properties 2))
13845 tags (when (match-end 4) (match-string-no-properties 4)))
13846 (goto-char (setq lspos (match-beginning 0)))
13847 (setq level (org-reduced-level (org-outline-level))
13848 category (org-get-category))
13849 (when (eq action 'agenda)
13850 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13851 ts-date (car ts-date-pair)
13852 ts-date-type (cdr ts-date-pair)))
13853 (setq i llast llast level)
13854 ;; remove tag lists from same and sublevels
13855 (while (>= i level)
13856 (when (setq entry (assoc i tags-alist))
13857 (setq tags-alist (delete entry tags-alist)))
13858 (setq i (1- i)))
13859 ;; add the next tags
13860 (when tags
13861 (setq tags (org-split-string tags ":")
13862 tags-alist
13863 (cons (cons level tags) tags-alist)))
13864 ;; compile tags for current headline
13865 (setq tags-list
13866 (if org-use-tag-inheritance
13867 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13868 tags)
13869 org-scanner-tags tags-list)
13870 (when org-use-tag-inheritance
13871 (setcdr (car tags-alist)
13872 (mapcar (lambda (x)
13873 (setq x (copy-sequence x))
13874 (org-add-prop-inherited x))
13875 (cdar tags-alist))))
13876 (when (and tags org-use-tag-inheritance
13877 (or (not (eq t org-use-tag-inheritance))
13878 org-tags-exclude-from-inheritance))
13879 ;; Selective inheritance, remove uninherited ones.
13880 (setcdr (car tags-alist)
13881 (org-remove-uninherited-tags (cdar tags-alist))))
13882 (when (and
13884 ;; eval matcher only when the todo condition is OK
13885 (and (or (not todo-only) (member todo org-todo-keywords-1))
13886 (if (functionp matcher)
13887 (let ((case-fold-search t) (org-trust-scanner-tags t))
13888 (funcall matcher todo tags-list level))
13889 matcher))
13891 ;; Call the skipper, but return t if it does not
13892 ;; skip, so that the `and' form continues evaluating.
13893 (progn
13894 (unless (eq action 'sparse-tree) (org-agenda-skip))
13897 ;; Check if timestamps are deselecting this entry
13898 (or (not todo-only)
13899 (and (member todo org-todo-keywords-1)
13900 (or (not org-agenda-tags-todo-honor-ignore-options)
13901 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13903 ;; select this headline
13904 (cond
13905 ((eq action 'sparse-tree)
13906 (and org-highlight-sparse-tree-matches
13907 (org-get-heading) (match-end 0)
13908 (org-highlight-new-match
13909 (match-beginning 1) (match-end 1)))
13910 (org-show-context 'tags-tree))
13911 ((eq action 'agenda)
13912 (setq txt (org-agenda-format-item
13914 (concat
13915 (if (eq org-tags-match-list-sublevels 'indented)
13916 (make-string (1- level) ?.) "")
13917 (org-get-heading))
13918 (make-string level ?\s)
13919 category
13920 tags-list)
13921 priority (org-get-priority txt))
13922 (goto-char lspos)
13923 (setq marker (org-agenda-new-marker))
13924 (org-add-props txt props
13925 'org-marker marker 'org-hd-marker marker 'org-category category
13926 'todo-state todo
13927 'ts-date ts-date
13928 'priority priority
13929 'type (concat "tagsmatch" ts-date-type))
13930 (push txt rtn))
13931 ((functionp action)
13932 (setq org-map-continue-from nil)
13933 (save-excursion
13934 (setq rtn1 (funcall action))
13935 (push rtn1 rtn)))
13936 (t (user-error "Invalid action")))
13938 ;; if we are to skip sublevels, jump to end of subtree
13939 (unless org-tags-match-list-sublevels
13940 (org-end-of-subtree t)
13941 (backward-char 1))))
13942 ;; Get the correct position from where to continue
13943 (if org-map-continue-from
13944 (goto-char org-map-continue-from)
13945 (and (= (point) lspos) (end-of-line 1)))))
13946 (when (and (eq action 'sparse-tree)
13947 (not org-sparse-tree-open-archived-trees))
13948 (org-hide-archived-subtrees (point-min) (point-max)))
13949 (nreverse rtn)))
13951 (defun org-remove-uninherited-tags (tags)
13952 "Remove all tags that are not inherited from the list TAGS."
13953 (cond
13954 ((eq org-use-tag-inheritance t)
13955 (if org-tags-exclude-from-inheritance
13956 (org-delete-all org-tags-exclude-from-inheritance tags)
13957 tags))
13958 ((not org-use-tag-inheritance) nil)
13959 ((stringp org-use-tag-inheritance)
13960 (delq nil (mapcar
13961 (lambda (x)
13962 (if (and (string-match org-use-tag-inheritance x)
13963 (not (member x org-tags-exclude-from-inheritance)))
13964 x nil))
13965 tags)))
13966 ((listp org-use-tag-inheritance)
13967 (delq nil (mapcar
13968 (lambda (x)
13969 (if (member x org-use-tag-inheritance) x nil))
13970 tags)))))
13972 (defun org-match-sparse-tree (&optional todo-only match)
13973 "Create a sparse tree according to tags string MATCH.
13975 MATCH is a string with match syntax. It can contain a selection
13976 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13977 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13978 those. See the manual for details.
13980 If optional argument TODO-ONLY is non-nil, only select lines that
13981 are also TODO tasks."
13982 (interactive "P")
13983 (org-agenda-prepare-buffers (list (current-buffer)))
13984 (let ((org--matcher-tags-todo-only todo-only))
13985 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13986 org--matcher-tags-todo-only)))
13988 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13990 (defvar org-cached-props nil)
13991 (defun org-cached-entry-get (pom property)
13992 (if (or (eq t org-use-property-inheritance)
13993 (and (stringp org-use-property-inheritance)
13994 (let ((case-fold-search t))
13995 (string-match-p org-use-property-inheritance property)))
13996 (and (listp org-use-property-inheritance)
13997 (member-ignore-case property org-use-property-inheritance)))
13998 ;; Caching is not possible, check it directly.
13999 (org-entry-get pom property 'inherit)
14000 ;; Get all properties, so we can do complicated checks easily.
14001 (cdr (assoc-string property
14002 (or org-cached-props
14003 (setq org-cached-props (org-entry-properties pom)))
14004 t))))
14006 (defun org-global-tags-completion-table (&optional files)
14007 "Return the list of all tags in all agenda buffer/files.
14008 Optional FILES argument is a list of files which can be used
14009 instead of the agenda files."
14010 (save-excursion
14011 (org-uniquify
14012 (delq nil
14013 (apply #'append
14014 (mapcar
14015 (lambda (file)
14016 (set-buffer (find-file-noselect file))
14017 (mapcar (lambda (x)
14018 (and (stringp (car-safe x))
14019 (list (car-safe x))))
14020 (or org-current-tag-alist (org-get-buffer-tags))))
14021 (if (car-safe files) files
14022 (org-agenda-files))))))))
14024 (defun org-make-tags-matcher (match)
14025 "Create the TAGS/TODO matcher form for the selection string MATCH.
14027 Returns a cons of the selection string MATCH and a function
14028 implementing the matcher.
14030 The matcher is to be called at an Org entry, with point on the
14031 headline, and returns non-nil if the entry matches the selection
14032 string MATCH. It must be called with three arguments: the TODO
14033 keyword at the entry (or nil if none), the list of all tags at
14034 the entry including inherited ones and the reduced level of the
14035 headline. Additionally, the category of the entry, if any, must
14036 be specified as the text property `org-category' on the headline.
14038 This function sets the variable `org--matcher-tags-todo-only' to
14039 a non-nil value if the matcher restricts matching to TODO
14040 entries, otherwise it is not touched.
14042 See also `org-scan-tags'."
14043 (unless match
14044 ;; Get a new match request, with completion against the global
14045 ;; tags table and the local tags in current buffer.
14046 (let ((org-last-tags-completion-table
14047 (org-uniquify
14048 (delq nil (append (org-get-buffer-tags)
14049 (org-global-tags-completion-table))))))
14050 (setq match
14051 (completing-read
14052 "Match: "
14053 'org-tags-completion-function nil nil nil 'org-tags-history))))
14055 (let ((match0 match)
14056 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14057 (start 0)
14058 tagsmatch todomatch tagsmatcher todomatcher)
14060 ;; Expand group tags.
14061 (setq match (org-tags-expand match))
14063 ;; Check if there is a TODO part of this match, which would be the
14064 ;; part after a "/". To make sure that this slash is not part of
14065 ;; a property value to be matched against, we also check that
14066 ;; there is no / after that slash. First, find the last slash.
14067 (let ((s 0))
14068 (while (string-match "/+" match s)
14069 (setq start (match-beginning 0))
14070 (setq s (match-end 0))))
14071 (if (and (string-match "/+" match start)
14072 (not (string-match-p "\"" match start)))
14073 ;; Match contains also a TODO-matching request.
14074 (progn
14075 (setq tagsmatch (substring match 0 (match-beginning 0)))
14076 (setq todomatch (substring match (match-end 0)))
14077 (when (string-prefix-p "!" todomatch)
14078 (setq org--matcher-tags-todo-only t)
14079 (setq todomatch (substring todomatch 1)))
14080 (when (string-match "\\`\\s-*\\'" todomatch)
14081 (setq todomatch nil)))
14082 ;; Only matching tags.
14083 (setq tagsmatch match)
14084 (setq todomatch nil))
14086 ;; Make the tags matcher.
14087 (when (org-string-nw-p tagsmatch)
14088 (let ((orlist nil)
14089 (orterms (org-split-string tagsmatch "|"))
14090 term)
14091 (while (setq term (pop orterms))
14092 (while (and (equal (substring term -1) "\\") orterms)
14093 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14094 (while (string-match re term)
14095 (let* ((rest (substring term (match-end 0)))
14096 (minus (and (match-end 1)
14097 (equal (match-string 1 term) "-")))
14098 (tag (save-match-data
14099 (replace-regexp-in-string
14100 "\\\\-" "-" (match-string 2 term))))
14101 (regexp (eq (string-to-char tag) ?{))
14102 (levelp (match-end 4))
14103 (propp (match-end 5))
14105 (cond
14106 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14107 (levelp
14108 `(,(org-op-to-function (match-string 3 term))
14109 level
14110 ,(string-to-number (match-string 4 term))))
14111 (propp
14112 (let* ((gv (pcase (upcase (match-string 5 term))
14113 ("CATEGORY"
14114 '(get-text-property (point) 'org-category))
14115 ("TODO" 'todo)
14116 (p `(org-cached-entry-get nil ,p))))
14117 (pv (match-string 7 term))
14118 (regexp (eq (string-to-char pv) ?{))
14119 (strp (eq (string-to-char pv) ?\"))
14120 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14121 (po (org-op-to-function (match-string 6 term)
14122 (if timep 'time strp))))
14123 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14124 (when timep (setq pv (org-matcher-time pv)))
14125 (cond ((and regexp (eq po 'org<>))
14126 `(not (string-match ,pv (or ,gv ""))))
14127 (regexp `(string-match ,pv (or ,gv "")))
14128 (strp `(,po (or ,gv "") ,pv))
14130 `(,po
14131 (string-to-number (or ,gv ""))
14132 ,(string-to-number pv))))))
14133 (t `(member ,tag tags-list)))))
14134 (push (if minus `(not ,mm) mm) tagsmatcher)
14135 (setq term rest)))
14136 (push `(and ,@tagsmatcher) orlist)
14137 (setq tagsmatcher nil))
14138 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14140 ;; Make the TODO matcher.
14141 (when (org-string-nw-p todomatch)
14142 (let ((orlist nil))
14143 (dolist (term (org-split-string todomatch "|"))
14144 (while (string-match re term)
14145 (let* ((minus (and (match-end 1)
14146 (equal (match-string 1 term) "-")))
14147 (kwd (match-string 2 term))
14148 (regexp (eq (string-to-char kwd) ?{))
14149 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14150 `(equal todo ,kwd))))
14151 (push (if minus `(not ,mm) mm) todomatcher))
14152 (setq term (substring term (match-end 0))))
14153 (push (if (> (length todomatcher) 1)
14154 (cons 'and todomatcher)
14155 (car todomatcher))
14156 orlist)
14157 (setq todomatcher nil))
14158 (setq todomatcher (cons 'or orlist))))
14160 ;; Return the string and function of the matcher. If no
14161 ;; tags-specific or todo-specific matcher exists, match
14162 ;; everything.
14163 (let ((matcher (if (and tagsmatcher todomatcher)
14164 `(and ,tagsmatcher ,todomatcher)
14165 (or tagsmatcher todomatcher t))))
14166 (when org--matcher-tags-todo-only
14167 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14168 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14170 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14171 "Expand group tags in MATCH.
14173 This replaces every group tag in MATCH with a regexp tag search.
14174 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14175 will be replaced like this:
14177 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14178 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14179 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14181 Replacing by a regexp preserves the structure of the match.
14182 E.g., this expansion
14184 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14186 will match anything tagged with \"Lab\" and \"Home\", or tagged
14187 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14189 A group tag in MATCH can contain regular expressions of its own.
14190 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14191 will be replaced like this:
14193 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14195 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14196 assumed to be a single group tag, and the function will return
14197 the list of tags in this group.
14199 When DOWNCASE is non-nil, expand downcased TAGS."
14200 (if org-group-tags
14201 (let* ((case-fold-search t)
14202 (stable org-mode-syntax-table)
14203 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14204 (taggroups (if downcased
14205 (mapcar (lambda (tg) (mapcar #'downcase tg))
14206 taggroups)
14207 taggroups))
14208 (taggroups-keys (mapcar #'car taggroups))
14209 (return-match (if downcased (downcase match) match))
14210 (count 0)
14211 (work-already-expanded tags-already-expanded)
14212 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14213 ;; @ and _ are allowed as word-components in tags.
14214 (modify-syntax-entry ?@ "w" stable)
14215 (modify-syntax-entry ?_ "w" stable)
14216 ;; Temporarily replace regexp-expressions in the match-expression.
14217 (while (string-match "{.+?}" return-match)
14218 (cl-incf count)
14219 (push (match-string 0 return-match) regexps-in-match)
14220 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14221 (while (and taggroups-keys
14222 (with-syntax-table stable
14223 (string-match
14224 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14225 (regexp-opt taggroups-keys) "\\>\\)")
14226 return-match)))
14227 (let* ((dir (match-string 1 return-match))
14228 (tag (match-string 2 return-match))
14229 (tag (if downcased (downcase tag) tag)))
14230 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14231 (member tag work-already-expanded))
14232 (setq tags-in-group (assoc tag taggroups))
14233 (push tag work-already-expanded)
14234 ;; Recursively expand each tag in the group, if the tag hasn't
14235 ;; already been expanded. Restore the match-data after all recursive calls.
14236 (save-match-data
14237 (let (tags-expanded)
14238 (dolist (x (cdr tags-in-group))
14239 (if (and (member x taggroups-keys)
14240 (not (member x work-already-expanded)))
14241 (setq tags-expanded
14242 (delete-dups
14243 (append
14244 (org-tags-expand x t downcased
14245 work-already-expanded)
14246 tags-expanded)))
14247 (setq tags-expanded
14248 (append (list x) tags-expanded)))
14249 (setq work-already-expanded
14250 (delete-dups
14251 (append tags-expanded
14252 work-already-expanded))))
14253 (setq tags-in-group
14254 (delete-dups (cons (car tags-in-group)
14255 tags-expanded)))))
14256 ;; Filter tag-regexps from tags.
14257 (setq regexp-in-group-escaped
14258 (delq nil (mapcar (lambda (x)
14259 (if (stringp x)
14260 (and (equal "{" (substring x 0 1))
14261 (equal "}" (substring x -1))
14264 tags-in-group))
14265 regexp-in-group
14266 (mapcar (lambda (x)
14267 (substring x 1 -1))
14268 regexp-in-group-escaped)
14269 tags-in-group
14270 (delq nil (mapcar (lambda (x)
14271 (if (stringp x)
14272 (and (not (equal "{" (substring x 0 1)))
14273 (not (equal "}" (substring x -1)))
14276 tags-in-group)))
14277 ;; If single-as-list, do no more in the while-loop.
14278 (if (not single-as-list)
14279 (progn
14280 (when regexp-in-group
14281 (setq regexp-in-group
14282 (concat "\\|"
14283 (mapconcat 'identity regexp-in-group
14284 "\\|"))))
14285 (setq tags-in-group
14286 (concat dir
14287 "{\\<"
14288 (regexp-opt tags-in-group)
14289 "\\>"
14290 regexp-in-group
14291 "}"))
14292 (when (stringp tags-in-group)
14293 (org-add-props tags-in-group '(grouptag t)))
14294 (setq return-match
14295 (replace-match tags-in-group t t return-match)))
14296 (setq tags-in-group
14297 (append regexp-in-group-escaped tags-in-group))))
14298 (setq taggroups-keys (delete tag taggroups-keys))))
14299 ;; Add the regular expressions back into the match-expression again.
14300 (while regexps-in-match
14301 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14302 (pop regexps-in-match)
14303 return-match t t))
14304 (cl-decf count))
14305 (if single-as-list
14306 (if tags-in-group tags-in-group (list return-match))
14307 return-match))
14308 (if single-as-list
14309 (list (if downcased (downcase match) match))
14310 match)))
14312 (defun org-op-to-function (op &optional stringp)
14313 "Turn an operator into the appropriate function."
14314 (setq op
14315 (cond
14316 ((equal op "<" ) '(< string< org-time<))
14317 ((equal op ">" ) '(> org-string> org-time>))
14318 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14319 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14320 ((member op '("=" "==")) '(= string= org-time=))
14321 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14322 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14324 (defun org<> (a b) (not (= a b)))
14325 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14326 (defun org-string>= (a b) (not (string< a b)))
14327 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14328 (defun org-string<> (a b) (not (string= a b)))
14329 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14330 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14331 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14332 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14333 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14334 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14335 (defun org-2ft (s)
14336 "Convert S to a floating point time.
14337 If S is already a number, just return it. If it is a string, parse
14338 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14339 (cond
14340 ((numberp s) s)
14341 ((stringp s)
14342 (condition-case nil
14343 (float-time (apply #'encode-time (org-parse-time-string s)))
14344 (error 0.)))
14345 (t 0.)))
14347 (defun org-time-today ()
14348 "Time in seconds today at 0:00.
14349 Returns the float number of seconds since the beginning of the
14350 epoch to the beginning of today (00:00)."
14351 (float-time (apply 'encode-time
14352 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14354 (defun org-matcher-time (s)
14355 "Interpret a time comparison value."
14356 (save-match-data
14357 (cond
14358 ((string= s "<now>") (float-time))
14359 ((string= s "<today>") (org-time-today))
14360 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14361 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14362 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14363 (+ (org-time-today)
14364 (* (string-to-number (match-string 1 s))
14365 (cdr (assoc (match-string 2 s)
14366 '(("d" . 86400.0) ("w" . 604800.0)
14367 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14368 (t (org-2ft s)))))
14370 (defun org-match-any-p (re list)
14371 "Does re match any element of list?"
14372 (setq list (mapcar (lambda (x) (string-match re x)) list))
14373 (delq nil list))
14375 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14376 (defvar org-tags-overlay (make-overlay 1 1))
14377 (delete-overlay org-tags-overlay)
14379 (defun org-get-local-tags-at (&optional pos)
14380 "Get a list of tags defined in the current headline."
14381 (org-get-tags-at pos 'local))
14383 (defun org-get-local-tags ()
14384 "Get a list of tags defined in the current headline."
14385 (org-get-tags-at nil 'local))
14387 (defun org-get-tags-at (&optional pos local)
14388 "Get a list of all headline tags applicable at POS.
14389 POS defaults to point. If tags are inherited, the list contains
14390 the targets in the same sequence as the headlines appear, i.e.
14391 the tags of the current headline come last.
14392 When LOCAL is non-nil, only return tags from the current headline,
14393 ignore inherited ones."
14394 (interactive)
14395 (if (and org-trust-scanner-tags
14396 (or (not pos) (equal pos (point)))
14397 (not local))
14398 org-scanner-tags
14399 (let (tags ltags lastpos parent)
14400 (save-excursion
14401 (save-restriction
14402 (widen)
14403 (goto-char (or pos (point)))
14404 (save-match-data
14405 (catch 'done
14406 (condition-case nil
14407 (progn
14408 (org-back-to-heading t)
14409 (while (not (equal lastpos (point)))
14410 (setq lastpos (point))
14411 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14412 (setq ltags (org-split-string
14413 (match-string-no-properties 1) ":"))
14414 (when parent
14415 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14416 (setq tags (append
14417 (if parent
14418 (org-remove-uninherited-tags ltags)
14419 ltags)
14420 tags)))
14421 (or org-use-tag-inheritance (throw 'done t))
14422 (when local (throw 'done t))
14423 (or (org-up-heading-safe) (error nil))
14424 (setq parent t)))
14425 (error nil)))))
14426 (if local
14427 tags
14428 (reverse (delete-dups
14429 (reverse (append
14430 (org-remove-uninherited-tags
14431 org-file-tags)
14432 tags)))))))))
14434 (defun org-add-prop-inherited (s)
14435 (add-text-properties 0 (length s) '(inherited t) s)
14438 (defun org-toggle-tag (tag &optional onoff)
14439 "Toggle the tag TAG for the current line.
14440 If ONOFF is `on' or `off', don't toggle but set to this state."
14441 (save-excursion
14442 (org-back-to-heading t)
14443 (let ((current
14444 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14445 (line-end-position) t)
14446 (let ((tags (match-string 1)))
14447 ;; Clear current tags.
14448 (replace-match "")
14449 ;; Reverse the tags list so any new tag is appended to
14450 ;; the current list of tags.
14451 (nreverse (org-split-string tags ":")))))
14452 res)
14453 (pcase onoff
14454 (`off (setq current (delete tag current)))
14455 ((or `on (guard (not (member tag current))))
14456 (setq res t)
14457 (cl-pushnew tag current :test #'equal))
14458 (_ (setq current (delete tag current))))
14459 (end-of-line)
14460 (if current
14461 (progn
14462 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14463 (org-set-tags nil t))
14464 (delete-horizontal-space))
14465 (run-hooks 'org-after-tags-change-hook)
14466 res)))
14468 (defun org--align-tags-here (to-col)
14469 "Align tags on the current headline to TO-COL.
14470 Assume point is on a headline."
14471 (let ((pos (point)))
14472 (beginning-of-line)
14473 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14474 (>= pos (match-beginning 2)))
14475 ;; No tags or point within tags: do not align.
14476 (goto-char pos)
14477 (goto-char (match-beginning 1))
14478 (let ((shift (max (- (if (>= to-col 0) to-col
14479 (- (abs to-col) (string-width (match-string 2))))
14480 (current-column))
14481 1)))
14482 (replace-match (make-string shift ?\s) nil nil nil 1)
14483 ;; Preserve initial position, if possible. In any case, stop
14484 ;; before tags.
14485 (when (< pos (point)) (goto-char pos))))))
14487 (defun org-set-tags-command (&optional arg just-align)
14488 "Call the set-tags command for the current entry."
14489 (interactive "P")
14490 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14491 (org-set-tags arg just-align)
14492 (save-excursion
14493 (unless (and (org-region-active-p)
14494 org-loop-over-headlines-in-active-region)
14495 (org-back-to-heading t))
14496 (org-set-tags arg just-align))))
14498 (defun org-set-tags-to (data)
14499 "Set the tags of the current entry to DATA, replacing the current tags.
14500 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14501 If DATA is nil or the empty string, any tags will be removed."
14502 (interactive "sTags: ")
14503 (setq data
14504 (cond
14505 ((eq data nil) "")
14506 ((equal data "") "")
14507 ((stringp data)
14508 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14509 ":"))
14510 ((listp data)
14511 (concat ":" (mapconcat 'identity data ":") ":"))))
14512 (when data
14513 (save-excursion
14514 (org-back-to-heading t)
14515 (when (let ((case-fold-search nil))
14516 (looking-at org-complex-heading-regexp))
14517 (if (match-end 5)
14518 (progn
14519 (goto-char (match-beginning 5))
14520 (insert data)
14521 (delete-region (point) (point-at-eol))
14522 (org-set-tags nil 'align))
14523 (goto-char (point-at-eol))
14524 (insert " " data)
14525 (org-set-tags nil 'align)))
14526 (beginning-of-line 1)
14527 (when (looking-at ".*?\\([ \t]+\\)$")
14528 (delete-region (match-beginning 1) (match-end 1))))))
14530 (defun org-align-all-tags ()
14531 "Align the tags in all headings."
14532 (interactive)
14533 (save-excursion
14534 (or (ignore-errors (org-back-to-heading t))
14535 (outline-next-heading))
14536 (if (org-at-heading-p)
14537 (org-set-tags t)
14538 (message "No headings"))))
14540 (defvar org-indent-indentation-per-level)
14541 (defun org-set-tags (&optional arg just-align)
14542 "Set the tags for the current headline.
14543 With prefix ARG, realign all tags in headings in the current buffer.
14544 When JUST-ALIGN is non-nil, only align tags."
14545 (interactive "P")
14546 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14547 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14548 'region-start-level
14549 'region))
14550 org-loop-over-headlines-in-active-region)
14551 (org-map-entries
14552 ;; We don't use ARG and JUST-ALIGN here because these args
14553 ;; are not useful when looping over headlines.
14554 #'org-set-tags
14555 org-loop-over-headlines-in-active-region
14557 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14558 (let ((org-setting-tags t))
14559 (if arg
14560 (save-excursion
14561 (goto-char (point-min))
14562 (while (re-search-forward org-outline-regexp-bol nil t)
14563 (org-set-tags nil t)
14564 (end-of-line))
14565 (message "All tags realigned to column %d" org-tags-column))
14566 (let* ((current (org-get-tags-string))
14567 (tags
14568 (if just-align current
14569 ;; Get a new set of tags from the user.
14570 (save-excursion
14571 (let* ((seen)
14572 (table
14573 (setq
14574 org-last-tags-completion-table
14575 ;; Uniquify tags in alists, yet preserve
14576 ;; structure (i.e., keywords).
14577 (delq nil
14578 (mapcar
14579 (lambda (pair)
14580 (let ((head (car pair)))
14581 (cond ((symbolp head) pair)
14582 ((member head seen) nil)
14583 (t (push head seen)
14584 pair))))
14585 (append
14586 (or org-current-tag-alist
14587 (org-get-buffer-tags))
14588 (and
14589 org-complete-tags-always-offer-all-agenda-tags
14590 (org-global-tags-completion-table
14591 (org-agenda-files))))))))
14592 (current-tags (org-split-string current ":"))
14593 (inherited-tags
14594 (nreverse (nthcdr (length current-tags)
14595 (nreverse (org-get-tags-at))))))
14596 (replace-regexp-in-string
14597 "\\([-+&]+\\|,\\)"
14599 (if (or (eq t org-use-fast-tag-selection)
14600 (and org-use-fast-tag-selection
14601 (delq nil (mapcar #'cdr table))))
14602 (org-fast-tag-selection
14603 current-tags inherited-tags table
14604 (and org-fast-tag-selection-include-todo
14605 org-todo-key-alist))
14606 (let ((org-add-colon-after-tag-completion
14607 (< 1 (length table))))
14608 (org-trim
14609 (completing-read
14610 "Tags: "
14611 #'org-tags-completion-function
14612 nil nil current 'org-tags-history))))))))))
14614 (when org-tags-sort-function
14615 (setq tags
14616 (mapconcat
14617 #'identity
14618 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14619 org-tags-sort-function)
14620 ":")))
14622 (if (or (string= ":" tags)
14623 (string= "::" tags))
14624 (setq tags ""))
14625 (if (not (org-string-nw-p tags)) (setq tags "")
14626 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14627 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14629 ;; Insert new tags at the correct column.
14630 (unless (equal current tags)
14631 (save-excursion
14632 (beginning-of-line)
14633 (let ((case-fold-search nil))
14634 (looking-at org-complex-heading-regexp))
14635 ;; Remove current tags, if any.
14636 (when (match-end 5) (replace-match "" nil nil nil 5))
14637 ;; Insert new tags, if any. Otherwise, remove trailing
14638 ;; white spaces.
14639 (end-of-line)
14640 (if (not (equal tags ""))
14641 ;; When text is being inserted on an invisible
14642 ;; region boundary, it can be inadvertently sucked
14643 ;; into invisibility.
14644 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14645 (skip-chars-backward " \t")
14646 (delete-region (point) (line-end-position)))))
14647 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14648 ;; is on.
14649 (unless (equal tags "")
14650 (let* ((level (save-excursion
14651 (beginning-of-line)
14652 (skip-chars-forward "\\*")))
14653 (offset (if (bound-and-true-p org-indent-mode)
14654 (* (1- org-indent-indentation-per-level)
14655 (1- level))
14657 (tags-column
14658 (+ org-tags-column
14659 (if (> org-tags-column 0) (- offset) offset))))
14660 (org--align-tags-here tags-column))))
14661 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14663 (defun org-change-tag-in-region (beg end tag off)
14664 "Add or remove TAG for each entry in the region.
14665 This works in the agenda, and also in an Org buffer."
14666 (interactive
14667 (list (region-beginning) (region-end)
14668 (let ((org-last-tags-completion-table
14669 (if (derived-mode-p 'org-mode)
14670 (org-uniquify
14671 (delq nil (append (org-get-buffer-tags)
14672 (org-global-tags-completion-table))))
14673 (org-global-tags-completion-table))))
14674 (completing-read
14675 "Tag: " 'org-tags-completion-function nil nil nil
14676 'org-tags-history))
14677 (progn
14678 (message "[s]et or [r]emove? ")
14679 (equal (read-char-exclusive) ?r))))
14680 (when (fboundp 'deactivate-mark) (deactivate-mark))
14681 (let ((agendap (equal major-mode 'org-agenda-mode))
14682 l1 l2 m buf pos newhead (cnt 0))
14683 (goto-char end)
14684 (setq l2 (1- (org-current-line)))
14685 (goto-char beg)
14686 (setq l1 (org-current-line))
14687 (cl-loop for l from l1 to l2 do
14688 (org-goto-line l)
14689 (setq m (get-text-property (point) 'org-hd-marker))
14690 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14691 (and agendap m))
14692 (setq buf (if agendap (marker-buffer m) (current-buffer))
14693 pos (if agendap m (point)))
14694 (with-current-buffer buf
14695 (save-excursion
14696 (save-restriction
14697 (goto-char pos)
14698 (setq cnt (1+ cnt))
14699 (org-toggle-tag tag (if off 'off 'on))
14700 (setq newhead (org-get-heading)))))
14701 (and agendap (org-agenda-change-all-lines newhead m))))
14702 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14704 (defun org-tags-completion-function (string _predicate &optional flag)
14705 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14706 (confirm (lambda (x) (stringp (car x)))))
14707 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14708 (setq s1 (match-string 1 string)
14709 s2 (match-string 2 string))
14710 (setq s1 "" s2 string))
14711 (cond
14712 ((eq flag nil)
14713 ;; try completion
14714 (setq rtn (try-completion s2 ctable confirm))
14715 (when (stringp rtn)
14716 (setq rtn
14717 (concat s1 s2 (substring rtn (length s2))
14718 (if (and org-add-colon-after-tag-completion
14719 (assoc rtn ctable))
14720 ":" ""))))
14721 rtn)
14722 ((eq flag t)
14723 ;; all-completions
14724 (all-completions s2 ctable confirm))
14725 ((eq flag 'lambda)
14726 ;; exact match?
14727 (assoc s2 ctable)))))
14729 (defun org-fast-tag-insert (kwd tags face &optional end)
14730 "Insert KDW, and the TAGS, the latter with face FACE.
14731 Also insert END."
14732 (insert (format "%-12s" (concat kwd ":"))
14733 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14734 (or end "")))
14736 (defun org-fast-tag-show-exit (flag)
14737 (save-excursion
14738 (org-goto-line 3)
14739 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14740 (replace-match ""))
14741 (when flag
14742 (end-of-line 1)
14743 (org-move-to-column (- (window-width) 19) t)
14744 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14746 (defun org-set-current-tags-overlay (current prefix)
14747 "Add an overlay to CURRENT tag with PREFIX."
14748 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14749 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14750 (org-overlay-display org-tags-overlay (concat prefix s))))
14752 (defvar org-last-tag-selection-key nil)
14753 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14754 "Fast tag selection with single keys.
14755 CURRENT is the current list of tags in the headline, INHERITED is the
14756 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14757 possibly with grouping information. TODO-TABLE is a similar table with
14758 TODO keywords, should these have keys assigned to them.
14759 If the keys are nil, a-z are automatically assigned.
14760 Returns the new tags string, or nil to not change the current settings."
14761 (let* ((fulltable (append table todo-table))
14762 (maxlen (apply 'max (mapcar
14763 (lambda (x)
14764 (if (stringp (car x)) (string-width (car x)) 0))
14765 fulltable)))
14766 (buf (current-buffer))
14767 (expert (eq org-fast-tag-selection-single-key 'expert))
14768 (buffer-tags nil)
14769 (fwidth (+ maxlen 3 1 3))
14770 (ncol (/ (- (window-width) 4) fwidth))
14771 (i-face 'org-done)
14772 (c-face 'org-todo)
14773 tg cnt e c char c1 c2 ntable tbl rtn
14774 ov-start ov-end ov-prefix
14775 (exit-after-next org-fast-tag-selection-single-key)
14776 (done-keywords org-done-keywords)
14777 groups ingroup intaggroup)
14778 (save-excursion
14779 (beginning-of-line 1)
14780 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14781 (setq ov-start (match-beginning 1)
14782 ov-end (match-end 1)
14783 ov-prefix "")
14784 (setq ov-start (1- (point-at-eol))
14785 ov-end (1+ ov-start))
14786 (skip-chars-forward "^\n\r")
14787 (setq ov-prefix
14788 (concat
14789 (buffer-substring (1- (point)) (point))
14790 (if (> (current-column) org-tags-column)
14792 (make-string (- org-tags-column (current-column)) ?\ ))))))
14793 (move-overlay org-tags-overlay ov-start ov-end)
14794 (save-window-excursion
14795 (if expert
14796 (set-buffer (get-buffer-create " *Org tags*"))
14797 (delete-other-windows)
14798 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14799 (org-switch-to-buffer-other-window " *Org tags*"))
14800 (erase-buffer)
14801 (setq-local org-done-keywords done-keywords)
14802 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14803 (org-fast-tag-insert "Current" current c-face "\n\n")
14804 (org-fast-tag-show-exit exit-after-next)
14805 (org-set-current-tags-overlay current ov-prefix)
14806 (setq tbl fulltable char ?a cnt 0)
14807 (while (setq e (pop tbl))
14808 (cond
14809 ((eq (car e) :startgroup)
14810 (push '() groups) (setq ingroup t)
14811 (unless (zerop cnt)
14812 (setq cnt 0)
14813 (insert "\n"))
14814 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14815 ((eq (car e) :endgroup)
14816 (setq ingroup nil cnt 0)
14817 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14818 ((eq (car e) :startgrouptag)
14819 (setq intaggroup t)
14820 (unless (zerop cnt)
14821 (setq cnt 0)
14822 (insert "\n"))
14823 (insert "[ "))
14824 ((eq (car e) :endgrouptag)
14825 (setq intaggroup nil cnt 0)
14826 (insert "]\n"))
14827 ((equal e '(:newline))
14828 (unless (zerop cnt)
14829 (setq cnt 0)
14830 (insert "\n")
14831 (setq e (car tbl))
14832 (while (equal (car tbl) '(:newline))
14833 (insert "\n")
14834 (setq tbl (cdr tbl)))))
14835 ((equal e '(:grouptags)) (insert " : "))
14837 (setq tg (copy-sequence (car e)) c2 nil)
14838 (if (cdr e)
14839 (setq c (cdr e))
14840 ;; automatically assign a character.
14841 (setq c1 (string-to-char
14842 (downcase (substring
14843 tg (if (= (string-to-char tg) ?@) 1 0)))))
14844 (if (or (rassoc c1 ntable) (rassoc c1 table))
14845 (while (or (rassoc char ntable) (rassoc char table))
14846 (setq char (1+ char)))
14847 (setq c2 c1))
14848 (setq c (or c2 char)))
14849 (when ingroup (push tg (car groups)))
14850 (setq tg (org-add-props tg nil 'face
14851 (cond
14852 ((not (assoc tg table))
14853 (org-get-todo-face tg))
14854 ((member tg current) c-face)
14855 ((member tg inherited) i-face))))
14856 (when (equal (caar tbl) :grouptags)
14857 (org-add-props tg nil 'face 'org-tag-group))
14858 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14859 (insert "[" c "] " tg (make-string
14860 (- fwidth 4 (length tg)) ?\ ))
14861 (push (cons tg c) ntable)
14862 (when (= (cl-incf cnt) ncol)
14863 (insert "\n")
14864 (when (or ingroup intaggroup) (insert " "))
14865 (setq cnt 0)))))
14866 (setq ntable (nreverse ntable))
14867 (insert "\n")
14868 (goto-char (point-min))
14869 (unless expert (org-fit-window-to-buffer))
14870 (setq rtn
14871 (catch 'exit
14872 (while t
14873 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14874 (if (not groups) "no " "")
14875 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14876 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14877 (setq org-last-tag-selection-key c)
14878 (cond
14879 ((= c ?\r) (throw 'exit t))
14880 ((= c ?!)
14881 (setq groups (not groups))
14882 (goto-char (point-min))
14883 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14884 ((= c ?\C-c)
14885 (if (not expert)
14886 (org-fast-tag-show-exit
14887 (setq exit-after-next (not exit-after-next)))
14888 (setq expert nil)
14889 (delete-other-windows)
14890 (set-window-buffer (split-window-vertically) " *Org tags*")
14891 (org-switch-to-buffer-other-window " *Org tags*")
14892 (org-fit-window-to-buffer)))
14893 ((or (= c ?\C-g)
14894 (and (= c ?q) (not (rassoc c ntable))))
14895 (delete-overlay org-tags-overlay)
14896 (setq quit-flag t))
14897 ((= c ?\ )
14898 (setq current nil)
14899 (when exit-after-next (setq exit-after-next 'now)))
14900 ((= c ?\t)
14901 (condition-case nil
14902 (setq tg (completing-read
14903 "Tag: "
14904 (or buffer-tags
14905 (with-current-buffer buf
14906 (setq buffer-tags
14907 (org-get-buffer-tags))))))
14908 (quit (setq tg "")))
14909 (when (string-match "\\S-" tg)
14910 (cl-pushnew (list tg) buffer-tags :test #'equal)
14911 (if (member tg current)
14912 (setq current (delete tg current))
14913 (push tg current)))
14914 (when exit-after-next (setq exit-after-next 'now)))
14915 ((setq e (rassoc c todo-table) tg (car e))
14916 (with-current-buffer buf
14917 (save-excursion (org-todo tg)))
14918 (when exit-after-next (setq exit-after-next 'now)))
14919 ((setq e (rassoc c ntable) tg (car e))
14920 (if (member tg current)
14921 (setq current (delete tg current))
14922 (cl-loop for g in groups do
14923 (when (member tg g)
14924 (dolist (x g) (setq current (delete x current)))))
14925 (push tg current))
14926 (when exit-after-next (setq exit-after-next 'now))))
14928 ;; Create a sorted list
14929 (setq current
14930 (sort current
14931 (lambda (a b)
14932 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14933 (when (eq exit-after-next 'now) (throw 'exit t))
14934 (goto-char (point-min))
14935 (beginning-of-line 2)
14936 (delete-region (point) (point-at-eol))
14937 (org-fast-tag-insert "Current" current c-face)
14938 (org-set-current-tags-overlay current ov-prefix)
14939 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14940 (setq tg (match-string 1))
14941 (add-text-properties
14942 (match-beginning 1) (match-end 1)
14943 (list 'face
14944 (cond
14945 ((member tg current) c-face)
14946 ((member tg inherited) i-face)
14947 (t (get-text-property (match-beginning 1) 'face))))))
14948 (goto-char (point-min)))))
14949 (delete-overlay org-tags-overlay)
14950 (if rtn
14951 (mapconcat 'identity current ":")
14952 nil))))
14954 (defun org-get-tags-string ()
14955 "Get the TAGS string in the current headline."
14956 (unless (org-at-heading-p t)
14957 (user-error "Not on a heading"))
14958 (save-excursion
14959 (beginning-of-line 1)
14960 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14961 (match-string-no-properties 1)
14962 "")))
14964 (defun org-get-tags ()
14965 "Get the list of tags specified in the current headline."
14966 (org-split-string (org-get-tags-string) ":"))
14968 (defun org-get-buffer-tags ()
14969 "Get a table of all tags used in the buffer, for completion."
14970 (org-with-wide-buffer
14971 (goto-char (point-min))
14972 (let ((tag-re (concat org-outline-regexp-bol
14973 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14974 tags)
14975 (while (re-search-forward tag-re nil t)
14976 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14977 (push tag tags)))
14978 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14980 ;;;; The mapping API
14982 (defvar org-agenda-skip-comment-trees)
14983 (defvar org-agenda-skip-function)
14984 (defun org-map-entries (func &optional match scope &rest skip)
14985 "Call FUNC at each headline selected by MATCH in SCOPE.
14987 FUNC is a function or a lisp form. The function will be called without
14988 arguments, with the cursor positioned at the beginning of the headline.
14989 The return values of all calls to the function will be collected and
14990 returned as a list.
14992 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14993 does not need to preserve point. After evaluation, the cursor will be
14994 moved to the end of the line (presumably of the headline of the
14995 processed entry) and search continues from there. Under some
14996 circumstances, this may not produce the wanted results. For example,
14997 if you have removed (e.g. archived) the current (sub)tree it could
14998 mean that the next entry will be skipped entirely. In such cases, you
14999 can specify the position from where search should continue by making
15000 FUNC set the variable `org-map-continue-from' to the desired buffer
15001 position.
15003 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15004 Only headlines that are matched by this query will be considered during
15005 the iteration. When MATCH is nil or t, all headlines will be
15006 visited by the iteration.
15008 SCOPE determines the scope of this command. It can be any of:
15010 nil The current buffer, respecting the restriction if any
15011 tree The subtree started with the entry at point
15012 region The entries within the active region, if any
15013 region-start-level
15014 The entries within the active region, but only those at
15015 the same level than the first one.
15016 file The current buffer, without restriction
15017 file-with-archives
15018 The current buffer, and any archives associated with it
15019 agenda All agenda files
15020 agenda-with-archives
15021 All agenda files with any archive files associated with them
15022 \(file1 file2 ...)
15023 If this is a list, all files in the list will be scanned
15025 The remaining args are treated as settings for the skipping facilities of
15026 the scanner. The following items can be given here:
15028 archive skip trees with the archive tag
15029 comment skip trees with the COMMENT keyword
15030 function or Emacs Lisp form:
15031 will be used as value for `org-agenda-skip-function', so
15032 whenever the function returns a position, FUNC will not be
15033 called for that entry and search will continue from the
15034 position returned
15036 If your function needs to retrieve the tags including inherited tags
15037 at the *current* entry, you can use the value of the variable
15038 `org-scanner-tags' which will be much faster than getting the value
15039 with `org-get-tags-at'. If your function gets properties with
15040 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15041 to t around the call to `org-entry-properties' to get the same speedup.
15042 Note that if your function moves around to retrieve tags and properties at
15043 a *different* entry, you cannot use these techniques."
15044 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15045 (not (org-region-active-p)))
15046 (let* ((org-agenda-archives-mode nil) ; just to make sure
15047 (org-agenda-skip-archived-trees (memq 'archive skip))
15048 (org-agenda-skip-comment-trees (memq 'comment skip))
15049 (org-agenda-skip-function
15050 (car (org-delete-all '(comment archive) skip)))
15051 (org-tags-match-list-sublevels t)
15052 (start-level (eq scope 'region-start-level))
15053 matcher res
15054 org-todo-keywords-for-agenda
15055 org-done-keywords-for-agenda
15056 org-todo-keyword-alist-for-agenda
15057 org-tag-alist-for-agenda
15058 org--matcher-tags-todo-only)
15060 (cond
15061 ((eq match t) (setq matcher t))
15062 ((eq match nil) (setq matcher t))
15063 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15065 (save-excursion
15066 (save-restriction
15067 (cond ((eq scope 'tree)
15068 (org-back-to-heading t)
15069 (org-narrow-to-subtree)
15070 (setq scope nil))
15071 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15072 (org-region-active-p))
15073 ;; If needed, set start-level to a string like "2"
15074 (when start-level
15075 (save-excursion
15076 (goto-char (region-beginning))
15077 (unless (org-at-heading-p) (outline-next-heading))
15078 (setq start-level (org-current-level))))
15079 (narrow-to-region (region-beginning)
15080 (save-excursion
15081 (goto-char (region-end))
15082 (unless (and (bolp) (org-at-heading-p))
15083 (outline-next-heading))
15084 (point)))
15085 (setq scope nil)))
15087 (if (not scope)
15088 (progn
15089 (org-agenda-prepare-buffers
15090 (and buffer-file-name (list buffer-file-name)))
15091 (setq res
15092 (org-scan-tags
15093 func matcher org--matcher-tags-todo-only start-level)))
15094 ;; Get the right scope
15095 (cond
15096 ((and scope (listp scope) (symbolp (car scope)))
15097 (setq scope (eval scope)))
15098 ((eq scope 'agenda)
15099 (setq scope (org-agenda-files t)))
15100 ((eq scope 'agenda-with-archives)
15101 (setq scope (org-agenda-files t))
15102 (setq scope (org-add-archive-files scope)))
15103 ((eq scope 'file)
15104 (setq scope (and buffer-file-name (list buffer-file-name))))
15105 ((eq scope 'file-with-archives)
15106 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15107 (org-agenda-prepare-buffers scope)
15108 (dolist (file scope)
15109 (with-current-buffer (org-find-base-buffer-visiting file)
15110 (org-with-wide-buffer
15111 (goto-char (point-min))
15112 (setq res
15113 (append
15115 (org-scan-tags
15116 func matcher org--matcher-tags-todo-only)))))))))
15117 res)))
15119 ;;; Properties API
15121 (defconst org-special-properties
15122 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15123 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15124 "The special properties valid in Org mode.
15125 These are properties that are not defined in the property drawer,
15126 but in some other way.")
15128 (defconst org-default-properties
15129 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15130 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15131 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15132 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15133 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15134 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15135 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15136 "Some properties that are used by Org mode for various purposes.
15137 Being in this list makes sure that they are offered for completion.")
15139 (defun org--valid-property-p (property)
15140 "Non nil when string PROPERTY is a valid property name."
15141 (not
15142 (or (equal property "")
15143 (string-match-p "\\s-" property))))
15145 (defun org--update-property-plist (key val props)
15146 "Associate KEY to VAL in alist PROPS.
15147 Modifications are made by side-effect. Return new alist."
15148 (let* ((appending (string= (substring key -1) "+"))
15149 (key (if appending (substring key 0 -1) key))
15150 (old (assoc-string key props t)))
15151 (if (not old) (cons (cons key val) props)
15152 (setcdr old (if appending (concat (cdr old) " " val) val))
15153 props)))
15155 (defun org-get-property-block (&optional beg force)
15156 "Return the (beg . end) range of the body of the property drawer.
15157 BEG is the beginning of the current subtree, or of the part
15158 before the first headline. If it is not given, it will be found.
15159 If the drawer does not exist, create it if FORCE is non-nil, or
15160 return nil."
15161 (org-with-wide-buffer
15162 (when beg (goto-char beg))
15163 (unless (org-before-first-heading-p)
15164 (let ((beg (cond (beg)
15165 ((or (not (featurep 'org-inlinetask))
15166 (org-inlinetask-in-task-p))
15167 (org-back-to-heading t))
15168 (t (org-with-limited-levels (org-back-to-heading t))))))
15169 (forward-line)
15170 (when (looking-at-p org-planning-line-re) (forward-line))
15171 (cond ((looking-at org-property-drawer-re)
15172 (forward-line)
15173 (cons (point) (progn (goto-char (match-end 0))
15174 (line-beginning-position))))
15175 (force
15176 (goto-char beg)
15177 (org-insert-property-drawer)
15178 (let ((pos (save-excursion (search-forward ":END:")
15179 (line-beginning-position))))
15180 (cons pos pos))))))))
15182 (defun org-at-property-p ()
15183 "Non-nil when point is inside a property drawer.
15184 See `org-property-re' for match data, if applicable."
15185 (save-excursion
15186 (beginning-of-line)
15187 (and (looking-at org-property-re)
15188 (let ((property-drawer (save-match-data (org-get-property-block))))
15189 (and property-drawer
15190 (>= (point) (car property-drawer))
15191 (< (point) (cdr property-drawer)))))))
15193 (defun org-property-action ()
15194 "Do an action on properties."
15195 (interactive)
15196 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15197 (let ((c (read-char-exclusive)))
15198 (cl-case c
15199 (?s (call-interactively #'org-set-property))
15200 (?d (call-interactively #'org-delete-property))
15201 (?D (call-interactively #'org-delete-property-globally))
15202 (?c (call-interactively #'org-compute-property-at-point))
15203 (otherwise (user-error "No such property action %c" c)))))
15205 (defun org-inc-effort ()
15206 "Increment the value of the effort property in the current entry."
15207 (interactive)
15208 (org-set-effort nil t))
15210 (defvar org-clock-effort) ; Defined in org-clock.el.
15211 (defvar org-clock-current-task) ; Defined in org-clock.el.
15212 (defun org-set-effort (&optional value increment)
15213 "Set the effort property of the current entry.
15214 With numerical prefix arg, use the nth allowed value, 0 stands for the
15215 10th allowed value.
15217 When INCREMENT is non-nil, set the property to the next allowed value."
15218 (interactive "P")
15219 (when (equal value 0) (setq value 10))
15220 (let* ((completion-ignore-case t)
15221 (prop org-effort-property)
15222 (cur (org-entry-get nil prop))
15223 (allowed (org-property-get-allowed-values nil prop 'table))
15224 (existing (mapcar 'list (org-property-values prop)))
15225 (heading (nth 4 (org-heading-components)))
15227 (val (cond
15228 ((stringp value) value)
15229 ((and allowed (integerp value))
15230 (or (car (nth (1- value) allowed))
15231 (car (org-last allowed))))
15232 ((and allowed increment)
15233 (or (cl-caadr (member (list cur) allowed))
15234 (user-error "Allowed effort values are not set")))
15235 (allowed
15236 (message "Select 1-9,0, [RET%s]: %s"
15237 (if cur (concat "=" cur) "")
15238 (mapconcat 'car allowed " "))
15239 (setq rpl (read-char-exclusive))
15240 (if (equal rpl ?\r)
15242 (setq rpl (- rpl ?0))
15243 (when (equal rpl 0) (setq rpl 10))
15244 (if (and (> rpl 0) (<= rpl (length allowed)))
15245 (car (nth (1- rpl) allowed))
15246 (org-completing-read "Effort: " allowed nil))))
15248 (org-completing-read
15249 (concat "Effort" (and cur (string-match "\\S-" cur)
15250 (concat " [" cur "]"))
15251 ": ")
15252 existing nil nil "" nil cur)))))
15253 (unless (equal (org-entry-get nil prop) val)
15254 (org-entry-put nil prop val))
15255 (org-refresh-property
15256 '((effort . identity)
15257 (effort-minutes . org-duration-to-minutes))
15258 val)
15259 (when (equal heading (bound-and-true-p org-clock-current-task))
15260 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15261 (org-clock-update-mode-line))
15262 (message "%s is now %s" prop val)))
15264 (defun org-entry-properties (&optional pom which)
15265 "Get all properties of the current entry.
15267 When POM is a buffer position, get all properties from the entry
15268 there instead.
15270 This includes the TODO keyword, the tags, time strings for
15271 deadline, scheduled, and clocking, and any additional properties
15272 defined in the entry.
15274 If WHICH is nil or `all', get all properties. If WHICH is
15275 `special' or `standard', only get that subclass. If WHICH is
15276 a string, only get that property.
15278 Return value is an alist. Keys are properties, as upcased
15279 strings."
15280 (org-with-point-at pom
15281 (when (and (derived-mode-p 'org-mode)
15282 (ignore-errors (org-back-to-heading t)))
15283 (catch 'exit
15284 (let* ((beg (point))
15285 (specific (and (stringp which) (upcase which)))
15286 (which (cond ((not specific) which)
15287 ((member specific org-special-properties) 'special)
15288 (t 'standard)))
15289 props)
15290 ;; Get the special properties, like TODO and TAGS.
15291 (when (memq which '(nil all special))
15292 (when (or (not specific) (string= specific "CLOCKSUM"))
15293 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15294 (when clocksum
15295 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15296 props)))
15297 (when specific (throw 'exit props)))
15298 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15299 (let ((clocksumt (get-text-property (point)
15300 :org-clock-minutes-today)))
15301 (when clocksumt
15302 (push (cons "CLOCKSUM_T"
15303 (org-duration-from-minutes clocksumt))
15304 props)))
15305 (when specific (throw 'exit props)))
15306 (when (or (not specific) (string= specific "ITEM"))
15307 (let ((case-fold-search nil))
15308 (when (looking-at org-complex-heading-regexp)
15309 (push (cons "ITEM"
15310 (let ((title (match-string-no-properties 4)))
15311 (if (org-string-nw-p title)
15312 (org-remove-tabs title)
15313 "")))
15314 props)))
15315 (when specific (throw 'exit props)))
15316 (when (or (not specific) (string= specific "TODO"))
15317 (let ((case-fold-search nil))
15318 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15319 (push (cons "TODO" (match-string-no-properties 2)) props)))
15320 (when specific (throw 'exit props)))
15321 (when (or (not specific) (string= specific "PRIORITY"))
15322 (push (cons "PRIORITY"
15323 (if (looking-at org-priority-regexp)
15324 (match-string-no-properties 2)
15325 (char-to-string org-default-priority)))
15326 props)
15327 (when specific (throw 'exit props)))
15328 (when (or (not specific) (string= specific "FILE"))
15329 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15330 props)
15331 (when specific (throw 'exit props)))
15332 (when (or (not specific) (string= specific "TAGS"))
15333 (let ((value (org-string-nw-p (org-get-tags-string))))
15334 (when value (push (cons "TAGS" value) props)))
15335 (when specific (throw 'exit props)))
15336 (when (or (not specific) (string= specific "ALLTAGS"))
15337 (let ((value (org-get-tags-at)))
15338 (when value
15339 (push (cons "ALLTAGS"
15340 (format ":%s:" (mapconcat #'identity value ":")))
15341 props)))
15342 (when specific (throw 'exit props)))
15343 (when (or (not specific) (string= specific "BLOCKED"))
15344 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15345 (when specific (throw 'exit props)))
15346 (when (or (not specific)
15347 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15348 (forward-line)
15349 (when (looking-at-p org-planning-line-re)
15350 (end-of-line)
15351 (let ((bol (line-beginning-position))
15352 ;; Backward compatibility: time keywords used to
15353 ;; be configurable (before 8.3). Make sure we
15354 ;; get the correct keyword.
15355 (key-assoc `(("CLOSED" . ,org-closed-string)
15356 ("DEADLINE" . ,org-deadline-string)
15357 ("SCHEDULED" . ,org-scheduled-string))))
15358 (dolist (pair (if specific (list (assoc specific key-assoc))
15359 key-assoc))
15360 (save-excursion
15361 (when (search-backward (cdr pair) bol t)
15362 (goto-char (match-end 0))
15363 (skip-chars-forward " \t")
15364 (and (looking-at org-ts-regexp-both)
15365 (push (cons (car pair)
15366 (match-string-no-properties 0))
15367 props)))))))
15368 (when specific (throw 'exit props)))
15369 (when (or (not specific)
15370 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15371 (let ((find-ts
15372 (lambda (end ts)
15373 ;; Fix next time-stamp before END. TS is the
15374 ;; list of time-stamps found so far.
15375 (let ((ts ts)
15376 (regexp (cond
15377 ((string= specific "TIMESTAMP")
15378 org-ts-regexp)
15379 ((string= specific "TIMESTAMP_IA")
15380 org-ts-regexp-inactive)
15381 ((assoc "TIMESTAMP_IA" ts)
15382 org-ts-regexp)
15383 ((assoc "TIMESTAMP" ts)
15384 org-ts-regexp-inactive)
15385 (t org-ts-regexp-both))))
15386 (catch 'next
15387 (while (re-search-forward regexp end t)
15388 (backward-char)
15389 (let ((object (org-element-context)))
15390 ;; Accept to match timestamps in node
15391 ;; properties, too.
15392 (when (memq (org-element-type object)
15393 '(node-property timestamp))
15394 (let ((type
15395 (org-element-property :type object)))
15396 (cond
15397 ((and (memq type '(active active-range))
15398 (not (equal specific "TIMESTAMP_IA")))
15399 (unless (assoc "TIMESTAMP" ts)
15400 (push (cons "TIMESTAMP"
15401 (org-element-property
15402 :raw-value object))
15404 (when specific (throw 'exit ts))))
15405 ((and (memq type '(inactive inactive-range))
15406 (not (string= specific "TIMESTAMP")))
15407 (unless (assoc "TIMESTAMP_IA" ts)
15408 (push (cons "TIMESTAMP_IA"
15409 (org-element-property
15410 :raw-value object))
15412 (when specific (throw 'exit ts))))))
15413 ;; Both timestamp types are found,
15414 ;; move to next part.
15415 (when (= (length ts) 2) (throw 'next ts)))))
15416 ts)))))
15417 (goto-char beg)
15418 ;; First look for timestamps within headline.
15419 (let ((ts (funcall find-ts (line-end-position) nil)))
15420 (if (= (length ts) 2) (setq props (nconc ts props))
15421 ;; Then find timestamps in the section, skipping
15422 ;; planning line.
15423 (let ((end (save-excursion (outline-next-heading))))
15424 (forward-line)
15425 (when (looking-at-p org-planning-line-re) (forward-line))
15426 (setq props (nconc (funcall find-ts end ts) props))))))))
15427 ;; Get the standard properties, like :PROP:.
15428 (when (memq which '(nil all standard))
15429 ;; If we are looking after a specific property, delegate
15430 ;; to `org-entry-get', which is faster. However, make an
15431 ;; exception for "CATEGORY", since it can be also set
15432 ;; through keywords (i.e. #+CATEGORY).
15433 (if (and specific (not (equal specific "CATEGORY")))
15434 (let ((value (org-entry-get beg specific nil t)))
15435 (throw 'exit (and value (list (cons specific value)))))
15436 (let ((range (org-get-property-block beg)))
15437 (when range
15438 (let ((end (cdr range)) seen-base)
15439 (goto-char (car range))
15440 ;; Unlike to `org--update-property-plist', we
15441 ;; handle the case where base values is found
15442 ;; after its extension. We also forbid standard
15443 ;; properties to be named as special properties.
15444 (while (re-search-forward org-property-re end t)
15445 (let* ((key (upcase (match-string-no-properties 2)))
15446 (extendp (string-match-p "\\+\\'" key))
15447 (key-base (if extendp (substring key 0 -1) key))
15448 (value (match-string-no-properties 3)))
15449 (cond
15450 ((member-ignore-case key-base org-special-properties))
15451 (extendp
15452 (setq props
15453 (org--update-property-plist key value props)))
15454 ((member key seen-base))
15455 (t (push key seen-base)
15456 (let ((p (assoc-string key props t)))
15457 (if p (setcdr p (concat value " " (cdr p)))
15458 (push (cons key value) props))))))))))))
15459 (unless (assoc "CATEGORY" props)
15460 (push (cons "CATEGORY" (org-get-category beg)) props)
15461 (when (string= specific "CATEGORY") (throw 'exit props)))
15462 ;; Return value.
15463 props)))))
15465 (defun org--property-local-values (property literal-nil)
15466 "Return value for PROPERTY in current entry.
15467 Value is a list whose car is the base value for PROPERTY and cdr
15468 a list of accumulated values. Return nil if neither is found in
15469 the entry. Also return nil when PROPERTY is set to \"nil\",
15470 unless LITERAL-NIL is non-nil."
15471 (let ((range (org-get-property-block)))
15472 (when range
15473 (goto-char (car range))
15474 (let* ((case-fold-search t)
15475 (end (cdr range))
15476 (value
15477 ;; Base value.
15478 (save-excursion
15479 (let ((v (and (re-search-forward
15480 (org-re-property property nil t) end t)
15481 (match-string-no-properties 3))))
15482 (list (if literal-nil v (org-not-nil v)))))))
15483 ;; Find additional values.
15484 (let* ((property+ (org-re-property (concat property "+") nil t)))
15485 (while (re-search-forward property+ end t)
15486 (push (match-string-no-properties 3) value)))
15487 ;; Return final values.
15488 (and (not (equal value '(nil))) (nreverse value))))))
15490 (defun org--property-global-value (property literal-nil)
15491 "Return value for PROPERTY in current buffer.
15492 Return value is a string. Return nil if property is not set
15493 globally. Also return nil when PROPERTY is set to \"nil\",
15494 unless LITERAL-NIL is non-nil."
15495 (let ((global
15496 (cdr (or (assoc-string property org-file-properties t)
15497 (assoc-string property org-global-properties t)
15498 (assoc-string property org-global-properties-fixed t)))))
15499 (if literal-nil global (org-not-nil global))))
15501 (defun org-entry-get (pom property &optional inherit literal-nil)
15502 "Get value of PROPERTY for entry or content at point-or-marker POM.
15504 If INHERIT is non-nil and the entry does not have the property,
15505 then also check higher levels of the hierarchy. If INHERIT is
15506 the symbol `selective', use inheritance only if the setting in
15507 `org-use-property-inheritance' selects PROPERTY for inheritance.
15509 If the property is present but empty, the return value is the
15510 empty string. If the property is not present at all, nil is
15511 returned. In any other case, return the value as a string.
15512 Search is case-insensitive.
15514 If LITERAL-NIL is set, return the string value \"nil\" as
15515 a string, do not interpret it as the list atom nil. This is used
15516 for inheritance when a \"nil\" value can supersede a non-nil
15517 value higher up the hierarchy."
15518 (org-with-point-at pom
15519 (cond
15520 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15521 ;; We need a special property. Use `org-entry-properties' to
15522 ;; retrieve it, but specify the wanted property.
15523 (cdr (assoc-string property (org-entry-properties nil property))))
15524 ((and inherit
15525 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15526 (org-entry-get-with-inheritance property literal-nil))
15528 (let* ((local (org--property-local-values property literal-nil))
15529 (value (and local (mapconcat #'identity (delq nil local) " "))))
15530 (if literal-nil value (org-not-nil value)))))))
15532 (defun org-property-or-variable-value (var &optional inherit)
15533 "Check if there is a property fixing the value of VAR.
15534 If yes, return this value. If not, return the current value of the variable."
15535 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15536 (if (and prop (stringp prop) (string-match "\\S-" prop))
15537 (read prop)
15538 (symbol-value var))))
15540 (defun org-entry-delete (pom property)
15541 "Delete PROPERTY from entry at point-or-marker POM.
15542 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15543 non-nil when a property was removed."
15544 (org-with-point-at pom
15545 (pcase (org-get-property-block)
15546 (`(,begin . ,origin)
15547 (let* ((end (copy-marker origin))
15548 (re (org-re-property
15549 (concat (regexp-quote property) "\\+?") t t)))
15550 (goto-char begin)
15551 (while (re-search-forward re end t)
15552 (delete-region (match-beginning 0) (line-beginning-position 2)))
15553 ;; If drawer is empty, remove it altogether.
15554 (when (= begin end)
15555 (delete-region (line-beginning-position 0)
15556 (line-beginning-position 2)))
15557 ;; Return non-nil if some property was removed.
15558 (prog1 (/= end origin) (set-marker end nil))))
15559 (_ nil))))
15561 ;; Multi-values properties are properties that contain multiple values
15562 ;; These values are assumed to be single words, separated by whitespace.
15563 (defun org-entry-add-to-multivalued-property (pom property value)
15564 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15565 (let* ((old (org-entry-get pom property))
15566 (values (and old (split-string old))))
15567 (setq value (org-entry-protect-space value))
15568 (unless (member value values)
15569 (setq values (append values (list value)))
15570 (org-entry-put pom property (mapconcat #'identity values " ")))))
15572 (defun org-entry-remove-from-multivalued-property (pom property value)
15573 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15574 (let* ((old (org-entry-get pom property))
15575 (values (and old (split-string old))))
15576 (setq value (org-entry-protect-space value))
15577 (when (member value values)
15578 (setq values (delete value values))
15579 (org-entry-put pom property (mapconcat #'identity values " ")))))
15581 (defun org-entry-member-in-multivalued-property (pom property value)
15582 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15583 (let* ((old (org-entry-get pom property))
15584 (values (and old (split-string old))))
15585 (setq value (org-entry-protect-space value))
15586 (member value values)))
15588 (defun org-entry-get-multivalued-property (pom property)
15589 "Return a list of values in a multivalued property."
15590 (let* ((value (org-entry-get pom property))
15591 (values (and value (split-string value))))
15592 (mapcar #'org-entry-restore-space values)))
15594 (defun org-entry-put-multivalued-property (pom property &rest values)
15595 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15596 VALUES should be a list of strings. Spaces will be protected."
15597 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15598 (let* ((value (org-entry-get pom property))
15599 (values (and value (split-string value))))
15600 (mapcar #'org-entry-restore-space values)))
15602 (defun org-entry-protect-space (s)
15603 "Protect spaces and newline in string S."
15604 (while (string-match " " s)
15605 (setq s (replace-match "%20" t t s)))
15606 (while (string-match "\n" s)
15607 (setq s (replace-match "%0A" t t s)))
15610 (defun org-entry-restore-space (s)
15611 "Restore spaces and newline in string S."
15612 (while (string-match "%20" s)
15613 (setq s (replace-match " " t t s)))
15614 (while (string-match "%0A" s)
15615 (setq s (replace-match "\n" t t s)))
15618 (defvar org-entry-property-inherited-from (make-marker)
15619 "Marker pointing to the entry from where a property was inherited.
15620 Each call to `org-entry-get-with-inheritance' will set this marker to the
15621 location of the entry where the inheritance search matched. If there was
15622 no match, the marker will point nowhere.
15623 Note that also `org-entry-get' calls this function, if the INHERIT flag
15624 is set.")
15626 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15627 "Get PROPERTY of entry or content at point, search higher levels if needed.
15628 The search will stop at the first ancestor which has the property defined.
15629 If the value found is \"nil\", return nil to show that the property
15630 should be considered as undefined (this is the meaning of nil here).
15631 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15632 (move-marker org-entry-property-inherited-from nil)
15633 (org-with-wide-buffer
15634 (let (value)
15635 (catch 'exit
15636 (while t
15637 (let ((v (org--property-local-values property literal-nil)))
15638 (when v
15639 (setq value
15640 (concat (mapconcat #'identity (delq nil v) " ")
15641 (and value " ")
15642 value)))
15643 (cond
15644 ((car v)
15645 (org-back-to-heading t)
15646 (move-marker org-entry-property-inherited-from (point))
15647 (throw 'exit nil))
15648 ((org-up-heading-safe))
15650 (let ((global (org--property-global-value property literal-nil)))
15651 (cond ((not global))
15652 (value (setq value (concat global " " value)))
15653 (t (setq value global))))
15654 (throw 'exit nil))))))
15655 (if literal-nil value (org-not-nil value)))))
15657 (defvar org-property-changed-functions nil
15658 "Hook called when the value of a property has changed.
15659 Each hook function should accept two arguments, the name of the property
15660 and the new value.")
15662 (defun org-entry-put (pom property value)
15663 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15665 If the value is nil, it is converted to the empty string. If it
15666 is not a string, an error is raised. Also raise an error on
15667 invalid property names.
15669 PROPERTY can be any regular property (see
15670 `org-special-properties'). It can also be \"TODO\",
15671 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15673 For the last two properties, VALUE may have any of the special
15674 values \"earlier\" and \"later\". The function then increases or
15675 decreases scheduled or deadline date by one day."
15676 (cond ((null value) (setq value ""))
15677 ((not (stringp value)) (error "Properties values should be strings"))
15678 ((not (org--valid-property-p property))
15679 (user-error "Invalid property name: \"%s\"" property)))
15680 (org-with-point-at pom
15681 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15682 (org-back-to-heading t)
15683 (org-with-limited-levels (org-back-to-heading t)))
15684 (let ((beg (point)))
15685 (cond
15686 ((equal property "TODO")
15687 (cond ((not (org-string-nw-p value)) (setq value 'none))
15688 ((not (member value org-todo-keywords-1))
15689 (user-error "\"%s\" is not a valid TODO state" value)))
15690 (org-todo value)
15691 (org-set-tags nil 'align))
15692 ((equal property "PRIORITY")
15693 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15694 (org-set-tags nil 'align))
15695 ((equal property "SCHEDULED")
15696 (forward-line)
15697 (if (and (looking-at-p org-planning-line-re)
15698 (re-search-forward
15699 org-scheduled-time-regexp (line-end-position) t))
15700 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15701 ((string= value "later") (org-timestamp-change 1 'day))
15702 ((string= value "") (org-schedule '(4)))
15703 (t (org-schedule nil value)))
15704 (if (member value '("earlier" "later" ""))
15705 (call-interactively #'org-schedule)
15706 (org-schedule nil value))))
15707 ((equal property "DEADLINE")
15708 (forward-line)
15709 (if (and (looking-at-p org-planning-line-re)
15710 (re-search-forward
15711 org-deadline-time-regexp (line-end-position) t))
15712 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15713 ((string= value "later") (org-timestamp-change 1 'day))
15714 ((string= value "") (org-deadline '(4)))
15715 (t (org-deadline nil value)))
15716 (if (member value '("earlier" "later" ""))
15717 (call-interactively #'org-deadline)
15718 (org-deadline nil value))))
15719 ((member property org-special-properties)
15720 (error "The %s property cannot be set with `org-entry-put'" property))
15722 (let* ((range (org-get-property-block beg 'force))
15723 (end (cdr range))
15724 (case-fold-search t))
15725 (goto-char (car range))
15726 (if (re-search-forward (org-re-property property nil t) end t)
15727 (progn (delete-region (match-beginning 0) (match-end 0))
15728 (goto-char (match-beginning 0)))
15729 (goto-char end)
15730 (insert "\n")
15731 (backward-char))
15732 (insert ":" property ":")
15733 (when value (insert " " value))
15734 (org-indent-line)))))
15735 (run-hook-with-args 'org-property-changed-functions property value)))
15737 (defun org-buffer-property-keys (&optional specials defaults columns)
15738 "Get all property keys in the current buffer.
15740 When SPECIALS is non-nil, also list the special properties that
15741 reflect things like tags and TODO state.
15743 When DEFAULTS is non-nil, also include properties that has
15744 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15745 DESCRIPTION, LOCATION, and LOGGING and others.
15747 When COLUMNS in non-nil, also include property names given in
15748 COLUMN formats in the current buffer."
15749 (let ((case-fold-search t)
15750 (props (append
15751 (and specials org-special-properties)
15752 (and defaults (cons org-effort-property org-default-properties))
15753 nil)))
15754 (org-with-wide-buffer
15755 (goto-char (point-min))
15756 (while (re-search-forward org-property-start-re nil t)
15757 (catch :skip
15758 (let ((range (org-get-property-block)))
15759 (unless range (throw :skip nil))
15760 (goto-char (car range))
15761 (let ((begin (car range))
15762 (end (cdr range)))
15763 ;; Make sure that found property block is not located
15764 ;; before current point, as it would generate an infloop.
15765 ;; It can happen, for example, in the following
15766 ;; situation:
15768 ;; * Headline
15769 ;; :PROPERTIES:
15770 ;; ...
15771 ;; :END:
15772 ;; *************** Inlinetask
15773 ;; #+BEGIN_EXAMPLE
15774 ;; :PROPERTIES:
15775 ;; #+END_EXAMPLE
15777 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15778 (while (< (point) end)
15779 (let ((p (progn (looking-at org-property-re)
15780 (match-string-no-properties 2))))
15781 ;; Only add true property name, not extension symbol.
15782 (push (if (not (string-match-p "\\+\\'" p)) p
15783 (substring p 0 -1))
15784 props))
15785 (forward-line))))
15786 (outline-next-heading)))
15787 (when columns
15788 (goto-char (point-min))
15789 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15790 (let ((element (org-element-at-point)))
15791 (when (memq (org-element-type element) '(keyword node-property))
15792 (let ((value (org-element-property :value element))
15793 (start 0))
15794 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15795 \\(?:{[^}]+}\\)?"
15796 value start)
15797 (setq start (match-end 0))
15798 (let ((p (match-string-no-properties 1 value)))
15799 (unless (member-ignore-case p org-special-properties)
15800 (push p props))))))))))
15801 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15803 (defun org-property-values (key)
15804 "List all non-nil values of property KEY in current buffer."
15805 (org-with-wide-buffer
15806 (goto-char (point-min))
15807 (let ((case-fold-search t)
15808 (re (org-re-property key))
15809 values)
15810 (while (re-search-forward re nil t)
15811 (push (org-entry-get (point) key) values))
15812 (delete-dups values))))
15814 (defun org-insert-property-drawer ()
15815 "Insert a property drawer into the current entry."
15816 (org-with-wide-buffer
15817 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15818 (org-back-to-heading t)
15819 (org-with-limited-levels (org-back-to-heading t)))
15820 (forward-line)
15821 (when (looking-at-p org-planning-line-re) (forward-line))
15822 (unless (looking-at-p org-property-drawer-re)
15823 ;; Make sure we start editing a line from current entry, not from
15824 ;; next one. It prevents extending text properties or overlays
15825 ;; belonging to the latter.
15826 (when (bolp) (backward-char))
15827 (let ((begin (1+ (point)))
15828 (inhibit-read-only t))
15829 (insert "\n:PROPERTIES:\n:END:")
15830 (when (eobp) (insert "\n"))
15831 (org-indent-region begin (point))))))
15833 (defun org-insert-drawer (&optional arg drawer)
15834 "Insert a drawer at point.
15836 When optional argument ARG is non-nil, insert a property drawer.
15838 Optional argument DRAWER, when non-nil, is a string representing
15839 drawer's name. Otherwise, the user is prompted for a name.
15841 If a region is active, insert the drawer around that region
15842 instead.
15844 Point is left between drawer's boundaries."
15845 (interactive "P")
15846 (let* ((drawer (if arg "PROPERTIES"
15847 (or drawer (read-from-minibuffer "Drawer: ")))))
15848 (cond
15849 ;; With C-u, fall back on `org-insert-property-drawer'
15850 (arg (org-insert-property-drawer))
15851 ;; Check validity of suggested drawer's name.
15852 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15853 (user-error "Invalid drawer name"))
15854 ;; With an active region, insert a drawer at point.
15855 ((not (org-region-active-p))
15856 (progn
15857 (unless (bolp) (insert "\n"))
15858 (insert (format ":%s:\n\n:END:\n" drawer))
15859 (forward-line -2)))
15860 ;; Otherwise, insert the drawer at point
15862 (let ((rbeg (region-beginning))
15863 (rend (copy-marker (region-end))))
15864 (unwind-protect
15865 (progn
15866 (goto-char rbeg)
15867 (beginning-of-line)
15868 (when (save-excursion
15869 (re-search-forward org-outline-regexp-bol rend t))
15870 (user-error "Drawers cannot contain headlines"))
15871 ;; Position point at the beginning of the first
15872 ;; non-blank line in region. Insert drawer's opening
15873 ;; there, then indent it.
15874 (org-skip-whitespace)
15875 (beginning-of-line)
15876 (insert ":" drawer ":\n")
15877 (forward-line -1)
15878 (indent-for-tab-command)
15879 ;; Move point to the beginning of the first blank line
15880 ;; after the last non-blank line in region. Insert
15881 ;; drawer's closing, then indent it.
15882 (goto-char rend)
15883 (skip-chars-backward " \r\t\n")
15884 (insert "\n:END:")
15885 (deactivate-mark t)
15886 (indent-for-tab-command)
15887 (unless (eolp) (insert "\n")))
15888 ;; Clear marker, whatever the outcome of insertion is.
15889 (set-marker rend nil)))))))
15891 (defvar org-property-set-functions-alist nil
15892 "Property set function alist.
15893 Each entry should have the following format:
15895 (PROPERTY . READ-FUNCTION)
15897 The read function will be called with the same argument as
15898 `org-completing-read'.")
15900 (defun org-set-property-function (property)
15901 "Get the function that should be used to set PROPERTY.
15902 This is computed according to `org-property-set-functions-alist'."
15903 (or (cdr (assoc property org-property-set-functions-alist))
15904 'org-completing-read))
15906 (defun org-read-property-value (property)
15907 "Read PROPERTY value from user."
15908 (let* ((completion-ignore-case t)
15909 (allowed (org-property-get-allowed-values nil property 'table))
15910 (cur (org-entry-get nil property))
15911 (prompt (concat property " value"
15912 (if (and cur (string-match "\\S-" cur))
15913 (concat " [" cur "]") "") ": "))
15914 (set-function (org-set-property-function property))
15915 (val (if allowed
15916 (funcall set-function prompt allowed nil
15917 (not (get-text-property 0 'org-unrestricted
15918 (caar allowed))))
15919 (funcall set-function prompt
15920 (mapcar 'list (org-property-values property))
15921 nil nil "" nil cur))))
15922 (org-trim val)))
15924 (defvar org-last-set-property nil)
15925 (defvar org-last-set-property-value nil)
15926 (defun org-read-property-name ()
15927 "Read a property name."
15928 (let ((completion-ignore-case t)
15929 (default-prop (or (and (org-at-property-p)
15930 (match-string-no-properties 2))
15931 org-last-set-property)))
15932 (org-completing-read
15933 (concat "Property"
15934 (if default-prop (concat " [" default-prop "]") "")
15935 ": ")
15936 (mapcar #'list (org-buffer-property-keys nil t t))
15937 nil nil nil nil default-prop)))
15939 (defun org-set-property-and-value (use-last)
15940 "Allow to set [PROPERTY]: [value] direction from prompt.
15941 When use-default, don't even ask, just use the last
15942 \"[PROPERTY]: [value]\" string from the history."
15943 (interactive "P")
15944 (let* ((completion-ignore-case t)
15945 (pv (or (and use-last org-last-set-property-value)
15946 (org-completing-read
15947 "Enter a \"[Property]: [value]\" pair: "
15948 nil nil nil nil nil
15949 org-last-set-property-value)))
15950 prop val)
15951 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15952 (setq prop (match-string 1 pv)
15953 val (match-string 2 pv))
15954 (org-set-property prop val))))
15956 (defun org-set-property (property value)
15957 "In the current entry, set PROPERTY to VALUE.
15959 When called interactively, this will prompt for a property name, offering
15960 completion on existing and default properties. And then it will prompt
15961 for a value, offering completion either on allowed values (via an inherited
15962 xxx_ALL property) or on existing values in other instances of this property
15963 in the current file.
15965 Throw an error when trying to set a property with an invalid name."
15966 (interactive (list nil nil))
15967 (let ((property (or property (org-read-property-name))))
15968 ;; `org-entry-put' also makes the following check, but this one
15969 ;; avoids polluting `org-last-set-property' and
15970 ;; `org-last-set-property-value' needlessly.
15971 (unless (org--valid-property-p property)
15972 (user-error "Invalid property name: \"%s\"" property))
15973 (let ((value (or value (org-read-property-value property)))
15974 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15975 (setq org-last-set-property property)
15976 (setq org-last-set-property-value (concat property ": " value))
15977 ;; Possibly postprocess the inserted value:
15978 (when fn (setq value (funcall fn value)))
15979 (unless (equal (org-entry-get nil property) value)
15980 (org-entry-put nil property value)))))
15982 (defun org-find-property (property &optional value)
15983 "Find first entry in buffer that sets PROPERTY.
15985 When optional argument VALUE is non-nil, only consider an entry
15986 if it contains PROPERTY set to this value. If PROPERTY should be
15987 explicitly set to nil, use string \"nil\" for VALUE.
15989 Return position where the entry begins, or nil if there is no
15990 such entry. If narrowing is in effect, only search the visible
15991 part of the buffer."
15992 (save-excursion
15993 (goto-char (point-min))
15994 (let ((case-fold-search t)
15995 (re (org-re-property property nil (not value) value)))
15996 (catch 'exit
15997 (while (re-search-forward re nil t)
15998 (when (if value (org-at-property-p)
15999 (org-entry-get (point) property nil t))
16000 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16002 (defun org-delete-property (property)
16003 "In the current entry, delete PROPERTY."
16004 (interactive
16005 (let* ((completion-ignore-case t)
16006 (cat (org-entry-get (point) "CATEGORY"))
16007 (props0 (org-entry-properties nil 'standard))
16008 (props (if cat props0
16009 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16010 (prop (if (< 1 (length props))
16011 (completing-read "Property: " props nil t)
16012 (caar props))))
16013 (list prop)))
16014 (if (not property)
16015 (message "No property to delete in this entry")
16016 (org-entry-delete nil property)
16017 (message "Property \"%s\" deleted" property)))
16019 (defun org-delete-property-globally (property)
16020 "Remove PROPERTY globally, from all entries.
16021 This function ignores narrowing, if any."
16022 (interactive
16023 (let* ((completion-ignore-case t)
16024 (prop (completing-read
16025 "Globally remove property: "
16026 (mapcar #'list (org-buffer-property-keys)))))
16027 (list prop)))
16028 (org-with-wide-buffer
16029 (goto-char (point-min))
16030 (let ((count 0)
16031 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16032 (while (re-search-forward re nil t)
16033 (when (org-entry-delete (point) property) (cl-incf count)))
16034 (message "Property \"%s\" removed from %d entries" property count))))
16036 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16038 (defun org-compute-property-at-point ()
16039 "Compute the property at point.
16040 This looks for an enclosing column format, extracts the operator and
16041 then applies it to the property in the column format's scope."
16042 (interactive)
16043 (unless (org-at-property-p)
16044 (user-error "Not at a property"))
16045 (let ((prop (match-string-no-properties 2)))
16046 (org-columns-get-format-and-top-level)
16047 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16048 (user-error "No operator defined for property %s" prop))
16049 (org-columns-compute prop)))
16051 (defvar org-property-allowed-value-functions nil
16052 "Hook for functions supplying allowed values for a specific property.
16053 The functions must take a single argument, the name of the property, and
16054 return a flat list of allowed values. If \":ETC\" is one of
16055 the values, this means that these values are intended as defaults for
16056 completion, but that other values should be allowed too.
16057 The functions must return nil if they are not responsible for this
16058 property.")
16060 (defun org-property-get-allowed-values (pom property &optional table)
16061 "Get allowed values for the property PROPERTY.
16062 When TABLE is non-nil, return an alist that can directly be used for
16063 completion."
16064 (let (vals)
16065 (cond
16066 ((equal property "TODO")
16067 (setq vals (org-with-point-at pom
16068 (append org-todo-keywords-1 '("")))))
16069 ((equal property "PRIORITY")
16070 (let ((n org-lowest-priority))
16071 (while (>= n org-highest-priority)
16072 (push (char-to-string n) vals)
16073 (setq n (1- n)))))
16074 ((equal property "CATEGORY"))
16075 ((member property org-special-properties))
16076 ((setq vals (run-hook-with-args-until-success
16077 'org-property-allowed-value-functions property)))
16079 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16080 (when (and vals (string-match "\\S-" vals))
16081 (setq vals (car (read-from-string (concat "(" vals ")"))))
16082 (setq vals (mapcar (lambda (x)
16083 (cond ((stringp x) x)
16084 ((numberp x) (number-to-string x))
16085 ((symbolp x) (symbol-name x))
16086 (t "???")))
16087 vals)))))
16088 (when (member ":ETC" vals)
16089 (setq vals (remove ":ETC" vals))
16090 (org-add-props (car vals) '(org-unrestricted t)))
16091 (if table (mapcar 'list vals) vals)))
16093 (defun org-property-previous-allowed-value (&optional _previous)
16094 "Switch to the next allowed value for this property."
16095 (interactive)
16096 (org-property-next-allowed-value t))
16098 (defun org-property-next-allowed-value (&optional previous)
16099 "Switch to the next allowed value for this property."
16100 (interactive)
16101 (unless (org-at-property-p)
16102 (user-error "Not at a property"))
16103 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16104 (key (match-string 2))
16105 (value (match-string 3))
16106 (allowed (or (org-property-get-allowed-values (point) key)
16107 (and (member value '("[ ]" "[-]" "[X]"))
16108 '("[ ]" "[X]"))))
16109 (heading (save-match-data (nth 4 (org-heading-components))))
16110 nval)
16111 (unless allowed
16112 (user-error "Allowed values for this property have not been defined"))
16113 (when previous (setq allowed (reverse allowed)))
16114 (when (member value allowed)
16115 (setq nval (car (cdr (member value allowed)))))
16116 (setq nval (or nval (car allowed)))
16117 (when (equal nval value)
16118 (user-error "Only one allowed value for this property"))
16119 (org-at-property-p)
16120 (replace-match (concat " :" key ": " nval) t t)
16121 (org-indent-line)
16122 (beginning-of-line 1)
16123 (skip-chars-forward " \t")
16124 (when (equal prop org-effort-property)
16125 (org-refresh-property
16126 '((effort . identity)
16127 (effort-minutes . org-duration-to-minutes))
16128 nval)
16129 (when (string= org-clock-current-task heading)
16130 (setq org-clock-effort nval)
16131 (org-clock-update-mode-line)))
16132 (run-hook-with-args 'org-property-changed-functions key nval)))
16134 (defun org-find-olp (path &optional this-buffer)
16135 "Return a marker pointing to the entry at outline path OLP.
16136 If anything goes wrong, throw an error.
16137 You can wrap this call to catch the error like this:
16139 (condition-case msg
16140 (org-mobile-locate-entry (match-string 4))
16141 (error (nth 1 msg)))
16143 The return value will then be either a string with the error message,
16144 or a marker if everything is OK.
16146 If THIS-BUFFER is set, the outline path does not contain a file,
16147 only headings."
16148 (let* ((file (if this-buffer buffer-file-name (pop path)))
16149 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16150 (level 1)
16151 (lmin 1)
16152 (lmax 1)
16153 end found flevel)
16154 (unless buffer (error "File not found :%s" file))
16155 (with-current-buffer buffer
16156 (unless (derived-mode-p 'org-mode)
16157 (error "Buffer %s needs to be in Org mode" buffer))
16158 (org-with-wide-buffer
16159 (goto-char (point-min))
16160 (dolist (heading path)
16161 (let ((re (format org-complex-heading-regexp-format
16162 (regexp-quote heading)))
16163 (cnt 0))
16164 (while (re-search-forward re end t)
16165 (setq level (- (match-end 1) (match-beginning 1)))
16166 (when (and (>= level lmin) (<= level lmax))
16167 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16168 (when (= cnt 0)
16169 (error "Heading not found on level %d: %s" lmax heading))
16170 (when (> cnt 1)
16171 (error "Heading not unique on level %d: %s" lmax heading))
16172 (goto-char found)
16173 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16174 (setq end (save-excursion (org-end-of-subtree t t)))))
16175 (when (org-at-heading-p)
16176 (point-marker))))))
16178 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16179 "Find node HEADING in BUFFER.
16180 Return a marker to the heading if it was found, or nil if not.
16181 If POS-ONLY is set, return just the position instead of a marker.
16183 The heading text must match exact, but it may have a TODO keyword,
16184 a priority cookie and tags in the standard locations."
16185 (with-current-buffer (or buffer (current-buffer))
16186 (org-with-wide-buffer
16187 (goto-char (point-min))
16188 (let (case-fold-search)
16189 (when (re-search-forward
16190 (format org-complex-heading-regexp-format
16191 (regexp-quote heading)) nil t)
16192 (if pos-only
16193 (match-beginning 0)
16194 (move-marker (make-marker) (match-beginning 0))))))))
16196 (defun org-find-exact-heading-in-directory (heading &optional dir)
16197 "Find Org node headline HEADING in all .org files in directory DIR.
16198 When the target headline is found, return a marker to this location."
16199 (let ((files (directory-files (or dir default-directory)
16200 t "\\`[^.#].*\\.org\\'"))
16201 visiting m buffer)
16202 (catch 'found
16203 (dolist (file files)
16204 (message "trying %s" file)
16205 (setq visiting (org-find-base-buffer-visiting file))
16206 (setq buffer (or visiting (find-file-noselect file)))
16207 (setq m (org-find-exact-headline-in-buffer
16208 heading buffer))
16209 (when (and (not m) (not visiting)) (kill-buffer buffer))
16210 (and m (throw 'found m))))))
16212 (defun org-find-entry-with-id (ident)
16213 "Locate the entry that contains the ID property with exact value IDENT.
16214 IDENT can be a string, a symbol or a number, this function will search for
16215 the string representation of it.
16216 Return the position where this entry starts, or nil if there is no such entry."
16217 (interactive "sID: ")
16218 (let ((id (cond
16219 ((stringp ident) ident)
16220 ((symbolp ident) (symbol-name ident))
16221 ((numberp ident) (number-to-string ident))
16222 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16223 (org-with-wide-buffer (org-find-property "ID" id))))
16225 ;;;; Timestamps
16227 (defvar org-last-changed-timestamp nil)
16228 (defvar org-last-inserted-timestamp nil
16229 "The last time stamp inserted with `org-insert-time-stamp'.")
16231 (defun org-time-stamp (arg &optional inactive)
16232 "Prompt for a date/time and insert a time stamp.
16234 If the user specifies a time like HH:MM or if this command is
16235 called with at least one prefix argument, the time stamp contains
16236 the date and the time. Otherwise, only the date is included.
16238 All parts of a date not specified by the user are filled in from
16239 the timestamp at point, if any, or the current date/time
16240 otherwise.
16242 If there is already a timestamp at the cursor, it is replaced.
16244 With two universal prefix arguments, insert an active timestamp
16245 with the current time without prompting the user.
16247 When called from lisp, the timestamp is inactive if INACTIVE is
16248 non-nil."
16249 (interactive "P")
16250 (let* ((ts (cond
16251 ((org-at-date-range-p t)
16252 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16253 ((org-at-timestamp-p 'lax) (match-string 0))))
16254 ;; Default time is either the timestamp at point or today.
16255 ;; When entering a range, only the range start is considered.
16256 (default-time (if (not ts) (current-time)
16257 (apply #'encode-time (org-parse-time-string ts))))
16258 (default-input (and ts (org-get-compact-tod ts)))
16259 (repeater (and ts
16260 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16261 (match-string 0 ts)))
16262 org-time-was-given
16263 org-end-time-was-given
16264 (time
16265 (and (if (equal arg '(16)) (current-time)
16266 ;; Preserve `this-command' and `last-command'.
16267 (let ((this-command this-command)
16268 (last-command last-command))
16269 (org-read-date
16270 arg 'totime nil nil default-time default-input
16271 inactive))))))
16272 (cond
16273 ((and ts
16274 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16275 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16276 (insert "--")
16277 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16279 ;; Make sure we're on a timestamp. When in the middle of a date
16280 ;; range, move arbitrarily to range end.
16281 (unless (org-at-timestamp-p 'lax)
16282 (skip-chars-forward "-")
16283 (org-at-timestamp-p 'lax))
16284 (replace-match "")
16285 (setq org-last-changed-timestamp
16286 (org-insert-time-stamp
16287 time (or org-time-was-given arg)
16288 inactive nil nil (list org-end-time-was-given)))
16289 (when repeater
16290 (backward-char)
16291 (insert " " repeater)
16292 (setq org-last-changed-timestamp
16293 (concat (substring org-last-inserted-timestamp 0 -1)
16294 " " repeater ">")))
16295 (message "Timestamp updated"))
16296 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16297 (t (org-insert-time-stamp
16298 time (or org-time-was-given arg) inactive nil nil
16299 (list org-end-time-was-given))))))
16301 ;; FIXME: can we use this for something else, like computing time differences?
16302 (defun org-get-compact-tod (s)
16303 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16304 (let* ((t1 (match-string 1 s))
16305 (h1 (string-to-number (match-string 2 s)))
16306 (m1 (string-to-number (match-string 3 s)))
16307 (t2 (and (match-end 4) (match-string 5 s)))
16308 (h2 (and t2 (string-to-number (match-string 6 s))))
16309 (m2 (and t2 (string-to-number (match-string 7 s))))
16310 dh dm)
16311 (if (not t2)
16313 (setq dh (- h2 h1) dm (- m2 m1))
16314 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16315 (concat t1 "+" (number-to-string dh)
16316 (and (/= 0 dm) (format ":%02d" dm)))))))
16318 (defun org-time-stamp-inactive (&optional arg)
16319 "Insert an inactive time stamp.
16320 An inactive time stamp is enclosed in square brackets instead of angle
16321 brackets. It is inactive in the sense that it does not trigger agenda entries,
16322 does not link to the calendar and cannot be changed with the S-cursor keys.
16323 So these are more for recording a certain time/date."
16324 (interactive "P")
16325 (org-time-stamp arg 'inactive))
16327 (defvar org-date-ovl (make-overlay 1 1))
16328 (overlay-put org-date-ovl 'face 'org-date-selected)
16329 (delete-overlay org-date-ovl)
16331 (defvar org-ans1) ; dynamically scoped parameter
16332 (defvar org-ans2) ; dynamically scoped parameter
16334 (defvar org-plain-time-of-day-regexp) ; defined below
16336 (defvar org-overriding-default-time nil) ; dynamically scoped
16337 (defvar org-read-date-overlay nil)
16338 (defvar org-dcst nil) ; dynamically scoped
16339 (defvar org-read-date-history nil)
16340 (defvar org-read-date-final-answer nil)
16341 (defvar org-read-date-analyze-futurep nil)
16342 (defvar org-read-date-analyze-forced-year nil)
16343 (defvar org-read-date-inactive)
16345 (defvar org-read-date-minibuffer-local-map
16346 (let* ((map (make-sparse-keymap)))
16347 (set-keymap-parent map minibuffer-local-map)
16348 (org-defkey map (kbd ".")
16349 (lambda () (interactive)
16350 ;; Are we at the beginning of the prompt?
16351 (if (looking-back "^[^:]+: "
16352 (let ((inhibit-field-text-motion t))
16353 (line-beginning-position)))
16354 (org-eval-in-calendar '(calendar-goto-today))
16355 (insert "."))))
16356 (org-defkey map (kbd "C-.")
16357 (lambda () (interactive)
16358 (org-eval-in-calendar '(calendar-goto-today))))
16359 (org-defkey map [(meta shift left)]
16360 (lambda () (interactive)
16361 (org-eval-in-calendar '(calendar-backward-month 1))))
16362 (org-defkey map [(meta shift right)]
16363 (lambda () (interactive)
16364 (org-eval-in-calendar '(calendar-forward-month 1))))
16365 (org-defkey map [(meta shift up)]
16366 (lambda () (interactive)
16367 (org-eval-in-calendar '(calendar-backward-year 1))))
16368 (org-defkey map [(meta shift down)]
16369 (lambda () (interactive)
16370 (org-eval-in-calendar '(calendar-forward-year 1))))
16371 (org-defkey map [?\e (shift left)]
16372 (lambda () (interactive)
16373 (org-eval-in-calendar '(calendar-backward-month 1))))
16374 (org-defkey map [?\e (shift right)]
16375 (lambda () (interactive)
16376 (org-eval-in-calendar '(calendar-forward-month 1))))
16377 (org-defkey map [?\e (shift up)]
16378 (lambda () (interactive)
16379 (org-eval-in-calendar '(calendar-backward-year 1))))
16380 (org-defkey map [?\e (shift down)]
16381 (lambda () (interactive)
16382 (org-eval-in-calendar '(calendar-forward-year 1))))
16383 (org-defkey map [(shift up)]
16384 (lambda () (interactive)
16385 (org-eval-in-calendar '(calendar-backward-week 1))))
16386 (org-defkey map [(shift down)]
16387 (lambda () (interactive)
16388 (org-eval-in-calendar '(calendar-forward-week 1))))
16389 (org-defkey map [(shift left)]
16390 (lambda () (interactive)
16391 (org-eval-in-calendar '(calendar-backward-day 1))))
16392 (org-defkey map [(shift right)]
16393 (lambda () (interactive)
16394 (org-eval-in-calendar '(calendar-forward-day 1))))
16395 (org-defkey map "!"
16396 (lambda () (interactive)
16397 (org-eval-in-calendar '(diary-view-entries))
16398 (message "")))
16399 (org-defkey map ">"
16400 (lambda () (interactive)
16401 (org-eval-in-calendar '(calendar-scroll-left 1))))
16402 (org-defkey map "<"
16403 (lambda () (interactive)
16404 (org-eval-in-calendar '(calendar-scroll-right 1))))
16405 (org-defkey map "\C-v"
16406 (lambda () (interactive)
16407 (org-eval-in-calendar
16408 '(calendar-scroll-left-three-months 1))))
16409 (org-defkey map "\M-v"
16410 (lambda () (interactive)
16411 (org-eval-in-calendar
16412 '(calendar-scroll-right-three-months 1))))
16413 map)
16414 "Keymap for minibuffer commands when using `org-read-date'.")
16416 (defvar org-def)
16417 (defvar org-defdecode)
16418 (defvar org-with-time)
16420 (defvar calendar-setup) ; Dynamically scoped.
16421 (defun org-read-date (&optional with-time to-time from-string prompt
16422 default-time default-input inactive)
16423 "Read a date, possibly a time, and make things smooth for the user.
16424 The prompt will suggest to enter an ISO date, but you can also enter anything
16425 which will at least partially be understood by `parse-time-string'.
16426 Unrecognized parts of the date will default to the current day, month, year,
16427 hour and minute. If this command is called to replace a timestamp at point,
16428 or to enter the second timestamp of a range, the default time is taken
16429 from the existing stamp. Furthermore, the command prefers the future,
16430 so if you are giving a date where the year is not given, and the day-month
16431 combination is already past in the current year, it will assume you
16432 mean next year. For details, see the manual. A few examples:
16434 3-2-5 --> 2003-02-05
16435 feb 15 --> currentyear-02-15
16436 2/15 --> currentyear-02-15
16437 sep 12 9 --> 2009-09-12
16438 12:45 --> today 12:45
16439 22 sept 0:34 --> currentyear-09-22 0:34
16440 12 --> currentyear-currentmonth-12
16441 Fri --> nearest Friday after today
16442 -Tue --> last Tuesday
16443 etc.
16445 Furthermore you can specify a relative date by giving, as the *first* thing
16446 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16447 change in days weeks, months, years.
16448 With a single plus or minus, the date is relative to today. With a double
16449 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16450 +4d --> four days from today
16451 +4 --> same as above
16452 +2w --> two weeks from today
16453 ++5 --> five days from default date
16455 The function understands only English month and weekday abbreviations.
16457 While prompting, a calendar is popped up - you can also select the
16458 date with the mouse (button 1). The calendar shows a period of three
16459 months. To scroll it to other months, use the keys `>' and `<'.
16460 If you don't like the calendar, turn it off with
16461 (setq org-read-date-popup-calendar nil)
16463 With optional argument TO-TIME, the date will immediately be converted
16464 to an internal time.
16465 With an optional argument WITH-TIME, the prompt will suggest to
16466 also insert a time. Note that when WITH-TIME is not set, you can
16467 still enter a time, and this function will inform the calling routine
16468 about this change. The calling routine may then choose to change the
16469 format used to insert the time stamp into the buffer to include the time.
16470 With optional argument FROM-STRING, read from this string instead from
16471 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16472 the time/date that is used for everything that is not specified by the
16473 user."
16474 (require 'parse-time)
16475 (let* ((org-with-time with-time)
16476 (org-time-stamp-rounding-minutes
16477 (if (equal org-with-time '(16))
16478 '(0 0)
16479 org-time-stamp-rounding-minutes))
16480 (org-dcst org-display-custom-times)
16481 (ct (org-current-time))
16482 (org-def (or org-overriding-default-time default-time ct))
16483 (org-defdecode (decode-time org-def))
16484 (cur-frame (selected-frame))
16485 (mouse-autoselect-window nil) ; Don't let the mouse jump
16486 (calendar-setup
16487 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16488 (calendar-move-hook nil)
16489 (calendar-view-diary-initially-flag nil)
16490 (calendar-view-holidays-initially-flag nil)
16491 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16492 ;; Rationalize `org-def' and `org-defdecode', if required.
16493 (when (< (nth 2 org-defdecode) org-extend-today-until)
16494 (setf (nth 2 org-defdecode) -1)
16495 (setf (nth 1 org-defdecode) 59)
16496 (setq org-def (apply #'encode-time org-defdecode))
16497 (setq org-defdecode (decode-time org-def)))
16498 (let* ((timestr (format-time-string
16499 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16500 org-def))
16501 (prompt (concat (if prompt (concat prompt " ") "")
16502 (format "Date+time [%s]: " timestr))))
16503 (cond
16504 (from-string (setq ans from-string))
16505 (org-read-date-popup-calendar
16506 (save-excursion
16507 (save-window-excursion
16508 (calendar)
16509 (when (eq calendar-setup 'calendar-only)
16510 (setq cal-frame
16511 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16512 (select-frame cal-frame))
16513 (org-eval-in-calendar '(setq cursor-type nil) t)
16514 (unwind-protect
16515 (progn
16516 (calendar-forward-day (- (time-to-days org-def)
16517 (calendar-absolute-from-gregorian
16518 (calendar-current-date))))
16519 (org-eval-in-calendar nil t)
16520 (let* ((old-map (current-local-map))
16521 (map (copy-keymap calendar-mode-map))
16522 (minibuffer-local-map
16523 (copy-keymap org-read-date-minibuffer-local-map)))
16524 (org-defkey map (kbd "RET") 'org-calendar-select)
16525 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16526 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16527 (unwind-protect
16528 (progn
16529 (use-local-map map)
16530 (setq org-read-date-inactive inactive)
16531 (add-hook 'post-command-hook 'org-read-date-display)
16532 (setq org-ans0
16533 (read-string prompt
16534 default-input
16535 'org-read-date-history
16536 nil))
16537 ;; org-ans0: from prompt
16538 ;; org-ans1: from mouse click
16539 ;; org-ans2: from calendar motion
16540 (setq ans
16541 (concat org-ans0 " " (or org-ans1 org-ans2))))
16542 (remove-hook 'post-command-hook 'org-read-date-display)
16543 (use-local-map old-map)
16544 (when org-read-date-overlay
16545 (delete-overlay org-read-date-overlay)
16546 (setq org-read-date-overlay nil)))))
16547 (bury-buffer "*Calendar*")
16548 (when cal-frame
16549 (delete-frame cal-frame)
16550 (select-frame-set-input-focus cur-frame))))))
16552 (t ; Naked prompt only
16553 (unwind-protect
16554 (setq ans (read-string prompt default-input
16555 'org-read-date-history timestr))
16556 (when org-read-date-overlay
16557 (delete-overlay org-read-date-overlay)
16558 (setq org-read-date-overlay nil))))))
16560 (setq final (org-read-date-analyze ans org-def org-defdecode))
16562 (when org-read-date-analyze-forced-year
16563 (message "Year was forced into %s"
16564 (if org-read-date-force-compatible-dates
16565 "compatible range (1970-2037)"
16566 "range representable on this machine"))
16567 (ding))
16569 ;; One round trip to get rid of 34th of August and stuff like that....
16570 (setq final (decode-time (apply 'encode-time final)))
16572 (setq org-read-date-final-answer ans)
16574 (if to-time
16575 (apply 'encode-time final)
16576 (if (and (boundp 'org-time-was-given) org-time-was-given)
16577 (format "%04d-%02d-%02d %02d:%02d"
16578 (nth 5 final) (nth 4 final) (nth 3 final)
16579 (nth 2 final) (nth 1 final))
16580 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16582 (defun org-read-date-display ()
16583 "Display the current date prompt interpretation in the minibuffer."
16584 (when org-read-date-display-live
16585 (when org-read-date-overlay
16586 (delete-overlay org-read-date-overlay))
16587 (when (minibufferp (current-buffer))
16588 (save-excursion
16589 (end-of-line 1)
16590 (while (not (equal (buffer-substring
16591 (max (point-min) (- (point) 4)) (point))
16592 " "))
16593 (insert " ")))
16594 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16595 " " (or org-ans1 org-ans2)))
16596 (org-end-time-was-given nil)
16597 (f (org-read-date-analyze ans org-def org-defdecode))
16598 (fmts (if org-dcst
16599 org-time-stamp-custom-formats
16600 org-time-stamp-formats))
16601 (fmt (if (or org-with-time
16602 (and (boundp 'org-time-was-given) org-time-was-given))
16603 (cdr fmts)
16604 (car fmts)))
16605 (txt (format-time-string fmt (apply 'encode-time f)))
16606 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16607 (txt (concat "=> " txt)))
16608 (when (and org-end-time-was-given
16609 (string-match org-plain-time-of-day-regexp txt))
16610 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16611 org-end-time-was-given
16612 (substring txt (match-end 0)))))
16613 (when org-read-date-analyze-futurep
16614 (setq txt (concat txt " (=>F)")))
16615 (setq org-read-date-overlay
16616 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16617 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16619 (defun org-read-date-analyze (ans def defdecode)
16620 "Analyze the combined answer of the date prompt."
16621 ;; FIXME: cleanup and comment
16622 ;; Pass `current-time' result to `decode-time' (instead of calling
16623 ;; without arguments) so that only `current-time' has to be
16624 ;; overridden in tests.
16625 (let ((org-def def)
16626 (org-defdecode defdecode)
16627 (nowdecode (decode-time (current-time)))
16628 delta deltan deltaw deltadef year month day
16629 hour minute second wday pm h2 m2 tl wday1
16630 iso-year iso-weekday iso-week iso-date futurep kill-year)
16631 (setq org-read-date-analyze-futurep nil
16632 org-read-date-analyze-forced-year nil)
16633 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16634 (setq ans "+0"))
16636 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16637 (setq ans (replace-match "" t t ans)
16638 deltan (car delta)
16639 deltaw (nth 1 delta)
16640 deltadef (nth 2 delta)))
16642 ;; Check if there is an iso week date in there. If yes, store the
16643 ;; info and postpone interpreting it until the rest of the parsing
16644 ;; is done.
16645 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16646 (setq iso-year (when (match-end 1)
16647 (org-small-year-to-year
16648 (string-to-number (match-string 1 ans))))
16649 iso-weekday (when (match-end 3)
16650 (string-to-number (match-string 3 ans)))
16651 iso-week (string-to-number (match-string 2 ans)))
16652 (setq ans (replace-match "" t t ans)))
16654 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16655 (when (string-match
16656 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16657 (setq year (if (match-end 2)
16658 (string-to-number (match-string 2 ans))
16659 (progn (setq kill-year t)
16660 (string-to-number (format-time-string "%Y"))))
16661 month (string-to-number (match-string 3 ans))
16662 day (string-to-number (match-string 4 ans)))
16663 (setq year (org-small-year-to-year year))
16664 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16665 t nil ans)))
16667 ;; Help matching dotted european dates
16668 (when (string-match
16669 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16670 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16671 (setq kill-year t)
16672 (string-to-number (format-time-string "%Y")))
16673 day (string-to-number (match-string 1 ans))
16674 month (string-to-number (match-string 2 ans))
16675 ans (replace-match (format "%04d-%02d-%02d" year month day)
16676 t nil ans)))
16678 ;; Help matching american dates, like 5/30 or 5/30/7
16679 (when (string-match
16680 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16681 (setq year (if (match-end 4)
16682 (string-to-number (match-string 4 ans))
16683 (progn (setq kill-year t)
16684 (string-to-number (format-time-string "%Y"))))
16685 month (string-to-number (match-string 1 ans))
16686 day (string-to-number (match-string 2 ans)))
16687 (setq year (org-small-year-to-year year))
16688 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16689 t nil ans)))
16690 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16691 ;; If there is a time with am/pm, and *no* time without it, we convert
16692 ;; so that matching will be successful.
16693 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16694 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16695 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16696 (setq hour (string-to-number (match-string 1 ans))
16697 minute (if (match-end 3)
16698 (string-to-number (match-string 3 ans))
16700 pm (equal ?p
16701 (string-to-char (downcase (match-string 4 ans)))))
16702 (if (and (= hour 12) (not pm))
16703 (setq hour 0)
16704 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16705 (setq ans (replace-match (format "%02d:%02d" hour minute)
16706 t t ans))))
16708 ;; Check if a time range is given as a duration
16709 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16710 (setq hour (string-to-number (match-string 1 ans))
16711 h2 (+ hour (string-to-number (match-string 3 ans)))
16712 minute (string-to-number (match-string 2 ans))
16713 m2 (+ minute (if (match-end 5) (string-to-number
16714 (match-string 5 ans))0)))
16715 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16716 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16717 t t ans)))
16719 ;; Check if there is a time range
16720 (when (boundp 'org-end-time-was-given)
16721 (setq org-time-was-given nil)
16722 (when (and (string-match org-plain-time-of-day-regexp ans)
16723 (match-end 8))
16724 (setq org-end-time-was-given (match-string 8 ans))
16725 (setq ans (concat (substring ans 0 (match-beginning 7))
16726 (substring ans (match-end 7))))))
16728 (setq tl (parse-time-string ans)
16729 day (or (nth 3 tl) (nth 3 org-defdecode))
16730 month
16731 (cond ((nth 4 tl))
16732 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16733 ;; Day was specified. Make sure DAY+MONTH
16734 ;; combination happens in the future.
16735 ((nth 3 tl)
16736 (setq futurep t)
16737 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16738 (nth 4 nowdecode)))
16739 (t (nth 4 org-defdecode)))
16740 year
16741 (cond ((and (not kill-year) (nth 5 tl)))
16742 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16743 ;; Month was guessed in the future and is at least
16744 ;; equal to NOWDECODE's. Fix year accordingly.
16745 (futurep
16746 (if (or (> month (nth 4 nowdecode))
16747 (>= day (nth 3 nowdecode)))
16748 (nth 5 nowdecode)
16749 (1+ (nth 5 nowdecode))))
16750 ;; Month was specified. Make sure MONTH+YEAR
16751 ;; combination happens in the future.
16752 ((nth 4 tl)
16753 (setq futurep t)
16754 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16755 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16756 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16757 (t (nth 5 nowdecode))))
16758 (t (nth 5 org-defdecode)))
16759 hour (or (nth 2 tl) (nth 2 org-defdecode))
16760 minute (or (nth 1 tl) (nth 1 org-defdecode))
16761 second (or (nth 0 tl) 0)
16762 wday (nth 6 tl))
16764 (when (and (eq org-read-date-prefer-future 'time)
16765 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16766 (equal day (nth 3 nowdecode))
16767 (equal month (nth 4 nowdecode))
16768 (equal year (nth 5 nowdecode))
16769 (nth 2 tl)
16770 (or (< (nth 2 tl) (nth 2 nowdecode))
16771 (and (= (nth 2 tl) (nth 2 nowdecode))
16772 (nth 1 tl)
16773 (< (nth 1 tl) (nth 1 nowdecode)))))
16774 (setq day (1+ day)
16775 futurep t))
16777 ;; Special date definitions below
16778 (cond
16779 (iso-week
16780 ;; There was an iso week
16781 (require 'cal-iso)
16782 (setq futurep nil)
16783 (setq year (or iso-year year)
16784 day (or iso-weekday wday 1)
16785 wday nil ; to make sure that the trigger below does not match
16786 iso-date (calendar-gregorian-from-absolute
16787 (calendar-iso-to-absolute
16788 (list iso-week day year))))
16789 ; FIXME: Should we also push ISO weeks into the future?
16790 ; (when (and org-read-date-prefer-future
16791 ; (not iso-year)
16792 ; (< (calendar-absolute-from-gregorian iso-date)
16793 ; (time-to-days (current-time))))
16794 ; (setq year (1+ year)
16795 ; iso-date (calendar-gregorian-from-absolute
16796 ; (calendar-iso-to-absolute
16797 ; (list iso-week day year)))))
16798 (setq month (car iso-date)
16799 year (nth 2 iso-date)
16800 day (nth 1 iso-date)))
16801 (deltan
16802 (setq futurep nil)
16803 (unless deltadef
16804 ;; Pass `current-time' result to `decode-time' (instead of
16805 ;; calling without arguments) so that only `current-time' has
16806 ;; to be overridden in tests.
16807 (let ((now (decode-time (current-time))))
16808 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16809 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16810 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16811 ((equal deltaw "m") (setq month (+ month deltan)))
16812 ((equal deltaw "y") (setq year (+ year deltan)))))
16813 ((and wday (not (nth 3 tl)))
16814 ;; Weekday was given, but no day, so pick that day in the week
16815 ;; on or after the derived date.
16816 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16817 (unless (equal wday wday1)
16818 (setq day (+ day (% (- wday wday1 -7) 7))))))
16819 (when (and (boundp 'org-time-was-given)
16820 (nth 2 tl))
16821 (setq org-time-was-given t))
16822 (when (< year 100) (setq year (+ 2000 year)))
16823 ;; Check of the date is representable
16824 (if org-read-date-force-compatible-dates
16825 (progn
16826 (when (< year 1970)
16827 (setq year 1970 org-read-date-analyze-forced-year t))
16828 (when (> year 2037)
16829 (setq year 2037 org-read-date-analyze-forced-year t)))
16830 (condition-case nil
16831 (ignore (encode-time second minute hour day month year))
16832 (error
16833 (setq year (nth 5 org-defdecode))
16834 (setq org-read-date-analyze-forced-year t))))
16835 (setq org-read-date-analyze-futurep futurep)
16836 (list second minute hour day month year)))
16838 (defvar parse-time-weekdays)
16839 (defun org-read-date-get-relative (s today default)
16840 "Check string S for special relative date string.
16841 TODAY and DEFAULT are internal times, for today and for a default.
16842 Return shift list (N what def-flag)
16843 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16844 N is the number of WHATs to shift.
16845 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16846 the DEFAULT date rather than TODAY."
16847 (require 'parse-time)
16848 (when (and
16849 (string-match
16850 (concat
16851 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16852 "\\([0-9]+\\)?"
16853 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16854 "\\([ \t]\\|$\\)") s)
16855 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16856 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16857 (string-to-char (substring (match-string 1 s) -1))
16858 ?+))
16859 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16860 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16861 (what (if (match-end 3) (match-string 3 s) "d"))
16862 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16863 (date (if rel default today))
16864 (wday (nth 6 (decode-time date)))
16865 delta)
16866 (if wday1
16867 (progn
16868 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16869 (when (= delta 0) (setq delta 7))
16870 (when (= dir ?-)
16871 (setq delta (- delta 7))
16872 (when (= delta 0) (setq delta -7)))
16873 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16874 (list delta "d" rel))
16875 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16877 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16878 "Turn a user-specified date into the internal representation.
16879 The internal representation needed by the calendar is (month day year).
16880 This is a wrapper to handle the brain-dead convention in calendar that
16881 user function argument order change dependent on argument order."
16882 (pcase calendar-date-style
16883 (`american (list arg1 arg2 arg3))
16884 (`european (list arg2 arg1 arg3))
16885 (`iso (list arg2 arg3 arg1))))
16887 (defun org-eval-in-calendar (form &optional keepdate)
16888 "Eval FORM in the calendar window and return to current window.
16889 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16890 (let ((sf (selected-frame))
16891 (sw (selected-window)))
16892 (select-window (get-buffer-window "*Calendar*" t))
16893 (eval form)
16894 (when (and (not keepdate) (calendar-cursor-to-date))
16895 (let* ((date (calendar-cursor-to-date))
16896 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16897 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16898 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16899 (select-window sw)
16900 (select-frame-set-input-focus sf)))
16902 (defun org-calendar-select ()
16903 "Return to `org-read-date' with the date currently selected.
16904 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16905 (interactive)
16906 (when (calendar-cursor-to-date)
16907 (let* ((date (calendar-cursor-to-date))
16908 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16909 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16910 (when (active-minibuffer-window) (exit-minibuffer))))
16912 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16913 "Insert a date stamp for the date given by the internal TIME.
16914 See `format-time-string' for the format of TIME.
16915 WITH-HM means use the stamp format that includes the time of the day.
16916 INACTIVE means use square brackets instead of angular ones, so that the
16917 stamp will not contribute to the agenda.
16918 PRE and POST are optional strings to be inserted before and after the
16919 stamp.
16920 The command returns the inserted time stamp."
16921 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16922 stamp)
16923 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16924 (insert-before-markers (or pre ""))
16925 (when (listp extra)
16926 (setq extra (car extra))
16927 (if (and (stringp extra)
16928 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16929 (setq extra (format "-%02d:%02d"
16930 (string-to-number (match-string 1 extra))
16931 (string-to-number (match-string 2 extra))))
16932 (setq extra nil)))
16933 (when extra
16934 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16935 (insert-before-markers (setq stamp (format-time-string fmt time)))
16936 (insert-before-markers (or post ""))
16937 (setq org-last-inserted-timestamp stamp)))
16939 (defun org-toggle-time-stamp-overlays ()
16940 "Toggle the use of custom time stamp formats."
16941 (interactive)
16942 (setq org-display-custom-times (not org-display-custom-times))
16943 (unless org-display-custom-times
16944 (let ((p (point-min)) (bmp (buffer-modified-p)))
16945 (while (setq p (next-single-property-change p 'display))
16946 (when (and (get-text-property p 'display)
16947 (eq (get-text-property p 'face) 'org-date))
16948 (remove-text-properties
16949 p (setq p (next-single-property-change p 'display))
16950 '(display t))))
16951 (set-buffer-modified-p bmp)))
16952 (org-restart-font-lock)
16953 (setq org-table-may-need-update t)
16954 (if org-display-custom-times
16955 (message "Time stamps are overlaid with custom format")
16956 (message "Time stamp overlays removed")))
16958 (defun org-display-custom-time (beg end)
16959 "Overlay modified time stamp format over timestamp between BEG and END."
16960 (let* ((ts (buffer-substring beg end))
16961 t1 with-hm tf time str (off 0))
16962 (save-match-data
16963 (setq t1 (org-parse-time-string ts t))
16964 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16965 (setq off (- (match-end 0) (match-beginning 0)))))
16966 (setq end (- end off))
16967 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16968 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16969 time (org-fix-decoded-time t1)
16970 str (org-add-props
16971 (format-time-string
16972 (substring tf 1 -1) (apply 'encode-time time))
16973 nil 'mouse-face 'highlight))
16974 (put-text-property beg end 'display str)))
16976 (defun org-fix-decoded-time (time)
16977 "Set 0 instead of nil for the first 6 elements of time.
16978 Don't touch the rest."
16979 (let ((n 0))
16980 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16982 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16983 "Difference between TIMESTAMP-STRING and now in days.
16984 If SECONDS is non-nil, return the difference in seconds."
16985 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16986 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16987 (funcall fdiff (current-time)))))
16989 (defun org-deadline-close-p (timestamp-string &optional ndays)
16990 "Is the time in TIMESTAMP-STRING close to the current date?"
16991 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16992 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16993 (not (org-entry-is-done-p))))
16995 (defun org-get-wdays (ts &optional delay zero-delay)
16996 "Get the deadline lead time appropriate for timestring TS.
16997 When DELAY is non-nil, get the delay time for scheduled items
16998 instead of the deadline lead time. When ZERO-DELAY is non-nil
16999 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17000 don't try to find the delay cookie in the scheduled timestamp."
17001 (let ((tv (if delay org-scheduled-delay-days
17002 org-deadline-warning-days)))
17003 (cond
17004 ((or (and delay (< tv 0))
17005 (and delay zero-delay (<= tv 0))
17006 (and (not delay) (<= tv 0)))
17007 ;; Enforce this value no matter what
17008 (- tv))
17009 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17010 ;; lead time is specified.
17011 (floor (* (string-to-number (match-string 1 ts))
17012 (cdr (assoc (match-string 2 ts)
17013 '(("d" . 1) ("w" . 7)
17014 ("m" . 30.4) ("y" . 365.25)
17015 ("h" . 0.041667)))))))
17016 ;; go for the default.
17017 (t tv))))
17019 (defun org-calendar-select-mouse (ev)
17020 "Return to `org-read-date' with the date currently selected.
17021 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17022 (interactive "e")
17023 (mouse-set-point ev)
17024 (when (calendar-cursor-to-date)
17025 (let* ((date (calendar-cursor-to-date))
17026 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17027 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17028 (when (active-minibuffer-window) (exit-minibuffer))))
17030 (defun org-check-deadlines (ndays)
17031 "Check if there are any deadlines due or past due.
17032 A deadline is considered due if it happens within `org-deadline-warning-days'
17033 days from today's date. If the deadline appears in an entry marked DONE,
17034 it is not shown. A numeric prefix argument NDAYS can be used to test that
17035 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17036 are shown."
17037 (interactive "P")
17038 (let* ((org-warn-days
17039 (cond
17040 ((equal ndays '(4)) 100000)
17041 (ndays (prefix-numeric-value ndays))
17042 (t (abs org-deadline-warning-days))))
17043 (case-fold-search nil)
17044 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17045 (callback
17046 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17047 (message "%d deadlines past-due or due within %d days"
17048 (org-occur regexp nil callback)
17049 org-warn-days)))
17051 (defsubst org-re-timestamp (type)
17052 "Return a regexp for timestamp TYPE.
17053 Allowed values for TYPE are:
17055 all: all timestamps
17056 active: only active timestamps (<...>)
17057 inactive: only inactive timestamps ([...])
17058 scheduled: only scheduled timestamps
17059 deadline: only deadline timestamps
17060 closed: only closed time-stamps
17062 When TYPE is nil, fall back on returning a regexp that matches
17063 both scheduled and deadline timestamps."
17064 (cl-case type
17065 (all org-ts-regexp-both)
17066 (active org-ts-regexp)
17067 (inactive org-ts-regexp-inactive)
17068 (scheduled org-scheduled-time-regexp)
17069 (deadline org-deadline-time-regexp)
17070 (closed org-closed-time-regexp)
17071 (otherwise
17072 (concat "\\<"
17073 (regexp-opt (list org-deadline-string org-scheduled-string))
17074 " *<\\([^>]+\\)>"))))
17076 (defun org-check-before-date (d)
17077 "Check if there are deadlines or scheduled entries before date D."
17078 (interactive (list (org-read-date)))
17079 (let* ((case-fold-search nil)
17080 (regexp (org-re-timestamp org-ts-type))
17081 (ts-type org-ts-type)
17082 (callback
17083 (lambda ()
17084 (let ((match (match-string 1)))
17085 (and (if (memq ts-type '(active inactive all))
17086 (eq (org-element-type (save-excursion
17087 (backward-char)
17088 (org-element-context)))
17089 'timestamp)
17090 (org-at-planning-p))
17091 (time-less-p
17092 (org-time-string-to-time match)
17093 (org-time-string-to-time d)))))))
17094 (message "%d entries before %s"
17095 (org-occur regexp nil callback)
17096 d)))
17098 (defun org-check-after-date (d)
17099 "Check if there are deadlines or scheduled entries after date D."
17100 (interactive (list (org-read-date)))
17101 (let* ((case-fold-search nil)
17102 (regexp (org-re-timestamp org-ts-type))
17103 (ts-type org-ts-type)
17104 (callback
17105 (lambda ()
17106 (let ((match (match-string 1)))
17107 (and (if (memq ts-type '(active inactive all))
17108 (eq (org-element-type (save-excursion
17109 (backward-char)
17110 (org-element-context)))
17111 'timestamp)
17112 (org-at-planning-p))
17113 (not (time-less-p
17114 (org-time-string-to-time match)
17115 (org-time-string-to-time d))))))))
17116 (message "%d entries after %s"
17117 (org-occur regexp nil callback)
17118 d)))
17120 (defun org-check-dates-range (start-date end-date)
17121 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17122 (interactive (list (org-read-date nil nil nil "Range starts")
17123 (org-read-date nil nil nil "Range end")))
17124 (let ((case-fold-search nil)
17125 (regexp (org-re-timestamp org-ts-type))
17126 (callback
17127 (let ((type org-ts-type))
17128 (lambda ()
17129 (let ((match (match-string 1)))
17130 (and
17131 (if (memq type '(active inactive all))
17132 (eq (org-element-type (save-excursion
17133 (backward-char)
17134 (org-element-context)))
17135 'timestamp)
17136 (org-at-planning-p))
17137 (not (time-less-p
17138 (org-time-string-to-time match)
17139 (org-time-string-to-time start-date)))
17140 (time-less-p
17141 (org-time-string-to-time match)
17142 (org-time-string-to-time end-date))))))))
17143 (message "%d entries between %s and %s"
17144 (org-occur regexp nil callback) start-date end-date)))
17146 (defun org-evaluate-time-range (&optional to-buffer)
17147 "Evaluate a time range by computing the difference between start and end.
17148 Normally the result is just printed in the echo area, but with prefix arg
17149 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17150 If the time range is actually in a table, the result is inserted into the
17151 next column.
17152 For time difference computation, a year is assumed to be exactly 365
17153 days in order to avoid rounding problems."
17154 (interactive "P")
17156 (org-clock-update-time-maybe)
17157 (save-excursion
17158 (unless (org-at-date-range-p t)
17159 (goto-char (point-at-bol))
17160 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17161 (unless (org-at-date-range-p t)
17162 (user-error "Not at a time-stamp range, and none found in current line")))
17163 (let* ((ts1 (match-string 1))
17164 (ts2 (match-string 2))
17165 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17166 (match-end (match-end 0))
17167 (time1 (org-time-string-to-time ts1))
17168 (time2 (org-time-string-to-time ts2))
17169 (t1 (float-time time1))
17170 (t2 (float-time time2))
17171 (diff (abs (- t2 t1)))
17172 (negative (< (- t2 t1) 0))
17173 ;; (ys (floor (* 365 24 60 60)))
17174 (ds (* 24 60 60))
17175 (hs (* 60 60))
17176 (fy "%dy %dd %02d:%02d")
17177 (fy1 "%dy %dd")
17178 (fd "%dd %02d:%02d")
17179 (fd1 "%dd")
17180 (fh "%02d:%02d")
17181 y d h m align)
17182 (if havetime
17183 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17185 d (floor (/ diff ds)) diff (mod diff ds)
17186 h (floor (/ diff hs)) diff (mod diff hs)
17187 m (floor (/ diff 60)))
17188 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17190 d (floor (+ (/ diff ds) 0.5))
17191 h 0 m 0))
17192 (if (not to-buffer)
17193 (message "%s" (org-make-tdiff-string y d h m))
17194 (if (org-at-table-p)
17195 (progn
17196 (goto-char match-end)
17197 (setq align t)
17198 (and (looking-at " *|") (goto-char (match-end 0))))
17199 (goto-char match-end))
17200 (when (looking-at
17201 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17202 (replace-match ""))
17203 (when negative (insert " -"))
17204 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17205 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17206 (insert " " (format fh h m))))
17207 (when align (org-table-align))
17208 (message "Time difference inserted")))))
17210 (defun org-make-tdiff-string (y d h m)
17211 (let ((fmt "")
17212 (l nil))
17213 (when (> y 0)
17214 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17215 (push y l))
17216 (when (> d 0)
17217 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17218 (push d l))
17219 (when (> h 0)
17220 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17221 (push h l))
17222 (when (> m 0)
17223 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17224 (push m l))
17225 (apply 'format fmt (nreverse l))))
17227 (defun org-time-string-to-time (s)
17228 "Convert timestamp string S into internal time."
17229 (apply #'encode-time (org-parse-time-string s)))
17231 (defun org-time-string-to-seconds (s)
17232 "Convert a timestamp string S into a number of seconds."
17233 (float-time (org-time-string-to-time s)))
17235 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17237 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17238 "Convert time stamp S to an absolute day number.
17240 If DAYNR in non-nil, and there is a specifier for a cyclic time
17241 stamp, get the closest date to DAYNR. If PREFER is
17242 `past' (respectively `future') return a date past (respectively
17243 after) or equal to DAYNR.
17245 POS is the location of time stamp S, as a buffer position in
17246 BUFFER.
17248 Diary sexp timestamps are matched against DAYNR, when non-nil.
17249 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17250 signaled."
17251 (cond
17252 ((string-match "\\`%%\\((.*)\\)" s)
17253 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17254 ;; only able to match individual dates. If it fails, raise an
17255 ;; error.
17256 (if (and daynr
17257 (org-diary-sexp-entry
17258 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17259 daynr
17260 (signal 'org-diary-sexp-no-match (list s))))
17261 (daynr (org-closest-date s daynr prefer))
17262 (t (time-to-days
17263 (condition-case errdata
17264 (apply #'encode-time (org-parse-time-string s))
17265 (error (error "Bad timestamp `%s'%s\nError was: %s"
17267 (if (not (and buffer pos)) ""
17268 (format-message " at %d in buffer `%s'" pos buffer))
17269 (cdr errdata))))))))
17271 (defun org-days-to-iso-week (days)
17272 "Return the iso week number."
17273 (require 'cal-iso)
17274 (car (calendar-iso-from-absolute days)))
17276 (defun org-small-year-to-year (year)
17277 "Convert 2-digit years into 4-digit years.
17278 YEAR is expanded into one of the 30 next years, if possible, or
17279 into a past one. Any year larger than 99 is returned unchanged."
17280 (if (>= year 100) year
17281 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17282 (century (/ current 100))
17283 (offset (- year (% current 100))))
17284 (cond ((> offset 30) (+ (* (1- century) 100) year))
17285 ((> offset -70) (+ (* century 100) year))
17286 (t (+ (* (1+ century) 100) year))))))
17288 (defun org-time-from-absolute (d)
17289 "Return the time corresponding to date D.
17290 D may be an absolute day number, or a calendar-type list (month day year)."
17291 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17292 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17294 (defvar org-agenda-current-date)
17295 (defun org-calendar-holiday ()
17296 "List of holidays, for Diary display in Org mode."
17297 (require 'holidays)
17298 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17299 (and hl (mapconcat #'identity hl "; "))))
17301 (defun org-diary-sexp-entry (sexp entry d)
17302 "Process a SEXP diary ENTRY for date D."
17303 (require 'diary-lib)
17304 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17305 ;; dynamically.
17306 (let* ((sexp `(let ((entry ,entry)
17307 (date ',d))
17308 ,(car (read-from-string sexp))))
17309 (result (if calendar-debug-sexp (eval sexp)
17310 (condition-case nil
17311 (eval sexp)
17312 (error
17313 (beep)
17314 (message "Bad sexp at line %d in %s: %s"
17315 (org-current-line)
17316 (buffer-file-name) sexp)
17317 (sleep-for 2))))))
17318 (cond ((stringp result) (split-string result "; "))
17319 ((and (consp result)
17320 (not (consp (cdr result)))
17321 (stringp (cdr result))) (cdr result))
17322 ((and (consp result)
17323 (stringp (car result))) result)
17324 (result entry))))
17326 (defun org-diary-to-ical-string (frombuf)
17327 "Get iCalendar entries from diary entries in buffer FROMBUF.
17328 This uses the icalendar.el library."
17329 (let* ((tmpdir temporary-file-directory)
17330 (tmpfile (make-temp-name
17331 (expand-file-name "orgics" tmpdir)))
17332 buf rtn b e)
17333 (with-current-buffer frombuf
17334 (icalendar-export-region (point-min) (point-max) tmpfile)
17335 (setq buf (find-buffer-visiting tmpfile))
17336 (set-buffer buf)
17337 (goto-char (point-min))
17338 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17339 (setq b (match-beginning 0)))
17340 (goto-char (point-max))
17341 (when (re-search-backward "^END:VEVENT" nil t)
17342 (setq e (match-end 0)))
17343 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17344 (kill-buffer buf)
17345 (delete-file tmpfile)
17346 rtn))
17348 (defun org-closest-date (start current prefer)
17349 "Return closest date to CURRENT starting from START.
17351 CURRENT and START are both time stamps.
17353 When PREFER is `past', return a date that is either CURRENT or
17354 past. When PREFER is `future', return a date that is either
17355 CURRENT or future.
17357 Only time stamps with a repeater are modified. Any other time
17358 stamp stay unchanged. In any case, return value is an absolute
17359 day number."
17360 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17361 ;; No repeater. Do not shift time stamp.
17362 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17363 (let ((value (string-to-number (match-string 1 start)))
17364 (type (match-string 2 start)))
17365 (if (= 0 value)
17366 ;; Repeater with a 0-value is considered as void.
17367 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17368 (let* ((base (org-date-to-gregorian start))
17369 (target (org-date-to-gregorian current))
17370 (sday (calendar-absolute-from-gregorian base))
17371 (cday (calendar-absolute-from-gregorian target))
17372 n1 n2)
17373 ;; If START is already past CURRENT, just return START.
17374 (if (<= cday sday) sday
17375 ;; Compute closest date before (N1) and closest date past
17376 ;; (N2) CURRENT.
17377 (pcase type
17378 ("h"
17379 (let ((missing-hours
17380 (mod (+ (- (* 24 (- cday sday))
17381 (nth 2 (org-parse-time-string start)))
17382 org-extend-today-until)
17383 value)))
17384 (setf n1 (if (= missing-hours 0) cday
17385 (- cday (1+ (/ missing-hours 24)))))
17386 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17387 ((or "d" "w")
17388 (let ((value (if (equal type "w") (* 7 value) value)))
17389 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17390 (setf n2 (+ n1 value))))
17391 ("m"
17392 (let* ((add-months
17393 (lambda (d n)
17394 ;; Add N months to gregorian date D, i.e.,
17395 ;; a list (MONTH DAY YEAR). Return a valid
17396 ;; gregorian date.
17397 (let ((m (+ (nth 0 d) n)))
17398 (list (mod m 12)
17399 (nth 1 d)
17400 (+ (/ m 12) (nth 2 d))))))
17401 (months ; Complete months to TARGET.
17402 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17403 (- (nth 0 target) (nth 0 base))
17404 ;; If START's day is greater than
17405 ;; TARGET's, remove incomplete month.
17406 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17407 value)
17408 value))
17409 (before (funcall add-months base months)))
17410 (setf n1 (calendar-absolute-from-gregorian before))
17411 (setf n2
17412 (calendar-absolute-from-gregorian
17413 (funcall add-months before value)))))
17415 (let* ((d (nth 1 base))
17416 (m (nth 0 base))
17417 (y (nth 2 base))
17418 (years ; Complete years to TARGET.
17419 (* (/ (- (nth 2 target)
17421 ;; If START's month and day are
17422 ;; greater than TARGET's, remove
17423 ;; incomplete year.
17424 (if (or (> (nth 0 target) m)
17425 (and (= (nth 0 target) m)
17426 (> (nth 1 target) d)))
17429 value)
17430 value))
17431 (before (list m d (+ y years))))
17432 (setf n1 (calendar-absolute-from-gregorian before))
17433 (setf n2 (calendar-absolute-from-gregorian
17434 (list m d (+ (nth 2 before) value)))))))
17435 ;; Handle PREFER parameter, if any.
17436 (cond
17437 ((eq prefer 'past) (if (= cday n2) n2 n1))
17438 ((eq prefer 'future) (if (= cday n1) n1 n2))
17439 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17441 (defun org-date-to-gregorian (d)
17442 "Turn any specification of date D into a Gregorian date for the calendar."
17443 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17444 ((and (listp d) (= (length d) 3)) d)
17445 ((stringp d)
17446 (let ((d (org-parse-time-string d)))
17447 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17448 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17450 (defun org-parse-time-string (s &optional nodefault)
17451 "Parse the standard Org time string.
17453 This should be a lot faster than the normal `parse-time-string'.
17455 If time is not given, defaults to 0:00. However, with optional
17456 NODEFAULT, hour and minute fields will be nil if not given."
17457 (cond ((string-match org-ts-regexp0 s)
17458 (list 0
17459 (when (or (match-beginning 8) (not nodefault))
17460 (string-to-number (or (match-string 8 s) "0")))
17461 (when (or (match-beginning 7) (not nodefault))
17462 (string-to-number (or (match-string 7 s) "0")))
17463 (string-to-number (match-string 4 s))
17464 (string-to-number (match-string 3 s))
17465 (string-to-number (match-string 2 s))
17466 nil nil nil))
17467 ((string-match "^<[^>]+>$" s)
17468 ;; FIXME: `decode-time' needs to be called with ZONE as its
17469 ;; second argument. However, this requires at least Emacs
17470 ;; 25.1. We can do it when we switch to this version as our
17471 ;; minimal requirement.
17472 (decode-time (seconds-to-time (org-matcher-time s))))
17473 (t (error "Not a standard Org time string: %s" s))))
17475 (defun org-timestamp-up (&optional arg)
17476 "Increase the date item at the cursor by one.
17477 If the cursor is on the year, change the year. If it is on the month,
17478 the day or the time, change that.
17479 With prefix ARG, change by that many units."
17480 (interactive "p")
17481 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17483 (defun org-timestamp-down (&optional arg)
17484 "Decrease the date item at the cursor by one.
17485 If the cursor is on the year, change the year. If it is on the month,
17486 the day or the time, change that.
17487 With prefix ARG, change by that many units."
17488 (interactive "p")
17489 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17491 (defun org-timestamp-up-day (&optional arg)
17492 "Increase the date in the time stamp by one day.
17493 With prefix ARG, change that many days."
17494 (interactive "p")
17495 (if (and (not (org-at-timestamp-p 'lax))
17496 (org-at-heading-p))
17497 (org-todo 'up)
17498 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17500 (defun org-timestamp-down-day (&optional arg)
17501 "Decrease the date in the time stamp by one day.
17502 With prefix ARG, change that many days."
17503 (interactive "p")
17504 (if (and (not (org-at-timestamp-p 'lax))
17505 (org-at-heading-p))
17506 (org-todo 'down)
17507 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17509 (defun org-at-timestamp-p (&optional extended)
17510 "Non-nil if point is inside a timestamp.
17512 By default, the function only consider syntactically valid active
17513 timestamps. However, the caller may have a broader definition
17514 for timestamps. As a consequence, optional argument EXTENDED can
17515 be set to the following values
17517 `inactive'
17519 Include also syntactically valid inactive timestamps.
17521 `agenda'
17523 Include timestamps allowed in Agenda, i.e., those in
17524 properties drawers, planning lines and clock lines.
17526 `lax'
17528 Ignore context. The function matches any part of the
17529 document looking like a timestamp. This includes comments,
17530 example blocks...
17532 For backward-compatibility with Org 9.0, every other non-nil
17533 value is equivalent to `inactive'.
17535 When at a timestamp, return the position of the point as a symbol
17536 among `bracket', `after', `year', `month', `hour', `minute',
17537 `day' or a number of character from the last know part of the
17538 time stamp.
17540 When matching, the match groups are the following:
17541 group 1: year
17542 group 2: month
17543 group 3: day number
17544 group 4: day name
17545 group 5: hours, if any
17546 group 6: minutes, if any"
17547 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17548 (pos (point))
17549 (match?
17550 (let ((boundaries (org-in-regexp regexp)))
17551 (save-match-data
17552 (cond ((null boundaries) nil)
17553 ((eq extended 'lax) t)
17555 (or (and (eq extended 'agenda)
17556 (or (org-at-planning-p)
17557 (org-at-property-p)
17558 (and (bound-and-true-p
17559 org-agenda-include-inactive-timestamps)
17560 (org-at-clock-log-p))))
17561 (eq 'timestamp
17562 (save-excursion
17563 (when (= pos (cdr boundaries)) (forward-char -1))
17564 (org-element-type (org-element-context)))))))))))
17565 (cond
17566 ((not match?) nil)
17567 ((= pos (match-beginning 0)) 'bracket)
17568 ;; Distinguish location right before the closing bracket from
17569 ;; right after it.
17570 ((= pos (1- (match-end 0))) 'bracket)
17571 ((= pos (match-end 0)) 'after)
17572 ((org-pos-in-match-range pos 2) 'year)
17573 ((org-pos-in-match-range pos 3) 'month)
17574 ((org-pos-in-match-range pos 7) 'hour)
17575 ((org-pos-in-match-range pos 8) 'minute)
17576 ((or (org-pos-in-match-range pos 4)
17577 (org-pos-in-match-range pos 5)) 'day)
17578 ((and (> pos (or (match-end 8) (match-end 5)))
17579 (< pos (match-end 0)))
17580 (- pos (or (match-end 8) (match-end 5))))
17581 (t 'day))))
17583 (defun org-toggle-timestamp-type ()
17584 "Toggle the type (<active> or [inactive]) of a time stamp."
17585 (interactive)
17586 (when (org-at-timestamp-p 'lax)
17587 (let ((beg (match-beginning 0)) (end (match-end 0))
17588 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17589 (save-excursion
17590 (goto-char beg)
17591 (while (re-search-forward "[][<>]" end t)
17592 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17593 t t)))
17594 (message "Timestamp is now %sactive"
17595 (if (equal (char-after beg) ?<) "" "in")))))
17597 (defun org-at-clock-log-p ()
17598 "Non-nil if point is on a clock log line."
17599 (and (org-match-line org-clock-line-re)
17600 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17602 (defvar org-clock-history) ; defined in org-clock.el
17603 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17604 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17605 "Change the date in the time stamp at point.
17606 The date will be changed by N times WHAT. WHAT can be `day', `month',
17607 `year', `minute', `second'. If WHAT is not given, the cursor position
17608 in the timestamp determines what will be changed.
17609 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17610 (let ((origin (point))
17611 (timestamp? (org-at-timestamp-p 'lax))
17612 origin-cat
17613 with-hm inactive
17614 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17615 extra rem
17616 ts time time0 fixnext clrgx)
17617 (unless timestamp? (user-error "Not at a timestamp"))
17618 (if (and (not what) (eq timestamp? 'bracket))
17619 (org-toggle-timestamp-type)
17620 ;; Point isn't on brackets. Remember the part of the time-stamp
17621 ;; the point was in. Indeed, size of time-stamps may change,
17622 ;; but point must be kept in the same category nonetheless.
17623 (setq origin-cat timestamp?)
17624 (when (and (not what) (not (eq timestamp? 'day))
17625 org-display-custom-times
17626 (get-text-property (point) 'display)
17627 (not (get-text-property (1- (point)) 'display)))
17628 (setq timestamp? 'day))
17629 (setq timestamp? (or what timestamp?)
17630 inactive (= (char-after (match-beginning 0)) ?\[)
17631 ts (match-string 0))
17632 (replace-match "")
17633 (when (string-match
17634 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17636 (setq extra (match-string 1 ts))
17637 (when suppress-tmp-delay
17638 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17639 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17640 (setq with-hm t))
17641 (setq time0 (org-parse-time-string ts))
17642 (when (and updown
17643 (eq timestamp? 'minute)
17644 (not current-prefix-arg))
17645 ;; This looks like s-up and s-down. Change by one rounding step.
17646 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17647 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17648 (setcar (cdr time0) (+ (nth 1 time0)
17649 (if (> n 0) (- rem) (- dm rem))))))
17650 (setq time
17651 (apply #'encode-time
17652 (or (car time0) 0)
17653 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17654 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17655 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17656 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17657 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17658 (nthcdr 6 time0)))
17659 (when (and (memq timestamp? '(hour minute))
17660 extra
17661 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17662 (setq extra (org-modify-ts-extra
17663 extra
17664 (if (eq timestamp? 'hour) 2 5)
17665 n dm)))
17666 (when (integerp timestamp?)
17667 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17668 (when (eq what 'calendar)
17669 (let ((cal-date (org-get-date-from-calendar)))
17670 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17671 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17672 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17673 (setcar time0 (or (car time0) 0))
17674 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17675 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17676 (setq time (apply 'encode-time time0))))
17677 ;; Insert the new time-stamp, and ensure point stays in the same
17678 ;; category as before (i.e. not after the last position in that
17679 ;; category).
17680 (let ((pos (point)))
17681 ;; Stay before inserted string. `save-excursion' is of no use.
17682 (setq org-last-changed-timestamp
17683 (org-insert-time-stamp time with-hm inactive nil nil extra))
17684 (goto-char pos))
17685 (save-match-data
17686 (looking-at org-ts-regexp3)
17687 (goto-char
17688 (pcase origin-cat
17689 ;; `day' category ends before `hour' if any, or at the end
17690 ;; of the day name.
17691 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17692 (`hour (min (match-end 7) origin))
17693 (`minute (min (1- (match-end 8)) origin))
17694 ((pred integerp) (min (1- (match-end 0)) origin))
17695 ;; Point was right after the time-stamp. However, the
17696 ;; time-stamp length might have changed, so refer to
17697 ;; (match-end 0) instead.
17698 (`after (match-end 0))
17699 ;; `year' and `month' have both fixed size: point couldn't
17700 ;; have moved into another part.
17701 (_ origin))))
17702 ;; Update clock if on a CLOCK line.
17703 (org-clock-update-time-maybe)
17704 ;; Maybe adjust the closest clock in `org-clock-history'
17705 (when org-clock-adjust-closest
17706 (if (not (and (org-at-clock-log-p)
17707 (< 1 (length (delq nil (mapcar 'marker-position
17708 org-clock-history))))))
17709 (message "No clock to adjust")
17710 (cond ((save-excursion ; fix previous clock?
17711 (re-search-backward org-ts-regexp0 nil t)
17712 (looking-back (concat org-clock-string " \\[")
17713 (line-beginning-position)))
17714 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17715 ((save-excursion ; fix next clock?
17716 (re-search-backward org-ts-regexp0 nil t)
17717 (looking-at (concat org-ts-regexp0 "\\] =>")))
17718 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17719 (save-window-excursion
17720 ;; Find closest clock to point, adjust the previous/next one in history
17721 (let* ((p (save-excursion (org-back-to-heading t)))
17722 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17723 (clfixnth
17724 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17725 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17726 (if (not clfixpos)
17727 (message "No clock to adjust")
17728 (save-excursion
17729 (org-goto-marker-or-bmk clfixpos)
17730 (org-show-subtree)
17731 (when (re-search-forward clrgx nil t)
17732 (goto-char (match-beginning 1))
17733 (let (org-clock-adjust-closest)
17734 (org-timestamp-change n timestamp? updown))
17735 (message "Clock adjusted in %s for heading: %s"
17736 (file-name-nondirectory (buffer-file-name))
17737 (org-get-heading t t)))))))))
17738 ;; Try to recenter the calendar window, if any.
17739 (when (and org-calendar-follow-timestamp-change
17740 (get-buffer-window "*Calendar*" t)
17741 (memq timestamp? '(day month year)))
17742 (org-recenter-calendar (time-to-days time))))))
17744 (defun org-modify-ts-extra (s pos n dm)
17745 "Change the different parts of the lead-time and repeat fields in timestamp."
17746 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17747 ng h m new rem)
17748 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17749 (cond
17750 ((or (org-pos-in-match-range pos 2)
17751 (org-pos-in-match-range pos 3))
17752 (setq m (string-to-number (match-string 3 s))
17753 h (string-to-number (match-string 2 s)))
17754 (if (org-pos-in-match-range pos 2)
17755 (setq h (+ h n))
17756 (setq n (* dm (with-no-warnings (signum n))))
17757 (unless (= 0 (setq rem (% m dm)))
17758 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17759 (setq m (+ m n)))
17760 (when (< m 0) (setq m (+ m 60) h (1- h)))
17761 (when (> m 59) (setq m (- m 60) h (1+ h)))
17762 (setq h (mod h 24))
17763 (setq ng 1 new (format "-%02d:%02d" h m)))
17764 ((org-pos-in-match-range pos 6)
17765 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17766 ((org-pos-in-match-range pos 5)
17767 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17769 ((org-pos-in-match-range pos 9)
17770 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17771 ((org-pos-in-match-range pos 8)
17772 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17774 (when ng
17775 (setq s (concat
17776 (substring s 0 (match-beginning ng))
17778 (substring s (match-end ng))))))
17781 (defun org-recenter-calendar (d)
17782 "If the calendar is visible, recenter it to date D."
17783 (let ((cwin (get-buffer-window "*Calendar*" t)))
17784 (when cwin
17785 (let ((calendar-move-hook nil))
17786 (with-selected-window cwin
17787 (calendar-goto-date
17788 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17790 (defun org-goto-calendar (&optional arg)
17791 "Go to the Emacs calendar at the current date.
17792 If there is a time stamp in the current line, go to that date.
17793 A prefix ARG can be used to force the current date."
17794 (interactive "P")
17795 (let ((calendar-move-hook nil)
17796 (calendar-view-holidays-initially-flag nil)
17797 (calendar-view-diary-initially-flag nil)
17798 diff)
17799 (when (or (org-at-timestamp-p 'lax)
17800 (org-match-line (concat ".*" org-ts-regexp)))
17801 (let ((d1 (time-to-days (current-time)))
17802 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17803 (setq diff (- d2 d1))))
17804 (calendar)
17805 (calendar-goto-today)
17806 (when (and diff (not arg)) (calendar-forward-day diff))))
17808 (defun org-get-date-from-calendar ()
17809 "Return a list (month day year) of date at point in calendar."
17810 (with-current-buffer "*Calendar*"
17811 (save-match-data
17812 (calendar-cursor-to-date))))
17814 (defun org-date-from-calendar ()
17815 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17816 If there is already a time stamp at the cursor position, update it."
17817 (interactive)
17818 (if (org-at-timestamp-p 'lax)
17819 (org-timestamp-change 0 'calendar)
17820 (let ((cal-date (org-get-date-from-calendar)))
17821 (org-insert-time-stamp
17822 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17824 (defcustom org-effort-durations
17825 `(("min" . 1)
17826 ("h" . 60)
17827 ("d" . ,(* 60 8))
17828 ("w" . ,(* 60 8 5))
17829 ("m" . ,(* 60 8 5 4))
17830 ("y" . ,(* 60 8 5 40)))
17831 "Conversion factor to minutes for an effort modifier.
17833 Each entry has the form (MODIFIER . MINUTES).
17835 In an effort string, a number followed by MODIFIER is multiplied
17836 by the specified number of MINUTES to obtain an effort in
17837 minutes.
17839 For example, if the value of this variable is ((\"hours\" . 60)), then an
17840 effort string \"2hours\" is equivalent to 120 minutes."
17841 :group 'org-agenda
17842 :version "26.1"
17843 :package-version '(Org . "8.3")
17844 :type '(alist :key-type (string :tag "Modifier")
17845 :value-type (number :tag "Minutes")))
17847 (defcustom org-image-actual-width t
17848 "Should we use the actual width of images when inlining them?
17850 When set to t, always use the image width.
17852 When set to a number, use imagemagick (when available) to set
17853 the image's width to this value.
17855 When set to a number in a list, try to get the width from any
17856 #+ATTR.* keyword if it matches a width specification like
17858 #+ATTR_HTML: :width 300px
17860 and fall back on that number if none is found.
17862 When set to nil, try to get the width from an #+ATTR.* keyword
17863 and fall back on the original width if none is found.
17865 This requires Emacs >= 24.1, build with imagemagick support."
17866 :group 'org-appearance
17867 :version "24.4"
17868 :package-version '(Org . "8.0")
17869 :type '(choice
17870 (const :tag "Use the image width" t)
17871 (integer :tag "Use a number of pixels")
17872 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17873 (const :tag "Use #+ATTR* or don't resize" nil)))
17875 (defcustom org-agenda-inhibit-startup nil
17876 "Inhibit startup when preparing agenda buffers.
17877 When this variable is t, the initialization of the Org agenda
17878 buffers is inhibited: e.g. the visibility state is not set, the
17879 tables are not re-aligned, etc."
17880 :type 'boolean
17881 :version "24.3"
17882 :group 'org-agenda)
17884 (defcustom org-agenda-ignore-properties nil
17885 "Avoid updating text properties when building the agenda.
17886 Properties are used to prepare buffers for effort estimates,
17887 appointments, statistics and subtree-local categories.
17888 If you don't use these in the agenda, you can add them to this
17889 list and agenda building will be a bit faster.
17890 The value is a list, with zero or more of the symbols `effort', `appt',
17891 `stats' or `category'."
17892 :type '(set :greedy t
17893 (const effort)
17894 (const appt)
17895 (const stats)
17896 (const category))
17897 :version "26.1"
17898 :package-version '(Org . "8.3")
17899 :group 'org-agenda)
17901 ;;;; Files
17903 (defun org-save-all-org-buffers ()
17904 "Save all Org buffers without user confirmation."
17905 (interactive)
17906 (message "Saving all Org buffers...")
17907 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17908 (when (featurep 'org-id) (org-id-locations-save))
17909 (message "Saving all Org buffers... done"))
17911 (defun org-revert-all-org-buffers ()
17912 "Revert all Org buffers.
17913 Prompt for confirmation when there are unsaved changes.
17914 Be sure you know what you are doing before letting this function
17915 overwrite your changes.
17917 This function is useful in a setup where one tracks org files
17918 with a version control system, to revert on one machine after pulling
17919 changes from another. I believe the procedure must be like this:
17921 1. M-x org-save-all-org-buffers
17922 2. Pull changes from the other machine, resolve conflicts
17923 3. M-x org-revert-all-org-buffers"
17924 (interactive)
17925 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17926 (user-error "Abort"))
17927 (save-excursion
17928 (save-window-excursion
17929 (dolist (b (buffer-list))
17930 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17931 (with-current-buffer b buffer-file-name))
17932 (pop-to-buffer-same-window b)
17933 (revert-buffer t 'no-confirm)))
17934 (when (and (featurep 'org-id) org-id-track-globally)
17935 (org-id-locations-load)))))
17937 ;;;; Agenda files
17939 ;;;###autoload
17940 (defun org-switchb (&optional arg)
17941 "Switch between Org buffers.
17943 With `\\[universal-argument]' prefix, restrict available buffers to files.
17945 With `\\[universal-argument] \\[universal-argument]' \
17946 prefix, restrict available buffers to agenda files."
17947 (interactive "P")
17948 (let ((blist (org-buffer-list
17949 (cond ((equal arg '(4)) 'files)
17950 ((equal arg '(16)) 'agenda)))))
17951 (pop-to-buffer-same-window
17952 (completing-read "Org buffer: "
17953 (mapcar #'list (mapcar #'buffer-name blist))
17954 nil t))))
17956 (defun org-buffer-list (&optional predicate exclude-tmp)
17957 "Return a list of Org buffers.
17958 PREDICATE can be `export', `files' or `agenda'.
17960 export restrict the list to Export buffers.
17961 files restrict the list to buffers visiting Org files.
17962 agenda restrict the list to buffers visiting agenda files.
17964 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17965 (let* ((bfn nil)
17966 (agenda-files (and (eq predicate 'agenda)
17967 (mapcar 'file-truename (org-agenda-files t))))
17968 (filter
17969 (cond
17970 ((eq predicate 'files)
17971 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17972 ((eq predicate 'export)
17973 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17974 ((eq predicate 'agenda)
17975 (lambda (b)
17976 (with-current-buffer b
17977 (and (derived-mode-p 'org-mode)
17978 (setq bfn (buffer-file-name b))
17979 (member (file-truename bfn) agenda-files)))))
17980 (t (lambda (b) (with-current-buffer b
17981 (or (derived-mode-p 'org-mode)
17982 (string-match "\\*Org .*Export"
17983 (buffer-name b)))))))))
17984 (delq nil
17985 (mapcar
17986 (lambda(b)
17987 (if (and (funcall filter b)
17988 (or (not exclude-tmp)
17989 (not (string-match "tmp" (buffer-name b)))))
17991 nil))
17992 (buffer-list)))))
17994 (defun org-agenda-files (&optional unrestricted archives)
17995 "Get the list of agenda files.
17996 Optional UNRESTRICTED means return the full list even if a restriction
17997 is currently in place.
17998 When ARCHIVES is t, include all archive files that are really being
17999 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18000 `org-agenda-archives-mode' is t."
18001 (let ((files
18002 (cond
18003 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18004 ((stringp org-agenda-files) (org-read-agenda-file-list))
18005 ((listp org-agenda-files) org-agenda-files)
18006 (t (error "Invalid value of `org-agenda-files'")))))
18007 (setq files (apply 'append
18008 (mapcar (lambda (f)
18009 (if (file-directory-p f)
18010 (directory-files
18011 f t org-agenda-file-regexp)
18012 (list f)))
18013 files)))
18014 (when org-agenda-skip-unavailable-files
18015 (setq files (delq nil
18016 (mapcar (function
18017 (lambda (file)
18018 (and (file-readable-p file) file)))
18019 files))))
18020 (when (or (eq archives t)
18021 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18022 (setq files (org-add-archive-files files)))
18023 files))
18025 (defun org-agenda-file-p (&optional file)
18026 "Return non-nil, if FILE is an agenda file.
18027 If FILE is omitted, use the file associated with the current
18028 buffer."
18029 (let ((fname (or file (buffer-file-name))))
18030 (and fname
18031 (member (file-truename fname)
18032 (mapcar #'file-truename (org-agenda-files t))))))
18034 (defun org-edit-agenda-file-list ()
18035 "Edit the list of agenda files.
18036 Depending on setup, this either uses customize to edit the variable
18037 `org-agenda-files', or it visits the file that is holding the list. In the
18038 latter case, the buffer is set up in a way that saving it automatically kills
18039 the buffer and restores the previous window configuration."
18040 (interactive)
18041 (if (stringp org-agenda-files)
18042 (let ((cw (current-window-configuration)))
18043 (find-file org-agenda-files)
18044 (setq-local org-window-configuration cw)
18045 (add-hook 'after-save-hook
18046 (lambda ()
18047 (set-window-configuration
18048 (prog1 org-window-configuration
18049 (kill-buffer (current-buffer))))
18050 (org-install-agenda-files-menu)
18051 (message "New agenda file list installed"))
18052 nil 'local)
18053 (message "%s" (substitute-command-keys
18054 "Edit list and finish with \\[save-buffer]")))
18055 (customize-variable 'org-agenda-files)))
18057 (defun org-store-new-agenda-file-list (list)
18058 "Set new value for the agenda file list and save it correctly."
18059 (if (stringp org-agenda-files)
18060 (let ((fe (org-read-agenda-file-list t)) b u)
18061 (while (setq b (find-buffer-visiting org-agenda-files))
18062 (kill-buffer b))
18063 (with-temp-file org-agenda-files
18064 (insert
18065 (mapconcat
18066 (lambda (f) ;; Keep un-expanded entries.
18067 (if (setq u (assoc f fe))
18068 (cdr u)
18070 list "\n")
18071 "\n")))
18072 (let ((org-mode-hook nil) (org-inhibit-startup t)
18073 (org-insert-mode-line-in-empty-file nil))
18074 (setq org-agenda-files list)
18075 (customize-save-variable 'org-agenda-files org-agenda-files))))
18077 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18078 "Read the list of agenda files from a file.
18079 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18080 filenames, used by `org-store-new-agenda-file-list' to write back
18081 un-expanded file names."
18082 (when (file-directory-p org-agenda-files)
18083 (error "`org-agenda-files' cannot be a single directory"))
18084 (when (stringp org-agenda-files)
18085 (with-temp-buffer
18086 (insert-file-contents org-agenda-files)
18087 (mapcar
18088 (lambda (f)
18089 (let ((e (expand-file-name (substitute-in-file-name f)
18090 org-directory)))
18091 (if pair-with-expansion
18092 (cons e f)
18093 e)))
18094 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18096 ;;;###autoload
18097 (defun org-cycle-agenda-files ()
18098 "Cycle through the files in `org-agenda-files'.
18099 If the current buffer visits an agenda file, find the next one in the list.
18100 If the current buffer does not, find the first agenda file."
18101 (interactive)
18102 (let* ((fs (or (org-agenda-files t)
18103 (user-error "No agenda files")))
18104 (files (copy-sequence fs))
18105 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18106 file)
18107 (when tcf
18108 (while (and (setq file (pop files))
18109 (not (equal (file-truename file) tcf)))))
18110 (find-file (car (or files fs)))
18111 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18113 (defun org-agenda-file-to-front (&optional to-end)
18114 "Move/add the current file to the top of the agenda file list.
18115 If the file is not present in the list, it is added to the front. If it is
18116 present, it is moved there. With optional argument TO-END, add/move to the
18117 end of the list."
18118 (interactive "P")
18119 (let ((org-agenda-skip-unavailable-files nil)
18120 (file-alist (mapcar (lambda (x)
18121 (cons (file-truename x) x))
18122 (org-agenda-files t)))
18123 (ctf (file-truename
18124 (or buffer-file-name
18125 (user-error "Please save the current buffer to a file"))))
18126 x had)
18127 (setq x (assoc ctf file-alist) had x)
18129 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18130 (if to-end
18131 (setq file-alist (append (delq x file-alist) (list x)))
18132 (setq file-alist (cons x (delq x file-alist))))
18133 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18134 (org-install-agenda-files-menu)
18135 (message "File %s to %s of agenda file list"
18136 (if had "moved" "added") (if to-end "end" "front"))))
18138 (defun org-remove-file (&optional file)
18139 "Remove current file from the list of files in variable `org-agenda-files'.
18140 These are the files which are being checked for agenda entries.
18141 Optional argument FILE means use this file instead of the current."
18142 (interactive)
18143 (let* ((org-agenda-skip-unavailable-files nil)
18144 (file (or file buffer-file-name
18145 (user-error "Current buffer does not visit a file")))
18146 (true-file (file-truename file))
18147 (afile (abbreviate-file-name file))
18148 (files (delq nil (mapcar
18149 (lambda (x)
18150 (unless (equal true-file
18151 (file-truename x))
18153 (org-agenda-files t)))))
18154 (if (not (= (length files) (length (org-agenda-files t))))
18155 (progn
18156 (org-store-new-agenda-file-list files)
18157 (org-install-agenda-files-menu)
18158 (message "Removed from Org Agenda list: %s" afile))
18159 (message "File was not in list: %s (not removed)" afile))))
18161 (defun org-file-menu-entry (file)
18162 (vector file (list 'find-file file) t))
18164 (defun org-check-agenda-file (file)
18165 "Make sure FILE exists. If not, ask user what to do."
18166 (unless (file-exists-p file)
18167 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18168 (abbreviate-file-name file))
18169 (let ((r (downcase (read-char-exclusive))))
18170 (cond
18171 ((equal r ?r)
18172 (org-remove-file file)
18173 (throw 'nextfile t))
18174 (t (user-error "Abort"))))))
18176 (defun org-get-agenda-file-buffer (file)
18177 "Get an agenda buffer visiting FILE.
18178 If the buffer needs to be created, add it to the list of buffers
18179 which might be released later."
18180 (let ((buf (org-find-base-buffer-visiting file)))
18181 (if buf
18182 buf ; just return it
18183 ;; Make a new buffer and remember it
18184 (setq buf (find-file-noselect file))
18185 (when buf (push buf org-agenda-new-buffers))
18186 buf)))
18188 (defun org-release-buffers (blist)
18189 "Release all buffers in list, asking the user for confirmation when needed.
18190 When a buffer is unmodified, it is just killed. When modified, it is saved
18191 \(if the user agrees) and then killed."
18192 (let (file)
18193 (dolist (buf blist)
18194 (setq file (buffer-file-name buf))
18195 (when (and (buffer-modified-p buf)
18196 file
18197 (y-or-n-p (format "Save file %s? " file)))
18198 (with-current-buffer buf (save-buffer)))
18199 (kill-buffer buf))))
18201 (defun org-agenda-prepare-buffers (files)
18202 "Create buffers for all agenda files, protect archived trees and comments."
18203 (interactive)
18204 (let ((pa '(:org-archived t))
18205 (pc '(:org-comment t))
18206 (pall '(:org-archived t :org-comment t))
18207 (inhibit-read-only t)
18208 (org-inhibit-startup org-agenda-inhibit-startup)
18209 (rea (concat ":" org-archive-tag ":"))
18210 re pos)
18211 (setq org-tag-alist-for-agenda nil
18212 org-tag-groups-alist-for-agenda nil)
18213 (save-excursion
18214 (save-restriction
18215 (dolist (file files)
18216 (catch 'nextfile
18217 (if (bufferp file)
18218 (set-buffer file)
18219 (org-check-agenda-file file)
18220 (set-buffer (org-get-agenda-file-buffer file)))
18221 (widen)
18222 (org-set-regexps-and-options 'tags-only)
18223 (setq pos (point))
18224 (or (memq 'category org-agenda-ignore-properties)
18225 (org-refresh-category-properties))
18226 (or (memq 'stats org-agenda-ignore-properties)
18227 (org-refresh-stats-properties))
18228 (or (memq 'effort org-agenda-ignore-properties)
18229 (org-refresh-effort-properties))
18230 (or (memq 'appt org-agenda-ignore-properties)
18231 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18232 (setq org-todo-keywords-for-agenda
18233 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18234 (setq org-done-keywords-for-agenda
18235 (append org-done-keywords-for-agenda org-done-keywords))
18236 (setq org-todo-keyword-alist-for-agenda
18237 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18238 (setq org-tag-alist-for-agenda
18239 (org-uniquify
18240 (append org-tag-alist-for-agenda
18241 org-current-tag-alist)))
18242 ;; Merge current file's tag groups into global
18243 ;; `org-tag-groups-alist-for-agenda'.
18244 (when org-group-tags
18245 (dolist (alist org-tag-groups-alist)
18246 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18247 (if old
18248 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18249 (push alist org-tag-groups-alist-for-agenda)))))
18250 (org-with-silent-modifications
18251 (save-excursion
18252 (remove-text-properties (point-min) (point-max) pall)
18253 (when org-agenda-skip-archived-trees
18254 (goto-char (point-min))
18255 (while (re-search-forward rea nil t)
18256 (when (org-at-heading-p t)
18257 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18258 (goto-char (point-min))
18259 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18260 (while (re-search-forward re nil t)
18261 (when (save-match-data (org-in-commented-heading-p t))
18262 (add-text-properties
18263 (match-beginning 0) (org-end-of-subtree t) pc)))))
18264 (goto-char pos)))))
18265 (setq org-todo-keywords-for-agenda
18266 (org-uniquify org-todo-keywords-for-agenda))
18267 (setq org-todo-keyword-alist-for-agenda
18268 (org-uniquify org-todo-keyword-alist-for-agenda))))
18271 ;;;; CDLaTeX minor mode
18273 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18274 "Keymap for the minor `org-cdlatex-mode'.")
18276 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18277 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18278 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18279 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18280 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18282 (defvar org-cdlatex-texmathp-advice-is-done nil
18283 "Flag remembering if we have applied the advice to texmathp already.")
18285 (define-minor-mode org-cdlatex-mode
18286 "Toggle the minor `org-cdlatex-mode'.
18287 This mode supports entering LaTeX environment and math in LaTeX fragments
18288 in Org mode.
18289 \\{org-cdlatex-mode-map}"
18290 nil " OCDL" nil
18291 (when org-cdlatex-mode
18292 (require 'cdlatex)
18293 (run-hooks 'cdlatex-mode-hook)
18294 (cdlatex-compute-tables))
18295 (unless org-cdlatex-texmathp-advice-is-done
18296 (setq org-cdlatex-texmathp-advice-is-done t)
18297 (defadvice texmathp (around org-math-always-on activate)
18298 "Always return t in Org buffers.
18299 This is because we want to insert math symbols without dollars even outside
18300 the LaTeX math segments. If Org mode thinks that point is actually inside
18301 an embedded LaTeX fragment, let `texmathp' do its job.
18302 `\\[org-cdlatex-mode-map]'"
18303 (interactive)
18304 (let (p)
18305 (cond
18306 ((not (derived-mode-p 'org-mode)) ad-do-it)
18307 ((eq this-command 'cdlatex-math-symbol)
18308 (setq ad-return-value t
18309 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18311 (let ((p (org-inside-LaTeX-fragment-p)))
18312 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18313 (setq ad-return-value t
18314 texmathp-why '("Org mode embedded math" . 0))
18315 (when p ad-do-it)))))))))
18317 (defun turn-on-org-cdlatex ()
18318 "Unconditionally turn on `org-cdlatex-mode'."
18319 (org-cdlatex-mode 1))
18321 (defun org-try-cdlatex-tab ()
18322 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18323 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18324 - inside a LaTeX fragment, or
18325 - after the first word in a line, where an abbreviation expansion could
18326 insert a LaTeX environment."
18327 (when org-cdlatex-mode
18328 (cond
18329 ;; Before any word on the line: No expansion possible.
18330 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18331 ;; Just after first word on the line: Expand it. Make sure it
18332 ;; cannot happen on headlines, though.
18333 ((save-excursion
18334 (skip-chars-backward "a-zA-Z0-9*")
18335 (skip-chars-backward " \t")
18336 (and (bolp) (not (org-at-heading-p))))
18337 (cdlatex-tab) t)
18338 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18340 (defun org-cdlatex-underscore-caret (&optional _arg)
18341 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18342 Revert to the normal definition outside of these fragments."
18343 (interactive "P")
18344 (if (org-inside-LaTeX-fragment-p)
18345 (call-interactively 'cdlatex-sub-superscript)
18346 (let (org-cdlatex-mode)
18347 (call-interactively (key-binding (vector last-input-event))))))
18349 (defun org-cdlatex-math-modify (&optional _arg)
18350 "Execute `cdlatex-math-modify' in LaTeX fragments.
18351 Revert to the normal definition outside of these fragments."
18352 (interactive "P")
18353 (if (org-inside-LaTeX-fragment-p)
18354 (call-interactively 'cdlatex-math-modify)
18355 (let (org-cdlatex-mode)
18356 (call-interactively (key-binding (vector last-input-event))))))
18358 (defun org-cdlatex-environment-indent (&optional environment item)
18359 "Execute `cdlatex-environment' and indent the inserted environment.
18361 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18363 The inserted environment is indented to current indentation
18364 unless point is at the beginning of the line, in which the
18365 environment remains unintended."
18366 (interactive)
18367 ;; cdlatex-environment always return nil. Therefore, capture output
18368 ;; first and determine if an environment was selected.
18369 (let* ((beg (point-marker))
18370 (end (copy-marker (point) t))
18371 (inserted (progn
18372 (ignore-errors (cdlatex-environment environment item))
18373 (< beg end)))
18374 ;; Figure out how many lines to move forward after the
18375 ;; environment has been inserted.
18376 (lines (when inserted
18377 (save-excursion
18378 (- (cl-loop while (< beg (point))
18379 with x = 0
18380 do (forward-line -1)
18381 (cl-incf x)
18382 finally return x)
18383 (if (progn (goto-char beg)
18384 (and (progn (skip-chars-forward " \t") (eolp))
18385 (progn (skip-chars-backward " \t") (bolp))))
18386 1 0)))))
18387 (env (org-trim (delete-and-extract-region beg end))))
18388 (when inserted
18389 ;; Get indentation of next line unless at column 0.
18390 (let ((ind (if (bolp) 0
18391 (save-excursion
18392 (org-return-indent)
18393 (prog1 (org-get-indentation)
18394 (when (progn (skip-chars-forward " \t") (eolp))
18395 (delete-region beg (point)))))))
18396 (bol (progn (skip-chars-backward " \t") (bolp))))
18397 ;; Insert a newline before environment unless at column zero
18398 ;; to "escape" the current line. Insert a newline if
18399 ;; something is one the same line as \end{ENVIRONMENT}.
18400 (insert
18401 (concat (unless bol "\n") env
18402 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18403 (unless (zerop ind)
18404 (save-excursion
18405 (goto-char beg)
18406 (while (< (point) end)
18407 (unless (eolp) (indent-line-to ind))
18408 (forward-line))))
18409 (goto-char beg)
18410 (forward-line lines)
18411 (indent-line-to ind)))
18412 (set-marker beg nil)
18413 (set-marker end nil)))
18416 ;;;; LaTeX fragments
18418 (defun org-inside-LaTeX-fragment-p ()
18419 "Test if point is inside a LaTeX fragment.
18420 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18421 sequence appearing also before point.
18422 Even though the matchers for math are configurable, this function assumes
18423 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18424 delimiters are skipped when they have been removed by customization.
18425 The return value is nil, or a cons cell with the delimiter and the
18426 position of this delimiter.
18428 This function does a reasonably good job, but can locally be fooled by
18429 for example currency specifications. For example it will assume being in
18430 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18431 fragments that are properly closed, but during editing, we have to live
18432 with the uncertainty caused by missing closing delimiters. This function
18433 looks only before point, not after."
18434 (catch 'exit
18435 (let ((pos (point))
18436 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18437 (lim (save-excursion (org-backward-paragraph) (point)))
18438 dd-on str (start 0) m re)
18439 (goto-char pos)
18440 (when dodollar
18441 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18442 re (nth 1 (assoc "$" org-latex-regexps)))
18443 (while (string-match re str start)
18444 (cond
18445 ((= (match-end 0) (length str))
18446 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18447 ((= (match-end 0) (- (length str) 5))
18448 (throw 'exit nil))
18449 (t (setq start (match-end 0))))))
18450 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18451 (goto-char pos)
18452 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18453 (and (match-beginning 2) (throw 'exit nil))
18454 ;; count $$
18455 (while (re-search-backward "\\$\\$" lim t)
18456 (setq dd-on (not dd-on)))
18457 (goto-char pos)
18458 (when dd-on (cons "$$" m))))))
18460 (defun org-inside-latex-macro-p ()
18461 "Is point inside a LaTeX macro or its arguments?"
18462 (save-match-data
18463 (org-in-regexp
18464 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18466 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18467 "Build an overlay between BEG and END using IMAGE file.
18468 Argument IMAGETYPE is the extension of the displayed image,
18469 as a string. It defaults to \"png\"."
18470 (let ((ov (make-overlay beg end))
18471 (imagetype (or (intern imagetype) 'png)))
18472 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18473 (overlay-put ov 'evaporate t)
18474 (overlay-put ov
18475 'modification-hooks
18476 (list (lambda (o _flag _beg _end &optional _l)
18477 (delete-overlay o))))
18478 (overlay-put ov
18479 'display
18480 (list 'image :type imagetype :file image :ascent 'center))))
18482 (defun org--list-latex-overlays (&optional beg end)
18483 "List all Org LaTeX overlays in current buffer.
18484 Limit to overlays between BEG and END when those are provided."
18485 (cl-remove-if-not
18486 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18487 (overlays-in (or beg (point-min)) (or end (point-max)))))
18489 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18490 "Remove all overlays with LaTeX fragment images in current buffer.
18491 When optional arguments BEG and END are non-nil, remove all
18492 overlays between them instead. Return a non-nil value when some
18493 overlays were removed, nil otherwise."
18494 (let ((overlays (org--list-latex-overlays beg end)))
18495 (mapc #'delete-overlay overlays)
18496 overlays))
18498 (defun org-toggle-latex-fragment (&optional arg)
18499 "Preview the LaTeX fragment at point, or all locally or globally.
18501 If the cursor is on a LaTeX fragment, create the image and overlay
18502 it over the source code, if there is none. Remove it otherwise.
18503 If there is no fragment at point, display all fragments in the
18504 current section.
18506 With prefix ARG, preview or clear image for all fragments in the
18507 current subtree or in the whole buffer when used before the first
18508 headline. With a prefix ARG `\\[universal-argument] \
18509 \\[universal-argument]' preview or clear images
18510 for all fragments in the buffer."
18511 (interactive "P")
18512 (when (display-graphic-p)
18513 (catch 'exit
18514 (save-excursion
18515 (let (beg end msg)
18516 (cond
18517 ((or (equal arg '(16))
18518 (and (equal arg '(4))
18519 (org-with-limited-levels (org-before-first-heading-p))))
18520 (if (org-remove-latex-fragment-image-overlays)
18521 (progn (message "LaTeX fragments images removed from buffer")
18522 (throw 'exit nil))
18523 (setq msg "Creating images for buffer...")))
18524 ((equal arg '(4))
18525 (org-with-limited-levels (org-back-to-heading t))
18526 (setq beg (point))
18527 (setq end (progn (org-end-of-subtree t) (point)))
18528 (if (org-remove-latex-fragment-image-overlays beg end)
18529 (progn
18530 (message "LaTeX fragment images removed from subtree")
18531 (throw 'exit nil))
18532 (setq msg "Creating images for subtree...")))
18533 ((let ((datum (org-element-context)))
18534 (when (memq (org-element-type datum)
18535 '(latex-environment latex-fragment))
18536 (setq beg (org-element-property :begin datum))
18537 (setq end (org-element-property :end datum))
18538 (if (org-remove-latex-fragment-image-overlays beg end)
18539 (progn (message "LaTeX fragment image removed")
18540 (throw 'exit nil))
18541 (setq msg "Creating image...")))))
18543 (org-with-limited-levels
18544 (setq beg (if (org-at-heading-p) (line-beginning-position)
18545 (outline-previous-heading)
18546 (point)))
18547 (setq end (progn (outline-next-heading) (point)))
18548 (if (org-remove-latex-fragment-image-overlays beg end)
18549 (progn
18550 (message "LaTeX fragment images removed from section")
18551 (throw 'exit nil))
18552 (setq msg "Creating images for section...")))))
18553 (let ((file (buffer-file-name (buffer-base-buffer))))
18554 (org-format-latex
18555 (concat org-preview-latex-image-directory "org-ltximg")
18556 beg end
18557 ;; Emacs cannot overlay images from remote hosts. Create
18558 ;; it in `temporary-file-directory' instead.
18559 (if (or (not file) (file-remote-p file))
18560 temporary-file-directory
18561 default-directory)
18562 'overlays msg 'forbuffer org-preview-latex-default-process))
18563 (message (concat msg "done")))))))
18565 (defun org-format-latex
18566 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18567 "Replace LaTeX fragments with links to an image.
18569 The function takes care of creating the replacement image.
18571 Only consider fragments between BEG and END when those are
18572 provided.
18574 When optional argument OVERLAYS is non-nil, display the image on
18575 top of the fragment instead of replacing it.
18577 PROCESSING-TYPE is the conversion method to use, as a symbol.
18579 Some of the options can be changed using the variable
18580 `org-format-latex-options', which see."
18581 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18582 (unless (eq processing-type 'verbatim)
18583 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18584 (cnt 0)
18585 checkdir-flag)
18586 (goto-char (or beg (point-min)))
18587 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18588 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18589 (overlay-recenter (or end (point-max))))
18590 (while (re-search-forward math-regexp end t)
18591 (unless (and overlays
18592 (eq (get-char-property (point) 'org-overlay-type)
18593 'org-latex-overlay))
18594 (let* ((context (org-element-context))
18595 (type (org-element-type context)))
18596 (when (memq type '(latex-environment latex-fragment))
18597 (let ((block-type (eq type 'latex-environment))
18598 (value (org-element-property :value context))
18599 (beg (org-element-property :begin context))
18600 (end (save-excursion
18601 (goto-char (org-element-property :end context))
18602 (skip-chars-backward " \r\t\n")
18603 (point))))
18604 (cond
18605 ((eq processing-type 'mathjax)
18606 ;; Prepare for MathJax processing.
18607 (if (not (string-match "\\`\\$\\$?" value))
18608 (goto-char end)
18609 (delete-region beg end)
18610 (if (string= (match-string 0 value) "$$")
18611 (insert "\\[" (substring value 2 -2) "\\]")
18612 (insert "\\(" (substring value 1 -1) "\\)"))))
18613 ((assq processing-type org-preview-latex-process-alist)
18614 ;; Process to an image.
18615 (cl-incf cnt)
18616 (goto-char beg)
18617 (let* ((processing-info
18618 (cdr (assq processing-type org-preview-latex-process-alist)))
18619 (face (face-at-point))
18620 ;; Get the colors from the face at point.
18622 (let ((color (plist-get org-format-latex-options
18623 :foreground)))
18624 (if (and forbuffer (eq color 'auto))
18625 (face-attribute face :foreground nil 'default)
18626 color)))
18628 (let ((color (plist-get org-format-latex-options
18629 :background)))
18630 (if (and forbuffer (eq color 'auto))
18631 (face-attribute face :background nil 'default)
18632 color)))
18633 (hash (sha1 (prin1-to-string
18634 (list org-format-latex-header
18635 org-latex-default-packages-alist
18636 org-latex-packages-alist
18637 org-format-latex-options
18638 forbuffer value fg bg))))
18639 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18640 (absprefix (expand-file-name prefix dir))
18641 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18642 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18643 (sep (and block-type "\n\n"))
18644 (link (concat sep "[[file:" linkfile "]]" sep))
18645 (options
18646 (org-combine-plists
18647 org-format-latex-options
18648 `(:foreground ,fg :background ,bg))))
18649 (when msg (message msg cnt))
18650 (unless checkdir-flag ; Ensure the directory exists.
18651 (setq checkdir-flag t)
18652 (let ((todir (file-name-directory absprefix)))
18653 (unless (file-directory-p todir)
18654 (make-directory todir t))))
18655 (unless (file-exists-p movefile)
18656 (org-create-formula-image
18657 value movefile options forbuffer processing-type))
18658 (if overlays
18659 (progn
18660 (dolist (o (overlays-in beg end))
18661 (when (eq (overlay-get o 'org-overlay-type)
18662 'org-latex-overlay)
18663 (delete-overlay o)))
18664 (org--format-latex-make-overlay beg end movefile imagetype)
18665 (goto-char end))
18666 (delete-region beg end)
18667 (insert
18668 (org-add-props link
18669 (list 'org-latex-src
18670 (replace-regexp-in-string "\"" "" value)
18671 'org-latex-src-embed-type
18672 (if block-type 'paragraph 'character)))))))
18673 ((eq processing-type 'mathml)
18674 ;; Process to MathML.
18675 (unless (org-format-latex-mathml-available-p)
18676 (user-error "LaTeX to MathML converter not configured"))
18677 (cl-incf cnt)
18678 (when msg (message msg cnt))
18679 (goto-char beg)
18680 (delete-region beg end)
18681 (insert (org-format-latex-as-mathml
18682 value block-type prefix dir)))
18684 (error "Unknown conversion process %s for LaTeX fragments"
18685 processing-type)))))))))))
18687 (defun org-create-math-formula (latex-frag &optional mathml-file)
18688 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18689 Use `org-latex-to-mathml-convert-command'. If the conversion is
18690 sucessful, return the portion between \"<math...> </math>\"
18691 elements otherwise return nil. When MATHML-FILE is specified,
18692 write the results in to that file. When invoked as an
18693 interactive command, prompt for LATEX-FRAG, with initial value
18694 set to the current active region and echo the results for user
18695 inspection."
18696 (interactive (list (let ((frag (when (org-region-active-p)
18697 (buffer-substring-no-properties
18698 (region-beginning) (region-end)))))
18699 (read-string "LaTeX Fragment: " frag nil frag))))
18700 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18701 (let* ((tmp-in-file
18702 (let ((file (file-relative-name
18703 (make-temp-name (expand-file-name "ltxmathml-in")))))
18704 (write-region latex-frag nil file)
18705 file))
18706 (tmp-out-file (file-relative-name
18707 (make-temp-name (expand-file-name "ltxmathml-out"))))
18708 (cmd (format-spec
18709 org-latex-to-mathml-convert-command
18710 `((?j . ,(and org-latex-to-mathml-jar-file
18711 (shell-quote-argument
18712 (expand-file-name
18713 org-latex-to-mathml-jar-file))))
18714 (?I . ,(shell-quote-argument tmp-in-file))
18715 (?i . ,latex-frag)
18716 (?o . ,(shell-quote-argument tmp-out-file)))))
18717 mathml shell-command-output)
18718 (when (called-interactively-p 'any)
18719 (unless (org-format-latex-mathml-available-p)
18720 (user-error "LaTeX to MathML converter not configured")))
18721 (message "Running %s" cmd)
18722 (setq shell-command-output (shell-command-to-string cmd))
18723 (setq mathml
18724 (when (file-readable-p tmp-out-file)
18725 (with-current-buffer (find-file-noselect tmp-out-file t)
18726 (goto-char (point-min))
18727 (when (re-search-forward
18728 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18729 (regexp-quote
18730 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18731 nil t)
18732 (prog1 (match-string 0) (kill-buffer))))))
18733 (cond
18734 (mathml
18735 (setq mathml
18736 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18737 (when mathml-file
18738 (write-region mathml nil mathml-file))
18739 (when (called-interactively-p 'any)
18740 (message mathml)))
18741 ((message "LaTeX to MathML conversion failed")
18742 (message shell-command-output)))
18743 (delete-file tmp-in-file)
18744 (when (file-exists-p tmp-out-file)
18745 (delete-file tmp-out-file))
18746 mathml))
18748 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18749 prefix &optional dir)
18750 "Use `org-create-math-formula' but check local cache first."
18751 (let* ((absprefix (expand-file-name prefix dir))
18752 (print-length nil) (print-level nil)
18753 (formula-id (concat
18754 "formula-"
18755 (sha1
18756 (prin1-to-string
18757 (list latex-frag
18758 org-latex-to-mathml-convert-command)))))
18759 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18760 (formula-cache-dir (file-name-directory formula-cache)))
18762 (unless (file-directory-p formula-cache-dir)
18763 (make-directory formula-cache-dir t))
18765 (unless (file-exists-p formula-cache)
18766 (org-create-math-formula latex-frag formula-cache))
18768 (if (file-exists-p formula-cache)
18769 ;; Successful conversion. Return the link to MathML file.
18770 (org-add-props
18771 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18772 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18773 'org-latex-src-embed-type (if latex-frag-type
18774 'paragraph 'character)))
18775 ;; Failed conversion. Return the LaTeX fragment verbatim
18776 latex-frag)))
18778 (defun org--get-display-dpi ()
18779 "Get the DPI of the display.
18780 The function assumes that the display has the same pixel width in
18781 the horizontal and vertical directions."
18782 (if (display-graphic-p)
18783 (round (/ (display-pixel-height)
18784 (/ (display-mm-height) 25.4)))
18785 (error "Attempt to calculate the dpi of a non-graphic display")))
18787 (defun org-create-formula-image
18788 (string tofile options buffer &optional processing-type)
18789 "Create an image from LaTeX source using external processes.
18791 The LaTeX STRING is saved to a temporary LaTeX file, then
18792 converted to an image file by process PROCESSING-TYPE defined in
18793 `org-preview-latex-process-alist'. A nil value defaults to
18794 `org-preview-latex-default-process'.
18796 The generated image file is eventually moved to TOFILE.
18798 The OPTIONS argument controls the size, foreground color and
18799 background color of the generated image.
18801 When BUFFER non-nil, this function is used for LaTeX previewing.
18802 Otherwise, it is used to deal with LaTeX snippets showed in
18803 a HTML file."
18804 (let* ((processing-type (or processing-type
18805 org-preview-latex-default-process))
18806 (processing-info
18807 (cdr (assq processing-type org-preview-latex-process-alist)))
18808 (programs (plist-get processing-info :programs))
18809 (error-message (or (plist-get processing-info :message) ""))
18810 (use-xcolor (plist-get processing-info :use-xcolor))
18811 (image-input-type (plist-get processing-info :image-input-type))
18812 (image-output-type (plist-get processing-info :image-output-type))
18813 (post-clean (or (plist-get processing-info :post-clean)
18814 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18815 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18816 (latex-header
18817 (or (plist-get processing-info :latex-header)
18818 (org-latex-make-preamble
18819 (org-export-get-environment (org-export-get-backend 'latex))
18820 org-format-latex-header
18821 'snippet)))
18822 (latex-compiler (plist-get processing-info :latex-compiler))
18823 (image-converter (plist-get processing-info :image-converter))
18824 (tmpdir temporary-file-directory)
18825 (texfilebase (make-temp-name
18826 (expand-file-name "orgtex" tmpdir)))
18827 (texfile (concat texfilebase ".tex"))
18828 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18829 '(1.0 . 1.0)))
18830 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18831 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18832 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18833 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18834 "Black"))
18835 (bg (or (plist-get options (if buffer :background :html-background))
18836 "Transparent"))
18837 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18838 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18839 (dolist (program programs)
18840 (org-check-external-command program error-message))
18841 (if use-xcolor
18842 (progn (if (eq fg 'default)
18843 (setq fg (org-latex-color :foreground))
18844 (setq fg (org-latex-color-format fg)))
18845 (if (eq bg 'default)
18846 (setq bg (org-latex-color :background))
18847 (setq bg (org-latex-color-format
18848 (if (string= bg "Transparent") "white" bg))))
18849 (with-temp-file texfile
18850 (insert latex-header)
18851 (insert "\n\\begin{document}\n"
18852 "\\definecolor{fg}{rgb}{" fg "}\n"
18853 "\\definecolor{bg}{rgb}{" bg "}\n"
18854 "\n\\pagecolor{bg}\n"
18855 "\n{\\color{fg}\n"
18856 string
18857 "\n}\n"
18858 "\n\\end{document}\n")))
18859 (if (eq fg 'default)
18860 (setq fg (org-dvipng-color :foreground))
18861 (unless (string= fg "Transparent")
18862 (setq fg (org-dvipng-color-format fg))))
18863 (if (eq bg 'default)
18864 (setq bg (org-dvipng-color :background))
18865 (unless (string= bg "Transparent")
18866 (setq bg (org-dvipng-color-format bg))))
18867 (with-temp-file texfile
18868 (insert latex-header)
18869 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18871 (let* ((err-msg (format "Please adjust `%s' part of \
18872 `org-preview-latex-process-alist'."
18873 processing-type))
18874 (image-input-file
18875 (org-compile-file
18876 texfile latex-compiler image-input-type err-msg log-buf))
18877 (image-output-file
18878 (org-compile-file
18879 image-input-file image-converter image-output-type err-msg log-buf
18880 `((?F . ,(shell-quote-argument fg))
18881 (?B . ,(shell-quote-argument bg))
18882 (?D . ,(shell-quote-argument (format "%s" dpi)))
18883 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18884 (copy-file image-output-file tofile 'replace)
18885 (dolist (e post-clean)
18886 (when (file-exists-p (concat texfilebase e))
18887 (delete-file (concat texfilebase e))))
18888 image-output-file)))
18890 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18891 "Fill a LaTeX header template TPL.
18892 In the template, the following place holders will be recognized:
18894 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18895 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18896 [PACKAGES] \\usepackage statements for PKG
18897 [NO-PACKAGES] do not include PKG
18898 [EXTRA] the string EXTRA
18899 [NO-EXTRA] do not include EXTRA
18901 For backward compatibility, if both the positive and the negative place
18902 holder is missing, the positive one (without the \"NO-\") will be
18903 assumed to be present at the end of the template.
18904 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18905 EXTRA is a string.
18906 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18907 (let (rpl (end ""))
18908 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18909 (setq rpl (if (or (match-end 1) (not def-pkg))
18910 "" (org-latex-packages-to-string def-pkg snippets-p t))
18911 tpl (replace-match rpl t t tpl))
18912 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18914 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18915 (setq rpl (if (or (match-end 1) (not pkg))
18916 "" (org-latex-packages-to-string pkg snippets-p t))
18917 tpl (replace-match rpl t t tpl))
18918 (when pkg (setq end
18919 (concat end "\n"
18920 (org-latex-packages-to-string pkg snippets-p)))))
18922 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18923 (setq rpl (if (or (match-end 1) (not extra))
18924 "" (concat extra "\n"))
18925 tpl (replace-match rpl t t tpl))
18926 (when (and extra (string-match "\\S-" extra))
18927 (setq end (concat end "\n" extra))))
18929 (if (string-match "\\S-" end)
18930 (concat tpl "\n" end)
18931 tpl)))
18933 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18934 "Turn an alist of packages into a string with the \\usepackage macros."
18935 (setq pkg (mapconcat (lambda(p)
18936 (cond
18937 ((stringp p) p)
18938 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18939 (format "%% Package %s omitted" (cadr p)))
18940 ((equal "" (car p))
18941 (format "\\usepackage{%s}" (cadr p)))
18943 (format "\\usepackage[%s]{%s}"
18944 (car p) (cadr p)))))
18946 "\n"))
18947 (if newline (concat pkg "\n") pkg))
18949 (defun org-dvipng-color (attr)
18950 "Return a RGB color specification for dvipng."
18951 (org-dvipng-color-format (face-attribute 'default attr nil)))
18953 (defun org-dvipng-color-format (color-name)
18954 "Convert COLOR-NAME to a RGB color value for dvipng."
18955 (apply #'format "rgb %s %s %s"
18956 (mapcar 'org-normalize-color
18957 (color-values color-name))))
18959 (defun org-latex-color (attr)
18960 "Return a RGB color for the LaTeX color package."
18961 (org-latex-color-format (face-attribute 'default attr nil)))
18963 (defun org-latex-color-format (color-name)
18964 "Convert COLOR-NAME to a RGB color value."
18965 (apply #'format "%s,%s,%s"
18966 (mapcar 'org-normalize-color
18967 (color-values color-name))))
18969 (defun org-normalize-color (value)
18970 "Return string to be used as color value for an RGB component."
18971 (format "%g" (/ value 65535.0)))
18975 ;; Image display
18977 (defvar-local org-inline-image-overlays nil)
18979 (defun org-toggle-inline-images (&optional include-linked)
18980 "Toggle the display of inline images.
18981 INCLUDE-LINKED is passed to `org-display-inline-images'."
18982 (interactive "P")
18983 (if org-inline-image-overlays
18984 (progn
18985 (org-remove-inline-images)
18986 (when (called-interactively-p 'interactive)
18987 (message "Inline image display turned off")))
18988 (org-display-inline-images include-linked)
18989 (when (called-interactively-p 'interactive)
18990 (message (if org-inline-image-overlays
18991 (format "%d images displayed inline"
18992 (length org-inline-image-overlays))
18993 "No images to display inline")))))
18995 (defun org-redisplay-inline-images ()
18996 "Refresh the display of inline images."
18997 (interactive)
18998 (if (not org-inline-image-overlays)
18999 (org-toggle-inline-images)
19000 (org-toggle-inline-images)
19001 (org-toggle-inline-images)))
19003 (defun org-display-inline-images (&optional include-linked refresh beg end)
19004 "Display inline images.
19006 An inline image is a link which follows either of these
19007 conventions:
19009 1. Its path is a file with an extension matching return value
19010 from `image-file-name-regexp' and it has no contents.
19012 2. Its description consists in a single link of the previous
19013 type.
19015 When optional argument INCLUDE-LINKED is non-nil, also links with
19016 a text description part will be inlined. This can be nice for
19017 a quick look at those images, but it does not reflect what
19018 exported files will look like.
19020 When optional argument REFRESH is non-nil, refresh existing
19021 images between BEG and END. This will create new image displays
19022 only if necessary. BEG and END default to the buffer
19023 boundaries."
19024 (interactive "P")
19025 (when (display-graphic-p)
19026 (unless refresh
19027 (org-remove-inline-images)
19028 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19029 (org-with-wide-buffer
19030 (goto-char (or beg (point-min)))
19031 (let* ((case-fold-search t)
19032 (file-extension-re (image-file-name-regexp))
19033 (link-abbrevs (mapcar #'car
19034 (append org-link-abbrev-alist-local
19035 org-link-abbrev-alist)))
19036 ;; Check absolute, relative file names and explicit
19037 ;; "file:" links. Also check link abbreviations since
19038 ;; some might expand to "file" links.
19039 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19040 (if (not link-abbrevs) ""
19041 (format "\\|\\(?:%s:\\)"
19042 (regexp-opt link-abbrevs))))))
19043 (while (re-search-forward file-types-re end t)
19044 (let ((link (save-match-data (org-element-context))))
19045 ;; Check if we're at an inline image, i.e., an image file
19046 ;; link without a description (unless INCLUDE-LINKED is
19047 ;; non-nil).
19048 (when (and (equal "file" (org-element-property :type link))
19049 (or include-linked
19050 (null (org-element-contents link)))
19051 (string-match-p file-extension-re
19052 (org-element-property :path link)))
19053 (let ((file (expand-file-name
19054 (org-link-unescape
19055 (org-element-property :path link)))))
19056 (when (file-exists-p file)
19057 (let ((width
19058 ;; Apply `org-image-actual-width' specifications.
19059 (cond
19060 ((not (image-type-available-p 'imagemagick)) nil)
19061 ((eq org-image-actual-width t) nil)
19062 ((listp org-image-actual-width)
19064 ;; First try to find a width among
19065 ;; attributes associated to the paragraph
19066 ;; containing link.
19067 (let ((paragraph
19068 (let ((e link))
19069 (while (and (setq e (org-element-property
19070 :parent e))
19071 (not (eq (org-element-type e)
19072 'paragraph))))
19073 e)))
19074 (when paragraph
19075 (save-excursion
19076 (goto-char (org-element-property :begin paragraph))
19077 (when
19078 (re-search-forward
19079 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19080 (org-element-property
19081 :post-affiliated paragraph)
19083 (string-to-number (match-string 1))))))
19084 ;; Otherwise, fall-back to provided number.
19085 (car org-image-actual-width)))
19086 ((numberp org-image-actual-width)
19087 org-image-actual-width)))
19088 (old (get-char-property-and-overlay
19089 (org-element-property :begin link)
19090 'org-image-overlay)))
19091 (if (and (car-safe old) refresh)
19092 (image-refresh (overlay-get (cdr old) 'display))
19093 (let ((image (create-image file
19094 (and width 'imagemagick)
19096 :width width)))
19097 (when image
19098 (let ((ov (make-overlay
19099 (org-element-property :begin link)
19100 (progn
19101 (goto-char
19102 (org-element-property :end link))
19103 (skip-chars-backward " \t")
19104 (point)))))
19105 (overlay-put ov 'display image)
19106 (overlay-put ov 'face 'default)
19107 (overlay-put ov 'org-image-overlay t)
19108 (overlay-put
19109 ov 'modification-hooks
19110 (list 'org-display-inline-remove-overlay))
19111 (push ov org-inline-image-overlays)))))))))))))))
19113 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19114 "Remove inline-display overlay if a corresponding region is modified."
19115 (let ((inhibit-modification-hooks t))
19116 (when (and ov after)
19117 (delete ov org-inline-image-overlays)
19118 (delete-overlay ov))))
19120 (defun org-remove-inline-images ()
19121 "Remove inline display of images."
19122 (interactive)
19123 (mapc #'delete-overlay org-inline-image-overlays)
19124 (setq org-inline-image-overlays nil))
19126 ;;;; Key bindings
19128 (defun org-remap (map &rest commands)
19129 "In MAP, remap the functions given in COMMANDS.
19130 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19131 (let (new old)
19132 (while commands
19133 (setq old (pop commands) new (pop commands))
19134 (org-defkey map (vector 'remap old) new))))
19136 ;; Outline functions from `outline-mode-prefix-map'
19137 ;; that can be remapped in Org:
19138 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19139 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19140 (define-key org-mode-map [remap outline-forward-same-level]
19141 'org-forward-heading-same-level)
19142 (define-key org-mode-map [remap outline-backward-same-level]
19143 'org-backward-heading-same-level)
19144 (define-key org-mode-map [remap outline-show-branches]
19145 'org-kill-note-or-show-branches)
19146 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19147 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19148 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19149 (define-key org-mode-map [remap outline-next-visible-heading]
19150 'org-next-visible-heading)
19151 (define-key org-mode-map [remap outline-previous-visible-heading]
19152 'org-previous-visible-heading)
19153 (define-key org-mode-map [remap show-children] 'org-show-children)
19155 ;; Outline functions from `outline-mode-prefix-map' that can not
19156 ;; be remapped in Org:
19158 ;; - the column "key binding" shows whether the Outline function is still
19159 ;; available in Org mode on the same key that it has been bound to in
19160 ;; Outline mode:
19161 ;; - "overridden": key used for a different functionality in Org mode
19162 ;; - else: key still bound to the same Outline function in Org mode
19164 ;; | Outline function | key binding | Org replacement |
19165 ;; |------------------------------------+-------------+--------------------------|
19166 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19167 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19168 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19169 ;; | `show-entry' | overridden | no replacement |
19170 ;; | `show-branches' | `C-c C-k' | still same function |
19171 ;; | `show-subtree' | overridden | visibility cycling |
19172 ;; | `show-all' | overridden | no replacement |
19173 ;; | `hide-subtree' | overridden | visibility cycling |
19174 ;; | `hide-body' | overridden | no replacement |
19175 ;; | `hide-entry' | overridden | visibility cycling |
19176 ;; | `hide-leaves' | overridden | no replacement |
19177 ;; | `hide-sublevels' | overridden | no replacement |
19178 ;; | `hide-other' | overridden | no replacement |
19180 ;; Make `C-c C-x' a prefix key
19181 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19183 ;; TAB key with modifiers
19184 (org-defkey org-mode-map "\C-i" 'org-cycle)
19185 (org-defkey org-mode-map [(tab)] 'org-cycle)
19186 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19187 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19189 ;; The following line is necessary under Suse GNU/Linux
19190 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19191 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19192 (define-key org-mode-map [backtab] 'org-shifttab)
19194 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19195 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19196 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19198 ;; Cursor keys with modifiers
19199 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19200 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19201 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19202 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19204 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19205 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19206 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19207 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19208 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19209 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19211 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19212 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19213 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19214 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19216 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19217 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19218 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19219 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19221 ;; Babel keys
19222 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19223 (dolist (pair org-babel-key-bindings)
19224 (define-key org-babel-map (car pair) (cdr pair)))
19226 ;;; Extra keys for tty access.
19227 ;; We only set them when really needed because otherwise the
19228 ;; menus don't show the simple keys
19230 (when (or org-use-extra-keys (not window-system))
19231 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19232 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19233 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19234 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19235 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19236 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19237 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19238 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19239 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19240 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19241 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19242 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19243 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19244 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19245 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19246 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19247 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19248 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19249 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19250 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19251 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19252 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19253 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19254 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19255 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19256 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19257 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19258 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19260 ;; All the other keys
19261 (org-remap org-mode-map
19262 'self-insert-command 'org-self-insert-command
19263 'delete-char 'org-delete-char
19264 'delete-backward-char 'org-delete-backward-char)
19265 (org-defkey org-mode-map "|" 'org-force-self-insert)
19267 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19268 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19269 (if (boundp 'narrow-map)
19270 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19271 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19272 (if (boundp 'narrow-map)
19273 (org-defkey narrow-map "b" 'org-narrow-to-block)
19274 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19275 (if (boundp 'narrow-map)
19276 (org-defkey narrow-map "e" 'org-narrow-to-element)
19277 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19278 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19279 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19280 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19281 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19282 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19283 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19284 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19285 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19286 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19287 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19288 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19289 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19290 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19291 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19292 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19293 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19294 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19295 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19296 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19297 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19298 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19299 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19300 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19301 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19302 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19303 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19304 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19305 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19306 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19307 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19308 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19309 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19310 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19311 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19312 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19313 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19314 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19315 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19316 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19317 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19318 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19319 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19320 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19321 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19322 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19323 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19324 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19325 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19326 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19327 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19328 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19329 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19330 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19331 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19332 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19333 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19334 (org-defkey org-mode-map "\C-c^" 'org-sort)
19335 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19336 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19337 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19338 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19339 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19340 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19341 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19342 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19343 (org-defkey org-mode-map "\C-m" 'org-return)
19344 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19345 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19346 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19347 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19348 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19349 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19350 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19351 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19352 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19353 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19354 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19355 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19356 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19357 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19358 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19359 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19360 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19361 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19362 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19363 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19364 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19365 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19366 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19367 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19368 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19370 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19371 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19372 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19374 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19375 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19376 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19377 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19378 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19379 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19380 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19381 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19382 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19383 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19384 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19385 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19386 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19387 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19388 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19389 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19390 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19391 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19392 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19393 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19394 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19395 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19396 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19398 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19399 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19400 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19401 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19402 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19404 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19406 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19408 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19409 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19411 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19414 (defconst org-speed-commands-default
19416 ("Outline Navigation")
19417 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19418 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19419 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19420 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19421 ("F" . org-next-block)
19422 ("B" . org-previous-block)
19423 ("u" . (org-speed-move-safe 'outline-up-heading))
19424 ("j" . org-goto)
19425 ("g" . (org-refile t))
19426 ("Outline Visibility")
19427 ("c" . org-cycle)
19428 ("C" . org-shifttab)
19429 (" " . org-display-outline-path)
19430 ("s" . org-narrow-to-subtree)
19431 ("=" . org-columns)
19432 ("Outline Structure Editing")
19433 ("U" . org-metaup)
19434 ("D" . org-metadown)
19435 ("r" . org-metaright)
19436 ("l" . org-metaleft)
19437 ("R" . org-shiftmetaright)
19438 ("L" . org-shiftmetaleft)
19439 ("i" . (progn (forward-char 1) (call-interactively
19440 'org-insert-heading-respect-content)))
19441 ("^" . org-sort)
19442 ("w" . org-refile)
19443 ("a" . org-archive-subtree-default-with-confirmation)
19444 ("@" . org-mark-subtree)
19445 ("#" . org-toggle-comment)
19446 ("Clock Commands")
19447 ("I" . org-clock-in)
19448 ("O" . org-clock-out)
19449 ("Meta Data Editing")
19450 ("t" . org-todo)
19451 ("," . (org-priority))
19452 ("0" . (org-priority ?\ ))
19453 ("1" . (org-priority ?A))
19454 ("2" . (org-priority ?B))
19455 ("3" . (org-priority ?C))
19456 (":" . org-set-tags-command)
19457 ("e" . org-set-effort)
19458 ("E" . org-inc-effort)
19459 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19460 (org-entry-put (point) "APPT_WARNTIME" m)))
19461 ("Agenda Views etc")
19462 ("v" . org-agenda)
19463 ("/" . org-sparse-tree)
19464 ("Misc")
19465 ("o" . org-open-at-point)
19466 ("?" . org-speed-command-help)
19467 ("<" . (org-agenda-set-restriction-lock 'subtree))
19468 (">" . (org-agenda-remove-restriction-lock))
19470 "The default speed commands.")
19472 (defun org-print-speed-command (e)
19473 (if (> (length (car e)) 1)
19474 (progn
19475 (princ "\n")
19476 (princ (car e))
19477 (princ "\n")
19478 (princ (make-string (length (car e)) ?-))
19479 (princ "\n"))
19480 (princ (car e))
19481 (princ " ")
19482 (if (symbolp (cdr e))
19483 (princ (symbol-name (cdr e)))
19484 (prin1 (cdr e)))
19485 (princ "\n")))
19487 (defun org-speed-command-help ()
19488 "Show the available speed commands."
19489 (interactive)
19490 (if (not org-use-speed-commands)
19491 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19492 (with-output-to-temp-buffer "*Help*"
19493 (princ "User-defined Speed commands\n===========================\n")
19494 (mapc #'org-print-speed-command org-speed-commands-user)
19495 (princ "\n")
19496 (princ "Built-in Speed commands\n=======================\n")
19497 (mapc #'org-print-speed-command org-speed-commands-default))
19498 (with-current-buffer "*Help*"
19499 (setq truncate-lines t))))
19501 (defun org-speed-move-safe (cmd)
19502 "Execute CMD, but make sure that the cursor always ends up in a headline.
19503 If not, return to the original position and throw an error."
19504 (interactive)
19505 (let ((pos (point)))
19506 (call-interactively cmd)
19507 (unless (and (bolp) (org-at-heading-p))
19508 (goto-char pos)
19509 (error "Boundary reached while executing %s" cmd))))
19511 (defvar org-self-insert-command-undo-counter 0)
19513 (defvar org-table-auto-blank-field) ; defined in org-table.el
19514 (defvar org-speed-command nil)
19516 (defun org-speed-command-activate (keys)
19517 "Hook for activating single-letter speed commands.
19518 `org-speed-commands-default' specifies a minimal command set.
19519 Use `org-speed-commands-user' for further customization."
19520 (when (or (and (bolp) (looking-at org-outline-regexp))
19521 (and (functionp org-use-speed-commands)
19522 (funcall org-use-speed-commands)))
19523 (cdr (assoc keys (append org-speed-commands-user
19524 org-speed-commands-default)))))
19526 (defun org-babel-speed-command-activate (keys)
19527 "Hook for activating single-letter code block commands."
19528 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19529 (cdr (assoc keys org-babel-key-bindings))))
19531 (defcustom org-speed-command-hook
19532 '(org-speed-command-activate org-babel-speed-command-activate)
19533 "Hook for activating speed commands at strategic locations.
19534 Hook functions are called in sequence until a valid handler is
19535 found.
19537 Each hook takes a single argument, a user-pressed command key
19538 which is also a `self-insert-command' from the global map.
19540 Within the hook, examine the cursor position and the command key
19541 and return nil or a valid handler as appropriate. Handler could
19542 be one of an interactive command, a function, or a form.
19544 Set `org-use-speed-commands' to non-nil value to enable this
19545 hook. The default setting is `org-speed-command-activate'."
19546 :group 'org-structure
19547 :version "24.1"
19548 :type 'hook)
19550 (defun org-self-insert-command (N)
19551 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19552 If the cursor is in a table looking at whitespace, the whitespace is
19553 overwritten, and the table is not marked as requiring realignment."
19554 (interactive "p")
19555 (org-check-before-invisible-edit 'insert)
19556 (cond
19557 ((and org-use-speed-commands
19558 (let ((kv (this-command-keys-vector)))
19559 (setq org-speed-command
19560 (run-hook-with-args-until-success
19561 'org-speed-command-hook
19562 (make-string 1 (aref kv (1- (length kv))))))))
19563 (cond
19564 ((commandp org-speed-command)
19565 (setq this-command org-speed-command)
19566 (call-interactively org-speed-command))
19567 ((functionp org-speed-command)
19568 (funcall org-speed-command))
19569 ((and org-speed-command (listp org-speed-command))
19570 (eval org-speed-command))
19571 (t (let (org-use-speed-commands)
19572 (call-interactively 'org-self-insert-command)))))
19573 ((and
19574 (org-at-table-p)
19575 (eq N 1)
19576 (not (org-region-active-p))
19577 (progn
19578 ;; Check if we blank the field, and if that triggers align.
19579 (and (featurep 'org-table) org-table-auto-blank-field
19580 (memq last-command
19581 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19582 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19583 ;; Got extra space, this field does not determine
19584 ;; column width.
19585 (let (org-table-may-need-update) (org-table-blank-field))
19586 ;; No extra space, this field may determine column
19587 ;; width.
19588 (org-table-blank-field)))
19590 (looking-at "[^|\n]* \\( \\)|"))
19591 ;; There is room for insertion without re-aligning the table.
19592 (delete-region (match-beginning 1) (match-end 1))
19593 (self-insert-command N))
19595 (setq org-table-may-need-update t)
19596 (self-insert-command N)
19597 (org-fix-tags-on-the-fly)
19598 (when org-self-insert-cluster-for-undo
19599 (if (not (eq last-command 'org-self-insert-command))
19600 (setq org-self-insert-command-undo-counter 1)
19601 (if (>= org-self-insert-command-undo-counter 20)
19602 (setq org-self-insert-command-undo-counter 1)
19603 (and (> org-self-insert-command-undo-counter 0)
19604 buffer-undo-list (listp buffer-undo-list)
19605 (not (cadr buffer-undo-list)) ; remove nil entry
19606 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19607 (setq org-self-insert-command-undo-counter
19608 (1+ org-self-insert-command-undo-counter))))))))
19610 (defun org-check-before-invisible-edit (kind)
19611 "Check is editing if kind KIND would be dangerous with invisible text around.
19612 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19613 ;; First, try to get out of here as quickly as possible, to reduce overhead
19614 (when (and org-catch-invisible-edits
19615 (or (not (boundp 'visible-mode)) (not visible-mode))
19616 (or (get-char-property (point) 'invisible)
19617 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19618 ;; OK, we need to take a closer look. Do not consider
19619 ;; invisibility obtained through text properties (e.g., link
19620 ;; fontification), as it cannot be toggled.
19621 (let* ((invisible-at-point
19622 (pcase (get-char-property-and-overlay (point) 'invisible)
19623 (`(,_ . ,(and (pred overlayp) o)) o)))
19624 ;; Assume that point cannot land in the middle of an
19625 ;; overlay, or between two overlays.
19626 (invisible-before-point
19627 (and (not invisible-at-point)
19628 (not (bobp))
19629 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19630 (`(,_ . ,(and (pred overlayp) o)) o))))
19631 (border-and-ok-direction
19633 ;; Check if we are acting predictably before invisible
19634 ;; text.
19635 (and invisible-at-point
19636 (memq kind '(insert delete-backward)))
19637 ;; Check if we are acting predictably after invisible text
19638 ;; This works not well, and I have turned it off. It seems
19639 ;; better to always show and stop after invisible text.
19640 ;; (and (not invisible-at-point) invisible-before-point
19641 ;; (memq kind '(insert delete)))
19643 (when (or invisible-at-point invisible-before-point)
19644 (when (eq org-catch-invisible-edits 'error)
19645 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19646 (if (and org-custom-properties-overlays
19647 (y-or-n-p "Display invisible properties in this buffer? "))
19648 (org-toggle-custom-properties-visibility)
19649 ;; Make the area visible
19650 (save-excursion
19651 (when invisible-before-point
19652 (goto-char
19653 (previous-single-char-property-change (point) 'invisible)))
19654 ;; Remove whatever overlay is currently making yet-to-be
19655 ;; edited text invisible. Also remove nested invisibility
19656 ;; related overlays.
19657 (delete-overlay (or invisible-at-point invisible-before-point))
19658 (let ((origin (if invisible-at-point (point) (1- (point)))))
19659 (while (pcase (get-char-property-and-overlay origin 'invisible)
19660 (`(,_ . ,(and (pred overlayp) o))
19661 (delete-overlay o)
19662 t)))))
19663 (cond
19664 ((eq org-catch-invisible-edits 'show)
19665 ;; That's it, we do the edit after showing
19666 (message
19667 "Unfolding invisible region around point before editing")
19668 (sit-for 1))
19669 ((and (eq org-catch-invisible-edits 'smart)
19670 border-and-ok-direction)
19671 (message "Unfolding invisible region around point before editing"))
19673 ;; Don't do the edit, make the user repeat it in full visibility
19674 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19676 (defun org-fix-tags-on-the-fly ()
19677 "Align tags in headline at point.
19678 Unlike to `org-set-tags', it ignores region and sorting."
19679 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19680 (org-at-heading-p))
19681 (let ((org-ignore-region t)
19682 (org-tags-sort-function nil))
19683 (org-set-tags nil t))))
19685 (defun org-delete-backward-char (N)
19686 "Like `delete-backward-char', insert whitespace at field end in tables.
19687 When deleting backwards, in tables this function will insert whitespace in
19688 front of the next \"|\" separator, to keep the table aligned. The table will
19689 still be marked for re-alignment if the field did fill the entire column,
19690 because, in this case the deletion might narrow the column."
19691 (interactive "p")
19692 (save-match-data
19693 (org-check-before-invisible-edit 'delete-backward)
19694 (if (and (org-at-table-p)
19695 (eq N 1)
19696 (not (org-region-active-p))
19697 (string-match "|" (buffer-substring (point-at-bol) (point)))
19698 (looking-at ".*?|"))
19699 (let ((pos (point))
19700 (noalign (looking-at "[^|\n\r]* |"))
19701 (c org-table-may-need-update))
19702 (backward-delete-char N)
19703 (unless overwrite-mode
19704 (skip-chars-forward "^|")
19705 (insert " ")
19706 (goto-char (1- pos)))
19707 ;; noalign: if there were two spaces at the end, this field
19708 ;; does not determine the width of the column.
19709 (when noalign (setq org-table-may-need-update c)))
19710 (backward-delete-char N)
19711 (org-fix-tags-on-the-fly))))
19713 (defun org-delete-char (N)
19714 "Like `delete-char', but insert whitespace at field end in tables.
19715 When deleting characters, in tables this function will insert whitespace in
19716 front of the next \"|\" separator, to keep the table aligned. The table will
19717 still be marked for re-alignment if the field did fill the entire column,
19718 because, in this case the deletion might narrow the column."
19719 (interactive "p")
19720 (save-match-data
19721 (org-check-before-invisible-edit 'delete)
19722 (if (and (org-at-table-p)
19723 (not (bolp))
19724 (not (= (char-after) ?|))
19725 (eq N 1))
19726 (if (looking-at ".*?|")
19727 (let ((pos (point))
19728 (noalign (looking-at "[^|\n\r]* |"))
19729 (c org-table-may-need-update))
19730 (replace-match
19731 (concat (substring (match-string 0) 1 -1) " |") nil t)
19732 (goto-char pos)
19733 ;; noalign: if there were two spaces at the end, this field
19734 ;; does not determine the width of the column.
19735 (when noalign (setq org-table-may-need-update c)))
19736 (delete-char N))
19737 (delete-char N)
19738 (org-fix-tags-on-the-fly))))
19740 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19741 (put 'org-self-insert-command 'delete-selection
19742 (lambda ()
19743 (not (run-hook-with-args-until-success
19744 'self-insert-uses-region-functions))))
19745 (put 'orgtbl-self-insert-command 'delete-selection
19746 (lambda ()
19747 (not (run-hook-with-args-until-success
19748 'self-insert-uses-region-functions))))
19749 (put 'org-delete-char 'delete-selection 'supersede)
19750 (put 'org-delete-backward-char 'delete-selection 'supersede)
19751 (put 'org-yank 'delete-selection 'yank)
19753 ;; Make `flyspell-mode' delay after some commands
19754 (put 'org-self-insert-command 'flyspell-delayed t)
19755 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19756 (put 'org-delete-char 'flyspell-delayed t)
19757 (put 'org-delete-backward-char 'flyspell-delayed t)
19759 ;; Make pabbrev-mode expand after Org mode commands
19760 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19761 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19763 (defun org-transpose-words ()
19764 "Transpose words for Org.
19765 This uses the `org-mode-transpose-word-syntax-table' syntax
19766 table, which interprets characters in `org-emphasis-alist' as
19767 word constituents."
19768 (interactive)
19769 (with-syntax-table org-mode-transpose-word-syntax-table
19770 (call-interactively 'transpose-words)))
19771 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19773 (defvar org-ctrl-c-ctrl-c-hook nil
19774 "Hook for functions attaching themselves to `C-c C-c'.
19776 This can be used to add additional functionality to the C-c C-c
19777 key which executes context-dependent commands. This hook is run
19778 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19779 run after the last test.
19781 Each function will be called with no arguments. The function
19782 must check if the context is appropriate for it to act. If yes,
19783 it should do its thing and then return a non-nil value. If the
19784 context is wrong, just do nothing and return nil.")
19786 (defvar org-ctrl-c-ctrl-c-final-hook nil
19787 "Hook for functions attaching themselves to `C-c C-c'.
19789 This can be used to add additional functionality to the C-c C-c
19790 key which executes context-dependent commands. This hook is run
19791 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19792 before the first test.
19794 Each function will be called with no arguments. The function
19795 must check if the context is appropriate for it to act. If yes,
19796 it should do its thing and then return a non-nil value. If the
19797 context is wrong, just do nothing and return nil.")
19799 (defvar org-tab-first-hook nil
19800 "Hook for functions to attach themselves to TAB.
19801 See `org-ctrl-c-ctrl-c-hook' for more information.
19802 This hook runs as the first action when TAB is pressed, even before
19803 `org-cycle' messes around with the `outline-regexp' to cater for
19804 inline tasks and plain list item folding.
19805 If any function in this hook returns t, any other actions that
19806 would have been caused by TAB (such as table field motion or visibility
19807 cycling) will not occur.")
19809 (defvar org-tab-after-check-for-table-hook nil
19810 "Hook for functions to attach themselves to TAB.
19811 See `org-ctrl-c-ctrl-c-hook' for more information.
19812 This hook runs after it has been established that the cursor is not in a
19813 table, but before checking if the cursor is in a headline or if global cycling
19814 should be done.
19815 If any function in this hook returns t, not other actions like visibility
19816 cycling will be done.")
19818 (defvar org-tab-after-check-for-cycling-hook nil
19819 "Hook for functions to attach themselves to TAB.
19820 See `org-ctrl-c-ctrl-c-hook' for more information.
19821 This hook runs after it has been established that not table field motion and
19822 not visibility should be done because of current context. This is probably
19823 the place where a package like yasnippets can hook in.")
19825 (defvar org-tab-before-tab-emulation-hook nil
19826 "Hook for functions to attach themselves to TAB.
19827 See `org-ctrl-c-ctrl-c-hook' for more information.
19828 This hook runs after every other options for TAB have been exhausted, but
19829 before indentation and \t insertion takes place.")
19831 (defvar org-metaleft-hook nil
19832 "Hook for functions attaching themselves to `M-left'.
19833 See `org-ctrl-c-ctrl-c-hook' for more information.")
19834 (defvar org-metaright-hook nil
19835 "Hook for functions attaching themselves to `M-right'.
19836 See `org-ctrl-c-ctrl-c-hook' for more information.")
19837 (defvar org-metaup-hook nil
19838 "Hook for functions attaching themselves to `M-up'.
19839 See `org-ctrl-c-ctrl-c-hook' for more information.")
19840 (defvar org-metadown-hook nil
19841 "Hook for functions attaching themselves to `M-down'.
19842 See `org-ctrl-c-ctrl-c-hook' for more information.")
19843 (defvar org-shiftmetaleft-hook nil
19844 "Hook for functions attaching themselves to `M-S-left'.
19845 See `org-ctrl-c-ctrl-c-hook' for more information.")
19846 (defvar org-shiftmetaright-hook nil
19847 "Hook for functions attaching themselves to `M-S-right'.
19848 See `org-ctrl-c-ctrl-c-hook' for more information.")
19849 (defvar org-shiftmetaup-hook nil
19850 "Hook for functions attaching themselves to `M-S-up'.
19851 See `org-ctrl-c-ctrl-c-hook' for more information.")
19852 (defvar org-shiftmetadown-hook nil
19853 "Hook for functions attaching themselves to `M-S-down'.
19854 See `org-ctrl-c-ctrl-c-hook' for more information.")
19855 (defvar org-metareturn-hook nil
19856 "Hook for functions attaching themselves to `M-RET'.
19857 See `org-ctrl-c-ctrl-c-hook' for more information.")
19858 (defvar org-shiftup-hook nil
19859 "Hook for functions attaching themselves to `S-up'.
19860 See `org-ctrl-c-ctrl-c-hook' for more information.")
19861 (defvar org-shiftup-final-hook nil
19862 "Hook for functions attaching themselves to `S-up'.
19863 This one runs after all other options except shift-select have been excluded.
19864 See `org-ctrl-c-ctrl-c-hook' for more information.")
19865 (defvar org-shiftdown-hook nil
19866 "Hook for functions attaching themselves to `S-down'.
19867 See `org-ctrl-c-ctrl-c-hook' for more information.")
19868 (defvar org-shiftdown-final-hook nil
19869 "Hook for functions attaching themselves to `S-down'.
19870 This one runs after all other options except shift-select have been excluded.
19871 See `org-ctrl-c-ctrl-c-hook' for more information.")
19872 (defvar org-shiftleft-hook nil
19873 "Hook for functions attaching themselves to `S-left'.
19874 See `org-ctrl-c-ctrl-c-hook' for more information.")
19875 (defvar org-shiftleft-final-hook nil
19876 "Hook for functions attaching themselves to `S-left'.
19877 This one runs after all other options except shift-select have been excluded.
19878 See `org-ctrl-c-ctrl-c-hook' for more information.")
19879 (defvar org-shiftright-hook nil
19880 "Hook for functions attaching themselves to `S-right'.
19881 See `org-ctrl-c-ctrl-c-hook' for more information.")
19882 (defvar org-shiftright-final-hook nil
19883 "Hook for functions attaching themselves to `S-right'.
19884 This one runs after all other options except shift-select have been excluded.
19885 See `org-ctrl-c-ctrl-c-hook' for more information.")
19887 (defun org-modifier-cursor-error ()
19888 "Throw an error, a modified cursor command was applied in wrong context."
19889 (user-error "This command is active in special context like tables, headlines or items"))
19891 (defun org-shiftselect-error ()
19892 "Throw an error because Shift-Cursor command was applied in wrong context."
19893 (if (and (boundp 'shift-select-mode) shift-select-mode)
19894 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19895 (user-error "This command works only in special context like headlines or timestamps")))
19897 (defun org-call-for-shift-select (cmd)
19898 (let ((this-command-keys-shift-translated t))
19899 (call-interactively cmd)))
19901 (defun org-shifttab (&optional arg)
19902 "Global visibility cycling or move to previous table field.
19903 Call `org-table-previous-field' within a table.
19904 When ARG is nil, cycle globally through visibility states.
19905 When ARG is a numeric prefix, show contents of this level."
19906 (interactive "P")
19907 (cond
19908 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19909 ((integerp arg)
19910 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19911 (message "Content view to level: %d" arg)
19912 (org-content (prefix-numeric-value arg2))
19913 (org-cycle-show-empty-lines t)
19914 (setq org-cycle-global-status 'overview)))
19915 (t (call-interactively 'org-global-cycle))))
19917 (defun org-shiftmetaleft ()
19918 "Promote subtree or delete table column.
19919 Calls `org-promote-subtree', `org-outdent-item-tree', or
19920 `org-table-delete-column', depending on context. See the
19921 individual commands for more information."
19922 (interactive)
19923 (cond
19924 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19925 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19926 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19927 ((if (not (org-region-active-p)) (org-at-item-p)
19928 (save-excursion (goto-char (region-beginning))
19929 (org-at-item-p)))
19930 (call-interactively 'org-outdent-item-tree))
19931 (t (org-modifier-cursor-error))))
19933 (defun org-shiftmetaright ()
19934 "Demote subtree or insert table column.
19935 Calls `org-demote-subtree', `org-indent-item-tree', or
19936 `org-table-insert-column', depending on context. See the
19937 individual commands for more information."
19938 (interactive)
19939 (cond
19940 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19941 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19942 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19943 ((if (not (org-region-active-p)) (org-at-item-p)
19944 (save-excursion (goto-char (region-beginning))
19945 (org-at-item-p)))
19946 (call-interactively 'org-indent-item-tree))
19947 (t (org-modifier-cursor-error))))
19949 (defun org-shiftmetaup (&optional _arg)
19950 "Drag the line at point up.
19951 In a table, kill the current row.
19952 On a clock timestamp, update the value of the timestamp like `S-<up>'
19953 but also adjust the previous clocked item in the clock history.
19954 Everywhere else, drag the line at point up."
19955 (interactive "P")
19956 (cond
19957 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19958 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19959 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19960 (call-interactively 'org-timestamp-up)))
19961 (t (call-interactively 'org-drag-line-backward))))
19963 (defun org-shiftmetadown (&optional _arg)
19964 "Drag the line at point down.
19965 In a table, insert an empty row at the current line.
19966 On a clock timestamp, update the value of the timestamp like `S-<down>'
19967 but also adjust the previous clocked item in the clock history.
19968 Everywhere else, drag the line at point down."
19969 (interactive "P")
19970 (cond
19971 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19972 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19973 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19974 (call-interactively 'org-timestamp-down)))
19975 (t (call-interactively 'org-drag-line-forward))))
19977 (defsubst org-hidden-tree-error ()
19978 (user-error
19979 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19981 (defun org-metaleft (&optional _arg)
19982 "Promote heading, list item at point or move table column left.
19984 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19985 depending on context. With no specific context, calls the Emacs
19986 default `backward-word'. See the individual commands for more
19987 information.
19989 This function runs the hook `org-metaleft-hook' as a first step,
19990 and returns at first non-nil value."
19991 (interactive "P")
19992 (cond
19993 ((run-hook-with-args-until-success 'org-metaleft-hook))
19994 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19995 ((org-with-limited-levels
19996 (or (org-at-heading-p)
19997 (and (org-region-active-p)
19998 (save-excursion
19999 (goto-char (region-beginning))
20000 (org-at-heading-p)))))
20001 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20002 (call-interactively 'org-do-promote))
20003 ;; At an inline task.
20004 ((org-at-heading-p)
20005 (call-interactively 'org-inlinetask-promote))
20006 ((or (org-at-item-p)
20007 (and (org-region-active-p)
20008 (save-excursion
20009 (goto-char (region-beginning))
20010 (org-at-item-p))))
20011 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20012 (call-interactively 'org-outdent-item))
20013 (t (call-interactively 'backward-word))))
20015 (defun org-metaright (&optional _arg)
20016 "Demote heading, list item at point or move table column right.
20018 In front of a drawer or a block keyword, indent it correctly.
20020 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20021 `org-indent-drawer' or `org-indent-block' depending on context.
20022 With no specific context, calls the Emacs default `forward-word'.
20023 See the individual commands for more information.
20025 This function runs the hook `org-metaright-hook' as a first step,
20026 and returns at first non-nil value."
20027 (interactive "P")
20028 (cond
20029 ((run-hook-with-args-until-success 'org-metaright-hook))
20030 ((org-at-table-p) (call-interactively 'org-table-move-column))
20031 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20032 ((org-at-block-p) (call-interactively 'org-indent-block))
20033 ((org-with-limited-levels
20034 (or (org-at-heading-p)
20035 (and (org-region-active-p)
20036 (save-excursion
20037 (goto-char (region-beginning))
20038 (org-at-heading-p)))))
20039 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20040 (call-interactively 'org-do-demote))
20041 ;; At an inline task.
20042 ((org-at-heading-p)
20043 (call-interactively 'org-inlinetask-demote))
20044 ((or (org-at-item-p)
20045 (and (org-region-active-p)
20046 (save-excursion
20047 (goto-char (region-beginning))
20048 (org-at-item-p))))
20049 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20050 (call-interactively 'org-indent-item))
20051 (t (call-interactively 'forward-word))))
20053 (defun org-check-for-hidden (what)
20054 "Check if there are hidden headlines/items in the current visual line.
20055 WHAT can be either `headlines' or `items'. If the current line is
20056 an outline or item heading and it has a folded subtree below it,
20057 this function returns t, nil otherwise."
20058 (let ((re (cond
20059 ((eq what 'headlines) org-outline-regexp-bol)
20060 ((eq what 'items) (org-item-beginning-re))
20061 (t (error "This should not happen"))))
20062 beg end)
20063 (save-excursion
20064 (catch 'exit
20065 (unless (org-region-active-p)
20066 (setq beg (point-at-bol))
20067 (beginning-of-line 2)
20068 (while (and (not (eobp)) ;; this is like `next-line'
20069 (get-char-property (1- (point)) 'invisible))
20070 (beginning-of-line 2))
20071 (setq end (point))
20072 (goto-char beg)
20073 (goto-char (point-at-eol))
20074 (setq end (max end (point)))
20075 (while (re-search-forward re end t)
20076 (when (get-char-property (match-beginning 0) 'invisible)
20077 (throw 'exit t))))
20078 nil))))
20080 (defun org-metaup (&optional _arg)
20081 "Move subtree up or move table row up.
20082 Calls `org-move-subtree-up' or `org-table-move-row' or
20083 `org-move-item-up', depending on context. See the individual commands
20084 for more information."
20085 (interactive "P")
20086 (cond
20087 ((run-hook-with-args-until-success 'org-metaup-hook))
20088 ((org-region-active-p)
20089 (let* ((a (min (region-beginning) (region-end)))
20090 (b (1- (max (region-beginning) (region-end))))
20091 (c (save-excursion (goto-char a)
20092 (move-beginning-of-line 0)))
20093 (d (save-excursion (goto-char a)
20094 (move-end-of-line 0) (point))))
20095 (transpose-regions a b c d)
20096 (goto-char c)))
20097 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20098 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20099 ((org-at-item-p) (call-interactively 'org-move-item-up))
20100 (t (org-drag-element-backward))))
20102 (defun org-metadown (&optional _arg)
20103 "Move subtree down or move table row down.
20104 Calls `org-move-subtree-down' or `org-table-move-row' or
20105 `org-move-item-down', depending on context. See the individual
20106 commands for more information."
20107 (interactive "P")
20108 (cond
20109 ((run-hook-with-args-until-success 'org-metadown-hook))
20110 ((org-region-active-p)
20111 (let* ((a (min (region-beginning) (region-end)))
20112 (b (max (region-beginning) (region-end)))
20113 (c (save-excursion (goto-char b)
20114 (move-beginning-of-line 1)))
20115 (d (save-excursion (goto-char b)
20116 (move-end-of-line 1) (1+ (point)))))
20117 (transpose-regions a b c d)
20118 (goto-char d)))
20119 ((org-at-table-p) (call-interactively 'org-table-move-row))
20120 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20121 ((org-at-item-p) (call-interactively 'org-move-item-down))
20122 (t (org-drag-element-forward))))
20124 (defun org-shiftup (&optional arg)
20125 "Increase item in timestamp or increase priority of current headline.
20126 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20127 depending on context. See the individual commands for more information."
20128 (interactive "P")
20129 (cond
20130 ((run-hook-with-args-until-success 'org-shiftup-hook))
20131 ((and org-support-shift-select (org-region-active-p))
20132 (org-call-for-shift-select 'previous-line))
20133 ((org-at-timestamp-p 'lax)
20134 (call-interactively (if org-edit-timestamp-down-means-later
20135 'org-timestamp-down 'org-timestamp-up)))
20136 ((and (not (eq org-support-shift-select 'always))
20137 org-enable-priority-commands
20138 (org-at-heading-p))
20139 (call-interactively 'org-priority-up))
20140 ((and (not org-support-shift-select) (org-at-item-p))
20141 (call-interactively 'org-previous-item))
20142 ((org-clocktable-try-shift 'up arg))
20143 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20144 (org-support-shift-select
20145 (org-call-for-shift-select 'previous-line))
20146 (t (org-shiftselect-error))))
20148 (defun org-shiftdown (&optional arg)
20149 "Decrease item in timestamp or decrease priority of current headline.
20150 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20151 depending on context. See the individual commands for more information."
20152 (interactive "P")
20153 (cond
20154 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20155 ((and org-support-shift-select (org-region-active-p))
20156 (org-call-for-shift-select 'next-line))
20157 ((org-at-timestamp-p 'lax)
20158 (call-interactively (if org-edit-timestamp-down-means-later
20159 'org-timestamp-up 'org-timestamp-down)))
20160 ((and (not (eq org-support-shift-select 'always))
20161 org-enable-priority-commands
20162 (org-at-heading-p))
20163 (call-interactively 'org-priority-down))
20164 ((and (not org-support-shift-select) (org-at-item-p))
20165 (call-interactively 'org-next-item))
20166 ((org-clocktable-try-shift 'down arg))
20167 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20168 (org-support-shift-select
20169 (org-call-for-shift-select 'next-line))
20170 (t (org-shiftselect-error))))
20172 (defun org-shiftright (&optional arg)
20173 "Cycle the thing at point or in the current line, depending on context.
20174 Depending on context, this does one of the following:
20176 - switch a timestamp at point one day into the future
20177 - on a headline, switch to the next TODO keyword.
20178 - on an item, switch entire list to the next bullet type
20179 - on a property line, switch to the next allowed value
20180 - on a clocktable definition line, move time block into the future"
20181 (interactive "P")
20182 (cond
20183 ((run-hook-with-args-until-success 'org-shiftright-hook))
20184 ((and org-support-shift-select (org-region-active-p))
20185 (org-call-for-shift-select 'forward-char))
20186 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20187 ((and (not (eq org-support-shift-select 'always))
20188 (org-at-heading-p))
20189 (let ((org-inhibit-logging
20190 (not org-treat-S-cursor-todo-selection-as-state-change))
20191 (org-inhibit-blocking
20192 (not org-treat-S-cursor-todo-selection-as-state-change)))
20193 (org-call-with-arg 'org-todo 'right)))
20194 ((or (and org-support-shift-select
20195 (not (eq org-support-shift-select 'always))
20196 (org-at-item-bullet-p))
20197 (and (not org-support-shift-select) (org-at-item-p)))
20198 (org-call-with-arg 'org-cycle-list-bullet nil))
20199 ((and (not (eq org-support-shift-select 'always))
20200 (org-at-property-p))
20201 (call-interactively 'org-property-next-allowed-value))
20202 ((org-clocktable-try-shift 'right arg))
20203 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20204 (org-support-shift-select
20205 (org-call-for-shift-select 'forward-char))
20206 (t (org-shiftselect-error))))
20208 (defun org-shiftleft (&optional arg)
20209 "Cycle the thing at point or in the current line, depending on context.
20210 Depending on context, this does one of the following:
20212 - switch a timestamp at point one day into the past
20213 - on a headline, switch to the previous TODO keyword.
20214 - on an item, switch entire list to the previous bullet type
20215 - on a property line, switch to the previous allowed value
20216 - on a clocktable definition line, move time block into the past"
20217 (interactive "P")
20218 (cond
20219 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20220 ((and org-support-shift-select (org-region-active-p))
20221 (org-call-for-shift-select 'backward-char))
20222 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20223 ((and (not (eq org-support-shift-select 'always))
20224 (org-at-heading-p))
20225 (let ((org-inhibit-logging
20226 (not org-treat-S-cursor-todo-selection-as-state-change))
20227 (org-inhibit-blocking
20228 (not org-treat-S-cursor-todo-selection-as-state-change)))
20229 (org-call-with-arg 'org-todo 'left)))
20230 ((or (and org-support-shift-select
20231 (not (eq org-support-shift-select 'always))
20232 (org-at-item-bullet-p))
20233 (and (not org-support-shift-select) (org-at-item-p)))
20234 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20235 ((and (not (eq org-support-shift-select 'always))
20236 (org-at-property-p))
20237 (call-interactively 'org-property-previous-allowed-value))
20238 ((org-clocktable-try-shift 'left arg))
20239 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20240 (org-support-shift-select
20241 (org-call-for-shift-select 'backward-char))
20242 (t (org-shiftselect-error))))
20244 (defun org-shiftcontrolright ()
20245 "Switch to next TODO set."
20246 (interactive)
20247 (cond
20248 ((and org-support-shift-select (org-region-active-p))
20249 (org-call-for-shift-select 'forward-word))
20250 ((and (not (eq org-support-shift-select 'always))
20251 (org-at-heading-p))
20252 (org-call-with-arg 'org-todo 'nextset))
20253 (org-support-shift-select
20254 (org-call-for-shift-select 'forward-word))
20255 (t (org-shiftselect-error))))
20257 (defun org-shiftcontrolleft ()
20258 "Switch to previous TODO set."
20259 (interactive)
20260 (cond
20261 ((and org-support-shift-select (org-region-active-p))
20262 (org-call-for-shift-select 'backward-word))
20263 ((and (not (eq org-support-shift-select 'always))
20264 (org-at-heading-p))
20265 (org-call-with-arg 'org-todo 'previousset))
20266 (org-support-shift-select
20267 (org-call-for-shift-select 'backward-word))
20268 (t (org-shiftselect-error))))
20270 (defun org-shiftcontrolup (&optional n)
20271 "Change timestamps synchronously up in CLOCK log lines.
20272 Optional argument N tells to change by that many units."
20273 (interactive "P")
20274 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20275 (let (org-support-shift-select)
20276 (org-clock-timestamps-up n))
20277 (user-error "Not at a clock log")))
20279 (defun org-shiftcontroldown (&optional n)
20280 "Change timestamps synchronously down in CLOCK log lines.
20281 Optional argument N tells to change by that many units."
20282 (interactive "P")
20283 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20284 (let (org-support-shift-select)
20285 (org-clock-timestamps-down n))
20286 (user-error "Not at a clock log")))
20288 (defun org-increase-number-at-point (&optional inc)
20289 "Increment the number at point.
20290 With an optional prefix numeric argument INC, increment using
20291 this numeric value."
20292 (interactive "p")
20293 (if (not (number-at-point))
20294 (user-error "Not on a number")
20295 (unless inc (setq inc 1))
20296 (let ((pos (point))
20297 (beg (skip-chars-backward "-+^/*0-9eE."))
20298 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20299 (setq nap (buffer-substring-no-properties
20300 (+ pos beg) (+ pos beg end)))
20301 (delete-region (+ pos beg) (+ pos beg end))
20302 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20303 (when (org-at-table-p)
20304 (org-table-align)
20305 (org-table-end-of-field 1))))
20307 (defun org-decrease-number-at-point (&optional inc)
20308 "Decrement the number at point.
20309 With an optional prefix numeric argument INC, decrement using
20310 this numeric value."
20311 (interactive "p")
20312 (org-increase-number-at-point (- (or inc 1))))
20314 (defun org-ctrl-c-ret ()
20315 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20316 (interactive)
20317 (cond
20318 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20319 (t (call-interactively 'org-insert-heading))))
20321 (defun org-find-visible ()
20322 (let ((s (point)))
20323 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20324 (get-char-property s 'invisible)))
20326 (defun org-find-invisible ()
20327 (let ((s (point)))
20328 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20329 (not (get-char-property s 'invisible))))
20332 (defun org-copy-visible (beg end)
20333 "Copy the visible parts of the region."
20334 (interactive "r")
20335 (let ((result ""))
20336 (while (/= beg end)
20337 (when (get-char-property beg 'invisible)
20338 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20339 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20340 (setq result (concat result (buffer-substring beg next)))
20341 (setq beg next)))
20342 (kill-new result)))
20344 (defun org-copy-special ()
20345 "Copy region in table or copy current subtree.
20346 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20347 context. See the individual commands for more information."
20348 (interactive)
20349 (call-interactively
20350 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20352 (defun org-cut-special ()
20353 "Cut region in table or cut current subtree.
20354 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20355 context. See the individual commands for more information."
20356 (interactive)
20357 (call-interactively
20358 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20360 (defun org-paste-special (arg)
20361 "Paste rectangular region into table, or past subtree relative to level.
20362 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20363 See the individual commands for more information."
20364 (interactive "P")
20365 (if (org-at-table-p)
20366 (org-table-paste-rectangle)
20367 (org-paste-subtree arg)))
20369 (defun org-edit-special (&optional arg)
20370 "Call a special editor for the element at point.
20371 When at a table, call the formula editor with `org-table-edit-formulas'.
20372 When in a source code block, call `org-edit-src-code'.
20373 When in a fixed-width region, call `org-edit-fixed-width-region'.
20374 When in an export block, call `org-edit-export-block'.
20375 When in a LaTeX environment, call `org-edit-latex-environment'.
20376 When at an #+INCLUDE keyword, visit the included file.
20377 When at a footnote reference, call `org-edit-footnote-reference'
20378 On a link, call `ffap' to visit the link at point.
20379 Otherwise, return a user error."
20380 (interactive "P")
20381 (let ((element (org-element-at-point)))
20382 (barf-if-buffer-read-only)
20383 (pcase (org-element-type element)
20384 (`src-block
20385 (if (not arg) (org-edit-src-code)
20386 (let* ((info (org-babel-get-src-block-info))
20387 (lang (nth 0 info))
20388 (params (nth 2 info))
20389 (session (cdr (assq :session params))))
20390 (if (not session) (org-edit-src-code)
20391 ;; At a src-block with a session and function called with
20392 ;; an ARG: switch to the buffer related to the inferior
20393 ;; process.
20394 (switch-to-buffer
20395 (funcall (intern (concat "org-babel-prep-session:" lang))
20396 session params))))))
20397 (`keyword
20398 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20399 (org-open-link-from-string
20400 (format "[[%s]]"
20401 (expand-file-name
20402 (let ((value (org-element-property :value element)))
20403 (cond ((org-file-url-p value)
20404 (user-error "The file is specified as a URL, cannot be edited"))
20405 ((not (org-string-nw-p value))
20406 (user-error "No file to edit"))
20407 ((string-match "\\`\"\\(.*?\\)\"" value)
20408 (match-string 1 value))
20409 ((string-match "\\`[^ \t\"]\\S-*" value)
20410 (match-string 0 value))
20411 (t (user-error "No valid file specified")))))))
20412 (user-error "No special environment to edit here")))
20413 (`table
20414 (if (eq (org-element-property :type element) 'table.el)
20415 (org-edit-table.el)
20416 (call-interactively 'org-table-edit-formulas)))
20417 ;; Only Org tables contain `table-row' type elements.
20418 (`table-row (call-interactively 'org-table-edit-formulas))
20419 (`example-block (org-edit-src-code))
20420 (`export-block (org-edit-export-block))
20421 (`fixed-width (org-edit-fixed-width-region))
20422 (`latex-environment (org-edit-latex-environment))
20424 ;; No notable element at point. Though, we may be at a link or
20425 ;; a footnote reference, which are objects. Thus, scan deeper.
20426 (let ((context (org-element-context element)))
20427 (pcase (org-element-type context)
20428 (`footnote-reference (org-edit-footnote-reference))
20429 (`inline-src-block (org-edit-inline-src-code))
20430 (`link (call-interactively #'ffap))
20431 (_ (user-error "No special environment to edit here"))))))))
20433 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20434 (defun org-ctrl-c-ctrl-c (&optional arg)
20435 "Set tags in headline, or update according to changed information at point.
20437 This command does many different things, depending on context:
20439 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20440 this is what we do.
20442 - If the cursor is on a statistics cookie, update it.
20444 - If the cursor is in a headline, prompt for tags and insert them
20445 into the current line, aligned to `org-tags-column'. When called
20446 with prefix arg, realign all tags in the current buffer.
20448 - If the cursor is in one of the special #+KEYWORD lines, this
20449 triggers scanning the buffer for these lines and updating the
20450 information.
20452 - If the cursor is inside a table, realign the table. This command
20453 works even if the automatic table editor has been turned off.
20455 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20456 the entire table.
20458 - If the cursor is at a footnote reference or definition, jump to
20459 the corresponding definition or references, respectively.
20461 - If the cursor is a the beginning of a dynamic block, update it.
20463 - If the current buffer is a capture buffer, close note and file it.
20465 - If the cursor is on a <<<target>>>, update radio targets and
20466 corresponding links in this buffer.
20468 - If the cursor is on a numbered item in a plain list, renumber the
20469 ordered list.
20471 - If the cursor is on a checkbox, toggle it.
20473 - If the cursor is on a code block, evaluate it. The variable
20474 `org-confirm-babel-evaluate' can be used to control prompting
20475 before code block evaluation, by default every code block
20476 evaluation requires confirmation. Code block evaluation can be
20477 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20478 (interactive "P")
20479 (cond
20480 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20481 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20482 (org-remove-occur-highlights)
20483 (message "Temporary highlights/overlays removed from current buffer"))
20484 ((and (local-variable-p 'org-finish-function)
20485 (fboundp org-finish-function))
20486 (funcall org-finish-function))
20487 ((org-babel-hash-at-point))
20488 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20490 (let* ((context
20491 (org-element-lineage
20492 (org-element-context)
20493 ;; Limit to supported contexts.
20494 '(babel-call clock dynamic-block footnote-definition
20495 footnote-reference inline-babel-call inline-src-block
20496 inlinetask item keyword node-property paragraph
20497 plain-list planning property-drawer radio-target
20498 src-block statistics-cookie table table-cell table-row
20499 timestamp)
20501 (type (org-element-type context)))
20502 ;; For convenience: at the first line of a paragraph on the same
20503 ;; line as an item, apply function on that item instead.
20504 (when (eq type 'paragraph)
20505 (let ((parent (org-element-property :parent context)))
20506 (when (and (eq (org-element-type parent) 'item)
20507 (= (line-beginning-position)
20508 (org-element-property :begin parent)))
20509 (setq context parent)
20510 (setq type 'item))))
20511 ;; Act according to type of element or object at point.
20513 ;; Do nothing on a blank line, except if it is contained in
20514 ;; a src block. Hence, we first check if point is in such
20515 ;; a block and then if it is at a blank line.
20516 (pcase type
20517 ((or `inline-src-block `src-block)
20518 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20519 (org-babel-eval-wipe-error-buffer)
20520 (org-babel-execute-src-block
20521 current-prefix-arg (org-babel-get-src-block-info nil context))))
20522 ((guard (org-match-line "[ \t]*$"))
20523 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20524 (user-error
20525 (substitute-command-keys
20526 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20527 ((or `babel-call `inline-babel-call)
20528 (let ((info (org-babel-lob-get-info context)))
20529 (when info (org-babel-execute-src-block nil info))))
20530 (`clock (org-clock-update-time-maybe))
20531 (`dynamic-block
20532 (save-excursion
20533 (goto-char (org-element-property :post-affiliated context))
20534 (org-update-dblock)))
20535 (`footnote-definition
20536 (goto-char (org-element-property :post-affiliated context))
20537 (call-interactively 'org-footnote-action))
20538 (`footnote-reference (call-interactively #'org-footnote-action))
20539 ((or `headline `inlinetask)
20540 (save-excursion (goto-char (org-element-property :begin context))
20541 (call-interactively #'org-set-tags)))
20542 (`item
20543 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20544 ;; unconditionally, whereas `C-u' will toggle its presence.
20545 ;; Without a universal argument, if the item has a checkbox,
20546 ;; toggle it. Otherwise repair the list.
20547 (let* ((box (org-element-property :checkbox context))
20548 (struct (org-element-property :structure context))
20549 (old-struct (copy-tree struct))
20550 (parents (org-list-parents-alist struct))
20551 (prevs (org-list-prevs-alist struct))
20552 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20553 (org-list-set-checkbox
20554 (org-element-property :begin context) struct
20555 (cond ((equal arg '(16)) "[-]")
20556 ((and (not box) (equal arg '(4))) "[ ]")
20557 ((or (not box) (equal arg '(4))) nil)
20558 ((eq box 'on) "[ ]")
20559 (t "[X]")))
20560 ;; Mimic `org-list-write-struct' but with grabbing a return
20561 ;; value from `org-list-struct-fix-box'.
20562 (org-list-struct-fix-ind struct parents 2)
20563 (org-list-struct-fix-item-end struct)
20564 (org-list-struct-fix-bul struct prevs)
20565 (org-list-struct-fix-ind struct parents)
20566 (let ((block-item
20567 (org-list-struct-fix-box struct parents prevs orderedp)))
20568 (if (and box (equal struct old-struct))
20569 (if (equal arg '(16))
20570 (message "Checkboxes already reset")
20571 (user-error "Cannot toggle this checkbox: %s"
20572 (if (eq box 'on)
20573 "all subitems checked"
20574 "unchecked subitems")))
20575 (org-list-struct-apply-struct struct old-struct)
20576 (org-update-checkbox-count-maybe))
20577 (when block-item
20578 (message "Checkboxes were removed due to empty box at line %d"
20579 (org-current-line block-item))))))
20580 (`keyword
20581 (let ((org-inhibit-startup-visibility-stuff t)
20582 (org-startup-align-all-tables nil))
20583 (when (boundp 'org-table-coordinate-overlays)
20584 (mapc #'delete-overlay org-table-coordinate-overlays)
20585 (setq org-table-coordinate-overlays nil))
20586 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20587 (message "Local setup has been refreshed"))
20588 (`plain-list
20589 ;; At a plain list, with a double C-u argument, set
20590 ;; checkboxes of each item to "[-]", whereas a single one
20591 ;; will toggle their presence according to the state of the
20592 ;; first item in the list. Without an argument, repair the
20593 ;; list.
20594 (let* ((begin (org-element-property :contents-begin context))
20595 (beginm (move-marker (make-marker) begin))
20596 (struct (org-element-property :structure context))
20597 (old-struct (copy-tree struct))
20598 (first-box (save-excursion
20599 (goto-char begin)
20600 (looking-at org-list-full-item-re)
20601 (match-string-no-properties 3)))
20602 (new-box (cond ((equal arg '(16)) "[-]")
20603 ((equal arg '(4)) (unless first-box "[ ]"))
20604 ((equal first-box "[X]") "[ ]")
20605 (t "[X]"))))
20606 (cond
20607 (arg
20608 (dolist (pos
20609 (org-list-get-all-items
20610 begin struct (org-list-prevs-alist struct)))
20611 (org-list-set-checkbox pos struct new-box)))
20612 ((and first-box (eq (point) begin))
20613 ;; For convenience, when point is at bol on the first
20614 ;; item of the list and no argument is provided, simply
20615 ;; toggle checkbox of that item, if any.
20616 (org-list-set-checkbox begin struct new-box)))
20617 (org-list-write-struct
20618 struct (org-list-parents-alist struct) old-struct)
20619 (org-update-checkbox-count-maybe)
20620 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20621 ((or `property-drawer `node-property)
20622 (call-interactively #'org-property-action))
20623 (`radio-target
20624 (call-interactively #'org-update-radio-target-regexp))
20625 (`statistics-cookie
20626 (call-interactively #'org-update-statistics-cookies))
20627 ((or `table `table-cell `table-row)
20628 ;; At a table, recalculate every field and align it. Also
20629 ;; send the table if necessary. If the table has
20630 ;; a `table.el' type, just give up. At a table row or cell,
20631 ;; maybe recalculate line but always align table.
20632 (if (eq (org-element-property :type context) 'table.el)
20633 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20634 Use `\\[org-edit-special]' to edit table.el tables"))
20635 (if (or (eq type 'table)
20636 ;; Check if point is at a TBLFM line.
20637 (and (eq type 'table-row)
20638 (= (point) (org-element-property :end context))))
20639 (save-excursion
20640 (if (org-at-TBLFM-p)
20641 (progn (require 'org-table)
20642 (org-table-calc-current-TBLFM))
20643 (goto-char (org-element-property :contents-begin context))
20644 (org-call-with-arg 'org-table-recalculate (or arg t))
20645 (orgtbl-send-table 'maybe)))
20646 (org-table-maybe-eval-formula)
20647 (cond (arg (call-interactively #'org-table-recalculate))
20648 ((org-table-maybe-recalculate-line))
20649 (t (org-table-align))))))
20650 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20651 (org-timestamp-change 0 'day))
20652 ((and `nil (guard (org-at-heading-p)))
20653 ;; When point is on an unsupported object type, we can miss
20654 ;; the fact that it also is at a heading. Handle it here.
20655 (call-interactively #'org-set-tags))
20656 ((guard
20657 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20659 (user-error
20660 (substitute-command-keys
20661 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20663 (defun org-mode-restart ()
20664 (interactive)
20665 (let ((indent-status (bound-and-true-p org-indent-mode)))
20666 (funcall major-mode)
20667 (hack-local-variables)
20668 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20669 (org-indent-mode -1))
20670 (org-reset-file-cache))
20671 (message "%s restarted" major-mode))
20673 (defun org-kill-note-or-show-branches ()
20674 "Abort storing current note, or call `outline-show-branches'."
20675 (interactive)
20676 (if (not org-finish-function)
20677 (progn
20678 (outline-hide-subtree)
20679 (call-interactively 'outline-show-branches))
20680 (let ((org-note-abort t))
20681 (funcall org-finish-function))))
20683 (defun org-delete-indentation (&optional arg)
20684 "Join current line to previous and fix whitespace at join.
20686 If previous line is a headline add to headline title. Otherwise
20687 the function calls `delete-indentation'.
20689 With a non-nil optional argument, join it to the following one."
20690 (interactive "*P")
20691 (if (save-excursion
20692 (beginning-of-line (if arg 1 0))
20693 (let ((case-fold-search nil))
20694 (looking-at org-complex-heading-regexp)))
20695 ;; At headline.
20696 (let ((tags-column (when (match-beginning 5)
20697 (save-excursion (goto-char (match-beginning 5))
20698 (current-column))))
20699 (string (concat " " (progn (when arg (forward-line 1))
20700 (org-trim (delete-and-extract-region
20701 (line-beginning-position)
20702 (line-end-position)))))))
20703 (unless (bobp) (delete-region (point) (1- (point))))
20704 (goto-char (or (match-end 4)
20705 (match-beginning 5)
20706 (match-end 0)))
20707 (skip-chars-backward " \t")
20708 (save-excursion (insert string))
20709 ;; Adjust alignment of tags.
20710 (cond
20711 ((not tags-column)) ;no tags
20712 (org-auto-align-tags (org-set-tags nil t))
20713 (t (org--align-tags-here tags-column)))) ;preserve tags column
20714 (delete-indentation arg)))
20716 (defun org-open-line (n)
20717 "Insert a new row in tables, call `open-line' elsewhere.
20718 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20719 As a special case, when a document starts with a table, allow to
20720 call `open-line' on the very first character."
20721 (interactive "*p")
20722 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20723 (org-table-insert-row)
20724 (open-line n)))
20726 (defun org-return (&optional indent)
20727 "Goto next table row or insert a newline.
20729 Calls `org-table-next-row' or `newline', depending on context.
20731 When optional INDENT argument is non-nil, call
20732 `newline-and-indent' instead of `newline'.
20734 When `org-return-follows-link' is non-nil and point is on
20735 a timestamp or a link, call `org-open-at-point'. However, it
20736 will not happen if point is in a table or on a \"dead\"
20737 object (e.g., within a comment). In these case, you need to use
20738 `org-open-at-point' directly."
20739 (interactive)
20740 (let ((context (if org-return-follows-link (org-element-context)
20741 (org-element-at-point))))
20742 (cond
20743 ;; In a table, call `org-table-next-row'. However, before first
20744 ;; column or after last one, split the table.
20745 ((or (and (eq (org-element-type context) 'table)
20746 (>= (point) (org-element-property :contents-begin context))
20747 (< (point) (org-element-property :contents-end context)))
20748 (org-element-lineage context '(table-row table-cell) t))
20749 (if (or (looking-at-p "[ \t]*$")
20750 (save-excursion (skip-chars-backward " \t") (bolp)))
20751 (insert "\n")
20752 (org-table-justify-field-maybe)
20753 (call-interactively #'org-table-next-row)))
20754 ;; On a link or a timestamp, call `org-open-at-point' if
20755 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20756 ;; locations, e.g., in a comment, as `org-open-at-point'.
20757 ((and org-return-follows-link
20758 (or (org-in-regexp org-ts-regexp-both nil t)
20759 (org-in-regexp org-tsr-regexp-both nil t)
20760 (org-in-regexp org-any-link-re nil t)))
20761 (call-interactively #'org-open-at-point))
20762 ;; Insert newline in heading, but preserve tags.
20763 ((and (not (bolp))
20764 (save-excursion (beginning-of-line)
20765 (let ((case-fold-search nil))
20766 (looking-at org-complex-heading-regexp))))
20767 ;; At headline. Split line. However, if point is on keyword,
20768 ;; priority cookie or tags, do not break any of them: add
20769 ;; a newline after the headline instead.
20770 (let ((tags-column (and (match-beginning 5)
20771 (save-excursion (goto-char (match-beginning 5))
20772 (current-column))))
20773 (string
20774 (when (and (match-end 4) (org-point-in-group (point) 4))
20775 (delete-and-extract-region (point) (match-end 4)))))
20776 ;; Adjust tag alignment.
20777 (cond
20778 ((not (and tags-column string)))
20779 (org-auto-align-tags (org-set-tags nil t))
20780 (t (org--align-tags-here tags-column))) ;preserve tags column
20781 (end-of-line)
20782 (org-show-entry)
20783 (if indent (newline-and-indent) (newline))
20784 (when string (save-excursion (insert (org-trim string))))))
20785 ;; In a list, make sure indenting keeps trailing text within.
20786 ((and indent
20787 (not (eolp))
20788 (org-element-lineage context '(item)))
20789 (let ((trailing-data
20790 (delete-and-extract-region (point) (line-end-position))))
20791 (newline-and-indent)
20792 (save-excursion (insert trailing-data))))
20793 (t (if indent (newline-and-indent) (newline))))))
20795 (defun org-return-indent ()
20796 "Goto next table row or insert a newline and indent.
20797 Calls `org-table-next-row' or `newline-and-indent', depending on
20798 context. See the individual commands for more information."
20799 (interactive)
20800 (org-return t))
20802 (defun org-ctrl-c-tab (&optional _arg)
20803 "Toggle columns width in a table, or show children.
20804 Call `org-table-toggle-column-width' if point is in a table.
20805 Otherwise, call `org-show-children'."
20806 (interactive "p")
20807 (call-interactively
20808 (if (org-at-table-p) #'org-table-toggle-column-width
20809 #'org-show-children)))
20811 (defun org-ctrl-c-star ()
20812 "Compute table, or change heading status of lines.
20813 Calls `org-table-recalculate' or `org-toggle-heading',
20814 depending on context."
20815 (interactive)
20816 (cond
20817 ((org-at-table-p)
20818 (call-interactively 'org-table-recalculate))
20820 ;; Convert all lines in region to list items
20821 (call-interactively 'org-toggle-heading))))
20823 (defun org-ctrl-c-minus ()
20824 "Insert separator line in table or modify bullet status of line.
20825 Also turns a plain line or a region of lines into list items.
20826 Calls `org-table-insert-hline', `org-toggle-item', or
20827 `org-cycle-list-bullet', depending on context."
20828 (interactive)
20829 (cond
20830 ((org-at-table-p)
20831 (call-interactively 'org-table-insert-hline))
20832 ((org-region-active-p)
20833 (call-interactively 'org-toggle-item))
20834 ((org-in-item-p)
20835 (call-interactively 'org-cycle-list-bullet))
20837 (call-interactively 'org-toggle-item))))
20839 (defun org-toggle-heading (&optional nstars)
20840 "Convert headings to normal text, or items or text to headings.
20841 If there is no active region, only convert the current line.
20843 With a `\\[universal-argument]' prefix, convert the whole list at
20844 point into heading.
20846 In a region:
20848 - If the first non blank line is a headline, remove the stars
20849 from all headlines in the region.
20851 - If it is a normal line, turn each and every normal line (i.e.,
20852 not an heading or an item) in the region into headings. If you
20853 want to convert only the first line of this region, use one
20854 universal prefix argument.
20856 - If it is a plain list item, turn all plain list items into headings.
20858 When converting a line into a heading, the number of stars is chosen
20859 such that the lines become children of the current entry. However,
20860 when a numeric prefix argument is given, its value determines the
20861 number of stars to add."
20862 (interactive "P")
20863 (let ((skip-blanks
20864 (function
20865 ;; Return beginning of first non-blank line, starting from
20866 ;; line at POS.
20867 (lambda (pos)
20868 (save-excursion
20869 (goto-char pos)
20870 (while (org-at-comment-p) (forward-line))
20871 (skip-chars-forward " \r\t\n")
20872 (point-at-bol)))))
20873 beg end toggled)
20874 ;; Determine boundaries of changes. If a universal prefix has
20875 ;; been given, put the list in a region. If region ends at a bol,
20876 ;; do not consider the last line to be in the region.
20878 (when (and current-prefix-arg (org-at-item-p))
20879 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20880 (org-mark-element))
20882 (if (org-region-active-p)
20883 (setq beg (funcall skip-blanks (region-beginning))
20884 end (copy-marker (save-excursion
20885 (goto-char (region-end))
20886 (if (bolp) (point) (point-at-eol)))))
20887 (setq beg (funcall skip-blanks (point-at-bol))
20888 end (copy-marker (point-at-eol))))
20889 ;; Ensure inline tasks don't count as headings.
20890 (org-with-limited-levels
20891 (save-excursion
20892 (goto-char beg)
20893 (cond
20894 ;; Case 1. Started at an heading: de-star headings.
20895 ((org-at-heading-p)
20896 (while (< (point) end)
20897 (when (org-at-heading-p t)
20898 (looking-at org-outline-regexp) (replace-match "")
20899 (setq toggled t))
20900 (forward-line)))
20901 ;; Case 2. Started at an item: change items into headlines.
20902 ;; One star will be added by `org-list-to-subtree'.
20903 ((org-at-item-p)
20904 (while (< (point) end)
20905 (when (org-at-item-p)
20906 ;; Pay attention to cases when region ends before list.
20907 (let* ((struct (org-list-struct))
20908 (list-end
20909 (min (org-list-get-bottom-point struct) (1+ end))))
20910 (save-restriction
20911 (narrow-to-region (point) list-end)
20912 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20913 (setq toggled t))
20914 (forward-line)))
20915 ;; Case 3. Started at normal text: make every line an heading,
20916 ;; skipping headlines and items.
20917 (t (let* ((stars
20918 (make-string
20919 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20920 (add-stars
20921 (cond (nstars "") ; stars from prefix only
20922 ((equal stars "") "*") ; before first heading
20923 (org-odd-levels-only "**") ; inside heading, odd
20924 (t "*"))) ; inside heading, oddeven
20925 (rpl (concat stars add-stars " "))
20926 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20927 (while (< (point) (if (equal nstars '(4)) lend end))
20928 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20929 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20930 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20931 (forward-line)))))))
20932 (unless toggled (message "Cannot toggle heading from here"))))
20934 (defun org-meta-return (&optional arg)
20935 "Insert a new heading or wrap a region in a table.
20936 Calls `org-insert-heading', `org-insert-item' or
20937 `org-table-wrap-region', depending on context. When called with
20938 an argument, unconditionally call `org-insert-heading'."
20939 (interactive "P")
20940 (org-check-before-invisible-edit 'insert)
20941 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20942 (call-interactively (cond (arg #'org-insert-heading)
20943 ((org-at-table-p) #'org-table-wrap-region)
20944 ((org-in-item-p) #'org-insert-item)
20945 (t #'org-insert-heading)))))
20947 ;;; Menu entries
20949 (defsubst org-in-subtree-not-table-p ()
20950 "Are we in a subtree and not in a table?"
20951 (and (not (org-before-first-heading-p))
20952 (not (org-at-table-p))))
20954 ;; Define the Org mode menus
20955 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20956 '("Tbl"
20957 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20958 ["Next Field" org-cycle (org-at-table-p)]
20959 ["Previous Field" org-shifttab (org-at-table-p)]
20960 ["Next Row" org-return (org-at-table-p)]
20961 "--"
20962 ["Blank Field" org-table-blank-field (org-at-table-p)]
20963 ["Edit Field" org-table-edit-field (org-at-table-p)]
20964 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20965 "--"
20966 ("Column"
20967 ["Move Column Left" org-metaleft (org-at-table-p)]
20968 ["Move Column Right" org-metaright (org-at-table-p)]
20969 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20970 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20971 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20972 ("Row"
20973 ["Move Row Up" org-metaup (org-at-table-p)]
20974 ["Move Row Down" org-metadown (org-at-table-p)]
20975 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20976 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20977 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20978 "--"
20979 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20980 ("Rectangle"
20981 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20982 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20983 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20984 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20985 "--"
20986 ("Calculate"
20987 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20988 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20989 ["Edit Formulas" org-edit-special (org-at-table-p)]
20990 "--"
20991 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20992 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20993 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20994 "--"
20995 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20996 "--"
20997 ["Sum Column/Rectangle" org-table-sum
20998 (or (org-at-table-p) (org-region-active-p))]
20999 ["Which Column?" org-table-current-column (org-at-table-p)])
21000 ["Debug Formulas"
21001 org-table-toggle-formula-debugger
21002 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21003 ["Show Col/Row Numbers"
21004 org-table-toggle-coordinate-overlays
21005 :style toggle
21006 :selected (bound-and-true-p org-table-overlay-coordinates)]
21007 "--"
21008 ["Create" org-table-create (not (org-at-table-p))]
21009 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21010 ["Import from File" org-table-import (not (org-at-table-p))]
21011 ["Export to File" org-table-export (org-at-table-p)]
21012 "--"
21013 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21014 "--"
21015 ("Plot"
21016 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21017 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21019 (easy-menu-define org-org-menu org-mode-map "Org menu"
21020 '("Org"
21021 ("Show/Hide"
21022 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21023 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21024 ["Sparse Tree..." org-sparse-tree t]
21025 ["Reveal Context" org-reveal t]
21026 ["Show All" outline-show-all t]
21027 "--"
21028 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21029 "--"
21030 ["New Heading" org-insert-heading t]
21031 ("Navigate Headings"
21032 ["Up" outline-up-heading t]
21033 ["Next" outline-next-visible-heading t]
21034 ["Previous" outline-previous-visible-heading t]
21035 ["Next Same Level" outline-forward-same-level t]
21036 ["Previous Same Level" outline-backward-same-level t]
21037 "--"
21038 ["Jump" org-goto t])
21039 ("Edit Structure"
21040 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21041 "--"
21042 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21043 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21044 "--"
21045 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21046 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21047 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21048 "--"
21049 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21050 "--"
21051 ["Copy visible text" org-copy-visible t]
21052 "--"
21053 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21054 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21055 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21056 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21057 "--"
21058 ["Sort Region/Children" org-sort t]
21059 "--"
21060 ["Convert to odd levels" org-convert-to-odd-levels t]
21061 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21062 ("Editing"
21063 ["Emphasis..." org-emphasize t]
21064 ["Edit Source Example" org-edit-special t]
21065 "--"
21066 ["Footnote new/jump" org-footnote-action t]
21067 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21068 ("Archive"
21069 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21070 "--"
21071 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21072 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21073 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21075 "--"
21076 ("Hyperlinks"
21077 ["Store Link (Global)" org-store-link t]
21078 ["Find existing link to here" org-occur-link-in-agenda-files t]
21079 ["Insert Link" org-insert-link t]
21080 ["Follow Link" org-open-at-point t]
21081 "--"
21082 ["Next link" org-next-link t]
21083 ["Previous link" org-previous-link t]
21084 "--"
21085 ["Descriptive Links"
21086 org-toggle-link-display
21087 :style radio
21088 :selected org-descriptive-links
21090 ["Literal Links"
21091 org-toggle-link-display
21092 :style radio
21093 :selected (not org-descriptive-links)])
21094 "--"
21095 ("TODO Lists"
21096 ["TODO/DONE/-" org-todo t]
21097 ("Select keyword"
21098 ["Next keyword" org-shiftright (org-at-heading-p)]
21099 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21100 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21101 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21102 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21103 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21104 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21105 "--"
21106 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21107 :selected org-enforce-todo-dependencies :style toggle :active t]
21108 "Settings for tree at point"
21109 ["Do Children sequentially" org-toggle-ordered-property :style radio
21110 :selected (org-entry-get nil "ORDERED")
21111 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21112 ["Do Children parallel" org-toggle-ordered-property :style radio
21113 :selected (not (org-entry-get nil "ORDERED"))
21114 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21115 "--"
21116 ["Set Priority" org-priority t]
21117 ["Priority Up" org-shiftup t]
21118 ["Priority Down" org-shiftdown t]
21119 "--"
21120 ["Get news from all feeds" org-feed-update-all t]
21121 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21122 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21123 ("TAGS and Properties"
21124 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21125 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21126 "--"
21127 ["Set property" org-set-property (not (org-before-first-heading-p))]
21128 ["Column view of properties" org-columns t]
21129 ["Insert Column View DBlock" org-columns-insert-dblock t])
21130 ("Dates and Scheduling"
21131 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21132 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21133 ("Change Date"
21134 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21135 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21136 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21137 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21138 ["Compute Time Range" org-evaluate-time-range t]
21139 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21140 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21141 "--"
21142 ["Custom time format" org-toggle-time-stamp-overlays
21143 :style radio :selected org-display-custom-times]
21144 "--"
21145 ["Goto Calendar" org-goto-calendar t]
21146 ["Date from Calendar" org-date-from-calendar t]
21147 "--"
21148 ["Start/Restart Timer" org-timer-start t]
21149 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21150 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21151 ["Insert Timer String" org-timer t]
21152 ["Insert Timer Item" org-timer-item t])
21153 ("Logging work"
21154 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21155 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21156 ["Clock out" org-clock-out t]
21157 ["Clock cancel" org-clock-cancel t]
21158 "--"
21159 ["Mark as default task" org-clock-mark-default-task t]
21160 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21161 ["Goto running clock" org-clock-goto t]
21162 "--"
21163 ["Display times" org-clock-display t]
21164 ["Create clock table" org-clock-report t]
21165 "--"
21166 ["Record DONE time"
21167 (progn (setq org-log-done (not org-log-done))
21168 (message "Switching to %s will %s record a timestamp"
21169 (car org-done-keywords)
21170 (if org-log-done "automatically" "not")))
21171 :style toggle :selected org-log-done])
21172 "--"
21173 ["Agenda Command..." org-agenda t]
21174 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21175 ("File List for Agenda")
21176 ("Special views current file"
21177 ["TODO Tree" org-show-todo-tree t]
21178 ["Check Deadlines" org-check-deadlines t]
21179 ["Tags/Property tree" org-match-sparse-tree t])
21180 "--"
21181 ["Export/Publish..." org-export-dispatch t]
21182 ("LaTeX"
21183 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21184 :style toggle :selected org-cdlatex-mode]
21185 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21186 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21187 ["Modify math symbol" org-cdlatex-math-modify
21188 (org-inside-LaTeX-fragment-p)]
21189 ["Insert citation" org-reftex-citation t])
21190 "--"
21191 ("MobileOrg"
21192 ["Push Files and Views" org-mobile-push t]
21193 ["Get Captured and Flagged" org-mobile-pull t]
21194 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21195 "--"
21196 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21197 "--"
21198 ("Documentation"
21199 ["Show Version" org-version t]
21200 ["Info Documentation" org-info t])
21201 ("Customize"
21202 ["Browse Org Group" org-customize t]
21203 "--"
21204 ["Expand This Menu" org-create-customize-menu
21205 (fboundp 'customize-menu-create)])
21206 ["Send bug report" org-submit-bug-report t]
21207 "--"
21208 ("Refresh/Reload"
21209 ["Refresh setup current buffer" org-mode-restart t]
21210 ["Reload Org (after update)" org-reload t]
21211 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21214 (defun org-info (&optional node)
21215 "Read documentation for Org in the info system.
21216 With optional NODE, go directly to that node."
21217 (interactive)
21218 (info (format "(org)%s" (or node ""))))
21220 ;;;###autoload
21221 (defun org-submit-bug-report ()
21222 "Submit a bug report on Org via mail.
21224 Don't hesitate to report any problems or inaccurate documentation.
21226 If you don't have setup sending mail from (X)Emacs, please copy the
21227 output buffer into your mail program, as it gives us important
21228 information about your Org version and configuration."
21229 (interactive)
21230 (require 'reporter)
21231 (defvar reporter-prompt-for-summary-p)
21232 (org-load-modules-maybe)
21233 (org-require-autoloaded-modules)
21234 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21235 (reporter-submit-bug-report
21236 "emacs-orgmode@gnu.org"
21237 (org-version nil 'full)
21238 (let (list)
21239 (save-window-excursion
21240 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21241 (delete-other-windows)
21242 (erase-buffer)
21243 (insert "You are about to submit a bug report to the Org mailing list.
21245 We would like to add your full Org and Outline configuration to the
21246 bug report. This greatly simplifies the work of the maintainer and
21247 other experts on the mailing list.
21249 HOWEVER, some variables you have customized may contain private
21250 information. The names of customers, colleagues, or friends, might
21251 appear in the form of file names, tags, todo states, or search strings.
21252 If you answer yes to the prompt, you might want to check and remove
21253 such private information before sending the email.")
21254 (add-text-properties (point-min) (point-max) '(face org-warning))
21255 (when (yes-or-no-p "Include your Org configuration ")
21256 (mapatoms
21257 (lambda (v)
21258 (and (boundp v)
21259 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21260 (or (and (symbol-value v)
21261 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21262 (and
21263 (get v 'custom-type) (get v 'standard-value)
21264 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21265 (push v list)))))
21266 (kill-buffer (get-buffer "*Warn about privacy*"))
21267 list))
21268 nil nil
21269 "Remember to cover the basics, that is, what you expected to happen and
21270 what in fact did happen. You don't know how to make a good report? See
21272 http://orgmode.org/manual/Feedback.html#Feedback
21274 Your bug report will be posted to the Org mailing list.
21275 ------------------------------------------------------------------------")
21276 (save-excursion
21277 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21278 (replace-match "\\1Bug: \\3 [\\2]")))))
21281 (defun org-install-agenda-files-menu ()
21282 (let ((bl (buffer-list)))
21283 (save-excursion
21284 (while bl
21285 (set-buffer (pop bl))
21286 (when (derived-mode-p 'org-mode) (setq bl nil)))
21287 (when (derived-mode-p 'org-mode)
21288 (easy-menu-change
21289 '("Org") "File List for Agenda"
21290 (append
21291 (list
21292 ["Edit File List" (org-edit-agenda-file-list) t]
21293 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21294 ["Remove Current File from List" org-remove-file t]
21295 ["Cycle through agenda files" org-cycle-agenda-files t]
21296 ["Occur in all agenda files" org-occur-in-agenda-files t]
21297 "--")
21298 (mapcar 'org-file-menu-entry
21299 ;; Prevent initialization from failing.
21300 (ignore-errors (org-agenda-files t)))))))))
21302 ;;;; Documentation
21304 (defun org-require-autoloaded-modules ()
21305 (interactive)
21306 (mapc #'require
21307 '(org-agenda org-archive org-attach org-clock org-colview org-id
21308 org-table org-timer)))
21310 ;;;###autoload
21311 (defun org-reload (&optional uncompiled)
21312 "Reload all org lisp files.
21313 With prefix arg UNCOMPILED, load the uncompiled versions."
21314 (interactive "P")
21315 (require 'loadhist)
21316 (let* ((org-dir (org-find-library-dir "org"))
21317 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21318 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21319 (remove-re (format "\\`%s\\'"
21320 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21321 (feats (delete-dups
21322 (mapcar 'file-name-sans-extension
21323 (mapcar 'file-name-nondirectory
21324 (delq nil
21325 (mapcar 'feature-file
21326 features))))))
21327 (lfeat (append
21328 (sort
21329 (setq feats
21330 (delq nil (mapcar
21331 (lambda (f)
21332 (if (and (string-match feature-re f)
21333 (not (string-match remove-re f)))
21334 f nil))
21335 feats)))
21336 'string-lessp)
21337 (list "org-version" "org")))
21338 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21339 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21340 load-uncore load-misses)
21341 (setq load-misses
21342 (delq 't
21343 (mapcar (lambda (f)
21344 (or (org-load-noerror-mustsuffix (concat org-dir f))
21345 (and (string= org-dir contrib-dir)
21346 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21347 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21348 (add-to-list 'load-uncore f 'append)
21351 lfeat)))
21352 (when load-uncore
21353 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21354 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21355 (if load-misses
21356 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21357 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21358 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21360 ;;;###autoload
21361 (defun org-customize ()
21362 "Call the customize function with org as argument."
21363 (interactive)
21364 (org-load-modules-maybe)
21365 (org-require-autoloaded-modules)
21366 (customize-browse 'org))
21368 (defun org-create-customize-menu ()
21369 "Create a full customization menu for Org mode, insert it into the menu."
21370 (interactive)
21371 (org-load-modules-maybe)
21372 (org-require-autoloaded-modules)
21373 (if (fboundp 'customize-menu-create)
21374 (progn
21375 (easy-menu-change
21376 '("Org") "Customize"
21377 `(["Browse Org group" org-customize t]
21378 "--"
21379 ,(customize-menu-create 'org)
21380 ["Set" Custom-set t]
21381 ["Save" Custom-save t]
21382 ["Reset to Current" Custom-reset-current t]
21383 ["Reset to Saved" Custom-reset-saved t]
21384 ["Reset to Standard Settings" Custom-reset-standard t]))
21385 (message "\"Org\"-menu now contains full customization menu"))
21386 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21388 ;;;; Miscellaneous stuff
21390 ;;; Generally useful functions
21392 (defun org-link-display-format (s)
21393 "Replace links in string S with their description.
21394 If there is no description, use the link target."
21395 (save-match-data
21396 (replace-regexp-in-string
21397 org-bracket-link-analytic-regexp
21398 (lambda (m)
21399 (if (match-end 5) (match-string 5 m)
21400 (concat (match-string 1 m) (match-string 3 m))))
21401 s nil t)))
21403 (defun org-toggle-link-display ()
21404 "Toggle the literal or descriptive display of links."
21405 (interactive)
21406 (if org-descriptive-links
21407 (progn (org-remove-from-invisibility-spec '(org-link))
21408 (org-restart-font-lock)
21409 (setq org-descriptive-links nil))
21410 (progn (add-to-invisibility-spec '(org-link))
21411 (org-restart-font-lock)
21412 (setq org-descriptive-links t))))
21414 (defun org-in-clocktable-p ()
21415 "Check if the cursor is in a clocktable."
21416 (let ((pos (point)) start)
21417 (save-excursion
21418 (end-of-line 1)
21419 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21420 (setq start (match-beginning 0))
21421 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21422 (>= (match-end 0) pos)
21423 start))))
21425 (defun org-in-verbatim-emphasis ()
21426 (save-match-data
21427 (and (org-in-regexp org-verbatim-re 2)
21428 (>= (point) (match-beginning 3))
21429 (<= (point) (match-end 4)))))
21431 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21432 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21433 (if (and marker (marker-buffer marker)
21434 (buffer-live-p (marker-buffer marker)))
21435 (progn
21436 (pop-to-buffer-same-window (marker-buffer marker))
21437 (when (or (> marker (point-max)) (< marker (point-min)))
21438 (widen))
21439 (goto-char marker)
21440 (org-show-context 'org-goto))
21441 (if bookmark
21442 (bookmark-jump bookmark)
21443 (error "Cannot find location"))))
21445 (defun org-quote-csv-field (s)
21446 "Quote field for inclusion in CSV material."
21447 (if (string-match "[\",]" s)
21448 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21451 (defun org-force-self-insert (N)
21452 "Needed to enforce self-insert under remapping."
21453 (interactive "p")
21454 (self-insert-command N))
21456 (defun org-get-indentation (&optional line)
21457 "Get the indentation of the current line, interpreting tabs.
21458 When LINE is given, assume it represents a line and compute its indentation."
21459 (if line
21460 (when (string-match "^ *" (org-remove-tabs line))
21461 (match-end 0))
21462 (save-excursion
21463 (beginning-of-line 1)
21464 (skip-chars-forward " \t")
21465 (current-column))))
21467 (defun org-get-string-indentation (s)
21468 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21469 (let ((n -1) (i 0) (w tab-width) c)
21470 (catch 'exit
21471 (while (< (setq n (1+ n)) (length s))
21472 (setq c (aref s n))
21473 (cond ((= c ?\ ) (setq i (1+ i)))
21474 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21475 (t (throw 'exit t)))))
21478 (defun org-fix-indentation (line ind)
21479 "Fix indentation in LINE.
21480 IND is a cons cell with target and minimum indentation.
21481 If the current indentation in LINE is smaller than the minimum,
21482 leave it alone. If it is larger than ind, set it to the target."
21483 (let* ((l (org-remove-tabs line))
21484 (i (org-get-indentation l))
21485 (i1 (car ind)) (i2 (cdr ind)))
21486 (when (>= i i2) (setq l (substring line i2)))
21487 (if (> i1 0)
21488 (concat (make-string i1 ?\ ) l)
21489 l)))
21491 (defun org-fill-template (template alist)
21492 "Find each %key of ALIST in TEMPLATE and replace it."
21493 (let ((case-fold-search nil))
21494 (dolist (entry (sort (copy-sequence alist)
21495 (lambda (a b) (< (length (car a)) (length (car b))))))
21496 (setq template
21497 (replace-regexp-in-string
21498 (concat "%" (regexp-quote (car entry)))
21499 (or (cdr entry) "") template t t)))
21500 template))
21502 (defun org-quote-vert (s)
21503 "Replace \"|\" with \"\\vert\"."
21504 (while (string-match "|" s)
21505 (setq s (replace-match "\\vert" t t s)))
21508 (defun org-uuidgen-p (s)
21509 "Is S an ID created by UUIDGEN?"
21510 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21512 (defun org-in-src-block-p (&optional inside)
21513 "Whether point is in a code source block.
21514 When INSIDE is non-nil, don't consider we are within a src block
21515 when point is at #+BEGIN_SRC or #+END_SRC."
21516 (let ((case-fold-search t))
21517 (or (and (eq (get-char-property (point) 'src-block) t))
21518 (and (not inside)
21519 (save-match-data
21520 (save-excursion
21521 (beginning-of-line)
21522 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21524 (defun org-context ()
21525 "Return a list of contexts of the current cursor position.
21526 If several contexts apply, all are returned.
21527 Each context entry is a list with a symbol naming the context, and
21528 two positions indicating start and end of the context. Possible
21529 contexts are:
21531 :headline anywhere in a headline
21532 :headline-stars on the leading stars in a headline
21533 :todo-keyword on a TODO keyword (including DONE) in a headline
21534 :tags on the TAGS in a headline
21535 :priority on the priority cookie in a headline
21536 :item on the first line of a plain list item
21537 :item-bullet on the bullet/number of a plain list item
21538 :checkbox on the checkbox in a plain list item
21539 :table in an Org table
21540 :table-special on a special filed in a table
21541 :table-table in a table.el table
21542 :clocktable in a clocktable
21543 :src-block in a source block
21544 :link on a hyperlink
21545 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21546 :target on a <<target>>
21547 :radio-target on a <<<radio-target>>>
21548 :latex-fragment on a LaTeX fragment
21549 :latex-preview on a LaTeX fragment with overlaid preview image
21551 This function expects the position to be visible because it uses font-lock
21552 faces as a help to recognize the following contexts: :table-special, :link,
21553 and :keyword."
21554 (let* ((f (get-text-property (point) 'face))
21555 (faces (if (listp f) f (list f)))
21556 (case-fold-search t)
21557 (p (point)) clist o)
21558 ;; First the large context
21559 (cond
21560 ((org-at-heading-p t)
21561 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21562 (when (progn
21563 (beginning-of-line 1)
21564 (looking-at org-todo-line-tags-regexp))
21565 (push (org-point-in-group p 1 :headline-stars) clist)
21566 (push (org-point-in-group p 2 :todo-keyword) clist)
21567 (push (org-point-in-group p 4 :tags) clist))
21568 (goto-char p)
21569 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21570 (when (looking-at "\\[#[A-Z0-9]\\]")
21571 (push (org-point-in-group p 0 :priority) clist)))
21573 ((org-at-item-p)
21574 (push (org-point-in-group p 2 :item-bullet) clist)
21575 (push (list :item (point-at-bol)
21576 (save-excursion (org-end-of-item) (point)))
21577 clist)
21578 (and (org-at-item-checkbox-p)
21579 (push (org-point-in-group p 0 :checkbox) clist)))
21581 ((org-at-table-p)
21582 (push (list :table (org-table-begin) (org-table-end)) clist)
21583 (when (memq 'org-formula faces)
21584 (push (list :table-special
21585 (previous-single-property-change p 'face)
21586 (next-single-property-change p 'face)) clist)))
21587 ((org-at-table-p 'any)
21588 (push (list :table-table) clist)))
21589 (goto-char p)
21591 (let ((case-fold-search t))
21592 ;; New the "medium" contexts: clocktables, source blocks
21593 (cond ((org-in-clocktable-p)
21594 (push (list :clocktable
21595 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21596 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21597 (match-beginning 1))
21598 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21599 (match-end 0))) clist))
21600 ((org-in-src-block-p)
21601 (push (list :src-block
21602 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21603 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21604 (match-beginning 1))
21605 (and (search-forward "#+END_SRC" nil t)
21606 (match-beginning 0))) clist))))
21607 (goto-char p)
21609 ;; Now the small context
21610 (cond
21611 ((org-at-timestamp-p)
21612 (push (org-point-in-group p 0 :timestamp) clist))
21613 ((memq 'org-link faces)
21614 (push (list :link
21615 (previous-single-property-change p 'face)
21616 (next-single-property-change p 'face)) clist))
21617 ((memq 'org-special-keyword faces)
21618 (push (list :keyword
21619 (previous-single-property-change p 'face)
21620 (next-single-property-change p 'face)) clist))
21621 ((org-at-target-p)
21622 (push (org-point-in-group p 0 :target) clist)
21623 (goto-char (1- (match-beginning 0)))
21624 (when (looking-at org-radio-target-regexp)
21625 (push (org-point-in-group p 0 :radio-target) clist))
21626 (goto-char p))
21627 ((setq o (cl-some
21628 (lambda (o)
21629 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21631 (overlays-at (point))))
21632 (push (list :latex-fragment
21633 (overlay-start o) (overlay-end o)) clist)
21634 (push (list :latex-preview
21635 (overlay-start o) (overlay-end o)) clist))
21636 ((org-inside-LaTeX-fragment-p)
21637 ;; FIXME: positions wrong.
21638 (push (list :latex-fragment (point) (point)) clist)))
21640 (setq clist (nreverse (delq nil clist)))
21641 clist))
21643 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21644 "Non-nil when point is between matches of START-RE and END-RE.
21646 Also return a non-nil value when point is on one of the matches.
21648 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21649 buffer positions. Default values are the positions of headlines
21650 surrounding the point.
21652 The functions returns a cons cell whose car (resp. cdr) is the
21653 position before START-RE (resp. after END-RE)."
21654 (save-match-data
21655 (let ((pos (point))
21656 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21657 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21658 beg end)
21659 (save-excursion
21660 ;; Point is on a block when on START-RE or if START-RE can be
21661 ;; found before it...
21662 (and (or (org-in-regexp start-re)
21663 (re-search-backward start-re limit-up t))
21664 (setq beg (match-beginning 0))
21665 ;; ... and END-RE after it...
21666 (goto-char (match-end 0))
21667 (re-search-forward end-re limit-down t)
21668 (> (setq end (match-end 0)) pos)
21669 ;; ... without another START-RE in-between.
21670 (goto-char (match-beginning 0))
21671 (not (re-search-backward start-re (1+ beg) t))
21672 ;; Return value.
21673 (cons beg end))))))
21675 (defun org-in-block-p (names)
21676 "Non-nil when point belongs to a block whose name belongs to NAMES.
21678 NAMES is a list of strings containing names of blocks.
21680 Return first block name matched, or nil. Beware that in case of
21681 nested blocks, the returned name may not belong to the closest
21682 block from point."
21683 (save-match-data
21684 (catch 'exit
21685 (let ((case-fold-search t)
21686 (lim-up (save-excursion (outline-previous-heading)))
21687 (lim-down (save-excursion (outline-next-heading))))
21688 (dolist (name names)
21689 (let ((n (regexp-quote name)))
21690 (when (org-between-regexps-p
21691 (concat "^[ \t]*#\\+begin_" n)
21692 (concat "^[ \t]*#\\+end_" n)
21693 lim-up lim-down)
21694 (throw 'exit n)))))
21695 nil)))
21697 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21698 "Call `multi-occur' with buffers for all agenda files."
21699 (interactive "sOrg-files matching: ")
21700 (let* ((files (org-agenda-files))
21701 (tnames (mapcar #'file-truename files))
21702 (extra org-agenda-text-search-extra-files))
21703 (when (eq (car extra) 'agenda-archives)
21704 (setq extra (cdr extra))
21705 (setq files (org-add-archive-files files)))
21706 (dolist (f extra)
21707 (unless (member (file-truename f) tnames)
21708 (unless (member f files) (setq files (append files (list f))))
21709 (setq tnames (append tnames (list (file-truename f))))))
21710 (multi-occur
21711 (mapcar (lambda (x)
21712 (with-current-buffer
21713 ;; FIXME: Why not just (find-file-noselect x)?
21714 ;; Is it to avoid the "revert buffer" prompt?
21715 (or (get-file-buffer x) (find-file-noselect x))
21716 (widen)
21717 (current-buffer)))
21718 files)
21719 regexp)))
21721 (add-hook 'occur-mode-find-occurrence-hook
21722 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21724 (defun org-occur-link-in-agenda-files ()
21725 "Create a link and search for it in the agendas.
21726 The link is not stored in `org-stored-links', it is just created
21727 for the search purpose."
21728 (interactive)
21729 (let ((link (condition-case nil
21730 (org-store-link nil)
21731 (error "Unable to create a link to here"))))
21732 (org-occur-in-agenda-files (regexp-quote link))))
21734 (defun org-back-over-empty-lines ()
21735 "Move backwards over whitespace, to the beginning of the first empty line.
21736 Returns the number of empty lines passed."
21737 (let ((pos (point)))
21738 (if (cdr (assq 'heading org-blank-before-new-entry))
21739 (skip-chars-backward " \t\n\r")
21740 (unless (eobp)
21741 (forward-line -1)))
21742 (beginning-of-line 2)
21743 (goto-char (min (point) pos))
21744 (count-lines (point) pos)))
21746 (defun org-switch-to-buffer-other-window (&rest args)
21747 "Switch to buffer in a second window on the current frame.
21748 In particular, do not allow pop-up frames.
21749 Returns the newly created buffer."
21750 (org-no-popups
21751 (apply 'switch-to-buffer-other-window args)))
21753 (defun org-replace-escapes (string table)
21754 "Replace %-escapes in STRING with values in TABLE.
21755 TABLE is an association list with keys like \"%a\" and string values.
21756 The sequences in STRING may contain normal field width and padding information,
21757 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21758 so values can contain further %-escapes if they are define later in TABLE."
21759 (let ((tbl (copy-alist table))
21760 (case-fold-search nil)
21761 (pchg 0)
21762 re rpl)
21763 (dolist (e tbl)
21764 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21765 (when (and (cdr e) (string-match re (cdr e)))
21766 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21767 (safe "SREF"))
21768 (add-text-properties 0 3 (list 'sref sref) safe)
21769 (setcdr e (replace-match safe t t (cdr e)))))
21770 (while (string-match re string)
21771 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21772 (cdr e)))
21773 (setq string (replace-match rpl t t string))))
21774 (while (setq pchg (next-property-change pchg string))
21775 (let ((sref (get-text-property pchg 'sref string)))
21776 (when (and sref (string-match "SREF" string pchg))
21777 (setq string (replace-match sref t t string)))))
21778 string))
21780 ;;; TODO: Only called once, from ox-odt which should probably use
21781 ;;; org-export-inline-image-p or something.
21782 (defun org-file-image-p (file)
21783 "Return non-nil if FILE is an image."
21784 (save-match-data
21785 (string-match (image-file-name-regexp) file)))
21787 (defun org-get-cursor-date (&optional with-time)
21788 "Return the date at cursor in as a time.
21789 This works in the calendar and in the agenda, anywhere else it just
21790 returns the current time.
21791 If WITH-TIME is non-nil, returns the time of the event at point (in
21792 the agenda) or the current time of the day."
21793 (let (date day defd tp hod mod)
21794 (when with-time
21795 (setq tp (get-text-property (point) 'time))
21796 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21797 (setq hod (string-to-number (match-string 1 tp))
21798 mod (string-to-number (match-string 2 tp))))
21799 (or tp (let ((now (decode-time)))
21800 (setq hod (nth 2 now)
21801 mod (nth 1 now)))))
21802 (cond
21803 ((eq major-mode 'calendar-mode)
21804 (setq date (calendar-cursor-to-date)
21805 defd (encode-time 0 (or mod 0) (or hod 0)
21806 (nth 1 date) (nth 0 date) (nth 2 date))))
21807 ((eq major-mode 'org-agenda-mode)
21808 (setq day (get-text-property (point) 'day))
21809 (when day
21810 (setq date (calendar-gregorian-from-absolute day)
21811 defd (encode-time 0 (or mod 0) (or hod 0)
21812 (nth 1 date) (nth 0 date) (nth 2 date))))))
21813 (or defd (current-time))))
21815 (defun org-mark-subtree (&optional up)
21816 "Mark the current subtree.
21817 This puts point at the start of the current subtree, and mark at
21818 the end. If a numeric prefix UP is given, move up into the
21819 hierarchy of headlines by UP levels before marking the subtree."
21820 (interactive "P")
21821 (org-with-limited-levels
21822 (cond ((org-at-heading-p) (beginning-of-line))
21823 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21824 (t (outline-previous-visible-heading 1))))
21825 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21826 (if (called-interactively-p 'any)
21827 (call-interactively 'org-mark-element)
21828 (org-mark-element)))
21830 (defun org-file-newer-than-p (file time)
21831 "Non-nil if FILE is newer than TIME.
21832 FILE is a filename, as a string, TIME is a list of integers, as
21833 returned by, e.g., `current-time'."
21834 (and (file-exists-p file)
21835 ;; Only compare times up to whole seconds as some file-systems
21836 ;; (e.g. HFS+) do not retain any finer granularity. As
21837 ;; a consequence, make sure we return non-nil when the two
21838 ;; times are equal.
21839 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21840 (cl-subseq time 0 2)))))
21842 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21843 "Compile a SOURCE file using PROCESS.
21845 PROCESS is either a function or a list of shell commands, as
21846 strings. EXT is a file extension, without the leading dot, as
21847 a string. It is used to check if the process actually succeeded.
21849 PROCESS must create a file with the same base name and directory
21850 as SOURCE, but ending with EXT. The function then returns its
21851 filename. Otherwise, it raises an error. The error message can
21852 then be refined by providing string ERR-MSG, which is appended to
21853 the standard message.
21855 If PROCESS is a function, it is called with a single argument:
21856 the SOURCE file.
21858 If it is a list of commands, each of them is called using
21859 `shell-command'. By default, in each command, %b, %f, %F, %o and
21860 %O are replaced with, respectively, SOURCE base name, name, full
21861 name, directory and absolute output file name. It is possible,
21862 however, to use more place-holders by specifying them in optional
21863 argument SPEC, as an alist following the pattern
21865 (CHARACTER . REPLACEMENT-STRING).
21867 When PROCESS is a list of commands, optional argument LOG-BUF can
21868 be set to a buffer or a buffer name. `shell-command' then uses
21869 it for output."
21870 (let* ((base-name (file-name-base source))
21871 (full-name (file-truename source))
21872 (out-dir (or (file-name-directory source) "./"))
21873 (output (expand-file-name (concat base-name "." ext) out-dir))
21874 (time (current-time))
21875 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21876 (save-window-excursion
21877 (pcase process
21878 ((pred functionp) (funcall process (shell-quote-argument source)))
21879 ((pred consp)
21880 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21881 (spec (append spec
21882 `((?b . ,(shell-quote-argument base-name))
21883 (?f . ,(shell-quote-argument source))
21884 (?F . ,(shell-quote-argument full-name))
21885 (?o . ,(shell-quote-argument out-dir))
21886 (?O . ,(shell-quote-argument output))))))
21887 (dolist (command process)
21888 (shell-command (format-spec command spec) log-buf))
21889 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21890 (_ (error "No valid command to process %S%s" source err-msg))))
21891 ;; Check for process failure. Output file is expected to be
21892 ;; located in the same directory as SOURCE.
21893 (unless (org-file-newer-than-p output time)
21894 (error (format "File %S wasn't produced%s" output err-msg)))
21895 output))
21897 ;;; Indentation
21899 (defvar org-element-greater-elements)
21900 (defun org--get-expected-indentation (element contentsp)
21901 "Expected indentation column for current line, according to ELEMENT.
21902 ELEMENT is an element containing point. CONTENTSP is non-nil
21903 when indentation is to be computed according to contents of
21904 ELEMENT."
21905 (let ((type (org-element-type element))
21906 (start (org-element-property :begin element))
21907 (post-affiliated (org-element-property :post-affiliated element)))
21908 (org-with-wide-buffer
21909 (cond
21910 (contentsp
21911 (cl-case type
21912 ((diary-sexp footnote-definition) 0)
21913 ((headline inlinetask nil)
21914 (if (not org-adapt-indentation) 0
21915 (let ((level (org-current-level)))
21916 (if level (1+ level) 0))))
21917 ((item plain-list) (org-list-item-body-column post-affiliated))
21919 (goto-char start)
21920 (org-get-indentation))))
21921 ((memq type '(headline inlinetask nil))
21922 (if (org-match-line "[ \t]*$")
21923 (org--get-expected-indentation element t)
21925 ((memq type '(diary-sexp footnote-definition)) 0)
21926 ;; First paragraph of a footnote definition or an item.
21927 ;; Indent like parent.
21928 ((< (line-beginning-position) start)
21929 (org--get-expected-indentation
21930 (org-element-property :parent element) t))
21931 ;; At first line: indent according to previous sibling, if any,
21932 ;; ignoring footnote definitions and inline tasks, or parent's
21933 ;; contents.
21934 ((= (line-beginning-position) start)
21935 (catch 'exit
21936 (while t
21937 (if (= (point-min) start) (throw 'exit 0)
21938 (goto-char (1- start))
21939 (let* ((previous (org-element-at-point))
21940 (parent previous))
21941 (while (and parent (<= (org-element-property :end parent) start))
21942 (setq previous parent
21943 parent (org-element-property :parent parent)))
21944 (cond
21945 ((not previous) (throw 'exit 0))
21946 ((> (org-element-property :end previous) start)
21947 (throw 'exit (org--get-expected-indentation previous t)))
21948 ((memq (org-element-type previous)
21949 '(footnote-definition inlinetask))
21950 (setq start (org-element-property :begin previous)))
21951 (t (goto-char (org-element-property :begin previous))
21952 (throw 'exit
21953 (if (bolp) (org-get-indentation)
21954 ;; At first paragraph in an item or
21955 ;; a footnote definition.
21956 (org--get-expected-indentation
21957 (org-element-property :parent previous) t))))))))))
21958 ;; Otherwise, move to the first non-blank line above.
21960 (beginning-of-line)
21961 (let ((pos (point)))
21962 (skip-chars-backward " \r\t\n")
21963 (cond
21964 ;; Two blank lines end a footnote definition or a plain
21965 ;; list. When we indent an empty line after them, the
21966 ;; containing list or footnote definition is over, so it
21967 ;; qualifies as a previous sibling. Therefore, we indent
21968 ;; like its first line.
21969 ((and (memq type '(footnote-definition plain-list))
21970 (> (count-lines (point) pos) 2))
21971 (goto-char start)
21972 (org-get-indentation))
21973 ;; Line above is the first one of a paragraph at the
21974 ;; beginning of an item or a footnote definition. Indent
21975 ;; like parent.
21976 ((< (line-beginning-position) start)
21977 (org--get-expected-indentation
21978 (org-element-property :parent element) t))
21979 ;; Line above is the beginning of an element, i.e., point
21980 ;; was originally on the blank lines between element's start
21981 ;; and contents.
21982 ((= (line-beginning-position) post-affiliated)
21983 (org--get-expected-indentation element t))
21984 ;; POS is after contents in a greater element. Indent like
21985 ;; the beginning of the element.
21986 ((and (memq type org-element-greater-elements)
21987 (let ((cend (org-element-property :contents-end element)))
21988 (and cend (<= cend pos))))
21989 ;; As a special case, if point is at the end of a footnote
21990 ;; definition or an item, indent like the very last element
21991 ;; within. If that last element is an item, indent like
21992 ;; its contents.
21993 (if (memq type '(footnote-definition item plain-list))
21994 (let ((last (org-element-at-point)))
21995 (goto-char pos)
21996 (org--get-expected-indentation
21997 last (eq (org-element-type last) 'item)))
21998 (goto-char start)
21999 (org-get-indentation)))
22000 ;; In any other case, indent like the current line.
22001 (t (org-get-indentation)))))))))
22003 (defun org--align-node-property ()
22004 "Align node property at point.
22005 Alignment is done according to `org-property-format', which see."
22006 (when (save-excursion
22007 (beginning-of-line)
22008 (looking-at org-property-re))
22009 (replace-match
22010 (concat (match-string 4)
22011 (org-trim
22012 (format org-property-format (match-string 1) (match-string 3))))
22013 t t)))
22015 (defun org-indent-line ()
22016 "Indent line depending on context.
22018 Indentation is done according to the following rules:
22020 - Footnote definitions, diary sexps, headlines and inline tasks
22021 have to start at column 0.
22023 - On the very first line of an element, consider, in order, the
22024 next rules until one matches:
22026 1. If there's a sibling element before, ignoring footnote
22027 definitions and inline tasks, indent like its first line.
22029 2. If element has a parent, indent like its contents. More
22030 precisely, if parent is an item, indent after the
22031 description part, if any, or the bullet (see
22032 `org-list-description-max-indent'). Else, indent like
22033 parent's first line.
22035 3. Otherwise, indent relatively to current level, if
22036 `org-adapt-indentation' is non-nil, or to left margin.
22038 - On a blank line at the end of an element, indent according to
22039 the type of the element. More precisely
22041 1. If element is a plain list, an item, or a footnote
22042 definition, indent like the very last element within.
22044 2. If element is a paragraph, indent like its last non blank
22045 line.
22047 3. Otherwise, indent like its very first line.
22049 - In the code part of a source block, use language major mode
22050 to indent current line if `org-src-tab-acts-natively' is
22051 non-nil. If it is nil, do nothing.
22053 - Otherwise, indent like the first non-blank line above.
22055 The function doesn't indent an item as it could break the whole
22056 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22057 `\\[org-shiftmetaright]'.
22059 Also align node properties according to `org-property-format'."
22060 (interactive)
22061 (cond
22062 (orgstruct-is-++
22063 (let ((indent-line-function
22064 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22065 (indent-according-to-mode)))
22066 ((org-at-heading-p) 'noindent)
22068 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22069 (type (org-element-type element)))
22070 (cond ((and (memq type '(plain-list item))
22071 (= (line-beginning-position)
22072 (org-element-property :post-affiliated element)))
22073 'noindent)
22074 ((and (eq type 'latex-environment)
22075 (>= (point) (org-element-property :post-affiliated element))
22076 (< (point) (org-with-wide-buffer
22077 (goto-char (org-element-property :end element))
22078 (skip-chars-backward " \r\t\n")
22079 (line-beginning-position 2))))
22080 'noindent)
22081 ((and (eq type 'src-block)
22082 org-src-tab-acts-natively
22083 (> (line-beginning-position)
22084 (org-element-property :post-affiliated element))
22085 (< (line-beginning-position)
22086 (org-with-wide-buffer
22087 (goto-char (org-element-property :end element))
22088 (skip-chars-backward " \r\t\n")
22089 (line-beginning-position))))
22090 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22092 (let ((column (org--get-expected-indentation element nil)))
22093 ;; Preserve current column.
22094 (if (<= (current-column) (current-indentation))
22095 (indent-line-to column)
22096 (save-excursion (indent-line-to column))))
22097 ;; Align node property. Also preserve current column.
22098 (when (eq type 'node-property)
22099 (let ((column (current-column)))
22100 (org--align-node-property)
22101 (org-move-to-column column)))))))))
22103 (defun org-indent-region (start end)
22104 "Indent each non-blank line in the region.
22105 Called from a program, START and END specify the region to
22106 indent. The function will not indent contents of example blocks,
22107 verse blocks and export blocks as leading white spaces are
22108 assumed to be significant there."
22109 (interactive "r")
22110 (save-excursion
22111 (goto-char start)
22112 (skip-chars-forward " \r\t\n")
22113 (unless (eobp) (beginning-of-line))
22114 (let ((indent-to
22115 (lambda (ind pos)
22116 ;; Set IND as indentation for all lines between point and
22117 ;; POS. Blank lines are ignored. Leave point after POS
22118 ;; once done.
22119 (let ((limit (copy-marker pos)))
22120 (while (< (point) limit)
22121 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22122 (forward-line))
22123 (set-marker limit nil))))
22124 (end (copy-marker end)))
22125 (while (< (point) end)
22126 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22127 (let* ((element (org-element-at-point))
22128 (type (org-element-type element))
22129 (element-end (copy-marker (org-element-property :end element)))
22130 (ind (org--get-expected-indentation element nil)))
22131 (cond
22132 ;; Element indented as a single block. Example blocks
22133 ;; preserving indentation are a special case since the
22134 ;; "contents" must not be indented whereas the block
22135 ;; boundaries can.
22136 ((or (memq type '(export-block latex-environment))
22137 (and (eq type 'example-block)
22138 (not
22139 (or org-src-preserve-indentation
22140 (org-element-property :preserve-indent element)))))
22141 (let ((offset (- ind (org-get-indentation))))
22142 (unless (zerop offset)
22143 (indent-rigidly (org-element-property :begin element)
22144 (org-element-property :end element)
22145 offset)))
22146 (goto-char element-end))
22147 ;; Elements indented line wise. Be sure to exclude
22148 ;; example blocks (preserving indentation) and source
22149 ;; blocks from this category as they are treated
22150 ;; specially later.
22151 ((or (memq type '(paragraph table table-row))
22152 (not (or (org-element-property :contents-begin element)
22153 (memq type '(example-block src-block)))))
22154 (when (eq type 'node-property)
22155 (org--align-node-property)
22156 (beginning-of-line))
22157 (funcall indent-to ind (min element-end end)))
22158 ;; Elements consisting of three parts: before the
22159 ;; contents, the contents, and after the contents. The
22160 ;; contents are treated specially, according to the
22161 ;; element type, or not indented at all. Other parts are
22162 ;; indented as a single block.
22164 (let* ((post (copy-marker
22165 (org-element-property :post-affiliated element)))
22166 (cbeg
22167 (copy-marker
22168 (cond
22169 ((not (org-element-property :contents-begin element))
22170 ;; Fake contents for source blocks.
22171 (org-with-wide-buffer
22172 (goto-char post)
22173 (line-beginning-position 2)))
22174 ((memq type '(footnote-definition item plain-list))
22175 ;; Contents in these elements could start on
22176 ;; the same line as the beginning of the
22177 ;; element. Make sure we start indenting
22178 ;; from the second line.
22179 (org-with-wide-buffer
22180 (goto-char post)
22181 (end-of-line)
22182 (skip-chars-forward " \r\t\n")
22183 (if (eobp) (point) (line-beginning-position))))
22184 (t (org-element-property :contents-begin element)))))
22185 (cend (copy-marker
22186 (or (org-element-property :contents-end element)
22187 ;; Fake contents for source blocks.
22188 (org-with-wide-buffer
22189 (goto-char element-end)
22190 (skip-chars-backward " \r\t\n")
22191 (line-beginning-position)))
22192 t)))
22193 ;; Do not change items indentation individually as it
22194 ;; might break the list as a whole. On the other
22195 ;; hand, when at a plain list, indent it as a whole.
22196 (cond ((eq type 'plain-list)
22197 (let ((offset (- ind (org-get-indentation))))
22198 (unless (zerop offset)
22199 (indent-rigidly (org-element-property :begin element)
22200 (org-element-property :end element)
22201 offset))
22202 (goto-char cbeg)))
22203 ((eq type 'item) (goto-char cbeg))
22204 (t (funcall indent-to ind (min cbeg end))))
22205 (when (< (point) end)
22206 (cl-case type
22207 ((example-block verse-block))
22208 (src-block
22209 ;; In a source block, indent source code
22210 ;; according to language major mode, but only if
22211 ;; `org-src-tab-acts-natively' is non-nil.
22212 (when (and (< (point) end) org-src-tab-acts-natively)
22213 (ignore-errors
22214 (org-babel-do-in-edit-buffer
22215 (indent-region (point-min) (point-max))))))
22216 (t (org-indent-region (point) (min cend end))))
22217 (goto-char (min cend end))
22218 (when (< (point) end)
22219 (funcall indent-to ind (min element-end end))))
22220 (set-marker post nil)
22221 (set-marker cbeg nil)
22222 (set-marker cend nil))))
22223 (set-marker element-end nil))))
22224 (set-marker end nil))))
22226 (defun org-indent-drawer ()
22227 "Indent the drawer at point."
22228 (interactive)
22229 (unless (save-excursion
22230 (beginning-of-line)
22231 (looking-at-p org-drawer-regexp))
22232 (user-error "Not at a drawer"))
22233 (let ((element (org-element-at-point)))
22234 (unless (memq (org-element-type element) '(drawer property-drawer))
22235 (user-error "Not at a drawer"))
22236 (org-with-wide-buffer
22237 (org-indent-region (org-element-property :begin element)
22238 (org-element-property :end element))))
22239 (message "Drawer at point indented"))
22241 (defun org-indent-block ()
22242 "Indent the block at point."
22243 (interactive)
22244 (unless (save-excursion
22245 (beginning-of-line)
22246 (let ((case-fold-search t))
22247 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22248 (user-error "Not at a block"))
22249 (let ((element (org-element-at-point)))
22250 (unless (memq (org-element-type element)
22251 '(comment-block center-block dynamic-block example-block
22252 export-block quote-block special-block
22253 src-block verse-block))
22254 (user-error "Not at a block"))
22255 (org-with-wide-buffer
22256 (org-indent-region (org-element-property :begin element)
22257 (org-element-property :end element))))
22258 (message "Block at point indented"))
22261 ;;; Filling
22263 ;; We use our own fill-paragraph and auto-fill functions.
22265 ;; `org-fill-paragraph' relies on adaptive filling and context
22266 ;; checking. Appropriate `fill-prefix' is computed with
22267 ;; `org-adaptive-fill-function'.
22269 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22270 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22271 ;; `org-adaptive-fill-function' value. Internally,
22272 ;; `org-comment-line-break-function' breaks the line.
22274 ;; `org-setup-filling' installs filling and auto-filling related
22275 ;; variables during `org-mode' initialization.
22277 (defun org-setup-filling ()
22278 (require 'org-element)
22279 ;; Prevent auto-fill from inserting unwanted new items.
22280 (when (boundp 'fill-nobreak-predicate)
22281 (setq-local
22282 fill-nobreak-predicate
22283 (org-uniquify
22284 (append fill-nobreak-predicate
22285 '(org-fill-line-break-nobreak-p
22286 org-fill-n-macro-as-item-nobreak-p
22287 org-fill-paragraph-with-timestamp-nobreak-p)))))
22288 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22289 (setq-local paragraph-start paragraph-ending)
22290 (setq-local paragraph-separate paragraph-ending))
22291 (setq-local fill-paragraph-function 'org-fill-paragraph)
22292 (setq-local auto-fill-inhibit-regexp nil)
22293 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22294 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22295 (setq-local comment-line-break-function 'org-comment-line-break-function))
22297 (defun org-fill-line-break-nobreak-p ()
22298 "Non-nil when a new line at point would create an Org line break."
22299 (save-excursion
22300 (skip-chars-backward "[ \t]")
22301 (skip-chars-backward "\\\\")
22302 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22304 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22305 "Non-nil when a new line at point would split a timestamp."
22306 (and (org-at-timestamp-p 'lax)
22307 (not (looking-at org-ts-regexp-both))))
22309 (defun org-fill-n-macro-as-item-nobreak-p ()
22310 "Non-nil when a new line at point would create a new list."
22311 ;; During export, a "n" macro followed by a dot or a closing
22312 ;; parenthesis can end up being parsed as a new list item.
22313 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22315 (declare-function message-in-body-p "message" ())
22316 (defvar orgtbl-line-start-regexp) ; From org-table.el
22317 (defun org-adaptive-fill-function ()
22318 "Compute a fill prefix for the current line.
22319 Return fill prefix, as a string, or nil if current line isn't
22320 meant to be filled. For convenience, if `adaptive-fill-regexp'
22321 matches in paragraphs or comments, use it."
22322 (catch 'exit
22323 (when (derived-mode-p 'message-mode)
22324 (save-excursion
22325 (beginning-of-line)
22326 (cond ((not (message-in-body-p)) (throw 'exit nil))
22327 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22328 ((looking-at message-cite-prefix-regexp)
22329 (throw 'exit (match-string-no-properties 0)))
22330 ((looking-at org-outline-regexp)
22331 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22332 (org-with-wide-buffer
22333 (unless (org-at-heading-p)
22334 (let* ((p (line-beginning-position))
22335 (element (save-excursion
22336 (beginning-of-line)
22337 (org-element-at-point)))
22338 (type (org-element-type element))
22339 (post-affiliated (org-element-property :post-affiliated element)))
22340 (unless (< p post-affiliated)
22341 (cl-case type
22342 (comment
22343 (save-excursion
22344 (beginning-of-line)
22345 (looking-at "[ \t]*")
22346 (concat (match-string 0) "# ")))
22347 (footnote-definition "")
22348 ((item plain-list)
22349 (make-string (org-list-item-body-column post-affiliated) ?\s))
22350 (paragraph
22351 ;; Fill prefix is usually the same as the current line,
22352 ;; unless the paragraph is at the beginning of an item.
22353 (let ((parent (org-element-property :parent element)))
22354 (save-excursion
22355 (beginning-of-line)
22356 (cond ((eq (org-element-type parent) 'item)
22357 (make-string (org-list-item-body-column
22358 (org-element-property :begin parent))
22359 ?\s))
22360 ((and adaptive-fill-regexp
22361 ;; Locally disable
22362 ;; `adaptive-fill-function' to let
22363 ;; `fill-context-prefix' handle
22364 ;; `adaptive-fill-regexp' variable.
22365 (let (adaptive-fill-function)
22366 (fill-context-prefix
22367 post-affiliated
22368 (org-element-property :end element)))))
22369 ((looking-at "[ \t]+") (match-string 0))
22370 (t "")))))
22371 (comment-block
22372 ;; Only fill contents if P is within block boundaries.
22373 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22374 (forward-line)
22375 (point)))
22376 (cend (save-excursion
22377 (goto-char (org-element-property :end element))
22378 (skip-chars-backward " \r\t\n")
22379 (line-beginning-position))))
22380 (when (and (>= p cbeg) (< p cend))
22381 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22382 (match-string 0)
22383 "")))))))))))
22385 (declare-function message-goto-body "message" ())
22386 (defvar message-cite-prefix-regexp) ; From message.el
22388 (defun org-fill-element (&optional justify)
22389 "Fill element at point, when applicable.
22391 This function only applies to comment blocks, comments, example
22392 blocks and paragraphs. Also, as a special case, re-align table
22393 when point is at one.
22395 If JUSTIFY is non-nil (interactively, with prefix argument),
22396 justify as well. If `sentence-end-double-space' is non-nil, then
22397 period followed by one space does not end a sentence, so don't
22398 break a line there. The variable `fill-column' controls the
22399 width for filling.
22401 For convenience, when point is at a plain list, an item or
22402 a footnote definition, try to fill the first paragraph within."
22403 (with-syntax-table org-mode-transpose-word-syntax-table
22404 ;; Move to end of line in order to get the first paragraph within
22405 ;; a plain list or a footnote definition.
22406 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22407 ;; First check if point is in a blank line at the beginning of
22408 ;; the buffer. In that case, ignore filling.
22409 (cl-case (org-element-type element)
22410 ;; Use major mode filling function is src blocks.
22411 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22412 ;; Align Org tables, leave table.el tables as-is.
22413 (table-row (org-table-align) t)
22414 (table
22415 (when (eq (org-element-property :type element) 'org)
22416 (save-excursion
22417 (goto-char (org-element-property :post-affiliated element))
22418 (org-table-align)))
22420 (paragraph
22421 ;; Paragraphs may contain `line-break' type objects.
22422 (let ((beg (max (point-min)
22423 (org-element-property :contents-begin element)))
22424 (end (min (point-max)
22425 (org-element-property :contents-end element))))
22426 ;; Do nothing if point is at an affiliated keyword.
22427 (if (< (line-end-position) beg) t
22428 (when (derived-mode-p 'message-mode)
22429 ;; In `message-mode', do not fill following citation
22430 ;; in current paragraph nor text before message body.
22431 (let ((body-start (save-excursion (message-goto-body))))
22432 (when body-start (setq beg (max body-start beg))))
22433 (when (save-excursion
22434 (re-search-forward
22435 (concat "^" message-cite-prefix-regexp) end t))
22436 (setq end (match-beginning 0))))
22437 ;; Fill paragraph, taking line breaks into account.
22438 (save-excursion
22439 (goto-char beg)
22440 (let ((cuts (list beg)))
22441 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22442 (when (eq 'line-break
22443 (org-element-type
22444 (save-excursion (backward-char)
22445 (org-element-context))))
22446 (push (point) cuts)))
22447 (dolist (c (delq end cuts))
22448 (fill-region-as-paragraph c end justify)
22449 (setq end c))))
22450 t)))
22451 ;; Contents of `comment-block' type elements should be
22452 ;; filled as plain text, but only if point is within block
22453 ;; markers.
22454 (comment-block
22455 (let* ((case-fold-search t)
22456 (beg (save-excursion
22457 (goto-char (org-element-property :begin element))
22458 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22459 (forward-line)
22460 (point)))
22461 (end (save-excursion
22462 (goto-char (org-element-property :end element))
22463 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22464 (line-beginning-position))))
22465 (if (or (< (point) beg) (> (point) end)) t
22466 (fill-region-as-paragraph
22467 (save-excursion (end-of-line)
22468 (re-search-backward "^[ \t]*$" beg 'move)
22469 (line-beginning-position))
22470 (save-excursion (beginning-of-line)
22471 (re-search-forward "^[ \t]*$" end 'move)
22472 (line-beginning-position))
22473 justify))))
22474 ;; Fill comments.
22475 (comment
22476 (let ((begin (org-element-property :post-affiliated element))
22477 (end (org-element-property :end element)))
22478 (when (and (>= (point) begin) (<= (point) end))
22479 (let ((begin (save-excursion
22480 (end-of-line)
22481 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22482 (progn (forward-line) (point))
22483 begin)))
22484 (end (save-excursion
22485 (end-of-line)
22486 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22487 (1- (line-beginning-position))
22488 (skip-chars-backward " \r\t\n")
22489 (line-end-position)))))
22490 ;; Do not fill comments when at a blank line.
22491 (when (> end begin)
22492 (let ((fill-prefix
22493 (save-excursion
22494 (beginning-of-line)
22495 (looking-at "[ \t]*#")
22496 (let ((comment-prefix (match-string 0)))
22497 (goto-char (match-end 0))
22498 (if (looking-at adaptive-fill-regexp)
22499 (concat comment-prefix (match-string 0))
22500 (concat comment-prefix " "))))))
22501 (save-excursion
22502 (fill-region-as-paragraph begin end justify))))))
22504 ;; Ignore every other element.
22505 (otherwise t)))))
22507 (defun org-fill-paragraph (&optional justify region)
22508 "Fill element at point, when applicable.
22510 This function only applies to comment blocks, comments, example
22511 blocks and paragraphs. Also, as a special case, re-align table
22512 when point is at one.
22514 For convenience, when point is at a plain list, an item or
22515 a footnote definition, try to fill the first paragraph within.
22517 If JUSTIFY is non-nil (interactively, with prefix argument),
22518 justify as well. If `sentence-end-double-space' is non-nil, then
22519 period followed by one space does not end a sentence, so don't
22520 break a line there. The variable `fill-column' controls the
22521 width for filling.
22523 The REGION argument is non-nil if called interactively; in that
22524 case, if Transient Mark mode is enabled and the mark is active,
22525 fill each of the elements in the active region, instead of just
22526 filling the current element."
22527 (interactive (progn
22528 (barf-if-buffer-read-only)
22529 (list (if current-prefix-arg 'full) t)))
22530 (cond
22531 ((and (derived-mode-p 'message-mode)
22532 (or (not (message-in-body-p))
22533 (save-excursion (move-beginning-of-line 1)
22534 (looking-at message-cite-prefix-regexp))))
22535 ;; First ensure filling is correct in message-mode.
22536 (let ((fill-paragraph-function
22537 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22538 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22539 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22540 (paragraph-separate
22541 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22542 (fill-paragraph nil)))
22543 ((and region transient-mark-mode mark-active
22544 (not (eq (region-beginning) (region-end))))
22545 (let ((origin (point-marker))
22546 (start (region-beginning)))
22547 (unwind-protect
22548 (progn
22549 (goto-char (region-end))
22550 (while (> (point) start)
22551 (org-backward-paragraph)
22552 (org-fill-element justify)))
22553 (goto-char origin)
22554 (set-marker origin nil))))
22555 (t (org-fill-element justify))))
22556 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22558 (defun org-auto-fill-function ()
22559 "Auto-fill function."
22560 ;; Check if auto-filling is meaningful.
22561 (let ((fc (current-fill-column)))
22562 (when (and fc (> (current-column) fc))
22563 (let* ((fill-prefix (org-adaptive-fill-function))
22564 ;; Enforce empty fill prefix, if required. Otherwise, it
22565 ;; will be computed again.
22566 (adaptive-fill-mode (not (equal fill-prefix ""))))
22567 (when fill-prefix (do-auto-fill))))))
22569 (defun org-comment-line-break-function (&optional soft)
22570 "Break line at point and indent, continuing comment if within one.
22571 The inserted newline is marked hard if variable
22572 `use-hard-newlines' is true, unless optional argument SOFT is
22573 non-nil."
22574 (if soft (insert-and-inherit ?\n) (newline 1))
22575 (save-excursion (forward-char -1) (delete-horizontal-space))
22576 (delete-horizontal-space)
22577 (indent-to-left-margin)
22578 (insert-before-markers-and-inherit fill-prefix))
22581 ;;; Fixed Width Areas
22583 (defun org-toggle-fixed-width ()
22584 "Toggle fixed-width markup.
22586 Add or remove fixed-width markup on current line, whenever it
22587 makes sense. Return an error otherwise.
22589 If a region is active and if it contains only fixed-width areas
22590 or blank lines, remove all fixed-width markup in it. If the
22591 region contains anything else, convert all non-fixed-width lines
22592 to fixed-width ones.
22594 Blank lines at the end of the region are ignored unless the
22595 region only contains such lines."
22596 (interactive)
22597 (if (not (org-region-active-p))
22598 ;; No region:
22600 ;; Remove fixed width marker only in a fixed-with element.
22602 ;; Add fixed width maker in paragraphs, in blank lines after
22603 ;; elements or at the beginning of a headline or an inlinetask,
22604 ;; and before any one-line elements (e.g., a clock).
22605 (progn
22606 (beginning-of-line)
22607 (let* ((element (org-element-at-point))
22608 (type (org-element-type element)))
22609 (cond
22610 ((and (eq type 'fixed-width)
22611 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22612 (replace-match
22613 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22614 ((and (memq type '(babel-call clock comment diary-sexp headline
22615 horizontal-rule keyword paragraph
22616 planning))
22617 (<= (org-element-property :post-affiliated element) (point)))
22618 (skip-chars-forward " \t")
22619 (insert ": "))
22620 ((and (looking-at-p "[ \t]*$")
22621 (or (eq type 'inlinetask)
22622 (save-excursion
22623 (skip-chars-forward " \r\t\n")
22624 (<= (org-element-property :end element) (point)))))
22625 (delete-region (point) (line-end-position))
22626 (org-indent-line)
22627 (insert ": "))
22628 (t (user-error "Cannot insert a fixed-width line here")))))
22629 ;; Region active.
22630 (let* ((begin (save-excursion
22631 (goto-char (region-beginning))
22632 (line-beginning-position)))
22633 (end (copy-marker
22634 (save-excursion
22635 (goto-char (region-end))
22636 (unless (eolp) (beginning-of-line))
22637 (if (save-excursion (re-search-backward "\\S-" begin t))
22638 (progn (skip-chars-backward " \r\t\n") (point))
22639 (point)))))
22640 (all-fixed-width-p
22641 (catch 'not-all-p
22642 (save-excursion
22643 (goto-char begin)
22644 (skip-chars-forward " \r\t\n")
22645 (when (eobp) (throw 'not-all-p nil))
22646 (while (< (point) end)
22647 (let ((element (org-element-at-point)))
22648 (if (eq (org-element-type element) 'fixed-width)
22649 (goto-char (org-element-property :end element))
22650 (throw 'not-all-p nil))))
22651 t))))
22652 (if all-fixed-width-p
22653 (save-excursion
22654 (goto-char begin)
22655 (while (< (point) end)
22656 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22657 (replace-match
22658 "" nil nil nil
22659 (if (= (line-end-position) (match-end 0)) 0 1)))
22660 (forward-line)))
22661 (let ((min-ind (point-max)))
22662 ;; Find minimum indentation across all lines.
22663 (save-excursion
22664 (goto-char begin)
22665 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22666 (setq min-ind 0)
22667 (catch 'zerop
22668 (while (< (point) end)
22669 (unless (looking-at-p "[ \t]*$")
22670 (let ((ind (org-get-indentation)))
22671 (setq min-ind (min min-ind ind))
22672 (when (zerop ind) (throw 'zerop t))))
22673 (forward-line)))))
22674 ;; Loop over all lines and add fixed-width markup everywhere
22675 ;; but in fixed-width lines.
22676 (save-excursion
22677 (goto-char begin)
22678 (while (< (point) end)
22679 (cond
22680 ((org-at-heading-p)
22681 (insert ": ")
22682 (forward-line)
22683 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22684 (insert ":")
22685 (forward-line)))
22686 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22687 (let* ((element (org-element-at-point))
22688 (element-end (org-element-property :end element)))
22689 (if (eq (org-element-type element) 'fixed-width)
22690 (progn (goto-char element-end)
22691 (skip-chars-backward " \r\t\n")
22692 (forward-line))
22693 (let ((limit (min end element-end)))
22694 (while (< (point) limit)
22695 (org-move-to-column min-ind t)
22696 (insert ": ")
22697 (forward-line))))))
22699 (org-move-to-column min-ind t)
22700 (insert ": ")
22701 (forward-line)))))))
22702 (set-marker end nil))))
22705 ;;; Comments
22707 ;; Org comments syntax is quite complex. It requires the entire line
22708 ;; to be just a comment. Also, even with the right syntax at the
22709 ;; beginning of line, some elements (e.g., verse-block or
22710 ;; example-block) don't accept comments. Usual Emacs comment commands
22711 ;; cannot cope with those requirements. Therefore, Org replaces them.
22713 ;; Org still relies on `comment-dwim', but cannot trust
22714 ;; `comment-only-p'. So, `comment-region-function' and
22715 ;; `uncomment-region-function' both point
22716 ;; to`org-comment-or-uncomment-region'. Eventually,
22717 ;; `org-insert-comment' takes care of insertion of comments at the
22718 ;; beginning of line.
22720 ;; `org-setup-comments-handling' install comments related variables
22721 ;; during `org-mode' initialization.
22723 (defun org-setup-comments-handling ()
22724 (interactive)
22725 (setq-local comment-use-syntax nil)
22726 (setq-local comment-start "# ")
22727 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22728 (setq-local comment-insert-comment-function 'org-insert-comment)
22729 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22730 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22732 (defun org-insert-comment ()
22733 "Insert an empty comment above current line.
22734 If the line is empty, insert comment at its beginning. When
22735 point is within a source block, comment according to the related
22736 major mode."
22737 (if (let ((element (org-element-at-point)))
22738 (and (eq (org-element-type element) 'src-block)
22739 (< (save-excursion
22740 (goto-char (org-element-property :post-affiliated element))
22741 (line-end-position))
22742 (point))
22743 (> (save-excursion
22744 (goto-char (org-element-property :end element))
22745 (skip-chars-backward " \r\t\n")
22746 (line-beginning-position))
22747 (point))))
22748 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22749 (beginning-of-line)
22750 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22751 (open-line 1))
22752 (org-indent-line)
22753 (insert "# ")))
22755 (defvar comment-empty-lines) ; From newcomment.el.
22756 (defun org-comment-or-uncomment-region (beg end &rest _)
22757 "Comment or uncomment each non-blank line in the region.
22758 Uncomment each non-blank line between BEG and END if it only
22759 contains commented lines. Otherwise, comment them. If region is
22760 strictly within a source block, use appropriate comment syntax."
22761 (if (let ((element (org-element-at-point)))
22762 (and (eq (org-element-type element) 'src-block)
22763 (< (save-excursion
22764 (goto-char (org-element-property :post-affiliated element))
22765 (line-end-position))
22766 beg)
22767 (>= (save-excursion
22768 (goto-char (org-element-property :end element))
22769 (skip-chars-backward " \r\t\n")
22770 (line-beginning-position))
22771 end)))
22772 ;; Translate region boundaries for the Org buffer to the source
22773 ;; buffer.
22774 (let ((offset (- end beg)))
22775 (save-excursion
22776 (goto-char beg)
22777 (org-babel-do-in-edit-buffer
22778 (comment-or-uncomment-region (point) (+ offset (point))))))
22779 (save-restriction
22780 ;; Restrict region
22781 (narrow-to-region (save-excursion (goto-char beg)
22782 (skip-chars-forward " \r\t\n" end)
22783 (line-beginning-position))
22784 (save-excursion (goto-char end)
22785 (skip-chars-backward " \r\t\n" beg)
22786 (line-end-position)))
22787 (let ((uncommentp
22788 ;; UNCOMMENTP is non-nil when every non blank line between
22789 ;; BEG and END is a comment.
22790 (save-excursion
22791 (goto-char (point-min))
22792 (while (and (not (eobp))
22793 (let ((element (org-element-at-point)))
22794 (and (eq (org-element-type element) 'comment)
22795 (goto-char (min (point-max)
22796 (org-element-property
22797 :end element)))))))
22798 (eobp))))
22799 (if uncommentp
22800 ;; Only blank lines and comments in region: uncomment it.
22801 (save-excursion
22802 (goto-char (point-min))
22803 (while (not (eobp))
22804 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22805 (replace-match "" nil nil nil 1))
22806 (forward-line)))
22807 ;; Comment each line in region.
22808 (let ((min-indent (point-max)))
22809 ;; First find the minimum indentation across all lines.
22810 (save-excursion
22811 (goto-char (point-min))
22812 (while (and (not (eobp)) (not (zerop min-indent)))
22813 (unless (looking-at "[ \t]*$")
22814 (setq min-indent (min min-indent (current-indentation))))
22815 (forward-line)))
22816 ;; Then loop over all lines.
22817 (save-excursion
22818 (goto-char (point-min))
22819 (while (not (eobp))
22820 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22821 ;; Don't get fooled by invisible text (e.g. link path)
22822 ;; when moving to column MIN-INDENT.
22823 (let ((buffer-invisibility-spec nil))
22824 (org-move-to-column min-indent t))
22825 (insert comment-start))
22826 (forward-line)))))))))
22828 (defun org-comment-dwim (_arg)
22829 "Call the comment command you mean.
22830 Call `org-toggle-comment' if on a heading, otherwise call
22831 `comment-dwim', within a source edit buffer if needed."
22832 (interactive "*P")
22833 (cond ((org-at-heading-p)
22834 (call-interactively #'org-toggle-comment))
22835 ((org-in-src-block-p)
22836 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22837 (t (call-interactively #'comment-dwim))))
22840 ;;; Timestamps API
22842 ;; This section contains tools to operate on timestamp objects, as
22843 ;; returned by, e.g. `org-element-context'.
22845 (defun org-timestamp--to-internal-time (timestamp &optional end)
22846 "Encode TIMESTAMP object into Emacs internal time.
22847 Use end of date range or time range when END is non-nil."
22848 (apply #'encode-time
22849 (cons 0
22850 (mapcar
22851 (lambda (prop) (or (org-element-property prop timestamp) 0))
22852 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22853 '(:minute-start :hour-start :day-start :month-start
22854 :year-start))))))
22856 (defun org-timestamp-has-time-p (timestamp)
22857 "Non-nil when TIMESTAMP has a time specified."
22858 (org-element-property :hour-start timestamp))
22860 (defun org-timestamp-format (timestamp format &optional end utc)
22861 "Format a TIMESTAMP object into a string.
22863 FORMAT is a format specifier to be passed to
22864 `format-time-string'.
22866 When optional argument END is non-nil, use end of date-range or
22867 time-range, if possible.
22869 When optional argument UTC is non-nil, time will be expressed as
22870 Universal Time."
22871 (format-time-string
22872 format (org-timestamp--to-internal-time timestamp end)
22873 (and utc t)))
22875 (defun org-timestamp-split-range (timestamp &optional end)
22876 "Extract a TIMESTAMP object from a date or time range.
22878 END, when non-nil, means extract the end of the range.
22879 Otherwise, extract its start.
22881 Return a new timestamp object."
22882 (let ((type (org-element-property :type timestamp)))
22883 (if (memq type '(active inactive diary)) timestamp
22884 (let ((split-ts (org-element-copy timestamp)))
22885 ;; Set new type.
22886 (org-element-put-property
22887 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22888 ;; Copy start properties over end properties if END is
22889 ;; non-nil. Otherwise, copy end properties over `start' ones.
22890 (let ((p-alist '((:minute-start . :minute-end)
22891 (:hour-start . :hour-end)
22892 (:day-start . :day-end)
22893 (:month-start . :month-end)
22894 (:year-start . :year-end))))
22895 (dolist (p-cell p-alist)
22896 (org-element-put-property
22897 split-ts
22898 (funcall (if end #'car #'cdr) p-cell)
22899 (org-element-property
22900 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22901 ;; Eventually refresh `:raw-value'.
22902 (org-element-put-property split-ts :raw-value nil)
22903 (org-element-put-property
22904 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22906 (defun org-timestamp-translate (timestamp &optional boundary)
22907 "Translate TIMESTAMP object to custom format.
22909 Format string is defined in `org-time-stamp-custom-formats',
22910 which see.
22912 When optional argument BOUNDARY is non-nil, it is either the
22913 symbol `start' or `end'. In this case, only translate the
22914 starting or ending part of TIMESTAMP if it is a date or time
22915 range. Otherwise, translate both parts.
22917 Return timestamp as-is if `org-display-custom-times' is nil or if
22918 it has a `diary' type."
22919 (let ((type (org-element-property :type timestamp)))
22920 (if (or (not org-display-custom-times) (eq type 'diary))
22921 (org-element-interpret-data timestamp)
22922 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22923 org-time-stamp-custom-formats)))
22924 (if (and (not boundary) (memq type '(active-range inactive-range)))
22925 (concat (org-timestamp-format timestamp fmt)
22926 "--"
22927 (org-timestamp-format timestamp fmt t))
22928 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22932 ;;; Other stuff.
22934 (defvar reftex-docstruct-symbol)
22935 (defvar org--rds)
22937 (defun org-reftex-citation ()
22938 "Use reftex-citation to insert a citation into the buffer.
22939 This looks for a line like
22941 #+BIBLIOGRAPHY: foo plain option:-d
22943 and derives from it that foo.bib is the bibliography file relevant
22944 for this document. It then installs the necessary environment for RefTeX
22945 to work in this buffer and calls `reftex-citation' to insert a citation
22946 into the buffer.
22948 Export of such citations to both LaTeX and HTML is handled by the contributed
22949 package ox-bibtex by Taru Karttunen."
22950 (interactive)
22951 (let ((reftex-docstruct-symbol 'org--rds)
22952 org--rds bib)
22953 (org-with-wide-buffer
22954 (let ((case-fold-search t)
22955 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22956 (if (not (save-excursion
22957 (or (re-search-forward re nil t)
22958 (re-search-backward re nil t))))
22959 (user-error "No bibliography defined in file")
22960 (setq bib (concat (match-string 1) ".bib")
22961 org--rds (list (list 'bib bib))))))
22962 (call-interactively 'reftex-citation)))
22964 ;;;; Functions extending outline functionality
22966 (defun org-beginning-of-line (&optional n)
22967 "Go to the beginning of the current visible line.
22969 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22970 tags on the first attempt, and only move to after the tags when
22971 the cursor is already beyond the end of the headline.
22973 With argument N not nil or 1, move forward N - 1 lines first."
22974 (interactive "^p")
22975 (let ((origin (point))
22976 (special (pcase org-special-ctrl-a/e
22977 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22978 deactivate-mark)
22979 ;; First move to a visible line.
22980 (if (bound-and-true-p visual-line-mode)
22981 (beginning-of-visual-line n)
22982 (move-beginning-of-line n)
22983 ;; `move-beginning-of-line' may leave point after invisible
22984 ;; characters if line starts with such of these (e.g., with
22985 ;; a link at column 0). Really move to the beginning of the
22986 ;; current visible line.
22987 (beginning-of-line))
22988 (cond
22989 ;; No special behavior. Point is already at the beginning of
22990 ;; a line, logical or visual.
22991 ((not special))
22992 ;; `beginning-of-visual-line' left point before logical beginning
22993 ;; of line: point is at the beginning of a visual line. Bail
22994 ;; out.
22995 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22996 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22997 ;; At a headline, special position is before the title, but
22998 ;; after any TODO keyword or priority cookie.
22999 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23000 (line-end-position)))
23001 (bol (point)))
23002 (if (eq special 'reversed)
23003 (when (and (= origin bol) (eq last-command this-command))
23004 (goto-char refpos))
23005 (when (or (> origin refpos) (= origin bol))
23006 (goto-char refpos)))))
23007 ((and (looking-at org-list-full-item-re)
23008 (memq (org-element-type (save-match-data (org-element-at-point)))
23009 '(item plain-list)))
23010 ;; Set special position at first white space character after
23011 ;; bullet, and check-box, if any.
23012 (let ((after-bullet
23013 (let ((box (match-end 3)))
23014 (cond ((not box) (match-end 1))
23015 ((eq (char-after box) ?\s) (1+ box))
23016 (t box)))))
23017 (if (eq special 'reversed)
23018 (when (and (= (point) origin) (eq last-command this-command))
23019 (goto-char after-bullet))
23020 (when (or (> origin after-bullet) (= (point) origin))
23021 (goto-char after-bullet)))))
23022 ;; No special context. Point is already at beginning of line.
23023 (t nil))))
23025 (defun org-end-of-line (&optional n)
23026 "Go to the end of the line, but before ellipsis, if any.
23028 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23029 tags on the first attempt, and only move to after the tags when
23030 the cursor is already beyond the end of the headline.
23032 With argument N not nil or 1, move forward N - 1 lines first."
23033 (interactive "^p")
23034 (let ((origin (point))
23035 (special (pcase org-special-ctrl-a/e
23036 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23037 deactivate-mark)
23038 ;; First move to a visible line.
23039 (if (bound-and-true-p visual-line-mode)
23040 (beginning-of-visual-line n)
23041 (move-beginning-of-line n))
23042 (cond
23043 ;; At a headline, with tags.
23044 ((and special
23045 (save-excursion
23046 (beginning-of-line)
23047 (let ((case-fold-search nil))
23048 (looking-at org-complex-heading-regexp)))
23049 (match-end 5))
23050 (let ((tags (save-excursion
23051 (goto-char (match-beginning 5))
23052 (skip-chars-backward " \t")
23053 (point)))
23054 (visual-end (and (bound-and-true-p visual-line-mode)
23055 (save-excursion
23056 (end-of-visual-line)
23057 (point)))))
23058 ;; If `end-of-visual-line' brings us before end of line or
23059 ;; even tags, i.e., the headline spans over multiple visual
23060 ;; lines, move there.
23061 (cond ((and visual-end
23062 (< visual-end tags)
23063 (<= origin visual-end))
23064 (goto-char visual-end))
23065 ((eq special 'reversed)
23066 (if (and (= origin (line-end-position))
23067 (eq this-command last-command))
23068 (goto-char tags)
23069 (end-of-line)))
23071 (if (or (< origin tags) (= origin (line-end-position)))
23072 (goto-char tags)
23073 (end-of-line))))))
23074 ((bound-and-true-p visual-line-mode)
23075 (let ((bol (line-beginning-position)))
23076 (end-of-visual-line)
23077 ;; If `end-of-visual-line' gets us past the ellipsis at the
23078 ;; end of a line, backtrack and use `end-of-line' instead.
23079 (when (/= bol (line-beginning-position))
23080 (goto-char bol)
23081 (end-of-line))))
23082 (t (end-of-line)))))
23084 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23085 (define-key org-mode-map "\C-e" 'org-end-of-line)
23087 (defun org-backward-sentence (&optional _arg)
23088 "Go to beginning of sentence, or beginning of table field.
23089 This will call `backward-sentence' or `org-table-beginning-of-field',
23090 depending on context."
23091 (interactive)
23092 (let* ((element (org-element-at-point))
23093 (contents-begin (org-element-property :contents-begin element))
23094 (table (org-element-lineage element '(table) t)))
23095 (if (and table
23096 (> (point) contents-begin)
23097 (<= (point) (org-element-property :contents-end table)))
23098 (call-interactively #'org-table-beginning-of-field)
23099 (save-restriction
23100 (when (and contents-begin
23101 (< (point-min) contents-begin)
23102 (> (point) contents-begin))
23103 (narrow-to-region contents-begin
23104 (org-element-property :contents-end element)))
23105 (call-interactively #'backward-sentence)))))
23107 (defun org-forward-sentence (&optional _arg)
23108 "Go to end of sentence, or end of table field.
23109 This will call `forward-sentence' or `org-table-end-of-field',
23110 depending on context."
23111 (interactive)
23112 (if (and (org-at-heading-p)
23113 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23114 (save-restriction
23115 (narrow-to-region (line-beginning-position) (line-end-position))
23116 (call-interactively #'forward-sentence))
23117 (let* ((element (org-element-at-point))
23118 (contents-end (org-element-property :contents-end element))
23119 (table (org-element-lineage element '(table) t)))
23120 (if (and table
23121 (>= (point) (org-element-property :contents-begin table))
23122 (< (point) contents-end))
23123 (call-interactively #'org-table-end-of-field)
23124 (save-restriction
23125 (when (and contents-end
23126 (> (point-max) contents-end)
23127 ;; Skip blank lines between elements.
23128 (< (org-element-property :end element)
23129 (save-excursion (goto-char contents-end)
23130 (skip-chars-forward " \r\t\n"))))
23131 (narrow-to-region (org-element-property :contents-begin element)
23132 contents-end))
23133 ;; End of heading is considered as the end of a sentence.
23134 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23135 (call-interactively #'forward-sentence)))))))
23137 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23138 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23140 (defun org-kill-line (&optional _arg)
23141 "Kill line, to tags or end of line."
23142 (interactive)
23143 (cond
23144 ((or (not org-special-ctrl-k)
23145 (bolp)
23146 (not (org-at-heading-p)))
23147 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23148 org-ctrl-k-protect-subtree
23149 (or (eq org-ctrl-k-protect-subtree 'error)
23150 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23151 (user-error "C-k aborted as it would kill a hidden subtree"))
23152 (call-interactively
23153 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23154 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23155 (kill-region (point) (match-beginning 1))
23156 (org-set-tags nil t))
23157 (t (kill-region (point) (point-at-eol)))))
23159 (define-key org-mode-map "\C-k" 'org-kill-line)
23161 (defun org-yank (&optional arg)
23162 "Yank. If the kill is a subtree, treat it specially.
23163 This command will look at the current kill and check if is a single
23164 subtree, or a series of subtrees[1]. If it passes the test, and if the
23165 cursor is at the beginning of a line or after the stars of a currently
23166 empty headline, then the yank is handled specially. How exactly depends
23167 on the value of the following variables.
23169 `org-yank-folded-subtrees'
23170 By default, this variable is non-nil, which results in
23171 subtree(s) being folded after insertion, except if doing so
23172 would swallow text after the yanked text.
23174 `org-yank-adjusted-subtrees'
23175 When non-nil (the default value is nil), the subtree will be
23176 promoted or demoted in order to fit into the local outline tree
23177 structure, which means that the level will be adjusted so that it
23178 becomes the smaller one of the two *visible* surrounding headings.
23180 Any prefix to this command will cause `yank' to be called directly with
23181 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23182 will just
23183 plainly yank the text as it is.
23185 \[1] The test checks if the first non-white line is a heading
23186 and if there are no other headings with fewer stars."
23187 (interactive "P")
23188 (org-yank-generic 'yank arg))
23190 (defun org-yank-generic (command arg)
23191 "Perform some yank-like command.
23193 This function implements the behavior described in the `org-yank'
23194 documentation. However, it has been generalized to work for any
23195 interactive command with similar behavior."
23197 ;; pretend to be command COMMAND
23198 (setq this-command command)
23200 (if arg
23201 (call-interactively command)
23203 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23204 (and (org-kill-is-subtree-p)
23205 (or (bolp)
23206 (and (looking-at "[ \t]*$")
23207 (string-match
23208 "\\`\\*+\\'"
23209 (buffer-substring (point-at-bol) (point)))))))
23210 swallowp)
23211 (cond
23212 ((and subtreep org-yank-folded-subtrees)
23213 (let ((beg (point))
23214 end)
23215 (if (and subtreep org-yank-adjusted-subtrees)
23216 (org-paste-subtree nil nil 'for-yank)
23217 (call-interactively command))
23219 (setq end (point))
23220 (goto-char beg)
23221 (when (and (bolp) subtreep
23222 (not (setq swallowp
23223 (org-yank-folding-would-swallow-text beg end))))
23224 (org-with-limited-levels
23225 (or (looking-at org-outline-regexp)
23226 (re-search-forward org-outline-regexp-bol end t))
23227 (while (and (< (point) end) (looking-at org-outline-regexp))
23228 (outline-hide-subtree)
23229 (org-cycle-show-empty-lines 'folded)
23230 (condition-case nil
23231 (outline-forward-same-level 1)
23232 (error (goto-char end))))))
23233 (when swallowp
23234 (message
23235 "Inserted text not folded because that would swallow text"))
23237 (goto-char end)
23238 (skip-chars-forward " \t\n\r")
23239 (beginning-of-line 1)
23240 (push-mark beg 'nomsg)))
23241 ((and subtreep org-yank-adjusted-subtrees)
23242 (let ((beg (point-at-bol)))
23243 (org-paste-subtree nil nil 'for-yank)
23244 (push-mark beg 'nomsg)))
23246 (call-interactively command))))))
23248 (defun org-yank-folding-would-swallow-text (beg end)
23249 "Would hide-subtree at BEG swallow any text after END?"
23250 (let (level)
23251 (org-with-limited-levels
23252 (save-excursion
23253 (goto-char beg)
23254 (when (or (looking-at org-outline-regexp)
23255 (re-search-forward org-outline-regexp-bol end t))
23256 (setq level (org-outline-level)))
23257 (goto-char end)
23258 (skip-chars-forward " \t\r\n\v\f")
23259 (not (or (eobp)
23260 (and (bolp) (looking-at-p org-outline-regexp)
23261 (<= (org-outline-level) level))))))))
23263 (define-key org-mode-map "\C-y" 'org-yank)
23265 (defun org-back-to-heading (&optional invisible-ok)
23266 "Call `outline-back-to-heading', but provide a better error message."
23267 (condition-case nil
23268 (outline-back-to-heading invisible-ok)
23269 (error (error "Before first headline at position %d in buffer %s"
23270 (point) (current-buffer)))))
23272 (defun org-before-first-heading-p ()
23273 "Before first heading?"
23274 (save-excursion
23275 (end-of-line)
23276 (null (re-search-backward org-outline-regexp-bol nil t))))
23278 (defun org-at-heading-p (&optional ignored)
23279 (outline-on-heading-p t))
23281 (defun org-in-commented-heading-p (&optional no-inheritance)
23282 "Non-nil if point is under a commented heading.
23283 This function also checks ancestors of the current headline,
23284 unless optional argument NO-INHERITANCE is non-nil."
23285 (cond
23286 ((org-before-first-heading-p) nil)
23287 ((let ((headline (nth 4 (org-heading-components))))
23288 (and headline
23289 (let ((case-fold-search nil))
23290 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23291 headline)))))
23292 (no-inheritance nil)
23294 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23296 (defun org-at-comment-p nil
23297 "Is cursor in a commented line?"
23298 (save-excursion
23299 (save-match-data
23300 (beginning-of-line)
23301 (looking-at "^[ \t]*# "))))
23303 (defun org-at-drawer-p nil
23304 "Is cursor at a drawer keyword?"
23305 (save-excursion
23306 (move-beginning-of-line 1)
23307 (looking-at org-drawer-regexp)))
23309 (defun org-at-block-p nil
23310 "Is cursor at a block keyword?"
23311 (save-excursion
23312 (move-beginning-of-line 1)
23313 (looking-at org-block-regexp)))
23315 (defun org-point-at-end-of-empty-headline ()
23316 "If point is at the end of an empty headline, return t, else nil.
23317 If the heading only contains a TODO keyword, it is still still considered
23318 empty."
23319 (let ((case-fold-search nil))
23320 (and (looking-at "[ \t]*$")
23321 org-todo-line-regexp
23322 (save-excursion
23323 (beginning-of-line)
23324 (looking-at org-todo-line-regexp)
23325 (string= (match-string 3) "")))))
23327 (defun org-at-heading-or-item-p ()
23328 (or (org-at-heading-p) (org-at-item-p)))
23330 (defun org-at-target-p ()
23331 (or (org-in-regexp org-radio-target-regexp)
23332 (org-in-regexp org-target-regexp)))
23333 ;; Compatibility alias with Org versions < 7.8.03
23334 (defalias 'org-on-target-p 'org-at-target-p)
23336 (defun org-up-heading-all (arg)
23337 "Move to the heading line of which the present line is a subheading.
23338 This function considers both visible and invisible heading lines.
23339 With argument, move up ARG levels."
23340 (outline-up-heading arg t))
23342 (defun org-up-heading-safe ()
23343 "Move to the heading line of which the present line is a subheading.
23344 This version will not throw an error. It will return the level of the
23345 headline found, or nil if no higher level is found.
23347 Also, this function will be a lot faster than `outline-up-heading',
23348 because it relies on stars being the outline starters. This can really
23349 make a significant difference in outlines with very many siblings."
23350 (when (ignore-errors (org-back-to-heading t))
23351 (let ((level-up (1- (funcall outline-level))))
23352 (and (> level-up 0)
23353 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23354 (funcall outline-level)))))
23356 (defun org-first-sibling-p ()
23357 "Is this heading the first child of its parents?"
23358 (interactive)
23359 (let ((re org-outline-regexp-bol)
23360 level l)
23361 (unless (org-at-heading-p t)
23362 (user-error "Not at a heading"))
23363 (setq level (funcall outline-level))
23364 (save-excursion
23365 (if (not (re-search-backward re nil t))
23367 (setq l (funcall outline-level))
23368 (< l level)))))
23370 (defun org-goto-sibling (&optional previous)
23371 "Goto the next sibling, even if it is invisible.
23372 When PREVIOUS is set, go to the previous sibling instead. Returns t
23373 when a sibling was found. When none is found, return nil and don't
23374 move point."
23375 (let ((fun (if previous 're-search-backward 're-search-forward))
23376 (pos (point))
23377 (re org-outline-regexp-bol)
23378 level l)
23379 (when (ignore-errors (org-back-to-heading t))
23380 (setq level (funcall outline-level))
23381 (catch 'exit
23382 (or previous (forward-char 1))
23383 (while (funcall fun re nil t)
23384 (setq l (funcall outline-level))
23385 (when (< l level) (goto-char pos) (throw 'exit nil))
23386 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23387 (goto-char pos)
23388 nil))))
23390 (defun org-show-siblings ()
23391 "Show all siblings of the current headline."
23392 (save-excursion
23393 (while (org-goto-sibling) (org-flag-heading nil)))
23394 (save-excursion
23395 (while (org-goto-sibling 'previous)
23396 (org-flag-heading nil))))
23398 (defun org-goto-first-child ()
23399 "Goto the first child, even if it is invisible.
23400 Return t when a child was found. Otherwise don't move point and
23401 return nil."
23402 (let (level (pos (point)) (re org-outline-regexp-bol))
23403 (when (ignore-errors (org-back-to-heading t))
23404 (setq level (outline-level))
23405 (forward-char 1)
23406 (if (and (re-search-forward re nil t) (> (outline-level) level))
23407 (progn (goto-char (match-beginning 0)) t)
23408 (goto-char pos) nil))))
23410 (defun org-show-hidden-entry ()
23411 "Show an entry where even the heading is hidden."
23412 (save-excursion
23413 (org-show-entry)))
23415 (defun org-flag-heading (flag &optional entry)
23416 "Flag the current heading. FLAG non-nil means make invisible.
23417 When ENTRY is non-nil, show the entire entry."
23418 (save-excursion
23419 (org-back-to-heading t)
23420 ;; Check if we should show the entire entry
23421 (if entry
23422 (progn
23423 (org-show-entry)
23424 (save-excursion
23425 (and (outline-next-heading)
23426 (org-flag-heading nil))))
23427 (outline-flag-region (max (point-min) (1- (point)))
23428 (save-excursion (outline-end-of-heading) (point))
23429 flag))))
23431 (defun org-get-next-sibling ()
23432 "Move to next heading of the same level, and return point.
23433 If there is no such heading, return nil.
23434 This is like outline-next-sibling, but invisible headings are ok."
23435 (let ((level (funcall outline-level)))
23436 (outline-next-heading)
23437 (while (and (not (eobp)) (> (funcall outline-level) level))
23438 (outline-next-heading))
23439 (unless (or (eobp) (< (funcall outline-level) level))
23440 (point))))
23442 (defun org-get-last-sibling ()
23443 "Move to previous heading of the same level, and return point.
23444 If there is no such heading, return nil."
23445 (let ((opoint (point))
23446 (level (funcall outline-level)))
23447 (outline-previous-heading)
23448 (when (and (/= (point) opoint) (outline-on-heading-p t))
23449 (while (and (> (funcall outline-level) level)
23450 (not (bobp)))
23451 (outline-previous-heading))
23452 (unless (< (funcall outline-level) level)
23453 (point)))))
23455 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23456 "Goto to the end of a subtree."
23457 ;; This contains an exact copy of the original function, but it uses
23458 ;; `org-back-to-heading', to make it work also in invisible
23459 ;; trees. And is uses an invisible-ok argument.
23460 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23461 ;; Furthermore, when used inside Org, finding the end of a large subtree
23462 ;; with many children and grandchildren etc, this can be much faster
23463 ;; than the outline version.
23464 (org-back-to-heading invisible-ok)
23465 (let ((first t)
23466 (level (funcall outline-level)))
23467 (if (and (derived-mode-p 'org-mode) (< level 1000))
23468 ;; A true heading (not a plain list item), in Org
23469 ;; This means we can easily find the end by looking
23470 ;; only for the right number of stars. Using a regexp to do
23471 ;; this is so much faster than using a Lisp loop.
23472 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23473 (forward-char 1)
23474 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23475 ;; something else, do it the slow way
23476 (while (and (not (eobp))
23477 (or first (> (funcall outline-level) level)))
23478 (setq first nil)
23479 (outline-next-heading)))
23480 (unless to-heading
23481 (when (memq (preceding-char) '(?\n ?\^M))
23482 ;; Go to end of line before heading
23483 (forward-char -1)
23484 (when (memq (preceding-char) '(?\n ?\^M))
23485 ;; leave blank line before heading
23486 (forward-char -1)))))
23487 (point))
23489 (defun org-end-of-meta-data (&optional full)
23490 "Skip planning line and properties drawer in current entry.
23491 When optional argument FULL is non-nil, also skip empty lines,
23492 clocking lines and regular drawers at the beginning of the
23493 entry."
23494 (org-back-to-heading t)
23495 (forward-line)
23496 (when (looking-at-p org-planning-line-re) (forward-line))
23497 (when (looking-at org-property-drawer-re)
23498 (goto-char (match-end 0))
23499 (forward-line))
23500 (when (and full (not (org-at-heading-p)))
23501 (catch 'exit
23502 (let ((end (save-excursion (outline-next-heading) (point)))
23503 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23504 (while (not (eobp))
23505 (cond ((looking-at-p org-drawer-regexp)
23506 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23507 (forward-line)
23508 (throw 'exit t)))
23509 ((looking-at-p re) (forward-line))
23510 (t (throw 'exit t))))))))
23512 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23513 "Move forward to the ARG'th subheading at same level as this one.
23514 Stop at the first and last subheadings of a superior heading.
23515 Normally this only looks at visible headings, but when INVISIBLE-OK is
23516 non-nil it will also look at invisible ones."
23517 (interactive "p")
23518 (let ((backward? (and arg (< arg 0))))
23519 (if (org-before-first-heading-p)
23520 (if backward? (goto-char (point-min)) (outline-next-heading))
23521 (org-back-to-heading invisible-ok)
23522 (unless backward? (end-of-line)) ;do not match current headline
23523 (let ((level (- (match-end 0) (match-beginning 0) 1))
23524 (f (if backward? #'re-search-backward #'re-search-forward))
23525 (count (if arg (abs arg) 1))
23526 (result (point)))
23527 (while (and (> count 0)
23528 (funcall f org-outline-regexp-bol nil 'move))
23529 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23530 (cond ((< l level) (setq count 0))
23531 ((and (= l level)
23532 (or invisible-ok
23533 (not (org-invisible-p
23534 (line-beginning-position)))))
23535 (cl-decf count)
23536 (when (= l level) (setq result (point)))))))
23537 (goto-char result))
23538 (beginning-of-line))))
23540 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23541 "Move backward to the ARG'th subheading at same level as this one.
23542 Stop at the first and last subheadings of a superior heading."
23543 (interactive "p")
23544 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23546 (defun org-next-visible-heading (arg)
23547 "Move to the next visible heading.
23549 This function wraps `outline-next-visible-heading' with
23550 `org-with-limited-levels' in order to skip over inline tasks and
23551 respect customization of `org-odd-levels-only'."
23552 (interactive "p")
23553 (org-with-limited-levels
23554 (outline-next-visible-heading arg)))
23556 (defun org-previous-visible-heading (arg)
23557 "Move to the previous visible heading.
23559 This function wraps `outline-previous-visible-heading' with
23560 `org-with-limited-levels' in order to skip over inline tasks and
23561 respect customization of `org-odd-levels-only'."
23562 (interactive "p")
23563 (org-with-limited-levels
23564 (outline-previous-visible-heading arg)))
23566 (defun org-next-block (arg &optional backward block-regexp)
23567 "Jump to the next block.
23569 With a prefix argument ARG, jump forward ARG many blocks.
23571 When BACKWARD is non-nil, jump to the previous block.
23573 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23574 Match data is set according to this regexp when the function
23575 returns.
23577 Return point at beginning of the opening line of found block.
23578 Throw an error if no block is found."
23579 (interactive "p")
23580 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23581 (case-fold-search t)
23582 (search-fn (if backward #'re-search-backward #'re-search-forward))
23583 (count (or arg 1))
23584 (origin (point))
23585 last-element)
23586 (if backward (beginning-of-line) (end-of-line))
23587 (while (and (> count 0) (funcall search-fn re nil t))
23588 (let ((element (save-excursion
23589 (goto-char (match-beginning 0))
23590 (save-match-data (org-element-at-point)))))
23591 (when (and (memq (org-element-type element)
23592 '(center-block comment-block dynamic-block
23593 example-block export-block quote-block
23594 special-block src-block verse-block))
23595 (<= (match-beginning 0)
23596 (org-element-property :post-affiliated element)))
23597 (setq last-element element)
23598 (cl-decf count))))
23599 (if (= count 0)
23600 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23601 (save-match-data (org-show-context)))
23602 (goto-char origin)
23603 (user-error "No %s code blocks" (if backward "previous" "further")))))
23605 (defun org-previous-block (arg &optional block-regexp)
23606 "Jump to the previous block.
23607 With a prefix argument ARG, jump backward ARG many source blocks.
23608 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23609 (interactive "p")
23610 (org-next-block arg t block-regexp))
23612 (defun org-forward-paragraph ()
23613 "Move forward to beginning of next paragraph or equivalent.
23615 The function moves point to the beginning of the next visible
23616 structural element, which can be a paragraph, a table, a list
23617 item, etc. It also provides some special moves for convenience:
23619 - On an affiliated keyword, jump to the beginning of the
23620 relative element.
23621 - On an item or a footnote definition, move to the second
23622 element inside, if any.
23623 - On a table or a property drawer, jump after it.
23624 - On a verse or source block, stop after blank lines."
23625 (interactive)
23626 (unless (eobp)
23627 (let* ((deactivate-mark nil)
23628 (element (org-element-at-point))
23629 (type (org-element-type element))
23630 (post-affiliated (org-element-property :post-affiliated element))
23631 (contents-begin (org-element-property :contents-begin element))
23632 (contents-end (org-element-property :contents-end element))
23633 (end (let ((end (org-element-property :end element)) (parent element))
23634 (while (and (setq parent (org-element-property :parent parent))
23635 (= (org-element-property :contents-end parent) end))
23636 (setq end (org-element-property :end parent)))
23637 end)))
23638 (cond ((not element)
23639 (skip-chars-forward " \r\t\n")
23640 (or (eobp) (beginning-of-line)))
23641 ;; On affiliated keywords, move to element's beginning.
23642 ((< (point) post-affiliated)
23643 (goto-char post-affiliated))
23644 ;; At a table row, move to the end of the table. Similarly,
23645 ;; at a node property, move to the end of the property
23646 ;; drawer.
23647 ((memq type '(node-property table-row))
23648 (goto-char (org-element-property
23649 :end (org-element-property :parent element))))
23650 ((memq type '(property-drawer table)) (goto-char end))
23651 ;; Consider blank lines as separators in verse and source
23652 ;; blocks to ease editing.
23653 ((memq type '(src-block verse-block))
23654 (when (eq type 'src-block)
23655 (setq contents-end
23656 (save-excursion (goto-char end)
23657 (skip-chars-backward " \r\t\n")
23658 (line-beginning-position))))
23659 (beginning-of-line)
23660 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23661 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23662 (goto-char end)
23663 (skip-chars-forward " \r\t\n")
23664 (if (= (point) contents-end) (goto-char end)
23665 (beginning-of-line))))
23666 ;; With no contents, just skip element.
23667 ((not contents-begin) (goto-char end))
23668 ;; If contents are invisible, skip the element altogether.
23669 ((org-invisible-p (line-end-position))
23670 (cl-case type
23671 (headline
23672 (org-with-limited-levels (outline-next-visible-heading 1)))
23673 ;; At a plain list, make sure we move to the next item
23674 ;; instead of skipping the whole list.
23675 (plain-list (forward-char)
23676 (org-forward-paragraph))
23677 (otherwise (goto-char end))))
23678 ((>= (point) contents-end) (goto-char end))
23679 ((>= (point) contents-begin)
23680 ;; This can only happen on paragraphs and plain lists.
23681 (cl-case type
23682 (paragraph (goto-char end))
23683 ;; At a plain list, try to move to second element in
23684 ;; first item, if possible.
23685 (plain-list (end-of-line)
23686 (org-forward-paragraph))))
23687 ;; When contents start on the middle of a line (e.g. in
23688 ;; items and footnote definitions), try to reach first
23689 ;; element starting after current line.
23690 ((> (line-end-position) contents-begin)
23691 (end-of-line)
23692 (org-forward-paragraph))
23693 (t (goto-char contents-begin))))))
23695 (defun org-backward-paragraph ()
23696 "Move backward to start of previous paragraph or equivalent.
23698 The function moves point to the beginning of the current
23699 structural element, which can be a paragraph, a table, a list
23700 item, etc., or to the beginning of the previous visible one if
23701 point is already there. It also provides some special moves for
23702 convenience:
23704 - On an affiliated keyword, jump to the first one.
23705 - On a table or a property drawer, move to its beginning.
23706 - On comment, example, export, src and verse blocks, stop
23707 before blank lines."
23708 (interactive)
23709 (unless (bobp)
23710 (let* ((deactivate-mark nil)
23711 (element (org-element-at-point))
23712 (type (org-element-type element))
23713 (contents-end (org-element-property :contents-end element))
23714 (post-affiliated (org-element-property :post-affiliated element))
23715 (begin (org-element-property :begin element))
23716 (special? ;blocks handled specially
23717 (memq type '(comment-block example-block export-block src-block
23718 verse-block)))
23719 (contents-begin
23720 (if special?
23721 ;; These types have no proper contents. Fake line
23722 ;; below the block opening line as contents beginning.
23723 (save-excursion (goto-char begin) (line-beginning-position 2))
23724 (org-element-property :contents-begin element))))
23725 (cond
23726 ((not element) (goto-char (point-min)))
23727 ((= (point) begin)
23728 (backward-char)
23729 (org-backward-paragraph))
23730 ((<= (point) post-affiliated) (goto-char begin))
23731 ;; Special behavior: on a table or a property drawer, move to
23732 ;; its beginning.
23733 ((memq type '(node-property table-row))
23734 (goto-char (org-element-property
23735 :post-affiliated (org-element-property :parent element))))
23736 (special?
23737 (if (<= (point) contents-begin) (goto-char post-affiliated)
23738 ;; Inside a verse block, see blank lines as paragraph
23739 ;; separators.
23740 (let ((origin (point)))
23741 (skip-chars-backward " \r\t\n" contents-begin)
23742 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23743 (skip-chars-forward " \r\t\n" origin)
23744 (if (= (point) origin) (goto-char contents-begin)
23745 (beginning-of-line))))))
23746 ((eq type 'paragraph) (goto-char contents-begin)
23747 ;; When at first paragraph in an item or a footnote definition,
23748 ;; move directly to beginning of line.
23749 (let ((parent-contents
23750 (org-element-property
23751 :contents-begin (org-element-property :parent element))))
23752 (when (and parent-contents (= parent-contents contents-begin))
23753 (beginning-of-line))))
23754 ;; At the end of a greater element, move to the beginning of
23755 ;; the last element within.
23756 ((and contents-end (>= (point) contents-end))
23757 (goto-char (1- contents-end))
23758 (org-backward-paragraph))
23759 (t (goto-char (or post-affiliated begin))))
23760 ;; Ensure we never leave point invisible.
23761 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23763 (defun org-forward-element ()
23764 "Move forward by one element.
23765 Move to the next element at the same level, when possible."
23766 (interactive)
23767 (cond ((eobp) (user-error "Cannot move further down"))
23768 ((org-with-limited-levels (org-at-heading-p))
23769 (let ((origin (point)))
23770 (goto-char (org-end-of-subtree nil t))
23771 (unless (org-with-limited-levels (org-at-heading-p))
23772 (goto-char origin)
23773 (user-error "Cannot move further down"))))
23775 (let* ((elem (org-element-at-point))
23776 (end (org-element-property :end elem))
23777 (parent (org-element-property :parent elem)))
23778 (cond ((and parent (= (org-element-property :contents-end parent) end))
23779 (goto-char (org-element-property :end parent)))
23780 ((integer-or-marker-p end) (goto-char end))
23781 (t (message "No element at point")))))))
23783 (defun org-backward-element ()
23784 "Move backward by one element.
23785 Move to the previous element at the same level, when possible."
23786 (interactive)
23787 (cond ((bobp) (user-error "Cannot move further up"))
23788 ((org-with-limited-levels (org-at-heading-p))
23789 ;; At a headline, move to the previous one, if any, or stay
23790 ;; here.
23791 (let ((origin (point)))
23792 (org-with-limited-levels (org-backward-heading-same-level 1))
23793 ;; When current headline has no sibling above, move to its
23794 ;; parent.
23795 (when (= (point) origin)
23796 (or (org-with-limited-levels (org-up-heading-safe))
23797 (progn (goto-char origin)
23798 (user-error "Cannot move further up"))))))
23800 (let* ((elem (org-element-at-point))
23801 (beg (org-element-property :begin elem)))
23802 (cond
23803 ;; Move to beginning of current element if point isn't
23804 ;; there already.
23805 ((null beg) (message "No element at point"))
23806 ((/= (point) beg) (goto-char beg))
23807 (t (goto-char beg)
23808 (skip-chars-backward " \r\t\n")
23809 (unless (bobp)
23810 (let ((prev (org-element-at-point)))
23811 (goto-char (org-element-property :begin prev))
23812 (while (and (setq prev (org-element-property :parent prev))
23813 (<= (org-element-property :end prev) beg))
23814 (goto-char (org-element-property :begin prev)))))))))))
23816 (defun org-up-element ()
23817 "Move to upper element."
23818 (interactive)
23819 (if (org-with-limited-levels (org-at-heading-p))
23820 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23821 (let* ((elem (org-element-at-point))
23822 (parent (org-element-property :parent elem)))
23823 (if parent (goto-char (org-element-property :begin parent))
23824 (if (org-with-limited-levels (org-before-first-heading-p))
23825 (user-error "No surrounding element")
23826 (org-with-limited-levels (org-back-to-heading)))))))
23828 (defun org-down-element ()
23829 "Move to inner element."
23830 (interactive)
23831 (let ((element (org-element-at-point)))
23832 (cond
23833 ((memq (org-element-type element) '(plain-list table))
23834 (goto-char (org-element-property :contents-begin element))
23835 (forward-char))
23836 ((memq (org-element-type element) org-element-greater-elements)
23837 ;; If contents are hidden, first disclose them.
23838 (when (org-invisible-p (line-end-position)) (org-cycle))
23839 (goto-char (or (org-element-property :contents-begin element)
23840 (user-error "No content for this element"))))
23841 (t (user-error "No inner element")))))
23843 (defun org-drag-element-backward ()
23844 "Move backward element at point."
23845 (interactive)
23846 (let ((elem (or (org-element-at-point)
23847 (user-error "No element at point"))))
23848 (if (eq (org-element-type elem) 'headline)
23849 ;; Preserve point when moving a whole tree, even if point was
23850 ;; on blank lines below the headline.
23851 (let ((offset (skip-chars-backward " \t\n")))
23852 (unwind-protect (org-move-subtree-up)
23853 (forward-char (- offset))))
23854 (let ((prev-elem
23855 (save-excursion
23856 (goto-char (org-element-property :begin elem))
23857 (skip-chars-backward " \r\t\n")
23858 (unless (bobp)
23859 (let* ((beg (org-element-property :begin elem))
23860 (prev (org-element-at-point))
23861 (up prev))
23862 (while (and (setq up (org-element-property :parent up))
23863 (<= (org-element-property :end up) beg))
23864 (setq prev up))
23865 prev)))))
23866 ;; Error out if no previous element or previous element is
23867 ;; a parent of the current one.
23868 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23869 (user-error "Cannot drag element backward")
23870 (let ((pos (point)))
23871 (org-element-swap-A-B prev-elem elem)
23872 (goto-char (+ (org-element-property :begin prev-elem)
23873 (- pos (org-element-property :begin elem))))))))))
23875 (defun org-drag-element-forward ()
23876 "Move forward element at point."
23877 (interactive)
23878 (let* ((pos (point))
23879 (elem (or (org-element-at-point)
23880 (user-error "No element at point"))))
23881 (when (= (point-max) (org-element-property :end elem))
23882 (user-error "Cannot drag element forward"))
23883 (goto-char (org-element-property :end elem))
23884 (let ((next-elem (org-element-at-point)))
23885 (when (or (org-element-nested-p elem next-elem)
23886 (and (eq (org-element-type next-elem) 'headline)
23887 (not (eq (org-element-type elem) 'headline))))
23888 (goto-char pos)
23889 (user-error "Cannot drag element forward"))
23890 ;; Compute new position of point: it's shifted by NEXT-ELEM
23891 ;; body's length (without final blanks) and by the length of
23892 ;; blanks between ELEM and NEXT-ELEM.
23893 (let ((size-next (- (save-excursion
23894 (goto-char (org-element-property :end next-elem))
23895 (skip-chars-backward " \r\t\n")
23896 (forward-line)
23897 ;; Small correction if buffer doesn't end
23898 ;; with a newline character.
23899 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23900 (org-element-property :begin next-elem)))
23901 (size-blank (- (org-element-property :end elem)
23902 (save-excursion
23903 (goto-char (org-element-property :end elem))
23904 (skip-chars-backward " \r\t\n")
23905 (forward-line)
23906 (point)))))
23907 (org-element-swap-A-B elem next-elem)
23908 (goto-char (+ pos size-next size-blank))))))
23910 (defun org-drag-line-forward (arg)
23911 "Drag the line at point ARG lines forward."
23912 (interactive "p")
23913 (dotimes (_ (abs arg))
23914 (let ((c (current-column)))
23915 (if (< 0 arg)
23916 (progn
23917 (beginning-of-line 2)
23918 (transpose-lines 1)
23919 (beginning-of-line 0))
23920 (transpose-lines 1)
23921 (beginning-of-line -1))
23922 (org-move-to-column c))))
23924 (defun org-drag-line-backward (arg)
23925 "Drag the line at point ARG lines backward."
23926 (interactive "p")
23927 (org-drag-line-forward (- arg)))
23929 (defun org-mark-element ()
23930 "Put point at beginning of this element, mark at end.
23932 Interactively, if this command is repeated or (in Transient Mark
23933 mode) if the mark is active, it marks the next element after the
23934 ones already marked."
23935 (interactive)
23936 (let (deactivate-mark)
23937 (if (and (called-interactively-p 'any)
23938 (or (and (eq last-command this-command) (mark t))
23939 (and transient-mark-mode mark-active)))
23940 (set-mark
23941 (save-excursion
23942 (goto-char (mark))
23943 (goto-char (org-element-property :end (org-element-at-point)))))
23944 (let ((element (org-element-at-point)))
23945 (end-of-line)
23946 (push-mark (org-element-property :end element) t t)
23947 (goto-char (org-element-property :begin element))))))
23949 (defun org-narrow-to-element ()
23950 "Narrow buffer to current element."
23951 (interactive)
23952 (let ((elem (org-element-at-point)))
23953 (cond
23954 ((eq (car elem) 'headline)
23955 (narrow-to-region
23956 (org-element-property :begin elem)
23957 (org-element-property :end elem)))
23958 ((memq (car elem) org-element-greater-elements)
23959 (narrow-to-region
23960 (org-element-property :contents-begin elem)
23961 (org-element-property :contents-end elem)))
23963 (narrow-to-region
23964 (org-element-property :begin elem)
23965 (org-element-property :end elem))))))
23967 (defun org-transpose-element ()
23968 "Transpose current and previous elements, keeping blank lines between.
23969 Point is moved after both elements."
23970 (interactive)
23971 (org-skip-whitespace)
23972 (let ((end (org-element-property :end (org-element-at-point))))
23973 (org-drag-element-backward)
23974 (goto-char end)))
23976 (defun org-unindent-buffer ()
23977 "Un-indent the visible part of the buffer.
23978 Relative indentation (between items, inside blocks, etc.) isn't
23979 modified."
23980 (interactive)
23981 (unless (eq major-mode 'org-mode)
23982 (user-error "Cannot un-indent a buffer not in Org mode"))
23983 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23984 (unindent-tree
23985 (lambda (contents)
23986 (dolist (element (reverse contents))
23987 (if (memq (org-element-type element) '(headline section))
23988 (funcall unindent-tree (org-element-contents element))
23989 (save-excursion
23990 (save-restriction
23991 (narrow-to-region
23992 (org-element-property :begin element)
23993 (org-element-property :end element))
23994 (org-do-remove-indentation))))))))
23995 (funcall unindent-tree (org-element-contents parse-tree))))
23997 (defun org-show-children (&optional level)
23998 "Show all direct subheadings of this heading.
23999 Prefix arg LEVEL is how many levels below the current level
24000 should be shown. Default is enough to cause the following
24001 heading to appear."
24002 (interactive "p")
24003 ;; If `orgstruct-mode' is active, use the slower version.
24004 (if orgstruct-mode (call-interactively #'outline-show-children)
24005 (save-excursion
24006 (org-back-to-heading t)
24007 (let* ((current-level (funcall outline-level))
24008 (max-level (org-get-valid-level
24009 current-level
24010 (if level (prefix-numeric-value level) 1)))
24011 (end (save-excursion (org-end-of-subtree t t)))
24012 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24013 (past-first-child nil)
24014 ;; Make sure to skip inlinetasks.
24015 (re (format regexp-fmt
24016 current-level
24017 (cond
24018 ((not (featurep 'org-inlinetask)) "")
24019 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24021 (t (1- org-inlinetask-min-level))))))
24022 ;; Display parent heading.
24023 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24024 (forward-line)
24025 ;; Display children. First child may be deeper than expected
24026 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24027 ;; MAX-LEVEL accordingly.
24028 (while (re-search-forward re end t)
24029 (unless past-first-child
24030 (setq re (format regexp-fmt
24031 current-level
24032 (max (funcall outline-level) max-level)))
24033 (setq past-first-child t))
24034 (outline-flag-region
24035 (line-end-position 0) (line-end-position) nil))))))
24037 (defun org-show-subtree ()
24038 "Show everything after this heading at deeper levels."
24039 (interactive)
24040 (outline-flag-region
24041 (point)
24042 (save-excursion
24043 (org-end-of-subtree t t))
24044 nil))
24046 (defun org-show-entry ()
24047 "Show the body directly following this heading.
24048 Show the heading too, if it is currently invisible."
24049 (interactive)
24050 (save-excursion
24051 (ignore-errors
24052 (org-back-to-heading t)
24053 (outline-flag-region
24054 (max (point-min) (1- (point)))
24055 (save-excursion
24056 (if (re-search-forward
24057 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24058 (match-beginning 1)
24059 (point-max)))
24060 nil)
24061 (org-cycle-hide-drawers 'children))))
24063 (defun org-make-options-regexp (kwds &optional extra)
24064 "Make a regular expression for keyword lines.
24065 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24066 when non-nil, is a regexp matching keywords names."
24067 (concat "^[ \t]*#\\+\\("
24068 (regexp-opt kwds)
24069 (and extra (concat (and kwds "\\|") extra))
24070 "\\):[ \t]*\\(.*\\)"))
24072 ;;;; Finish up
24074 (provide 'org)
24076 (run-hooks 'org-load-hook)
24078 ;;; org.el ends here