Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobdef4274d94648a348e89f1b0680856974612c471
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
1482 :safe #'booleanp)
1484 (defcustom org-special-ctrl-a/e nil
1485 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1487 When t, `C-a' will bring back the cursor to the beginning of the
1488 headline text, i.e. after the stars and after a possible TODO
1489 keyword. In an item, this will be the position after bullet and
1490 check-box, if any. When the cursor is already at that position,
1491 another `C-a' will bring it to the beginning of the line.
1493 `C-e' will jump to the end of the headline, ignoring the presence
1494 of tags in the headline. A second `C-e' will then jump to the
1495 true end of the line, after any tags. This also means that, when
1496 this variable is non-nil, `C-e' also will never jump beyond the
1497 end of the heading of a folded section, i.e. not after the
1498 ellipses.
1500 When set to the symbol `reversed', the first `C-a' or `C-e' works
1501 normally, going to the true line boundary first. Only a directly
1502 following, identical keypress will bring the cursor to the
1503 special positions.
1505 This may also be a cons cell where the behavior for `C-a' and
1506 `C-e' is set separately."
1507 :group 'org-edit-structure
1508 :type '(choice
1509 (const :tag "off" nil)
1510 (const :tag "on: after stars/bullet and before tags first" t)
1511 (const :tag "reversed: true line boundary first" reversed)
1512 (cons :tag "Set C-a and C-e separately"
1513 (choice :tag "Special C-a"
1514 (const :tag "off" nil)
1515 (const :tag "on: after stars/bullet first" t)
1516 (const :tag "reversed: before stars/bullet first" reversed))
1517 (choice :tag "Special C-e"
1518 (const :tag "off" nil)
1519 (const :tag "on: before tags first" t)
1520 (const :tag "reversed: after tags first" reversed)))))
1521 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1523 (defcustom org-special-ctrl-k nil
1524 "Non-nil means `C-k' will behave specially in headlines.
1525 When nil, `C-k' will call the default `kill-line' command.
1526 When t, the following will happen while the cursor is in the headline:
1528 - When the cursor is at the beginning of a headline, kill the entire
1529 line and possible the folded subtree below the line.
1530 - When in the middle of the headline text, kill the headline up to the tags.
1531 - When after the headline text, kill the tags."
1532 :group 'org-edit-structure
1533 :type 'boolean)
1535 (defcustom org-ctrl-k-protect-subtree nil
1536 "Non-nil means, do not delete a hidden subtree with C-k.
1537 When set to the symbol `error', simply throw an error when C-k is
1538 used to kill (part-of) a headline that has hidden text behind it.
1539 Any other non-nil value will result in a query to the user, if it is
1540 OK to kill that hidden subtree. When nil, kill without remorse."
1541 :group 'org-edit-structure
1542 :version "24.1"
1543 :type '(choice
1544 (const :tag "Do not protect hidden subtrees" nil)
1545 (const :tag "Protect hidden subtrees with a security query" t)
1546 (const :tag "Never kill a hidden subtree with C-k" error)))
1548 (defcustom org-special-ctrl-o t
1549 "Non-nil means, make `C-o' insert a row in tables."
1550 :group 'org-edit-structure
1551 :type 'boolean)
1553 (defcustom org-catch-invisible-edits nil
1554 "Check if in invisible region before inserting or deleting a character.
1555 Valid values are:
1557 nil Do not check, so just do invisible edits.
1558 error Throw an error and do nothing.
1559 show Make point visible, and do the requested edit.
1560 show-and-error Make point visible, then throw an error and abort the edit.
1561 smart Make point visible, and do insertion/deletion if it is
1562 adjacent to visible text and the change feels predictable.
1563 Never delete a previously invisible character or add in the
1564 middle or right after an invisible region. Basically, this
1565 allows insertion and backward-delete right before ellipses.
1566 FIXME: maybe in this case we should not even show?"
1567 :group 'org-edit-structure
1568 :version "24.1"
1569 :type '(choice
1570 (const :tag "Do not check" nil)
1571 (const :tag "Throw error when trying to edit" error)
1572 (const :tag "Unhide, but do not do the edit" show-and-error)
1573 (const :tag "Show invisible part and do the edit" show)
1574 (const :tag "Be smart and do the right thing" smart)))
1576 (defcustom org-yank-folded-subtrees t
1577 "Non-nil means when yanking subtrees, fold them.
1578 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1579 it starts with a heading and all other headings in it are either children
1580 or siblings, then fold all the subtrees. However, do this only if no
1581 text after the yank would be swallowed into a folded tree by this action."
1582 :group 'org-edit-structure
1583 :type 'boolean)
1585 (defcustom org-yank-adjusted-subtrees nil
1586 "Non-nil means when yanking subtrees, adjust the level.
1587 With this setting, `org-paste-subtree' is used to insert the subtree, see
1588 this function for details."
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defcustom org-M-RET-may-split-line '((default . t))
1593 "Non-nil means M-RET will split the line at the cursor position.
1594 When nil, it will go to the end of the line before making a
1595 new line.
1596 You may also set this option in a different way for different
1597 contexts. Valid contexts are:
1599 headline when creating a new headline
1600 item when creating a new item
1601 table in a table field
1602 default the value to be used for all contexts not explicitly
1603 customized"
1604 :group 'org-structure
1605 :group 'org-table
1606 :type '(choice
1607 (const :tag "Always" t)
1608 (const :tag "Never" nil)
1609 (repeat :greedy t :tag "Individual contexts"
1610 (cons
1611 (choice :tag "Context"
1612 (const headline)
1613 (const item)
1614 (const table)
1615 (const default))
1616 (boolean)))))
1619 (defcustom org-insert-heading-respect-content nil
1620 "Non-nil means insert new headings after the current subtree.
1621 \\<org-mode-map>
1622 When nil, the new heading is created directly after the current line.
1623 The commands `\\[org-insert-heading-respect-content]' and \
1624 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1625 for the duration of the command."
1626 :group 'org-structure
1627 :type 'boolean)
1629 (defcustom org-blank-before-new-entry '((heading . auto)
1630 (plain-list-item . auto))
1631 "Should `org-insert-heading' leave a blank line before new heading/item?
1632 The value is an alist, with `heading' and `plain-list-item' as CAR,
1633 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1634 which case Org will look at the surrounding headings/items and try to
1635 make an intelligent decision whether to insert a blank line or not."
1636 :group 'org-edit-structure
1637 :type '(list
1638 (cons (const heading)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))
1642 (cons (const plain-list-item)
1643 (choice (const :tag "Never" nil)
1644 (const :tag "Always" t)
1645 (const :tag "Auto" auto)))))
1647 (defcustom org-insert-heading-hook nil
1648 "Hook being run after inserting a new heading."
1649 :group 'org-edit-structure
1650 :type 'hook)
1652 (defcustom org-enable-fixed-width-editor t
1653 "Non-nil means lines starting with \":\" are treated as fixed-width.
1654 This currently only means they are never auto-wrapped.
1655 When nil, such lines will be treated like ordinary lines."
1656 :group 'org-edit-structure
1657 :type 'boolean)
1659 (defgroup org-sparse-trees nil
1660 "Options concerning sparse trees in Org mode."
1661 :tag "Org Sparse Trees"
1662 :group 'org-structure)
1664 (defcustom org-highlight-sparse-tree-matches t
1665 "Non-nil means highlight all matches that define a sparse tree.
1666 The highlights will automatically disappear the next time the buffer is
1667 changed by an edit command."
1668 :group 'org-sparse-trees
1669 :type 'boolean)
1671 (defcustom org-remove-highlights-with-change t
1672 "Non-nil means any change to the buffer will remove temporary highlights.
1673 \\<org-mode-map>\
1674 Such highlights are created by `org-occur' and `org-clock-display'.
1675 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1676 to get rid of the highlights.
1677 The highlights created by `org-toggle-latex-fragment' always need
1678 `\\[org-toggle-latex-fragment]' to be removed."
1679 :group 'org-sparse-trees
1680 :group 'org-time
1681 :type 'boolean)
1683 (defcustom org-occur-case-fold-search t
1684 "Non-nil means `org-occur' should be case-insensitive.
1685 If set to `smart' the search will be case-insensitive only if it
1686 doesn't specify any upper case character."
1687 :group 'org-sparse-trees
1688 :version "26.1"
1689 :type '(choice
1690 (const :tag "Case-sensitive" nil)
1691 (const :tag "Case-insensitive" t)
1692 (const :tag "Case-insensitive for lower case searches only" smart)))
1694 (defcustom org-occur-hook '(org-first-headline-recenter)
1695 "Hook that is run after `org-occur' has constructed a sparse tree.
1696 This can be used to recenter the window to show as much of the structure
1697 as possible."
1698 :group 'org-sparse-trees
1699 :type 'hook)
1701 (defgroup org-table nil
1702 "Options concerning tables in Org mode."
1703 :tag "Org Table"
1704 :group 'org)
1706 (defcustom org-self-insert-cluster-for-undo nil
1707 "Non-nil means cluster self-insert commands for undo when possible.
1708 If this is set, then, like in the Emacs command loop, 20 consecutive
1709 characters will be undone together.
1710 This is configurable, because there is some impact on typing performance."
1711 :group 'org-table
1712 :type 'boolean)
1714 (defcustom org-table-tab-recognizes-table.el t
1715 "Non-nil means TAB will automatically notice a table.el table.
1716 When it sees such a table, it moves point into it and - if necessary -
1717 calls `table-recognize-table'."
1718 :group 'org-table-editing
1719 :type 'boolean)
1721 (defgroup org-link nil
1722 "Options concerning links in Org mode."
1723 :tag "Org Link"
1724 :group 'org)
1726 (defvar-local org-link-abbrev-alist-local nil
1727 "Buffer-local version of `org-link-abbrev-alist', which see.
1728 The value of this is taken from the #+LINK lines.")
1730 (defcustom org-link-parameters
1731 '(("doi" :follow org--open-doi-link)
1732 ("elisp" :follow org--open-elisp-link)
1733 ("file" :complete org-file-complete-link)
1734 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1735 ("help" :follow org--open-help-link)
1736 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1737 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1738 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1739 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1740 ("shell" :follow org--open-shell-link))
1741 "An alist of properties that defines all the links in Org mode.
1742 The key in each association is a string of the link type.
1743 Subsequent optional elements make up a p-list of link properties.
1745 :follow - A function that takes the link path as an argument.
1747 :export - A function that takes the link path, description and
1748 export-backend as arguments.
1750 :store - A function responsible for storing the link. See the
1751 function `org-store-link-functions'.
1753 :complete - A function that inserts a link with completion. The
1754 function takes one optional prefix arg.
1756 :face - A face for the link, or a function that returns a face.
1757 The function takes one argument which is the link path. The
1758 default face is `org-link'.
1760 :mouse-face - The mouse-face. The default is `highlight'.
1762 :display - `full' will not fold the link in descriptive
1763 display. Default is `org-link'.
1765 :help-echo - A string or function that takes (window object position)
1766 as arguments and returns a string.
1768 :keymap - A keymap that is active on the link. The default is
1769 `org-mouse-map'.
1771 :htmlize-link - A function for the htmlize-link. Defaults
1772 to (list :uri \"type:path\")
1774 :activate-func - A function to run at the end of font-lock
1775 activation. The function must accept (link-start link-end path bracketp)
1776 as arguments."
1777 :group 'org-link
1778 :type '(alist :tag "Link display parameters"
1779 :value-type plist)
1780 :version "26.1"
1781 :package-version '(Org . "9.1"))
1783 (defun org-link-get-parameter (type key)
1784 "Get TYPE link property for KEY.
1785 TYPE is a string and KEY is a plist keyword."
1786 (plist-get
1787 (cdr (assoc type org-link-parameters))
1788 key))
1790 (defun org-link-set-parameters (type &rest parameters)
1791 "Set link TYPE properties to PARAMETERS.
1792 PARAMETERS should be :key val pairs."
1793 (let ((data (assoc type org-link-parameters)))
1794 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1795 (push (cons type parameters) org-link-parameters)
1796 (org-make-link-regexps)
1797 (org-element-update-syntax))))
1799 (defun org-link-types ()
1800 "Return a list of known link types."
1801 (mapcar #'car org-link-parameters))
1803 (defcustom org-link-abbrev-alist nil
1804 "Alist of link abbreviations.
1805 The car of each element is a string, to be replaced at the start of a link.
1806 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1807 links in Org buffers can have an optional tag after a double colon, e.g.,
1809 [[linkkey:tag][description]]
1811 The `linkkey' must be a single word, starting with a letter, followed
1812 by letters, numbers, `-' or `_'.
1814 If REPLACE is a string, the tag will simply be appended to create the link.
1815 If the string contains \"%s\", the tag will be inserted there. If the string
1816 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1817 at that point (see the function `url-hexify-string'). If the string contains
1818 the specifier \"%(my-function)\", then the custom function `my-function' will
1819 be invoked: this function takes the tag as its only argument and must return
1820 a string.
1822 REPLACE may also be a function that will be called with the tag as the
1823 only argument to create the link, which should be returned as a string.
1825 See the manual for examples."
1826 :group 'org-link
1827 :type '(repeat
1828 (cons
1829 (string :tag "Protocol")
1830 (choice
1831 (string :tag "Format")
1832 (function)))))
1834 (defcustom org-descriptive-links t
1835 "Non-nil means Org will display descriptive links.
1836 E.g. [[http://orgmode.org][Org website]] will be displayed as
1837 \"Org Website\", hiding the link itself and just displaying its
1838 description. When set to nil, Org will display the full links
1839 literally.
1841 You can interactively set the value of this variable by calling
1842 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1843 :group 'org-link
1844 :type 'boolean)
1846 (defcustom org-link-file-path-type 'adaptive
1847 "How the path name in file links should be stored.
1848 Valid values are:
1850 relative Relative to the current directory, i.e. the directory of the file
1851 into which the link is being inserted.
1852 absolute Absolute path, if possible with ~ for home directory.
1853 noabbrev Absolute path, no abbreviation of home directory.
1854 adaptive Use relative path for files in the current directory and sub-
1855 directories of it. For other files, use an absolute path."
1856 :group 'org-link
1857 :type '(choice
1858 (const relative)
1859 (const absolute)
1860 (const noabbrev)
1861 (const adaptive)))
1863 (defvaralias 'org-activate-links 'org-highlight-links)
1864 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1865 "Types of links that should be highlighted in Org files.
1867 This is a list of symbols, each one of them leading to the
1868 highlighting of a certain link type.
1870 You can still open links that are not highlighted.
1872 In principle, it does not hurt to turn on highlighting for all
1873 link types. There may be a small gain when turning off unused
1874 link types. The types are:
1876 bracket The recommended [[link][description]] or [[link]] links with hiding.
1877 angle Links in angular brackets that may contain whitespace like
1878 <bbdb:Carsten Dominik>.
1879 plain Plain links in normal text, no whitespace, like http://google.com.
1880 radio Text that is matched by a radio target, see manual for details.
1881 tag Tag settings in a headline (link to tag search).
1882 date Time stamps (link to calendar).
1883 footnote Footnote labels.
1885 If you set this variable during an Emacs session, use `org-mode-restart'
1886 in the Org buffer so that the change takes effect."
1887 :group 'org-link
1888 :group 'org-appearance
1889 :type '(set :greedy t
1890 (const :tag "Double bracket links" bracket)
1891 (const :tag "Angular bracket links" angle)
1892 (const :tag "Plain text links" plain)
1893 (const :tag "Radio target matches" radio)
1894 (const :tag "Tags" tag)
1895 (const :tag "Timestamps" date)
1896 (const :tag "Footnotes" footnote)))
1898 (defcustom org-make-link-description-function nil
1899 "Function to use for generating link descriptions from links.
1900 This function must take two parameters: the first one is the
1901 link, the second one is the description generated by
1902 `org-insert-link'. The function should return the description to
1903 use."
1904 :group 'org-link
1905 :type '(choice (const nil) (function)))
1907 (defgroup org-link-store nil
1908 "Options concerning storing links in Org mode."
1909 :tag "Org Store Link"
1910 :group 'org-link)
1912 (defcustom org-url-hexify-p t
1913 "When non-nil, hexify URL when creating a link."
1914 :type 'boolean
1915 :version "24.3"
1916 :group 'org-link-store)
1918 (defcustom org-email-link-description-format "Email %c: %.30s"
1919 "Format of the description part of a link to an email or usenet message.
1920 The following %-escapes will be replaced by corresponding information:
1922 %F full \"From\" field
1923 %f name, taken from \"From\" field, address if no name
1924 %T full \"To\" field
1925 %t first name in \"To\" field, address if no name
1926 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1927 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1928 %s subject
1929 %d date
1930 %m message-id.
1932 You may use normal field width specification between the % and the letter.
1933 This is for example useful to limit the length of the subject.
1935 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1936 :group 'org-link-store
1937 :type 'string)
1939 (defcustom org-from-is-user-regexp
1940 (let (r1 r2)
1941 (when (and user-mail-address (not (string= user-mail-address "")))
1942 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1943 (when (and user-full-name (not (string= user-full-name "")))
1944 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1945 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1946 "Regexp matched against the \"From:\" header of an email or usenet message.
1947 It should match if the message is from the user him/herself."
1948 :group 'org-link-store
1949 :type 'regexp)
1951 (defcustom org-context-in-file-links t
1952 "Non-nil means file links from `org-store-link' contain context.
1953 \\<org-mode-map>
1954 A search string will be added to the file name with :: as separator
1955 and used to find the context when the link is activated by the command
1956 `org-open-at-point'. When this option is t, the entire active region
1957 will be placed in the search string of the file link. If set to a
1958 positive integer, only the first n lines of context will be stored.
1960 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1961 \\[org-store-link]')
1962 negates this setting for the duration of the command."
1963 :group 'org-link-store
1964 :type '(choice boolean integer))
1966 (defcustom org-keep-stored-link-after-insertion nil
1967 "Non-nil means keep link in list for entire session.
1968 \\<org-mode-map>
1969 The command `org-store-link' adds a link pointing to the current
1970 location to an internal list. These links accumulate during a session.
1971 The command `org-insert-link' can be used to insert links into any
1972 Org file (offering completion for all stored links).
1974 When this option is nil, every link which has been inserted once using
1975 `\\[org-insert-link]' will be removed from the list, to make completing the \
1976 unused
1977 links more efficient."
1978 :group 'org-link-store
1979 :type 'boolean)
1981 (defgroup org-link-follow nil
1982 "Options concerning following links in Org mode."
1983 :tag "Org Follow Link"
1984 :group 'org-link)
1986 (defcustom org-link-translation-function nil
1987 "Function to translate links with different syntax to Org syntax.
1988 This can be used to translate links created for example by the Planner
1989 or emacs-wiki packages to Org syntax.
1990 The function must accept two parameters, a TYPE containing the link
1991 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1992 which is everything after the link protocol. It should return a cons
1993 with possibly modified values of type and path.
1994 Org contains a function for this, so if you set this variable to
1995 `org-translate-link-from-planner', you should be able follow many
1996 links created by planner."
1997 :group 'org-link-follow
1998 :type '(choice (const nil) (function)))
2000 (defcustom org-follow-link-hook nil
2001 "Hook that is run after a link has been followed."
2002 :group 'org-link-follow
2003 :type 'hook)
2005 (defcustom org-tab-follows-link nil
2006 "Non-nil means on links TAB will follow the link.
2007 Needs to be set before org.el is loaded.
2008 This really should not be used, it does not make sense, and the
2009 implementation is bad."
2010 :group 'org-link-follow
2011 :type 'boolean)
2013 (defcustom org-return-follows-link nil
2014 "Non-nil means on links RET will follow the link.
2015 In tables, the special behavior of RET has precedence."
2016 :group 'org-link-follow
2017 :type 'boolean)
2019 (defcustom org-mouse-1-follows-link
2020 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2021 "Non-nil means mouse-1 on a link will follow the link.
2022 A longer mouse click will still set point. Needs to be set
2023 before org.el is loaded."
2024 :group 'org-link-follow
2025 :version "26.1"
2026 :package-version '(Org . "8.3")
2027 :type '(choice
2028 (const :tag "A double click follows the link" double)
2029 (const :tag "Unconditionally follow the link with mouse-1" t)
2030 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2032 (defcustom org-mark-ring-length 4
2033 "Number of different positions to be recorded in the ring.
2034 Changing this requires a restart of Emacs to work correctly."
2035 :group 'org-link-follow
2036 :type 'integer)
2038 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2039 "Non-nil means internal fuzzy links can only match headlines.
2041 When nil, the a fuzzy link may point to a target or a named
2042 construct in the document. When set to the special value
2043 `query-to-create', offer to create a new headline when none
2044 matched.
2046 Spaces and statistics cookies are ignored during heading searches."
2047 :group 'org-link-follow
2048 :version "24.1"
2049 :type '(choice
2050 (const :tag "Use fuzzy text search" nil)
2051 (const :tag "Match only exact headline" t)
2052 (const :tag "Match exact headline or query to create it"
2053 query-to-create))
2054 :safe #'symbolp)
2056 (defcustom org-link-frame-setup
2057 '((vm . vm-visit-folder-other-frame)
2058 (vm-imap . vm-visit-imap-folder-other-frame)
2059 (gnus . org-gnus-no-new-news)
2060 (file . find-file-other-window)
2061 (wl . wl-other-frame))
2062 "Setup the frame configuration for following links.
2063 When following a link with Emacs, it may often be useful to display
2064 this link in another window or frame. This variable can be used to
2065 set this up for the different types of links.
2066 For VM, use any of
2067 `vm-visit-folder'
2068 `vm-visit-folder-other-window'
2069 `vm-visit-folder-other-frame'
2070 For Gnus, use any of
2071 `gnus'
2072 `gnus-other-frame'
2073 `org-gnus-no-new-news'
2074 For FILE, use any of
2075 `find-file'
2076 `find-file-other-window'
2077 `find-file-other-frame'
2078 For Wanderlust use any of
2079 `wl'
2080 `wl-other-frame'
2081 For the calendar, use the variable `calendar-setup'.
2082 For BBDB, it is currently only possible to display the matches in
2083 another window."
2084 :group 'org-link-follow
2085 :type '(list
2086 (cons (const vm)
2087 (choice
2088 (const vm-visit-folder)
2089 (const vm-visit-folder-other-window)
2090 (const vm-visit-folder-other-frame)))
2091 (cons (const vm-imap)
2092 (choice
2093 (const vm-visit-imap-folder)
2094 (const vm-visit-imap-folder-other-window)
2095 (const vm-visit-imap-folder-other-frame)))
2096 (cons (const gnus)
2097 (choice
2098 (const gnus)
2099 (const gnus-other-frame)
2100 (const org-gnus-no-new-news)))
2101 (cons (const file)
2102 (choice
2103 (const find-file)
2104 (const find-file-other-window)
2105 (const find-file-other-frame)))
2106 (cons (const wl)
2107 (choice
2108 (const wl)
2109 (const wl-other-frame)))))
2111 (defcustom org-display-internal-link-with-indirect-buffer nil
2112 "Non-nil means use indirect buffer to display infile links.
2113 Activating internal links (from one location in a file to another location
2114 in the same file) normally just jumps to the location. When the link is
2115 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2116 is displayed in
2117 another window. When this option is set, the other window actually displays
2118 an indirect buffer clone of the current buffer, to avoid any visibility
2119 changes to the current buffer."
2120 :group 'org-link-follow
2121 :type 'boolean)
2123 (defcustom org-open-non-existing-files nil
2124 "Non-nil means `org-open-file' will open non-existing files.
2125 When nil, an error will be generated.
2126 This variable applies only to external applications because they
2127 might choke on non-existing files. If the link is to a file that
2128 will be opened in Emacs, the variable is ignored."
2129 :group 'org-link-follow
2130 :type 'boolean)
2132 (defcustom org-open-directory-means-index-dot-org nil
2133 "Non-nil means a link to a directory really means to index.org.
2134 When nil, following a directory link will run dired or open a finder/explorer
2135 window on that directory."
2136 :group 'org-link-follow
2137 :type 'boolean)
2139 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2140 "Non-nil means ask for confirmation before executing shell links.
2141 Shell links can be dangerous: just think about a link
2143 [[shell:rm -rf ~/*][Google Search]]
2145 This link would show up in your Org document as \"Google Search\",
2146 but really it would remove your entire home directory.
2147 Therefore we advise against setting this variable to nil.
2148 Just change it to `y-or-n-p' if you want to confirm with a
2149 single keystroke rather than having to type \"yes\"."
2150 :group 'org-link-follow
2151 :type '(choice
2152 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2153 (const :tag "with y-or-n (faster)" y-or-n-p)
2154 (const :tag "no confirmation (dangerous)" nil)))
2155 (put 'org-confirm-shell-link-function
2156 'safe-local-variable
2157 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2159 (defcustom org-confirm-shell-link-not-regexp ""
2160 "A regexp to skip confirmation for shell links."
2161 :group 'org-link-follow
2162 :version "24.1"
2163 :type 'regexp)
2165 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2166 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2167 Elisp links can be dangerous: just think about a link
2169 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2171 This link would show up in your Org document as \"Google Search\",
2172 but really it would remove your entire home directory.
2173 Therefore we advise against setting this variable to nil.
2174 Just change it to `y-or-n-p' if you want to confirm with a
2175 single keystroke rather than having to type \"yes\"."
2176 :group 'org-link-follow
2177 :type '(choice
2178 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2179 (const :tag "with y-or-n (faster)" y-or-n-p)
2180 (const :tag "no confirmation (dangerous)" nil)))
2181 (put 'org-confirm-shell-link-function
2182 'safe-local-variable
2183 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2185 (defcustom org-confirm-elisp-link-not-regexp ""
2186 "A regexp to skip confirmation for Elisp links."
2187 :group 'org-link-follow
2188 :version "24.1"
2189 :type 'regexp)
2191 (defconst org-file-apps-defaults-gnu
2192 '((remote . emacs)
2193 (system . mailcap)
2194 (t . mailcap))
2195 "Default file applications on a UNIX or GNU/Linux system.
2196 See `org-file-apps'.")
2198 (defconst org-file-apps-defaults-macosx
2199 '((remote . emacs)
2200 (system . "open %s")
2201 ("ps.gz" . "gv %s")
2202 ("eps.gz" . "gv %s")
2203 ("dvi" . "xdvi %s")
2204 ("fig" . "xfig %s")
2205 (t . "open %s"))
2206 "Default file applications on a macOS system.
2207 The system \"open\" is known as a default, but we use X11 applications
2208 for some files for which the OS does not have a good default.
2209 See `org-file-apps'.")
2211 (defconst org-file-apps-defaults-windowsnt
2212 (list '(remote . emacs)
2213 (cons 'system (lambda (file _path)
2214 (with-no-warnings (w32-shell-execute "open" file))))
2215 (cons t (lambda (file _path)
2216 (with-no-warnings (w32-shell-execute "open" file)))))
2217 "Default file applications on a Windows NT system.
2218 The system \"open\" is used for most files.
2219 See `org-file-apps'.")
2221 (defcustom org-file-apps
2222 '((auto-mode . emacs)
2223 ("\\.mm\\'" . default)
2224 ("\\.x?html?\\'" . default)
2225 ("\\.pdf\\'" . default))
2226 "External applications for opening `file:path' items in a document.
2227 \\<org-mode-map>\
2229 Org mode uses system defaults for different file types, but
2230 you can use this variable to set the application for a given file
2231 extension. The entries in this list are cons cells where the car identifies
2232 files and the cdr the corresponding command.
2234 Possible values for the file identifier are:
2236 \"string\" A string as a file identifier can be interpreted in different
2237 ways, depending on its contents:
2239 - Alphanumeric characters only:
2240 Match links with this file extension.
2241 Example: (\"pdf\" . \"evince %s\")
2242 to open PDFs with evince.
2244 - Regular expression: Match links where the
2245 filename matches the regexp. If you want to
2246 use groups here, use shy groups.
2248 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2249 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2250 to open *.html and *.xhtml with firefox.
2252 - Regular expression which contains (non-shy) groups:
2253 Match links where the whole link, including \"::\", and
2254 anything after that, matches the regexp.
2255 In a custom command string, %1, %2, etc. are replaced with
2256 the parts of the link that were matched by the groups.
2257 For backwards compatibility, if a command string is given
2258 that does not use any of the group matches, this case is
2259 handled identically to the second one (i.e. match against
2260 file name only).
2261 In a custom function, you can access the group matches with
2262 (match-string n link).
2264 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2265 \"evince -p %1 %s\")
2266 to open [[file:document.pdf::5]] with evince at page 5.
2268 `directory' Matches a directory
2269 `remote' Matches a remote file, accessible through tramp or efs.
2270 Remote files most likely should be visited through Emacs
2271 because external applications cannot handle such paths.
2272 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2273 so all files Emacs knows how to handle. Using this with
2274 command `emacs' will open most files in Emacs. Beware that this
2275 will also open html files inside Emacs, unless you add
2276 (\"html\" . default) to the list as well.
2277 `system' The system command to open files, like `open' on Windows
2278 and macOS, and mailcap under GNU/Linux. This is the command
2279 that will be selected if you call `org-open-at-point' with a
2280 double prefix argument (`\\[universal-argument] \
2281 \\[universal-argument] \\[org-open-at-point]').
2282 t Default for files not matched by any of the other options.
2284 Possible values for the command are:
2286 `emacs' The file will be visited by the current Emacs process.
2287 `default' Use the default application for this file type, which is the
2288 association for t in the list, most likely in the system-specific
2289 part. This can be used to overrule an unwanted setting in the
2290 system-specific variable.
2291 `system' Use the system command for opening files, like \"open\".
2292 This command is specified by the entry whose car is `system'.
2293 Most likely, the system-specific version of this variable
2294 does define this command, but you can overrule/replace it
2295 here.
2296 `mailcap' Use command specified in the mailcaps.
2297 string A command to be executed by a shell; %s will be replaced
2298 by the path to the file.
2299 function A Lisp function, which will be called with two arguments:
2300 the file path and the original link string, without the
2301 \"file:\" prefix.
2303 For more examples, see the system specific constants
2304 `org-file-apps-defaults-macosx'
2305 `org-file-apps-defaults-windowsnt'
2306 `org-file-apps-defaults-gnu'."
2307 :group 'org-link-follow
2308 :type '(repeat
2309 (cons (choice :value ""
2310 (string :tag "Extension")
2311 (const :tag "System command to open files" system)
2312 (const :tag "Default for unrecognized files" t)
2313 (const :tag "Remote file" remote)
2314 (const :tag "Links to a directory" directory)
2315 (const :tag "Any files that have Emacs modes"
2316 auto-mode))
2317 (choice :value ""
2318 (const :tag "Visit with Emacs" emacs)
2319 (const :tag "Use default" default)
2320 (const :tag "Use the system command" system)
2321 (string :tag "Command")
2322 (function :tag "Function")))))
2324 (defcustom org-doi-server-url "http://dx.doi.org/"
2325 "The URL of the DOI server."
2326 :type 'string
2327 :version "24.3"
2328 :group 'org-link-follow)
2330 (defgroup org-refile nil
2331 "Options concerning refiling entries in Org mode."
2332 :tag "Org Refile"
2333 :group 'org)
2335 (defcustom org-directory "~/org"
2336 "Directory with Org files.
2337 This is just a default location to look for Org files. There is no need
2338 at all to put your files into this directory. It is used in the
2339 following situations:
2341 1. When a capture template specifies a target file that is not an
2342 absolute path. The path will then be interpreted relative to
2343 `org-directory'
2344 2. When the value of variable `org-agenda-files' is a single file, any
2345 relative paths in this file will be taken as relative to
2346 `org-directory'."
2347 :group 'org-refile
2348 :group 'org-capture
2349 :type 'directory)
2351 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2352 "Default target for storing notes.
2353 Used as a fall back file for org-capture.el, for templates that
2354 do not specify a target file."
2355 :group 'org-refile
2356 :group 'org-capture
2357 :type 'file)
2359 (defcustom org-reverse-note-order nil
2360 "Non-nil means store new notes at the beginning of a file or entry.
2361 When nil, new notes will be filed to the end of a file or entry.
2362 This can also be a list with cons cells of regular expressions that
2363 are matched against file names, and values."
2364 :group 'org-capture
2365 :group 'org-refile
2366 :type '(choice
2367 (const :tag "Reverse always" t)
2368 (const :tag "Reverse never" nil)
2369 (repeat :tag "By file name regexp"
2370 (cons regexp boolean))))
2372 (defcustom org-log-refile nil
2373 "Information to record when a task is refiled.
2375 Possible values are:
2377 nil Don't add anything
2378 time Add a time stamp to the task
2379 note Prompt for a note and add it with template `org-log-note-headings'
2381 This option can also be set with on a per-file-basis with
2383 #+STARTUP: nologrefile
2384 #+STARTUP: logrefile
2385 #+STARTUP: lognoterefile
2387 You can have local logging settings for a subtree by setting the LOGGING
2388 property to one or more of these keywords.
2390 When bulk-refiling from the agenda, the value `note' is forbidden and
2391 will temporarily be changed to `time'."
2392 :group 'org-refile
2393 :group 'org-progress
2394 :version "24.1"
2395 :type '(choice
2396 (const :tag "No logging" nil)
2397 (const :tag "Record timestamp" time)
2398 (const :tag "Record timestamp with note." note)))
2400 (defcustom org-refile-targets nil
2401 "Targets for refiling entries with `\\[org-refile]'.
2402 This is a list of cons cells. Each cell contains:
2403 - a specification of the files to be considered, either a list of files,
2404 or a symbol whose function or variable value will be used to retrieve
2405 a file name or a list of file names. If you use `org-agenda-files' for
2406 that, all agenda files will be scanned for targets. Nil means consider
2407 headings in the current buffer.
2408 - A specification of how to find candidate refile targets. This may be
2409 any of:
2410 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2411 This tag has to be present in all target headlines, inheritance will
2412 not be considered.
2413 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2414 todo keyword.
2415 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2416 headlines that are refiling targets.
2417 - a cons cell (:level . N). Any headline of level N is considered a target.
2418 Note that, when `org-odd-levels-only' is set, level corresponds to
2419 order in hierarchy, not to the number of stars.
2420 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2421 Note that, when `org-odd-levels-only' is set, level corresponds to
2422 order in hierarchy, not to the number of stars.
2424 Each element of this list generates a set of possible targets.
2425 The union of these sets is presented (with completion) to
2426 the user by `org-refile'.
2428 You can set the variable `org-refile-target-verify-function' to a function
2429 to verify each headline found by the simple criteria above.
2431 When this variable is nil, all top-level headlines in the current buffer
2432 are used, equivalent to the value `((nil . (:level . 1))'."
2433 :group 'org-refile
2434 :type '(repeat
2435 (cons
2436 (choice :value org-agenda-files
2437 (const :tag "All agenda files" org-agenda-files)
2438 (const :tag "Current buffer" nil)
2439 (function) (variable) (file))
2440 (choice :tag "Identify target headline by"
2441 (cons :tag "Specific tag" (const :value :tag) (string))
2442 (cons :tag "TODO keyword" (const :value :todo) (string))
2443 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2444 (cons :tag "Level number" (const :value :level) (integer))
2445 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2447 (defcustom org-refile-target-verify-function nil
2448 "Function to verify if the headline at point should be a refile target.
2449 The function will be called without arguments, with point at the
2450 beginning of the headline. It should return t and leave point
2451 where it is if the headline is a valid target for refiling.
2453 If the target should not be selected, the function must return nil.
2454 In addition to this, it may move point to a place from where the search
2455 should be continued. For example, the function may decide that the entire
2456 subtree of the current entry should be excluded and move point to the end
2457 of the subtree."
2458 :group 'org-refile
2459 :type '(choice
2460 (const nil)
2461 (function)))
2463 (defcustom org-refile-use-cache nil
2464 "Non-nil means cache refile targets to speed up the process.
2465 \\<org-mode-map>\
2466 The cache for a particular file will be updated automatically when
2467 the buffer has been killed, or when any of the marker used for flagging
2468 refile targets no longer points at a live buffer.
2469 If you have added new entries to a buffer that might themselves be targets,
2470 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2471 if you find that easier, \
2472 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2473 \\[org-refile]'."
2474 :group 'org-refile
2475 :version "24.1"
2476 :type 'boolean)
2478 (defcustom org-refile-use-outline-path nil
2479 "Non-nil means provide refile targets as paths.
2480 So a level 3 headline will be available as level1/level2/level3.
2482 When the value is `file', also include the file name (without directory)
2483 into the path. In this case, you can also stop the completion after
2484 the file name, to get entries inserted as top level in the file.
2486 When `full-file-path', include the full file path.
2488 When `buffer-name', use the buffer name."
2489 :group 'org-refile
2490 :type '(choice
2491 (const :tag "Not" nil)
2492 (const :tag "Yes" t)
2493 (const :tag "Start with file name" file)
2494 (const :tag "Start with full file path" full-file-path)
2495 (const :tag "Start with buffer name" buffer-name)))
2497 (defcustom org-outline-path-complete-in-steps t
2498 "Non-nil means complete the outline path in hierarchical steps.
2499 When Org uses the refile interface to select an outline path (see
2500 `org-refile-use-outline-path'), the completion of the path can be
2501 done in a single go, or it can be done in steps down the headline
2502 hierarchy. Going in steps is probably the best if you do not use
2503 a special completion package like `ido' or `icicles'. However,
2504 when using these packages, going in one step can be very fast,
2505 while still showing the whole path to the entry."
2506 :group 'org-refile
2507 :type 'boolean)
2509 (defcustom org-refile-allow-creating-parent-nodes nil
2510 "Non-nil means allow the creation of new nodes as refile targets.
2511 New nodes are then created by adding \"/new node name\" to the completion
2512 of an existing node. When the value of this variable is `confirm',
2513 new node creation must be confirmed by the user (recommended).
2514 When nil, the completion must match an existing entry.
2516 Note that, if the new heading is not seen by the criteria
2517 listed in `org-refile-targets', multiple instances of the same
2518 heading would be created by trying again to file under the new
2519 heading."
2520 :group 'org-refile
2521 :type '(choice
2522 (const :tag "Never" nil)
2523 (const :tag "Always" t)
2524 (const :tag "Prompt for confirmation" confirm)))
2526 (defcustom org-refile-active-region-within-subtree nil
2527 "Non-nil means also refile active region within a subtree.
2529 By default `org-refile' doesn't allow refiling regions if they
2530 don't contain a set of subtrees, but it might be convenient to
2531 do so sometimes: in that case, the first line of the region is
2532 converted to a headline before refiling."
2533 :group 'org-refile
2534 :version "24.1"
2535 :type 'boolean)
2537 (defgroup org-todo nil
2538 "Options concerning TODO items in Org mode."
2539 :tag "Org TODO"
2540 :group 'org)
2542 (defgroup org-progress nil
2543 "Options concerning Progress logging in Org mode."
2544 :tag "Org Progress"
2545 :group 'org-time)
2547 (defvar org-todo-interpretation-widgets
2548 '((:tag "Sequence (cycling hits every state)" sequence)
2549 (:tag "Type (cycling directly to DONE)" type))
2550 "The available interpretation symbols for customizing `org-todo-keywords'.
2551 Interested libraries should add to this list.")
2553 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2554 "List of TODO entry keyword sequences and their interpretation.
2555 \\<org-mode-map>This is a list of sequences.
2557 Each sequence starts with a symbol, either `sequence' or `type',
2558 indicating if the keywords should be interpreted as a sequence of
2559 action steps, or as different types of TODO items. The first
2560 keywords are states requiring action - these states will select a headline
2561 for inclusion into the global TODO list Org produces. If one of the
2562 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2563 signify that no further action is necessary. If \"|\" is not found,
2564 the last keyword is treated as the only DONE state of the sequence.
2566 The command `\\[org-todo]' cycles an entry through these states, and one
2567 additional state where no keyword is present. For details about this
2568 cycling, see the manual.
2570 TODO keywords and interpretation can also be set on a per-file basis with
2571 the special #+SEQ_TODO and #+TYP_TODO lines.
2573 Each keyword can optionally specify a character for fast state selection
2574 \(in combination with the variable `org-use-fast-todo-selection')
2575 and specifiers for state change logging, using the same syntax that
2576 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2577 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2578 indicates to record a time stamp each time this state is selected.
2580 Each keyword may also specify if a timestamp or a note should be
2581 recorded when entering or leaving the state, by adding additional
2582 characters in the parenthesis after the keyword. This looks like this:
2583 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2584 record only the time of the state change. With X and Y being either
2585 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2586 Y when leaving the state if and only if the *target* state does not
2587 define X. You may omit any of the fast-selection key or X or /Y,
2588 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2590 For backward compatibility, this variable may also be just a list
2591 of keywords. In this case the interpretation (sequence or type) will be
2592 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2593 :group 'org-todo
2594 :group 'org-keywords
2595 :type '(choice
2596 (repeat :tag "Old syntax, just keywords"
2597 (string :tag "Keyword"))
2598 (repeat :tag "New syntax"
2599 (cons
2600 (choice
2601 :tag "Interpretation"
2602 ;;Quick and dirty way to see
2603 ;;`org-todo-interpretations'. This takes the
2604 ;;place of item arguments
2605 :convert-widget
2606 (lambda (widget)
2607 (widget-put widget
2608 :args (mapcar
2609 (lambda (x)
2610 (widget-convert
2611 (cons 'const x)))
2612 org-todo-interpretation-widgets))
2613 widget))
2614 (repeat
2615 (string :tag "Keyword"))))))
2617 (defvar-local org-todo-keywords-1 nil
2618 "All TODO and DONE keywords active in a buffer.")
2619 (defvar org-todo-keywords-for-agenda nil)
2620 (defvar org-done-keywords-for-agenda nil)
2621 (defvar org-todo-keyword-alist-for-agenda nil)
2622 (defvar org-tag-alist-for-agenda nil
2623 "Alist of all tags from all agenda files.")
2624 (defvar org-tag-groups-alist-for-agenda nil
2625 "Alist of all groups tags from all current agenda files.")
2626 (defvar-local org-tag-groups-alist nil)
2627 (defvar org-agenda-contributing-files nil)
2628 (defvar-local org-current-tag-alist nil
2629 "Alist of all tag groups in current buffer.
2630 This variable takes into consideration `org-tag-alist',
2631 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2632 (defvar-local org-not-done-keywords nil)
2633 (defvar-local org-done-keywords nil)
2634 (defvar-local org-todo-heads nil)
2635 (defvar-local org-todo-sets nil)
2636 (defvar-local org-todo-log-states nil)
2637 (defvar-local org-todo-kwd-alist nil)
2638 (defvar-local org-todo-key-alist nil)
2639 (defvar-local org-todo-key-trigger nil)
2641 (defcustom org-todo-interpretation 'sequence
2642 "Controls how TODO keywords are interpreted.
2643 This variable is in principle obsolete and is only used for
2644 backward compatibility, if the interpretation of todo keywords is
2645 not given already in `org-todo-keywords'. See that variable for
2646 more information."
2647 :group 'org-todo
2648 :group 'org-keywords
2649 :type '(choice (const sequence)
2650 (const type)))
2652 (defcustom org-use-fast-todo-selection t
2653 "\\<org-mode-map>\
2654 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2655 This variable describes if and under what circumstances the cycling
2656 mechanism for TODO keywords will be replaced by a single-key, direct
2657 selection scheme.
2659 When nil, fast selection is never used.
2661 When the symbol `prefix', it will be used when `org-todo' is called
2662 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2663 in an Org buffer, and
2664 `\\[universal-argument] t' in an agenda buffer.
2666 When t, fast selection is used by default. In this case, the prefix
2667 argument forces cycling instead.
2669 In all cases, the special interface is only used if access keys have
2670 actually been assigned by the user, i.e. if keywords in the configuration
2671 are followed by a letter in parenthesis, like TODO(t)."
2672 :group 'org-todo
2673 :type '(choice
2674 (const :tag "Never" nil)
2675 (const :tag "By default" t)
2676 (const :tag "Only with C-u C-c C-t" prefix)))
2678 (defcustom org-provide-todo-statistics t
2679 "Non-nil means update todo statistics after insert and toggle.
2680 ALL-HEADLINES means update todo statistics by including headlines
2681 with no TODO keyword as well, counting them as not done.
2682 A list of TODO keywords means the same, but skip keywords that are
2683 not in this list.
2684 When set to a list of two lists, the first list contains keywords
2685 to consider as TODO keywords, the second list contains keywords
2686 to consider as DONE keywords.
2688 When this is set, todo statistics is updated in the parent of the
2689 current entry each time a todo state is changed."
2690 :group 'org-todo
2691 :type '(choice
2692 (const :tag "Yes, only for TODO entries" t)
2693 (const :tag "Yes, including all entries" all-headlines)
2694 (repeat :tag "Yes, for TODOs in this list"
2695 (string :tag "TODO keyword"))
2696 (list :tag "Yes, for TODOs and DONEs in these lists"
2697 (repeat (string :tag "TODO keyword"))
2698 (repeat (string :tag "DONE keyword")))
2699 (other :tag "No TODO statistics" nil)))
2701 (defcustom org-hierarchical-todo-statistics t
2702 "Non-nil means TODO statistics covers just direct children.
2703 When nil, all entries in the subtree are considered.
2704 This has only an effect if `org-provide-todo-statistics' is set.
2705 To set this to nil for only a single subtree, use a COOKIE_DATA
2706 property and include the word \"recursive\" into the value."
2707 :group 'org-todo
2708 :type 'boolean)
2710 (defcustom org-after-todo-state-change-hook nil
2711 "Hook which is run after the state of a TODO item was changed.
2712 The new state (a string with a TODO keyword, or nil) is available in the
2713 Lisp variable `org-state'."
2714 :group 'org-todo
2715 :type 'hook)
2717 (defvar org-blocker-hook nil
2718 "Hook for functions that are allowed to block a state change.
2720 Functions in this hook should not modify the buffer.
2721 Each function gets as its single argument a property list,
2722 see `org-trigger-hook' for more information about this list.
2724 If any of the functions in this hook returns nil, the state change
2725 is blocked.")
2727 (defvar org-trigger-hook nil
2728 "Hook for functions that are triggered by a state change.
2730 Each function gets as its single argument a property list with at
2731 least the following elements:
2733 (:type type-of-change :position pos-at-entry-start
2734 :from old-state :to new-state)
2736 Depending on the type, more properties may be present.
2738 This mechanism is currently implemented for:
2740 TODO state changes
2741 ------------------
2742 :type todo-state-change
2743 :from previous state (keyword as a string), or nil, or a symbol
2744 `todo' or `done', to indicate the general type of state.
2745 :to new state, like in :from")
2747 (defcustom org-enforce-todo-dependencies nil
2748 "Non-nil means undone TODO entries will block switching the parent to DONE.
2749 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2750 be blocked if any prior sibling is not yet done.
2751 Finally, if the parent is blocked because of ordered siblings of its own,
2752 the child will also be blocked."
2753 :set (lambda (var val)
2754 (set var val)
2755 (if val
2756 (add-hook 'org-blocker-hook
2757 'org-block-todo-from-children-or-siblings-or-parent)
2758 (remove-hook 'org-blocker-hook
2759 'org-block-todo-from-children-or-siblings-or-parent)))
2760 :group 'org-todo
2761 :type 'boolean)
2763 (defcustom org-enforce-todo-checkbox-dependencies nil
2764 "Non-nil means unchecked boxes will block switching the parent to DONE.
2765 When this is nil, checkboxes have no influence on switching TODO states.
2766 When non-nil, you first need to check off all check boxes before the TODO
2767 entry can be switched to DONE.
2768 This variable needs to be set before org.el is loaded, and you need to
2769 restart Emacs after a change to make the change effective. The only way
2770 to change is while Emacs is running is through the customize interface."
2771 :set (lambda (var val)
2772 (set var val)
2773 (if val
2774 (add-hook 'org-blocker-hook
2775 'org-block-todo-from-checkboxes)
2776 (remove-hook 'org-blocker-hook
2777 'org-block-todo-from-checkboxes)))
2778 :group 'org-todo
2779 :type 'boolean)
2781 (defcustom org-treat-insert-todo-heading-as-state-change nil
2782 "Non-nil means inserting a TODO heading is treated as state change.
2783 So when the command `\\[org-insert-todo-heading]' is used, state change
2784 logging will apply if appropriate. When nil, the new TODO item will
2785 be inserted directly, and no logging will take place."
2786 :group 'org-todo
2787 :type 'boolean)
2789 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2790 "Non-nil means switching TODO states with S-cursor counts as state change.
2791 This is the default behavior. However, setting this to nil allows a
2792 convenient way to select a TODO state and bypass any logging associated
2793 with that."
2794 :group 'org-todo
2795 :type 'boolean)
2797 (defcustom org-todo-state-tags-triggers nil
2798 "Tag changes that should be triggered by TODO state changes.
2799 This is a list. Each entry is
2801 (state-change (tag . flag) .......)
2803 State-change can be a string with a state, and empty string to indicate the
2804 state that has no TODO keyword, or it can be one of the symbols `todo'
2805 or `done', meaning any not-done or done state, respectively."
2806 :group 'org-todo
2807 :group 'org-tags
2808 :type '(repeat
2809 (cons (choice :tag "When changing to"
2810 (const :tag "Not-done state" todo)
2811 (const :tag "Done state" done)
2812 (string :tag "State"))
2813 (repeat
2814 (cons :tag "Tag action"
2815 (string :tag "Tag")
2816 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2818 (defcustom org-log-done nil
2819 "Information to record when a task moves to the DONE state.
2821 Possible values are:
2823 nil Don't add anything, just change the keyword
2824 time Add a time stamp to the task
2825 note Prompt for a note and add it with template `org-log-note-headings'
2827 This option can also be set with on a per-file-basis with
2829 #+STARTUP: nologdone
2830 #+STARTUP: logdone
2831 #+STARTUP: lognotedone
2833 You can have local logging settings for a subtree by setting the LOGGING
2834 property to one or more of these keywords."
2835 :group 'org-todo
2836 :group 'org-progress
2837 :type '(choice
2838 (const :tag "No logging" nil)
2839 (const :tag "Record CLOSED timestamp" time)
2840 (const :tag "Record CLOSED timestamp with note." note)))
2842 ;; Normalize old uses of org-log-done.
2843 (cond
2844 ((eq org-log-done t) (setq org-log-done 'time))
2845 ((and (listp org-log-done) (memq 'done org-log-done))
2846 (setq org-log-done 'note)))
2848 (defcustom org-log-reschedule nil
2849 "Information to record when the scheduling date of a tasks is modified.
2851 Possible values are:
2853 nil Don't add anything, just change the date
2854 time Add a time stamp to the task
2855 note Prompt for a note and add it with template `org-log-note-headings'
2857 This option can also be set with on a per-file-basis with
2859 #+STARTUP: nologreschedule
2860 #+STARTUP: logreschedule
2861 #+STARTUP: lognotereschedule"
2862 :group 'org-todo
2863 :group 'org-progress
2864 :type '(choice
2865 (const :tag "No logging" nil)
2866 (const :tag "Record timestamp" time)
2867 (const :tag "Record timestamp with note." note)))
2869 (defcustom org-log-redeadline nil
2870 "Information to record when the deadline date of a tasks is modified.
2872 Possible values are:
2874 nil Don't add anything, just change the date
2875 time Add a time stamp to the task
2876 note Prompt for a note and add it with template `org-log-note-headings'
2878 This option can also be set with on a per-file-basis with
2880 #+STARTUP: nologredeadline
2881 #+STARTUP: logredeadline
2882 #+STARTUP: lognoteredeadline
2884 You can have local logging settings for a subtree by setting the LOGGING
2885 property to one or more of these keywords."
2886 :group 'org-todo
2887 :group 'org-progress
2888 :type '(choice
2889 (const :tag "No logging" nil)
2890 (const :tag "Record timestamp" time)
2891 (const :tag "Record timestamp with note." note)))
2893 (defcustom org-log-note-clock-out nil
2894 "Non-nil means record a note when clocking out of an item.
2895 This can also be configured on a per-file basis by adding one of
2896 the following lines anywhere in the buffer:
2898 #+STARTUP: lognoteclock-out
2899 #+STARTUP: nolognoteclock-out"
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type 'boolean)
2904 (defcustom org-log-done-with-time t
2905 "Non-nil means the CLOSED time stamp will contain date and time.
2906 When nil, only the date will be recorded."
2907 :group 'org-progress
2908 :type 'boolean)
2910 (defcustom org-log-note-headings
2911 '((done . "CLOSING NOTE %t")
2912 (state . "State %-12s from %-12S %t")
2913 (note . "Note taken on %t")
2914 (reschedule . "Rescheduled from %S on %t")
2915 (delschedule . "Not scheduled, was %S on %t")
2916 (redeadline . "New deadline from %S on %t")
2917 (deldeadline . "Removed deadline, was %S on %t")
2918 (refile . "Refiled on %t")
2919 (clock-out . ""))
2920 "Headings for notes added to entries.
2922 The value is an alist, with the car being a symbol indicating the
2923 note context, and the cdr is the heading to be used. The heading
2924 may also be the empty string. The following placeholders can be
2925 used:
2927 %t a time stamp.
2928 %T an active time stamp instead the default inactive one
2929 %d a short-format time stamp.
2930 %D an active short-format time stamp.
2931 %s the new TODO state or time stamp (inactive), in double quotes.
2932 %S the old TODO state or time stamp (inactive), in double quotes.
2933 %u the user name.
2934 %U full user name.
2936 In fact, it is not a good idea to change the `state' entry,
2937 because Agenda Log mode depends on the format of these entries."
2938 :group 'org-todo
2939 :group 'org-progress
2940 :type '(list :greedy t
2941 (cons (const :tag "Heading when closing an item" done) string)
2942 (cons (const :tag
2943 "Heading when changing todo state (todo sequence only)"
2944 state) string)
2945 (cons (const :tag "Heading when just taking a note" note) string)
2946 (cons (const :tag "Heading when rescheduling" reschedule) string)
2947 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2948 (cons (const :tag "Heading when changing deadline" redeadline) string)
2949 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2950 (cons (const :tag "Heading when refiling" refile) string)
2951 (cons (const :tag "Heading when clocking out" clock-out) string)))
2953 (unless (assq 'note org-log-note-headings)
2954 (push '(note . "%t") org-log-note-headings))
2956 (defcustom org-log-into-drawer nil
2957 "Non-nil means insert state change notes and time stamps into a drawer.
2958 When nil, state changes notes will be inserted after the headline and
2959 any scheduling and clock lines, but not inside a drawer.
2961 The value of this variable should be the name of the drawer to use.
2962 LOGBOOK is proposed as the default drawer for this purpose, you can
2963 also set this to a string to define the drawer of your choice.
2965 A value of t is also allowed, representing \"LOGBOOK\".
2967 A value of t or nil can also be set with on a per-file-basis with
2969 #+STARTUP: logdrawer
2970 #+STARTUP: nologdrawer
2972 If this variable is set, `org-log-state-notes-insert-after-drawers'
2973 will be ignored.
2975 You can set the property LOG_INTO_DRAWER to overrule this setting for
2976 a subtree.
2978 Do not check directly this variable in a Lisp program. Call
2979 function `org-log-into-drawer' instead."
2980 :group 'org-todo
2981 :group 'org-progress
2982 :type '(choice
2983 (const :tag "Not into a drawer" nil)
2984 (const :tag "LOGBOOK" t)
2985 (string :tag "Other")))
2987 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2989 (defun org-log-into-drawer ()
2990 "Name of the log drawer, as a string, or nil.
2991 This is the value of `org-log-into-drawer'. However, if the
2992 current entry has or inherits a LOG_INTO_DRAWER property, it will
2993 be used instead of the default value."
2994 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2995 (cond ((equal p "nil") nil)
2996 ((equal p "t") "LOGBOOK")
2997 ((stringp p) p)
2998 (p "LOGBOOK")
2999 ((stringp org-log-into-drawer) org-log-into-drawer)
3000 (org-log-into-drawer "LOGBOOK"))))
3002 (defcustom org-log-state-notes-insert-after-drawers nil
3003 "Non-nil means insert state change notes after any drawers in entry.
3004 Only the drawers that *immediately* follow the headline and the
3005 deadline/scheduled line are skipped.
3006 When nil, insert notes right after the heading and perhaps the line
3007 with deadline/scheduling if present.
3009 This variable will have no effect if `org-log-into-drawer' is
3010 set."
3011 :group 'org-todo
3012 :group 'org-progress
3013 :type 'boolean)
3015 (defcustom org-log-states-order-reversed t
3016 "Non-nil means the latest state note will be directly after heading.
3017 When nil, the state change notes will be ordered according to time.
3019 This option can also be set with on a per-file-basis with
3021 #+STARTUP: logstatesreversed
3022 #+STARTUP: nologstatesreversed"
3023 :group 'org-todo
3024 :group 'org-progress
3025 :type 'boolean)
3027 (defcustom org-todo-repeat-to-state nil
3028 "The TODO state to which a repeater should return the repeating task.
3029 By default this is the first task of a TODO sequence or the
3030 previous state of a TYPE_TODO set. But you can specify to use
3031 the previous state in a TODO sequence or a string.
3033 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3034 entry, which has precedence over this option."
3035 :group 'org-todo
3036 :version "24.1"
3037 :type '(choice (const :tag "Use the previous TODO state" t)
3038 (const :tag "Use the head of the TODO sequence" nil)
3039 (string :tag "Use a specific TODO state")))
3041 (defcustom org-log-repeat 'time
3042 "Non-nil means record moving through the DONE state when triggering repeat.
3043 An auto-repeating task is immediately switched back to TODO when
3044 marked DONE. If you are not logging state changes (by adding \"@\"
3045 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3046 record a closing note, there will be no record of the task moving
3047 through DONE. This variable forces taking a note anyway.
3049 nil Don't force a record
3050 time Record a time stamp
3051 note Prompt for a note and add it with template `org-log-note-headings'
3053 This option can also be set with on a per-file-basis with
3055 #+STARTUP: nologrepeat
3056 #+STARTUP: logrepeat
3057 #+STARTUP: lognoterepeat
3059 You can have local logging settings for a subtree by setting the LOGGING
3060 property to one or more of these keywords."
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type '(choice
3064 (const :tag "Don't force a record" nil)
3065 (const :tag "Force recording the DONE state" time)
3066 (const :tag "Force recording a note with the DONE state" note)))
3069 (defgroup org-priorities nil
3070 "Priorities in Org mode."
3071 :tag "Org Priorities"
3072 :group 'org-todo)
3074 (defcustom org-enable-priority-commands t
3075 "Non-nil means priority commands are active.
3076 When nil, these commands will be disabled, so that you never accidentally
3077 set a priority."
3078 :group 'org-priorities
3079 :type 'boolean)
3081 (defcustom org-highest-priority ?A
3082 "The highest priority of TODO items. A character like ?A, ?B etc.
3083 Must have a smaller ASCII number than `org-lowest-priority'."
3084 :group 'org-priorities
3085 :type 'character)
3087 (defcustom org-lowest-priority ?C
3088 "The lowest priority of TODO items. A character like ?A, ?B etc.
3089 Must have a larger ASCII number than `org-highest-priority'."
3090 :group 'org-priorities
3091 :type 'character)
3093 (defcustom org-default-priority ?B
3094 "The default priority of TODO items.
3095 This is the priority an item gets if no explicit priority is given.
3096 When starting to cycle on an empty priority the first step in the cycle
3097 depends on `org-priority-start-cycle-with-default'. The resulting first
3098 step priority must not exceed the range from `org-highest-priority' to
3099 `org-lowest-priority' which means that `org-default-priority' has to be
3100 in this range exclusive or inclusive the range boundaries. Else the
3101 first step refuses to set the default and the second will fall back
3102 to (depending on the command used) the highest or lowest priority."
3103 :group 'org-priorities
3104 :type 'character)
3106 (defcustom org-priority-start-cycle-with-default t
3107 "Non-nil means start with default priority when starting to cycle.
3108 When this is nil, the first step in the cycle will be (depending on the
3109 command used) one higher or lower than the default priority.
3110 See also `org-default-priority'."
3111 :group 'org-priorities
3112 :type 'boolean)
3114 (defcustom org-get-priority-function nil
3115 "Function to extract the priority from a string.
3116 The string is normally the headline. If this is nil Org computes the
3117 priority from the priority cookie like [#A] in the headline. It returns
3118 an integer, increasing by 1000 for each priority level.
3119 The user can set a different function here, which should take a string
3120 as an argument and return the numeric priority."
3121 :group 'org-priorities
3122 :version "24.1"
3123 :type '(choice
3124 (const nil)
3125 (function)))
3127 (defgroup org-time nil
3128 "Options concerning time stamps and deadlines in Org mode."
3129 :tag "Org Time"
3130 :group 'org)
3132 (defcustom org-time-stamp-rounding-minutes '(0 5)
3133 "Number of minutes to round time stamps to.
3134 \\<org-mode-map>\
3135 These are two values, the first applies when first creating a time stamp.
3136 The second applies when changing it with the commands `S-up' and `S-down'.
3137 When changing the time stamp, this means that it will change in steps
3138 of N minutes, as given by the second value.
3140 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3141 numbers should be factors of 60, so for example 5, 10, 15.
3143 When this is larger than 1, you can still force an exact time stamp by using
3144 a double prefix argument to a time stamp command like \
3145 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3146 and by using a prefix arg to `S-up/down' to specify the exact number
3147 of minutes to shift."
3148 :group 'org-time
3149 :get (lambda (var) ; Make sure both elements are there
3150 (if (integerp (default-value var))
3151 (list (default-value var) 5)
3152 (default-value var)))
3153 :type '(list
3154 (integer :tag "when inserting times")
3155 (integer :tag "when modifying times")))
3157 ;; Normalize old customizations of this variable.
3158 (when (integerp org-time-stamp-rounding-minutes)
3159 (setq org-time-stamp-rounding-minutes
3160 (list org-time-stamp-rounding-minutes
3161 org-time-stamp-rounding-minutes)))
3163 (defcustom org-display-custom-times nil
3164 "Non-nil means overlay custom formats over all time stamps.
3165 The formats are defined through the variable `org-time-stamp-custom-formats'.
3166 To turn this on on a per-file basis, insert anywhere in the file:
3167 #+STARTUP: customtime"
3168 :group 'org-time
3169 :set 'set-default
3170 :type 'sexp)
3171 (make-variable-buffer-local 'org-display-custom-times)
3173 (defcustom org-time-stamp-custom-formats
3174 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3175 "Custom formats for time stamps. See `format-time-string' for the syntax.
3176 These are overlaid over the default ISO format if the variable
3177 `org-display-custom-times' is set. Time like %H:%M should be at the
3178 end of the second format. The custom formats are also honored by export
3179 commands, if custom time display is turned on at the time of export."
3180 :group 'org-time
3181 :type 'sexp)
3183 (defun org-time-stamp-format (&optional long inactive)
3184 "Get the right format for a time string."
3185 (let ((f (if long (cdr org-time-stamp-formats)
3186 (car org-time-stamp-formats))))
3187 (if inactive
3188 (concat "[" (substring f 1 -1) "]")
3189 f)))
3191 (defcustom org-deadline-warning-days 14
3192 "Number of days before expiration during which a deadline becomes active.
3193 This variable governs the display in sparse trees and in the agenda.
3194 When 0 or negative, it means use this number (the absolute value of it)
3195 even if a deadline has a different individual lead time specified.
3197 Custom commands can set this variable in the options section."
3198 :group 'org-time
3199 :group 'org-agenda-daily/weekly
3200 :type 'integer)
3202 (defcustom org-scheduled-delay-days 0
3203 "Number of days before a scheduled item becomes active.
3204 This variable governs the display in sparse trees and in the agenda.
3205 The default value (i.e. 0) means: don't delay scheduled item.
3206 When negative, it means use this number (the absolute value of it)
3207 even if a scheduled item has a different individual delay time
3208 specified.
3210 Custom commands can set this variable in the options section."
3211 :group 'org-time
3212 :group 'org-agenda-daily/weekly
3213 :version "24.4"
3214 :package-version '(Org . "8.0")
3215 :type 'integer)
3217 (defcustom org-read-date-prefer-future t
3218 "Non-nil means assume future for incomplete date input from user.
3219 This affects the following situations:
3220 1. The user gives a month but not a year.
3221 For example, if it is April and you enter \"feb 2\", this will be read
3222 as Feb 2, *next* year. \"May 5\", however, will be this year.
3223 2. The user gives a day, but no month.
3224 For example, if today is the 15th, and you enter \"3\", Org will read
3225 this as the third of *next* month. However, if you enter \"17\",
3226 it will be considered as *this* month.
3228 If you set this variable to the symbol `time', then also the following
3229 will work:
3231 3. If the user gives a time.
3232 If the time is before now, it will be interpreted as tomorrow.
3234 Currently none of this works for ISO week specifications.
3236 When this option is nil, the current day, month and year will always be
3237 used as defaults.
3239 See also `org-agenda-jump-prefer-future'."
3240 :group 'org-time
3241 :type '(choice
3242 (const :tag "Never" nil)
3243 (const :tag "Check month and day" t)
3244 (const :tag "Check month, day, and time" time)))
3246 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3247 "Should the agenda jump command prefer the future for incomplete dates?
3248 The default is to do the same as configured in `org-read-date-prefer-future'.
3249 But you can also set a deviating value here.
3250 This may t or nil, or the symbol `org-read-date-prefer-future'."
3251 :group 'org-agenda
3252 :group 'org-time
3253 :version "24.1"
3254 :type '(choice
3255 (const :tag "Use org-read-date-prefer-future"
3256 org-read-date-prefer-future)
3257 (const :tag "Never" nil)
3258 (const :tag "Always" t)))
3260 (defcustom org-read-date-force-compatible-dates t
3261 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3263 Depending on the system Emacs is running on, certain dates cannot
3264 be represented with the type used internally to represent time.
3265 Dates between 1970-1-1 and 2038-1-1 can always be represented
3266 correctly. Some systems allow for earlier dates, some for later,
3267 some for both. One way to find out it to insert any date into an
3268 Org buffer, putting the cursor on the year and hitting S-up and
3269 S-down to test the range.
3271 When this variable is set to t, the date/time prompt will not let
3272 you specify dates outside the 1970-2037 range, so it is certain that
3273 these dates will work in whatever version of Emacs you are
3274 running, and also that you can move a file from one Emacs implementation
3275 to another. WHenever Org is forcing the year for you, it will display
3276 a message and beep.
3278 When this variable is nil, Org will check if the date is
3279 representable in the specific Emacs implementation you are using.
3280 If not, it will force a year, usually the current year, and beep
3281 to remind you. Currently this setting is not recommended because
3282 the likelihood that you will open your Org files in an Emacs that
3283 has limited date range is not negligible.
3285 A workaround for this problem is to use diary sexp dates for time
3286 stamps outside of this range."
3287 :group 'org-time
3288 :version "24.1"
3289 :type 'boolean)
3291 (defcustom org-read-date-display-live t
3292 "Non-nil means display current interpretation of date prompt live.
3293 This display will be in an overlay, in the minibuffer."
3294 :group 'org-time
3295 :type 'boolean)
3297 (defcustom org-read-date-popup-calendar t
3298 "Non-nil means pop up a calendar when prompting for a date.
3299 In the calendar, the date can be selected with mouse-1. However, the
3300 minibuffer will also be active, and you can simply enter the date as well.
3301 When nil, only the minibuffer will be available."
3302 :group 'org-time
3303 :type 'boolean)
3304 (defvaralias 'org-popup-calendar-for-date-prompt
3305 'org-read-date-popup-calendar)
3307 (defcustom org-extend-today-until 0
3308 "The hour when your day really ends. Must be an integer.
3309 This has influence for the following applications:
3310 - When switching the agenda to \"today\". It it is still earlier than
3311 the time given here, the day recognized as TODAY is actually yesterday.
3312 - When a date is read from the user and it is still before the time given
3313 here, the current date and time will be assumed to be yesterday, 23:59.
3314 Also, timestamps inserted in capture templates follow this rule.
3316 IMPORTANT: This is a feature whose implementation is and likely will
3317 remain incomplete. Really, it is only here because past midnight seems to
3318 be the favorite working time of John Wiegley :-)"
3319 :group 'org-time
3320 :type 'integer)
3322 (defcustom org-use-effective-time nil
3323 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3324 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3325 \"effective time\" of any timestamps between midnight and 8am will be
3326 23:59 of the previous day."
3327 :group 'org-time
3328 :version "24.1"
3329 :type 'boolean)
3331 (defcustom org-use-last-clock-out-time-as-effective-time nil
3332 "When non-nil, use the last clock out time for `org-todo'.
3333 Note that this option has precedence over the combined use of
3334 `org-use-effective-time' and `org-extend-today-until'."
3335 :group 'org-time
3336 :version "24.4"
3337 :package-version '(Org . "8.0")
3338 :type 'boolean)
3340 (defcustom org-edit-timestamp-down-means-later nil
3341 "Non-nil means S-down will increase the time in a time stamp.
3342 When nil, S-up will increase."
3343 :group 'org-time
3344 :type 'boolean)
3346 (defcustom org-calendar-follow-timestamp-change t
3347 "Non-nil means make the calendar window follow timestamp changes.
3348 When a timestamp is modified and the calendar window is visible, it will be
3349 moved to the new date."
3350 :group 'org-time
3351 :type 'boolean)
3353 (defgroup org-tags nil
3354 "Options concerning tags in Org mode."
3355 :tag "Org Tags"
3356 :group 'org)
3358 (defcustom org-tag-alist nil
3359 "Default tags available in Org files.
3361 The value of this variable is an alist. Associations either:
3363 (TAG)
3364 (TAG . SELECT)
3365 (SPECIAL)
3367 where TAG is a tag as a string, SELECT is character, used to
3368 select that tag through the fast tag selection interface, and
3369 SPECIAL is one of the following keywords: `:startgroup',
3370 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3371 `:newline'. These keywords are used to define a hierarchy of
3372 tags. See manual for details.
3374 When this variable is nil, Org mode bases tag input on what is
3375 already in the buffer. The value can be overridden locally by
3376 using a TAGS keyword, e.g.,
3378 #+TAGS: tag1 tag2
3380 See also `org-tag-persistent-alist' to sidestep this behavior."
3381 :group 'org-tags
3382 :type '(repeat
3383 (choice
3384 (cons :tag "Tag with key"
3385 (string :tag "Tag name")
3386 (character :tag "Access char"))
3387 (list :tag "Tag" (string :tag "Tag name"))
3388 (const :tag "Start radio group" (:startgroup))
3389 (const :tag "Start tag group, non distinct" (:startgrouptag))
3390 (const :tag "Group tags delimiter" (:grouptags))
3391 (const :tag "End radio group" (:endgroup))
3392 (const :tag "End tag group, non distinct" (:endgrouptag))
3393 (const :tag "New line" (:newline)))))
3395 (defcustom org-tag-persistent-alist nil
3396 "Tags always available in Org files.
3398 The value of this variable is an alist. Associations either:
3400 (TAG)
3401 (TAG . SELECT)
3402 (SPECIAL)
3404 where TAG is a tag as a string, SELECT is a character, used to
3405 select that tag through the fast tag selection interface, and
3406 SPECIAL is one of the following keywords: `:startgroup',
3407 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3408 `:newline'. These keywords are used to define a hierarchy of
3409 tags. See manual for details.
3411 Unlike to `org-tag-alist', tags defined in this variable do not
3412 depend on a local TAGS keyword. Instead, to disable these tags
3413 on a per-file basis, insert anywhere in the file:
3415 #+STARTUP: noptag"
3416 :group 'org-tags
3417 :type '(repeat
3418 (choice
3419 (cons :tag "Tag with key"
3420 (string :tag "Tag name")
3421 (character :tag "Access char"))
3422 (list :tag "Tag" (string :tag "Tag name"))
3423 (const :tag "Start radio group" (:startgroup))
3424 (const :tag "Start tag group, non distinct" (:startgrouptag))
3425 (const :tag "Group tags delimiter" (:grouptags))
3426 (const :tag "End radio group" (:endgroup))
3427 (const :tag "End tag group, non distinct" (:endgrouptag))
3428 (const :tag "New line" (:newline)))))
3430 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3431 "If non-nil, always offer completion for all tags of all agenda files.
3432 Instead of customizing this variable directly, you might want to
3433 set it locally for capture buffers, because there no list of
3434 tags in that file can be created dynamically (there are none).
3436 (add-hook \\='org-capture-mode-hook
3437 (lambda ()
3438 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3439 :group 'org-tags
3440 :version "24.1"
3441 :type 'boolean)
3443 (defvar org-file-tags nil
3444 "List of tags that can be inherited by all entries in the file.
3445 The tags will be inherited if the variable `org-use-tag-inheritance'
3446 says they should be.
3447 This variable is populated from #+FILETAGS lines.")
3449 (defcustom org-use-fast-tag-selection 'auto
3450 "Non-nil means use fast tag selection scheme.
3451 This is a special interface to select and deselect tags with single keys.
3452 When nil, fast selection is never used.
3453 When the symbol `auto', fast selection is used if and only if selection
3454 characters for tags have been configured, either through the variable
3455 `org-tag-alist' or through a #+TAGS line in the buffer.
3456 When t, fast selection is always used and selection keys are assigned
3457 automatically if necessary."
3458 :group 'org-tags
3459 :type '(choice
3460 (const :tag "Always" t)
3461 (const :tag "Never" nil)
3462 (const :tag "When selection characters are configured" auto)))
3464 (defcustom org-fast-tag-selection-single-key nil
3465 "Non-nil means fast tag selection exits after first change.
3466 When nil, you have to press RET to exit it.
3467 During fast tag selection, you can toggle this flag with `C-c'.
3468 This variable can also have the value `expert'. In this case, the window
3469 displaying the tags menu is not even shown, until you press C-c again."
3470 :group 'org-tags
3471 :type '(choice
3472 (const :tag "No" nil)
3473 (const :tag "Yes" t)
3474 (const :tag "Expert" expert)))
3476 (defvar org-fast-tag-selection-include-todo nil
3477 "Non-nil means fast tags selection interface will also offer TODO states.
3478 This is an undocumented feature, you should not rely on it.")
3480 (defcustom org-tags-column -77
3481 "The column to which tags should be indented in a headline.
3482 If this number is positive, it specifies the column. If it is negative,
3483 it means that the tags should be flushright to that column. For example,
3484 -80 works well for a normal 80 character screen.
3485 When 0, place tags directly after headline text, with only one space in
3486 between."
3487 :group 'org-tags
3488 :type 'integer)
3490 (defcustom org-auto-align-tags t
3491 "Non-nil keeps tags aligned when modifying headlines.
3492 Some operations (i.e. demoting) change the length of a headline and
3493 therefore shift the tags around. With this option turned on, after
3494 each such operation the tags are again aligned to `org-tags-column'."
3495 :group 'org-tags
3496 :type 'boolean)
3498 (defcustom org-use-tag-inheritance t
3499 "Non-nil means tags in levels apply also for sublevels.
3500 When nil, only the tags directly given in a specific line apply there.
3501 This may also be a list of tags that should be inherited, or a regexp that
3502 matches tags that should be inherited. Additional control is possible
3503 with the variable `org-tags-exclude-from-inheritance' which gives an
3504 explicit list of tags to be excluded from inheritance, even if the value of
3505 `org-use-tag-inheritance' would select it for inheritance.
3507 If this option is t, a match early-on in a tree can lead to a large
3508 number of matches in the subtree when constructing the agenda or creating
3509 a sparse tree. If you only want to see the first match in a tree during
3510 a search, check out the variable `org-tags-match-list-sublevels'."
3511 :group 'org-tags
3512 :type '(choice
3513 (const :tag "Not" nil)
3514 (const :tag "Always" t)
3515 (repeat :tag "Specific tags" (string :tag "Tag"))
3516 (regexp :tag "Tags matched by regexp")))
3518 (defcustom org-tags-exclude-from-inheritance nil
3519 "List of tags that should never be inherited.
3520 This is a way to exclude a few tags from inheritance. For way to do
3521 the opposite, to actively allow inheritance for selected tags,
3522 see the variable `org-use-tag-inheritance'."
3523 :group 'org-tags
3524 :type '(repeat (string :tag "Tag")))
3526 (defun org-tag-inherit-p (tag)
3527 "Check if TAG is one that should be inherited."
3528 (cond
3529 ((member tag org-tags-exclude-from-inheritance) nil)
3530 ((eq org-use-tag-inheritance t) t)
3531 ((not org-use-tag-inheritance) nil)
3532 ((stringp org-use-tag-inheritance)
3533 (string-match org-use-tag-inheritance tag))
3534 ((listp org-use-tag-inheritance)
3535 (member tag org-use-tag-inheritance))
3536 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3538 (defcustom org-tags-match-list-sublevels t
3539 "Non-nil means list also sublevels of headlines matching a search.
3540 This variable applies to tags/property searches, and also to stuck
3541 projects because this search is based on a tags match as well.
3543 When set to the symbol `indented', sublevels are indented with
3544 leading dots.
3546 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3547 the sublevels of a headline matching a tag search often also match
3548 the same search. Listing all of them can create very long lists.
3549 Setting this variable to nil causes subtrees of a match to be skipped.
3551 This variable is semi-obsolete and probably should always be true. It
3552 is better to limit inheritance to certain tags using the variables
3553 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3554 :group 'org-tags
3555 :type '(choice
3556 (const :tag "No, don't list them" nil)
3557 (const :tag "Yes, do list them" t)
3558 (const :tag "List them, indented with leading dots" indented)))
3560 (defcustom org-tags-sort-function nil
3561 "When set, tags are sorted using this function as a comparator."
3562 :group 'org-tags
3563 :type '(choice
3564 (const :tag "No sorting" nil)
3565 (const :tag "Alphabetical" string<)
3566 (const :tag "Reverse alphabetical" string>)
3567 (function :tag "Custom function" nil)))
3569 (defvar org-tags-history nil
3570 "History of minibuffer reads for tags.")
3571 (defvar org-last-tags-completion-table nil
3572 "The last used completion table for tags.")
3573 (defvar org-after-tags-change-hook nil
3574 "Hook that is run after the tags in a line have changed.")
3576 (defgroup org-properties nil
3577 "Options concerning properties in Org mode."
3578 :tag "Org Properties"
3579 :group 'org)
3581 (defcustom org-property-format "%-10s %s"
3582 "How property key/value pairs should be formatted by `indent-line'.
3583 When `indent-line' hits a property definition, it will format the line
3584 according to this format, mainly to make sure that the values are
3585 lined-up with respect to each other."
3586 :group 'org-properties
3587 :type 'string)
3589 (defcustom org-properties-postprocess-alist nil
3590 "Alist of properties and functions to adjust inserted values.
3591 Elements of this alist must be of the form
3593 ([string] [function])
3595 where [string] must be a property name and [function] must be a
3596 lambda expression: this lambda expression must take one argument,
3597 the value to adjust, and return the new value as a string.
3599 For example, this element will allow the property \"Remaining\"
3600 to be updated wrt the relation between the \"Effort\" property
3601 and the clock summary:
3603 ((\"Remaining\" (lambda(value)
3604 (let ((clocksum (org-clock-sum-current-item))
3605 (effort (org-duration-to-minutes
3606 (org-entry-get (point) \"Effort\"))))
3607 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3608 :group 'org-properties
3609 :version "24.1"
3610 :type '(alist :key-type (string :tag "Property")
3611 :value-type (function :tag "Function")))
3613 (defcustom org-use-property-inheritance nil
3614 "Non-nil means properties apply also for sublevels.
3616 This setting is chiefly used during property searches. Turning it on can
3617 cause significant overhead when doing a search, which is why it is not
3618 on by default.
3620 When nil, only the properties directly given in the current entry count.
3621 When t, every property is inherited. The value may also be a list of
3622 properties that should have inheritance, or a regular expression matching
3623 properties that should be inherited.
3625 However, note that some special properties use inheritance under special
3626 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3627 and the properties ending in \"_ALL\" when they are used as descriptor
3628 for valid values of a property.
3630 Note for programmers:
3631 When querying an entry with `org-entry-get', you can control if inheritance
3632 should be used. By default, `org-entry-get' looks only at the local
3633 properties. You can request inheritance by setting the inherit argument
3634 to t (to force inheritance) or to `selective' (to respect the setting
3635 in this variable)."
3636 :group 'org-properties
3637 :type '(choice
3638 (const :tag "Not" nil)
3639 (const :tag "Always" t)
3640 (repeat :tag "Specific properties" (string :tag "Property"))
3641 (regexp :tag "Properties matched by regexp")))
3643 (defun org-property-inherit-p (property)
3644 "Return a non-nil value if PROPERTY should be inherited."
3645 (cond
3646 ((eq org-use-property-inheritance t) t)
3647 ((not org-use-property-inheritance) nil)
3648 ((stringp org-use-property-inheritance)
3649 (string-match org-use-property-inheritance property))
3650 ((listp org-use-property-inheritance)
3651 (member-ignore-case property org-use-property-inheritance))
3652 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3654 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3655 "The default column format, if no other format has been defined.
3656 This variable can be set on the per-file basis by inserting a line
3658 #+COLUMNS: %25ITEM ....."
3659 :group 'org-properties
3660 :type 'string)
3662 (defcustom org-columns-ellipses ".."
3663 "The ellipses to be used when a field in column view is truncated.
3664 When this is the empty string, as many characters as possible are shown,
3665 but then there will be no visual indication that the field has been truncated.
3666 When this is a string of length N, the last N characters of a truncated
3667 field are replaced by this string. If the column is narrower than the
3668 ellipses string, only part of the ellipses string will be shown."
3669 :group 'org-properties
3670 :type 'string)
3672 (defconst org-global-properties-fixed
3673 '(("VISIBILITY_ALL" . "folded children content all")
3674 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3675 "List of property/value pairs that can be inherited by any entry.
3677 These are fixed values, for the preset properties. The user variable
3678 that can be used to add to this list is `org-global-properties'.
3680 The entries in this list are cons cells where the car is a property
3681 name and cdr is a string with the value. If the value represents
3682 multiple items like an \"_ALL\" property, separate the items by
3683 spaces.")
3685 (defcustom org-global-properties nil
3686 "List of property/value pairs that can be inherited by any entry.
3688 This list will be combined with the constant `org-global-properties-fixed'.
3690 The entries in this list are cons cells where the car is a property
3691 name and cdr is a string with the value.
3693 You can set buffer-local values for the same purpose in the variable
3694 `org-file-properties' this by adding lines like
3696 #+PROPERTY: NAME VALUE"
3697 :group 'org-properties
3698 :type '(repeat
3699 (cons (string :tag "Property")
3700 (string :tag "Value"))))
3702 (defvar-local org-file-properties nil
3703 "List of property/value pairs that can be inherited by any entry.
3704 Valid for the current buffer.
3705 This variable is populated from #+PROPERTY lines.")
3707 (defgroup org-agenda nil
3708 "Options concerning agenda views in Org mode."
3709 :tag "Org Agenda"
3710 :group 'org)
3712 (defvar-local org-category nil
3713 "Variable used by org files to set a category for agenda display.
3714 Such files should use a file variable to set it, for example
3716 # -*- mode: org; org-category: \"ELisp\"
3718 or contain a special line
3720 #+CATEGORY: ELisp
3722 If the file does not specify a category, then file's base name
3723 is used instead.")
3724 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3726 (defcustom org-agenda-files nil
3727 "The files to be used for agenda display.
3729 If an entry is a directory, all files in that directory that are matched
3730 by `org-agenda-file-regexp' will be part of the file list.
3732 If the value of the variable is not a list but a single file name, then
3733 the list of agenda files is actually stored and maintained in that file,
3734 one agenda file per line. In this file paths can be given relative to
3735 `org-directory'. Tilde expansion and environment variable substitution
3736 are also made.
3738 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3739 and removed with `\\[org-remove-file]'."
3740 :group 'org-agenda
3741 :type '(choice
3742 (repeat :tag "List of files and directories" file)
3743 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3745 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3746 "Regular expression to match files for `org-agenda-files'.
3747 If any element in the list in that variable contains a directory instead
3748 of a normal file, all files in that directory that are matched by this
3749 regular expression will be included."
3750 :group 'org-agenda
3751 :type 'regexp)
3753 (defcustom org-agenda-text-search-extra-files nil
3754 "List of extra files to be searched by text search commands.
3755 These files will be searched in addition to the agenda files by the
3756 commands `org-search-view' (`\\[org-agenda] s') \
3757 and `org-occur-in-agenda-files'.
3758 Note that these files will only be searched for text search commands,
3759 not for the other agenda views like todo lists, tag searches or the weekly
3760 agenda. This variable is intended to list notes and possibly archive files
3761 that should also be searched by these two commands.
3762 In fact, if the first element in the list is the symbol `agenda-archives',
3763 then all archive files of all agenda files will be added to the search
3764 scope."
3765 :group 'org-agenda
3766 :type '(set :greedy t
3767 (const :tag "Agenda Archives" agenda-archives)
3768 (repeat :inline t (file))))
3770 (defvaralias 'org-agenda-multi-occur-extra-files
3771 'org-agenda-text-search-extra-files)
3773 (defcustom org-agenda-skip-unavailable-files nil
3774 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3775 A nil value means to remove them, after a query, from the list."
3776 :group 'org-agenda
3777 :type 'boolean)
3779 (defcustom org-calendar-to-agenda-key [?c]
3780 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3781 The command `org-calendar-goto-agenda' will be bound to this key. The
3782 default is the character `c' because then `c' can be used to switch back and
3783 forth between agenda and calendar."
3784 :group 'org-agenda
3785 :type 'sexp)
3787 (defcustom org-calendar-insert-diary-entry-key [?i]
3788 "The key to be installed in `calendar-mode-map' for adding diary entries.
3789 This option is irrelevant until `org-agenda-diary-file' has been configured
3790 to point to an Org file. When that is the case, the command
3791 `org-agenda-diary-entry' will be bound to the key given here, by default
3792 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3793 if you want to continue doing this, you need to change this to a different
3794 key."
3795 :group 'org-agenda
3796 :type 'sexp)
3798 (defcustom org-agenda-diary-file 'diary-file
3799 "File to which to add new entries with the `i' key in agenda and calendar.
3800 When this is the symbol `diary-file', the functionality in the Emacs
3801 calendar will be used to add entries to the `diary-file'. But when this
3802 points to a file, `org-agenda-diary-entry' will be used instead."
3803 :group 'org-agenda
3804 :type '(choice
3805 (const :tag "The standard Emacs diary file" diary-file)
3806 (file :tag "Special Org file diary entries")))
3808 (eval-after-load "calendar"
3809 '(progn
3810 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3811 'org-calendar-goto-agenda)
3812 (add-hook 'calendar-mode-hook
3813 (lambda ()
3814 (unless (eq org-agenda-diary-file 'diary-file)
3815 (define-key calendar-mode-map
3816 org-calendar-insert-diary-entry-key
3817 'org-agenda-diary-entry))))))
3819 (defgroup org-latex nil
3820 "Options for embedding LaTeX code into Org mode."
3821 :tag "Org LaTeX"
3822 :group 'org)
3824 (defcustom org-format-latex-options
3825 '(:foreground default :background default :scale 1.0
3826 :html-foreground "Black" :html-background "Transparent"
3827 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3828 "Options for creating images from LaTeX fragments.
3829 This is a property list with the following properties:
3830 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3831 `default' means use the foreground of the default face.
3832 `auto' means use the foreground from the text face.
3833 :background the background color, or \"Transparent\".
3834 `default' means use the background of the default face.
3835 `auto' means use the background from the text face.
3836 :scale a scaling factor for the size of the images, to get more pixels
3837 :html-foreground, :html-background, :html-scale
3838 the same numbers for HTML export.
3839 :matchers a list indicating which matchers should be used to
3840 find LaTeX fragments. Valid members of this list are:
3841 \"begin\" find environments
3842 \"$1\" find single characters surrounded by $.$
3843 \"$\" find math expressions surrounded by $...$
3844 \"$$\" find math expressions surrounded by $$....$$
3845 \"\\(\" find math expressions surrounded by \\(...\\)
3846 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3847 :group 'org-latex
3848 :type 'plist)
3850 (defcustom org-format-latex-signal-error t
3851 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3852 When nil, just push out a message."
3853 :group 'org-latex
3854 :version "24.1"
3855 :type 'boolean)
3857 (defcustom org-latex-to-mathml-jar-file nil
3858 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3859 Use this to specify additional executable file say a jar file.
3861 When using MathToWeb as the converter, specify the full-path to
3862 your mathtoweb.jar file."
3863 :group 'org-latex
3864 :version "24.1"
3865 :type '(choice
3866 (const :tag "None" nil)
3867 (file :tag "JAR file" :must-match t)))
3869 (defcustom org-latex-to-mathml-convert-command nil
3870 "Command to convert LaTeX fragments to MathML.
3871 Replace format-specifiers in the command as noted below and use
3872 `shell-command' to convert LaTeX to MathML.
3873 %j: Executable file in fully expanded form as specified by
3874 `org-latex-to-mathml-jar-file'.
3875 %I: Input LaTeX file in fully expanded form.
3876 %i: The latex fragment to be converted.
3877 %o: Output MathML file.
3879 This command is used by `org-create-math-formula'.
3881 When using MathToWeb as the converter, set this option to
3882 \"java -jar %j -unicode -force -df %o %I\".
3884 When using LaTeXML set this option to
3885 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3886 :group 'org-latex
3887 :version "24.1"
3888 :type '(choice
3889 (const :tag "None" nil)
3890 (string :tag "\nShell command")))
3892 (defcustom org-preview-latex-default-process 'dvipng
3893 "The default process to convert LaTeX fragments to image files.
3894 All available processes and theirs documents can be found in
3895 `org-preview-latex-process-alist', which see."
3896 :group 'org-latex
3897 :version "26.1"
3898 :package-version '(Org . "9.0")
3899 :type 'symbol)
3901 (defcustom org-preview-latex-process-alist
3902 '((dvipng
3903 :programs ("latex" "dvipng")
3904 :description "dvi > png"
3905 :message "you need to install the programs: latex and dvipng."
3906 :image-input-type "dvi"
3907 :image-output-type "png"
3908 :image-size-adjust (1.0 . 1.0)
3909 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3910 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3911 (dvisvgm
3912 :programs ("latex" "dvisvgm")
3913 :description "dvi > svg"
3914 :message "you need to install the programs: latex and dvisvgm."
3915 :use-xcolor t
3916 :image-input-type "dvi"
3917 :image-output-type "svg"
3918 :image-size-adjust (1.7 . 1.5)
3919 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3920 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3921 (imagemagick
3922 :programs ("latex" "convert")
3923 :description "pdf > png"
3924 :message "you need to install the programs: latex and imagemagick."
3925 :use-xcolor t
3926 :image-input-type "pdf"
3927 :image-output-type "png"
3928 :image-size-adjust (1.0 . 1.0)
3929 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3930 :image-converter
3931 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3932 "Definitions of external processes for LaTeX previewing.
3933 Org mode can use some external commands to generate TeX snippet's images for
3934 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3935 `org-create-formula-image' how to call them.
3937 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3938 PROPERTIES accepts the following attributes:
3940 :programs list of strings, required programs.
3941 :description string, describe the process.
3942 :message string, message it when required programs cannot be found.
3943 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3944 :image-output-type string, output file type of image converter (e.g., \"png\").
3945 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3946 deal with background and foreground color of image.
3947 Otherwise, dvipng style background and foreground color
3948 format are generated. You may then refer to them in
3949 command options with \"%F\" and \"%B\".
3950 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3951 image size showed in buffer and the cdr element is for
3952 HTML file. This option is only useful for process
3953 developers, users should use variable
3954 `org-format-latex-options' instead.
3955 :post-clean list of strings, files matched are to be cleaned up once
3956 the image is generated. When nil, the files with \".dvi\",
3957 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3958 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3959 be cleaned up.
3960 :latex-header list of strings, the LaTeX header of the snippet file.
3961 When nil, the fallback value is used instead, which is
3962 controlled by `org-format-latex-header',
3963 `org-latex-default-packages-alist' and
3964 `org-latex-packages-alist', which see.
3965 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3966 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3967 replaced with values defined below.
3968 :image-converter list of image converter commands strings. Each of them is
3969 given to the shell and supports any of the following
3970 place-holders defined below.
3972 Place-holders used by `:image-converter' and `:latex-compiler':
3974 %f input file name
3975 %b base name of input file
3976 %o base directory of input file
3977 %O absolute output file name
3979 Place-holders only used by `:image-converter':
3981 %F foreground of image
3982 %B background of image
3983 %D dpi, which is used to adjust image size by some processing commands.
3984 %S the image size scale ratio, which is used to adjust image size by some
3985 processing commands."
3986 :group 'org-latex
3987 :version "26.1"
3988 :package-version '(Org . "9.0")
3989 :type '(alist :tag "LaTeX to image backends"
3990 :value-type (plist)))
3992 (defcustom org-preview-latex-image-directory "ltximg/"
3993 "Path to store latex preview images.
3994 A relative path here creates many directories relative to the
3995 processed org files paths. An absolute path puts all preview
3996 images at the same place."
3997 :group 'org-latex
3998 :version "26.1"
3999 :package-version '(Org . "9.0")
4000 :type 'string)
4002 (defun org-format-latex-mathml-available-p ()
4003 "Return t if `org-latex-to-mathml-convert-command' is usable."
4004 (save-match-data
4005 (when (and (boundp 'org-latex-to-mathml-convert-command)
4006 org-latex-to-mathml-convert-command)
4007 (let ((executable (car (split-string
4008 org-latex-to-mathml-convert-command))))
4009 (when (executable-find executable)
4010 (if (string-match
4011 "%j" org-latex-to-mathml-convert-command)
4012 (file-readable-p org-latex-to-mathml-jar-file)
4013 t))))))
4015 (defcustom org-format-latex-header "\\documentclass{article}
4016 \\usepackage[usenames]{color}
4017 \[PACKAGES]
4018 \[DEFAULT-PACKAGES]
4019 \\pagestyle{empty} % do not remove
4020 % The settings below are copied from fullpage.sty
4021 \\setlength{\\textwidth}{\\paperwidth}
4022 \\addtolength{\\textwidth}{-3cm}
4023 \\setlength{\\oddsidemargin}{1.5cm}
4024 \\addtolength{\\oddsidemargin}{-2.54cm}
4025 \\setlength{\\evensidemargin}{\\oddsidemargin}
4026 \\setlength{\\textheight}{\\paperheight}
4027 \\addtolength{\\textheight}{-\\headheight}
4028 \\addtolength{\\textheight}{-\\headsep}
4029 \\addtolength{\\textheight}{-\\footskip}
4030 \\addtolength{\\textheight}{-3cm}
4031 \\setlength{\\topmargin}{1.5cm}
4032 \\addtolength{\\topmargin}{-2.54cm}"
4033 "The document header used for processing LaTeX fragments.
4034 It is imperative that this header make sure that no page number
4035 appears on the page. The package defined in the variables
4036 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4037 will either replace the placeholder \"[PACKAGES]\" in this
4038 header, or they will be appended."
4039 :group 'org-latex
4040 :type 'string)
4042 (defun org-set-packages-alist (var val)
4043 "Set the packages alist and make sure it has 3 elements per entry."
4044 (set var (mapcar (lambda (x)
4045 (if (and (consp x) (= (length x) 2))
4046 (list (car x) (nth 1 x) t)
4048 val)))
4050 (defun org-get-packages-alist (var)
4051 "Get the packages alist and make sure it has 3 elements per entry."
4052 (mapcar (lambda (x)
4053 (if (and (consp x) (= (length x) 2))
4054 (list (car x) (nth 1 x) t)
4056 (default-value var)))
4058 (defcustom org-latex-default-packages-alist
4059 '(("AUTO" "inputenc" t ("pdflatex"))
4060 ("T1" "fontenc" t ("pdflatex"))
4061 ("" "graphicx" t)
4062 ("" "grffile" t)
4063 ("" "longtable" nil)
4064 ("" "wrapfig" nil)
4065 ("" "rotating" nil)
4066 ("normalem" "ulem" t)
4067 ("" "amsmath" t)
4068 ("" "textcomp" t)
4069 ("" "amssymb" t)
4070 ("" "capt-of" nil)
4071 ("" "hyperref" nil))
4072 "Alist of default packages to be inserted in the header.
4074 Change this only if one of the packages here causes an
4075 incompatibility with another package you are using.
4077 The packages in this list are needed by one part or another of
4078 Org mode to function properly:
4080 - inputenc, fontenc: for basic font and character selection
4081 - graphicx: for including images
4082 - grffile: allow periods and spaces in graphics file names
4083 - longtable: For multipage tables
4084 - wrapfig: for figure placement
4085 - rotating: for sideways figures and tables
4086 - ulem: for underline and strike-through
4087 - amsmath: for subscript and superscript and math environments
4088 - textcomp, amssymb: for various symbols used
4089 for interpreting the entities in `org-entities'. You can skip
4090 some of these packages if you don't use any of their symbols.
4091 - capt-of: for captions outside of floats
4092 - hyperref: for cross references
4094 Therefore you should not modify this variable unless you know
4095 what you are doing. The one reason to change it anyway is that
4096 you might be loading some other package that conflicts with one
4097 of the default packages. Each element is either a cell or
4098 a string.
4100 A cell is of the format
4102 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4104 If SNIPPET-FLAG is non-nil, the package also needs to be included
4105 when compiling LaTeX snippets into images for inclusion into
4106 non-LaTeX output. COMPILERS is a list of compilers that should
4107 include the package, see `org-latex-compiler'. If the document
4108 compiler is not in the list, and the list is non-nil, the package
4109 will not be inserted in the final document.
4111 A string will be inserted as-is in the header of the document."
4112 :group 'org-latex
4113 :group 'org-export-latex
4114 :set 'org-set-packages-alist
4115 :get 'org-get-packages-alist
4116 :version "26.1"
4117 :package-version '(Org . "8.3")
4118 :type '(repeat
4119 (choice
4120 (list :tag "options/package pair"
4121 (string :tag "options")
4122 (string :tag "package")
4123 (boolean :tag "Snippet")
4124 (choice
4125 (const :tag "For all compilers" nil)
4126 (repeat :tag "Allowed compiler" string)))
4127 (string :tag "A line of LaTeX"))))
4129 (defcustom org-latex-packages-alist nil
4130 "Alist of packages to be inserted in every LaTeX header.
4132 These will be inserted after `org-latex-default-packages-alist'.
4133 Each element is either a cell or a string.
4135 A cell is of the format:
4137 (\"options\" \"package\" SNIPPET-FLAG)
4139 SNIPPET-FLAG, when non-nil, indicates that this package is also
4140 needed when turning LaTeX snippets into images for inclusion into
4141 non-LaTeX output.
4143 A string will be inserted as-is in the header of the document.
4145 Make sure that you only list packages here which:
4147 - you want in every file;
4148 - do not conflict with the setup in `org-format-latex-header';
4149 - do not conflict with the default packages in
4150 `org-latex-default-packages-alist'."
4151 :group 'org-latex
4152 :group 'org-export-latex
4153 :set 'org-set-packages-alist
4154 :get 'org-get-packages-alist
4155 :type '(repeat
4156 (choice
4157 (list :tag "options/package pair"
4158 (string :tag "options")
4159 (string :tag "package")
4160 (boolean :tag "Snippet"))
4161 (string :tag "A line of LaTeX"))))
4163 (defgroup org-appearance nil
4164 "Settings for Org mode appearance."
4165 :tag "Org Appearance"
4166 :group 'org)
4168 (defcustom org-level-color-stars-only nil
4169 "Non-nil means fontify only the stars in each headline.
4170 When nil, the entire headline is fontified.
4171 Changing it requires restart of `font-lock-mode' to become effective
4172 also in regions already fontified."
4173 :group 'org-appearance
4174 :type 'boolean)
4176 (defcustom org-hide-leading-stars nil
4177 "Non-nil means hide the first N-1 stars in a headline.
4178 This works by using the face `org-hide' for these stars. This
4179 face is white for a light background, and black for a dark
4180 background. You may have to customize the face `org-hide' to
4181 make this work.
4182 Changing it requires restart of `font-lock-mode' to become effective
4183 also in regions already fontified.
4184 You may also set this on a per-file basis by adding one of the following
4185 lines to the buffer:
4187 #+STARTUP: hidestars
4188 #+STARTUP: showstars"
4189 :group 'org-appearance
4190 :type 'boolean)
4192 (defcustom org-hidden-keywords nil
4193 "List of symbols corresponding to keywords to be hidden the org buffer.
4194 For example, a value \\='(title) for this list will make the document's title
4195 appear in the buffer without the initial #+TITLE: keyword."
4196 :group 'org-appearance
4197 :version "24.1"
4198 :type '(set (const :tag "#+AUTHOR" author)
4199 (const :tag "#+DATE" date)
4200 (const :tag "#+EMAIL" email)
4201 (const :tag "#+TITLE" title)))
4203 (defcustom org-custom-properties nil
4204 "List of properties (as strings) with a special meaning.
4205 The default use of these custom properties is to let the user
4206 hide them with `org-toggle-custom-properties-visibility'."
4207 :group 'org-properties
4208 :group 'org-appearance
4209 :version "24.3"
4210 :type '(repeat (string :tag "Property Name")))
4212 (defcustom org-fontify-done-headline nil
4213 "Non-nil means change the face of a headline if it is marked DONE.
4214 Normally, only the TODO/DONE keyword indicates the state of a headline.
4215 When this is non-nil, the headline after the keyword is set to the
4216 `org-headline-done' as an additional indication."
4217 :group 'org-appearance
4218 :type 'boolean)
4220 (defcustom org-fontify-emphasized-text t
4221 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4222 Changing this variable requires a restart of Emacs to take effect."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-fontify-whole-heading-line nil
4227 "Non-nil means fontify the whole line for headings.
4228 This is useful when setting a background color for the
4229 org-level-* faces."
4230 :group 'org-appearance
4231 :type 'boolean)
4233 (defcustom org-highlight-latex-and-related nil
4234 "Non-nil means highlight LaTeX related syntax in the buffer.
4235 When non nil, the value should be a list containing any of the
4236 following symbols:
4237 `latex' Highlight LaTeX snippets and environments.
4238 `script' Highlight subscript and superscript.
4239 `entities' Highlight entities."
4240 :group 'org-appearance
4241 :version "24.4"
4242 :package-version '(Org . "8.0")
4243 :type '(choice
4244 (const :tag "No highlighting" nil)
4245 (set :greedy t :tag "Highlight"
4246 (const :tag "LaTeX snippets and environments" latex)
4247 (const :tag "Subscript and superscript" script)
4248 (const :tag "Entities" entities))))
4250 (defcustom org-hide-emphasis-markers nil
4251 "Non-nil mean font-lock should hide the emphasis marker characters."
4252 :group 'org-appearance
4253 :type 'boolean)
4255 (defcustom org-hide-macro-markers nil
4256 "Non-nil mean font-lock should hide the brackets marking macro calls."
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-pretty-entities nil
4261 "Non-nil means show entities as UTF8 characters.
4262 When nil, the \\name form remains in the buffer."
4263 :group 'org-appearance
4264 :version "24.1"
4265 :type 'boolean)
4267 (defcustom org-pretty-entities-include-sub-superscripts t
4268 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4269 :group 'org-appearance
4270 :version "24.1"
4271 :type 'boolean)
4273 (defvar org-emph-re nil
4274 "Regular expression for matching emphasis.
4275 After a match, the match groups contain these elements:
4276 0 The match of the full regular expression, including the characters
4277 before and after the proper match
4278 1 The character before the proper match, or empty at beginning of line
4279 2 The proper match, including the leading and trailing markers
4280 3 The leading marker like * or /, indicating the type of highlighting
4281 4 The text between the emphasis markers, not including the markers
4282 5 The character after the match, empty at the end of a line")
4284 (defvar org-verbatim-re nil
4285 "Regular expression for matching verbatim text.")
4287 (defvar org-emphasis-regexp-components) ; defined just below
4288 (defvar org-emphasis-alist) ; defined just below
4289 (defun org-set-emph-re (var val)
4290 "Set variable and compute the emphasis regular expression."
4291 (set var val)
4292 (when (and (boundp 'org-emphasis-alist)
4293 (boundp 'org-emphasis-regexp-components)
4294 org-emphasis-alist org-emphasis-regexp-components)
4295 (pcase-let*
4296 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4297 (body (if (<= nl 0) body
4298 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4299 (template
4300 (format (concat "\\([%s]\\|^\\)" ;before markers
4301 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4302 "\\([%s]\\|$\\)") ;after markers
4303 pre border border body border post)))
4304 (setq org-emph-re (format template "*/_+"))
4305 (setq org-verbatim-re (format template "=~")))))
4307 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4308 ;; set this option proved cumbersome. See this message/thread:
4309 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4310 (defvar org-emphasis-regexp-components
4311 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4312 "Components used to build the regular expression for emphasis.
4313 This is a list with five entries. Terminology: In an emphasis string
4314 like \" *strong word* \", we call the initial space PREMATCH, the final
4315 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4316 and \"trong wor\" is the body. The different components in this variable
4317 specify what is allowed/forbidden in each part:
4319 pre Chars allowed as prematch. Beginning of line will be allowed too.
4320 post Chars allowed as postmatch. End of line will be allowed too.
4321 border The chars *forbidden* as border characters.
4322 body-regexp A regexp like \".\" to match a body character. Don't use
4323 non-shy groups here, and don't allow newline here.
4324 newline The maximum number of newlines allowed in an emphasis exp.
4326 You need to reload Org or to restart Emacs after setting this.")
4328 (defcustom org-emphasis-alist
4329 '(("*" bold)
4330 ("/" italic)
4331 ("_" underline)
4332 ("=" org-verbatim verbatim)
4333 ("~" org-code verbatim)
4334 ("+" (:strike-through t)))
4335 "Alist of characters and faces to emphasize text.
4336 Text starting and ending with a special character will be emphasized,
4337 for example *bold*, _underlined_ and /italic/. This variable sets the
4338 marker characters and the face to be used by font-lock for highlighting
4339 in Org buffers.
4341 You need to reload Org or to restart Emacs after customizing this."
4342 :group 'org-appearance
4343 :set 'org-set-emph-re
4344 :version "24.4"
4345 :package-version '(Org . "8.0")
4346 :type '(repeat
4347 (list
4348 (string :tag "Marker character")
4349 (choice
4350 (face :tag "Font-lock-face")
4351 (plist :tag "Face property list"))
4352 (option (const verbatim)))))
4354 (defvar org-protecting-blocks '("src" "example" "export")
4355 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4356 This is needed for font-lock setup.")
4358 ;;; Functions and variables from their packages
4359 ;; Declared here to avoid compiler warnings
4360 (defvar mark-active)
4362 ;; Various packages
4363 (declare-function calc-eval "calc" (str &optional separator &rest args))
4364 (declare-function calendar-forward-day "cal-move" (arg))
4365 (declare-function calendar-goto-date "cal-move" (date))
4366 (declare-function calendar-goto-today "cal-move" ())
4367 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4368 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4369 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4370 (declare-function cdlatex-tab "ext:cdlatex" ())
4371 (declare-function dired-get-filename
4372 "dired"
4373 (&optional localp no-error-if-not-filep))
4374 (declare-function iswitchb-read-buffer
4375 "iswitchb"
4376 (prompt &optional
4377 default require-match _predicate start matches-set))
4378 (declare-function org-agenda-change-all-lines
4379 "org-agenda"
4380 (newhead hdmarker &optional fixface just-this))
4381 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4382 "org-agenda"
4383 (&optional end))
4384 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4385 (declare-function org-agenda-format-item
4386 "org-agenda"
4387 (extra txt &optional level category tags dotime
4388 remove-re habitp))
4389 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4390 (declare-function org-agenda-save-markers-for-cut-and-paste
4391 "org-agenda"
4392 (beg end))
4393 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4394 (declare-function org-agenda-skip "org-agenda" ())
4395 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4396 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4397 (declare-function org-indent-mode "org-indent" (&optional arg))
4398 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4399 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4400 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4401 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4402 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4403 (declare-function parse-time-string "parse-time" (string))
4405 (defvar align-mode-rules-list)
4406 (defvar calc-embedded-close-formula)
4407 (defvar calc-embedded-open-formula)
4408 (defvar calc-embedded-open-mode)
4409 (defvar font-lock-unfontify-region-function)
4410 (defvar iswitchb-temp-buflist)
4411 (defvar org-agenda-tags-todo-honor-ignore-options)
4412 (defvar remember-data-file)
4413 (defvar texmathp-why)
4415 ;;;###autoload
4416 (defun turn-on-orgtbl ()
4417 "Unconditionally turn on `orgtbl-mode'."
4418 (require 'org-table)
4419 (orgtbl-mode 1))
4421 (defun org-at-table-p (&optional table-type)
4422 "Non-nil if the cursor is inside an Org table.
4423 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4424 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4425 (or (not (derived-mode-p 'org-mode))
4426 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4427 (and e (or table-type
4428 (eq 'org (org-element-property :type e))))))))
4430 (defun org-at-table.el-p ()
4431 "Non-nil when point is at a table.el table."
4432 (and (org-match-line "[ \t]*[|+]")
4433 (let ((element (org-element-at-point)))
4434 (and (eq (org-element-type element) 'table)
4435 (eq (org-element-property :type element) 'table.el)))))
4437 (defun org-at-table-hline-p ()
4438 "Non-nil when point is inside a hline in a table.
4439 Assume point is already in a table."
4440 (org-match-line org-table-hline-regexp))
4442 (defun org-table-map-tables (function &optional quietly)
4443 "Apply FUNCTION to the start of all tables in the buffer."
4444 (org-with-wide-buffer
4445 (goto-char (point-min))
4446 (while (re-search-forward org-table-any-line-regexp nil t)
4447 (unless quietly
4448 (message "Mapping tables: %d%%"
4449 (floor (* 100.0 (point)) (buffer-size))))
4450 (beginning-of-line 1)
4451 (when (and (looking-at org-table-line-regexp)
4452 ;; Exclude tables in src/example/verbatim/clocktable blocks
4453 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4454 (save-excursion (funcall function))
4455 (or (looking-at org-table-line-regexp)
4456 (forward-char 1)))
4457 (re-search-forward org-table-any-border-regexp nil 1)))
4458 (unless quietly (message "Mapping tables: done")))
4460 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4461 (declare-function org-clock-update-mode-line "org-clock" ())
4462 (declare-function org-resolve-clocks "org-clock"
4463 (&optional also-non-dangling-p prompt last-valid))
4465 (defun org-at-TBLFM-p (&optional pos)
4466 "Non-nil when point (or POS) is in #+TBLFM line."
4467 (save-excursion
4468 (goto-char (or pos (point)))
4469 (beginning-of-line)
4470 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4471 (eq (org-element-type (org-element-at-point)) 'table))))
4473 (defvar org-clock-start-time)
4474 (defvar org-clock-marker (make-marker)
4475 "Marker recording the last clock-in.")
4476 (defvar org-clock-hd-marker (make-marker)
4477 "Marker recording the last clock-in, but the headline position.")
4478 (defvar org-clock-heading ""
4479 "The heading of the current clock entry.")
4480 (defun org-clock-is-active ()
4481 "Return the buffer where the clock is currently running.
4482 Return nil if no clock is running."
4483 (marker-buffer org-clock-marker))
4485 (defun org-check-running-clock ()
4486 "Check if the current buffer contains the running clock.
4487 If yes, offer to stop it and to save the buffer with the changes."
4488 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4489 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4490 (buffer-name))))
4491 (org-clock-out)
4492 (when (y-or-n-p "Save changed buffer?")
4493 (save-buffer))))
4495 (defun org-clocktable-try-shift (dir n)
4496 "Check if this line starts a clock table, if yes, shift the time block."
4497 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4498 (org-clocktable-shift dir n)))
4500 ;;;###autoload
4501 (defun org-clock-persistence-insinuate ()
4502 "Set up hooks for clock persistence."
4503 (require 'org-clock)
4504 (add-hook 'org-mode-hook 'org-clock-load)
4505 (add-hook 'kill-emacs-hook 'org-clock-save))
4507 (defgroup org-archive nil
4508 "Options concerning archiving in Org mode."
4509 :tag "Org Archive"
4510 :group 'org-structure)
4512 (defcustom org-archive-location "%s_archive::"
4513 "The location where subtrees should be archived.
4515 The value of this variable is a string, consisting of two parts,
4516 separated by a double-colon. The first part is a filename and
4517 the second part is a headline.
4519 When the filename is omitted, archiving happens in the same file.
4520 %s in the filename will be replaced by the current file
4521 name (without the directory part). Archiving to a different file
4522 is useful to keep archived entries from contributing to the
4523 Org Agenda.
4525 The archived entries will be filed as subtrees of the specified
4526 headline. When the headline is omitted, the subtrees are simply
4527 filed away at the end of the file, as top-level entries. Also in
4528 the heading you can use %s to represent the file name, this can be
4529 useful when using the same archive for a number of different files.
4531 Here are a few examples:
4532 \"%s_archive::\"
4533 If the current file is Projects.org, archive in file
4534 Projects.org_archive, as top-level trees. This is the default.
4536 \"::* Archived Tasks\"
4537 Archive in the current file, under the top-level headline
4538 \"* Archived Tasks\".
4540 \"~/org/archive.org::\"
4541 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4543 \"~/org/archive.org::* From %s\"
4544 Archive in file ~/org/archive.org (absolute path), under headlines
4545 \"From FILENAME\" where file name is the current file name.
4547 \"~/org/datetree.org::datetree/* Finished Tasks\"
4548 The \"datetree/\" string is special, signifying to archive
4549 items to the datetree. Items are placed in either the CLOSED
4550 date of the item, or the current date if there is no CLOSED date.
4551 The heading will be a subentry to the current date. There doesn't
4552 need to be a heading, but there always needs to be a slash after
4553 datetree. For example, to store archived items directly in the
4554 datetree, use \"~/org/datetree.org::datetree/\".
4556 \"basement::** Finished Tasks\"
4557 Archive in file ./basement (relative path), as level 3 trees
4558 below the level 2 heading \"** Finished Tasks\".
4560 You may set this option on a per-file basis by adding to the buffer a
4561 line like
4563 #+ARCHIVE: basement::** Finished Tasks
4565 You may also define it locally for a subtree by setting an ARCHIVE property
4566 in the entry. If such a property is found in an entry, or anywhere up
4567 the hierarchy, it will be used."
4568 :group 'org-archive
4569 :type 'string)
4571 (defcustom org-agenda-skip-archived-trees t
4572 "Non-nil means the agenda will skip any items located in archived trees.
4573 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4574 variable is no longer recommended, you should leave it at the value t.
4575 Instead, use the key `v' to cycle the archives-mode in the agenda."
4576 :group 'org-archive
4577 :group 'org-agenda-skip
4578 :type 'boolean)
4580 (defcustom org-columns-skip-archived-trees t
4581 "Non-nil means ignore archived trees when creating column view."
4582 :group 'org-archive
4583 :group 'org-properties
4584 :type 'boolean)
4586 (defcustom org-cycle-open-archived-trees nil
4587 "Non-nil means `org-cycle' will open archived trees.
4588 An archived tree is a tree marked with the tag ARCHIVE.
4589 When nil, archived trees will stay folded. You can still open them with
4590 normal outline commands like `show-all', but not with the cycling commands."
4591 :group 'org-archive
4592 :group 'org-cycle
4593 :type 'boolean)
4595 (defcustom org-sparse-tree-open-archived-trees nil
4596 "Non-nil means sparse tree construction shows matches in archived trees.
4597 When nil, matches in these trees are highlighted, but the trees are kept in
4598 collapsed state."
4599 :group 'org-archive
4600 :group 'org-sparse-trees
4601 :type 'boolean)
4603 (defcustom org-sparse-tree-default-date-type nil
4604 "The default date type when building a sparse tree.
4605 When this is nil, a date is a scheduled or a deadline timestamp.
4606 Otherwise, these types are allowed:
4608 all: all timestamps
4609 active: only active timestamps (<...>)
4610 inactive: only inactive timestamps ([...])
4611 scheduled: only scheduled timestamps
4612 deadline: only deadline timestamps"
4613 :type '(choice (const :tag "Scheduled or deadline" nil)
4614 (const :tag "All timestamps" all)
4615 (const :tag "Only active timestamps" active)
4616 (const :tag "Only inactive timestamps" inactive)
4617 (const :tag "Only scheduled timestamps" scheduled)
4618 (const :tag "Only deadline timestamps" deadline)
4619 (const :tag "Only closed timestamps" closed))
4620 :version "26.1"
4621 :package-version '(Org . "8.3")
4622 :group 'org-sparse-trees)
4624 (defun org-cycle-hide-archived-subtrees (state)
4625 "Re-hide all archived subtrees after a visibility state change.
4626 STATE should be one of the symbols listed in the docstring of
4627 `org-cycle-hook'."
4628 (when (and (not org-cycle-open-archived-trees)
4629 (not (memq state '(overview folded))))
4630 (save-excursion
4631 (let* ((globalp (memq state '(contents all)))
4632 (beg (if globalp (point-min) (point)))
4633 (end (if globalp (point-max) (org-end-of-subtree t))))
4634 (org-hide-archived-subtrees beg end)
4635 (goto-char beg)
4636 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4637 (message "%s" (substitute-command-keys
4638 "Subtree is archived and stays closed. Use \
4639 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4641 (defun org-force-cycle-archived ()
4642 "Cycle subtree even if it is archived."
4643 (interactive)
4644 (setq this-command 'org-cycle)
4645 (let ((org-cycle-open-archived-trees t))
4646 (call-interactively 'org-cycle)))
4648 (defun org-hide-archived-subtrees (beg end)
4649 "Re-hide all archived subtrees after a visibility state change."
4650 (org-with-wide-buffer
4651 (let ((case-fold-search nil)
4652 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4653 (goto-char beg)
4654 ;; Include headline point is currently on.
4655 (beginning-of-line)
4656 (while (and (< (point) end) (re-search-forward re end t))
4657 (when (member org-archive-tag (org-get-tags))
4658 (org-flag-subtree t)
4659 (org-end-of-subtree t))))))
4661 (declare-function outline-end-of-heading "outline" ())
4662 (declare-function outline-flag-region "outline" (from to flag))
4663 (defun org-flag-subtree (flag)
4664 (save-excursion
4665 (org-back-to-heading t)
4666 (outline-end-of-heading)
4667 (outline-flag-region (point)
4668 (progn (org-end-of-subtree t) (point))
4669 flag)))
4671 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4673 ;; Declare Column View Code
4675 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4676 (declare-function org-columns-compute "org-colview" (property))
4678 ;; Declare ID code
4680 (declare-function org-id-store-link "org-id")
4681 (declare-function org-id-locations-load "org-id")
4682 (declare-function org-id-locations-save "org-id")
4683 (defvar org-id-track-globally)
4685 ;;; Variables for pre-computed regular expressions, all buffer local
4687 (defvar-local org-todo-regexp nil
4688 "Matches any of the TODO state keywords.
4689 Since TODO keywords are case-sensitive, `case-fold-search' is
4690 expected to be bound to nil when matching against this regexp.")
4692 (defvar-local org-not-done-regexp nil
4693 "Matches any of the TODO state keywords except the last one.
4694 Since TODO keywords are case-sensitive, `case-fold-search' is
4695 expected to be bound to nil when matching against this regexp.")
4697 (defvar-local org-not-done-heading-regexp nil
4698 "Matches a TODO headline that is not done.
4699 Since TODO keywords are case-sensitive, `case-fold-search' is
4700 expected to be bound to nil when matching against this regexp.")
4702 (defvar-local org-todo-line-regexp nil
4703 "Matches a headline and puts TODO state into group 2 if present.
4704 Since TODO keywords are case-sensitive, `case-fold-search' is
4705 expected to be bound to nil when matching against this regexp.")
4707 (defvar-local org-complex-heading-regexp nil
4708 "Matches a headline and puts everything into groups:
4710 group 1: Stars
4711 group 2: The TODO keyword, maybe
4712 group 3: Priority cookie
4713 group 4: True headline
4714 group 5: Tags
4716 Since TODO keywords are case-sensitive, `case-fold-search' is
4717 expected to be bound to nil when matching against this regexp.")
4719 (defvar-local org-complex-heading-regexp-format nil
4720 "Printf format to make regexp to match an exact headline.
4721 This regexp will match the headline of any node which has the
4722 exact headline text that is put into the format, but may have any
4723 TODO state, priority and tags.")
4725 (defvar-local org-todo-line-tags-regexp nil
4726 "Matches a headline and puts TODO state into group 2 if present.
4727 Also put tags into group 4 if tags are present.")
4729 (defconst org-plain-time-of-day-regexp
4730 (concat
4731 "\\(\\<[012]?[0-9]"
4732 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4733 "\\(--?"
4734 "\\(\\<[012]?[0-9]"
4735 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4736 "\\)?")
4737 "Regular expression to match a plain time or time range.
4738 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4739 groups carry important information:
4740 0 the full match
4741 1 the first time, range or not
4742 8 the second time, if it is a range.")
4744 (defconst org-plain-time-extension-regexp
4745 (concat
4746 "\\(\\<[012]?[0-9]"
4747 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4748 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4749 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4750 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4751 groups carry important information:
4752 0 the full match
4753 7 hours of duration
4754 9 minutes of duration")
4756 (defconst org-stamp-time-of-day-regexp
4757 (concat
4758 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4759 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4760 "\\(--?"
4761 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4762 "Regular expression to match a timestamp time or time range.
4763 After a match, the following groups carry important information:
4764 0 the full match
4765 1 date plus weekday, for back referencing to make sure both times are on the same day
4766 2 the first time, range or not
4767 4 the second time, if it is a range.")
4769 (defconst org-startup-options
4770 '(("fold" org-startup-folded t)
4771 ("overview" org-startup-folded t)
4772 ("nofold" org-startup-folded nil)
4773 ("showall" org-startup-folded nil)
4774 ("showeverything" org-startup-folded showeverything)
4775 ("content" org-startup-folded content)
4776 ("indent" org-startup-indented t)
4777 ("noindent" org-startup-indented nil)
4778 ("hidestars" org-hide-leading-stars t)
4779 ("showstars" org-hide-leading-stars nil)
4780 ("odd" org-odd-levels-only t)
4781 ("oddeven" org-odd-levels-only nil)
4782 ("align" org-startup-align-all-tables t)
4783 ("noalign" org-startup-align-all-tables nil)
4784 ("shrink" org-startup-shrink-all-tables t)
4785 ("inlineimages" org-startup-with-inline-images t)
4786 ("noinlineimages" org-startup-with-inline-images nil)
4787 ("latexpreview" org-startup-with-latex-preview t)
4788 ("nolatexpreview" org-startup-with-latex-preview nil)
4789 ("customtime" org-display-custom-times t)
4790 ("logdone" org-log-done time)
4791 ("lognotedone" org-log-done note)
4792 ("nologdone" org-log-done nil)
4793 ("lognoteclock-out" org-log-note-clock-out t)
4794 ("nolognoteclock-out" org-log-note-clock-out nil)
4795 ("logrepeat" org-log-repeat state)
4796 ("lognoterepeat" org-log-repeat note)
4797 ("logdrawer" org-log-into-drawer t)
4798 ("nologdrawer" org-log-into-drawer nil)
4799 ("logstatesreversed" org-log-states-order-reversed t)
4800 ("nologstatesreversed" org-log-states-order-reversed nil)
4801 ("nologrepeat" org-log-repeat nil)
4802 ("logreschedule" org-log-reschedule time)
4803 ("lognotereschedule" org-log-reschedule note)
4804 ("nologreschedule" org-log-reschedule nil)
4805 ("logredeadline" org-log-redeadline time)
4806 ("lognoteredeadline" org-log-redeadline note)
4807 ("nologredeadline" org-log-redeadline nil)
4808 ("logrefile" org-log-refile time)
4809 ("lognoterefile" org-log-refile note)
4810 ("nologrefile" org-log-refile nil)
4811 ("fninline" org-footnote-define-inline t)
4812 ("nofninline" org-footnote-define-inline nil)
4813 ("fnlocal" org-footnote-section nil)
4814 ("fnauto" org-footnote-auto-label t)
4815 ("fnprompt" org-footnote-auto-label nil)
4816 ("fnconfirm" org-footnote-auto-label confirm)
4817 ("fnplain" org-footnote-auto-label plain)
4818 ("fnadjust" org-footnote-auto-adjust t)
4819 ("nofnadjust" org-footnote-auto-adjust nil)
4820 ("constcgs" constants-unit-system cgs)
4821 ("constSI" constants-unit-system SI)
4822 ("noptag" org-tag-persistent-alist nil)
4823 ("hideblocks" org-hide-block-startup t)
4824 ("nohideblocks" org-hide-block-startup nil)
4825 ("beamer" org-startup-with-beamer-mode t)
4826 ("entitiespretty" org-pretty-entities t)
4827 ("entitiesplain" org-pretty-entities nil))
4828 "Variable associated with STARTUP options for org-mode.
4829 Each element is a list of three items: the startup options (as written
4830 in the #+STARTUP line), the corresponding variable, and the value to set
4831 this variable to if the option is found. An optional forth element PUSH
4832 means to push this value onto the list in the variable.")
4834 (defcustom org-group-tags t
4835 "When non-nil (the default), use group tags.
4836 This can be turned on/off through `org-toggle-tags-groups'."
4837 :group 'org-tags
4838 :group 'org-startup
4839 :type 'boolean)
4841 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4843 (defun org-toggle-tags-groups ()
4844 "Toggle support for group tags.
4845 Support for group tags is controlled by the option
4846 `org-group-tags', which is non-nil by default."
4847 (interactive)
4848 (setq org-group-tags (not org-group-tags))
4849 (cond ((and (derived-mode-p 'org-agenda-mode)
4850 org-group-tags)
4851 (org-agenda-redo))
4852 ((derived-mode-p 'org-mode)
4853 (let ((org-inhibit-startup t)) (org-mode))))
4854 (message "Groups tags support has been turned %s"
4855 (if org-group-tags "on" "off")))
4857 (defun org-set-regexps-and-options (&optional tags-only)
4858 "Precompute regular expressions used in the current buffer.
4859 When optional argument TAGS-ONLY is non-nil, only compute tags
4860 related expressions."
4861 (when (derived-mode-p 'org-mode)
4862 (let ((alist (org--setup-collect-keywords
4863 (org-make-options-regexp
4864 (append '("FILETAGS" "TAGS" "SETUPFILE")
4865 (and (not tags-only)
4866 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4867 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4868 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4869 ;; Startup options. Get this early since it does change
4870 ;; behavior for other options (e.g., tags).
4871 (let ((startup (cdr (assq 'startup alist))))
4872 (dolist (option startup)
4873 (let ((entry (assoc-string option org-startup-options t)))
4874 (when entry
4875 (let ((var (nth 1 entry))
4876 (val (nth 2 entry)))
4877 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4878 (unless (listp (symbol-value var))
4879 (set (make-local-variable var) nil))
4880 (add-to-list var val)))))))
4881 (setq-local org-file-tags
4882 (mapcar #'org-add-prop-inherited
4883 (cdr (assq 'filetags alist))))
4884 (setq org-current-tag-alist
4885 (append org-tag-persistent-alist
4886 (let ((tags (cdr (assq 'tags alist))))
4887 (if tags (org-tag-string-to-alist tags)
4888 org-tag-alist))))
4889 (setq org-tag-groups-alist
4890 (org-tag-alist-to-groups org-current-tag-alist))
4891 (unless tags-only
4892 ;; File properties.
4893 (setq-local org-file-properties (cdr (assq 'property alist)))
4894 ;; Archive location.
4895 (let ((archive (cdr (assq 'archive alist))))
4896 (when archive (setq-local org-archive-location archive)))
4897 ;; Category.
4898 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4899 (when cat
4900 (setq-local org-category (intern cat))
4901 (setq-local org-file-properties
4902 (org--update-property-plist
4903 "CATEGORY" cat org-file-properties))))
4904 ;; Columns.
4905 (let ((column (cdr (assq 'columns alist))))
4906 (when column (setq-local org-columns-default-format column)))
4907 ;; Constants.
4908 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4909 ;; Link abbreviations.
4910 (let ((links (cdr (assq 'link alist))))
4911 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4912 ;; Priorities.
4913 (let ((priorities (cdr (assq 'priorities alist))))
4914 (when priorities
4915 (setq-local org-highest-priority (nth 0 priorities))
4916 (setq-local org-lowest-priority (nth 1 priorities))
4917 (setq-local org-default-priority (nth 2 priorities))))
4918 ;; Scripts.
4919 (let ((scripts (assq 'scripts alist)))
4920 (when scripts
4921 (setq-local org-use-sub-superscripts (cdr scripts))))
4922 ;; TODO keywords.
4923 (setq-local org-todo-kwd-alist nil)
4924 (setq-local org-todo-key-alist nil)
4925 (setq-local org-todo-key-trigger nil)
4926 (setq-local org-todo-keywords-1 nil)
4927 (setq-local org-done-keywords nil)
4928 (setq-local org-todo-heads nil)
4929 (setq-local org-todo-sets nil)
4930 (setq-local org-todo-log-states nil)
4931 (let ((todo-sequences
4932 (or (nreverse (cdr (assq 'todo alist)))
4933 (let ((d (default-value 'org-todo-keywords)))
4934 (if (not (stringp (car d))) d
4935 ;; XXX: Backward compatibility code.
4936 (list (cons org-todo-interpretation d)))))))
4937 (dolist (sequence todo-sequences)
4938 (let* ((sequence (or (run-hook-with-args-until-success
4939 'org-todo-setup-filter-hook sequence)
4940 sequence))
4941 (sequence-type (car sequence))
4942 (keywords (cdr sequence))
4943 (sep (member "|" keywords))
4944 names alist)
4945 (dolist (k (remove "|" keywords))
4946 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4948 (error "Invalid TODO keyword %s" k))
4949 (let ((name (match-string 1 k))
4950 (key (match-string 2 k))
4951 (log (org-extract-log-state-settings k)))
4952 (push name names)
4953 (push (cons name (and key (string-to-char key))) alist)
4954 (when log (push log org-todo-log-states))))
4955 (let* ((names (nreverse names))
4956 (done (if sep (org-remove-keyword-keys (cdr sep))
4957 (last names)))
4958 (head (car names))
4959 (tail (list sequence-type head (car done) (org-last done))))
4960 (add-to-list 'org-todo-heads head 'append)
4961 (push names org-todo-sets)
4962 (setq org-done-keywords (append org-done-keywords done nil))
4963 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4964 (setq org-todo-key-alist
4965 (append org-todo-key-alist
4966 (and alist
4967 (append '((:startgroup))
4968 (nreverse alist)
4969 '((:endgroup))))))
4970 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4971 (setq org-todo-sets (nreverse org-todo-sets)
4972 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4973 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4974 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4975 ;; Compute the regular expressions and other local variables.
4976 ;; Using `org-outline-regexp-bol' would complicate them much,
4977 ;; because of the fixed white space at the end of that string.
4978 (unless org-done-keywords
4979 (setq org-done-keywords
4980 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4981 (setq org-not-done-keywords
4982 (org-delete-all org-done-keywords
4983 (copy-sequence org-todo-keywords-1))
4984 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4985 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4986 org-not-done-heading-regexp
4987 (format org-heading-keyword-regexp-format org-not-done-regexp)
4988 org-todo-line-regexp
4989 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4990 org-complex-heading-regexp
4991 (concat "^\\(\\*+\\)"
4992 "\\(?: +" org-todo-regexp "\\)?"
4993 "\\(?: +\\(\\[#.\\]\\)\\)?"
4994 "\\(?: +\\(.*?\\)\\)??"
4995 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4996 "[ \t]*$")
4997 org-complex-heading-regexp-format
4998 (concat "^\\(\\*+\\)"
4999 "\\(?: +" org-todo-regexp "\\)?"
5000 "\\(?: +\\(\\[#.\\]\\)\\)?"
5001 "\\(?: +"
5002 ;; Stats cookies can be stuck to body.
5003 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5004 "\\(%s\\)"
5005 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5006 "\\)"
5007 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5008 "[ \t]*$")
5009 org-todo-line-tags-regexp
5010 (concat "^\\(\\*+\\)"
5011 "\\(?: +" org-todo-regexp "\\)?"
5012 "\\(?: +\\(.*?\\)\\)??"
5013 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5014 "[ \t]*$"))
5015 (org-compute-latex-and-related-regexp)))))
5017 (defun org--setup-collect-keywords (regexp &optional files alist)
5018 "Return setup keywords values as an alist.
5020 REGEXP matches a subset of setup keywords. FILES is a list of
5021 file names already visited. It is used to avoid circular setup
5022 files. ALIST, when non-nil, is the alist computed so far.
5024 Return value contains the following keys: `archive', `category',
5025 `columns', `constants', `filetags', `link', `priorities',
5026 `property', `scripts', `startup', `tags' and `todo'."
5027 (org-with-wide-buffer
5028 (goto-char (point-min))
5029 (let ((case-fold-search t))
5030 (while (re-search-forward regexp nil t)
5031 (let ((element (org-element-at-point)))
5032 (when (eq (org-element-type element) 'keyword)
5033 (let ((key (org-element-property :key element))
5034 (value (org-element-property :value element)))
5035 (cond
5036 ((equal key "ARCHIVE")
5037 (when (org-string-nw-p value)
5038 (push (cons 'archive value) alist)))
5039 ((equal key "CATEGORY") (push (cons 'category value) alist))
5040 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5041 ((equal key "CONSTANTS")
5042 (let* ((constants (assq 'constants alist))
5043 (store (cdr constants)))
5044 (dolist (pair (split-string value))
5045 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5046 pair)
5047 (let* ((name (match-string 1 pair))
5048 (value (match-string 2 pair))
5049 (old (assoc name store)))
5050 (if old (setcdr old value)
5051 (push (cons name value) store)))))
5052 (if constants (setcdr constants store)
5053 (push (cons 'constants store) alist))))
5054 ((equal key "FILETAGS")
5055 (when (org-string-nw-p value)
5056 (let ((old (assq 'filetags alist))
5057 (new (apply #'nconc
5058 (mapcar (lambda (x) (org-split-string x ":"))
5059 (split-string value)))))
5060 (if old (setcdr old (append new (cdr old)))
5061 (push (cons 'filetags new) alist)))))
5062 ((equal key "LINK")
5063 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5064 (let ((links (assq 'link alist))
5065 (pair (cons (match-string-no-properties 1 value)
5066 (match-string-no-properties 2 value))))
5067 (if links (push pair (cdr links))
5068 (push (list 'link pair) alist)))))
5069 ((equal key "OPTIONS")
5070 (when (and (org-string-nw-p value)
5071 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5072 (push (cons 'scripts (read (match-string 1 value))) alist)))
5073 ((equal key "PRIORITIES")
5074 (push (cons 'priorities
5075 (let ((prio (split-string value)))
5076 (if (< (length prio) 3) '(?A ?C ?B)
5077 (mapcar #'string-to-char prio))))
5078 alist))
5079 ((equal key "PROPERTY")
5080 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5081 (let* ((property (assq 'property alist))
5082 (value (org--update-property-plist
5083 (match-string-no-properties 1 value)
5084 (match-string-no-properties 2 value)
5085 (cdr property))))
5086 (if property (setcdr property value)
5087 (push (cons 'property value) alist)))))
5088 ((equal key "STARTUP")
5089 (let ((startup (assq 'startup alist)))
5090 (if startup
5091 (setcdr startup
5092 (append (cdr startup) (split-string value)))
5093 (push (cons 'startup (split-string value)) alist))))
5094 ((equal key "TAGS")
5095 (let ((tag-cell (assq 'tags alist)))
5096 (if tag-cell
5097 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5098 (push (cons 'tags value) alist))))
5099 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5100 (let ((todo (assq 'todo alist))
5101 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5102 (split-string value))))
5103 (if todo (push value (cdr todo))
5104 (push (list 'todo value) alist))))
5105 ((equal key "SETUPFILE")
5106 (unless buffer-read-only ; Do not check in Gnus messages.
5107 (let ((f (and (org-string-nw-p value)
5108 (expand-file-name
5109 (org-unbracket-string "\"" "\"" value)))))
5110 (when (and f (file-readable-p f) (not (member f files)))
5111 (with-temp-buffer
5112 (setq default-directory (file-name-directory f))
5113 (insert-file-contents f)
5114 (setq alist
5115 ;; Fake Org mode to benefit from cache
5116 ;; without recurring needlessly.
5117 (let ((major-mode 'org-mode))
5118 (org--setup-collect-keywords
5119 regexp (cons f files) alist)))))))))))))))
5120 alist)
5122 (defun org-tag-string-to-alist (s)
5123 "Return tag alist associated to string S.
5124 S is a value for TAGS keyword or produced with
5125 `org-tag-alist-to-string'. Return value is an alist suitable for
5126 `org-tag-alist' or `org-tag-persistent-alist'."
5127 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5128 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5129 "\\|{.+?}\\)" ; regular expression
5130 "\\(?:(\\(.\\))\\)?\\'"))
5131 alist group-flag)
5132 (dolist (tokens lines (cdr (nreverse alist)))
5133 (push '(:newline) alist)
5134 (while tokens
5135 (let ((token (pop tokens)))
5136 (pcase token
5137 ("{"
5138 (push '(:startgroup) alist)
5139 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5140 ("}"
5141 (push '(:endgroup) alist)
5142 (setq group-flag nil))
5143 ("["
5144 (push '(:startgrouptag) alist)
5145 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5146 ("]"
5147 (push '(:endgrouptag) alist)
5148 (setq group-flag nil))
5149 (":"
5150 (push '(:grouptags) alist))
5151 ((guard (string-match tag-re token))
5152 (let ((tag (match-string 1 token))
5153 (key (and (match-beginning 2)
5154 (string-to-char (match-string 2 token)))))
5155 ;; Push all tags in groups, no matter if they already
5156 ;; appear somewhere else in the list.
5157 (when (or group-flag (not (assoc tag alist)))
5158 (push (cons tag key) alist))))))))))
5160 (defun org-tag-alist-to-string (alist &optional skip-key)
5161 "Return tag string associated to ALIST.
5163 ALIST is an alist, as defined in `org-tag-alist' or
5164 `org-tag-persistent-alist', or produced with
5165 `org-tag-string-to-alist'.
5167 Return value is a string suitable as a value for \"TAGS\"
5168 keyword.
5170 When optional argument SKIP-KEY is non-nil, skip selection keys
5171 next to tags."
5172 (mapconcat (lambda (token)
5173 (pcase token
5174 (`(:startgroup) "{")
5175 (`(:endgroup) "}")
5176 (`(:startgrouptag) "[")
5177 (`(:endgrouptag) "]")
5178 (`(:grouptags) ":")
5179 (`(:newline) "\\n")
5180 ((and
5181 (guard (not skip-key))
5182 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5183 (format "%s(%c)" tag key))
5184 (`(,(and tag (pred stringp)) . ,_) tag)
5185 (_ (user-error "Invalid tag token: %S" token))))
5186 alist
5187 " "))
5189 (defun org-tag-alist-to-groups (alist)
5190 "Return group alist from tag ALIST.
5191 ALIST is an alist, as defined in `org-tag-alist' or
5192 `org-tag-persistent-alist', or produced with
5193 `org-tag-string-to-alist'. Return value is an alist following
5194 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5195 a string, summarizing TAGS, as a list of strings."
5196 (let (groups group-status current-group)
5197 (dolist (token alist (nreverse groups))
5198 (pcase token
5199 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5200 (`(,(or :endgroup :endgrouptag))
5201 (when (eq group-status 'append)
5202 (push (nreverse current-group) groups))
5203 (setq group-status nil))
5204 (`(:grouptags) (setq group-status 'append))
5205 ((and `(,tag . ,_) (guard group-status))
5206 (if (eq group-status 'append) (push tag current-group)
5207 (setq current-group (list tag))))
5208 (_ nil)))))
5210 (defvar org--file-cache (make-hash-table :test #'equal)
5211 "Hash table to store contents of files referenced via a URL.
5212 This is the cache of file URLs read using `org-file-contents'.")
5214 (defun org-reset-file-cache ()
5215 "Reset the cache of files downloaded by `org-file-contents'."
5216 (clrhash org--file-cache))
5218 (defun org-file-url-p (file)
5219 "Non-nil if FILE is a URL."
5220 (require 'ffap)
5221 (string-match-p ffap-url-regexp file))
5223 (defun org-file-contents (file &optional noerror nocache)
5224 "Return the contents of FILE, as a string.
5226 FILE can be a file name or URL.
5228 If FILE is a URL, download the contents. If the URL contents are
5229 already cached in the `org--file-cache' hash table, the download step
5230 is skipped.
5232 If NOERROR is non-nil, ignore the error when unable to read the FILE
5233 from file or URL.
5235 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5236 is available. This option applies only if FILE is a URL."
5237 (let* ((is-url (org-file-url-p file))
5238 (cache (and is-url
5239 (not nocache)
5240 (gethash file org--file-cache))))
5241 (cond
5242 (cache)
5243 (is-url
5244 (with-current-buffer (url-retrieve-synchronously file)
5245 (goto-char (point-min))
5246 ;; Move point to after the url-retrieve header.
5247 (search-forward "\n\n" nil :move)
5248 ;; Search for the success code only in the url-retrieve header.
5249 (if (save-excursion
5250 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5251 ;; Update the cache `org--file-cache' and return contents.
5252 (puthash file
5253 (buffer-substring-no-properties (point) (point-max))
5254 org--file-cache)
5255 (funcall (if noerror #'message #'user-error)
5256 "Unable to fetch file from %S"
5257 file))))
5259 (with-temp-buffer
5260 (condition-case nil
5261 (progn
5262 (insert-file-contents file)
5263 (buffer-string))
5264 (file-error
5265 (funcall (if noerror #'message #'user-error)
5266 "Unable to read file %S"
5267 file))))))))
5269 (defun org-extract-log-state-settings (x)
5270 "Extract the log state setting from a TODO keyword string.
5271 This will extract info from a string like \"WAIT(w@/!)\"."
5272 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5273 (let ((kw (match-string 1 x))
5274 (log1 (and (match-end 3) (match-string 3 x)))
5275 (log2 (and (match-end 4) (match-string 4 x))))
5276 (and (or log1 log2)
5277 (list kw
5278 (and log1 (if (equal log1 "!") 'time 'note))
5279 (and log2 (if (equal log2 "!") 'time 'note)))))))
5281 (defun org-remove-keyword-keys (list)
5282 "Remove a pair of parenthesis at the end of each string in LIST."
5283 (mapcar (lambda (x)
5284 (if (string-match "(.*)$" x)
5285 (substring x 0 (match-beginning 0))
5287 list))
5289 (defun org-assign-fast-keys (alist)
5290 "Assign fast keys to a keyword-key alist.
5291 Respect keys that are already there."
5292 (let (new e (alt ?0))
5293 (while (setq e (pop alist))
5294 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5295 (cdr e)) ;; Key already assigned.
5296 (push e new)
5297 (let ((clist (string-to-list (downcase (car e))))
5298 (used (append new alist)))
5299 (when (= (car clist) ?@)
5300 (pop clist))
5301 (while (and clist (rassoc (car clist) used))
5302 (pop clist))
5303 (unless clist
5304 (while (rassoc alt used)
5305 (cl-incf alt)))
5306 (push (cons (car e) (or (car clist) alt)) new))))
5307 (nreverse new)))
5309 ;;; Some variables used in various places
5311 (defvar org-window-configuration nil
5312 "Used in various places to store a window configuration.")
5313 (defvar org-selected-window nil
5314 "Used in various places to store a window configuration.")
5315 (defvar org-finish-function nil
5316 "Function to be called when `C-c C-c' is used.
5317 This is for getting out of special buffers like capture.")
5318 (defvar org-last-state)
5320 ;; Defined somewhere in this file, but used before definition.
5321 (defvar org-entities) ;; defined in org-entities.el
5322 (defvar org-struct-menu)
5323 (defvar org-org-menu)
5324 (defvar org-tbl-menu)
5326 ;;;; Define the Org mode
5328 ;; We use a before-change function to check if a table might need
5329 ;; an update.
5330 (defvar org-table-may-need-update t
5331 "Indicates that a table might need an update.
5332 This variable is set by `org-before-change-function'.
5333 `org-table-align' sets it back to nil.")
5334 (defun org-before-change-function (_beg _end)
5335 "Every change indicates that a table might need an update."
5336 (setq org-table-may-need-update t))
5337 (defvar org-mode-map)
5338 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5339 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5340 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5341 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5342 (defvar org-table-buffer-is-an nil)
5344 (defvar bidi-paragraph-direction)
5345 (defvar buffer-face-mode-face)
5347 (require 'outline)
5349 ;; Other stuff we need.
5350 (require 'time-date)
5351 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5352 (require 'easymenu)
5353 (autoload 'easy-menu-add "easymenu")
5354 (require 'overlay)
5356 ;; (require 'org-macs) moved higher up in the file before it is first used
5357 (require 'org-entities)
5358 ;; (require 'org-compat) moved higher up in the file before it is first used
5359 (require 'org-faces)
5360 (require 'org-list)
5361 (require 'org-pcomplete)
5362 (require 'org-src)
5363 (require 'org-footnote)
5364 (require 'org-macro)
5366 ;; babel
5367 (require 'ob)
5369 ;;;###autoload
5370 (define-derived-mode org-mode outline-mode "Org"
5371 "Outline-based notes management and organizer, alias
5372 \"Carsten's outline-mode for keeping track of everything.\"
5374 Org mode develops organizational tasks around a NOTES file which
5375 contains information about projects as plain text. Org mode is
5376 implemented on top of Outline mode, which is ideal to keep the content
5377 of large files well structured. It supports ToDo items, deadlines and
5378 time stamps, which magically appear in the diary listing of the Emacs
5379 calendar. Tables are easily created with a built-in table editor.
5380 Plain text URL-like links connect to websites, emails (VM), Usenet
5381 messages (Gnus), BBDB entries, and any files related to the project.
5382 For printing and sharing of notes, an Org file (or a part of it)
5383 can be exported as a structured ASCII or HTML file.
5385 The following commands are available:
5387 \\{org-mode-map}"
5389 ;; Get rid of Outline menus, they are not needed
5390 ;; Need to do this here because define-derived-mode sets up
5391 ;; the keymap so late. Still, it is a waste to call this each time
5392 ;; we switch another buffer into Org mode.
5393 (define-key org-mode-map [menu-bar headings] 'undefined)
5394 (define-key org-mode-map [menu-bar hide] 'undefined)
5395 (define-key org-mode-map [menu-bar show] 'undefined)
5397 (org-load-modules-maybe)
5398 (org-install-agenda-files-menu)
5399 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5400 (add-to-invisibility-spec '(org-hide-block . t))
5401 (setq-local outline-regexp org-outline-regexp)
5402 (setq-local outline-level 'org-outline-level)
5403 (setq bidi-paragraph-direction 'left-to-right)
5404 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5405 (unless org-display-table
5406 (setq org-display-table (make-display-table)))
5407 (set-display-table-slot
5408 org-display-table 4
5409 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5410 org-ellipsis)))
5411 (setq buffer-display-table org-display-table))
5412 (org-set-regexps-and-options)
5413 (org-set-font-lock-defaults)
5414 (when (and org-tag-faces (not org-tags-special-faces-re))
5415 ;; tag faces set outside customize.... force initialization.
5416 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5417 ;; Calc embedded
5418 (setq-local calc-embedded-open-mode "# ")
5419 ;; Modify a few syntax entries
5420 (modify-syntax-entry ?@ "w")
5421 (modify-syntax-entry ?\" "\"")
5422 (modify-syntax-entry ?\\ "_")
5423 (modify-syntax-entry ?~ "_")
5424 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5425 ;; Activate before-change-function
5426 (setq-local org-table-may-need-update t)
5427 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5428 ;; Check for running clock before killing a buffer
5429 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5430 ;; Initialize macros templates.
5431 (org-macro-initialize-templates)
5432 ;; Initialize radio targets.
5433 (org-update-radio-target-regexp)
5434 ;; Indentation.
5435 (setq-local indent-line-function 'org-indent-line)
5436 (setq-local indent-region-function 'org-indent-region)
5437 ;; Filling and auto-filling.
5438 (org-setup-filling)
5439 ;; Comments.
5440 (org-setup-comments-handling)
5441 ;; Initialize cache.
5442 (org-element-cache-reset)
5443 ;; Beginning/end of defun
5444 (setq-local beginning-of-defun-function 'org-backward-element)
5445 (setq-local end-of-defun-function
5446 (lambda ()
5447 (if (not (org-at-heading-p))
5448 (org-forward-element)
5449 (org-forward-element)
5450 (forward-char -1))))
5451 ;; Next error for sparse trees
5452 (setq-local next-error-function 'org-occur-next-match)
5453 ;; Make sure dependence stuff works reliably, even for users who set it
5454 ;; too late :-(
5455 (if org-enforce-todo-dependencies
5456 (add-hook 'org-blocker-hook
5457 'org-block-todo-from-children-or-siblings-or-parent)
5458 (remove-hook 'org-blocker-hook
5459 'org-block-todo-from-children-or-siblings-or-parent))
5460 (if org-enforce-todo-checkbox-dependencies
5461 (add-hook 'org-blocker-hook
5462 'org-block-todo-from-checkboxes)
5463 (remove-hook 'org-blocker-hook
5464 'org-block-todo-from-checkboxes))
5466 ;; Align options lines
5467 (setq-local
5468 align-mode-rules-list
5469 '((org-in-buffer-settings
5470 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5471 (modes . '(org-mode)))))
5473 ;; Imenu
5474 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5476 ;; Make isearch reveal context
5477 (setq-local outline-isearch-open-invisible-function
5478 (lambda (&rest _) (org-show-context 'isearch)))
5480 ;; Setup the pcomplete hooks
5481 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5482 (setq-local pcomplete-command-name-function 'org-command-at-point)
5483 (setq-local pcomplete-default-completion-function 'ignore)
5484 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5485 (setq-local pcomplete-termination-string "")
5486 (setq-local buffer-face-mode-face 'org-default)
5488 ;; If empty file that did not turn on Org mode automatically, make
5489 ;; it to.
5490 (when (and org-insert-mode-line-in-empty-file
5491 (called-interactively-p 'any)
5492 (= (point-min) (point-max)))
5493 (insert "# -*- mode: org -*-\n\n"))
5494 (unless org-inhibit-startup
5495 (org-unmodified
5496 (when org-startup-with-beamer-mode (org-beamer-mode))
5497 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5498 (org-table-map-tables
5499 (cond ((and org-startup-align-all-tables
5500 org-startup-shrink-all-tables)
5501 (lambda () (org-table-align) (org-table-shrink)))
5502 (org-startup-align-all-tables #'org-table-align)
5503 (t #'org-table-shrink))
5505 (when org-startup-with-inline-images (org-display-inline-images))
5506 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5507 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5508 (when org-startup-truncated (setq truncate-lines t))
5509 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5510 (org-refresh-effort-properties)))
5511 ;; Try to set `org-hide' face correctly.
5512 (let ((foreground (org-find-invisible-foreground)))
5513 (when foreground
5514 (set-face-foreground 'org-hide foreground))))
5516 ;; Update `customize-package-emacs-version-alist'
5517 (add-to-list 'customize-package-emacs-version-alist
5518 '(Org ("8.0" . "24.4")
5519 ("8.1" . "24.4")
5520 ("8.2" . "24.4")
5521 ("8.2.7" . "24.4")
5522 ("8.3" . "26.1")
5523 ("9.0" . "26.1")
5524 ("9.1" . "26.1")
5525 ("9.2" . "27.1")))
5527 (defvar org-mode-transpose-word-syntax-table
5528 (let ((st (make-syntax-table text-mode-syntax-table)))
5529 (dolist (c org-emphasis-alist st)
5530 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5532 (when (fboundp 'abbrev-table-put)
5533 (abbrev-table-put org-mode-abbrev-table
5534 :parents (list text-mode-abbrev-table)))
5536 (defun org-find-invisible-foreground ()
5537 (let ((candidates (remove
5538 "unspecified-bg"
5539 (nconc
5540 (list (face-background 'default)
5541 (face-background 'org-default))
5542 (mapcar
5543 (lambda (alist)
5544 (when (boundp alist)
5545 (cdr (assq 'background-color (symbol-value alist)))))
5546 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5547 (list (face-foreground 'org-hide))))))
5548 (car (remove nil candidates))))
5550 (defun org-current-time (&optional rounding-minutes past)
5551 "Current time, possibly rounded to ROUNDING-MINUTES.
5552 When ROUNDING-MINUTES is not an integer, fall back on the car of
5553 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5554 the rounding returns a past time."
5555 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5556 (car org-time-stamp-rounding-minutes)))
5557 (time (decode-time)) res)
5558 (if (< r 1)
5559 (current-time)
5560 (setq res
5561 (apply 'encode-time
5562 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5563 (nthcdr 2 time))))
5564 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5565 (seconds-to-time (- (float-time res) (* r 60)))
5566 res))))
5568 (defun org-today ()
5569 "Return today date, considering `org-extend-today-until'."
5570 (time-to-days
5571 (time-subtract (current-time)
5572 (list 0 (* 3600 org-extend-today-until) 0))))
5574 ;;;; Font-Lock stuff, including the activators
5576 (defvar org-mouse-map (make-sparse-keymap))
5577 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5578 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5579 (when org-mouse-1-follows-link
5580 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5581 (when org-tab-follows-link
5582 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5583 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5585 (require 'font-lock)
5587 (defconst org-non-link-chars "]\t\n\r<>")
5588 (defvar org-link-types-re nil
5589 "Matches a link that has a url-like prefix like \"http:\"")
5590 (defvar org-link-re-with-space nil
5591 "Matches a link with spaces, optional angular brackets around it.")
5592 (defvar org-link-re-with-space2 nil
5593 "Matches a link with spaces, optional angular brackets around it.")
5594 (defvar org-link-re-with-space3 nil
5595 "Matches a link with spaces, only for internal part in bracket links.")
5596 (defvar org-angle-link-re nil
5597 "Matches link with angular brackets, spaces are allowed.")
5598 (defvar org-plain-link-re nil
5599 "Matches plain link, without spaces.")
5600 (defvar org-bracket-link-regexp nil
5601 "Matches a link in double brackets.")
5602 (defvar org-bracket-link-analytic-regexp nil
5603 "Regular expression used to analyze links.
5604 Here is what the match groups contain after a match:
5605 1: http:
5606 2: http
5607 3: path
5608 4: [desc]
5609 5: desc")
5610 (defvar org-bracket-link-analytic-regexp++ nil
5611 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5612 (defvar org-any-link-re nil
5613 "Regular expression matching any link.")
5615 (defconst org-match-sexp-depth 3
5616 "Number of stacked braces for sub/superscript matching.")
5618 (defun org-create-multibrace-regexp (left right n)
5619 "Create a regular expression which will match a balanced sexp.
5620 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5621 as single character strings.
5622 The regexp returned will match the entire expression including the
5623 delimiters. It will also define a single group which contains the
5624 match except for the outermost delimiters. The maximum depth of
5625 stacked delimiters is N. Escaping delimiters is not possible."
5626 (let* ((nothing (concat "[^" left right "]*?"))
5627 (or "\\|")
5628 (re nothing)
5629 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5630 (while (> n 1)
5631 (setq n (1- n)
5632 re (concat re or next)
5633 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5634 (concat left "\\(" re "\\)" right)))
5636 (defconst org-match-substring-regexp
5637 (concat
5638 "\\(\\S-\\)\\([_^]\\)\\("
5639 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5640 "\\|"
5641 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5642 "\\|"
5643 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5644 "The regular expression matching a sub- or superscript.")
5646 (defconst org-match-substring-with-braces-regexp
5647 (concat
5648 "\\(\\S-\\)\\([_^]\\)"
5649 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5650 "The regular expression matching a sub- or superscript, forcing braces.")
5652 (defun org-make-link-regexps ()
5653 "Update the link regular expressions.
5654 This should be called after the variable `org-link-parameters' has changed."
5655 (let ((types-re (regexp-opt (org-link-types) t)))
5656 (setq org-link-types-re
5657 (concat "\\`" types-re ":")
5658 org-link-re-with-space
5659 (concat "<?" types-re ":"
5660 "\\([^" org-non-link-chars " ]"
5661 "[^" org-non-link-chars "]*"
5662 "[^" org-non-link-chars " ]\\)>?")
5663 org-link-re-with-space2
5664 (concat "<?" types-re ":"
5665 "\\([^" org-non-link-chars " ]"
5666 "[^\t\n\r]*"
5667 "[^" org-non-link-chars " ]\\)>?")
5668 org-link-re-with-space3
5669 (concat "<?" types-re ":"
5670 "\\([^" org-non-link-chars " ]"
5671 "[^\t\n\r]*\\)")
5672 org-angle-link-re
5673 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5674 types-re)
5675 org-plain-link-re
5676 (concat
5677 "\\<" types-re ":"
5678 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5679 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5680 org-bracket-link-regexp
5681 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5682 org-bracket-link-analytic-regexp
5683 (concat
5684 "\\[\\["
5685 "\\(" types-re ":\\)?"
5686 "\\([^]]+\\)"
5687 "\\]"
5688 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5689 "\\]")
5690 org-bracket-link-analytic-regexp++
5691 (concat
5692 "\\[\\["
5693 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5694 "\\([^]]+\\)"
5695 "\\]"
5696 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5697 "\\]")
5698 org-any-link-re
5699 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5700 org-angle-link-re "\\)\\|\\("
5701 org-plain-link-re "\\)"))))
5703 (org-make-link-regexps)
5705 (defvar org-emph-face nil)
5707 (defun org-do-emphasis-faces (limit)
5708 "Run through the buffer and emphasize strings."
5709 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5710 (car org-emphasis-regexp-components))))
5711 (catch :exit
5712 (while (re-search-forward quick-re limit t)
5713 (let* ((marker (match-string 2))
5714 (verbatim? (member marker '("~" "="))))
5715 (when (save-excursion
5716 (goto-char (match-beginning 0))
5717 (and
5718 ;; Do not match table hlines.
5719 (not (and (equal marker "+")
5720 (org-match-line
5721 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5722 ;; Do not match headline stars. Do not consider
5723 ;; stars of a headline as closing marker for bold
5724 ;; markup either.
5725 (not (and (equal marker "*")
5726 (save-excursion
5727 (forward-char)
5728 (skip-chars-backward "*")
5729 (looking-at-p org-outline-regexp-bol))))
5730 ;; Match full emphasis markup regexp.
5731 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5732 ;; Do not span over paragraph boundaries.
5733 (not (string-match-p org-element-paragraph-separate
5734 (match-string 2)))
5735 ;; Do not span over cells in table rows.
5736 (not (and (save-match-data (org-match-line "[ \t]*|"))
5737 (string-match-p "|" (match-string 4))))))
5738 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5739 (font-lock-prepend-text-property
5740 (match-beginning 2) (match-end 2) 'face face)
5741 (when verbatim?
5742 (org-remove-flyspell-overlays-in
5743 (match-beginning 0) (match-end 0)))
5744 (add-text-properties (match-beginning 2) (match-end 2)
5745 '(font-lock-multiline t org-emphasis t))
5746 (when org-hide-emphasis-markers
5747 (add-text-properties (match-end 4) (match-beginning 5)
5748 '(invisible org-link))
5749 (add-text-properties (match-beginning 3) (match-end 3)
5750 '(invisible org-link)))
5751 (throw :exit t))))))))
5753 (defun org-emphasize (&optional char)
5754 "Insert or change an emphasis, i.e. a font like bold or italic.
5755 If there is an active region, change that region to a new emphasis.
5756 If there is no region, just insert the marker characters and position
5757 the cursor between them.
5758 CHAR should be the marker character. If it is a space, it means to
5759 remove the emphasis of the selected region.
5760 If CHAR is not given (for example in an interactive call) it will be
5761 prompted for."
5762 (interactive)
5763 (let ((erc org-emphasis-regexp-components)
5764 (string "") beg end move s)
5765 (if (org-region-active-p)
5766 (setq beg (region-beginning)
5767 end (region-end)
5768 string (buffer-substring beg end))
5769 (setq move t))
5771 (unless char
5772 (message "Emphasis marker or tag: [%s]"
5773 (mapconcat #'car org-emphasis-alist ""))
5774 (setq char (read-char-exclusive)))
5775 (if (equal char ?\s)
5776 (setq s ""
5777 move nil)
5778 (unless (assoc (char-to-string char) org-emphasis-alist)
5779 (user-error "No such emphasis marker: \"%c\"" char))
5780 (setq s (char-to-string char)))
5781 (while (and (> (length string) 1)
5782 (equal (substring string 0 1) (substring string -1))
5783 (assoc (substring string 0 1) org-emphasis-alist))
5784 (setq string (substring string 1 -1)))
5785 (setq string (concat s string s))
5786 (when beg (delete-region beg end))
5787 (unless (or (bolp)
5788 (string-match (concat "[" (nth 0 erc) "\n]")
5789 (char-to-string (char-before (point)))))
5790 (insert " "))
5791 (unless (or (eobp)
5792 (string-match (concat "[" (nth 1 erc) "\n]")
5793 (char-to-string (char-after (point)))))
5794 (insert " ") (backward-char 1))
5795 (insert string)
5796 (and move (backward-char 1))))
5798 (defconst org-nonsticky-props
5799 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5801 (defsubst org-rear-nonsticky-at (pos)
5802 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5804 (defun org-activate-links (limit)
5805 "Add link properties to links.
5806 This includes angle, plain, and bracket links."
5807 (catch :exit
5808 (while (re-search-forward org-any-link-re limit t)
5809 (let* ((start (match-beginning 0))
5810 (end (match-end 0))
5811 (style (cond ((eq ?< (char-after start)) 'angle)
5812 ((eq ?\[ (char-after (1+ start))) 'bracket)
5813 (t 'plain))))
5814 (when (and (memq style org-highlight-links)
5815 ;; Do not confuse plain links with tags.
5816 (not (and (eq style 'plain)
5817 (let ((face (get-text-property
5818 (max (1- start) (point-min)) 'face)))
5819 (if (consp face) (memq 'org-tag face)
5820 (eq 'org-tag face))))))
5821 (let* ((link-object (save-excursion
5822 (goto-char start)
5823 (save-match-data (org-element-link-parser))))
5824 (link (org-element-property :raw-link link-object))
5825 (type (org-element-property :type link-object))
5826 (path (org-element-property :path link-object))
5827 (properties ;for link's visible part
5828 (list
5829 'face (pcase (org-link-get-parameter type :face)
5830 ((and (pred functionp) face) (funcall face path))
5831 ((and (pred facep) face) face)
5832 ((and (pred consp) face) face) ;anonymous
5833 (_ 'org-link))
5834 'mouse-face (or (org-link-get-parameter type :mouse-face)
5835 'highlight)
5836 'keymap (or (org-link-get-parameter type :keymap)
5837 org-mouse-map)
5838 'help-echo (pcase (org-link-get-parameter type :help-echo)
5839 ((and (pred stringp) echo) echo)
5840 ((and (pred functionp) echo) echo)
5841 (_ (concat "LINK: " link)))
5842 'htmlize-link (pcase (org-link-get-parameter type
5843 :htmlize-link)
5844 ((and (pred functionp) f) (funcall f))
5845 (_ `(:uri ,link)))
5846 'font-lock-multiline t)))
5847 (org-remove-flyspell-overlays-in start end)
5848 (org-rear-nonsticky-at end)
5849 (if (not (eq 'bracket style))
5850 (add-text-properties start end properties)
5851 ;; Handle invisible parts in bracket links.
5852 (remove-text-properties start end '(invisible nil))
5853 (let ((hidden
5854 (append `(invisible
5855 ,(or (org-link-get-parameter type :display)
5856 'org-link))
5857 properties))
5858 (visible-start (or (match-beginning 4) (match-beginning 2)))
5859 (visible-end (or (match-end 4) (match-end 2))))
5860 (add-text-properties start visible-start hidden)
5861 (add-text-properties visible-start visible-end properties)
5862 (add-text-properties visible-end end hidden)
5863 (org-rear-nonsticky-at visible-start)
5864 (org-rear-nonsticky-at visible-end)))
5865 (let ((f (org-link-get-parameter type :activate-func)))
5866 (when (functionp f)
5867 (funcall f start end path (eq style 'bracket))))
5868 (throw :exit t))))) ;signal success
5869 nil))
5871 (defun org-activate-code (limit)
5872 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5873 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5874 (remove-text-properties (match-beginning 0) (match-end 0)
5875 '(display t invisible t intangible t))
5878 (defcustom org-src-fontify-natively t
5879 "When non-nil, fontify code in code blocks.
5880 See also the `org-block' face."
5881 :type 'boolean
5882 :version "26.1"
5883 :package-version '(Org . "8.3")
5884 :group 'org-appearance
5885 :group 'org-babel)
5887 (defcustom org-allow-promoting-top-level-subtree nil
5888 "When non-nil, allow promoting a top level subtree.
5889 The leading star of the top level headline will be replaced
5890 by a #."
5891 :type 'boolean
5892 :version "24.1"
5893 :group 'org-appearance)
5895 (defun org-fontify-meta-lines-and-blocks (limit)
5896 (condition-case nil
5897 (org-fontify-meta-lines-and-blocks-1 limit)
5898 (error (message "org-mode fontification error in %S at %d"
5899 (current-buffer)
5900 (line-number-at-pos)))))
5902 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5903 "Fontify #+ lines and blocks."
5904 (let ((case-fold-search t))
5905 (when (re-search-forward
5906 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5907 limit t)
5908 (let ((beg (match-beginning 0))
5909 (block-start (match-end 0))
5910 (block-end nil)
5911 (lang (match-string 7))
5912 (beg1 (line-beginning-position 2))
5913 (dc1 (downcase (match-string 2)))
5914 (dc3 (downcase (match-string 3)))
5915 end end1 quoting block-type)
5916 (cond
5917 ((and (match-end 4) (equal dc3 "+begin"))
5918 ;; Truly a block
5919 (setq block-type (downcase (match-string 5))
5920 quoting (member block-type org-protecting-blocks))
5921 (when (re-search-forward
5922 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5923 nil t) ;; on purpose, we look further than LIMIT
5924 (setq end (min (point-max) (match-end 0))
5925 end1 (min (point-max) (1- (match-beginning 0))))
5926 (setq block-end (match-beginning 0))
5927 (when quoting
5928 (org-remove-flyspell-overlays-in beg1 end1)
5929 (remove-text-properties beg end
5930 '(display t invisible t intangible t)))
5931 (add-text-properties
5932 beg end '(font-lock-fontified t font-lock-multiline t))
5933 (add-text-properties beg beg1 '(face org-meta-line))
5934 (org-remove-flyspell-overlays-in beg beg1)
5935 (add-text-properties ; For end_src
5936 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5937 (org-remove-flyspell-overlays-in end1 end)
5938 (cond
5939 ((and lang (not (string= lang "")) org-src-fontify-natively)
5940 (org-src-font-lock-fontify-block lang block-start block-end)
5941 (add-text-properties beg1 block-end '(src-block t)))
5942 (quoting
5943 (add-text-properties beg1 (min (point-max) (1+ end1))
5944 (list 'face
5945 (list :inherit
5946 (let ((face-name
5947 (intern (format "org-block-%s" lang))))
5948 (append (and (facep face-name) (list face-name))
5949 '(org-block))))))) ; end of source block
5950 ((not org-fontify-quote-and-verse-blocks))
5951 ((string= block-type "quote")
5952 (add-face-text-property
5953 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5954 ((string= block-type "verse")
5955 (add-face-text-property
5956 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5957 (add-text-properties beg beg1 '(face org-block-begin-line))
5958 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5959 '(face org-block-end-line))
5961 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5962 (org-remove-flyspell-overlays-in
5963 (match-beginning 0)
5964 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5965 (add-text-properties
5966 beg (match-end 3)
5967 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5968 '(font-lock-fontified t invisible t)
5969 '(font-lock-fontified t face org-document-info-keyword)))
5970 (add-text-properties
5971 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5972 (if (string-equal dc1 "+title:")
5973 '(font-lock-fontified t face org-document-title)
5974 '(font-lock-fontified t face org-document-info))))
5975 ((string-prefix-p "+caption" dc1)
5976 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5977 (remove-text-properties (match-beginning 0) (match-end 0)
5978 '(display t invisible t intangible t))
5979 ;; Handle short captions.
5980 (save-excursion
5981 (beginning-of-line)
5982 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5983 (add-text-properties (line-beginning-position) (match-end 1)
5984 '(font-lock-fontified t face org-meta-line))
5985 (add-text-properties (match-end 0) (line-end-position)
5986 '(font-lock-fontified t face org-block))
5988 ((member dc3 '(" " ""))
5989 (org-remove-flyspell-overlays-in beg (match-end 0))
5990 (add-text-properties
5991 beg (match-end 0)
5992 '(font-lock-fontified t face font-lock-comment-face)))
5993 (t ;; just any other in-buffer setting, but not indented
5994 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5995 (remove-text-properties (match-beginning 0) (match-end 0)
5996 '(display t invisible t intangible t))
5997 (add-text-properties beg (match-end 0)
5998 '(font-lock-fontified t face org-meta-line))
5999 t))))))
6001 (defun org-fontify-drawers (limit)
6002 "Fontify drawers."
6003 (when (re-search-forward org-drawer-regexp limit t)
6004 (add-text-properties
6005 (match-beginning 0) (match-end 0)
6006 '(font-lock-fontified t face org-special-keyword))
6007 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6010 (defun org-fontify-macros (limit)
6011 "Fontify macros."
6012 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6013 (add-text-properties
6014 (match-beginning 0) (match-end 0)
6015 '(font-lock-fontified t face org-macro))
6016 (when org-hide-macro-markers
6017 (add-text-properties (match-end 2) (match-beginning 2)
6018 '(invisible t))
6019 (add-text-properties (match-beginning 1) (match-end 1)
6020 '(invisible t)))
6021 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6024 (defun org-activate-footnote-links (limit)
6025 "Add text properties for footnotes."
6026 (let ((fn (org-footnote-next-reference-or-definition limit)))
6027 (when fn
6028 (let* ((beg (nth 1 fn))
6029 (end (nth 2 fn))
6030 (label (car fn))
6031 (referencep (/= (line-beginning-position) beg)))
6032 (when (and referencep (nth 3 fn))
6033 (save-excursion
6034 (goto-char beg)
6035 (search-forward (or label "fn:"))
6036 (org-remove-flyspell-overlays-in beg (match-end 0))))
6037 (add-text-properties beg end
6038 (list 'mouse-face 'highlight
6039 'keymap org-mouse-map
6040 'help-echo
6041 (if referencep "Footnote reference"
6042 "Footnote definition")
6043 'font-lock-fontified t
6044 'font-lock-multiline t
6045 'face 'org-footnote))))))
6047 (defun org-activate-dates (limit)
6048 "Add text properties for dates."
6049 (when (and (re-search-forward org-tsr-regexp-both limit t)
6050 (not (equal (char-before (match-beginning 0)) 91)))
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6052 (add-text-properties (match-beginning 0) (match-end 0)
6053 (list 'mouse-face 'highlight
6054 'keymap org-mouse-map))
6055 (org-rear-nonsticky-at (match-end 0))
6056 (when org-display-custom-times
6057 ;; If it's a date range, activate custom time for second date.
6058 (when (match-end 3)
6059 (org-display-custom-time (match-beginning 3) (match-end 3)))
6060 (org-display-custom-time (match-beginning 1) (match-end 1)))
6063 (defvar-local org-target-link-regexp nil
6064 "Regular expression matching radio targets in plain text.")
6066 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6067 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6068 border border border))
6069 "Regular expression matching a link target.")
6071 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6072 "Regular expression matching a radio target.")
6074 (defconst org-any-target-regexp
6075 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6076 "Regular expression matching any target.")
6078 (defun org-activate-target-links (limit)
6079 "Add text properties for target matches."
6080 (when org-target-link-regexp
6081 (let ((case-fold-search t))
6082 (when (re-search-forward org-target-link-regexp limit t)
6083 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6084 (add-text-properties (match-beginning 1) (match-end 1)
6085 (list 'mouse-face 'highlight
6086 'keymap org-mouse-map
6087 'help-echo "Radio target link"
6088 'org-linked-text t))
6089 (org-rear-nonsticky-at (match-end 1))
6090 t))))
6092 (defun org-update-radio-target-regexp ()
6093 "Find all radio targets in this file and update the regular expression.
6094 Also refresh fontification if needed."
6095 (interactive)
6096 (let ((old-regexp org-target-link-regexp)
6097 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6098 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6099 (targets
6100 (org-with-wide-buffer
6101 (goto-char (point-min))
6102 (let (rtn)
6103 (while (re-search-forward org-radio-target-regexp nil t)
6104 ;; Make sure point is really within the object.
6105 (backward-char)
6106 (let ((obj (org-element-context)))
6107 (when (eq (org-element-type obj) 'radio-target)
6108 (cl-pushnew (org-element-property :value obj) rtn
6109 :test #'equal))))
6110 rtn))))
6111 (setq org-target-link-regexp
6112 (and targets
6113 (concat before-re
6114 (mapconcat
6115 (lambda (x)
6116 (replace-regexp-in-string
6117 " +" "\\s-+" (regexp-quote x) t t))
6118 targets
6119 "\\|")
6120 after-re)))
6121 (unless (equal old-regexp org-target-link-regexp)
6122 ;; Clean-up cache.
6123 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6124 ((not org-target-link-regexp) old-regexp)
6126 (concat before-re
6127 (mapconcat
6128 (lambda (re)
6129 (substring re (length before-re)
6130 (- (length after-re))))
6131 (list old-regexp org-target-link-regexp)
6132 "\\|")
6133 after-re)))))
6134 (org-with-wide-buffer
6135 (goto-char (point-min))
6136 (while (re-search-forward regexp nil t)
6137 (org-element-cache-refresh (match-beginning 1)))))
6138 ;; Re fontify buffer.
6139 (when (memq 'radio org-highlight-links)
6140 (org-restart-font-lock)))))
6142 (defvar org-latex-and-related-regexp nil
6143 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6145 (defun org-compute-latex-and-related-regexp ()
6146 "Compute regular expression for LaTeX, entities and sub/superscript.
6147 Result depends on variable `org-highlight-latex-and-related'."
6148 (setq-local
6149 org-latex-and-related-regexp
6150 (let* ((re-sub
6151 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6152 ((eq org-use-sub-superscripts '{})
6153 (list org-match-substring-with-braces-regexp))
6154 (org-use-sub-superscripts (list org-match-substring-regexp))))
6155 (re-latex
6156 (when (memq 'latex org-highlight-latex-and-related)
6157 (let ((matchers (plist-get org-format-latex-options :matchers)))
6158 (delq nil
6159 (mapcar (lambda (x)
6160 (and (member (car x) matchers) (nth 1 x)))
6161 org-latex-regexps)))))
6162 (re-entities
6163 (when (memq 'entities org-highlight-latex-and-related)
6164 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6165 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6167 (defun org-do-latex-and-related (limit)
6168 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6169 LIMIT bounds the search for syntax to highlight. Stop at first
6170 highlighted object, if any. Return t if some highlighting was
6171 done, nil otherwise."
6172 (when (org-string-nw-p org-latex-and-related-regexp)
6173 (catch 'found
6174 (while (re-search-forward org-latex-and-related-regexp limit t)
6175 (unless
6176 (cl-some
6177 (lambda (f)
6178 (memq f '(org-code org-verbatim underline org-special-keyword)))
6179 (save-excursion
6180 (goto-char (1+ (match-beginning 0)))
6181 (face-at-point nil t)))
6182 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6183 '(?_ ?^))
6185 0)))
6186 (font-lock-prepend-text-property
6187 (+ offset (match-beginning 0)) (match-end 0)
6188 'face 'org-latex-and-related)
6189 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6190 '(font-lock-multiline t)))
6191 (throw 'found t)))
6192 nil)))
6194 (defun org-restart-font-lock ()
6195 "Restart `font-lock-mode', to force refontification."
6196 (when (and (boundp 'font-lock-mode) font-lock-mode)
6197 (font-lock-mode -1)
6198 (font-lock-mode 1)))
6200 (defun org-activate-tags (limit)
6201 (when (re-search-forward
6202 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6203 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6204 (add-text-properties (match-beginning 1) (match-end 1)
6205 (list 'mouse-face 'highlight
6206 'keymap org-mouse-map))
6207 (org-rear-nonsticky-at (match-end 1))
6210 (defun org-outline-level ()
6211 "Compute the outline level of the heading at point.
6213 If this is called at a normal headline, the level is the number
6214 of stars. Use `org-reduced-level' to remove the effect of
6215 `org-odd-levels'. Unlike to `org-current-level', this function
6216 takes into consideration inlinetasks."
6217 (org-with-wide-buffer
6218 (end-of-line)
6219 (if (re-search-backward org-outline-regexp-bol nil t)
6220 (1- (- (match-end 0) (match-beginning 0)))
6221 0)))
6223 (defvar org-font-lock-keywords nil)
6225 (defsubst org-re-property (property &optional literal allow-null value)
6226 "Return a regexp matching a PROPERTY line.
6228 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6229 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6230 non-nil, match properties even without a value.
6232 Match group 3 is set to the value when it exists. If there is no
6233 value and ALLOW-NULL is non-nil, it is set to the empty string.
6235 With optional argument VALUE, match only property lines with
6236 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6237 unless LITERAL is non-nil."
6238 (concat
6239 "^\\(?4:[ \t]*\\)"
6240 (format "\\(?1::\\(?2:%s\\):\\)"
6241 (if literal property (regexp-quote property)))
6242 (cond (value
6243 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6244 (if literal value (regexp-quote value))))
6245 (allow-null
6246 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6248 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6250 (defconst org-property-re
6251 (org-re-property "\\S-+" 'literal t)
6252 "Regular expression matching a property line.
6253 There are four matching groups:
6254 1: :PROPKEY: including the leading and trailing colon,
6255 2: PROPKEY without the leading and trailing colon,
6256 3: PROPVAL without leading or trailing spaces,
6257 4: the indentation of the current line,
6258 5: trailing whitespace.")
6260 (defvar org-font-lock-hook nil
6261 "Functions to be called for special font lock stuff.")
6263 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6265 (defvar org-font-lock-set-keywords-hook nil
6266 "Functions that can manipulate `org-font-lock-extra-keywords'.
6267 This is called after `org-font-lock-extra-keywords' is defined, but before
6268 it is installed to be used by font lock. This can be useful if something
6269 needs to be inserted at a specific position in the font-lock sequence.")
6271 (defun org-font-lock-hook (limit)
6272 "Run `org-font-lock-hook' within LIMIT."
6273 (run-hook-with-args 'org-font-lock-hook limit))
6275 (defun org-set-font-lock-defaults ()
6276 "Set font lock defaults for the current buffer."
6277 (let* ((em org-fontify-emphasized-text)
6278 (lk org-highlight-links)
6279 (org-font-lock-extra-keywords
6280 (list
6281 ;; Call the hook
6282 '(org-font-lock-hook)
6283 ;; Headlines
6284 `(,(if org-fontify-whole-heading-line
6285 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6286 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6287 (1 (org-get-level-face 1))
6288 (2 (org-get-level-face 2))
6289 (3 (org-get-level-face 3)))
6290 ;; Table lines
6291 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6292 (1 'org-table t))
6293 ;; Table internals
6294 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6295 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6296 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6297 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6298 ;; Drawers
6299 '(org-fontify-drawers)
6300 ;; Properties
6301 (list org-property-re
6302 '(1 'org-special-keyword t)
6303 '(3 'org-property-value t))
6304 ;; Link related fontification.
6305 '(org-activate-links)
6306 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6307 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6308 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6309 (when (memq 'footnote lk) '(org-activate-footnote-links))
6310 ;; Targets.
6311 (list org-any-target-regexp '(0 'org-target t))
6312 ;; Diary sexps.
6313 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6314 ;; Macro
6315 '(org-fontify-macros)
6316 ;; TODO keyword
6317 (list (format org-heading-keyword-regexp-format
6318 org-todo-regexp)
6319 '(2 (org-get-todo-face 2) t))
6320 ;; DONE
6321 (if org-fontify-done-headline
6322 (list (format org-heading-keyword-regexp-format
6323 (concat
6324 "\\(?:"
6325 (mapconcat 'regexp-quote org-done-keywords "\\|")
6326 "\\)"))
6327 '(2 'org-headline-done t))
6328 nil)
6329 ;; Priorities
6330 '(org-font-lock-add-priority-faces)
6331 ;; Tags
6332 '(org-font-lock-add-tag-faces)
6333 ;; Tags groups
6334 (when (and org-group-tags org-tag-groups-alist)
6335 (list (concat org-outline-regexp-bol ".+\\(:"
6336 (regexp-opt (mapcar 'car org-tag-groups-alist))
6337 ":\\).*$")
6338 '(1 'org-tag-group prepend)))
6339 ;; Special keywords
6340 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6341 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6342 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6343 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6344 ;; Emphasis
6345 (when em '(org-do-emphasis-faces))
6346 ;; Checkboxes
6347 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6348 1 'org-checkbox prepend)
6349 (when (cdr (assq 'checkbox org-list-automatic-rules))
6350 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6351 (0 (org-get-checkbox-statistics-face) t)))
6352 ;; Description list items
6353 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6354 1 'org-list-dt prepend)
6355 ;; ARCHIVEd headings
6356 (list (concat
6357 org-outline-regexp-bol
6358 "\\(.*:" org-archive-tag ":.*\\)")
6359 '(1 'org-archived prepend))
6360 ;; Specials
6361 '(org-do-latex-and-related)
6362 '(org-fontify-entities)
6363 '(org-raise-scripts)
6364 ;; Code
6365 '(org-activate-code (1 'org-code t))
6366 ;; COMMENT
6367 (list (format
6368 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6369 org-todo-regexp
6370 org-comment-string)
6371 '(9 'org-special-keyword t))
6372 ;; Blocks and meta lines
6373 '(org-fontify-meta-lines-and-blocks))))
6374 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6375 (run-hooks 'org-font-lock-set-keywords-hook)
6376 ;; Now set the full font-lock-keywords
6377 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6378 (setq-local font-lock-defaults
6379 '(org-font-lock-keywords t nil nil backward-paragraph))
6380 (kill-local-variable 'font-lock-keywords)
6381 nil))
6383 (defun org-toggle-pretty-entities ()
6384 "Toggle the composition display of entities as UTF8 characters."
6385 (interactive)
6386 (setq-local org-pretty-entities (not org-pretty-entities))
6387 (org-restart-font-lock)
6388 (if org-pretty-entities
6389 (message "Entities are now displayed as UTF8 characters")
6390 (save-restriction
6391 (widen)
6392 (decompose-region (point-min) (point-max))
6393 (message "Entities are now displayed as plain text"))))
6395 (defvar-local org-custom-properties-overlays nil
6396 "List of overlays used for custom properties.")
6398 (defun org-toggle-custom-properties-visibility ()
6399 "Display or hide properties in `org-custom-properties'."
6400 (interactive)
6401 (if org-custom-properties-overlays
6402 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6403 (setq org-custom-properties-overlays nil))
6404 (when org-custom-properties
6405 (org-with-wide-buffer
6406 (goto-char (point-min))
6407 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6408 (while (re-search-forward regexp nil t)
6409 (let ((end (cdr (save-match-data (org-get-property-block)))))
6410 (when (and end (< (point) end))
6411 ;; Hide first custom property in current drawer.
6412 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6413 (overlay-put o 'invisible t)
6414 (overlay-put o 'org-custom-property t)
6415 (push o org-custom-properties-overlays))
6416 ;; Hide additional custom properties in the same drawer.
6417 (while (re-search-forward regexp end t)
6418 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6419 (overlay-put o 'invisible t)
6420 (overlay-put o 'org-custom-property t)
6421 (push o org-custom-properties-overlays)))))
6422 ;; Each entry is limited to a single property drawer.
6423 (outline-next-heading)))))))
6425 (defun org-fontify-entities (limit)
6426 "Find an entity to fontify."
6427 (let (ee)
6428 (when org-pretty-entities
6429 (catch 'match
6430 ;; "\_ "-family is left out on purpose. Only the first one,
6431 ;; i.e., "\_ ", could be fontified anyway, and it would be
6432 ;; confusing when adding a second white space character.
6433 (while (re-search-forward
6434 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6435 limit t)
6436 (when (and (not (org-at-comment-p))
6437 (setq ee (org-entity-get (match-string 1)))
6438 (= (length (nth 6 ee)) 1))
6439 (let* ((end (if (equal (match-string 2) "{}")
6440 (match-end 2)
6441 (match-end 1))))
6442 (add-text-properties
6443 (match-beginning 0) end
6444 (list 'font-lock-fontified t))
6445 (compose-region (match-beginning 0) end
6446 (nth 6 ee) nil)
6447 (backward-char 1)
6448 (throw 'match t))))
6449 nil))))
6451 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6452 "Fontify string S like in Org mode."
6453 (with-temp-buffer
6454 (insert s)
6455 (let ((org-odd-levels-only odd-levels))
6456 (org-mode)
6457 (org-font-lock-ensure)
6458 (buffer-string))))
6460 (defvar org-m nil)
6461 (defvar org-l nil)
6462 (defvar org-f nil)
6463 (defun org-get-level-face (n)
6464 "Get the right face for match N in font-lock matching of headlines."
6465 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6466 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6467 (if org-cycle-level-faces
6468 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6469 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6470 (cond
6471 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6472 ((eq n 2) org-f)
6473 (t (unless org-level-color-stars-only org-f))))
6475 (defun org-face-from-face-or-color (context inherit face-or-color)
6476 "Create a face list that inherits INHERIT, but sets the foreground color.
6477 When FACE-OR-COLOR is not a string, just return it."
6478 (if (stringp face-or-color)
6479 (list :inherit inherit
6480 (cdr (assoc context org-faces-easy-properties))
6481 face-or-color)
6482 face-or-color))
6484 (defun org-get-todo-face (kwd)
6485 "Get the right face for a TODO keyword KWD.
6486 If KWD is a number, get the corresponding match group."
6487 (when (numberp kwd) (setq kwd (match-string kwd)))
6488 (or (org-face-from-face-or-color
6489 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6490 (and (member kwd org-done-keywords) 'org-done)
6491 'org-todo))
6493 (defun org-get-priority-face (priority)
6494 "Get the right face for PRIORITY.
6495 PRIORITY is a character."
6496 (or (org-face-from-face-or-color
6497 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6498 'org-priority))
6500 (defun org-get-tag-face (tag)
6501 "Get the right face for TAG.
6502 If TAG is a number, get the corresponding match group."
6503 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6504 (or (org-face-from-face-or-color
6505 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6506 'org-tag)))
6508 (defun org-font-lock-add-priority-faces (limit)
6509 "Add the special priority faces."
6510 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6511 (add-text-properties
6512 (match-beginning 1) (match-end 1)
6513 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6514 'font-lock-fontified t))))
6516 (defun org-font-lock-add-tag-faces (limit)
6517 "Add the special tag faces."
6518 (when (and org-tag-faces org-tags-special-faces-re)
6519 (while (re-search-forward org-tags-special-faces-re limit t)
6520 (add-text-properties (match-beginning 1) (match-end 1)
6521 (list 'face (org-get-tag-face 1)
6522 'font-lock-fontified t))
6523 (backward-char 1))))
6525 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6526 "Remove fontification and activation overlays from links."
6527 (font-lock-default-unfontify-region beg end)
6528 (let* ((buffer-undo-list t)
6529 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6530 (inhibit-modification-hooks t)
6531 deactivate-mark buffer-file-name buffer-file-truename)
6532 (decompose-region beg end)
6533 (remove-text-properties beg end
6534 '(mouse-face t keymap t org-linked-text t
6535 invisible t intangible t
6536 org-emphasis t))
6537 (org-remove-font-lock-display-properties beg end)))
6539 (defconst org-script-display '(((raise -0.3) (height 0.7))
6540 ((raise 0.3) (height 0.7))
6541 ((raise -0.5))
6542 ((raise 0.5)))
6543 "Display properties for showing superscripts and subscripts.")
6545 (defun org-remove-font-lock-display-properties (beg end)
6546 "Remove specific display properties that have been added by font lock.
6547 The will remove the raise properties that are used to show superscripts
6548 and subscripts."
6549 (let (next prop)
6550 (while (< beg end)
6551 (setq next (next-single-property-change beg 'display nil end)
6552 prop (get-text-property beg 'display))
6553 (when (member prop org-script-display)
6554 (put-text-property beg next 'display nil))
6555 (setq beg next))))
6557 (defun org-raise-scripts (limit)
6558 "Add raise properties to sub/superscripts."
6559 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6560 (re-search-forward
6561 (if (eq org-use-sub-superscripts t)
6562 org-match-substring-regexp
6563 org-match-substring-with-braces-regexp)
6564 limit t))
6565 (let* ((pos (point)) table-p comment-p
6566 (mpos (match-beginning 3))
6567 (emph-p (get-text-property mpos 'org-emphasis))
6568 (link-p (get-text-property mpos 'mouse-face))
6569 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6570 (goto-char (point-at-bol))
6571 (setq table-p (looking-at-p org-table-dataline-regexp)
6572 comment-p (looking-at-p "^[ \t]*#[ +]"))
6573 (goto-char pos)
6574 ;; Handle a_b^c
6575 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6576 (unless (or comment-p emph-p link-p keyw-p)
6577 (put-text-property (match-beginning 3) (match-end 0)
6578 'display
6579 (if (equal (char-after (match-beginning 2)) ?^)
6580 (nth (if table-p 3 1) org-script-display)
6581 (nth (if table-p 2 0) org-script-display)))
6582 (add-text-properties (match-beginning 2) (match-end 2)
6583 (list 'invisible t))
6584 (when (and (eq (char-after (match-beginning 3)) ?{)
6585 (eq (char-before (match-end 3)) ?}))
6586 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6587 (list 'invisible t))
6588 (add-text-properties (1- (match-end 3)) (match-end 3)
6589 (list 'invisible t))))
6590 t)))
6592 ;;;; Visibility cycling, including org-goto and indirect buffer
6594 ;;; Cycling
6596 (defvar-local org-cycle-global-status nil)
6597 (put 'org-cycle-global-status 'org-state t)
6598 (defvar-local org-cycle-subtree-status nil)
6599 (put 'org-cycle-subtree-status 'org-state t)
6601 (defvar org-inlinetask-min-level)
6603 ;;;###autoload
6604 (defun org-cycle (&optional arg)
6605 "TAB-action and visibility cycling for Org mode.
6607 This is the command invoked in Org mode by the `TAB' key. Its main
6608 purpose is outline visibility cycling, but it also invokes other actions
6609 in special contexts.
6611 When this function is called with a `\\[universal-argument]' prefix, rotate \
6612 the entire
6613 buffer through 3 states (global cycling)
6614 1. OVERVIEW: Show only top-level headlines.
6615 2. CONTENTS: Show all headlines of all levels, but no body text.
6616 3. SHOW ALL: Show everything.
6618 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6619 switch to the startup visibility,
6620 determined by the variable `org-startup-folded', and by any VISIBILITY
6621 properties in the buffer.
6623 With a `\\[universal-argument] \\[universal-argument] \
6624 \\[universal-argument]' prefix argument, show the entire buffer, including
6625 any drawers.
6627 When inside a table, re-align the table and move to the next field.
6629 When point is at the beginning of a headline, rotate the subtree started
6630 by this line through 3 different states (local cycling)
6631 1. FOLDED: Only the main headline is shown.
6632 2. CHILDREN: The main headline and the direct children are shown.
6633 From this state, you can move to one of the children
6634 and zoom in further.
6635 3. SUBTREE: Show the entire subtree, including body text.
6636 If there is no subtree, switch directly from CHILDREN to FOLDED.
6638 When point is at the beginning of an empty headline and the variable
6639 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6640 of the headline by demoting and promoting it to likely levels. This
6641 speeds up creation document structure by pressing `TAB' once or several
6642 times right after creating a new headline.
6644 When there is a numeric prefix, go up to a heading with level ARG, do
6645 a `show-subtree' and return to the previous cursor position. If ARG
6646 is negative, go up that many levels.
6648 When point is not at the beginning of a headline, execute the global
6649 binding for `TAB', which is re-indenting the line. See the option
6650 `org-cycle-emulate-tab' for details.
6652 As a special case, if point is at the beginning of the buffer and there is
6653 no headline in line 1, this function will act as if called with prefix arg
6654 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6655 prefix arg, but only
6656 if the variable `org-cycle-global-at-bob' is t."
6657 (interactive "P")
6658 (org-load-modules-maybe)
6659 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6660 (and org-cycle-level-after-item/entry-creation
6661 (or (org-cycle-level)
6662 (org-cycle-item-indentation))))
6663 (let* ((limit-level
6664 (or org-cycle-max-level
6665 (and (boundp 'org-inlinetask-min-level)
6666 org-inlinetask-min-level
6667 (1- org-inlinetask-min-level))))
6668 (nstars (and limit-level
6669 (if org-odd-levels-only
6670 (and limit-level (1- (* limit-level 2)))
6671 limit-level)))
6672 (org-outline-regexp
6673 (if (not (derived-mode-p 'org-mode))
6674 outline-regexp
6675 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6676 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6677 (not (looking-at org-outline-regexp))))
6678 (org-cycle-hook
6679 (if bob-special
6680 (delq 'org-optimize-window-after-visibility-change
6681 (copy-sequence org-cycle-hook))
6682 org-cycle-hook))
6683 (pos (point)))
6685 (cond
6687 ((equal arg '(16))
6688 (setq last-command 'dummy)
6689 (org-set-startup-visibility)
6690 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6692 ((equal arg '(64))
6693 (outline-show-all)
6694 (org-unlogged-message "Entire buffer visible, including drawers"))
6696 ((equal arg '(4)) (org-cycle-internal-global))
6698 ;; Try hiding block at point.
6699 ((org-hide-block-toggle-maybe))
6701 ;; Try cdlatex TAB completion
6702 ((org-try-cdlatex-tab))
6704 ;; Table: enter it or move to the next field.
6705 ((org-at-table-p 'any)
6706 (if (org-at-table.el-p)
6707 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6708 Use `\\[org-edit-special]' to edit table.el tables"))
6709 (if arg (org-table-edit-field t)
6710 (org-table-justify-field-maybe)
6711 (call-interactively 'org-table-next-field))))
6713 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6715 ;; Global cycling: delegate to `org-cycle-internal-global'.
6716 (bob-special (org-cycle-internal-global))
6718 ;; Drawers: delegate to `org-flag-drawer'.
6719 ((save-excursion
6720 (beginning-of-line 1)
6721 (looking-at org-drawer-regexp))
6722 (org-flag-drawer ; toggle block visibility
6723 (not (get-char-property (match-end 0) 'invisible))))
6725 ;; Show-subtree, ARG levels up from here.
6726 ((integerp arg)
6727 (save-excursion
6728 (org-back-to-heading)
6729 (outline-up-heading (if (< arg 0) (- arg)
6730 (- (funcall outline-level) arg)))
6731 (org-show-subtree)))
6733 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6734 ((and (featurep 'org-inlinetask)
6735 (org-inlinetask-at-task-p)
6736 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6737 (org-inlinetask-toggle-visibility))
6739 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6740 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6741 (save-excursion (move-beginning-of-line 1)
6742 (looking-at org-outline-regexp)))
6743 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6744 (org-cycle-internal-local))
6746 ;; From there: TAB emulation and template completion.
6747 (buffer-read-only (org-back-to-heading))
6749 ((run-hook-with-args-until-success
6750 'org-tab-after-check-for-cycling-hook))
6752 ((run-hook-with-args-until-success
6753 'org-tab-before-tab-emulation-hook))
6755 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6756 (or (not (bolp))
6757 (not (looking-at org-outline-regexp))))
6758 (call-interactively (global-key-binding "\t")))
6760 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6761 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6762 (or (and (eq org-cycle-emulate-tab 'white)
6763 (= (match-end 0) (point-at-eol)))
6764 (and (eq org-cycle-emulate-tab 'whitestart)
6765 (>= (match-end 0) pos))))
6767 (eq org-cycle-emulate-tab t))
6768 (call-interactively (global-key-binding "\t")))
6770 (t (save-excursion
6771 (org-back-to-heading)
6772 (org-cycle)))))))
6774 (defun org-cycle-internal-global ()
6775 "Do the global cycling action."
6776 ;; Hack to avoid display of messages for .org attachments in Gnus
6777 (let ((ga (string-match "\\*fontification" (buffer-name))))
6778 (cond
6779 ((and (eq last-command this-command)
6780 (eq org-cycle-global-status 'overview))
6781 ;; We just created the overview - now do table of contents
6782 ;; This can be slow in very large buffers, so indicate action
6783 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6784 (unless ga (org-unlogged-message "CONTENTS..."))
6785 (org-content)
6786 (unless ga (org-unlogged-message "CONTENTS...done"))
6787 (setq org-cycle-global-status 'contents)
6788 (run-hook-with-args 'org-cycle-hook 'contents))
6790 ((and (eq last-command this-command)
6791 (eq org-cycle-global-status 'contents))
6792 ;; We just showed the table of contents - now show everything
6793 (run-hook-with-args 'org-pre-cycle-hook 'all)
6794 (outline-show-all)
6795 (unless ga (org-unlogged-message "SHOW ALL"))
6796 (setq org-cycle-global-status 'all)
6797 (run-hook-with-args 'org-cycle-hook 'all))
6800 ;; Default action: go to overview
6801 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6802 (org-overview)
6803 (unless ga (org-unlogged-message "OVERVIEW"))
6804 (setq org-cycle-global-status 'overview)
6805 (run-hook-with-args 'org-cycle-hook 'overview)))))
6807 (defvar org-called-with-limited-levels nil
6808 "Non-nil when `org-with-limited-levels' is currently active.")
6810 (defun org-cycle-internal-local ()
6811 "Do the local cycling action."
6812 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6813 ;; First, determine end of headline (EOH), end of subtree or item
6814 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6815 (save-excursion
6816 (if (org-at-item-p)
6817 (progn
6818 (beginning-of-line)
6819 (setq struct (org-list-struct))
6820 (setq eoh (point-at-eol))
6821 (setq eos (org-list-get-item-end-before-blank (point) struct))
6822 (setq has-children (org-list-has-child-p (point) struct)))
6823 (org-back-to-heading)
6824 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6825 (setq eos (save-excursion (org-end-of-subtree t t)
6826 (when (bolp) (backward-char)) (point)))
6827 (setq has-children
6828 (or (save-excursion
6829 (let ((level (funcall outline-level)))
6830 (outline-next-heading)
6831 (and (org-at-heading-p t)
6832 (> (funcall outline-level) level))))
6833 (save-excursion
6834 (org-list-search-forward (org-item-beginning-re) eos t)))))
6835 ;; Determine end invisible part of buffer (EOL)
6836 (beginning-of-line 2)
6837 (while (and (not (eobp)) ;This is like `next-line'.
6838 (get-char-property (1- (point)) 'invisible))
6839 (goto-char (next-single-char-property-change (point) 'invisible))
6840 (and (eolp) (beginning-of-line 2)))
6841 (setq eol (point)))
6842 ;; Find out what to do next and set `this-command'
6843 (cond
6844 ((= eos eoh)
6845 ;; Nothing is hidden behind this heading
6846 (unless (org-before-first-heading-p)
6847 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6848 (org-unlogged-message "EMPTY ENTRY")
6849 (setq org-cycle-subtree-status nil)
6850 (save-excursion
6851 (goto-char eos)
6852 (outline-next-heading)
6853 (when (org-invisible-p) (org-flag-heading nil))))
6854 ((and (or (>= eol eos)
6855 (not (string-match "\\S-" (buffer-substring eol eos))))
6856 (or has-children
6857 (not (setq children-skipped
6858 org-cycle-skip-children-state-if-no-children))))
6859 ;; Entire subtree is hidden in one line: children view
6860 (unless (org-before-first-heading-p)
6861 (run-hook-with-args 'org-pre-cycle-hook 'children))
6862 (if (org-at-item-p)
6863 (org-list-set-item-visibility (point-at-bol) struct 'children)
6864 (org-show-entry)
6865 (org-with-limited-levels (org-show-children))
6866 (org-show-set-visibility 'canonical)
6867 ;; FIXME: This slows down the func way too much.
6868 ;; How keep drawers hidden in subtree anyway?
6869 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6870 ;; (org-cycle-hide-drawers 'subtree))
6872 ;; Fold every list in subtree to top-level items.
6873 (when (eq org-cycle-include-plain-lists 'integrate)
6874 (save-excursion
6875 (org-back-to-heading)
6876 (while (org-list-search-forward (org-item-beginning-re) eos t)
6877 (beginning-of-line 1)
6878 (let* ((struct (org-list-struct))
6879 (prevs (org-list-prevs-alist struct))
6880 (end (org-list-get-bottom-point struct)))
6881 (dolist (e (org-list-get-all-items (point) struct prevs))
6882 (org-list-set-item-visibility e struct 'folded))
6883 (goto-char (if (< end eos) end eos)))))))
6884 (org-unlogged-message "CHILDREN")
6885 (save-excursion
6886 (goto-char eos)
6887 (outline-next-heading)
6888 (when (org-invisible-p) (org-flag-heading nil)))
6889 (setq org-cycle-subtree-status 'children)
6890 (unless (org-before-first-heading-p)
6891 (run-hook-with-args 'org-cycle-hook 'children)))
6892 ((or children-skipped
6893 (and (eq last-command this-command)
6894 (eq org-cycle-subtree-status 'children)))
6895 ;; We just showed the children, or no children are there,
6896 ;; now show everything.
6897 (unless (org-before-first-heading-p)
6898 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6899 (outline-flag-region eoh eos nil)
6900 (org-unlogged-message
6901 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6902 (setq org-cycle-subtree-status 'subtree)
6903 (unless (org-before-first-heading-p)
6904 (run-hook-with-args 'org-cycle-hook 'subtree)))
6906 ;; Default action: hide the subtree.
6907 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6908 (outline-flag-region eoh eos t)
6909 (org-unlogged-message "FOLDED")
6910 (setq org-cycle-subtree-status 'folded)
6911 (unless (org-before-first-heading-p)
6912 (run-hook-with-args 'org-cycle-hook 'folded))))))
6914 ;;;###autoload
6915 (defun org-global-cycle (&optional arg)
6916 "Cycle the global visibility. For details see `org-cycle'.
6917 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6918 With a numeric prefix, show all headlines up to that level."
6919 (interactive "P")
6920 (let ((org-cycle-include-plain-lists
6921 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6922 (cond
6923 ((integerp arg)
6924 (outline-show-all)
6925 (outline-hide-sublevels arg)
6926 (setq org-cycle-global-status 'contents))
6927 ((equal arg '(4))
6928 (org-set-startup-visibility)
6929 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6931 (org-cycle '(4))))))
6933 (defun org-set-startup-visibility ()
6934 "Set the visibility required by startup options and properties."
6935 (cond
6936 ((eq org-startup-folded t)
6937 (org-overview))
6938 ((eq org-startup-folded 'content)
6939 (org-content))
6940 ((or (eq org-startup-folded 'showeverything)
6941 (eq org-startup-folded nil))
6942 (outline-show-all)))
6943 (unless (eq org-startup-folded 'showeverything)
6944 (when org-hide-block-startup (org-hide-block-all))
6945 (org-set-visibility-according-to-property 'no-cleanup)
6946 (org-cycle-hide-archived-subtrees 'all)
6947 (org-cycle-hide-drawers 'all)
6948 (org-cycle-show-empty-lines t)))
6950 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6951 "Switch subtree visibilities according to :VISIBILITY: property."
6952 (interactive)
6953 (org-with-wide-buffer
6954 (goto-char (point-min))
6955 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6956 (if (not (org-at-property-p)) (outline-next-heading)
6957 (let ((state (match-string 3)))
6958 (save-excursion
6959 (org-back-to-heading t)
6960 (outline-hide-subtree)
6961 (org-reveal)
6962 (cond
6963 ((equal state "folded")
6964 (outline-hide-subtree))
6965 ((equal state "children")
6966 (org-show-hidden-entry)
6967 (org-show-children))
6968 ((equal state "content")
6969 (save-excursion
6970 (save-restriction
6971 (org-narrow-to-subtree)
6972 (org-content))))
6973 ((member state '("all" "showall"))
6974 (outline-show-subtree)))))))
6975 (unless no-cleanup
6976 (org-cycle-hide-archived-subtrees 'all)
6977 (org-cycle-hide-drawers 'all)
6978 (org-cycle-show-empty-lines 'all))))
6980 ;; This function uses outline-regexp instead of the more fundamental
6981 ;; org-outline-regexp so that org-cycle-global works outside of Org
6982 ;; buffers, where outline-regexp is needed.
6983 (defun org-overview ()
6984 "Switch to overview mode, showing only top-level headlines.
6985 This shows all headlines with a level equal or greater than the level
6986 of the first headline in the buffer. This is important, because if the
6987 first headline is not level one, then (hide-sublevels 1) gives confusing
6988 results."
6989 (interactive)
6990 (save-excursion
6991 (let ((level
6992 (save-excursion
6993 (goto-char (point-min))
6994 (when (re-search-forward (concat "^" outline-regexp) nil t)
6995 (goto-char (match-beginning 0))
6996 (funcall outline-level)))))
6997 (and level (outline-hide-sublevels level)))))
6999 (defun org-content (&optional arg)
7000 "Show all headlines in the buffer, like a table of contents.
7001 With numerical argument N, show content up to level N."
7002 (interactive "P")
7003 (org-overview)
7004 (save-excursion
7005 ;; Visit all headings and show their offspring
7006 (and (integerp arg) (org-overview))
7007 (goto-char (point-max))
7008 (catch 'exit
7009 (while (and (progn (condition-case nil
7010 (outline-previous-visible-heading 1)
7011 (error (goto-char (point-min))))
7013 (looking-at org-outline-regexp))
7014 (if (integerp arg)
7015 (org-show-children (1- arg))
7016 (outline-show-branches))
7017 (when (bobp) (throw 'exit nil))))))
7019 (defun org-optimize-window-after-visibility-change (state)
7020 "Adjust the window after a change in outline visibility.
7021 This function is the default value of the hook `org-cycle-hook'."
7022 (when (get-buffer-window (current-buffer))
7023 (cond
7024 ((eq state 'content) nil)
7025 ((eq state 'all) nil)
7026 ((eq state 'folded) nil)
7027 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7028 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7030 (defun org-remove-empty-overlays-at (pos)
7031 "Remove outline overlays that do not contain non-white stuff."
7032 (dolist (o (overlays-at pos))
7033 (and (eq 'outline (overlay-get o 'invisible))
7034 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7035 (overlay-end o))))
7036 (delete-overlay o))))
7038 (defun org-clean-visibility-after-subtree-move ()
7039 "Fix visibility issues after moving a subtree."
7040 ;; First, find a reasonable region to look at:
7041 ;; Start two siblings above, end three below
7042 (let* ((beg (save-excursion
7043 (and (org-get-last-sibling)
7044 (org-get-last-sibling))
7045 (point)))
7046 (end (save-excursion
7047 (and (org-get-next-sibling)
7048 (org-get-next-sibling)
7049 (org-get-next-sibling))
7050 (if (org-at-heading-p)
7051 (point-at-eol)
7052 (point))))
7053 (level (looking-at "\\*+"))
7054 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7055 (save-excursion
7056 (save-restriction
7057 (narrow-to-region beg end)
7058 (when re
7059 ;; Properly fold already folded siblings
7060 (goto-char (point-min))
7061 (while (re-search-forward re nil t)
7062 (when (and (not (org-invisible-p))
7063 (save-excursion
7064 (goto-char (point-at-eol)) (org-invisible-p)))
7065 (outline-hide-entry))))
7066 (org-cycle-show-empty-lines 'overview)
7067 (org-cycle-hide-drawers 'overview)))))
7069 (defun org-cycle-show-empty-lines (state)
7070 "Show empty lines above all visible headlines.
7071 The region to be covered depends on STATE when called through
7072 `org-cycle-hook'. Lisp program can use t for STATE to get the
7073 entire buffer covered. Note that an empty line is only shown if there
7074 are at least `org-cycle-separator-lines' empty lines before the headline."
7075 (when (/= org-cycle-separator-lines 0)
7076 (save-excursion
7077 (let* ((n (abs org-cycle-separator-lines))
7078 (re (cond
7079 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7080 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7081 (t (let ((ns (number-to-string (- n 2))))
7082 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7083 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7084 beg end)
7085 (cond
7086 ((memq state '(overview contents t))
7087 (setq beg (point-min) end (point-max)))
7088 ((memq state '(children folded))
7089 (setq beg (point)
7090 end (progn (org-end-of-subtree t t)
7091 (line-beginning-position 2)))))
7092 (when beg
7093 (goto-char beg)
7094 (while (re-search-forward re end t)
7095 (unless (get-char-property (match-end 1) 'invisible)
7096 (let ((e (match-end 1))
7097 (b (if (>= org-cycle-separator-lines 0)
7098 (match-beginning 1)
7099 (save-excursion
7100 (goto-char (match-beginning 0))
7101 (skip-chars-backward " \t\n")
7102 (line-end-position)))))
7103 (outline-flag-region b e nil))))))))
7104 ;; Never hide empty lines at the end of the file.
7105 (save-excursion
7106 (goto-char (point-max))
7107 (outline-previous-heading)
7108 (outline-end-of-heading)
7109 (when (and (looking-at "[ \t\n]+")
7110 (= (match-end 0) (point-max)))
7111 (outline-flag-region (point) (match-end 0) nil))))
7113 (defun org-show-empty-lines-in-parent ()
7114 "Move to the parent and re-show empty lines before visible headlines."
7115 (save-excursion
7116 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7117 (org-cycle-show-empty-lines context))))
7119 (defun org-files-list ()
7120 "Return `org-agenda-files' list, plus all open Org files.
7121 This is useful for operations that need to scan all of a user's
7122 open and agenda-wise Org files."
7123 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
7124 (dolist (buf (buffer-list))
7125 (with-current-buffer buf
7126 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7127 (cl-pushnew (expand-file-name (buffer-file-name)) files
7128 :test #'equal))))
7129 files))
7131 (defsubst org-entry-beginning-position ()
7132 "Return the beginning position of the current entry."
7133 (save-excursion (org-back-to-heading t) (point)))
7135 (defsubst org-entry-end-position ()
7136 "Return the end position of the current entry."
7137 (save-excursion (outline-next-heading) (point)))
7139 (defun org-cycle-hide-drawers (state &optional exceptions)
7140 "Re-hide all drawers after a visibility state change.
7141 STATE should be one of the symbols listed in the docstring of
7142 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7143 a list of strings specifying which drawers should not be hidden."
7144 (when (and (derived-mode-p 'org-mode)
7145 (not (memq state '(overview folded contents))))
7146 (save-excursion
7147 (let* ((globalp (eq state 'all))
7148 (beg (if globalp (point-min) (point)))
7149 (end (if globalp (point-max)
7150 (if (eq state 'children)
7151 (save-excursion (outline-next-heading) (point))
7152 (org-end-of-subtree t)))))
7153 (goto-char beg)
7154 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7155 (unless (member-ignore-case (match-string 1) exceptions)
7156 (let ((drawer (org-element-at-point)))
7157 (when (memq (org-element-type drawer) '(drawer property-drawer))
7158 (org-flag-drawer t drawer)
7159 ;; Make sure to skip drawer entirely or we might flag
7160 ;; it another time when matching its ending line with
7161 ;; `org-drawer-regexp'.
7162 (goto-char (org-element-property :end drawer))))))))))
7164 (defun org-flag-drawer (flag &optional element)
7165 "When FLAG is non-nil, hide the drawer we are at.
7166 Otherwise make it visible. When optional argument ELEMENT is
7167 a parsed drawer, as returned by `org-element-at-point', hide or
7168 show that drawer instead."
7169 (let ((drawer (or element
7170 (and (save-excursion
7171 (beginning-of-line)
7172 (looking-at-p org-drawer-regexp))
7173 (org-element-at-point)))))
7174 (when (memq (org-element-type drawer) '(drawer property-drawer))
7175 (let ((post (org-element-property :post-affiliated drawer)))
7176 (save-excursion
7177 (outline-flag-region
7178 (progn (goto-char post) (line-end-position))
7179 (progn (goto-char (org-element-property :end drawer))
7180 (skip-chars-backward " \r\t\n")
7181 (line-end-position))
7182 flag))
7183 ;; When the drawer is hidden away, make sure point lies in
7184 ;; a visible part of the buffer.
7185 (when (and flag (> (line-beginning-position) post))
7186 (goto-char post))))))
7188 (defun org-subtree-end-visible-p ()
7189 "Is the end of the current subtree visible?"
7190 (pos-visible-in-window-p
7191 (save-excursion (org-end-of-subtree t) (point))))
7193 (defun org-first-headline-recenter ()
7194 "Move cursor to the first headline and recenter the headline."
7195 (let ((window (get-buffer-window)))
7196 (when window
7197 (goto-char (point-min))
7198 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7199 (set-window-start window (line-beginning-position))))))
7201 ;;; Saving and restoring visibility
7203 (defun org-outline-overlay-data (&optional use-markers)
7204 "Return a list of the locations of all outline overlays.
7205 These are overlays with the `invisible' property value `outline'.
7206 The return value is a list of cons cells, with start and stop
7207 positions for each overlay.
7208 If USE-MARKERS is set, return the positions as markers."
7209 (let (beg end)
7210 (org-with-wide-buffer
7211 (delq nil
7212 (mapcar (lambda (o)
7213 (when (eq (overlay-get o 'invisible) 'outline)
7214 (setq beg (overlay-start o)
7215 end (overlay-end o))
7216 (and beg end (> end beg)
7217 (if use-markers
7218 (cons (copy-marker beg)
7219 (copy-marker end t))
7220 (cons beg end)))))
7221 (overlays-in (point-min) (point-max)))))))
7223 (defun org-set-outline-overlay-data (data)
7224 "Create visibility overlays for all positions in DATA.
7225 DATA should have been made by `org-outline-overlay-data'."
7226 (org-with-wide-buffer
7227 (outline-show-all)
7228 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7230 ;;; Folding of blocks
7232 (defvar-local org-hide-block-overlays nil
7233 "Overlays hiding blocks.")
7235 (defun org-block-map (function &optional start end)
7236 "Call FUNCTION at the head of all source blocks in the current buffer.
7237 Optional arguments START and END can be used to limit the range."
7238 (let ((start (or start (point-min)))
7239 (end (or end (point-max))))
7240 (save-excursion
7241 (goto-char start)
7242 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7243 (save-excursion
7244 (save-match-data
7245 (goto-char (match-beginning 0))
7246 (funcall function)))))))
7248 (defun org-hide-block-toggle-all ()
7249 "Toggle the visibility of all blocks in the current buffer."
7250 (org-block-map 'org-hide-block-toggle))
7252 (defun org-hide-block-all ()
7253 "Fold all blocks in the current buffer."
7254 (interactive)
7255 (org-show-block-all)
7256 (org-block-map 'org-hide-block-toggle-maybe))
7258 (defun org-show-block-all ()
7259 "Unfold all blocks in the current buffer."
7260 (interactive)
7261 (mapc #'delete-overlay org-hide-block-overlays)
7262 (setq org-hide-block-overlays nil))
7264 (defun org-hide-block-toggle-maybe ()
7265 "Toggle visibility of block at point.
7266 Unlike to `org-hide-block-toggle', this function does not throw
7267 an error. Return a non-nil value when toggling is successful."
7268 (interactive)
7269 (ignore-errors (org-hide-block-toggle)))
7271 (defun org-hide-block-toggle (&optional force)
7272 "Toggle the visibility of the current block.
7273 When optional argument FORCE is `off', make block visible. If it
7274 is non-nil, hide it unconditionally. Throw an error when not at
7275 a block. Return a non-nil value when toggling is successful."
7276 (interactive)
7277 (let ((element (org-element-at-point)))
7278 (unless (memq (org-element-type element)
7279 '(center-block comment-block dynamic-block example-block
7280 export-block quote-block special-block
7281 src-block verse-block))
7282 (user-error "Not at a block"))
7283 (let* ((start (save-excursion
7284 (goto-char (org-element-property :post-affiliated element))
7285 (line-end-position)))
7286 (end (save-excursion
7287 (goto-char (org-element-property :end element))
7288 (skip-chars-backward " \r\t\n")
7289 (line-end-position)))
7290 (overlays (overlays-at start)))
7291 (cond
7292 ;; Do nothing when not before or at the block opening line or
7293 ;; at the block closing line.
7294 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7295 ((and (not (eq force 'off))
7296 (not (memq t (mapcar
7297 (lambda (o)
7298 (eq (overlay-get o 'invisible) 'org-hide-block))
7299 overlays))))
7300 (let ((ov (make-overlay start end)))
7301 (overlay-put ov 'invisible 'org-hide-block)
7302 ;; Make the block accessible to `isearch'.
7303 (overlay-put
7304 ov 'isearch-open-invisible
7305 (lambda (ov)
7306 (when (memq ov org-hide-block-overlays)
7307 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7308 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7309 (delete-overlay ov))))
7310 (push ov org-hide-block-overlays)
7311 ;; When the block is hidden away, make sure point is left in
7312 ;; a visible part of the buffer.
7313 (when (> (line-beginning-position) start)
7314 (goto-char start)
7315 (beginning-of-line))
7316 ;; Signal successful toggling.
7318 ((or (not force) (eq force 'off))
7319 (dolist (ov overlays t)
7320 (when (memq ov org-hide-block-overlays)
7321 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7322 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7323 (delete-overlay ov))))))))
7325 ;; Remove overlays when changing major mode
7326 (add-hook 'org-mode-hook
7327 (lambda () (add-hook 'change-major-mode-hook
7328 'org-show-block-all 'append 'local)))
7330 ;;; Indirect buffer display of subtrees
7332 (defvar org-indirect-dedicated-frame nil
7333 "This is the frame being used for indirect tree display.")
7334 (defvar org-last-indirect-buffer nil)
7336 (defun org-tree-to-indirect-buffer (&optional arg)
7337 "Create indirect buffer and narrow it to current subtree.
7339 With a numerical prefix ARG, go up to this level and then take that tree.
7340 If ARG is negative, go up that many levels.
7342 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7343 indirect buffer previously made with this command, to avoid proliferation of
7344 indirect buffers. However, when you call the command with a \
7345 `\\[universal-argument]' prefix, or
7346 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7347 so that you can work with several indirect buffers at the same time. If
7348 `org-indirect-buffer-display' is `dedicated-frame', the \
7349 `\\[universal-argument]' prefix also
7350 requests that a new frame be made for the new buffer, so that the dedicated
7351 frame is not changed."
7352 (interactive "P")
7353 (let ((cbuf (current-buffer))
7354 (cwin (selected-window))
7355 (pos (point))
7356 beg end level heading ibuf)
7357 (save-excursion
7358 (org-back-to-heading t)
7359 (when (numberp arg)
7360 (setq level (org-outline-level))
7361 (when (< arg 0) (setq arg (+ level arg)))
7362 (while (> (setq level (org-outline-level)) arg)
7363 (org-up-heading-safe)))
7364 (setq beg (point)
7365 heading (org-get-heading 'no-tags))
7366 (org-end-of-subtree t t)
7367 (when (org-at-heading-p) (backward-char 1))
7368 (setq end (point)))
7369 (when (and (buffer-live-p org-last-indirect-buffer)
7370 (not (eq org-indirect-buffer-display 'new-frame))
7371 (not arg))
7372 (kill-buffer org-last-indirect-buffer))
7373 (setq ibuf (org-get-indirect-buffer cbuf heading)
7374 org-last-indirect-buffer ibuf)
7375 (cond
7376 ((or (eq org-indirect-buffer-display 'new-frame)
7377 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7378 (select-frame (make-frame))
7379 (delete-other-windows)
7380 (pop-to-buffer-same-window ibuf)
7381 (org-set-frame-title heading))
7382 ((eq org-indirect-buffer-display 'dedicated-frame)
7383 (raise-frame
7384 (select-frame (or (and org-indirect-dedicated-frame
7385 (frame-live-p org-indirect-dedicated-frame)
7386 org-indirect-dedicated-frame)
7387 (setq org-indirect-dedicated-frame (make-frame)))))
7388 (delete-other-windows)
7389 (pop-to-buffer-same-window ibuf)
7390 (org-set-frame-title (concat "Indirect: " heading)))
7391 ((eq org-indirect-buffer-display 'current-window)
7392 (pop-to-buffer-same-window ibuf))
7393 ((eq org-indirect-buffer-display 'other-window)
7394 (pop-to-buffer ibuf))
7395 (t (error "Invalid value")))
7396 (narrow-to-region beg end)
7397 (outline-show-all)
7398 (goto-char pos)
7399 (run-hook-with-args 'org-cycle-hook 'all)
7400 (and (window-live-p cwin) (select-window cwin))))
7402 (defun org-get-indirect-buffer (&optional buffer heading)
7403 (setq buffer (or buffer (current-buffer)))
7404 (let ((n 1) (base (buffer-name buffer)) bname)
7405 (while (buffer-live-p
7406 (get-buffer
7407 (setq bname
7408 (concat base "-"
7409 (if heading (concat heading "-" (number-to-string n))
7410 (number-to-string n))))))
7411 (setq n (1+ n)))
7412 (condition-case nil
7413 (make-indirect-buffer buffer bname 'clone)
7414 (error (make-indirect-buffer buffer bname)))))
7416 (defun org-set-frame-title (title)
7417 "Set the title of the current frame to the string TITLE."
7418 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7420 ;;;; Structure editing
7422 ;;; Inserting headlines
7424 (defun org--line-empty-p (n)
7425 "Is the Nth next line empty?
7427 Counts the current line as N = 1 and the previous line as N = 0;
7428 see `beginning-of-line'."
7429 (save-excursion
7430 (and (not (bobp))
7431 (or (beginning-of-line n) t)
7432 (save-match-data
7433 (looking-at "[ \t]*$")))))
7435 (defun org-previous-line-empty-p ()
7436 "Is the previous line a blank line?
7437 When NEXT is non-nil, check the next line instead."
7438 (org--line-empty-p 0))
7440 (defun org-next-line-empty-p ()
7441 "Is the previous line a blank line?
7442 When NEXT is non-nil, check the next line instead."
7443 (org--line-empty-p 2))
7445 (defun org--blank-before-heading-p (&optional parent)
7446 "Non-nil when an empty line should precede a new heading here.
7447 When optional argument PARENT is non-nil, consider parent
7448 headline instead of current one."
7449 (pcase (assq 'heading org-blank-before-new-entry)
7450 (`(heading . auto)
7451 (save-excursion
7452 (org-with-limited-levels
7453 (unless (and (org-before-first-heading-p)
7454 (not (outline-next-heading)))
7455 (org-back-to-heading t)
7456 (when parent (org-up-heading-safe))
7457 (cond ((not (bobp))
7458 (org-previous-line-empty-p))
7459 ((outline-next-heading)
7460 (org-previous-line-empty-p))
7461 ;; Ignore trailing spaces on last buffer line.
7462 ((progn (skip-chars-backward " \t") (bolp))
7463 (org-previous-line-empty-p))
7464 (t nil))))))
7465 (`(heading . ,value) value)
7466 (_ nil)))
7468 (defun org-insert-heading (&optional arg invisible-ok top)
7469 "Insert a new heading or an item with the same depth at point.
7471 If point is at the beginning of a heading, insert a new heading
7472 or a new headline above the current one. When at the beginning
7473 of a regular line of text, turn it into a heading.
7475 If point is in the middle of a line, split it and create a new
7476 headline with the text in the current line after point (see
7477 `org-M-RET-may-split-line' on how to modify this behavior). As
7478 a special case, on a headline, splitting can only happen on the
7479 title itself. E.g., this excludes breaking stars or tags.
7481 With a `\\[universal-argument]' prefix, set \
7482 `org-insert-heading-respect-content' to
7483 a non-nil value for the duration of the command. This forces the
7484 insertion of a heading after the current subtree, independently
7485 on the location of point.
7487 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7488 insert the heading at the end of the tree
7489 above the current heading. For example, if point is within a
7490 2nd-level heading, then it will insert a 2nd-level heading at
7491 the end of the 1st-level parent subtree.
7493 When INVISIBLE-OK is set, stop at invisible headlines when going
7494 back. This is important for non-interactive uses of the
7495 command.
7497 When optional argument TOP is non-nil, insert a level 1 heading,
7498 unconditionally."
7499 (interactive "P")
7500 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7501 (level (org-current-level))
7502 (stars (make-string (if (and level (not top)) level 1) ?*)))
7503 (cond
7504 ((or org-insert-heading-respect-content
7505 (member arg '((4) (16)))
7506 (and (not invisible-ok)
7507 (invisible-p (max (1- (point)) (point-min)))))
7508 ;; Position point at the location of insertion.
7509 (if (not level) ;before first headline
7510 (org-with-limited-levels (outline-next-heading))
7511 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7512 ;; is nil.
7513 (org-with-limited-levels (org-back-to-heading invisible-ok))
7514 (cond ((equal arg '(16))
7515 (org-up-heading-safe)
7516 (org-end-of-subtree t t))
7518 (org-end-of-subtree t t))))
7519 (unless (bolp) (insert "\n")) ;ensure final newline
7520 (unless (and blank? (org-previous-line-empty-p))
7521 (org-N-empty-lines-before-current (if blank? 1 0)))
7522 (insert stars " \n")
7523 (forward-char -1))
7524 ;; At a headline...
7525 ((org-at-heading-p)
7526 (cond ((bolp)
7527 (when blank? (save-excursion (insert "\n")))
7528 (save-excursion (insert stars " \n"))
7529 (unless (and blank? (org-previous-line-empty-p))
7530 (org-N-empty-lines-before-current (if blank? 1 0)))
7531 (end-of-line))
7532 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7533 (org-match-line org-complex-heading-regexp)
7534 (org-pos-in-match-range (point) 4))
7535 ;; Grab the text that should moved to the new headline.
7536 ;; Preserve tags.
7537 (let ((split (delete-and-extract-region (point) (match-end 4))))
7538 (if (looking-at "[ \t]*$") (replace-match "")
7539 (org-set-tags nil t))
7540 (end-of-line)
7541 (when blank? (insert "\n"))
7542 (insert "\n" stars " ")
7543 (when (org-string-nw-p split) (insert split))
7544 (when (eobp) (save-excursion (insert "\n")))))
7546 (end-of-line)
7547 (when blank? (insert "\n"))
7548 (insert "\n" stars " ")
7549 (when (eobp) (save-excursion (insert "\n"))))))
7550 ;; On regular text, turn line into a headline or split, if
7551 ;; appropriate.
7552 ((bolp)
7553 (insert stars " ")
7554 (unless (and blank? (org-previous-line-empty-p))
7555 (org-N-empty-lines-before-current (if blank? 1 0))))
7557 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7558 (end-of-line))
7559 (insert "\n" stars " ")
7560 (unless (and blank? (org-previous-line-empty-p))
7561 (org-N-empty-lines-before-current (if blank? 1 0))))))
7562 (run-hooks 'org-insert-heading-hook))
7564 (defun org-N-empty-lines-before-current (n)
7565 "Make the number of empty lines before current exactly N.
7566 So this will delete or add empty lines."
7567 (let ((column (current-column)))
7568 (beginning-of-line)
7569 (unless (bobp)
7570 (let ((start (save-excursion
7571 (skip-chars-backward " \r\t\n")
7572 (line-end-position))))
7573 (delete-region start (line-end-position 0))))
7574 (insert (make-string n ?\n))
7575 (move-to-column column)))
7577 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7578 "Return the heading of the current entry, without the stars.
7579 When NO-TAGS is non-nil, don't include tags.
7580 When NO-TODO is non-nil, don't include TODO keywords.
7581 When NO-PRIORITY is non-nil, don't include priority cookie.
7582 When NO-COMMENT is non-nil, don't include COMMENT string."
7583 (save-excursion
7584 (org-back-to-heading t)
7585 (let ((case-fold-search nil))
7586 (looking-at org-complex-heading-regexp)
7587 (let ((todo (and (not no-todo) (match-string 2)))
7588 (priority (and (not no-priority) (match-string 3)))
7589 (headline (pcase (match-string 4)
7590 (`nil "")
7591 ((and (guard no-comment) h)
7592 (replace-regexp-in-string
7593 (eval-when-compile
7594 (format "\\`%s[ \t]+" org-comment-string))
7595 "" h))
7596 (h h)))
7597 (tags (and (not no-tags) (match-string 5))))
7598 (mapconcat #'identity
7599 (delq nil (list todo priority headline tags))
7600 " ")))))
7602 (defvar orgstruct-mode) ; defined below
7604 (defun org-heading-components ()
7605 "Return the components of the current heading.
7606 This is a list with the following elements:
7607 - the level as an integer
7608 - the reduced level, different if `org-odd-levels-only' is set.
7609 - the TODO keyword, or nil
7610 - the priority character, like ?A, or nil if no priority is given
7611 - the headline text itself, or the tags string if no headline text
7612 - the tags string, or nil."
7613 (save-excursion
7614 (org-back-to-heading t)
7615 (when (let (case-fold-search)
7616 (looking-at
7617 (if orgstruct-mode
7618 org-heading-regexp
7619 org-complex-heading-regexp)))
7620 (if orgstruct-mode
7621 (list (length (match-string 1))
7622 (org-reduced-level (length (match-string 1)))
7625 (match-string 2)
7626 nil)
7627 (list (length (match-string 1))
7628 (org-reduced-level (length (match-string 1)))
7629 (match-string-no-properties 2)
7630 (and (match-end 3) (aref (match-string 3) 2))
7631 (match-string-no-properties 4)
7632 (match-string-no-properties 5))))))
7634 (defun org-get-entry ()
7635 "Get the entry text, after heading, entire subtree."
7636 (save-excursion
7637 (org-back-to-heading t)
7638 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7640 (defun org-edit-headline (&optional heading)
7641 "Edit the current headline.
7642 Set it to HEADING when provided."
7643 (interactive)
7644 (org-with-wide-buffer
7645 (org-back-to-heading t)
7646 (let ((case-fold-search nil))
7647 (when (looking-at org-complex-heading-regexp)
7648 (let* ((old (match-string-no-properties 4))
7649 (new (save-match-data
7650 (org-trim (or heading (read-string "Edit: " old))))))
7651 (unless (equal old new)
7652 (if old (replace-match new t t nil 4)
7653 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7654 (insert " " new))
7655 (org-set-tags nil t)
7656 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7658 (defun org-insert-heading-after-current ()
7659 "Insert a new heading with same level as current, after current subtree."
7660 (interactive)
7661 (org-back-to-heading)
7662 (org-insert-heading)
7663 (org-move-subtree-down)
7664 (end-of-line 1))
7666 (defun org-insert-heading-respect-content (&optional invisible-ok)
7667 "Insert heading with `org-insert-heading-respect-content' set to t."
7668 (interactive)
7669 (org-insert-heading '(4) invisible-ok))
7671 (defun org-insert-todo-heading-respect-content (&optional force-state)
7672 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7673 (interactive)
7674 (org-insert-todo-heading force-state '(4)))
7676 (defun org-insert-todo-heading (arg &optional force-heading)
7677 "Insert a new heading with the same level and TODO state as current heading.
7679 If the heading has no TODO state, or if the state is DONE, use
7680 the first state (TODO by default). Also with one prefix arg,
7681 force first state. With two prefix args, force inserting at the
7682 end of the parent subtree.
7684 When called at a plain list item, insert a new item with an
7685 unchecked check box."
7686 (interactive "P")
7687 (when (or force-heading (not (org-insert-item 'checkbox)))
7688 (org-insert-heading (or (and (equal arg '(16)) '(16))
7689 force-heading))
7690 (save-excursion
7691 (org-forward-heading-same-level -1)
7692 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7693 (let* ((new-mark-x
7694 (if (or (equal arg '(4))
7695 (not (match-beginning 2))
7696 (member (match-string 2) org-done-keywords))
7697 (car org-todo-keywords-1)
7698 (match-string 2)))
7699 (new-mark
7701 (run-hook-with-args-until-success
7702 'org-todo-get-default-hook new-mark-x nil)
7703 new-mark-x)))
7704 (beginning-of-line 1)
7705 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7706 (if org-treat-insert-todo-heading-as-state-change
7707 (org-todo new-mark)
7708 (insert new-mark " "))))
7709 (when org-provide-todo-statistics
7710 (org-update-parent-todo-statistics))))
7712 (defun org-insert-subheading (arg)
7713 "Insert a new subheading and demote it.
7714 Works for outline headings and for plain lists alike."
7715 (interactive "P")
7716 (org-insert-heading arg)
7717 (cond
7718 ((org-at-heading-p) (org-do-demote))
7719 ((org-at-item-p) (org-indent-item))))
7721 (defun org-insert-todo-subheading (arg)
7722 "Insert a new subheading with TODO keyword or checkbox and demote it.
7723 Works for outline headings and for plain lists alike."
7724 (interactive "P")
7725 (org-insert-todo-heading arg)
7726 (cond
7727 ((org-at-heading-p) (org-do-demote))
7728 ((org-at-item-p) (org-indent-item))))
7730 ;;; Promotion and Demotion
7732 (defvar org-after-demote-entry-hook nil
7733 "Hook run after an entry has been demoted.
7734 The cursor will be at the beginning of the entry.
7735 When a subtree is being demoted, the hook will be called for each node.")
7737 (defvar org-after-promote-entry-hook nil
7738 "Hook run after an entry has been promoted.
7739 The cursor will be at the beginning of the entry.
7740 When a subtree is being promoted, the hook will be called for each node.")
7742 (defun org-promote-subtree ()
7743 "Promote the entire subtree.
7744 See also `org-promote'."
7745 (interactive)
7746 (save-excursion
7747 (org-with-limited-levels (org-map-tree 'org-promote)))
7748 (org-fix-position-after-promote))
7750 (defun org-demote-subtree ()
7751 "Demote the entire subtree.
7752 See `org-demote' and `org-promote'."
7753 (interactive)
7754 (save-excursion
7755 (org-with-limited-levels (org-map-tree 'org-demote)))
7756 (org-fix-position-after-promote))
7758 (defun org-do-promote ()
7759 "Promote the current heading higher up the tree.
7760 If the region is active in `transient-mark-mode', promote all
7761 headings in the region."
7762 (interactive)
7763 (save-excursion
7764 (if (org-region-active-p)
7765 (org-map-region 'org-promote (region-beginning) (region-end))
7766 (org-promote)))
7767 (org-fix-position-after-promote))
7769 (defun org-do-demote ()
7770 "Demote the current heading lower down the tree.
7771 If the region is active in `transient-mark-mode', demote all
7772 headings in the region."
7773 (interactive)
7774 (save-excursion
7775 (if (org-region-active-p)
7776 (org-map-region 'org-demote (region-beginning) (region-end))
7777 (org-demote)))
7778 (org-fix-position-after-promote))
7780 (defun org-fix-position-after-promote ()
7781 "Fix cursor position and indentation after demoting/promoting."
7782 (let ((pos (point)))
7783 (when (save-excursion
7784 (beginning-of-line)
7785 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7786 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7787 (cond ((eobp) (insert " "))
7788 ((eolp) (insert " "))
7789 ((equal (char-after) ?\s) (forward-char 1))))))
7791 (defun org-current-level ()
7792 "Return the level of the current entry, or nil if before the first headline.
7793 The level is the number of stars at the beginning of the
7794 headline. Use `org-reduced-level' to remove the effect of
7795 `org-odd-levels'. Unlike to `org-outline-level', this function
7796 ignores inlinetasks."
7797 (let ((level (org-with-limited-levels (org-outline-level))))
7798 (and (> level 0) level)))
7800 (defun org-get-previous-line-level ()
7801 "Return the outline depth of the last headline before the current line.
7802 Returns 0 for the first headline in the buffer, and nil if before the
7803 first headline."
7804 (and (org-current-level)
7805 (or (and (/= (line-beginning-position) (point-min))
7806 (save-excursion (beginning-of-line 0) (org-current-level)))
7807 0)))
7809 (defun org-reduced-level (l)
7810 "Compute the effective level of a heading.
7811 This takes into account the setting of `org-odd-levels-only'."
7812 (cond
7813 ((zerop l) 0)
7814 (org-odd-levels-only (1+ (floor (/ l 2))))
7815 (t l)))
7817 (defun org-level-increment ()
7818 "Return the number of stars that will be added or removed at a
7819 time to headlines when structure editing, based on the value of
7820 `org-odd-levels-only'."
7821 (if org-odd-levels-only 2 1))
7823 (defun org-get-valid-level (level &optional change)
7824 "Rectify a level change under the influence of `org-odd-levels-only'.
7825 LEVEL is a current level, CHANGE is by how much the level should
7826 be modified. Even if CHANGE is nil, LEVEL may be returned
7827 modified because even level numbers will become the next higher
7828 odd number. Returns values greater than 0."
7829 (if org-odd-levels-only
7830 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7831 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7832 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7833 (max 1 (+ level (or change 0)))))
7835 (defun org-promote ()
7836 "Promote the current heading higher up the tree."
7837 (org-with-wide-buffer
7838 (org-back-to-heading t)
7839 (let* ((after-change-functions (remq 'flyspell-after-change-function
7840 after-change-functions))
7841 (level (save-match-data (funcall outline-level)))
7842 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7843 (diff (abs (- level (length up-head) -1))))
7844 (cond
7845 ((and (= level 1) org-allow-promoting-top-level-subtree)
7846 (replace-match "# " nil t))
7847 ((= level 1)
7848 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7849 (t (replace-match up-head nil t)))
7850 (unless (= level 1)
7851 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7852 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7853 (run-hooks 'org-after-promote-entry-hook))))
7855 (defun org-demote ()
7856 "Demote the current heading lower down the tree."
7857 (org-with-wide-buffer
7858 (org-back-to-heading t)
7859 (let* ((after-change-functions (remq 'flyspell-after-change-function
7860 after-change-functions))
7861 (level (save-match-data (funcall outline-level)))
7862 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7863 (diff (abs (- level (length down-head) -1))))
7864 (replace-match down-head nil t)
7865 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7866 (when org-adapt-indentation (org-fixup-indentation diff))
7867 (run-hooks 'org-after-demote-entry-hook))))
7869 (defun org-cycle-level ()
7870 "Cycle the level of an empty headline through possible states.
7871 This goes first to child, then to parent, level, then up the hierarchy.
7872 After top level, it switches back to sibling level."
7873 (interactive)
7874 (let ((org-adapt-indentation nil))
7875 (when (org-point-at-end-of-empty-headline)
7876 (setq this-command 'org-cycle-level) ; Only needed for caching
7877 (let ((cur-level (org-current-level))
7878 (prev-level (org-get-previous-line-level)))
7879 (cond
7880 ;; If first headline in file, promote to top-level.
7881 ((= prev-level 0)
7882 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7883 do (org-do-promote)))
7884 ;; If same level as prev, demote one.
7885 ((= prev-level cur-level)
7886 (org-do-demote))
7887 ;; If parent is top-level, promote to top level if not already.
7888 ((= prev-level 1)
7889 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7890 do (org-do-promote)))
7891 ;; If top-level, return to prev-level.
7892 ((= cur-level 1)
7893 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7894 do (org-do-demote)))
7895 ;; If less than prev-level, promote one.
7896 ((< cur-level prev-level)
7897 (org-do-promote))
7898 ;; If deeper than prev-level, promote until higher than
7899 ;; prev-level.
7900 ((> cur-level prev-level)
7901 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7902 do (org-do-promote))))
7903 t))))
7905 (defun org-map-tree (fun)
7906 "Call FUN for every heading underneath the current one."
7907 (org-back-to-heading t)
7908 (let ((level (funcall outline-level)))
7909 (save-excursion
7910 (funcall fun)
7911 (while (and (progn
7912 (outline-next-heading)
7913 (> (funcall outline-level) level))
7914 (not (eobp)))
7915 (funcall fun)))))
7917 (defun org-map-region (fun beg end)
7918 "Call FUN for every heading between BEG and END."
7919 (let ((org-ignore-region t))
7920 (save-excursion
7921 (setq end (copy-marker end))
7922 (goto-char beg)
7923 (when (and (re-search-forward org-outline-regexp-bol nil t)
7924 (< (point) end))
7925 (funcall fun))
7926 (while (and (progn
7927 (outline-next-heading)
7928 (< (point) end))
7929 (not (eobp)))
7930 (funcall fun)))))
7932 (defun org-fixup-indentation (diff)
7933 "Change the indentation in the current entry by DIFF.
7935 DIFF is an integer. Indentation is done according to the
7936 following rules:
7938 - Planning information and property drawers are always indented
7939 according to the new level of the headline;
7941 - Footnote definitions and their contents are ignored;
7943 - Inlinetasks' boundaries are not shifted;
7945 - Empty lines are ignored;
7947 - Other lines' indentation are shifted by DIFF columns, unless
7948 it would introduce a structural change in the document, in
7949 which case no shifting is done at all.
7951 Assume point is at a heading or an inlinetask beginning."
7952 (org-with-wide-buffer
7953 (narrow-to-region (line-beginning-position)
7954 (save-excursion
7955 (if (org-with-limited-levels (org-at-heading-p))
7956 (org-with-limited-levels (outline-next-heading))
7957 (org-inlinetask-goto-end))
7958 (point)))
7959 (forward-line)
7960 ;; Indent properly planning info and property drawer.
7961 (when (looking-at-p org-planning-line-re)
7962 (org-indent-line)
7963 (forward-line))
7964 (when (looking-at org-property-drawer-re)
7965 (goto-char (match-end 0))
7966 (forward-line)
7967 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7968 (catch 'no-shift
7969 (when (zerop diff) (throw 'no-shift nil))
7970 ;; If DIFF is negative, first check if a shift is possible at all
7971 ;; (e.g., it doesn't break structure). This can only happen if
7972 ;; some contents are not properly indented.
7973 (let ((case-fold-search t))
7974 (when (< diff 0)
7975 (let ((diff (- diff))
7976 (forbidden-re (concat org-outline-regexp
7977 "\\|"
7978 (substring org-footnote-definition-re 1))))
7979 (save-excursion
7980 (while (not (eobp))
7981 (cond
7982 ((looking-at-p "[ \t]*$") (forward-line))
7983 ((and (looking-at-p org-footnote-definition-re)
7984 (let ((e (org-element-at-point)))
7985 (and (eq (org-element-type e) 'footnote-definition)
7986 (goto-char (org-element-property :end e))))))
7987 ((looking-at-p org-outline-regexp) (forward-line))
7988 ;; Give up if shifting would move before column 0 or
7989 ;; if it would introduce a headline or a footnote
7990 ;; definition.
7992 (skip-chars-forward " \t")
7993 (let ((ind (current-column)))
7994 (when (or (< ind diff)
7995 (and (= ind diff) (looking-at-p forbidden-re)))
7996 (throw 'no-shift nil)))
7997 ;; Ignore contents of example blocks and source
7998 ;; blocks if their indentation is meant to be
7999 ;; preserved. Jump to block's closing line.
8000 (beginning-of-line)
8001 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8002 (let ((e (org-element-at-point)))
8003 (and (memq (org-element-type e)
8004 '(example-block src-block))
8005 (or org-src-preserve-indentation
8006 (org-element-property :preserve-indent e))
8007 (goto-char (org-element-property :end e))
8008 (progn (skip-chars-backward " \r\t\n")
8009 (beginning-of-line)
8010 t))))
8011 (forward-line))))))))
8012 ;; Shift lines but footnote definitions, inlinetasks boundaries
8013 ;; by DIFF. Also skip contents of source or example blocks
8014 ;; when indentation is meant to be preserved.
8015 (while (not (eobp))
8016 (cond
8017 ((and (looking-at-p org-footnote-definition-re)
8018 (let ((e (org-element-at-point)))
8019 (and (eq (org-element-type e) 'footnote-definition)
8020 (goto-char (org-element-property :end e))))))
8021 ((looking-at-p org-outline-regexp) (forward-line))
8022 ((looking-at-p "[ \t]*$") (forward-line))
8024 (indent-line-to (+ (org-get-indentation) diff))
8025 (beginning-of-line)
8026 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8027 (let ((e (org-element-at-point)))
8028 (and (memq (org-element-type e)
8029 '(example-block src-block))
8030 (or org-src-preserve-indentation
8031 (org-element-property :preserve-indent e))
8032 (goto-char (org-element-property :end e))
8033 (progn (skip-chars-backward " \r\t\n")
8034 (beginning-of-line)
8035 t))))
8036 (forward-line)))))))))
8038 (defun org-convert-to-odd-levels ()
8039 "Convert an Org file with all levels allowed to one with odd levels.
8040 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8041 level 5 etc."
8042 (interactive)
8043 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8044 (let ((outline-level 'org-outline-level)
8045 (org-odd-levels-only nil) n)
8046 (save-excursion
8047 (goto-char (point-min))
8048 (while (re-search-forward "^\\*\\*+ " nil t)
8049 (setq n (- (length (match-string 0)) 2))
8050 (while (>= (setq n (1- n)) 0)
8051 (org-demote))
8052 (end-of-line 1))))))
8054 (defun org-convert-to-oddeven-levels ()
8055 "Convert an Org file with only odd levels to one with odd/even levels.
8056 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8057 file contains a section with an even level, conversion would
8058 destroy the structure of the file. An error is signaled in this
8059 case."
8060 (interactive)
8061 (goto-char (point-min))
8062 ;; First check if there are no even levels
8063 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8064 (org-show-set-visibility 'canonical)
8065 (error "Not all levels are odd in this file. Conversion not possible"))
8066 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8067 (let ((outline-regexp org-outline-regexp)
8068 (outline-level 'org-outline-level)
8069 (org-odd-levels-only nil) n)
8070 (save-excursion
8071 (goto-char (point-min))
8072 (while (re-search-forward "^\\*\\*+ " nil t)
8073 (setq n (/ (1- (length (match-string 0))) 2))
8074 (while (>= (setq n (1- n)) 0)
8075 (org-promote))
8076 (end-of-line 1))))))
8078 (defun org-tr-level (n)
8079 "Make N odd if required."
8080 (if org-odd-levels-only (1+ (/ n 2)) n))
8082 ;;; Vertical tree motion, cutting and pasting of subtrees
8084 (defun org-move-subtree-up (&optional arg)
8085 "Move the current subtree up past ARG headlines of the same level."
8086 (interactive "p")
8087 (org-move-subtree-down (- (prefix-numeric-value arg))))
8089 (defun org-move-subtree-down (&optional arg)
8090 "Move the current subtree down past ARG headlines of the same level."
8091 (interactive "p")
8092 (setq arg (prefix-numeric-value arg))
8093 (org-preserve-local-variables
8094 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8095 'org-get-last-sibling))
8096 (ins-point (make-marker))
8097 (cnt (abs arg))
8098 (col (current-column))
8099 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8100 ;; Select the tree
8101 (org-back-to-heading)
8102 (setq beg0 (point))
8103 (save-excursion
8104 (setq ne-beg (org-back-over-empty-lines))
8105 (setq beg (point)))
8106 (save-match-data
8107 (save-excursion (outline-end-of-heading)
8108 (setq folded (org-invisible-p)))
8109 (progn (org-end-of-subtree nil t)
8110 (unless (eobp) (backward-char))))
8111 (outline-next-heading)
8112 (setq ne-end (org-back-over-empty-lines))
8113 (setq end (point))
8114 (goto-char beg0)
8115 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8116 ;; include less whitespace
8117 (save-excursion
8118 (goto-char beg)
8119 (forward-line (- ne-beg ne-end))
8120 (setq beg (point))))
8121 ;; Find insertion point, with error handling
8122 (while (> cnt 0)
8123 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8124 (progn (goto-char beg0)
8125 (user-error "Cannot move past superior level or buffer limit")))
8126 (setq cnt (1- cnt)))
8127 (when (> arg 0)
8128 ;; Moving forward - still need to move over subtree
8129 (org-end-of-subtree t t)
8130 (save-excursion
8131 (org-back-over-empty-lines)
8132 (unless (bolp) (insert "\n"))))
8133 (setq ne-ins (org-back-over-empty-lines))
8134 (move-marker ins-point (point))
8135 (setq txt (buffer-substring beg end))
8136 (org-save-markers-in-region beg end)
8137 (delete-region beg end)
8138 (org-remove-empty-overlays-at beg)
8139 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8140 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8141 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8142 (let ((bbb (point)))
8143 (insert-before-markers txt)
8144 (org-reinstall-markers-in-region bbb)
8145 (move-marker ins-point bbb))
8146 (or (bolp) (insert "\n"))
8147 (setq ins-end (point))
8148 (goto-char ins-point)
8149 (org-skip-whitespace)
8150 (when (and (< arg 0)
8151 (org-first-sibling-p)
8152 (> ne-ins ne-beg))
8153 ;; Move whitespace back to beginning.
8154 (save-excursion
8155 (goto-char ins-end)
8156 (let ((kill-whole-line t))
8157 (kill-line (- ne-ins ne-beg)) (point)))
8158 (insert (make-string (- ne-ins ne-beg) ?\n)))
8159 (move-marker ins-point nil)
8160 (if folded
8161 (outline-hide-subtree)
8162 (org-show-entry)
8163 (org-show-children)
8164 (org-cycle-hide-drawers 'children))
8165 (org-clean-visibility-after-subtree-move)
8166 ;; Move back to the initial column we were at.
8167 (move-to-column col))))
8169 (defvar org-subtree-clip ""
8170 "Clipboard for cut and paste of subtrees.
8171 This is actually only a copy of the kill, because we use the normal kill
8172 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8174 (defvar org-subtree-clip-folded nil
8175 "Was the last copied subtree folded?
8176 This is used to fold the tree back after pasting.")
8178 (defun org-cut-subtree (&optional n)
8179 "Cut the current subtree into the clipboard.
8180 With prefix arg N, cut this many sequential subtrees.
8181 This is a short-hand for marking the subtree and then cutting it."
8182 (interactive "p")
8183 (org-copy-subtree n 'cut))
8185 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8186 "Copy the current subtree it in the clipboard.
8187 With prefix arg N, copy this many sequential subtrees.
8188 This is a short-hand for marking the subtree and then copying it.
8189 If CUT is non-nil, actually cut the subtree.
8190 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8191 of some markers in the region, even if CUT is non-nil. This is
8192 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8193 (interactive "p")
8194 (org-preserve-local-variables
8195 (let (beg end folded (beg0 (point)))
8196 (if (called-interactively-p 'any)
8197 (org-back-to-heading nil) ; take what looks like a subtree
8198 (org-back-to-heading t)) ; take what is really there
8199 (setq beg (point))
8200 (skip-chars-forward " \t\r\n")
8201 (save-match-data
8202 (if nosubtrees
8203 (outline-next-heading)
8204 (save-excursion (outline-end-of-heading)
8205 (setq folded (org-invisible-p)))
8206 (ignore-errors (org-forward-heading-same-level (1- n) t))
8207 (org-end-of-subtree t t)))
8208 ;; Include the end of an inlinetask
8209 (when (and (featurep 'org-inlinetask)
8210 (looking-at-p (concat (org-inlinetask-outline-regexp)
8211 "END[ \t]*$")))
8212 (end-of-line))
8213 (setq end (point))
8214 (goto-char beg0)
8215 (when (> end beg)
8216 (setq org-subtree-clip-folded folded)
8217 (when (or cut force-store-markers)
8218 (org-save-markers-in-region beg end))
8219 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8220 (setq org-subtree-clip (current-kill 0))
8221 (message "%s: Subtree(s) with %d characters"
8222 (if cut "Cut" "Copied")
8223 (length org-subtree-clip))))))
8225 (defun org-paste-subtree (&optional level tree for-yank remove)
8226 "Paste the clipboard as a subtree, with modification of headline level.
8227 The entire subtree is promoted or demoted in order to match a new headline
8228 level.
8230 If the cursor is at the beginning of a headline, the same level as
8231 that headline is used to paste the tree.
8233 If not, the new level is derived from the *visible* headings
8234 before and after the insertion point, and taken to be the inferior headline
8235 level of the two. So if the previous visible heading is level 3 and the
8236 next is level 4 (or vice versa), level 4 will be used for insertion.
8237 This makes sure that the subtree remains an independent subtree and does
8238 not swallow low level entries.
8240 You can also force a different level, either by using a numeric prefix
8241 argument, or by inserting the heading marker by hand. For example, if the
8242 cursor is after \"*****\", then the tree will be shifted to level 5.
8244 If optional TREE is given, use this text instead of the kill ring.
8246 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8247 move back over whitespace before inserting, and move point to the end of
8248 the inserted text when done.
8250 When REMOVE is non-nil, remove the subtree from the clipboard."
8251 (interactive "P")
8252 (setq tree (or tree (and kill-ring (current-kill 0))))
8253 (unless (org-kill-is-subtree-p tree)
8254 (user-error "%s"
8255 (substitute-command-keys
8256 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8257 (org-with-limited-levels
8258 (let* ((visp (not (org-invisible-p)))
8259 (txt tree)
8260 (^re_ "\\(\\*+\\)[ \t]*")
8261 (old-level (if (string-match org-outline-regexp-bol txt)
8262 (- (match-end 0) (match-beginning 0) 1)
8263 -1))
8264 (force-level (cond (level (prefix-numeric-value level))
8265 ((and (looking-at "[ \t]*$")
8266 (string-match
8267 "^\\*+$" (buffer-substring
8268 (point-at-bol) (point))))
8269 (- (match-end 0) (match-beginning 0)))
8270 ((and (bolp)
8271 (looking-at org-outline-regexp))
8272 (- (match-end 0) (point) 1))))
8273 (previous-level (save-excursion
8274 (condition-case nil
8275 (progn
8276 (outline-previous-visible-heading 1)
8277 (if (looking-at ^re_)
8278 (- (match-end 0) (match-beginning 0) 1)
8280 (error 1))))
8281 (next-level (save-excursion
8282 (condition-case nil
8283 (progn
8284 (or (looking-at org-outline-regexp)
8285 (outline-next-visible-heading 1))
8286 (if (looking-at ^re_)
8287 (- (match-end 0) (match-beginning 0) 1)
8289 (error 1))))
8290 (new-level (or force-level (max previous-level next-level)))
8291 (shift (if (or (= old-level -1)
8292 (= new-level -1)
8293 (= old-level new-level))
8295 (- new-level old-level)))
8296 (delta (if (> shift 0) -1 1))
8297 (func (if (> shift 0) 'org-demote 'org-promote))
8298 (org-odd-levels-only nil)
8299 beg end newend)
8300 ;; Remove the forced level indicator
8301 (when force-level
8302 (delete-region (point-at-bol) (point)))
8303 ;; Paste
8304 (beginning-of-line (if (bolp) 1 2))
8305 (setq beg (point))
8306 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8307 (insert-before-markers txt)
8308 (unless (string-suffix-p "\n" txt) (insert "\n"))
8309 (setq newend (point))
8310 (org-reinstall-markers-in-region beg)
8311 (setq end (point))
8312 (goto-char beg)
8313 (skip-chars-forward " \t\n\r")
8314 (setq beg (point))
8315 (when (and (org-invisible-p) visp)
8316 (save-excursion (outline-show-heading)))
8317 ;; Shift if necessary
8318 (unless (= shift 0)
8319 (save-restriction
8320 (narrow-to-region beg end)
8321 (while (not (= shift 0))
8322 (org-map-region func (point-min) (point-max))
8323 (setq shift (+ delta shift)))
8324 (goto-char (point-min))
8325 (setq newend (point-max))))
8326 (when (or (called-interactively-p 'interactive) for-yank)
8327 (message "Clipboard pasted as level %d subtree" new-level))
8328 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8329 kill-ring
8330 (eq org-subtree-clip (current-kill 0))
8331 org-subtree-clip-folded)
8332 ;; The tree was folded before it was killed/copied
8333 (outline-hide-subtree))
8334 (and for-yank (goto-char newend))
8335 (and remove (setq kill-ring (cdr kill-ring))))))
8337 (defun org-kill-is-subtree-p (&optional txt)
8338 "Check if the current kill is an outline subtree, or a set of trees.
8339 Returns nil if kill does not start with a headline, or if the first
8340 headline level is not the largest headline level in the tree.
8341 So this will actually accept several entries of equal levels as well,
8342 which is OK for `org-paste-subtree'.
8343 If optional TXT is given, check this string instead of the current kill."
8344 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8345 (re (org-get-limited-outline-regexp))
8346 (^re (concat "^" re))
8347 (start-level (and kill
8348 (string-match
8349 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8350 kill)
8351 (- (match-end 2) (match-beginning 2) 1)))
8352 (start (1+ (or (match-beginning 2) -1))))
8353 (if (not start-level)
8354 (progn
8355 nil) ;; does not even start with a heading
8356 (catch 'exit
8357 (while (setq start (string-match ^re kill (1+ start)))
8358 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8359 (throw 'exit nil)))
8360 t))))
8362 (defvar org-markers-to-move nil
8363 "Markers that should be moved with a cut-and-paste operation.
8364 Those markers are stored together with their positions relative to
8365 the start of the region.")
8367 (defun org-save-markers-in-region (beg end)
8368 "Check markers in region.
8369 If these markers are between BEG and END, record their position relative
8370 to BEG, so that after moving the block of text, we can put the markers back
8371 into place.
8372 This function gets called just before an entry or tree gets cut from the
8373 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8374 called immediately, to move the markers with the entries."
8375 (setq org-markers-to-move nil)
8376 (when (featurep 'org-clock)
8377 (org-clock-save-markers-for-cut-and-paste beg end))
8378 (when (featurep 'org-agenda)
8379 (org-agenda-save-markers-for-cut-and-paste beg end)))
8381 (defun org-check-and-save-marker (marker beg end)
8382 "Check if MARKER is between BEG and END.
8383 If yes, remember the marker and the distance to BEG."
8384 (when (and (marker-buffer marker)
8385 (equal (marker-buffer marker) (current-buffer))
8386 (>= marker beg) (< marker end))
8387 (push (cons marker (- marker beg)) org-markers-to-move)))
8389 (defun org-reinstall-markers-in-region (beg)
8390 "Move all remembered markers to their position relative to BEG."
8391 (dolist (x org-markers-to-move)
8392 (move-marker (car x) (+ beg (cdr x))))
8393 (setq org-markers-to-move nil))
8395 (defun org-narrow-to-subtree ()
8396 "Narrow buffer to the current subtree."
8397 (interactive)
8398 (save-excursion
8399 (save-match-data
8400 (org-with-limited-levels
8401 (narrow-to-region
8402 (progn (org-back-to-heading t) (point))
8403 (progn (org-end-of-subtree t t)
8404 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8405 (point)))))))
8407 (defun org-narrow-to-block ()
8408 "Narrow buffer to the current block."
8409 (interactive)
8410 (let* ((case-fold-search t)
8411 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8412 "^[ \t]*#\\+end_.*")))
8413 (if blockp
8414 (narrow-to-region (car blockp) (cdr blockp))
8415 (user-error "Not in a block"))))
8417 (defun org-clone-subtree-with-time-shift (n &optional shift)
8418 "Clone the task (subtree) at point N times.
8419 The clones will be inserted as siblings.
8421 In interactive use, the user will be prompted for the number of
8422 clones to be produced. If the entry has a timestamp, the user
8423 will also be prompted for a time shift, which may be a repeater
8424 as used in time stamps, for example `+3d'. To disable this,
8425 you can call the function with a universal prefix argument.
8427 When a valid repeater is given and the entry contains any time
8428 stamps, the clones will become a sequence in time, with time
8429 stamps in the subtree shifted for each clone produced. If SHIFT
8430 is nil or the empty string, time stamps will be left alone. The
8431 ID property of the original subtree is removed.
8433 In each clone, all the CLOCK entries will be removed. This
8434 prevents Org from considering that the clocked times overlap.
8436 If the original subtree did contain time stamps with a repeater,
8437 the following will happen:
8438 - the repeater will be removed in each clone
8439 - an additional clone will be produced, with the current, unshifted
8440 date(s) in the entry.
8441 - the original entry will be placed *after* all the clones, with
8442 repeater intact.
8443 - the start days in the repeater in the original entry will be shifted
8444 to past the last clone.
8445 In this way you can spell out a number of instances of a repeating task,
8446 and still retain the repeater to cover future instances of the task.
8448 As described above, N+1 clones are produced when the original
8449 subtree has a repeater. Setting N to 0, then, can be used to
8450 remove the repeater from a subtree and create a shifted clone
8451 with the original repeater."
8452 (interactive "nNumber of clones to produce: ")
8453 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8454 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8455 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8456 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8457 (shift
8458 (or shift
8459 (if (and (not (equal current-prefix-arg '(4)))
8460 (save-excursion
8461 (goto-char beg)
8462 (re-search-forward org-ts-regexp-both end-of-tree t)))
8463 (read-from-minibuffer
8464 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8465 ""))) ;No time shift
8466 (doshift
8467 (and (org-string-nw-p shift)
8468 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8469 shift)
8470 (user-error "Invalid shift specification %s" shift)))))
8471 (goto-char end-of-tree)
8472 (unless (bolp) (insert "\n"))
8473 (let* ((end (point))
8474 (template (buffer-substring beg end))
8475 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8476 (shift-what (pcase (and doshift (match-string 2 shift))
8477 (`nil nil)
8478 ("d" 'day)
8479 ("w" (setq shift-n (* 7 shift-n)) 'day)
8480 ("m" 'month)
8481 ("y" 'year)
8482 (_ (error "Unsupported time unit"))))
8483 (nmin 1)
8484 (nmax n)
8485 (n-no-remove -1)
8486 (idprop (org-entry-get nil "ID")))
8487 (when (and doshift
8488 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8489 template))
8490 (delete-region beg end)
8491 (setq end beg)
8492 (setq nmin 0)
8493 (setq nmax (1+ nmax))
8494 (setq n-no-remove nmax))
8495 (goto-char end)
8496 (cl-loop for n from nmin to nmax do
8497 (insert
8498 ;; Prepare clone.
8499 (with-temp-buffer
8500 (insert template)
8501 (org-mode)
8502 (goto-char (point-min))
8503 (org-show-subtree)
8504 (and idprop (if org-clone-delete-id
8505 (org-entry-delete nil "ID")
8506 (org-id-get-create t)))
8507 (unless (= n 0)
8508 (while (re-search-forward org-clock-line-re nil t)
8509 (delete-region (line-beginning-position)
8510 (line-beginning-position 2)))
8511 (goto-char (point-min))
8512 (while (re-search-forward org-drawer-regexp nil t)
8513 (org-remove-empty-drawer-at (point))))
8514 (goto-char (point-min))
8515 (when doshift
8516 (while (re-search-forward org-ts-regexp-both nil t)
8517 (org-timestamp-change (* n shift-n) shift-what))
8518 (unless (= n n-no-remove)
8519 (goto-char (point-min))
8520 (while (re-search-forward org-ts-regexp nil t)
8521 (save-excursion
8522 (goto-char (match-beginning 0))
8523 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8524 (delete-region (match-beginning 1) (match-end 1)))))))
8525 (buffer-string)))))
8526 (goto-char beg)))
8528 ;;; Outline Sorting
8530 (defun org-sort (&optional with-case)
8531 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8532 Optional argument WITH-CASE means sort case-sensitively."
8533 (interactive "P")
8534 (org-call-with-arg
8535 (cond ((org-at-table-p) #'org-table-sort-lines)
8536 ((org-at-item-p) #'org-sort-list)
8537 (t #'org-sort-entries))
8538 with-case))
8540 (defun org-sort-remove-invisible (s)
8541 "Remove invisible part of links and emphasis markers from string S."
8542 (remove-text-properties 0 (length s) org-rm-props s)
8543 (replace-regexp-in-string
8544 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8545 (replace-regexp-in-string
8546 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8547 (org-link-display-format s)
8548 t t) t t))
8550 (defvar org-priority-regexp) ; defined later in the file
8552 (defvar org-after-sorting-entries-or-items-hook nil
8553 "Hook that is run after a bunch of entries or items have been sorted.
8554 When children are sorted, the cursor is in the parent line when this
8555 hook gets called. When a region or a plain list is sorted, the cursor
8556 will be in the first entry of the sorted region/list.")
8558 (defun org-sort-entries
8559 (&optional with-case sorting-type getkey-func compare-func property
8560 interactive?)
8561 "Sort entries on a certain level of an outline tree.
8562 If there is an active region, the entries in the region are sorted.
8563 Else, if the cursor is before the first entry, sort the top-level items.
8564 Else, the children of the entry at point are sorted.
8566 Sorting can be alphabetically, numerically, by date/time as given by
8567 a time stamp, by a property, by priority order, or by a custom function.
8569 The command prompts for the sorting type unless it has been given to the
8570 function through the SORTING-TYPE argument, which needs to be a character,
8571 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8572 the precise meaning of each character:
8574 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8575 c By creation time, which is assumed to be the first inactive time stamp
8576 at the beginning of a line.
8577 d By deadline date/time.
8578 k By clocking time.
8579 n Numerically, by converting the beginning of the entry/item to a number.
8580 o By order of TODO keywords.
8581 p By priority according to the cookie.
8582 r By the value of a property.
8583 s By scheduled date/time.
8584 t By date/time, either the first active time stamp in the entry, or, if
8585 none exist, by the first inactive one.
8587 Capital letters will reverse the sort order.
8589 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8590 called with point at the beginning of the record. It must return a
8591 value that is compatible with COMPARE-FUNC, the function used to
8592 compare entries.
8594 Comparing entries ignores case by default. However, with an optional argument
8595 WITH-CASE, the sorting considers case as well.
8597 Sorting is done against the visible part of the headlines, it ignores hidden
8598 links.
8600 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8602 A non-nil value for INTERACTIVE? is used to signal that this
8603 function is being called interactively."
8604 (interactive (list current-prefix-arg nil nil nil nil t))
8605 (let ((case-func (if with-case 'identity 'downcase))
8606 start beg end stars re re2
8607 txt what tmp)
8608 ;; Find beginning and end of region to sort
8609 (cond
8610 ((org-region-active-p)
8611 ;; we will sort the region
8612 (setq end (region-end)
8613 what "region")
8614 (goto-char (region-beginning))
8615 (unless (org-at-heading-p) (outline-next-heading))
8616 (setq start (point)))
8617 ((or (org-at-heading-p)
8618 (ignore-errors (progn (org-back-to-heading) t)))
8619 ;; we will sort the children of the current headline
8620 (org-back-to-heading)
8621 (setq start (point)
8622 end (progn (org-end-of-subtree t t)
8623 (or (bolp) (insert "\n"))
8624 (when (>= (org-back-over-empty-lines) 1)
8625 (forward-line 1))
8626 (point))
8627 what "children")
8628 (goto-char start)
8629 (outline-show-subtree)
8630 (outline-next-heading))
8632 ;; we will sort the top-level entries in this file
8633 (goto-char (point-min))
8634 (or (org-at-heading-p) (outline-next-heading))
8635 (setq start (point))
8636 (goto-char (point-max))
8637 (beginning-of-line 1)
8638 (when (looking-at ".*?\\S-")
8639 ;; File ends in a non-white line
8640 (end-of-line 1)
8641 (insert "\n"))
8642 (setq end (point-max))
8643 (setq what "top-level")
8644 (goto-char start)
8645 (outline-show-all)))
8647 (setq beg (point))
8648 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8650 (looking-at "\\(\\*+\\)")
8651 (setq stars (match-string 1)
8652 re (concat "^" (regexp-quote stars) " +")
8653 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8654 txt (buffer-substring beg end))
8655 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8656 (when (and (not (equal stars "*")) (string-match re2 txt))
8657 (user-error "Region to sort contains a level above the first entry"))
8659 (unless sorting-type
8660 (message
8661 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8662 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8663 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8664 what)
8665 (setq sorting-type (read-char-exclusive)))
8667 (unless getkey-func
8668 (and (= (downcase sorting-type) ?f)
8669 (setq getkey-func
8670 (or (and interactive?
8671 (org-read-function
8672 "Function for extracting keys: "))
8673 (error "Missing key extractor")))))
8675 (and (= (downcase sorting-type) ?r)
8676 (not property)
8677 (setq property
8678 (completing-read "Property: "
8679 (mapcar #'list (org-buffer-property-keys t))
8680 nil t)))
8682 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8683 (message "Sorting entries...")
8685 (save-restriction
8686 (narrow-to-region start end)
8687 (let ((restore-clock?
8688 ;; The clock marker is lost when using `sort-subr'; mark
8689 ;; the clock with temporary `:org-clock-marker-backup'
8690 ;; text property.
8691 (when (and (eq (org-clock-is-active) (current-buffer))
8692 (<= start (marker-position org-clock-marker))
8693 (>= end (marker-position org-clock-marker)))
8694 (org-with-silent-modifications
8695 (put-text-property (1- org-clock-marker) org-clock-marker
8696 :org-clock-marker-backup t))
8698 (dcst (downcase sorting-type))
8699 (case-fold-search nil)
8700 (now (current-time)))
8701 (org-preserve-local-variables
8702 (sort-subr
8703 (/= dcst sorting-type)
8704 ;; This function moves to the beginning character of the
8705 ;; "record" to be sorted.
8706 (lambda nil
8707 (if (re-search-forward re nil t)
8708 (goto-char (match-beginning 0))
8709 (goto-char (point-max))))
8710 ;; This function moves to the last character of the "record" being
8711 ;; sorted.
8712 (lambda nil
8713 (save-match-data
8714 (condition-case nil
8715 (outline-forward-same-level 1)
8716 (error
8717 (goto-char (point-max))))))
8718 ;; This function returns the value that gets sorted against.
8719 (lambda ()
8720 (cond
8721 ((= dcst ?n)
8722 (if (looking-at org-complex-heading-regexp)
8723 (string-to-number
8724 (org-sort-remove-invisible (match-string 4)))
8725 nil))
8726 ((= dcst ?a)
8727 (if (looking-at org-complex-heading-regexp)
8728 (funcall case-func
8729 (org-sort-remove-invisible (match-string 4)))
8730 nil))
8731 ((= dcst ?k)
8732 (or (get-text-property (point) :org-clock-minutes) 0))
8733 ((= dcst ?t)
8734 (let ((end (save-excursion (outline-next-heading) (point))))
8735 (if (or (re-search-forward org-ts-regexp end t)
8736 (re-search-forward org-ts-regexp-both end t))
8737 (org-time-string-to-seconds (match-string 0))
8738 (float-time now))))
8739 ((= dcst ?c)
8740 (let ((end (save-excursion (outline-next-heading) (point))))
8741 (if (re-search-forward
8742 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8743 end t)
8744 (org-time-string-to-seconds (match-string 0))
8745 (float-time now))))
8746 ((= dcst ?s)
8747 (let ((end (save-excursion (outline-next-heading) (point))))
8748 (if (re-search-forward org-scheduled-time-regexp end t)
8749 (org-time-string-to-seconds (match-string 1))
8750 (float-time now))))
8751 ((= dcst ?d)
8752 (let ((end (save-excursion (outline-next-heading) (point))))
8753 (if (re-search-forward org-deadline-time-regexp end t)
8754 (org-time-string-to-seconds (match-string 1))
8755 (float-time now))))
8756 ((= dcst ?p)
8757 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8758 (string-to-char (match-string 2))
8759 org-default-priority))
8760 ((= dcst ?r)
8761 (or (org-entry-get nil property) ""))
8762 ((= dcst ?o)
8763 (when (looking-at org-complex-heading-regexp)
8764 (let* ((m (match-string 2))
8765 (s (if (member m org-done-keywords) '- '+)))
8766 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8767 ((= dcst ?f)
8768 (if getkey-func
8769 (progn
8770 (setq tmp (funcall getkey-func))
8771 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8772 tmp)
8773 (error "Invalid key function `%s'" getkey-func)))
8774 (t (error "Invalid sorting type `%c'" sorting-type))))
8776 (cond
8777 ((= dcst ?a) 'string<)
8778 ((= dcst ?f)
8779 (or compare-func
8780 (and interactive?
8781 (org-read-function
8782 (concat "Function for comparing keys "
8783 "(empty for default `sort-subr' predicate): ")
8784 'allow-empty))))
8785 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8786 (when restore-clock?
8787 (move-marker org-clock-marker
8788 (1+ (next-single-property-change
8789 start :org-clock-marker-backup)))
8790 (remove-text-properties (1- org-clock-marker) org-clock-marker
8791 '(:org-clock-marker-backup t)))))
8792 (run-hooks 'org-after-sorting-entries-or-items-hook)
8793 (message "Sorting entries...done")))
8795 ;;; The orgstruct minor mode
8797 ;; Define a minor mode which can be used in other modes in order to
8798 ;; integrate the Org mode structure editing commands.
8800 ;; This is really a hack, because the Org mode structure commands use
8801 ;; keys which normally belong to the major mode. Here is how it
8802 ;; works: The minor mode defines all the keys necessary to operate the
8803 ;; structure commands, but wraps the commands into a function which
8804 ;; tests if the cursor is currently at a headline or a plain list
8805 ;; item. If that is the case, the structure command is used,
8806 ;; temporarily setting many Org mode variables like regular
8807 ;; expressions for filling etc. However, when any of those keys is
8808 ;; used at a different location, function uses `key-binding' to look
8809 ;; up if the key has an associated command in another currently active
8810 ;; keymap (minor modes, major mode, global), and executes that
8811 ;; command. There might be problems if any of the keys is otherwise
8812 ;; used as a prefix key.
8814 (defcustom orgstruct-heading-prefix-regexp ""
8815 "Regexp that matches the custom prefix of Org headlines in
8816 orgstruct(++)-mode."
8817 :group 'org
8818 :version "26.1"
8819 :package-version '(Org . "8.3")
8820 :type 'regexp)
8821 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8823 (defcustom orgstruct-setup-hook nil
8824 "Hook run after orgstruct-mode-map is filled."
8825 :group 'org
8826 :version "24.4"
8827 :package-version '(Org . "8.0")
8828 :type 'hook)
8830 (defvar orgstruct-initialized nil)
8832 (defvar org-local-vars nil
8833 "List of local variables, for use by `orgstruct-mode'.")
8835 ;;;###autoload
8836 (define-minor-mode orgstruct-mode
8837 "Toggle the minor mode `orgstruct-mode'.
8838 This mode is for using Org mode structure commands in other
8839 modes. The following keys behave as if Org mode were active, if
8840 the cursor is on a headline, or on a plain list item (both as
8841 defined by Org mode)."
8842 nil " OrgStruct" (make-sparse-keymap)
8843 (funcall (if orgstruct-mode
8844 'add-to-invisibility-spec
8845 'remove-from-invisibility-spec)
8846 '(outline . t))
8847 (when orgstruct-mode
8848 (org-load-modules-maybe)
8849 (unless orgstruct-initialized
8850 (orgstruct-setup)
8851 (setq orgstruct-initialized t))))
8853 ;;;###autoload
8854 (defun turn-on-orgstruct ()
8855 "Unconditionally turn on `orgstruct-mode'."
8856 (orgstruct-mode 1))
8858 (defvar-local orgstruct-is-++ nil
8859 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8860 (defvar-local org-fb-vars nil)
8861 (defun orgstruct++-mode (&optional arg)
8862 "Toggle `orgstruct-mode', the enhanced version of it.
8863 In addition to setting orgstruct-mode, this also exports all
8864 indentation and autofilling variables from Org mode into the
8865 buffer. It will also recognize item context in multiline items."
8866 (interactive "P")
8867 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8868 (if (< arg 1)
8869 (progn (orgstruct-mode -1)
8870 (dolist (v org-fb-vars)
8871 (set (make-local-variable (car v))
8872 (if (eq (car-safe (cadr v)) 'quote)
8873 (cl-cadadr v)
8874 (nth 1 v)))))
8875 (orgstruct-mode 1)
8876 (setq org-fb-vars nil)
8877 (unless org-local-vars
8878 (setq org-local-vars (org-get-local-variables)))
8879 (let (var val)
8880 (dolist (x org-local-vars)
8881 (when (string-match
8882 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
8883 \\|fill-prefix\\|indent-\\)"
8884 (symbol-name (car x)))
8885 (setq var (car x) val (nth 1 x))
8886 (push (list var `(quote ,(eval var))) org-fb-vars)
8887 (set (make-local-variable var)
8888 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8889 (setq-local orgstruct-is-++ t))))
8891 ;;;###autoload
8892 (defun turn-on-orgstruct++ ()
8893 "Unconditionally turn on `orgstruct++-mode'."
8894 (orgstruct++-mode 1))
8896 (defun orgstruct-error ()
8897 "Error when there is no default binding for a structure key."
8898 (interactive)
8899 (funcall (if (fboundp 'user-error)
8900 'user-error
8901 'error)
8902 "This key has no function outside structure elements"))
8904 (defun orgstruct-setup ()
8905 "Setup orgstruct keymap."
8906 (dolist (cell '((org-demote . t)
8907 (org-metaleft . t)
8908 (org-metaright . t)
8909 (org-promote . t)
8910 (org-shiftmetaleft . t)
8911 (org-shiftmetaright . t)
8912 org-backward-element
8913 org-backward-heading-same-level
8914 org-ctrl-c-ret
8915 org-ctrl-c-minus
8916 org-ctrl-c-star
8917 org-cycle
8918 org-force-cycle-archived
8919 org-forward-heading-same-level
8920 org-insert-heading
8921 org-insert-heading-respect-content
8922 org-kill-note-or-show-branches
8923 org-mark-subtree
8924 org-meta-return
8925 org-metadown
8926 org-metaup
8927 org-narrow-to-subtree
8928 org-promote-subtree
8929 org-reveal
8930 org-shiftdown
8931 org-shiftleft
8932 org-shiftmetadown
8933 org-shiftmetaup
8934 org-shiftright
8935 org-shifttab
8936 org-shifttab
8937 org-shiftup
8938 org-show-children
8939 org-show-subtree
8940 org-sort
8941 org-up-element
8942 outline-demote
8943 outline-next-visible-heading
8944 outline-previous-visible-heading
8945 outline-promote
8946 outline-up-heading))
8947 (let ((f (or (car-safe cell) cell))
8948 (disable-when-heading-prefix (cdr-safe cell)))
8949 (when (fboundp f)
8950 (let ((new-bindings))
8951 (dolist (binding (nconc (where-is-internal f org-mode-map)
8952 (where-is-internal f outline-mode-map)))
8953 (push binding new-bindings)
8954 ;; TODO use local-function-key-map
8955 (dolist (rep '(("<tab>" . "TAB")
8956 ("<return>" . "RET")
8957 ("<escape>" . "ESC")
8958 ("<delete>" . "DEL")))
8959 (setq binding (read-kbd-macro
8960 (let ((case-fold-search))
8961 (replace-regexp-in-string
8962 (regexp-quote (cdr rep))
8963 (car rep)
8964 (key-description binding)))))
8965 (cl-pushnew binding new-bindings :test 'equal)))
8966 (dolist (binding new-bindings)
8967 (let ((key (lookup-key orgstruct-mode-map binding)))
8968 (when (or (not key) (numberp key))
8969 (ignore-errors
8970 (org-defkey orgstruct-mode-map
8971 binding
8972 (orgstruct-make-binding
8973 f binding disable-when-heading-prefix))))))))))
8974 (run-hooks 'orgstruct-setup-hook))
8976 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8977 "Create a function for binding in the structure minor mode.
8978 FUN is the command to call inside a table. KEY is the key that
8979 should be checked in for a command to execute outside of tables.
8980 Non-nil `disable-when-heading-prefix' means to disable the command
8981 if `orgstruct-heading-prefix-regexp' is not empty."
8982 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8983 (let ((nname name)
8984 (i 0))
8985 (while (fboundp (intern nname))
8986 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8987 (setq name (intern nname)))
8988 (eval
8989 (let ((bindings '((org-heading-regexp
8990 (concat "^"
8991 orgstruct-heading-prefix-regexp
8992 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8993 (org-outline-regexp
8994 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8995 (org-outline-regexp-bol
8996 (concat "^" org-outline-regexp))
8997 (outline-regexp org-outline-regexp)
8998 (outline-heading-end-regexp "\n")
8999 (outline-level 'org-outline-level)
9000 (outline-heading-alist))))
9001 `(defun ,name (arg)
9002 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9003 "Outside of structure, run the binding of `"
9004 (key-description key) "'."
9005 (when disable-when-heading-prefix
9006 (concat
9007 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9008 "back to the default binding due to limitations of Org's implementation of\n"
9009 "`" (symbol-name fun) "'.")))
9010 (interactive "p")
9011 (let* ((disable
9012 ,(and disable-when-heading-prefix
9013 '(not (string= orgstruct-heading-prefix-regexp ""))))
9014 (fallback
9015 (or disable
9016 (not
9017 (let* ,bindings
9018 (org-context-p 'headline 'item
9019 ,(when (memq fun
9020 '(org-insert-heading
9021 org-insert-heading-respect-content
9022 org-meta-return))
9023 '(when orgstruct-is-++
9024 'item-body))))))))
9025 (if fallback
9026 (let* ((orgstruct-mode)
9027 (binding
9028 (let ((key ,key))
9029 (catch 'exit
9030 (dolist
9031 (rep
9032 '(nil
9033 ("<\\([^>]*\\)tab>" . "\\1TAB")
9034 ("<\\([^>]*\\)return>" . "\\1RET")
9035 ("<\\([^>]*\\)escape>" . "\\1ESC")
9036 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9037 nil)
9038 (when rep
9039 (setq key (read-kbd-macro
9040 (let ((case-fold-search))
9041 (replace-regexp-in-string
9042 (car rep)
9043 (cdr rep)
9044 (key-description key))))))
9045 (when (key-binding key)
9046 (throw 'exit (key-binding key))))))))
9047 (if (keymapp binding)
9048 (org-set-transient-map binding)
9049 (let ((func (or binding
9050 (unless disable
9051 'orgstruct-error))))
9052 (when func
9053 (call-interactively func)))))
9054 (org-run-like-in-org-mode
9055 (lambda ()
9056 (interactive)
9057 (let* ,bindings
9058 (call-interactively ',fun)))))))))
9059 name))
9061 (defun org-contextualize-keys (alist contexts)
9062 "Return valid elements in ALIST depending on CONTEXTS.
9064 `org-agenda-custom-commands' or `org-capture-templates' are the
9065 values used for ALIST, and `org-agenda-custom-commands-contexts'
9066 or `org-capture-templates-contexts' are the associated contexts
9067 definitions."
9068 (let ((contexts
9069 ;; normalize contexts
9070 (mapcar
9071 (lambda(c) (cond ((listp (cadr c))
9072 (list (car c) (car c) (nth 1 c)))
9073 ((string= "" (cadr c))
9074 (list (car c) (car c) (nth 2 c)))
9075 (t c)))
9076 contexts))
9077 (a alist) r s)
9078 ;; loop over all commands or templates
9079 (dolist (c a)
9080 (let (vrules repl)
9081 (cond
9082 ((not (assoc (car c) contexts))
9083 (push c r))
9084 ((and (assoc (car c) contexts)
9085 (setq vrules (org-contextualize-validate-key
9086 (car c) contexts)))
9087 (mapc (lambda (vr)
9088 (unless (equal (car vr) (cadr vr))
9089 (setq repl vr)))
9090 vrules)
9091 (if (not repl) (push c r)
9092 (push (cadr repl) s)
9093 (push
9094 (cons (car c)
9095 (cdr (or (assoc (cadr repl) alist)
9096 (error "Undefined key `%s' as contextual replacement for `%s'"
9097 (cadr repl) (car c)))))
9098 r))))))
9099 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9100 (delq
9102 (delete-dups
9103 (mapcar (lambda (x)
9104 (let ((tpl (car x)))
9105 (unless (delq
9107 (mapcar (lambda (y)
9108 (equal y tpl))
9110 x)))
9111 (reverse r))))))
9113 (defun org-contextualize-validate-key (key contexts)
9114 "Check CONTEXTS for agenda or capture KEY."
9115 (let (res)
9116 (dolist (r contexts)
9117 (dolist (rr (car (last r)))
9118 (when
9119 (and (equal key (car r))
9120 (if (functionp rr) (funcall rr)
9121 (or (and (eq (car rr) 'in-file)
9122 (buffer-file-name)
9123 (string-match (cdr rr) (buffer-file-name)))
9124 (and (eq (car rr) 'in-mode)
9125 (string-match (cdr rr) (symbol-name major-mode)))
9126 (and (eq (car rr) 'in-buffer)
9127 (string-match (cdr rr) (buffer-name)))
9128 (when (and (eq (car rr) 'not-in-file)
9129 (buffer-file-name))
9130 (not (string-match (cdr rr) (buffer-file-name))))
9131 (when (eq (car rr) 'not-in-mode)
9132 (not (string-match (cdr rr) (symbol-name major-mode))))
9133 (when (eq (car rr) 'not-in-buffer)
9134 (not (string-match (cdr rr) (buffer-name)))))))
9135 (push r res))))
9136 (delete-dups (delq nil res))))
9138 (defun org-context-p (&rest contexts)
9139 "Check if local context is any of CONTEXTS.
9140 Possible values in the list of contexts are `table', `headline', and `item'."
9141 (let ((pos (point)))
9142 (goto-char (point-at-bol))
9143 (prog1 (or (and (memq 'table contexts)
9144 (looking-at "[ \t]*|"))
9145 (and (memq 'headline contexts)
9146 (looking-at org-outline-regexp))
9147 (and (memq 'item contexts)
9148 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9149 (and (memq 'item-body contexts)
9150 (org-in-item-p)))
9151 (goto-char pos))))
9153 ;;;###autoload
9154 (defun org-run-like-in-org-mode (cmd)
9155 "Run a command, pretending that the current buffer is in Org mode.
9156 This will temporarily bind local variables that are typically bound in
9157 Org mode to the values they have in Org mode, and then interactively
9158 call CMD."
9159 (org-load-modules-maybe)
9160 (unless org-local-vars
9161 (setq org-local-vars (org-get-local-variables)))
9162 (let (binds)
9163 (dolist (var org-local-vars)
9164 (when (or (not (boundp (car var)))
9165 (eq (symbol-value (car var))
9166 (default-value (car var))))
9167 (push (list (car var) `(quote ,(cadr var))) binds)))
9168 (eval `(let ,binds
9169 (call-interactively (quote ,cmd))))))
9171 (defun org-get-category (&optional pos force-refresh)
9172 "Get the category applying to position POS."
9173 (save-match-data
9174 (when force-refresh (org-refresh-category-properties))
9175 (let ((pos (or pos (point))))
9176 (or (get-text-property pos 'org-category)
9177 (progn (org-refresh-category-properties)
9178 (get-text-property pos 'org-category))))))
9180 ;;; Refresh properties
9182 (defun org-refresh-properties (dprop tprop)
9183 "Refresh buffer text properties.
9184 DPROP is the drawer property and TPROP is either the
9185 corresponding text property to set, or an alist with each element
9186 being a text property (as a symbol) and a function to apply to
9187 the value of the drawer property."
9188 (let* ((case-fold-search t)
9189 (inhibit-read-only t)
9190 (inherit? (org-property-inherit-p dprop))
9191 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9192 (global (and inherit? (org--property-global-value dprop nil))))
9193 (org-with-silent-modifications
9194 (org-with-point-at 1
9195 ;; Set global values (e.g., values defined through
9196 ;; "#+PROPERTY:" keywords) to the whole buffer.
9197 (when global (put-text-property (point-min) (point-max) tprop global))
9198 ;; Set local values.
9199 (while (re-search-forward property-re nil t)
9200 (when (org-at-property-p)
9201 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9202 (outline-next-heading))))))
9204 (defun org-refresh-property (tprop p &optional inherit)
9205 "Refresh the buffer text property TPROP from the drawer property P.
9206 The refresh happens only for the current headline, or the whole
9207 sub-tree if optional argument INHERIT is non-nil."
9208 (unless (org-before-first-heading-p)
9209 (save-excursion
9210 (org-back-to-heading t)
9211 (let ((start (point))
9212 (end (save-excursion
9213 (if inherit (org-end-of-subtree t t)
9214 (or (outline-next-heading) (point-max))))))
9215 (if (symbolp tprop)
9216 ;; TPROP is a text property symbol.
9217 (put-text-property start end tprop p)
9218 ;; TPROP is an alist with (property . function) elements.
9219 (pcase-dolist (`(,prop . ,f) tprop)
9220 (put-text-property start end prop (funcall f p))))))))
9222 (defun org-refresh-category-properties ()
9223 "Refresh category text properties in the buffer."
9224 (let ((case-fold-search t)
9225 (inhibit-read-only t)
9226 (default-category
9227 (cond ((null org-category)
9228 (if buffer-file-name
9229 (file-name-sans-extension
9230 (file-name-nondirectory buffer-file-name))
9231 "???"))
9232 ((symbolp org-category) (symbol-name org-category))
9233 (t org-category))))
9234 (org-with-silent-modifications
9235 (org-with-wide-buffer
9236 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9237 ;; This is the default category for the buffer. If none is
9238 ;; found, fall-back to `org-category' or buffer file name.
9239 (put-text-property
9240 (point-min) (point-max)
9241 'org-category
9242 (catch 'buffer-category
9243 (goto-char (point-max))
9244 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9245 (let ((element (org-element-at-point)))
9246 (when (eq (org-element-type element) 'keyword)
9247 (throw 'buffer-category
9248 (org-element-property :value element)))))
9249 default-category))
9250 ;; Set sub-tree specific categories.
9251 (goto-char (point-min))
9252 (let ((regexp (org-re-property "CATEGORY")))
9253 (while (re-search-forward regexp nil t)
9254 (let ((value (match-string-no-properties 3)))
9255 (when (org-at-property-p)
9256 (put-text-property
9257 (save-excursion (org-back-to-heading t) (point))
9258 (save-excursion (org-end-of-subtree t t) (point))
9259 'org-category
9260 value)))))))))
9262 (defun org-refresh-stats-properties ()
9263 "Refresh stats text properties in the buffer."
9264 (org-with-silent-modifications
9265 (org-with-point-at 1
9266 (let ((regexp (concat org-outline-regexp-bol
9267 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9268 (while (re-search-forward regexp nil t)
9269 (let* ((numerator (string-to-number (match-string 1)))
9270 (denominator (and (match-end 2)
9271 (string-to-number (match-string 2))))
9272 (stats (cond ((not denominator) numerator) ;percent
9273 ((= denominator 0) 0)
9274 (t (/ (* numerator 100) denominator)))))
9275 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9276 'org-stats stats)))))))
9278 (defun org-refresh-effort-properties ()
9279 "Refresh effort properties"
9280 (org-refresh-properties
9281 org-effort-property
9282 '((effort . identity)
9283 (effort-minutes . org-duration-to-minutes))))
9285 ;;;; Link Stuff
9287 ;;; Link abbreviations
9289 (defun org-link-expand-abbrev (link)
9290 "Apply replacements as defined in `org-link-abbrev-alist'."
9291 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9292 (let* ((key (match-string 1 link))
9293 (as (or (assoc key org-link-abbrev-alist-local)
9294 (assoc key org-link-abbrev-alist)))
9295 (tag (and (match-end 2) (match-string 3 link)))
9296 rpl)
9297 (if (not as)
9298 link
9299 (setq rpl (cdr as))
9300 (cond
9301 ((symbolp rpl) (funcall rpl tag))
9302 ((string-match "%(\\([^)]+\\))" rpl)
9303 (replace-match
9304 (save-match-data
9305 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9306 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9307 ((string-match "%h" rpl)
9308 (replace-match (url-hexify-string (or tag "")) t t rpl))
9309 (t (concat rpl tag)))))
9310 link))
9312 ;;; Storing and inserting links
9314 (defvar org-insert-link-history nil
9315 "Minibuffer history for links inserted with `org-insert-link'.")
9317 (defvar org-stored-links nil
9318 "Contains the links stored with `org-store-link'.")
9320 (defvar org-store-link-plist nil
9321 "Plist with info about the most recently link created with `org-store-link'.")
9323 (defun org-store-link-functions ()
9324 "Return a list of functions that are called to create and store a link.
9325 The functions defined in the :store property of
9326 `org-link-parameters'.
9328 Each function will be called in turn until one returns a non-nil
9329 value. Each function should check if it is responsible for
9330 creating this link (for example by looking at the major mode).
9331 If not, it must exit and return nil. If yes, it should return
9332 a non-nil value after calling `org-store-link-props' with a list
9333 of properties and values. Special properties are:
9335 :type The link prefix, like \"http\". This must be given.
9336 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9337 This is obligatory as well.
9338 :description Optional default description for the second pair
9339 of brackets in an Org mode link. The user can still change
9340 this when inserting this link into an Org mode buffer.
9342 In addition to these, any additional properties can be specified
9343 and then used in capture templates."
9344 (cl-loop for link in org-link-parameters
9345 with store-func
9346 do (setq store-func (org-link-get-parameter (car link) :store))
9347 if store-func
9348 collect store-func))
9350 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9351 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9353 ;;;###autoload
9354 (defun org-store-link (arg)
9355 "Store an org-link to the current location.
9356 \\<org-mode-map>
9357 This link is added to `org-stored-links' and can later be inserted
9358 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9360 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9361 A single
9362 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9363 `org-gnus-prefer-web-links' for links to Usenet articles.
9365 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9366 skipping storing functions that are not
9367 part of Org core.
9369 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9370 prefix ARG forces storing a link for each line in the
9371 active region."
9372 (interactive "P")
9373 (org-load-modules-maybe)
9374 (if (and (equal arg '(64)) (org-region-active-p))
9375 (save-excursion
9376 (let ((end (region-end)))
9377 (goto-char (region-beginning))
9378 (set-mark (point))
9379 (while (< (point-at-eol) end)
9380 (move-end-of-line 1) (activate-mark)
9381 (let (current-prefix-arg)
9382 (call-interactively 'org-store-link))
9383 (move-beginning-of-line 2)
9384 (set-mark (point)))))
9385 (setq org-store-link-plist nil)
9386 (let (link cpltxt desc description search txt custom-id agenda-link)
9387 (cond
9388 ;; Store a link using an external link type, if any function is
9389 ;; available. If more than one can generate a link from current
9390 ;; location, ask which one to use.
9391 ((and (not (equal arg '(16)))
9392 (let ((results-alist nil))
9393 (dolist (f (org-store-link-functions))
9394 (when (funcall f)
9395 ;; XXX: return value is not link's plist, so we
9396 ;; store the new value before it is modified. It
9397 ;; would be cleaner to ask store link functions to
9398 ;; return the plist instead.
9399 (push (cons f (copy-sequence org-store-link-plist))
9400 results-alist)))
9401 (pcase results-alist
9402 (`nil nil)
9403 (`((,_ . ,_)) t) ;single choice: nothing to do
9404 (`((,name . ,_) . ,_)
9405 ;; Reinstate link plist associated to the chosen
9406 ;; function.
9407 (apply #'org-store-link-props
9408 (cdr (assoc-string
9409 (completing-read
9410 "Which function for creating the link? "
9411 (mapcar #'car results-alist) nil t name)
9412 results-alist)))
9413 t))))
9414 (setq link (plist-get org-store-link-plist :link))
9415 (setq desc (or (plist-get org-store-link-plist :description)
9416 link)))
9418 ;; Store a link from a source code buffer.
9419 ((org-src-edit-buffer-p)
9420 (let ((coderef-format (org-src-coderef-format)))
9421 (cond ((save-excursion
9422 (beginning-of-line)
9423 (looking-at (org-src-coderef-regexp coderef-format)))
9424 (setq link (format "(%s)" (match-string-no-properties 3))))
9425 ((called-interactively-p 'any)
9426 (let ((label (read-string "Code line label: ")))
9427 (end-of-line)
9428 (setq link (format coderef-format label))
9429 (let ((gc (- 79 (length link))))
9430 (if (< (current-column) gc)
9431 (org-move-to-column gc t)
9432 (insert " ")))
9433 (insert link)
9434 (setq link (concat "(" label ")"))
9435 (setq desc nil)))
9436 (t (setq link nil)))))
9438 ;; We are in the agenda, link to referenced location
9439 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9440 (let ((m (or (get-text-property (point) 'org-hd-marker)
9441 (get-text-property (point) 'org-marker))))
9442 (when m
9443 (org-with-point-at m
9444 (setq agenda-link
9445 (if (called-interactively-p 'any)
9446 (call-interactively 'org-store-link)
9447 (org-store-link nil)))))))
9449 ((eq major-mode 'calendar-mode)
9450 (let ((cd (calendar-cursor-to-date)))
9451 (setq link
9452 (format-time-string
9453 (car org-time-stamp-formats)
9454 (apply 'encode-time
9455 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9456 nil nil nil))))
9457 (org-store-link-props :type "calendar" :date cd)))
9459 ((eq major-mode 'help-mode)
9460 (setq link (concat "help:" (save-excursion
9461 (goto-char (point-min))
9462 (looking-at "^[^ ]+")
9463 (match-string 0))))
9464 (org-store-link-props :type "help"))
9466 ((eq major-mode 'w3-mode)
9467 (setq cpltxt (if (and (buffer-name)
9468 (not (string-match "Untitled" (buffer-name))))
9469 (buffer-name)
9470 (url-view-url t))
9471 link (url-view-url t))
9472 (org-store-link-props :type "w3" :url (url-view-url t)))
9474 ((eq major-mode 'image-mode)
9475 (setq cpltxt (concat "file:"
9476 (abbreviate-file-name buffer-file-name))
9477 link cpltxt)
9478 (org-store-link-props :type "image" :file buffer-file-name))
9480 ;; In dired, store a link to the file of the current line
9481 ((derived-mode-p 'dired-mode)
9482 (let ((file (dired-get-filename nil t)))
9483 (setq file (if file
9484 (abbreviate-file-name
9485 (expand-file-name (dired-get-filename nil t)))
9486 ;; otherwise, no file so use current directory.
9487 default-directory))
9488 (setq cpltxt (concat "file:" file)
9489 link cpltxt)))
9491 ((setq search (run-hook-with-args-until-success
9492 'org-create-file-search-functions))
9493 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9494 "::" search))
9495 (setq cpltxt (or description link)))
9497 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9498 (org-with-limited-levels
9499 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9500 (cond
9501 ;; Store a link using the target at point
9502 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9503 (setq cpltxt
9504 (concat "file:"
9505 (abbreviate-file-name
9506 (buffer-file-name (buffer-base-buffer)))
9507 "::" (match-string 1))
9508 link cpltxt))
9509 ((and (featurep 'org-id)
9510 (or (eq org-id-link-to-org-use-id t)
9511 (and (called-interactively-p 'any)
9512 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9513 (and (eq org-id-link-to-org-use-id
9514 'create-if-interactive-and-no-custom-id)
9515 (not custom-id))))
9516 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9517 ;; Store a link using the ID at point
9518 (setq link (condition-case nil
9519 (prog1 (org-id-store-link)
9520 (setq desc (or (plist-get org-store-link-plist
9521 :description)
9522 "")))
9523 (error
9524 ;; Probably before first headline, link only to file
9525 (concat "file:"
9526 (abbreviate-file-name
9527 (buffer-file-name (buffer-base-buffer))))))))
9529 ;; Just link to current headline
9530 (setq cpltxt (concat "file:"
9531 (abbreviate-file-name
9532 (buffer-file-name (buffer-base-buffer)))))
9533 ;; Add a context search string
9534 (when (org-xor org-context-in-file-links
9535 (equal arg '(4)))
9536 (let* ((element (org-element-at-point))
9537 (name (org-element-property :name element)))
9538 (setq txt (cond
9539 ((org-at-heading-p) nil)
9540 (name)
9541 ((org-region-active-p)
9542 (buffer-substring (region-beginning) (region-end)))))
9543 (when (or (null txt) (string-match "\\S-" txt))
9544 (setq cpltxt
9545 (concat cpltxt "::"
9546 (condition-case nil
9547 (org-make-org-heading-search-string txt)
9548 (error "")))
9549 desc (or name
9550 (nth 4 (ignore-errors (org-heading-components)))
9551 "NONE")))))
9552 (when (string-match "::\\'" cpltxt)
9553 (setq cpltxt (substring cpltxt 0 -2)))
9554 (setq link cpltxt)))))
9556 ((buffer-file-name (buffer-base-buffer))
9557 ;; Just link to this file here.
9558 (setq cpltxt (concat "file:"
9559 (abbreviate-file-name
9560 (buffer-file-name (buffer-base-buffer)))))
9561 ;; Add a context string.
9562 (when (org-xor org-context-in-file-links
9563 (equal arg '(4)))
9564 (setq txt (if (org-region-active-p)
9565 (buffer-substring (region-beginning) (region-end))
9566 (buffer-substring (point-at-bol) (point-at-eol))))
9567 ;; Only use search option if there is some text.
9568 (when (string-match "\\S-" txt)
9569 (setq cpltxt
9570 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9571 desc "NONE")))
9572 (setq link cpltxt))
9574 ((called-interactively-p 'interactive)
9575 (user-error "No method for storing a link from this buffer"))
9577 (t (setq link nil)))
9579 ;; We're done setting link and desc, clean up
9580 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9581 (setq link (or link cpltxt)
9582 desc (or desc cpltxt))
9583 (cond ((not desc))
9584 ((equal desc "NONE") (setq desc nil))
9585 (t (setq desc
9586 (replace-regexp-in-string
9587 org-bracket-link-analytic-regexp
9588 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9589 desc))))
9590 ;; Return the link
9591 (if (not (and (or (called-interactively-p 'any)
9592 executing-kbd-macro)
9593 link))
9594 (or agenda-link (and link (org-make-link-string link desc)))
9595 (push (list link desc) org-stored-links)
9596 (message "Stored: %s" (or desc link))
9597 (when custom-id
9598 (setq link (concat "file:" (abbreviate-file-name
9599 (buffer-file-name)) "::#" custom-id))
9600 (push (list link desc) org-stored-links))
9601 (car org-stored-links)))))
9603 (defun org-store-link-props (&rest plist)
9604 "Store link properties.
9605 The properties are pre-processed by extracting names, addresses
9606 and dates."
9607 (let ((x (plist-get plist :from)))
9608 (when x
9609 (let ((adr (mail-extract-address-components x)))
9610 (setq plist (plist-put plist :fromname (car adr)))
9611 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9612 (let ((x (plist-get plist :to)))
9613 (when x
9614 (let ((adr (mail-extract-address-components x)))
9615 (setq plist (plist-put plist :toname (car adr)))
9616 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9617 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9618 (when x
9619 (setq plist (plist-put plist :date-timestamp
9620 (format-time-string
9621 (org-time-stamp-format t) x)))
9622 (setq plist (plist-put plist :date-timestamp-inactive
9623 (format-time-string
9624 (org-time-stamp-format t t) x)))))
9625 (let ((from (plist-get plist :from))
9626 (to (plist-get plist :to)))
9627 (when (and from to org-from-is-user-regexp)
9628 (setq plist
9629 (plist-put plist :fromto
9630 (if (string-match org-from-is-user-regexp from)
9631 (concat "to %t")
9632 (concat "from %f"))))))
9633 (setq org-store-link-plist plist))
9635 (defun org-add-link-props (&rest plist)
9636 "Add these properties to the link property list."
9637 (let (key value)
9638 (while plist
9639 (setq key (pop plist) value (pop plist))
9640 (setq org-store-link-plist
9641 (plist-put org-store-link-plist key value)))))
9643 (defun org-email-link-description (&optional fmt)
9644 "Return the description part of an email link.
9645 This takes information from `org-store-link-plist' and formats it
9646 according to FMT (default from `org-email-link-description-format')."
9647 (setq fmt (or fmt org-email-link-description-format))
9648 (let* ((p org-store-link-plist)
9649 (to (plist-get p :toaddress))
9650 (from (plist-get p :fromaddress))
9651 (table
9652 (list
9653 (cons "%c" (plist-get p :fromto))
9654 (cons "%F" (plist-get p :from))
9655 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9656 (cons "%T" (plist-get p :to))
9657 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9658 (cons "%s" (plist-get p :subject))
9659 (cons "%d" (plist-get p :date))
9660 (cons "%m" (plist-get p :message-id)))))
9661 (when (string-match "%c" fmt)
9662 ;; Check if the user wrote this message
9663 (if (and org-from-is-user-regexp from to
9664 (save-match-data (string-match org-from-is-user-regexp from)))
9665 (setq fmt (replace-match "to %t" t t fmt))
9666 (setq fmt (replace-match "from %f" t t fmt))))
9667 (org-replace-escapes fmt table)))
9669 (defun org-make-org-heading-search-string (&optional string)
9670 "Make search string for the current headline or STRING."
9671 (let ((s (or string
9672 (and (derived-mode-p 'org-mode)
9673 (save-excursion
9674 (org-back-to-heading t)
9675 (org-element-property :raw-value (org-element-at-point))))))
9676 (lines org-context-in-file-links))
9677 (unless string (setq s (concat "*" s))) ;Add * for headlines
9678 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9679 (when (and string (integerp lines) (> lines 0))
9680 (let ((slines (org-split-string s "\n")))
9681 (when (< lines (length slines))
9682 (setq s (mapconcat
9683 'identity
9684 (reverse (nthcdr (- (length slines) lines)
9685 (reverse slines))) "\n")))))
9686 (mapconcat #'identity (split-string s) " ")))
9688 (defconst org-link-escape-chars
9689 ;;%20 %5B %5D %25
9690 '(?\s ?\[ ?\] ?%)
9691 "List of characters that should be escaped in a link when stored to Org.
9692 This is the list that is used for internal purposes.")
9694 (defun org-make-link-string (link &optional description)
9695 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9696 (unless (org-string-nw-p link) (error "Empty link"))
9697 (let ((uri (cond ((string-match org-link-types-re link)
9698 (concat (match-string 1 link)
9699 (org-link-escape (substring link (match-end 1)))))
9700 ((or (file-name-absolute-p link)
9701 (string-match-p "\\`\\.\\.?/" link))
9702 (org-link-escape link))
9703 ;; For readability, do not encode space characters
9704 ;; in fuzzy links.
9705 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9706 (description
9707 (and (org-string-nw-p description)
9708 ;; Remove brackets from description, as they are fatal.
9709 (replace-regexp-in-string
9710 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9711 (org-trim description)))))
9712 (format "[[%s]%s]"
9714 (if description (format "[%s]" description) ""))))
9716 (defun org-link-escape (text &optional table merge)
9717 "Return percent escaped representation of TEXT.
9718 TEXT is a string with the text to escape.
9719 Optional argument TABLE is a list with characters that should be
9720 escaped. When nil, `org-link-escape-chars' is used.
9721 If optional argument MERGE is set, merge TABLE into
9722 `org-link-escape-chars'."
9723 (let ((characters-to-encode
9724 (cond ((null table) org-link-escape-chars)
9725 (merge (append org-link-escape-chars table))
9726 (t table))))
9727 (mapconcat
9728 (lambda (c)
9729 (if (or (memq c characters-to-encode)
9730 (and org-url-hexify-p (or (< c 32) (> c 126))))
9731 (mapconcat (lambda (e) (format "%%%.2X" e))
9732 (or (encode-coding-char c 'utf-8)
9733 (error "Unable to percent escape character: %c" c))
9735 (char-to-string c)))
9736 text "")))
9738 (defun org-link-unescape (str)
9739 "Unhex hexified Unicode parts in string STR.
9740 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9741 reciprocal of `org-link-escape', which see."
9742 (if (org-string-nw-p str)
9743 (replace-regexp-in-string
9744 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9745 str))
9747 (defun org-link-unescape-compound (hex)
9748 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9749 Note: this function also decodes single byte encodings like
9750 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9751 (save-match-data
9752 (let* ((bytes (cdr (split-string hex "%")))
9753 (ret "")
9754 (eat 0)
9755 (sum 0))
9756 (while bytes
9757 (let* ((val (string-to-number (pop bytes) 16))
9758 (shift-xor
9759 (if (= 0 eat)
9760 (cond
9761 ((>= val 252) (cons 6 252))
9762 ((>= val 248) (cons 5 248))
9763 ((>= val 240) (cons 4 240))
9764 ((>= val 224) (cons 3 224))
9765 ((>= val 192) (cons 2 192))
9766 (t (cons 0 0)))
9767 (cons 6 128))))
9768 (when (>= val 192) (setq eat (car shift-xor)))
9769 (setq val (logxor val (cdr shift-xor)))
9770 (setq sum (+ (lsh sum (car shift-xor)) val))
9771 (when (> eat 0) (setq eat (- eat 1)))
9772 (cond
9773 ((= 0 eat) ;multi byte
9774 (setq ret (concat ret (char-to-string sum)))
9775 (setq sum 0))
9776 ((not bytes) ; single byte(s)
9777 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9778 ret)))
9780 (defun org-link-unescape-single-byte-sequence (hex)
9781 "Unhexify hex-encoded single byte character sequences."
9782 (mapconcat (lambda (byte)
9783 (char-to-string (string-to-number byte 16)))
9784 (cdr (split-string hex "%")) ""))
9786 (defun org-fixup-message-id-for-http (s)
9787 "Replace special characters in a message id, so it can be used in an http query."
9788 (when (string-match "%" s)
9789 (setq s (mapconcat (lambda (c)
9790 (if (eq c ?%)
9791 "%25"
9792 (char-to-string c)))
9793 s "")))
9794 (while (string-match "<" s)
9795 (setq s (replace-match "%3C" t t s)))
9796 (while (string-match ">" s)
9797 (setq s (replace-match "%3E" t t s)))
9798 (while (string-match "@" s)
9799 (setq s (replace-match "%40" t t s)))
9802 (defun org-link-prettify (link)
9803 "Return a human-readable representation of LINK.
9804 The car of LINK must be a raw link.
9805 The cdr of LINK must be either a link description or nil."
9806 (let ((desc (or (cadr link) "<no description>")))
9807 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9808 "<" (car link) ">")))
9810 ;;;###autoload
9811 (defun org-insert-link-global ()
9812 "Insert a link like Org mode does.
9813 This command can be called in any mode to insert a link in Org syntax."
9814 (interactive)
9815 (org-load-modules-maybe)
9816 (org-run-like-in-org-mode 'org-insert-link))
9818 (defun org-insert-all-links (arg &optional pre post)
9819 "Insert all links in `org-stored-links'.
9820 When a universal prefix, do not delete the links from `org-stored-links'.
9821 When `ARG' is a number, insert the last N link(s).
9822 `PRE' and `POST' are optional arguments to define a string to
9823 prepend or to append."
9824 (interactive "P")
9825 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9826 (links (copy-sequence org-stored-links))
9827 (pr (or pre "- "))
9828 (po (or post "\n"))
9829 (cnt 1) l)
9830 (if (null org-stored-links)
9831 (message "No link to insert")
9832 (while (and (or (listp arg) (>= arg cnt))
9833 (setq l (if (listp arg)
9834 (pop links)
9835 (pop org-stored-links))))
9836 (setq cnt (1+ cnt))
9837 (insert pr)
9838 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9839 (insert po)))))
9841 (defun org-insert-last-stored-link (arg)
9842 "Insert the last link stored in `org-stored-links'."
9843 (interactive "p")
9844 (org-insert-all-links arg "" "\n"))
9846 (defun org-link-fontify-links-to-this-file ()
9847 "Fontify links to the current file in `org-stored-links'."
9848 (let ((f (buffer-file-name)) a b)
9849 (setq a (mapcar (lambda(l)
9850 (let ((ll (car l)))
9851 (when (and (string-match "^file:\\(.+\\)::" ll)
9852 (equal f (expand-file-name (match-string 1 ll))))
9853 ll)))
9854 org-stored-links))
9855 (when (featurep 'org-id)
9856 (setq b (mapcar (lambda(l)
9857 (let ((ll (car l)))
9858 (when (and (string-match "^id:\\(.+\\)$" ll)
9859 (equal f (expand-file-name
9860 (or (org-id-find-id-file
9861 (match-string 1 ll)) ""))))
9862 ll)))
9863 org-stored-links)))
9864 (mapcar (lambda(l)
9865 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9866 (delq nil (append a b)))))
9868 (defvar org--links-history nil)
9869 (defun org-insert-link (&optional complete-file link-location default-description)
9870 "Insert a link. At the prompt, enter the link.
9872 Completion can be used to insert any of the link protocol prefixes in use.
9874 The history can be used to select a link previously stored with
9875 `org-store-link'. When the empty string is entered (i.e. if you just
9876 press `RET' at the prompt), the link defaults to the most recently
9877 stored link. As `SPC' triggers completion in the minibuffer, you need to
9878 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9880 You will also be prompted for a description, and if one is given, it will
9881 be displayed in the buffer instead of the link.
9883 If there is already a link at point, this command will allow you to edit
9884 link and description parts.
9886 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9887 file name can be
9888 selected using completion. The path to the file will be relative to the
9889 current directory if the file is in the current directory or a subdirectory.
9890 Otherwise, the link will be the absolute path as completed in the minibuffer
9891 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9892 option `org-link-file-path-type'.
9894 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9895 absolute path even if the file is in
9896 the current directory or below.
9898 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9899 prefix negates `org-keep-stored-link-after-insertion'.
9901 If the LINK-LOCATION parameter is non-nil, this value will be used as
9902 the link location instead of reading one interactively.
9904 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9905 be used as the default description. Otherwise, if
9906 `org-make-link-description-function' is non-nil, this function
9907 will be called with the link target, and the result will be the
9908 default link description. When called non-interactivily, don't
9909 allow to edit the default description."
9910 (interactive "P")
9911 (let* ((wcf (current-window-configuration))
9912 (origbuf (current-buffer))
9913 (region (when (org-region-active-p)
9914 (buffer-substring (region-beginning) (region-end))))
9915 (remove (and region (list (region-beginning) (region-end))))
9916 (desc region)
9917 (link link-location)
9918 (abbrevs org-link-abbrev-alist-local)
9919 entry all-prefixes auto-desc)
9920 (cond
9921 (link-location) ; specified by arg, just use it.
9922 ((org-in-regexp org-bracket-link-regexp 1)
9923 ;; We do have a link at point, and we are going to edit it.
9924 (setq remove (list (match-beginning 0) (match-end 0)))
9925 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9926 (setq link (read-string "Link: "
9927 (org-link-unescape
9928 (match-string-no-properties 1)))))
9929 ((or (org-in-regexp org-angle-link-re)
9930 (org-in-regexp org-plain-link-re))
9931 ;; Convert to bracket link
9932 (setq remove (list (match-beginning 0) (match-end 0))
9933 link (read-string "Link: "
9934 (org-unbracket-string "<" ">" (match-string 0)))))
9935 ((member complete-file '((4) (16)))
9936 ;; Completing read for file names.
9937 (setq link (org-file-complete-link complete-file)))
9939 ;; Read link, with completion for stored links.
9940 (org-link-fontify-links-to-this-file)
9941 (org-switch-to-buffer-other-window "*Org Links*")
9942 (with-current-buffer "*Org Links*"
9943 (erase-buffer)
9944 (insert "Insert a link.
9945 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9946 (when org-stored-links
9947 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9948 (insert (mapconcat 'org-link-prettify
9949 (reverse org-stored-links) "\n")))
9950 (goto-char (point-min)))
9951 (let ((cw (selected-window)))
9952 (select-window (get-buffer-window "*Org Links*" 'visible))
9953 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9954 (unless (pos-visible-in-window-p (point-max))
9955 (org-fit-window-to-buffer))
9956 (and (window-live-p cw) (select-window cw)))
9957 (setq all-prefixes (append (mapcar 'car abbrevs)
9958 (mapcar 'car org-link-abbrev-alist)
9959 (org-link-types)))
9960 (unwind-protect
9961 ;; Fake a link history, containing the stored links.
9962 (let ((org--links-history
9963 (append (mapcar #'car org-stored-links)
9964 org-insert-link-history)))
9965 (setq link
9966 (org-completing-read
9967 "Link: "
9968 (append
9969 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9970 (mapcar #'car org-stored-links))
9971 nil nil nil
9972 'org--links-history
9973 (caar org-stored-links)))
9974 (unless (org-string-nw-p link) (user-error "No link selected"))
9975 (dolist (l org-stored-links)
9976 (when (equal link (cadr l))
9977 (setq link (car l))
9978 (setq auto-desc t)))
9979 (when (or (member link all-prefixes)
9980 (and (equal ":" (substring link -1))
9981 (member (substring link 0 -1) all-prefixes)
9982 (setq link (substring link 0 -1))))
9983 (setq link (with-current-buffer origbuf
9984 (org-link-try-special-completion link)))))
9985 (set-window-configuration wcf)
9986 (kill-buffer "*Org Links*"))
9987 (setq entry (assoc link org-stored-links))
9988 (or entry (push link org-insert-link-history))
9989 (setq desc (or desc (nth 1 entry)))))
9991 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9992 (not org-keep-stored-link-after-insertion))
9993 (setq org-stored-links (delq (assoc link org-stored-links)
9994 org-stored-links)))
9996 (when (and (string-match org-plain-link-re link)
9997 (not (string-match org-ts-regexp link)))
9998 ;; URL-like link, normalize the use of angular brackets.
9999 (setq link (org-unbracket-string "<" ">" link)))
10001 ;; Check if we are linking to the current file with a search
10002 ;; option If yes, simplify the link by using only the search
10003 ;; option.
10004 (when (and buffer-file-name
10005 (let ((case-fold-search nil))
10006 (string-match "\\`file:\\(.+?\\)::" link)))
10007 (let ((path (match-string-no-properties 1 link))
10008 (search (substring-no-properties link (match-end 0))))
10009 (save-match-data
10010 (when (equal (file-truename buffer-file-name) (file-truename path))
10011 ;; We are linking to this same file, with a search option
10012 (setq link search)))))
10014 ;; Check if we can/should use a relative path. If yes, simplify
10015 ;; the link.
10016 (let ((case-fold-search nil))
10017 (when (string-match "\\`\\(file\\|docview\\):" link)
10018 (let* ((type (match-string-no-properties 0 link))
10019 (path-start (match-end 0))
10020 (search (and (string-match "::\\(.*\\)\\'" link)
10021 (match-string 1 link)))
10022 (path
10023 (if search
10024 (substring-no-properties
10025 link path-start (match-beginning 0))
10026 (substring-no-properties link (match-end 0))))
10027 (origpath path))
10028 (cond
10029 ((or (eq org-link-file-path-type 'absolute)
10030 (equal complete-file '(16)))
10031 (setq path (abbreviate-file-name (expand-file-name path))))
10032 ((eq org-link-file-path-type 'noabbrev)
10033 (setq path (expand-file-name path)))
10034 ((eq org-link-file-path-type 'relative)
10035 (setq path (file-relative-name path)))
10037 (save-match-data
10038 (if (string-match (concat "^" (regexp-quote
10039 (expand-file-name
10040 (file-name-as-directory
10041 default-directory))))
10042 (expand-file-name path))
10043 ;; We are linking a file with relative path name.
10044 (setq path (substring (expand-file-name path)
10045 (match-end 0)))
10046 (setq path (abbreviate-file-name (expand-file-name path)))))))
10047 (setq link (concat type path (and search (concat "::" search))))
10048 (when (equal desc origpath)
10049 (setq desc path)))))
10051 (unless auto-desc
10052 (let ((initial-input
10053 (cond
10054 (default-description)
10055 ((not org-make-link-description-function) desc)
10056 (t (condition-case nil
10057 (funcall org-make-link-description-function link desc)
10058 (error
10059 (message "Can't get link description from `%s'"
10060 (symbol-name org-make-link-description-function))
10061 (sit-for 2)
10062 nil))))))
10063 (setq desc (if (called-interactively-p 'any)
10064 (read-string "Description: " initial-input)
10065 initial-input))))
10067 (unless (string-match "\\S-" desc) (setq desc nil))
10068 (when remove (apply 'delete-region remove))
10069 (insert (org-make-link-string link desc))
10070 ;; Redisplay so as the new link has proper invisible characters.
10071 (sit-for 0)))
10073 (defun org-link-try-special-completion (type)
10074 "If there is completion support for link type TYPE, offer it."
10075 (let ((fun (org-link-get-parameter type :complete)))
10076 (if (functionp fun)
10077 (funcall fun)
10078 (read-string "Link (no completion support): " (concat type ":")))))
10080 (defun org-file-complete-link (&optional arg)
10081 "Create a file link using completion."
10082 (let ((file (read-file-name "File: "))
10083 (pwd (file-name-as-directory (expand-file-name ".")))
10084 (pwd1 (file-name-as-directory (abbreviate-file-name
10085 (expand-file-name ".")))))
10086 (cond ((equal arg '(16))
10087 (concat "file:"
10088 (abbreviate-file-name (expand-file-name file))))
10089 ((string-match
10090 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10091 (concat "file:" (match-string 1 file)))
10092 ((string-match
10093 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10094 (expand-file-name file))
10095 (concat "file:"
10096 (match-string 1 (expand-file-name file))))
10097 (t (concat "file:" file)))))
10100 ;;; Opening/following a link
10102 (defvar org-link-search-failed nil)
10104 (defvar org-open-link-functions nil
10105 "Hook for functions finding a plain text link.
10106 These functions must take a single argument, the link content.
10107 They will be called for links that look like [[link text][description]]
10108 when LINK TEXT does not have a protocol like \"http:\" and does not look
10109 like a filename (e.g. \"./blue.png\").
10111 These functions will be called *before* Org attempts to resolve the
10112 link by doing text searches in the current buffer - so if you want a
10113 link \"[[target]]\" to still find \"<<target>>\", your function should
10114 handle this as a special case.
10116 When the function does handle the link, it must return a non-nil value.
10117 If it decides that it is not responsible for this link, it must return
10118 nil to indicate that that Org can continue with other options like
10119 exact and fuzzy text search.")
10121 (defun org-next-link (&optional search-backward)
10122 "Move forward to the next link.
10123 If the link is in hidden text, expose it."
10124 (interactive "P")
10125 (when (and org-link-search-failed (eq this-command last-command))
10126 (goto-char (point-min))
10127 (message "Link search wrapped back to beginning of buffer"))
10128 (setq org-link-search-failed nil)
10129 (let* ((pos (point))
10130 (ct (org-context))
10131 (a (assq :link ct))
10132 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10133 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10134 ((looking-at org-any-link-re)
10135 ;; Don't stay stuck at link without an org-link face
10136 (forward-char (if search-backward -1 1))))
10137 (if (funcall srch-fun org-any-link-re nil t)
10138 (progn
10139 (goto-char (match-beginning 0))
10140 (when (org-invisible-p) (org-show-context)))
10141 (goto-char pos)
10142 (setq org-link-search-failed t)
10143 (message "No further link found"))))
10145 (defun org-previous-link ()
10146 "Move backward to the previous link.
10147 If the link is in hidden text, expose it."
10148 (interactive)
10149 (funcall 'org-next-link t))
10151 (defun org-translate-link (s)
10152 "Translate a link string if a translation function has been defined."
10153 (with-temp-buffer
10154 (insert (org-trim s))
10155 (org-trim (org-element-interpret-data (org-element-context)))))
10157 (defun org-translate-link-from-planner (type path)
10158 "Translate a link from Emacs Planner syntax so that Org can follow it.
10159 This is still an experimental function, your mileage may vary."
10160 (cond
10161 ((member type '("http" "https" "news" "ftp"))
10162 ;; standard Internet links are the same.
10163 nil)
10164 ((and (equal type "irc") (string-match "^//" path))
10165 ;; Planner has two / at the beginning of an irc link, we have 1.
10166 ;; We should have zero, actually....
10167 (setq path (substring path 1)))
10168 ((and (equal type "lisp") (string-match "^/" path))
10169 ;; Planner has a slash, we do not.
10170 (setq type "elisp" path (substring path 1)))
10171 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10172 ;; A typical message link. Planner has the id after the final slash,
10173 ;; we separate it with a hash mark
10174 (setq path (concat (match-string 1 path) "#"
10175 (org-unbracket-string "<" ">" (match-string 2 path))))))
10176 (cons type path))
10178 (defun org-find-file-at-mouse (ev)
10179 "Open file link or URL at mouse."
10180 (interactive "e")
10181 (mouse-set-point ev)
10182 (org-open-at-point 'in-emacs))
10184 (defun org-open-at-mouse (ev)
10185 "Open file link or URL at mouse.
10186 See the docstring of `org-open-file' for details."
10187 (interactive "e")
10188 (mouse-set-point ev)
10189 (when (eq major-mode 'org-agenda-mode)
10190 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10191 (org-open-at-point))
10193 (defvar org-window-config-before-follow-link nil
10194 "The window configuration before following a link.
10195 This is saved in case the need arises to restore it.")
10197 ;;;###autoload
10198 (defun org-open-at-point-global ()
10199 "Follow a link or time-stamp like Org mode does.
10200 This command can be called in any mode to follow an external link
10201 or a time-stamp that has Org mode syntax. Its behavior is
10202 undefined when called on internal links (e.g., fuzzy links).
10203 Raise an error when there is nothing to follow. "
10204 (interactive)
10205 (cond ((org-in-regexp org-any-link-re)
10206 (org-open-link-from-string (match-string-no-properties 0)))
10207 ((or (org-in-regexp org-ts-regexp-both nil t)
10208 (org-in-regexp org-tsr-regexp-both nil t))
10209 (org-follow-timestamp-link))
10210 (t (user-error "No link found"))))
10212 ;;;###autoload
10213 (defun org-open-link-from-string (s &optional arg reference-buffer)
10214 "Open a link in the string S, as if it was in Org mode."
10215 (interactive "sLink: \nP")
10216 (let ((reference-buffer (or reference-buffer (current-buffer))))
10217 (with-temp-buffer
10218 (let ((org-inhibit-startup (not reference-buffer)))
10219 (org-mode)
10220 (insert s)
10221 (goto-char (point-min))
10222 (when reference-buffer
10223 (setq org-link-abbrev-alist-local
10224 (with-current-buffer reference-buffer
10225 org-link-abbrev-alist-local)))
10226 (org-open-at-point arg reference-buffer)))))
10228 (defvar org-open-at-point-functions nil
10229 "Hook that is run when following a link at point.
10231 Functions in this hook must return t if they identify and follow
10232 a link at point. If they don't find anything interesting at point,
10233 they must return nil.")
10235 (defvar org-link-search-inhibit-query nil)
10236 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10237 (defun org--open-doi-link (path)
10238 "Open a \"doi\" type link.
10239 PATH is a the path to search for, as a string."
10240 (browse-url (url-encode-url (concat org-doi-server-url path))))
10242 (defun org--open-elisp-link (path)
10243 "Open a \"elisp\" type link.
10244 PATH is the sexp to evaluate, as a string."
10245 (let ((cmd path))
10246 (if (or (and (org-string-nw-p
10247 org-confirm-elisp-link-not-regexp)
10248 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10249 (not org-confirm-elisp-link-function)
10250 (funcall org-confirm-elisp-link-function
10251 (format "Execute \"%s\" as elisp? "
10252 (org-add-props cmd nil 'face 'org-warning))))
10253 (message "%s => %s" cmd
10254 (if (eq (string-to-char cmd) ?\()
10255 (eval (read cmd))
10256 (call-interactively (read cmd))))
10257 (user-error "Abort"))))
10259 (defun org--open-help-link (path)
10260 "Open a \"help\" type link.
10261 PATH is a symbol name, as a string."
10262 (pcase (intern path)
10263 ((and (pred fboundp) variable) (describe-function variable))
10264 ((and (pred boundp) function) (describe-variable function))
10265 (name (user-error "Unknown function or variable: %s" name))))
10267 (defun org--open-shell-link (path)
10268 "Open a \"shell\" type link.
10269 PATH is the command to execute, as a string."
10270 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10271 (cmd path))
10272 (if (or (and (org-string-nw-p
10273 org-confirm-shell-link-not-regexp)
10274 (string-match
10275 org-confirm-shell-link-not-regexp cmd))
10276 (not org-confirm-shell-link-function)
10277 (funcall org-confirm-shell-link-function
10278 (format "Execute \"%s\" in shell? "
10279 (org-add-props cmd nil
10280 'face 'org-warning))))
10281 (progn
10282 (message "Executing %s" cmd)
10283 (shell-command cmd buf)
10284 (when (featurep 'midnight)
10285 (setq clean-buffer-list-kill-buffer-names
10286 (cons (buffer-name buf)
10287 clean-buffer-list-kill-buffer-names))))
10288 (user-error "Abort"))))
10290 (defun org-open-at-point (&optional arg reference-buffer)
10291 "Open link, timestamp, footnote or tags at point.
10293 When point is on a link, follow it. Normally, files will be
10294 opened by an appropriate application. If the optional prefix
10295 argument ARG is non-nil, Emacs will visit the file. With
10296 a double prefix argument, try to open outside of Emacs, in the
10297 application the system uses for this file type.
10299 When point is on a timestamp, open the agenda at the day
10300 specified.
10302 When point is a footnote definition, move to the first reference
10303 found. If it is on a reference, move to the associated
10304 definition.
10306 When point is on a headline, display a list of every link in the
10307 entry, so it is possible to pick one, or all, of them. If point
10308 is on a tag, call `org-tags-view' instead.
10310 When optional argument REFERENCE-BUFFER is non-nil, it should
10311 specify a buffer from where the link search should happen. This
10312 is used internally by `org-open-link-from-string'.
10314 On top of syntactically correct links, this function will also
10315 try to open links and time-stamps in comments, example
10316 blocks... i.e., whenever point is on something looking like
10317 a timestamp or a link."
10318 (interactive "P")
10319 ;; On a code block, open block's results.
10320 (unless (call-interactively 'org-babel-open-src-block-result)
10321 (org-load-modules-maybe)
10322 (setq org-window-config-before-follow-link (current-window-configuration))
10323 (org-remove-occur-highlights nil nil t)
10324 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10325 (let* ((context
10326 ;; Only consider supported types, even if they are not
10327 ;; the closest one.
10328 (org-element-lineage
10329 (org-element-context)
10330 '(clock footnote-definition footnote-reference headline
10331 inlinetask link timestamp)
10333 (type (org-element-type context))
10334 (value (org-element-property :value context)))
10335 (cond
10336 ;; On a headline or an inlinetask, but not on a timestamp,
10337 ;; a link, a footnote reference.
10338 ((memq type '(headline inlinetask))
10339 (org-match-line org-complex-heading-regexp)
10340 (if (and (match-beginning 5)
10341 (>= (point) (match-beginning 5))
10342 (< (point) (match-end 5)))
10343 ;; On tags.
10344 (org-tags-view arg (substring (match-string 5) 0 -1))
10345 ;; Not on tags.
10346 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10347 (`(nil . ,_)
10348 (require 'org-attach)
10349 (org-attach-reveal 'if-exists))
10350 (`(,links . ,links-end)
10351 (dolist (link (if (stringp links) (list links) links))
10352 (search-forward link nil links-end)
10353 (goto-char (match-beginning 0))
10354 (org-open-at-point))))))
10355 ;; On a footnote reference or at definition's label.
10356 ((or (eq type 'footnote-reference)
10357 (and (eq type 'footnote-definition)
10358 (save-excursion
10359 ;; Do not validate action when point is on the
10360 ;; spaces right after the footnote label, in
10361 ;; order to be on par with behaviour on links.
10362 (skip-chars-forward " \t")
10363 (let ((begin
10364 (org-element-property :contents-begin context)))
10365 (if begin (< (point) begin)
10366 (= (org-element-property :post-affiliated context)
10367 (line-beginning-position)))))))
10368 (org-footnote-action))
10369 ;; No valid context. Ignore catch-all types like `headline'.
10370 ;; If point is on something looking like a link or
10371 ;; a time-stamp, try opening it. It may be useful in
10372 ;; comments, example blocks...
10373 ((memq type '(footnote-definition headline inlinetask nil))
10374 (call-interactively #'org-open-at-point-global))
10375 ;; On a clock line, make sure point is on the timestamp
10376 ;; before opening it.
10377 ((and (eq type 'clock)
10378 value
10379 (>= (point) (org-element-property :begin value))
10380 (<= (point) (org-element-property :end value)))
10381 (org-follow-timestamp-link))
10382 ;; Do nothing on white spaces after an object.
10383 ((>= (point)
10384 (save-excursion
10385 (goto-char (org-element-property :end context))
10386 (skip-chars-backward " \t")
10387 (point)))
10388 (user-error "No link found"))
10389 ((eq type 'timestamp) (org-follow-timestamp-link))
10390 ((eq type 'link)
10391 (let ((type (org-element-property :type context))
10392 (path (org-link-unescape (org-element-property :path context))))
10393 ;; Switch back to REFERENCE-BUFFER needed when called in
10394 ;; a temporary buffer through `org-open-link-from-string'.
10395 (with-current-buffer (or reference-buffer (current-buffer))
10396 (cond
10397 ((equal type "file")
10398 (if (string-match "[*?{]" (file-name-nondirectory path))
10399 (dired path)
10400 ;; Look into `org-link-parameters' in order to find
10401 ;; a DEDICATED-FUNCTION to open file. The function
10402 ;; will be applied on raw link instead of parsed
10403 ;; link due to the limitation in `org-add-link-type'
10404 ;; ("open" function called with a single argument).
10405 ;; If no such function is found, fallback to
10406 ;; `org-open-file'.
10407 (let* ((option (org-element-property :search-option context))
10408 (app (org-element-property :application context))
10409 (dedicated-function
10410 (org-link-get-parameter
10411 (if app (concat type "+" app) type)
10412 :follow)))
10413 (if dedicated-function
10414 (funcall dedicated-function
10415 (concat path
10416 (and option (concat "::" option))))
10417 (apply #'org-open-file
10418 path
10419 (cond (arg)
10420 ((equal app "emacs") 'emacs)
10421 ((equal app "sys") 'system))
10422 (cond ((not option) nil)
10423 ((string-match-p "\\`[0-9]+\\'" option)
10424 (list (string-to-number option)))
10425 (t (list nil
10426 (org-link-unescape option)))))))))
10427 ((functionp (org-link-get-parameter type :follow))
10428 (funcall (org-link-get-parameter type :follow) path))
10429 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10430 (unless (run-hook-with-args-until-success
10431 'org-open-link-functions path)
10432 (if (not arg) (org-mark-ring-push)
10433 (switch-to-buffer-other-window
10434 (org-get-buffer-for-internal-link (current-buffer))))
10435 (let ((destination
10436 (org-with-wide-buffer
10437 (if (equal type "radio")
10438 (org-search-radio-target
10439 (org-element-property :path context))
10440 (org-link-search
10441 (if (member type '("custom-id" "coderef"))
10442 (org-element-property :raw-link context)
10443 path)
10444 ;; Prevent fuzzy links from matching
10445 ;; themselves.
10446 (and (equal type "fuzzy")
10447 (+ 2 (org-element-property :begin context)))))
10448 (point))))
10449 (unless (and (<= (point-min) destination)
10450 (>= (point-max) destination))
10451 (widen))
10452 (goto-char destination))))
10453 (t (browse-url-at-point))))))
10454 (t (user-error "No link found")))))
10455 (run-hook-with-args 'org-follow-link-hook)))
10457 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10458 "Offer links in the current entry and return the selected link.
10459 If there is only one link, return it.
10460 If NTH is an integer, return the NTH link found.
10461 If ZERO is a string, check also this string for a link, and if
10462 there is one, return it."
10463 (with-current-buffer buffer
10464 (org-with-wide-buffer
10465 (goto-char marker)
10466 (let ((cnt ?0)
10467 have-zero end links link c)
10468 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10469 (push (match-string 0 zero) links)
10470 (setq cnt (1- cnt) have-zero t))
10471 (save-excursion
10472 (org-back-to-heading t)
10473 (setq end (save-excursion (outline-next-heading) (point)))
10474 (while (re-search-forward org-any-link-re end t)
10475 (push (match-string 0) links))
10476 (setq links (org-uniquify (reverse links))))
10477 (cond
10478 ((null links)
10479 (message "No links"))
10480 ((equal (length links) 1)
10481 (setq link (car links)))
10482 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10483 (setq link (nth (if have-zero nth (1- nth)) links)))
10484 (t ; we have to select a link
10485 (save-excursion
10486 (save-window-excursion
10487 (delete-other-windows)
10488 (with-output-to-temp-buffer "*Select Link*"
10489 (dolist (l links)
10490 (cond
10491 ((not (string-match org-bracket-link-regexp l))
10492 (princ (format "[%c] %s\n" (cl-incf cnt)
10493 (org-unbracket-string "<" ">" l))))
10494 ((match-end 3)
10495 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10496 (match-string 3 l) (match-string 1 l))))
10497 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10498 (match-string 1 l)))))))
10499 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10500 (message "Select link to open, RET to open all:")
10501 (setq c (read-char-exclusive))
10502 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10503 (when (equal c ?q) (user-error "Abort"))
10504 (if (equal c ?\C-m)
10505 (setq link links)
10506 (setq nth (- c ?0))
10507 (when have-zero (setq nth (1+ nth)))
10508 (unless (and (integerp nth) (>= (length links) nth))
10509 (user-error "Invalid link selection"))
10510 (setq link (nth (1- nth) links)))))
10511 (cons link end)))))
10513 ;; TODO: These functions are deprecated since `org-open-at-point'
10514 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10515 (defun org-open-file-with-system (path)
10516 "Open file at PATH using the system way of opening it."
10517 (org-open-file path 'system))
10518 (defun org-open-file-with-emacs (path)
10519 "Open file at PATH in Emacs."
10520 (org-open-file path 'emacs))
10523 ;;; File search
10525 (defvar org-create-file-search-functions nil
10526 "List of functions to construct the right search string for a file link.
10527 These functions are called in turn with point at the location to
10528 which the link should point.
10530 A function in the hook should first test if it would like to
10531 handle this file type, for example by checking the `major-mode'
10532 or the file extension. If it decides not to handle this file, it
10533 should just return nil to give other functions a chance. If it
10534 does handle the file, it must return the search string to be used
10535 when following the link. The search string will be part of the
10536 file link, given after a double colon, and `org-open-at-point'
10537 will automatically search for it. If special measures must be
10538 taken to make the search successful, another function should be
10539 added to the companion hook `org-execute-file-search-functions',
10540 which see.
10542 A function in this hook may also use `setq' to set the variable
10543 `description' to provide a suggestion for the descriptive text to
10544 be used for this link when it gets inserted into an Org buffer
10545 with \\[org-insert-link].")
10547 (defvar org-execute-file-search-functions nil
10548 "List of functions to execute a file search triggered by a link.
10550 Functions added to this hook must accept a single argument, the
10551 search string that was part of the file link, the part after the
10552 double colon. The function must first check if it would like to
10553 handle this search, for example by checking the `major-mode' or
10554 the file extension. If it decides not to handle this search, it
10555 should just return nil to give other functions a chance. If it
10556 does handle the search, it must return a non-nil value to keep
10557 other functions from trying.
10559 Each function can access the current prefix argument through the
10560 variable `current-prefix-arg'. Note that a single prefix is used
10561 to force opening a link in Emacs, so it may be good to only use a
10562 numeric or double prefix to guide the search function.
10564 In case this is needed, a function in this hook can also restore
10565 the window configuration before `org-open-at-point' was called using:
10567 (set-window-configuration org-window-config-before-follow-link)")
10569 (defun org-search-radio-target (target)
10570 "Search a radio target matching TARGET in current buffer.
10571 White spaces are not significant."
10572 (let ((re (format "<<<%s>>>"
10573 (mapconcat #'regexp-quote
10574 (split-string target)
10575 "[ \t]+\\(?:\n[ \t]*\\)?")))
10576 (origin (point)))
10577 (goto-char (point-min))
10578 (catch :radio-match
10579 (while (re-search-forward re nil t)
10580 (backward-char)
10581 (let ((object (org-element-context)))
10582 (when (eq (org-element-type object) 'radio-target)
10583 (goto-char (org-element-property :begin object))
10584 (org-show-context 'link-search)
10585 (throw :radio-match nil))))
10586 (goto-char origin)
10587 (user-error "No match for radio target: %s" target))))
10589 (defun org-link-search (s &optional avoid-pos stealth)
10590 "Search for a search string S.
10592 If S starts with \"#\", it triggers a custom ID search.
10594 If S is enclosed within parenthesis, it initiates a coderef
10595 search.
10597 If S is surrounded by forward slashes, it is interpreted as
10598 a regular expression. In Org mode files, this will create an
10599 `org-occur' sparse tree. In ordinary files, `occur' will be used
10600 to list matches. If the current buffer is in `dired-mode', grep
10601 will be used to search in all files.
10603 When AVOID-POS is given, ignore matches near that position.
10605 When optional argument STEALTH is non-nil, do not modify
10606 visibility around point, thus ignoring `org-show-context-detail'
10607 variable.
10609 Search is case-insensitive and ignores white spaces. Return type
10610 of matched result, which is either `dedicated' or `fuzzy'."
10611 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10612 (let* ((case-fold-search t)
10613 (origin (point))
10614 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10615 (starred (eq (string-to-char normalized) ?*))
10616 (words (split-string (if starred (substring s 1) s)))
10617 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10618 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10619 type)
10620 (cond
10621 ;; Check if there are any special search functions.
10622 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10623 ((eq (string-to-char s) ?#)
10624 ;; Look for a custom ID S if S starts with "#".
10625 (let* ((id (substring normalized 1))
10626 (match (org-find-property "CUSTOM_ID" id)))
10627 (if match (progn (goto-char match) (setf type 'dedicated))
10628 (error "No match for custom ID: %s" id))))
10629 ((string-match "\\`(\\(.*\\))\\'" normalized)
10630 ;; Look for coderef targets if S is enclosed within parenthesis.
10631 (let ((coderef (match-string-no-properties 1 normalized))
10632 (re (substring s-single-re 1 -1)))
10633 (goto-char (point-min))
10634 (catch :coderef-match
10635 (while (re-search-forward re nil t)
10636 (let ((element (org-element-at-point)))
10637 (when (and (memq (org-element-type element)
10638 '(example-block src-block))
10639 ;; Build proper regexp according to current
10640 ;; block's label format.
10641 (let ((label-fmt
10642 (regexp-quote
10643 (or (org-element-property :label-fmt element)
10644 org-coderef-label-format))))
10645 (save-excursion
10646 (beginning-of-line)
10647 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10648 (format label-fmt coderef))))))
10649 (setq type 'dedicated)
10650 (goto-char (match-beginning 1))
10651 (throw :coderef-match nil))))
10652 (goto-char origin)
10653 (error "No match for coderef: %s" coderef))))
10654 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10655 ;; Look for a regular expression.
10656 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10657 (match-string 1 s)))
10658 ;; From here, we handle fuzzy links.
10660 ;; Look for targets, only if not in a headline search.
10661 ((and (not starred)
10662 (let ((target (format "<<%s>>" s-multi-re)))
10663 (catch :target-match
10664 (goto-char (point-min))
10665 (while (re-search-forward target nil t)
10666 (backward-char)
10667 (let ((context (org-element-context)))
10668 (when (eq (org-element-type context) 'target)
10669 (setq type 'dedicated)
10670 (goto-char (org-element-property :begin context))
10671 (throw :target-match t))))
10672 nil))))
10673 ;; Look for elements named after S, only if not in a headline
10674 ;; search.
10675 ((and (not starred)
10676 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10677 (catch :name-match
10678 (goto-char (point-min))
10679 (while (re-search-forward name nil t)
10680 (let ((element (org-element-at-point)))
10681 (when (equal words
10682 (split-string
10683 (org-element-property :name element)))
10684 (setq type 'dedicated)
10685 (beginning-of-line)
10686 (throw :name-match t))))
10687 nil))))
10688 ;; Regular text search. Prefer headlines in Org mode buffers.
10689 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10690 ;; statistics cookies and tags.
10691 ((and (derived-mode-p 'org-mode)
10692 (let ((title-re
10693 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10694 org-outline-regexp-bol
10695 org-comment-string
10696 (mapconcat #'regexp-quote words ".+")))
10697 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10698 (comment-re (eval-when-compile
10699 (format "\\`%s[ \t]+" org-comment-string))))
10700 (goto-char (point-min))
10701 (catch :found
10702 (while (re-search-forward title-re nil t)
10703 (when (equal words
10704 (split-string
10705 (replace-regexp-in-string
10706 cookie-re ""
10707 (replace-regexp-in-string
10708 comment-re "" (org-get-heading t t t)))))
10709 (throw :found t)))
10710 nil)))
10711 (beginning-of-line)
10712 (setq type 'dedicated))
10713 ;; Offer to create non-existent headline depending on
10714 ;; `org-link-search-must-match-exact-headline'.
10715 ((and (derived-mode-p 'org-mode)
10716 (not org-link-search-inhibit-query)
10717 (eq org-link-search-must-match-exact-headline 'query-to-create)
10718 (yes-or-no-p "No match - create this as a new heading? "))
10719 (goto-char (point-max))
10720 (unless (bolp) (newline))
10721 (org-insert-heading nil t t)
10722 (insert s "\n")
10723 (beginning-of-line 0))
10724 ;; Only headlines are looked after. No need to process
10725 ;; further: throw an error.
10726 ((and (derived-mode-p 'org-mode)
10727 (or starred org-link-search-must-match-exact-headline))
10728 (goto-char origin)
10729 (error "No match for fuzzy expression: %s" normalized))
10730 ;; Regular text search.
10731 ((catch :fuzzy-match
10732 (goto-char (point-min))
10733 (while (re-search-forward s-multi-re nil t)
10734 ;; Skip match if it contains AVOID-POS or it is included in
10735 ;; a link with a description but outside the description.
10736 (unless (or (and avoid-pos
10737 (<= (match-beginning 0) avoid-pos)
10738 (> (match-end 0) avoid-pos))
10739 (and (save-match-data
10740 (org-in-regexp org-bracket-link-regexp))
10741 (match-beginning 3)
10742 (or (> (match-beginning 3) (point))
10743 (<= (match-end 3) (point)))
10744 (org-element-lineage
10745 (save-match-data (org-element-context))
10746 '(link) t)))
10747 (goto-char (match-beginning 0))
10748 (setq type 'fuzzy)
10749 (throw :fuzzy-match t)))
10750 nil))
10751 ;; All failed. Throw an error.
10752 (t (goto-char origin)
10753 (error "No match for fuzzy expression: %s" normalized)))
10754 ;; Disclose surroundings of match, if appropriate.
10755 (when (and (derived-mode-p 'org-mode) (not stealth))
10756 (org-show-context 'link-search))
10757 type))
10759 (defun org-get-buffer-for-internal-link (buffer)
10760 "Return a buffer to be used for displaying the link target of internal links."
10761 (cond
10762 ((not org-display-internal-link-with-indirect-buffer)
10763 buffer)
10764 ((string-suffix-p "(Clone)" (buffer-name buffer))
10765 (message "Buffer is already a clone, not making another one")
10766 ;; we also do not modify visibility in this case
10767 buffer)
10768 (t ; make a new indirect buffer for displaying the link
10769 (let* ((bn (buffer-name buffer))
10770 (ibn (concat bn "(Clone)"))
10771 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10772 (with-current-buffer ib (org-overview))
10773 ib))))
10775 (defun org-do-occur (regexp &optional cleanup)
10776 "Call the Emacs command `occur'.
10777 If CLEANUP is non-nil, remove the printout of the regular expression
10778 in the *Occur* buffer. This is useful if the regex is long and not useful
10779 to read."
10780 (occur regexp)
10781 (when cleanup
10782 (let ((cwin (selected-window)) win beg end)
10783 (when (setq win (get-buffer-window "*Occur*"))
10784 (select-window win))
10785 (goto-char (point-min))
10786 (when (re-search-forward "match[a-z]+" nil t)
10787 (setq beg (match-end 0))
10788 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10789 (setq end (1- (match-beginning 0)))))
10790 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10791 (goto-char (point-min))
10792 (select-window cwin))))
10794 ;;; The mark ring for links jumps
10796 (defvar org-mark-ring nil
10797 "Mark ring for positions before jumps in Org mode.")
10798 (defvar org-mark-ring-last-goto nil
10799 "Last position in the mark ring used to go back.")
10800 ;; Fill and close the ring
10801 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10802 (dotimes (_ org-mark-ring-length)
10803 (push (make-marker) org-mark-ring))
10804 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10805 org-mark-ring)
10807 (defun org-mark-ring-push (&optional pos buffer)
10808 "Put the current position or POS into the mark ring and rotate it."
10809 (interactive)
10810 (setq pos (or pos (point)))
10811 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10812 (move-marker (car org-mark-ring)
10813 (or pos (point))
10814 (or buffer (current-buffer)))
10815 (message "%s"
10816 (substitute-command-keys
10817 "Position saved to mark ring, go back with \
10818 `\\[org-mark-ring-goto]'.")))
10820 (defun org-mark-ring-goto (&optional n)
10821 "Jump to the previous position in the mark ring.
10822 With prefix arg N, jump back that many stored positions. When
10823 called several times in succession, walk through the entire ring.
10824 Org mode commands jumping to a different position in the current file,
10825 or to another Org file, automatically push the old position onto the ring."
10826 (interactive "p")
10827 (let (p m)
10828 (if (eq last-command this-command)
10829 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10830 (setq p org-mark-ring))
10831 (setq org-mark-ring-last-goto p)
10832 (setq m (car p))
10833 (pop-to-buffer-same-window (marker-buffer m))
10834 (goto-char m)
10835 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10837 (defun org-add-angle-brackets (s)
10838 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10839 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10842 ;;; Following specific links
10844 (defvar org-agenda-buffer-tmp-name)
10845 (defvar org-agenda-start-on-weekday)
10846 (defun org-follow-timestamp-link ()
10847 "Open an agenda view for the time-stamp date/range at point."
10848 (cond
10849 ((org-at-date-range-p t)
10850 (let ((org-agenda-start-on-weekday)
10851 (t1 (match-string 1))
10852 (t2 (match-string 2)) tt1 tt2)
10853 (setq tt1 (time-to-days (org-time-string-to-time t1))
10854 tt2 (time-to-days (org-time-string-to-time t2)))
10855 (let ((org-agenda-buffer-tmp-name
10856 (format "*Org Agenda(a:%s)"
10857 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10858 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10859 ((org-at-timestamp-p 'lax)
10860 (let ((org-agenda-buffer-tmp-name
10861 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10862 (org-agenda-list nil (time-to-days (org-time-string-to-time
10863 (substring (match-string 1) 0 10)))
10864 1)))
10865 (t (error "This should not happen"))))
10868 ;;; Following file links
10869 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10870 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10871 (declare-function mailcap-mime-info
10872 "mailcap" (string &optional request no-decode))
10873 (defvar org-wait nil)
10874 (defun org-open-file (path &optional in-emacs line search)
10875 "Open the file at PATH.
10876 First, this expands any special file name abbreviations. Then the
10877 configuration variable `org-file-apps' is checked if it contains an
10878 entry for this file type, and if yes, the corresponding command is launched.
10880 If no application is found, Emacs simply visits the file.
10882 With optional prefix argument IN-EMACS, Emacs will visit the file.
10883 With a double \\[universal-argument] \\[universal-argument] \
10884 prefix arg, Org tries to avoid opening in Emacs
10885 and to use an external application to visit the file.
10887 Optional LINE specifies a line to go to, optional SEARCH a string
10888 to search for. If LINE or SEARCH is given, the file will be
10889 opened in Emacs, unless an entry from org-file-apps that makes
10890 use of groups in a regexp matches.
10892 If you want to change the way frames are used when following a
10893 link, please customize `org-link-frame-setup'.
10895 If the file does not exist, an error is thrown."
10896 (let* ((file (if (equal path "")
10897 buffer-file-name
10898 (substitute-in-file-name (expand-file-name path))))
10899 (file-apps (append org-file-apps (org-default-apps)))
10900 (apps (cl-remove-if
10901 'org-file-apps-entry-match-against-dlink-p file-apps))
10902 (apps-dlink (cl-remove-if-not
10903 'org-file-apps-entry-match-against-dlink-p file-apps))
10904 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10905 (dirp (unless remp (file-directory-p file)))
10906 (file (if (and dirp org-open-directory-means-index-dot-org)
10907 (concat (file-name-as-directory file) "index.org")
10908 file))
10909 (a-m-a-p (assq 'auto-mode apps))
10910 (dfile (downcase file))
10911 ;; Reconstruct the original link from the PATH, LINE and
10912 ;; SEARCH args.
10913 (link (cond (line (concat file "::" (number-to-string line)))
10914 (search (concat file "::" search))
10915 (t file)))
10916 (dlink (downcase link))
10917 (ext
10918 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10919 (match-string 1 dfile)))
10920 (save-position-maybe
10921 (let ((old-buffer (current-buffer))
10922 (old-pos (point))
10923 (old-mode major-mode))
10924 (lambda ()
10925 (and (derived-mode-p 'org-mode)
10926 (eq old-mode 'org-mode)
10927 (or (not (eq old-buffer (current-buffer)))
10928 (not (eq old-pos (point))))
10929 (org-mark-ring-push old-pos old-buffer)))))
10930 cmd link-match-data)
10931 (cond
10932 ((member in-emacs '((16) system))
10933 (setq cmd (cdr (assq 'system apps))))
10934 (in-emacs (setq cmd 'emacs))
10936 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10937 (and dirp (cdr (assq 'directory apps)))
10938 ;; First, try matching against apps-dlink if we
10939 ;; get a match here, store the match data for
10940 ;; later.
10941 (let ((match (assoc-default dlink apps-dlink
10942 'string-match)))
10943 (if match
10944 (progn (setq link-match-data (match-data))
10945 match)
10946 (progn (setq in-emacs (or in-emacs line search))
10947 nil))) ; if we have no match in apps-dlink,
10948 ; always open the file in emacs if line or search
10949 ; is given (for backwards compatibility)
10950 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10951 'string-match)
10952 (cdr (assoc ext apps))
10953 (cdr (assq t apps))))))
10954 (when (eq cmd 'system)
10955 (setq cmd (cdr (assq 'system apps))))
10956 (when (eq cmd 'default)
10957 (setq cmd (cdr (assoc t apps))))
10958 (when (eq cmd 'mailcap)
10959 (require 'mailcap)
10960 (mailcap-parse-mailcaps)
10961 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10962 (command (mailcap-mime-info mime-type)))
10963 (if (stringp command)
10964 (setq cmd command)
10965 (setq cmd 'emacs))))
10966 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10967 (not (file-exists-p file))
10968 (not org-open-non-existing-files))
10969 (user-error "No such file: %s" file))
10970 (cond
10971 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10972 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10973 (while (string-match "['\"]%s['\"]" cmd)
10974 (setq cmd (replace-match "%s" t t cmd)))
10975 (setq cmd (replace-regexp-in-string
10976 "%s"
10977 (shell-quote-argument (convert-standard-filename file))
10979 nil t))
10981 ;; Replace "%1", "%2" etc. in command with group matches from regex
10982 (save-match-data
10983 (let ((match-index 1)
10984 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10985 (set-match-data link-match-data)
10986 (while (<= match-index number-of-groups)
10987 (let ((regex (concat "%" (number-to-string match-index)))
10988 (replace-with (match-string match-index dlink)))
10989 (while (string-match regex cmd)
10990 (setq cmd (replace-match replace-with t t cmd))))
10991 (setq match-index (+ match-index 1)))))
10993 (save-window-excursion
10994 (message "Running %s...done" cmd)
10995 (start-process-shell-command cmd nil cmd)
10996 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10997 ((or (stringp cmd)
10998 (eq cmd 'emacs))
10999 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11000 (widen)
11001 (cond (line (org-goto-line line)
11002 (when (derived-mode-p 'org-mode) (org-reveal)))
11003 (search (condition-case err
11004 (org-link-search search)
11005 ;; Save position before error-ing out so user
11006 ;; can easily move back to the original buffer.
11007 (error (funcall save-position-maybe)
11008 (error (nth 1 err)))))))
11009 ((functionp cmd)
11010 (save-match-data
11011 (set-match-data link-match-data)
11012 (condition-case nil
11013 (funcall cmd file link)
11014 ;; FIXME: Remove this check when most default installations
11015 ;; of Emacs have at least Org 9.0.
11016 ((debug wrong-number-of-arguments wrong-type-argument
11017 invalid-function)
11018 (user-error "Please see Org News for version 9.0 about \
11019 `org-file-apps'--Lisp error: %S" cmd)))))
11020 ((consp cmd)
11021 ;; FIXME: Remove this check when most default installations of
11022 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11023 ;; fall back to `org-link-frame-setup' for an old usage of
11024 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11025 (user-error "Please see Org News for version 9.0 about \
11026 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11027 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11028 (funcall save-position-maybe)))
11030 (defun org-file-apps-entry-match-against-dlink-p (entry)
11031 "This function returns non-nil if `entry' uses a regular
11032 expression which should be matched against the whole link by
11033 org-open-file.
11035 It assumes that is the case when the entry uses a regular
11036 expression which has at least one grouping construct and the
11037 action is either a lisp form or a command string containing
11038 `%1', i.e. using at least one subexpression match as a
11039 parameter."
11040 (let ((selector (car entry))
11041 (action (cdr entry)))
11042 (if (stringp selector)
11043 (and (> (regexp-opt-depth selector) 0)
11044 (or (and (stringp action)
11045 (string-match "%[0-9]" action))
11046 (consp action)))
11047 nil)))
11049 (defun org-default-apps ()
11050 "Return the default applications for this operating system."
11051 (cond
11052 ((eq system-type 'darwin)
11053 org-file-apps-defaults-macosx)
11054 ((eq system-type 'windows-nt)
11055 org-file-apps-defaults-windowsnt)
11056 (t org-file-apps-defaults-gnu)))
11058 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11059 "Convert extensions to regular expressions in the cars of LIST.
11060 Also, weed out any non-string entries, because the return value is used
11061 only for regexp matching.
11062 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11063 point to the symbol `emacs', indicating that the file should
11064 be opened in Emacs."
11065 (append
11066 (delq nil
11067 (mapcar (lambda (x)
11068 (unless (not (stringp (car x)))
11069 (if (string-match "\\W" (car x))
11071 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11072 list))
11073 (when add-auto-mode
11074 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11076 (defvar ange-ftp-name-format)
11077 (defun org-file-remote-p (file)
11078 "Test whether FILE specifies a location on a remote system.
11079 Return non-nil if the location is indeed remote.
11081 For example, the filename \"/user@host:/foo\" specifies a location
11082 on the system \"/user@host:\"."
11083 (cond ((fboundp 'file-remote-p)
11084 (file-remote-p file))
11085 ((fboundp 'tramp-handle-file-remote-p)
11086 (tramp-handle-file-remote-p file))
11087 ((and (boundp 'ange-ftp-name-format)
11088 (string-match (car ange-ftp-name-format) file))
11089 t)))
11092 ;;;; Refiling
11094 (defun org-get-org-file ()
11095 "Read a filename, with default directory `org-directory'."
11096 (let ((default (or org-default-notes-file remember-data-file)))
11097 (read-file-name (format "File name [%s]: " default)
11098 (file-name-as-directory org-directory)
11099 default)))
11101 (defun org-notes-order-reversed-p ()
11102 "Check if the current file should receive notes in reversed order."
11103 (cond
11104 ((not org-reverse-note-order) nil)
11105 ((eq t org-reverse-note-order) t)
11106 ((not (listp org-reverse-note-order)) nil)
11107 (t (catch 'exit
11108 (dolist (entry org-reverse-note-order)
11109 (when (string-match (car entry) buffer-file-name)
11110 (throw 'exit (cdr entry))))))))
11112 (defvar org-refile-target-table nil
11113 "The list of refile targets, created by `org-refile'.")
11115 (defvar org-agenda-new-buffers nil
11116 "Buffers created to visit agenda files.")
11118 (defvar org-refile-cache nil
11119 "Cache for refile targets.")
11121 (defvar org-refile-markers nil
11122 "All the markers used for caching refile locations.")
11124 (defun org-refile-marker (pos)
11125 "Get a new refile marker, but only if caching is in use."
11126 (if (not org-refile-use-cache)
11128 (let ((m (make-marker)))
11129 (move-marker m pos)
11130 (push m org-refile-markers)
11131 m)))
11133 (defun org-refile-cache-clear ()
11134 "Clear the refile cache and disable all the markers."
11135 (dolist (m org-refile-markers) (move-marker m nil))
11136 (setq org-refile-markers nil)
11137 (setq org-refile-cache nil)
11138 (message "Refile cache has been cleared"))
11140 (defun org-refile-cache-check-set (set)
11141 "Check if all the markers in the cache still have live buffers."
11142 (let (marker)
11143 (catch 'exit
11144 (while (and set (setq marker (nth 3 (pop set))))
11145 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11146 (when (and marker (null (marker-buffer marker)))
11147 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11148 (sit-for 3)
11149 (throw 'exit nil)))
11150 t)))
11152 (defun org-refile-cache-put (set &rest identifiers)
11153 "Push the refile targets SET into the cache, under IDENTIFIERS."
11154 (let* ((key (sha1 (prin1-to-string identifiers)))
11155 (entry (assoc key org-refile-cache)))
11156 (if entry
11157 (setcdr entry set)
11158 (push (cons key set) org-refile-cache))))
11160 (defun org-refile-cache-get (&rest identifiers)
11161 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11162 (cond
11163 ((not org-refile-cache) nil)
11164 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11166 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11167 org-refile-cache))))
11168 (and set (org-refile-cache-check-set set) set)))))
11170 (defvar org-outline-path-cache nil
11171 "Alist between buffer positions and outline paths.
11172 It value is an alist (POSITION . PATH) where POSITION is the
11173 buffer position at the beginning of an entry and PATH is a list
11174 of strings describing the outline path for that entry, in reverse
11175 order.")
11177 (defun org-refile-get-targets (&optional default-buffer)
11178 "Produce a table with refile targets."
11179 (let ((case-fold-search nil)
11180 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11181 (entries (or org-refile-targets '((nil . (:level . 1)))))
11182 targets tgs files desc descre)
11183 (message "Getting targets...")
11184 (with-current-buffer (or default-buffer (current-buffer))
11185 (dolist (entry entries)
11186 (setq files (car entry) desc (cdr entry))
11187 (cond
11188 ((null files) (setq files (list (current-buffer))))
11189 ((eq files 'org-agenda-files)
11190 (setq files (org-agenda-files 'unrestricted)))
11191 ((and (symbolp files) (fboundp files))
11192 (setq files (funcall files)))
11193 ((and (symbolp files) (boundp files))
11194 (setq files (symbol-value files))))
11195 (when (stringp files) (setq files (list files)))
11196 (cond
11197 ((eq (car desc) :tag)
11198 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11199 ((eq (car desc) :todo)
11200 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11201 ((eq (car desc) :regexp)
11202 (setq descre (cdr desc)))
11203 ((eq (car desc) :level)
11204 (setq descre (concat "^\\*\\{" (number-to-string
11205 (if org-odd-levels-only
11206 (1- (* 2 (cdr desc)))
11207 (cdr desc)))
11208 "\\}[ \t]")))
11209 ((eq (car desc) :maxlevel)
11210 (setq descre (concat "^\\*\\{1," (number-to-string
11211 (if org-odd-levels-only
11212 (1- (* 2 (cdr desc)))
11213 (cdr desc)))
11214 "\\}[ \t]")))
11215 (t (error "Bad refiling target description %s" desc)))
11216 (dolist (f files)
11217 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11219 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11220 (progn
11221 (when (bufferp f)
11222 (setq f (buffer-file-name (buffer-base-buffer f))))
11223 (setq f (and f (expand-file-name f)))
11224 (when (eq org-refile-use-outline-path 'file)
11225 (push (list (file-name-nondirectory f) f nil nil) tgs))
11226 (when (eq org-refile-use-outline-path 'buffer-name)
11227 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11228 (when (eq org-refile-use-outline-path 'full-file-path)
11229 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11230 (org-with-wide-buffer
11231 (goto-char (point-min))
11232 (setq org-outline-path-cache nil)
11233 (while (re-search-forward descre nil t)
11234 (beginning-of-line)
11235 (let ((case-fold-search nil))
11236 (looking-at org-complex-heading-regexp))
11237 (let ((begin (point))
11238 (heading (match-string-no-properties 4)))
11239 (unless (or (and
11240 org-refile-target-verify-function
11241 (not
11242 (funcall org-refile-target-verify-function)))
11243 (not heading))
11244 (let ((re (format org-complex-heading-regexp-format
11245 (regexp-quote heading)))
11246 (target
11247 (if (not org-refile-use-outline-path) heading
11248 (mapconcat
11249 #'identity
11250 (append
11251 (pcase org-refile-use-outline-path
11252 (`file (list (file-name-nondirectory
11253 (buffer-file-name
11254 (buffer-base-buffer)))))
11255 (`full-file-path
11256 (list (buffer-file-name
11257 (buffer-base-buffer))))
11258 (`buffer-name
11259 (list (buffer-name
11260 (buffer-base-buffer))))
11261 (_ nil))
11262 (mapcar (lambda (s) (replace-regexp-in-string
11263 "/" "\\/" s nil t))
11264 (org-get-outline-path t t)))
11265 "/"))))
11266 (push (list target f re (org-refile-marker (point)))
11267 tgs)))
11268 (when (= (point) begin)
11269 ;; Verification function has not moved point.
11270 (end-of-line)))))))
11271 (when org-refile-use-cache
11272 (org-refile-cache-put tgs (buffer-file-name) descre))
11273 (setq targets (append tgs targets))))))
11274 (message "Getting targets...done")
11275 (delete-dups (nreverse targets))))
11277 (defun org--get-outline-path-1 (&optional use-cache)
11278 "Return outline path to current headline.
11280 Outline path is a list of strings, in reverse order. When
11281 optional argument USE-CACHE is non-nil, make use of a cache. See
11282 `org-get-outline-path' for details.
11284 Assume buffer is widened and point is on a headline."
11285 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11286 (let ((p (point))
11287 (heading (let ((case-fold-search nil))
11288 (looking-at org-complex-heading-regexp)
11289 (if (not (match-end 4)) ""
11290 ;; Remove statistics cookies.
11291 (org-trim
11292 (org-link-display-format
11293 (replace-regexp-in-string
11294 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11295 (match-string-no-properties 4))))))))
11296 (if (org-up-heading-safe)
11297 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11298 (when use-cache
11299 (push (cons p path) org-outline-path-cache))
11300 path)
11301 ;; This is a new root node. Since we assume we are moving
11302 ;; forward, we can drop previous cache so as to limit number
11303 ;; of associations there.
11304 (let ((path (list heading)))
11305 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11306 path)))))
11308 (defun org-get-outline-path (&optional with-self use-cache)
11309 "Return the outline path to the current entry.
11311 An outline path is a list of ancestors for current headline, as
11312 a list of strings. Statistics cookies are removed and links are
11313 replaced with their description, if any, or their path otherwise.
11315 When optional argument WITH-SELF is non-nil, the path also
11316 includes the current headline.
11318 When optional argument USE-CACHE is non-nil, cache outline paths
11319 between calls to this function so as to avoid backtracking. This
11320 argument is useful when planning to find more than one outline
11321 path in the same document. In that case, there are two
11322 conditions to satisfy:
11323 - `org-outline-path-cache' is set to nil before starting the
11324 process;
11325 - outline paths are computed by increasing buffer positions."
11326 (org-with-wide-buffer
11327 (and (or (and with-self (org-back-to-heading t))
11328 (org-up-heading-safe))
11329 (reverse (org--get-outline-path-1 use-cache)))))
11331 (defun org-format-outline-path (path &optional width prefix separator)
11332 "Format the outline path PATH for display.
11333 WIDTH is the maximum number of characters that is available.
11334 PREFIX is a prefix to be included in the returned string,
11335 such as the file name.
11336 SEPARATOR is inserted between the different parts of the path,
11337 the default is \"/\"."
11338 (setq width (or width 79))
11339 (setq path (delq nil path))
11340 (unless (> width 0)
11341 (user-error "Argument `width' must be positive"))
11342 (setq separator (or separator "/"))
11343 (let* ((org-odd-levels-only nil)
11344 (fpath (concat
11345 prefix (and prefix path separator)
11346 (mapconcat
11347 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11348 (cl-loop for head in path
11349 for n from 0
11350 collect (org-add-props
11351 head nil 'face
11352 (nth (% n org-n-level-faces) org-level-faces)))
11353 separator))))
11354 (when (> (length fpath) width)
11355 (if (< width 7)
11356 ;; It's unlikely that `width' will be this small, but don't
11357 ;; waste characters by adding ".." if it is.
11358 (setq fpath (substring fpath 0 width))
11359 (setf (substring fpath (- width 2)) "..")))
11360 fpath))
11362 (defun org-display-outline-path (&optional file current separator just-return-string)
11363 "Display the current outline path in the echo area.
11365 If FILE is non-nil, prepend the output with the file name.
11366 If CURRENT is non-nil, append the current heading to the output.
11367 SEPARATOR is passed through to `org-format-outline-path'. It separates
11368 the different parts of the path and defaults to \"/\".
11369 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11370 (interactive "P")
11371 (let* (case-fold-search
11372 (bfn (buffer-file-name (buffer-base-buffer)))
11373 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11374 res)
11375 (when current (setq path (append path
11376 (save-excursion
11377 (org-back-to-heading t)
11378 (when (looking-at org-complex-heading-regexp)
11379 (list (match-string 4)))))))
11380 (setq res
11381 (org-format-outline-path
11382 path
11383 (1- (frame-width))
11384 (and file bfn (concat (file-name-nondirectory bfn) separator))
11385 separator))
11386 (if just-return-string
11387 (org-no-properties res)
11388 (org-unlogged-message "%s" res))))
11390 (defvar org-refile-history nil
11391 "History for refiling operations.")
11393 (defvar org-after-refile-insert-hook nil
11394 "Hook run after `org-refile' has inserted its stuff at the new location.
11395 Note that this is still *before* the stuff will be removed from
11396 the *old* location.")
11398 (defvar org-capture-last-stored-marker)
11399 (defvar org-refile-keep nil
11400 "Non-nil means `org-refile' will copy instead of refile.")
11402 (defun org-copy ()
11403 "Like `org-refile', but copy."
11404 (interactive)
11405 (let ((org-refile-keep t))
11406 (funcall 'org-refile nil nil nil "Copy")))
11408 (defun org-refile (&optional arg default-buffer rfloc msg)
11409 "Move the entry or entries at point to another heading.
11411 The list of target headings is compiled using the information in
11412 `org-refile-targets', which see.
11414 At the target location, the entry is filed as a subitem of the
11415 target heading. Depending on `org-reverse-note-order', the new
11416 subitem will either be the first or the last subitem.
11418 If there is an active region, all entries in that region will be
11419 refiled. However, the region must fulfill the requirement that
11420 the first heading sets the top-level of the moved text.
11422 With a `\\[universal-argument]' ARG, the command will only visit the target \
11423 location
11424 and not actually move anything.
11426 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11427 location where the last
11428 refiling operation has put the subtree.
11430 With a numeric prefix argument of `2', refile to the running clock.
11432 With a numeric prefix argument of `3', emulate `org-refile-keep'
11433 being set to t and copy to the target location, don't move it.
11434 Beware that keeping refiled entries may result in duplicated ID
11435 properties.
11437 RFLOC can be a refile location obtained in a different way.
11439 MSG is a string to replace \"Refile\" in the default prompt with
11440 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11442 See also `org-refile-use-outline-path'.
11444 If you are using target caching (see `org-refile-use-cache'), you
11445 have to clear the target cache in order to find new targets.
11446 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11447 prefix argument (`C-u C-u C-u C-c C-w')."
11448 (interactive "P")
11449 (if (member arg '(0 (64)))
11450 (org-refile-cache-clear)
11451 (let* ((actionmsg (cond (msg msg)
11452 ((equal arg 3) "Refile (and keep)")
11453 (t "Refile")))
11454 (regionp (org-region-active-p))
11455 (region-start (and regionp (region-beginning)))
11456 (region-end (and regionp (region-end)))
11457 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11458 pos it nbuf file level reversed)
11459 (setq last-command nil)
11460 (when regionp
11461 (goto-char region-start)
11462 (or (bolp) (goto-char (point-at-bol)))
11463 (setq region-start (point))
11464 (unless (or (org-kill-is-subtree-p
11465 (buffer-substring region-start region-end))
11466 (prog1 org-refile-active-region-within-subtree
11467 (let ((s (point-at-eol)))
11468 (org-toggle-heading)
11469 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11470 (user-error "The region is not a (sequence of) subtree(s)")))
11471 (if (equal arg '(16))
11472 (org-refile-goto-last-stored)
11473 (when (or
11474 (and (equal arg 2)
11475 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11476 (prog1
11477 (setq it (list (or org-clock-heading "running clock")
11478 (buffer-file-name
11479 (marker-buffer org-clock-hd-marker))
11481 (marker-position org-clock-hd-marker)))
11482 (setq arg nil)))
11483 (setq it
11484 (or rfloc
11485 (let (heading-text)
11486 (save-excursion
11487 (unless (and arg (listp arg))
11488 (org-back-to-heading t)
11489 (setq heading-text
11490 (replace-regexp-in-string
11491 org-bracket-link-regexp
11492 "\\3"
11493 (or (nth 4 (org-heading-components))
11494 ""))))
11495 (org-refile-get-location
11496 (cond ((and arg (listp arg)) "Goto")
11497 (regionp (concat actionmsg " region to"))
11498 (t (concat actionmsg " subtree \""
11499 heading-text "\" to")))
11500 default-buffer
11501 (and (not (equal '(4) arg))
11502 org-refile-allow-creating-parent-nodes)))))))
11503 (setq file (nth 1 it)
11504 pos (nth 3 it))
11505 (when (and (not arg)
11507 (equal (buffer-file-name) file)
11508 (if regionp
11509 (and (>= pos region-start)
11510 (<= pos region-end))
11511 (and (>= pos (point))
11512 (< pos (save-excursion
11513 (org-end-of-subtree t t))))))
11514 (error "Cannot refile to position inside the tree or region"))
11515 (setq nbuf (or (find-buffer-visiting file)
11516 (find-file-noselect file)))
11517 (if (and arg (not (equal arg 3)))
11518 (progn
11519 (pop-to-buffer-same-window nbuf)
11520 (goto-char (cond (pos)
11521 ((org-notes-order-reversed-p) (point-min))
11522 (t (point-max))))
11523 (org-show-context 'org-goto))
11524 (if regionp
11525 (progn
11526 (org-kill-new (buffer-substring region-start region-end))
11527 (org-save-markers-in-region region-start region-end))
11528 (org-copy-subtree 1 nil t))
11529 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11530 (find-file-noselect file)))
11531 (setq reversed (org-notes-order-reversed-p))
11532 (org-with-wide-buffer
11533 (if pos
11534 (progn
11535 (goto-char pos)
11536 (setq level (org-get-valid-level (funcall outline-level) 1))
11537 (goto-char
11538 (if reversed
11539 (or (outline-next-heading) (point-max))
11540 (or (save-excursion (org-get-next-sibling))
11541 (org-end-of-subtree t t)
11542 (point-max)))))
11543 (setq level 1)
11544 (if (not reversed)
11545 (goto-char (point-max))
11546 (goto-char (point-min))
11547 (or (outline-next-heading) (goto-char (point-max)))))
11548 (unless (bolp) (newline))
11549 (org-paste-subtree level nil nil t)
11550 (when org-log-refile
11551 (org-add-log-setup 'refile nil nil org-log-refile)
11552 (unless (eq org-log-refile 'note)
11553 (save-excursion (org-add-log-note))))
11554 (and org-auto-align-tags
11555 (let ((org-loop-over-headlines-in-active-region nil))
11556 (org-set-tags nil t)))
11557 (let ((bookmark-name (plist-get org-bookmark-names-plist
11558 :last-refile)))
11559 (when bookmark-name
11560 (with-demoted-errors
11561 (bookmark-set bookmark-name))))
11562 ;; If we are refiling for capture, make sure that the
11563 ;; last-capture pointers point here
11564 (when (bound-and-true-p org-capture-is-refiling)
11565 (let ((bookmark-name (plist-get org-bookmark-names-plist
11566 :last-capture-marker)))
11567 (when bookmark-name
11568 (with-demoted-errors
11569 (bookmark-set bookmark-name))))
11570 (move-marker org-capture-last-stored-marker (point)))
11571 (when (fboundp 'deactivate-mark) (deactivate-mark))
11572 (run-hooks 'org-after-refile-insert-hook)))
11573 (unless org-refile-keep
11574 (if regionp
11575 (delete-region (point) (+ (point) (- region-end region-start)))
11576 (org-preserve-local-variables
11577 (delete-region
11578 (and (org-back-to-heading t) (point))
11579 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11580 (when (featurep 'org-inlinetask)
11581 (org-inlinetask-remove-END-maybe))
11582 (setq org-markers-to-move nil)
11583 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11585 (defun org-refile-goto-last-stored ()
11586 "Go to the location where the last refile was stored."
11587 (interactive)
11588 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11589 (message "This is the location of the last refile"))
11591 (defun org-refile--get-location (refloc tbl)
11592 "When user refile to REFLOC, find the associated target in TBL.
11593 Also check `org-refile-target-table'."
11594 (car (delq
11596 (mapcar
11597 (lambda (r) (or (assoc r tbl)
11598 (assoc r org-refile-target-table)))
11599 (list (replace-regexp-in-string "/$" "" refloc)
11600 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11602 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11603 "Prompt the user for a refile location, using PROMPT.
11604 PROMPT should not be suffixed with a colon and a space, because
11605 this function appends the default value from
11606 `org-refile-history' automatically, if that is not empty."
11607 (let ((org-refile-targets org-refile-targets)
11608 (org-refile-use-outline-path org-refile-use-outline-path))
11609 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11610 (unless org-refile-target-table
11611 (user-error "No refile targets"))
11612 (let* ((cbuf (current-buffer))
11613 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11614 (cfunc (if (and org-refile-use-outline-path
11615 org-outline-path-complete-in-steps)
11616 #'org-olpath-completing-read
11617 #'completing-read))
11618 (extra (if org-refile-use-outline-path "/" ""))
11619 (cbnex (concat (buffer-name) extra))
11620 (filename (and cfn (expand-file-name cfn)))
11621 (tbl (mapcar
11622 (lambda (x)
11623 (if (and (not (member org-refile-use-outline-path
11624 '(file full-file-path)))
11625 (not (equal filename (nth 1 x))))
11626 (cons (concat (car x) extra " ("
11627 (file-name-nondirectory (nth 1 x)) ")")
11628 (cdr x))
11629 (cons (concat (car x) extra) (cdr x))))
11630 org-refile-target-table))
11631 (completion-ignore-case t)
11632 cdef
11633 (prompt (concat prompt
11634 (or (and (car org-refile-history)
11635 (concat " (default " (car org-refile-history) ")"))
11636 (and (assoc cbnex tbl) (setq cdef cbnex)
11637 (concat " (default " cbnex ")"))) ": "))
11638 pa answ parent-target child parent old-hist)
11639 (setq old-hist org-refile-history)
11640 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11641 nil 'org-refile-history (or cdef (car org-refile-history))))
11642 (if (setq pa (org-refile--get-location answ tbl))
11643 (progn
11644 (org-refile-check-position pa)
11645 (when (or (not org-refile-history)
11646 (not (eq old-hist org-refile-history))
11647 (not (equal (car pa) (car org-refile-history))))
11648 (setq org-refile-history
11649 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11650 org-refile-history
11651 (cdr org-refile-history))))
11652 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11653 (pop org-refile-history)))
11655 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11656 (progn
11657 (setq parent (match-string 1 answ)
11658 child (match-string 2 answ))
11659 (setq parent-target (org-refile--get-location parent tbl))
11660 (when (and parent-target
11661 (or (eq new-nodes t)
11662 (and (eq new-nodes 'confirm)
11663 (y-or-n-p (format "Create new node \"%s\"? "
11664 child)))))
11665 (org-refile-new-child parent-target child)))
11666 (user-error "Invalid target location")))))
11668 (declare-function org-string-nw-p "org-macs" (s))
11669 (defun org-refile-check-position (refile-pointer)
11670 "Check if the refile pointer matches the headline to which it points."
11671 (let* ((file (nth 1 refile-pointer))
11672 (re (nth 2 refile-pointer))
11673 (pos (nth 3 refile-pointer))
11674 buffer)
11675 (if (and (not (markerp pos)) (not file))
11676 (user-error "Please indicate a target file in the refile path")
11677 (when (org-string-nw-p re)
11678 (setq buffer (if (markerp pos)
11679 (marker-buffer pos)
11680 (or (find-buffer-visiting file)
11681 (find-file-noselect file))))
11682 (with-current-buffer buffer
11683 (org-with-wide-buffer
11684 (goto-char pos)
11685 (beginning-of-line 1)
11686 (unless (looking-at-p re)
11687 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11689 (defun org-refile-new-child (parent-target child)
11690 "Use refile target PARENT-TARGET to add new CHILD below it."
11691 (unless parent-target
11692 (error "Cannot find parent for new node"))
11693 (let ((file (nth 1 parent-target))
11694 (pos (nth 3 parent-target))
11695 level)
11696 (with-current-buffer (or (find-buffer-visiting file)
11697 (find-file-noselect file))
11698 (org-with-wide-buffer
11699 (if pos
11700 (goto-char pos)
11701 (goto-char (point-max))
11702 (unless (bolp) (newline)))
11703 (when (looking-at org-outline-regexp)
11704 (setq level (funcall outline-level))
11705 (org-end-of-subtree t t))
11706 (org-back-over-empty-lines)
11707 (insert "\n" (make-string
11708 (if pos (org-get-valid-level level 1) 1) ?*)
11709 " " child "\n")
11710 (beginning-of-line 0)
11711 (list (concat (car parent-target) "/" child) file "" (point))))))
11713 (defun org-olpath-completing-read (prompt collection &rest args)
11714 "Read an outline path like a file name."
11715 (let ((thetable collection))
11716 (apply #'completing-read
11717 prompt
11718 (lambda (string predicate &optional flag)
11719 (cond
11720 ((eq flag nil) (try-completion string thetable))
11721 ((eq flag t)
11722 (let ((l (length string)))
11723 (mapcar (lambda (x)
11724 (let ((r (substring x l))
11725 (f (if (string-match " ([^)]*)$" x)
11726 (match-string 0 x)
11727 "")))
11728 (if (string-match "/" r)
11729 (concat string (substring r 0 (match-end 0)) f)
11730 x)))
11731 (all-completions string thetable predicate))))
11732 ;; Exact match?
11733 ((eq flag 'lambda) (assoc string thetable))))
11734 args)))
11736 ;;;; Dynamic blocks
11738 (defun org-find-dblock (name)
11739 "Find the first dynamic block with name NAME in the buffer.
11740 If not found, stay at current position and return nil."
11741 (let ((case-fold-search t) pos)
11742 (save-excursion
11743 (goto-char (point-min))
11744 (setq pos (and (re-search-forward
11745 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11746 (match-beginning 0))))
11747 (when pos (goto-char pos))
11748 pos))
11750 (defun org-create-dblock (plist)
11751 "Create a dynamic block section, with parameters taken from PLIST.
11752 PLIST must contain a :name entry which is used as the name of the block."
11753 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11754 (end-of-line 1)
11755 (newline))
11756 (let ((col (current-column))
11757 (name (plist-get plist :name)))
11758 (insert "#+BEGIN: " name)
11759 (while plist
11760 (if (eq (car plist) :name)
11761 (setq plist (cddr plist))
11762 (insert " " (prin1-to-string (pop plist)))))
11763 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11764 (beginning-of-line -2)))
11766 (defun org-prepare-dblock ()
11767 "Prepare dynamic block for refresh.
11768 This empties the block, puts the cursor at the insert position and returns
11769 the property list including an extra property :name with the block name."
11770 (unless (looking-at org-dblock-start-re)
11771 (user-error "Not at a dynamic block"))
11772 (let* ((begdel (1+ (match-end 0)))
11773 (name (org-no-properties (match-string 1)))
11774 (params (append (list :name name)
11775 (read (concat "(" (match-string 3) ")")))))
11776 (save-excursion
11777 (beginning-of-line 1)
11778 (skip-chars-forward " \t")
11779 (setq params (plist-put params :indentation-column (current-column))))
11780 (unless (re-search-forward org-dblock-end-re nil t)
11781 (error "Dynamic block not terminated"))
11782 (setq params
11783 (append params
11784 (list :content (buffer-substring
11785 begdel (match-beginning 0)))))
11786 (delete-region begdel (match-beginning 0))
11787 (goto-char begdel)
11788 (open-line 1)
11789 params))
11791 (defun org-map-dblocks (&optional command)
11792 "Apply COMMAND to all dynamic blocks in the current buffer.
11793 If COMMAND is not given, use `org-update-dblock'."
11794 (let ((cmd (or command 'org-update-dblock)))
11795 (save-excursion
11796 (goto-char (point-min))
11797 (while (re-search-forward org-dblock-start-re nil t)
11798 (goto-char (match-beginning 0))
11799 (save-excursion
11800 (condition-case nil
11801 (funcall cmd)
11802 (error (message "Error during update of dynamic block"))))
11803 (unless (re-search-forward org-dblock-end-re nil t)
11804 (error "Dynamic block not terminated"))))))
11806 (defun org-dblock-update (&optional arg)
11807 "User command for updating dynamic blocks.
11808 Update the dynamic block at point. With prefix ARG, update all dynamic
11809 blocks in the buffer."
11810 (interactive "P")
11811 (if arg
11812 (org-update-all-dblocks)
11813 (or (looking-at org-dblock-start-re)
11814 (org-beginning-of-dblock))
11815 (org-update-dblock)))
11817 (defun org-update-dblock ()
11818 "Update the dynamic block at point.
11819 This means to empty the block, parse for parameters and then call
11820 the correct writing function."
11821 (interactive)
11822 (save-excursion
11823 (let* ((win (selected-window))
11824 (pos (point))
11825 (line (org-current-line))
11826 (params (org-prepare-dblock))
11827 (name (plist-get params :name))
11828 (indent (plist-get params :indentation-column))
11829 (cmd (intern (concat "org-dblock-write:" name))))
11830 (message "Updating dynamic block `%s' at line %d..." name line)
11831 (funcall cmd params)
11832 (message "Updating dynamic block `%s' at line %d...done" name line)
11833 (goto-char pos)
11834 (when (and indent (> indent 0))
11835 (setq indent (make-string indent ?\ ))
11836 (save-excursion
11837 (select-window win)
11838 (org-beginning-of-dblock)
11839 (forward-line 1)
11840 (while (not (looking-at org-dblock-end-re))
11841 (insert indent)
11842 (beginning-of-line 2))
11843 (when (looking-at org-dblock-end-re)
11844 (and (looking-at "[ \t]+")
11845 (replace-match ""))
11846 (insert indent)))))))
11848 (defun org-beginning-of-dblock ()
11849 "Find the beginning of the dynamic block at point.
11850 Error if there is no such block at point."
11851 (let ((pos (point))
11852 beg)
11853 (end-of-line 1)
11854 (if (and (re-search-backward org-dblock-start-re nil t)
11855 (setq beg (match-beginning 0))
11856 (re-search-forward org-dblock-end-re nil t)
11857 (> (match-end 0) pos))
11858 (goto-char beg)
11859 (goto-char pos)
11860 (error "Not in a dynamic block"))))
11862 (defun org-update-all-dblocks ()
11863 "Update all dynamic blocks in the buffer.
11864 This function can be used in a hook."
11865 (interactive)
11866 (when (derived-mode-p 'org-mode)
11867 (org-map-dblocks 'org-update-dblock)))
11870 ;;;; Completion
11872 (declare-function org-export-backend-options "ox" (cl-x) t)
11873 (defun org-get-export-keywords ()
11874 "Return a list of all currently understood export keywords.
11875 Export keywords include options, block names, attributes and
11876 keywords relative to each registered export back-end."
11877 (let (keywords)
11878 (dolist (backend
11879 (bound-and-true-p org-export-registered-backends)
11880 (delq nil keywords))
11881 ;; Back-end name (for keywords, like #+LATEX:)
11882 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11883 (dolist (option-entry (org-export-backend-options backend))
11884 ;; Back-end options.
11885 (push (nth 1 option-entry) keywords)))))
11887 (defconst org-options-keywords
11888 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11889 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11890 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11891 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11892 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11894 (defcustom org-structure-template-alist
11895 '((?a . "export ascii")
11896 (?c . "center")
11897 (?C . "comment")
11898 (?e . "example")
11899 (?E . "export")
11900 (?h . "export html")
11901 (?l . "export latex")
11902 (?q . "quote")
11903 (?s . "src")
11904 (?v . "verse"))
11905 "Structure completion elements.
11906 This is an alist of characters and values. When
11907 `org-insert-structure-template' is called, an additional key is
11908 read. The key is first looked up in this alist, and the
11909 corresponding structure is inserted, with \"#+BEGIN_\" and
11910 \"#+END_\" added automatically."
11911 :group 'org-edit-structure
11912 :type '(repeat
11913 (cons (character :tag "Key")
11914 (string :tag "Template")))
11915 :package-version '(Org . "9.2"))
11917 (defun org-insert-structure-template (type)
11918 "Insert a block structure of the type #+begin_foo/#+end_foo.
11919 First read a character, which can be one of the keys in
11920 `org-structure-template-alist'. When it is <TAB>, prompt the
11921 user for a string to use. With an active region, wrap the region
11922 in the block. Otherwise, insert an empty block."
11923 (interactive
11924 (list
11925 (let* ((key (read-key "Key: "))
11926 (struct-string
11927 (or (cdr (assq key org-structure-template-alist))
11928 (and (= key ?\t)
11929 (read-string "Structure type: "))
11930 (user-error "`%c' has no structure definition" key))))
11931 struct-string)))
11932 (let* ((region? (use-region-p))
11933 (s (if region? (region-beginning) (point)))
11934 (e (copy-marker (if region? (region-end) (point)) t))
11935 column)
11936 (when (string-match-p
11937 (concat "\\`" (regexp-opt '("example" "export" "src")))
11938 type)
11939 (org-escape-code-in-region s e))
11940 (goto-char s)
11941 (setq column (current-indentation))
11942 (beginning-of-line)
11943 (indent-to column)
11944 (insert (format "#+begin_%s%s\n" type (if (string-equal "src" type) " " "")))
11945 (goto-char e)
11946 (if (bolp)
11947 (progn
11948 (skip-chars-backward " \n\t")
11949 (forward-line))
11950 (end-of-line)
11951 (insert "\n"))
11952 (indent-to column)
11953 (insert (format "#+end_%s\n"
11954 (car (split-string type))))
11955 (when (or (not region?)
11956 (string-match-p "src\\|\\`export\\'" type))
11957 (goto-char s)
11958 (end-of-line))
11959 (set-marker e nil)))
11961 ;;;; TODO, DEADLINE, Comments
11963 (defun org-toggle-comment ()
11964 "Change the COMMENT state of an entry."
11965 (interactive)
11966 (save-excursion
11967 (org-back-to-heading)
11968 (let ((case-fold-search nil))
11969 (looking-at org-complex-heading-regexp))
11970 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11971 (skip-chars-forward " \t")
11972 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11973 (if (org-in-commented-heading-p t)
11974 (delete-region (point)
11975 (progn (search-forward " " (line-end-position) 'move)
11976 (skip-chars-forward " \t")
11977 (point)))
11978 (insert org-comment-string)
11979 (unless (eolp) (insert " ")))))
11981 (defvar org-last-todo-state-is-todo nil
11982 "This is non-nil when the last TODO state change led to a TODO state.
11983 If the last change removed the TODO tag or switched to DONE, then
11984 this is nil.")
11986 (defvar org-setting-tags nil) ; dynamically skipped
11988 (defvar org-todo-setup-filter-hook nil
11989 "Hook for functions that pre-filter todo specs.
11990 Each function takes a todo spec and returns either nil or the spec
11991 transformed into canonical form." )
11993 (defvar org-todo-get-default-hook nil
11994 "Hook for functions that get a default item for todo.
11995 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11996 nil or a string to be used for the todo mark." )
11998 (defvar org-agenda-headline-snapshot-before-repeat)
12000 (defun org-current-effective-time ()
12001 "Return current time adjusted for `org-extend-today-until' variable."
12002 (let* ((ct (org-current-time))
12003 (dct (decode-time ct))
12004 (ct1
12005 (cond
12006 (org-use-last-clock-out-time-as-effective-time
12007 (or (org-clock-get-last-clock-out-time) ct))
12008 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12009 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12010 (t ct))))
12011 ct1))
12013 (defun org-todo-yesterday (&optional arg)
12014 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12015 (interactive "P")
12016 (if (eq major-mode 'org-agenda-mode)
12017 (apply 'org-agenda-todo-yesterday arg)
12018 (let* ((org-use-effective-time t)
12019 (hour (nth 2 (decode-time (org-current-time))))
12020 (org-extend-today-until (1+ hour)))
12021 (org-todo arg))))
12023 (defvar org-block-entry-blocking ""
12024 "First entry preventing the TODO state change.")
12026 (defun org-cancel-repeater ()
12027 "Cancel a repeater by setting its numeric value to zero."
12028 (interactive)
12029 (save-excursion
12030 (org-back-to-heading t)
12031 (let ((bound1 (point))
12032 (bound0 (save-excursion (outline-next-heading) (point))))
12033 (when (and (re-search-forward
12034 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12035 org-deadline-time-regexp "\\)\\|\\("
12036 org-ts-regexp "\\)")
12037 bound0 t)
12038 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12039 bound1 t))
12040 (replace-match "0" t nil nil 1)))))
12042 (defvar org-state)
12043 (defvar org-blocked-by-checkboxes)
12044 (defun org-todo (&optional arg)
12045 "Change the TODO state of an item.
12047 The state of an item is given by a keyword at the start of the heading,
12048 like
12049 *** TODO Write paper
12050 *** DONE Call mom
12052 The different keywords are specified in the variable `org-todo-keywords'.
12053 By default the available states are \"TODO\" and \"DONE\". So, for this
12054 example: when the item starts with TODO, it is changed to DONE.
12055 When it starts with DONE, the DONE is removed. And when neither TODO nor
12056 DONE are present, add TODO at the beginning of the heading.
12058 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12059 state.
12060 With numeric prefix ARG, switch to that state.
12061 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12062 next set of TODO \
12063 keywords (nextset).
12064 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12065 prefix, circumvent any state blocking.
12066 With a numeric prefix arg of 0, inhibit note taking for the change.
12067 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12069 When called through ELisp, arg is also interpreted in the following way:
12070 `none' -> empty state
12071 \"\" -> switch to empty state
12072 `done' -> switch to DONE
12073 `nextset' -> switch to the next set of keywords
12074 `previousset' -> switch to the previous set of keywords
12075 \"WAITING\" -> switch to the specified keyword, but only if it
12076 really is a member of `org-todo-keywords'."
12077 (interactive "P")
12078 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12079 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12080 'region-start-level 'region))
12081 org-loop-over-headlines-in-active-region)
12082 (org-map-entries
12083 `(org-todo ,arg)
12084 org-loop-over-headlines-in-active-region
12085 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12086 (when (equal arg '(16)) (setq arg 'nextset))
12087 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12088 (let ((org-blocker-hook org-blocker-hook)
12089 commentp
12090 case-fold-search)
12091 (when (equal arg '(64))
12092 (setq arg nil org-blocker-hook nil))
12093 (when (and org-blocker-hook
12094 (or org-inhibit-blocking
12095 (org-entry-get nil "NOBLOCKING")))
12096 (setq org-blocker-hook nil))
12097 (save-excursion
12098 (catch 'exit
12099 (org-back-to-heading t)
12100 (when (org-in-commented-heading-p t)
12101 (org-toggle-comment)
12102 (setq commentp t))
12103 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12104 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12105 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12106 (let* ((match-data (match-data))
12107 (startpos (copy-marker (line-beginning-position)))
12108 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12109 (org-log-done org-log-done)
12110 (org-log-repeat org-log-repeat)
12111 (org-todo-log-states org-todo-log-states)
12112 (org-inhibit-logging
12113 (if (equal arg 0)
12114 (progn (setq arg nil) 'note) org-inhibit-logging))
12115 (this (match-string 1))
12116 (hl-pos (match-beginning 0))
12117 (head (org-get-todo-sequence-head this))
12118 (ass (assoc head org-todo-kwd-alist))
12119 (interpret (nth 1 ass))
12120 (done-word (nth 3 ass))
12121 (final-done-word (nth 4 ass))
12122 (org-last-state (or this ""))
12123 (completion-ignore-case t)
12124 (member (member this org-todo-keywords-1))
12125 (tail (cdr member))
12126 (org-state (cond
12127 ((and org-todo-key-trigger
12128 (or (and (equal arg '(4))
12129 (eq org-use-fast-todo-selection 'prefix))
12130 (and (not arg) org-use-fast-todo-selection
12131 (not (eq org-use-fast-todo-selection
12132 'prefix)))))
12133 ;; Use fast selection.
12134 (org-fast-todo-selection))
12135 ((and (equal arg '(4))
12136 (or (not org-use-fast-todo-selection)
12137 (not org-todo-key-trigger)))
12138 ;; Read a state with completion.
12139 (completing-read
12140 "State: " (mapcar #'list org-todo-keywords-1)
12141 nil t))
12142 ((eq arg 'right)
12143 (if this
12144 (if tail (car tail) nil)
12145 (car org-todo-keywords-1)))
12146 ((eq arg 'left)
12147 (unless (equal member org-todo-keywords-1)
12148 (if this
12149 (nth (- (length org-todo-keywords-1)
12150 (length tail) 2)
12151 org-todo-keywords-1)
12152 (org-last org-todo-keywords-1))))
12153 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12154 (setq arg nil))) ;hack to fall back to cycling
12155 (arg
12156 ;; User or caller requests a specific state.
12157 (cond
12158 ((equal arg "") nil)
12159 ((eq arg 'none) nil)
12160 ((eq arg 'done) (or done-word (car org-done-keywords)))
12161 ((eq arg 'nextset)
12162 (or (car (cdr (member head org-todo-heads)))
12163 (car org-todo-heads)))
12164 ((eq arg 'previousset)
12165 (let ((org-todo-heads (reverse org-todo-heads)))
12166 (or (car (cdr (member head org-todo-heads)))
12167 (car org-todo-heads))))
12168 ((car (member arg org-todo-keywords-1)))
12169 ((stringp arg)
12170 (user-error "State `%s' not valid in this file" arg))
12171 ((nth (1- (prefix-numeric-value arg))
12172 org-todo-keywords-1))))
12173 ((null member) (or head (car org-todo-keywords-1)))
12174 ((equal this final-done-word) nil) ;-> make empty
12175 ((null tail) nil) ;-> first entry
12176 ((memq interpret '(type priority))
12177 (if (eq this-command last-command)
12178 (car tail)
12179 (if (> (length tail) 0)
12180 (or done-word (car org-done-keywords))
12181 nil)))
12183 (car tail))))
12184 (org-state (or
12185 (run-hook-with-args-until-success
12186 'org-todo-get-default-hook org-state org-last-state)
12187 org-state))
12188 (next (if org-state (concat " " org-state " ") " "))
12189 (change-plist (list :type 'todo-state-change :from this :to org-state
12190 :position startpos))
12191 dolog now-done-p)
12192 (when org-blocker-hook
12193 (let (org-blocked-by-checkboxes block-reason)
12194 (setq org-last-todo-state-is-todo
12195 (not (member this org-done-keywords)))
12196 (unless (save-excursion
12197 (save-match-data
12198 (org-with-wide-buffer
12199 (run-hook-with-args-until-failure
12200 'org-blocker-hook change-plist))))
12201 (setq block-reason (if org-blocked-by-checkboxes
12202 "contained checkboxes"
12203 (format "\"%s\"" org-block-entry-blocking)))
12204 (if (called-interactively-p 'interactive)
12205 (user-error "TODO state change from %s to %s blocked (by %s)"
12206 this org-state block-reason)
12207 ;; Fail silently.
12208 (message "TODO state change from %s to %s blocked (by %s)"
12209 this org-state block-reason)
12210 (throw 'exit nil)))))
12211 (store-match-data match-data)
12212 (replace-match next t t)
12213 (cond ((equal this org-state)
12214 (message "TODO state was already %s" (org-trim next)))
12215 ((not (pos-visible-in-window-p hl-pos))
12216 (message "TODO state changed to %s" (org-trim next))))
12217 (unless head
12218 (setq head (org-get-todo-sequence-head org-state)
12219 ass (assoc head org-todo-kwd-alist)
12220 interpret (nth 1 ass)
12221 done-word (nth 3 ass)
12222 final-done-word (nth 4 ass)))
12223 (when (memq arg '(nextset previousset))
12224 (message "Keyword-Set %d/%d: %s"
12225 (- (length org-todo-sets) -1
12226 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12227 (length org-todo-sets)
12228 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12229 (setq org-last-todo-state-is-todo
12230 (not (member org-state org-done-keywords)))
12231 (setq now-done-p (and (member org-state org-done-keywords)
12232 (not (member this org-done-keywords))))
12233 (and logging (org-local-logging logging))
12234 (when (and (or org-todo-log-states org-log-done)
12235 (not (eq org-inhibit-logging t))
12236 (not (memq arg '(nextset previousset))))
12237 ;; We need to look at recording a time and note.
12238 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12239 (nth 2 (assoc this org-todo-log-states))))
12240 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12241 (setq dolog 'time))
12242 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12243 (and org-state
12244 (member org-state org-not-done-keywords)
12245 (not (member this org-not-done-keywords))))
12246 ;; This is now a todo state and was not one before
12247 ;; If there was a CLOSED time stamp, get rid of it.
12248 (org-add-planning-info nil nil 'closed))
12249 (when (and now-done-p org-log-done)
12250 ;; It is now done, and it was not done before.
12251 (org-add-planning-info 'closed (org-current-effective-time))
12252 (when (and (not dolog) (eq 'note org-log-done))
12253 (org-add-log-setup 'done org-state this 'note)))
12254 (when (and org-state dolog)
12255 ;; This is a non-nil state, and we need to log it.
12256 (org-add-log-setup 'state org-state this dolog)))
12257 ;; Fixup tag positioning.
12258 (org-todo-trigger-tag-changes org-state)
12259 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12260 (when org-provide-todo-statistics
12261 (org-update-parent-todo-statistics))
12262 (run-hooks 'org-after-todo-state-change-hook)
12263 (when (and arg (not (member org-state org-done-keywords)))
12264 (setq head (org-get-todo-sequence-head org-state)))
12265 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12266 ;; Do we need to trigger a repeat?
12267 (when now-done-p
12268 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12269 ;; This is for the agenda, take a snapshot of the headline.
12270 (save-match-data
12271 (setq org-agenda-headline-snapshot-before-repeat
12272 (org-get-heading))))
12273 (org-auto-repeat-maybe org-state))
12274 ;; Fixup cursor location if close to the keyword.
12275 (when (and (outline-on-heading-p)
12276 (not (bolp))
12277 (save-excursion (beginning-of-line 1)
12278 (looking-at org-todo-line-regexp))
12279 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12280 (goto-char (or (match-end 2) (match-end 1)))
12281 (and (looking-at " ") (just-one-space)))
12282 (when org-trigger-hook
12283 (save-excursion
12284 (run-hook-with-args 'org-trigger-hook change-plist)))
12285 (when commentp (org-toggle-comment))))))))
12287 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12288 "Block turning an entry into a TODO, using the hierarchy.
12289 This checks whether the current task should be blocked from state
12290 changes. Such blocking occurs when:
12292 1. The task has children which are not all in a completed state.
12294 2. A task has a parent with the property :ORDERED:, and there
12295 are siblings prior to the current task with incomplete
12296 status.
12298 3. The parent of the task is blocked because it has siblings that should
12299 be done first, or is child of a block grandparent TODO entry."
12301 (if (not org-enforce-todo-dependencies)
12302 t ; if locally turned off don't block
12303 (catch 'dont-block
12304 ;; If this is not a todo state change, or if this entry is already DONE,
12305 ;; do not block
12306 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12307 (member (plist-get change-plist :from)
12308 (cons 'done org-done-keywords))
12309 (member (plist-get change-plist :to)
12310 (cons 'todo org-not-done-keywords))
12311 (not (plist-get change-plist :to)))
12312 (throw 'dont-block t))
12313 ;; If this task has children, and any are undone, it's blocked
12314 (save-excursion
12315 (org-back-to-heading t)
12316 (let ((this-level (funcall outline-level)))
12317 (outline-next-heading)
12318 (let ((child-level (funcall outline-level)))
12319 (while (and (not (eobp))
12320 (> child-level this-level))
12321 ;; this todo has children, check whether they are all
12322 ;; completed
12323 (when (and (not (org-entry-is-done-p))
12324 (org-entry-is-todo-p))
12325 (setq org-block-entry-blocking (org-get-heading))
12326 (throw 'dont-block nil))
12327 (outline-next-heading)
12328 (setq child-level (funcall outline-level))))))
12329 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12330 ;; any previous siblings are undone, it's blocked
12331 (save-excursion
12332 (org-back-to-heading t)
12333 (let* ((pos (point))
12334 (parent-pos (and (org-up-heading-safe) (point)))
12335 (case-fold-search nil))
12336 (unless parent-pos (throw 'dont-block t)) ; no parent
12337 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12338 (forward-line 1)
12339 (re-search-forward org-not-done-heading-regexp pos t))
12340 (setq org-block-entry-blocking (match-string 0))
12341 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12342 ;; Search further up the hierarchy, to see if an ancestor is blocked
12343 (while t
12344 (goto-char parent-pos)
12345 (unless (looking-at org-not-done-heading-regexp)
12346 (throw 'dont-block t)) ; do not block, parent is not a TODO
12347 (setq pos (point))
12348 (setq parent-pos (and (org-up-heading-safe) (point)))
12349 (unless parent-pos (throw 'dont-block t)) ; no parent
12350 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12351 (forward-line 1)
12352 (re-search-forward org-not-done-heading-regexp pos t)
12353 (setq org-block-entry-blocking (org-get-heading)))
12354 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12356 (defcustom org-track-ordered-property-with-tag nil
12357 "Should the ORDERED property also be shown as a tag?
12358 The ORDERED property decides if an entry should require subtasks to be
12359 completed in sequence. Since a property is not very visible, setting
12360 this option means that toggling the ORDERED property with the command
12361 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12362 not relevant for the behavior, but it makes things more visible.
12364 Note that toggling the tag with tags commands will not change the property
12365 and therefore not influence behavior!
12367 This can be t, meaning the tag ORDERED should be used, It can also be a
12368 string to select a different tag for this task."
12369 :group 'org-todo
12370 :type '(choice
12371 (const :tag "No tracking" nil)
12372 (const :tag "Track with ORDERED tag" t)
12373 (string :tag "Use other tag")))
12375 (defun org-toggle-ordered-property ()
12376 "Toggle the ORDERED property of the current entry.
12377 For better visibility, you can track the value of this property with a tag.
12378 See variable `org-track-ordered-property-with-tag'."
12379 (interactive)
12380 (let* ((t1 org-track-ordered-property-with-tag)
12381 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12382 (save-excursion
12383 (org-back-to-heading)
12384 (if (org-entry-get nil "ORDERED")
12385 (progn
12386 (org-delete-property "ORDERED")
12387 (and tag (org-toggle-tag tag 'off))
12388 (message "Subtasks can be completed in arbitrary order"))
12389 (org-entry-put nil "ORDERED" "t")
12390 (and tag (org-toggle-tag tag 'on))
12391 (message "Subtasks must be completed in sequence")))))
12393 (defun org-block-todo-from-checkboxes (change-plist)
12394 "Block turning an entry into a TODO, using checkboxes.
12395 This checks whether the current task should be blocked from state
12396 changes because there are unchecked boxes in this entry."
12397 (if (not org-enforce-todo-checkbox-dependencies)
12398 t ; if locally turned off don't block
12399 (catch 'dont-block
12400 ;; If this is not a todo state change, or if this entry is already DONE,
12401 ;; do not block
12402 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12403 (member (plist-get change-plist :from)
12404 (cons 'done org-done-keywords))
12405 (member (plist-get change-plist :to)
12406 (cons 'todo org-not-done-keywords))
12407 (not (plist-get change-plist :to)))
12408 (throw 'dont-block t))
12409 ;; If this task has checkboxes that are not checked, it's blocked
12410 (save-excursion
12411 (org-back-to-heading t)
12412 (let ((beg (point)) end)
12413 (outline-next-heading)
12414 (setq end (point))
12415 (goto-char beg)
12416 (when (org-list-search-forward
12417 (concat (org-item-beginning-re)
12418 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12419 "\\[[- ]\\]")
12420 end t)
12421 (when (boundp 'org-blocked-by-checkboxes)
12422 (setq org-blocked-by-checkboxes t))
12423 (throw 'dont-block nil))))
12424 t))) ; do not block
12426 (defun org-entry-blocked-p ()
12427 "Non-nil if entry at point is blocked."
12428 (and (not (org-entry-get nil "NOBLOCKING"))
12429 (member (org-entry-get nil "TODO") org-not-done-keywords)
12430 (not (run-hook-with-args-until-failure
12431 'org-blocker-hook
12432 (list :type 'todo-state-change
12433 :position (point)
12434 :from 'todo
12435 :to 'done)))))
12437 (defun org-update-statistics-cookies (all)
12438 "Update the statistics cookie, either from TODO or from checkboxes.
12439 This should be called with the cursor in a line with a statistics
12440 cookie. When called with a \\[universal-argument] prefix, update
12441 all statistics cookies in the buffer."
12442 (interactive "P")
12443 (if all
12444 (progn
12445 (org-update-checkbox-count 'all)
12446 (org-map-entries 'org-update-parent-todo-statistics))
12447 (if (not (org-at-heading-p))
12448 (org-update-checkbox-count)
12449 (let ((pos (point-marker))
12450 end l1 l2)
12451 (ignore-errors (org-back-to-heading t))
12452 (if (not (org-at-heading-p))
12453 (org-update-checkbox-count)
12454 (setq l1 (org-outline-level))
12455 (setq end (save-excursion
12456 (outline-next-heading)
12457 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12458 (point)))
12459 (if (and (save-excursion
12460 (re-search-forward
12461 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12462 (not (save-excursion (re-search-forward
12463 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12464 (org-update-checkbox-count)
12465 (if (and l2 (> l2 l1))
12466 (progn
12467 (goto-char end)
12468 (org-update-parent-todo-statistics))
12469 (goto-char pos)
12470 (beginning-of-line 1)
12471 (while (re-search-forward
12472 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12473 (point-at-eol) t)
12474 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12475 (goto-char pos)
12476 (move-marker pos nil)))))
12478 (defvar org-entry-property-inherited-from) ;; defined below
12479 (defun org-update-parent-todo-statistics ()
12480 "Update any statistics cookie in the parent of the current headline.
12481 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12482 the entire subtree and this will travel up the hierarchy and update
12483 statistics everywhere."
12484 (let* ((prop (save-excursion (org-up-heading-safe)
12485 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12486 (recursive (or (not org-hierarchical-todo-statistics)
12487 (and prop (string-match "\\<recursive\\>" prop))))
12488 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12490 (first t)
12491 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12492 level ltoggle l1 new ndel
12493 (cnt-all 0) (cnt-done 0) is-percent kwd
12494 checkbox-beg cookie-present)
12495 (catch 'exit
12496 (save-excursion
12497 (beginning-of-line 1)
12498 (setq ltoggle (funcall outline-level))
12499 ;; Three situations are to consider:
12501 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12502 ;; to the top-level ancestor on the headline;
12504 ;; 2. If parent has "recursive" property, repeat up to the
12505 ;; headline setting that property, taking inheritance into
12506 ;; account;
12508 ;; 3. Else, move up to direct parent and proceed only once.
12509 (while (and (setq level (org-up-heading-safe))
12510 (or recursive first)
12511 (>= (point) lim))
12512 (setq first nil cookie-present nil)
12513 (unless (and level
12514 (not (string-match
12515 "\\<checkbox\\>"
12516 (downcase (or (org-entry-get nil "COOKIE_DATA")
12517 "")))))
12518 (throw 'exit nil))
12519 (while (re-search-forward box-re (point-at-eol) t)
12520 (setq cnt-all 0 cnt-done 0 cookie-present t)
12521 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12522 (save-match-data
12523 (unless (outline-next-heading) (throw 'exit nil))
12524 (while (and (looking-at org-complex-heading-regexp)
12525 (> (setq l1 (length (match-string 1))) level))
12526 (setq kwd (and (or recursive (= l1 ltoggle))
12527 (match-string 2)))
12528 (if (or (eq org-provide-todo-statistics 'all-headlines)
12529 (and (eq org-provide-todo-statistics t)
12530 (or (member kwd org-done-keywords)))
12531 (and (listp org-provide-todo-statistics)
12532 (stringp (car org-provide-todo-statistics))
12533 (or (member kwd org-provide-todo-statistics)
12534 (member kwd org-done-keywords)))
12535 (and (listp org-provide-todo-statistics)
12536 (listp (car org-provide-todo-statistics))
12537 (or (member kwd (car org-provide-todo-statistics))
12538 (and (member kwd org-done-keywords)
12539 (member kwd (cadr org-provide-todo-statistics))))))
12540 (setq cnt-all (1+ cnt-all))
12541 (and (eq org-provide-todo-statistics t)
12543 (setq cnt-all (1+ cnt-all))))
12544 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12545 (member kwd org-done-keywords))
12546 (and (listp org-provide-todo-statistics)
12547 (listp (car org-provide-todo-statistics))
12548 (member kwd org-done-keywords)
12549 (member kwd (cadr org-provide-todo-statistics)))
12550 (and (listp org-provide-todo-statistics)
12551 (stringp (car org-provide-todo-statistics))
12552 (member kwd org-done-keywords)))
12553 (setq cnt-done (1+ cnt-done)))
12554 (outline-next-heading)))
12555 (setq new
12556 (if is-percent
12557 (format "[%d%%]" (floor (* 100.0 cnt-done)
12558 (max 1 cnt-all)))
12559 (format "[%d/%d]" cnt-done cnt-all))
12560 ndel (- (match-end 0) checkbox-beg))
12561 (goto-char checkbox-beg)
12562 (insert new)
12563 (delete-region (point) (+ (point) ndel))
12564 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12565 (when cookie-present
12566 (run-hook-with-args 'org-after-todo-statistics-hook
12567 cnt-done (- cnt-all cnt-done))))))
12568 (run-hooks 'org-todo-statistics-hook)))
12570 (defvar org-after-todo-statistics-hook nil
12571 "Hook that is called after a TODO statistics cookie has been updated.
12572 Each function is called with two arguments: the number of not-done entries
12573 and the number of done entries.
12575 For example, the following function, when added to this hook, will switch
12576 an entry to DONE when all children are done, and back to TODO when new
12577 entries are set to a TODO status. Note that this hook is only called
12578 when there is a statistics cookie in the headline!
12580 (defun org-summary-todo (n-done n-not-done)
12581 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12582 (let (org-log-done org-log-states) ; turn off logging
12583 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12586 (defvar org-todo-statistics-hook nil
12587 "Hook that is run whenever Org thinks TODO statistics should be updated.
12588 This hook runs even if there is no statistics cookie present, in which case
12589 `org-after-todo-statistics-hook' would not run.")
12591 (defun org-todo-trigger-tag-changes (state)
12592 "Apply the changes defined in `org-todo-state-tags-triggers'."
12593 (let ((l org-todo-state-tags-triggers)
12594 changes)
12595 (when (or (not state) (equal state ""))
12596 (setq changes (append changes (cdr (assoc "" l)))))
12597 (when (and (stringp state) (> (length state) 0))
12598 (setq changes (append changes (cdr (assoc state l)))))
12599 (when (member state org-not-done-keywords)
12600 (setq changes (append changes (cdr (assq 'todo l)))))
12601 (when (member state org-done-keywords)
12602 (setq changes (append changes (cdr (assq 'done l)))))
12603 (dolist (c changes)
12604 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12606 (defun org-local-logging (value)
12607 "Get logging settings from a property VALUE."
12608 ;; Directly set the variables, they are already local.
12609 (setq org-log-done nil
12610 org-log-repeat nil
12611 org-todo-log-states nil)
12612 (dolist (w (split-string value))
12613 (let (a)
12614 (cond
12615 ((setq a (assoc w org-startup-options))
12616 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12617 (set (nth 1 a) (nth 2 a))))
12618 ((setq a (org-extract-log-state-settings w))
12619 (and (member (car a) org-todo-keywords-1)
12620 (push a org-todo-log-states)))))))
12622 (defun org-get-todo-sequence-head (kwd)
12623 "Return the head of the TODO sequence to which KWD belongs.
12624 If KWD is not set, check if there is a text property remembering the
12625 right sequence."
12626 (let (p)
12627 (cond
12628 ((not kwd)
12629 (or (get-text-property (point-at-bol) 'org-todo-head)
12630 (progn
12631 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12632 nil (point-at-eol)))
12633 (get-text-property p 'org-todo-head))))
12634 ((not (member kwd org-todo-keywords-1))
12635 (car org-todo-keywords-1))
12636 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12638 (defun org-fast-todo-selection ()
12639 "Fast TODO keyword selection with single keys.
12640 Returns the new TODO keyword, or nil if no state change should occur."
12641 (let* ((fulltable org-todo-key-alist)
12642 (done-keywords org-done-keywords) ;; needed for the faces.
12643 (maxlen (apply 'max (mapcar
12644 (lambda (x)
12645 (if (stringp (car x)) (string-width (car x)) 0))
12646 fulltable)))
12647 (expert nil)
12648 (fwidth (+ maxlen 3 1 3))
12649 (ncol (/ (- (window-width) 4) fwidth))
12650 tg cnt e c tbl
12651 groups ingroup)
12652 (save-excursion
12653 (save-window-excursion
12654 (if expert
12655 (set-buffer (get-buffer-create " *Org todo*"))
12656 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12657 (erase-buffer)
12658 (setq-local org-done-keywords done-keywords)
12659 (setq tbl fulltable cnt 0)
12660 (while (setq e (pop tbl))
12661 (cond
12662 ((equal e '(:startgroup))
12663 (push '() groups) (setq ingroup t)
12664 (unless (= cnt 0)
12665 (setq cnt 0)
12666 (insert "\n"))
12667 (insert "{ "))
12668 ((equal e '(:endgroup))
12669 (setq ingroup nil cnt 0)
12670 (insert "}\n"))
12671 ((equal e '(:newline))
12672 (unless (= cnt 0)
12673 (setq cnt 0)
12674 (insert "\n")
12675 (setq e (car tbl))
12676 (while (equal (car tbl) '(:newline))
12677 (insert "\n")
12678 (setq tbl (cdr tbl)))))
12680 (setq tg (car e) c (cdr e))
12681 (when ingroup (push tg (car groups)))
12682 (setq tg (org-add-props tg nil 'face
12683 (org-get-todo-face tg)))
12684 (when (and (= cnt 0) (not ingroup)) (insert " "))
12685 (insert "[" c "] " tg (make-string
12686 (- fwidth 4 (length tg)) ?\ ))
12687 (when (= (setq cnt (1+ cnt)) ncol)
12688 (insert "\n")
12689 (when ingroup (insert " "))
12690 (setq cnt 0)))))
12691 (insert "\n")
12692 (goto-char (point-min))
12693 (unless expert (org-fit-window-to-buffer))
12694 (message "[a-z..]:Set [SPC]:clear")
12695 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12696 (cond
12697 ((or (= c ?\C-g)
12698 (and (= c ?q) (not (rassoc c fulltable))))
12699 (setq quit-flag t))
12700 ((= c ?\ ) nil)
12701 ((setq e (rassoc c fulltable) tg (car e))
12703 (t (setq quit-flag t)))))))
12705 (defun org-entry-is-todo-p ()
12706 (member (org-get-todo-state) org-not-done-keywords))
12708 (defun org-entry-is-done-p ()
12709 (member (org-get-todo-state) org-done-keywords))
12711 (defun org-get-todo-state ()
12712 "Return the TODO keyword of the current subtree."
12713 (save-excursion
12714 (org-back-to-heading t)
12715 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12716 (match-end 2)
12717 (match-string 2))))
12719 (defun org-at-date-range-p (&optional inactive-ok)
12720 "Non-nil if point is inside a date range.
12722 When optional argument INACTIVE-OK is non-nil, also consider
12723 inactive time ranges.
12725 When this function returns a non-nil value, match data is set
12726 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12727 on INACTIVE-OK."
12728 (interactive)
12729 (save-excursion
12730 (catch 'exit
12731 (let ((pos (point)))
12732 (skip-chars-backward "^[<\r\n")
12733 (skip-chars-backward "<[")
12734 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12735 (>= (match-end 0) pos)
12736 (throw 'exit t))
12737 (skip-chars-backward "^<[\r\n")
12738 (skip-chars-backward "<[")
12739 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12740 (>= (match-end 0) pos)
12741 (throw 'exit t)))
12742 nil)))
12744 (defun org-get-repeat (&optional timestamp)
12745 "Check if there is a time-stamp with repeater in this entry.
12747 Return the repeater, as a string, or nil. Also return nil when
12748 this function is called before first heading.
12750 When optional argument TIMESTAMP is a string, extract the
12751 repeater from there instead."
12752 (save-match-data
12753 (cond (timestamp
12754 (and (string-match org-repeat-re timestamp)
12755 (match-string-no-properties 1 timestamp)))
12756 ((org-before-first-heading-p) nil)
12758 (save-excursion
12759 (org-back-to-heading t)
12760 (let ((end (org-entry-end-position)))
12761 (catch :repeat
12762 (while (re-search-forward org-repeat-re end t)
12763 (when (save-match-data (org-at-timestamp-p 'agenda))
12764 (throw :repeat (match-string-no-properties 1)))))))))))
12766 (defvar org-last-changed-timestamp)
12767 (defvar org-last-inserted-timestamp)
12768 (defvar org-log-post-message)
12769 (defvar org-log-note-purpose)
12770 (defvar org-log-note-how nil)
12771 (defvar org-log-note-extra)
12772 (defun org-auto-repeat-maybe (done-word)
12773 "Check if the current headline contains a repeated time-stamp.
12775 If yes, set TODO state back to what it was and change the base date
12776 of repeating deadline/scheduled time stamps to new date.
12778 This function is run automatically after each state change to a DONE state."
12779 (let* ((repeat (org-get-repeat))
12780 (aa (assoc org-last-state org-todo-kwd-alist))
12781 (interpret (nth 1 aa))
12782 (head (nth 2 aa))
12783 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12784 (msg "Entry repeats: ")
12785 (org-log-done nil)
12786 (org-todo-log-states nil)
12787 (end (copy-marker (org-entry-end-position))))
12788 (unwind-protect
12789 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12790 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12791 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12792 (and (stringp org-todo-repeat-to-state)
12793 org-todo-repeat-to-state)
12794 (and org-todo-repeat-to-state org-last-state))))
12795 (org-todo (cond
12796 ((and to-state (member to-state org-todo-keywords-1))
12797 to-state)
12798 ((eq interpret 'type) org-last-state)
12799 (head)
12800 (t 'none))))
12801 (org-back-to-heading t)
12802 (org-add-planning-info nil nil 'closed)
12803 ;; When `org-log-repeat' is non-nil or entry contains
12804 ;; a clock, set LAST_REPEAT property.
12805 (when (or org-log-repeat
12806 (catch :clock
12807 (save-excursion
12808 (while (re-search-forward org-clock-line-re end t)
12809 (when (org-at-clock-log-p) (throw :clock t))))))
12810 (org-entry-put nil "LAST_REPEAT" (format-time-string
12811 (org-time-stamp-format t t)
12812 (current-time))))
12813 (when org-log-repeat
12814 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12815 (memq 'org-add-log-note post-command-hook))
12816 ;; We are already setup for some record.
12817 (when (eq org-log-repeat 'note)
12818 ;; Make sure we take a note, not only a time stamp.
12819 (setq org-log-note-how 'note))
12820 ;; Set up for taking a record.
12821 (org-add-log-setup 'state
12822 (or done-word (car org-done-keywords))
12823 org-last-state
12824 org-log-repeat)))
12825 (let ((planning-re (regexp-opt
12826 (list org-scheduled-string org-deadline-string))))
12827 (while (re-search-forward org-ts-regexp end t)
12828 (let* ((ts (match-string 0))
12829 (planning? (org-at-planning-p))
12830 (type (if (not planning?) "Plain:"
12831 (save-excursion
12832 (re-search-backward
12833 planning-re (line-beginning-position) t)
12834 (match-string 0)))))
12835 (cond
12836 ;; Ignore fake time-stamps (e.g., within comments).
12837 ((not (org-at-timestamp-p 'agenda)))
12838 ;; Time-stamps without a repeater are usually
12839 ;; skipped. However, a SCHEDULED time-stamp without
12840 ;; one is removed, as they are no longer relevant.
12841 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12842 ts))
12843 (when (equal type org-scheduled-string)
12844 (org-remove-timestamp-with-keyword type)))
12846 (let ((n (string-to-number (match-string 2 ts)))
12847 (what (match-string 3 ts)))
12848 (when (equal what "w") (setq n (* n 7) what "d"))
12849 (when (and (equal what "h")
12850 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12851 ts)))
12852 (user-error
12853 "Cannot repeat in Repeat in %d hour(s) because no hour \
12854 has been set"
12856 ;; Preparation, see if we need to modify the start
12857 ;; date for the change.
12858 (when (match-end 1)
12859 (let ((time (save-match-data
12860 (org-time-string-to-time ts))))
12861 (cond
12862 ((equal (match-string 1 ts) ".")
12863 ;; Shift starting date to today
12864 (org-timestamp-change
12865 (- (org-today) (time-to-days time))
12866 'day))
12867 ((equal (match-string 1 ts) "+")
12868 (let ((nshiftmax 10)
12869 (nshift 0))
12870 (while (or (= nshift 0)
12871 (not (time-less-p (current-time) time)))
12872 (when (= (cl-incf nshift) nshiftmax)
12873 (or (y-or-n-p
12874 (format "%d repeater intervals were not \
12875 enough to shift date past today. Continue? "
12876 nshift))
12877 (user-error "Abort")))
12878 (org-timestamp-change n (cdr (assoc what whata)))
12879 (org-in-regexp org-ts-regexp3)
12880 (setq ts (match-string 1))
12881 (setq time
12882 (save-match-data
12883 (org-time-string-to-time ts)))))
12884 (org-timestamp-change (- n) (cdr (assoc what whata)))
12885 ;; Rematch, so that we have everything in place
12886 ;; for the real shift.
12887 (org-in-regexp org-ts-regexp3)
12888 (setq ts (match-string 1))
12889 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12890 ts)))))
12891 (save-excursion
12892 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12893 (setq msg
12894 (concat
12895 msg type " " org-last-changed-timestamp " "))))))))
12896 (setq org-log-post-message msg)
12897 (message "%s" msg))
12898 (set-marker end nil))))
12900 (defun org-show-todo-tree (arg)
12901 "Make a compact tree which shows all headlines marked with TODO.
12902 The tree will show the lines where the regexp matches, and all higher
12903 headlines above the match.
12904 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12905 With a numeric prefix N, construct a sparse tree for the Nth element
12906 of `org-todo-keywords-1'."
12907 (interactive "P")
12908 (let ((case-fold-search nil)
12909 (kwd-re
12910 (cond ((null arg) org-not-done-regexp)
12911 ((equal arg '(4))
12912 (let ((kwd
12913 (completing-read "Keyword (or KWD1|KWD2|...): "
12914 (mapcar #'list org-todo-keywords-1))))
12915 (concat "\\("
12916 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12917 "\\)\\>")))
12918 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12919 (regexp-quote (nth (1- (prefix-numeric-value arg))
12920 org-todo-keywords-1)))
12921 (t (user-error "Invalid prefix argument: %s" arg)))))
12922 (message "%d TODO entries found"
12923 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12925 (defun org--deadline-or-schedule (arg type time)
12926 "Insert DEADLINE or SCHEDULE information in current entry.
12927 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12928 `org-schedule' for information about ARG and TIME arguments."
12929 (let* ((deadline? (eq type 'deadline))
12930 (keyword (if deadline? org-deadline-string org-scheduled-string))
12931 (log (if deadline? org-log-redeadline org-log-reschedule))
12932 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12933 (old-date-time (and old-date (org-time-string-to-time old-date)))
12934 ;; Save repeater cookie from either TIME or current scheduled
12935 ;; time stamp. We are going to insert it back at the end of
12936 ;; the process.
12937 (repeater (or (and (org-string-nw-p time)
12938 ;; We use `org-repeat-re' because we need
12939 ;; to tell the difference between a real
12940 ;; repeater and a time delta, e.g. "+2d".
12941 (string-match org-repeat-re time)
12942 (match-string 1 time))
12943 (and (org-string-nw-p old-date)
12944 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12945 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12946 old-date)
12947 (match-string 1 old-date)))))
12948 (pcase arg
12949 (`(4)
12950 (when (and old-date log)
12951 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12952 nil old-date log))
12953 (org-remove-timestamp-with-keyword keyword)
12954 (message (if deadline? "Item no longer has a deadline."
12955 "Item is no longer scheduled.")))
12956 (`(16)
12957 (save-excursion
12958 (org-back-to-heading t)
12959 (let ((regexp (if deadline? org-deadline-time-regexp
12960 org-scheduled-time-regexp)))
12961 (if (not (re-search-forward regexp (line-end-position 2) t))
12962 (user-error (if deadline? "No deadline information to update"
12963 "No scheduled information to update"))
12964 (let* ((rpl0 (match-string 1))
12965 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12966 (msg (if deadline? "Warn starting from" "Delay until")))
12967 (replace-match
12968 (concat keyword
12969 " <" rpl
12970 (format " -%dd"
12971 (abs (- (time-to-days
12972 (save-match-data
12973 (org-read-date
12974 nil t nil msg old-date-time)))
12975 (time-to-days old-date-time))))
12976 ">") t t))))))
12978 (org-add-planning-info type time 'closed)
12979 (when (and old-date
12981 (not (equal old-date org-last-inserted-timestamp)))
12982 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12983 org-last-inserted-timestamp
12984 old-date
12985 log))
12986 (when repeater
12987 (save-excursion
12988 (org-back-to-heading t)
12989 (when (re-search-forward
12990 (concat keyword " " org-last-inserted-timestamp)
12991 (line-end-position 2)
12993 (goto-char (1- (match-end 0)))
12994 (insert " " repeater)
12995 (setq org-last-inserted-timestamp
12996 (concat (substring org-last-inserted-timestamp 0 -1)
12997 " " repeater
12998 (substring org-last-inserted-timestamp -1))))))
12999 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13000 org-last-inserted-timestamp)))))
13002 (defun org-deadline (arg &optional time)
13003 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13004 With one universal prefix argument, remove any deadline from the item.
13005 With two universal prefix arguments, prompt for a warning delay.
13006 With argument TIME, set the deadline at the corresponding date. TIME
13007 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13008 (interactive "P")
13009 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13010 (org-map-entries
13011 (lambda () (org--deadline-or-schedule arg 'deadline time))
13013 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13014 'region-start-level
13015 'region)
13016 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13017 (org--deadline-or-schedule arg 'deadline time)))
13019 (defun org-schedule (arg &optional time)
13020 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13021 With one universal prefix argument, remove any scheduling date from the item.
13022 With two universal prefix arguments, prompt for a delay cookie.
13023 With argument TIME, scheduled at the corresponding date. TIME can
13024 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13025 (interactive "P")
13026 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13027 (org-map-entries
13028 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13030 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13031 'region-start-level
13032 'region)
13033 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13034 (org--deadline-or-schedule arg 'scheduled time)))
13036 (defun org-get-scheduled-time (pom &optional inherit)
13037 "Get the scheduled time as a time tuple, of a format suitable
13038 for calling org-schedule with, or if there is no scheduling,
13039 returns nil."
13040 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13041 (when time
13042 (apply 'encode-time (org-parse-time-string time)))))
13044 (defun org-get-deadline-time (pom &optional inherit)
13045 "Get the deadline as a time tuple, of a format suitable for
13046 calling org-deadline with, or if there is no scheduling, returns
13047 nil."
13048 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13049 (when time
13050 (apply 'encode-time (org-parse-time-string time)))))
13052 (defun org-remove-timestamp-with-keyword (keyword)
13053 "Remove all time stamps with KEYWORD in the current entry."
13054 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13055 beg)
13056 (save-excursion
13057 (org-back-to-heading t)
13058 (setq beg (point))
13059 (outline-next-heading)
13060 (while (re-search-backward re beg t)
13061 (replace-match "")
13062 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13063 (equal (char-before) ?\ ))
13064 (backward-delete-char 1)
13065 (when (string-match "^[ \t]*$" (buffer-substring
13066 (point-at-bol) (point-at-eol)))
13067 (delete-region (point-at-bol)
13068 (min (point-max) (1+ (point-at-eol))))))))))
13070 (defvar org-time-was-given) ; dynamically scoped parameter
13071 (defvar org-end-time-was-given) ; dynamically scoped parameter
13073 (defun org-at-planning-p ()
13074 "Non-nil when point is on a planning info line."
13075 ;; This is as accurate and faster than `org-element-at-point' since
13076 ;; planning info location is fixed in the section.
13077 (org-with-wide-buffer
13078 (beginning-of-line)
13079 (and (looking-at-p org-planning-line-re)
13080 (eq (point)
13081 (ignore-errors
13082 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13083 (org-back-to-heading t)
13084 (org-with-limited-levels (org-back-to-heading t)))
13085 (line-beginning-position 2))))))
13087 (defun org-add-planning-info (what &optional time &rest remove)
13088 "Insert new timestamp with keyword in the planning line.
13089 WHAT indicates what kind of time stamp to add. It is a symbol
13090 among `closed', `deadline', `scheduled' and nil. TIME indicates
13091 the time to use. If none is given, the user is prompted for
13092 a date. REMOVE indicates what kind of entries to remove. An old
13093 WHAT entry will also be removed."
13094 (let (org-time-was-given org-end-time-was-given default-time default-input)
13095 (catch 'exit
13096 (when (and (memq what '(scheduled deadline))
13097 (or (not time)
13098 (and (stringp time)
13099 (string-match "^[-+]+[0-9]" time))))
13100 ;; Try to get a default date/time from existing timestamp
13101 (save-excursion
13102 (org-back-to-heading t)
13103 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13104 (when (re-search-forward (if (eq what 'scheduled)
13105 org-scheduled-time-regexp
13106 org-deadline-time-regexp)
13107 end t)
13108 (setq ts (match-string 1)
13109 default-time (apply 'encode-time (org-parse-time-string ts))
13110 default-input (and ts (org-get-compact-tod ts)))))))
13111 (when what
13112 (setq time
13113 (if (stringp time)
13114 ;; This is a string (relative or absolute), set
13115 ;; proper date.
13116 (apply #'encode-time
13117 (org-read-date-analyze
13118 time default-time (decode-time default-time)))
13119 ;; If necessary, get the time from the user
13120 (or time (org-read-date nil 'to-time nil nil
13121 default-time default-input)))))
13123 (org-with-wide-buffer
13124 (org-back-to-heading t)
13125 (forward-line)
13126 (unless (bolp) (insert "\n"))
13127 (cond ((looking-at-p org-planning-line-re)
13128 ;; Move to current indentation.
13129 (skip-chars-forward " \t")
13130 ;; Check if we have to remove something.
13131 (dolist (type (if what (cons what remove) remove))
13132 (save-excursion
13133 (when (re-search-forward
13134 (cl-case type
13135 (closed org-closed-time-regexp)
13136 (deadline org-deadline-time-regexp)
13137 (scheduled org-scheduled-time-regexp)
13138 (otherwise
13139 (error "Invalid planning type: %s" type)))
13140 (line-end-position) t)
13141 ;; Delete until next keyword or end of line.
13142 (delete-region
13143 (match-beginning 0)
13144 (if (re-search-forward org-keyword-time-not-clock-regexp
13145 (line-end-position)
13147 (match-beginning 0)
13148 (line-end-position))))))
13149 ;; If there is nothing more to add and no more keyword
13150 ;; is left, remove the line completely.
13151 (if (and (looking-at-p "[ \t]*$") (not what))
13152 (delete-region (line-beginning-position)
13153 (line-beginning-position 2))
13154 ;; If we removed last keyword, do not leave trailing
13155 ;; white space at the end of line.
13156 (let ((p (point)))
13157 (save-excursion
13158 (end-of-line)
13159 (unless (= (skip-chars-backward " \t" p) 0)
13160 (delete-region (point) (line-end-position)))))))
13161 ((not what) (throw 'exit nil)) ; Nothing to do.
13162 (t (insert-before-markers "\n")
13163 (backward-char 1)
13164 (when org-adapt-indentation
13165 (indent-to-column (1+ (org-outline-level))))))
13166 (when what
13167 ;; Insert planning keyword.
13168 (insert (cl-case what
13169 (closed org-closed-string)
13170 (deadline org-deadline-string)
13171 (scheduled org-scheduled-string)
13172 (otherwise (error "Invalid planning type: %s" what)))
13173 " ")
13174 ;; Insert associated timestamp.
13175 (let ((ts (org-insert-time-stamp
13176 time
13177 (or org-time-was-given
13178 (and (eq what 'closed) org-log-done-with-time))
13179 (eq what 'closed)
13180 nil nil (list org-end-time-was-given))))
13181 (unless (eolp) (insert " "))
13182 ts))))))
13184 (defvar org-log-note-marker (make-marker)
13185 "Marker pointing at the entry where the note is to be inserted.")
13186 (defvar org-log-note-purpose nil)
13187 (defvar org-log-note-state nil)
13188 (defvar org-log-note-previous-state nil)
13189 (defvar org-log-note-extra nil)
13190 (defvar org-log-note-window-configuration nil)
13191 (defvar org-log-note-return-to (make-marker))
13192 (defvar org-log-note-effective-time nil
13193 "Remembered current time so that dynamically scoped
13194 `org-extend-today-until' affects timestamps in state change log")
13196 (defvar org-log-post-message nil
13197 "Message to be displayed after a log note has been stored.
13198 The auto-repeater uses this.")
13200 (defun org-add-note ()
13201 "Add a note to the current entry.
13202 This is done in the same way as adding a state change note."
13203 (interactive)
13204 (org-add-log-setup 'note))
13206 (defun org-log-beginning (&optional create)
13207 "Return expected start of log notes in current entry.
13208 When optional argument CREATE is non-nil, the function creates
13209 a drawer to store notes, if necessary. Returned position ignores
13210 narrowing."
13211 (org-with-wide-buffer
13212 (let ((drawer (org-log-into-drawer)))
13213 (cond
13214 (drawer
13215 (org-end-of-meta-data)
13216 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13217 (end (if (org-at-heading-p) (point)
13218 (save-excursion (outline-next-heading) (point))))
13219 (case-fold-search t))
13220 (catch 'exit
13221 ;; Try to find existing drawer.
13222 (while (re-search-forward regexp end t)
13223 (let ((element (org-element-at-point)))
13224 (when (eq (org-element-type element) 'drawer)
13225 (let ((cend (org-element-property :contents-end element)))
13226 (when (and (not org-log-states-order-reversed) cend)
13227 (goto-char cend)))
13228 (throw 'exit nil))))
13229 ;; No drawer found. Create one, if permitted.
13230 (when create
13231 (unless (bolp) (insert "\n"))
13232 (let ((beg (point)))
13233 (insert ":" drawer ":\n:END:\n")
13234 (org-indent-region beg (point)))
13235 (end-of-line -1)))))
13237 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13238 (skip-chars-forward " \t\n")
13239 (beginning-of-line)
13240 (unless org-log-states-order-reversed
13241 (org-skip-over-state-notes)
13242 (skip-chars-backward " \t\n")
13243 (forward-line)))))
13244 (if (bolp) (point) (line-beginning-position 2))))
13246 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13247 "Set up the post command hook to take a note.
13248 If this is about to TODO state change, the new state is expected in STATE.
13249 HOW is an indicator what kind of note should be created.
13250 EXTRA is additional text that will be inserted into the notes buffer."
13251 (move-marker org-log-note-marker (point))
13252 (setq org-log-note-purpose purpose
13253 org-log-note-state state
13254 org-log-note-previous-state prev-state
13255 org-log-note-how how
13256 org-log-note-extra extra
13257 org-log-note-effective-time (org-current-effective-time))
13258 (add-hook 'post-command-hook 'org-add-log-note 'append))
13260 (defun org-skip-over-state-notes ()
13261 "Skip past the list of State notes in an entry."
13262 (when (ignore-errors (goto-char (org-in-item-p)))
13263 (let* ((struct (org-list-struct))
13264 (prevs (org-list-prevs-alist struct))
13265 (regexp
13266 (concat "[ \t]*- +"
13267 (replace-regexp-in-string
13268 " +" " +"
13269 (org-replace-escapes
13270 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13271 `(("%d" . ,org-ts-regexp-inactive)
13272 ("%D" . ,org-ts-regexp)
13273 ("%s" . "\"\\S-+\"")
13274 ("%S" . "\"\\S-+\"")
13275 ("%t" . ,org-ts-regexp-inactive)
13276 ("%T" . ,org-ts-regexp)
13277 ("%u" . ".*?")
13278 ("%U" . ".*?")))))))
13279 (while (looking-at-p regexp)
13280 (goto-char (or (org-list-get-next-item (point) struct prevs)
13281 (org-list-get-item-end (point) struct)))))))
13283 (defun org-add-log-note (&optional _purpose)
13284 "Pop up a window for taking a note, and add this note later."
13285 (remove-hook 'post-command-hook 'org-add-log-note)
13286 (setq org-log-note-window-configuration (current-window-configuration))
13287 (delete-other-windows)
13288 (move-marker org-log-note-return-to (point))
13289 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13290 (goto-char org-log-note-marker)
13291 (org-switch-to-buffer-other-window "*Org Note*")
13292 (erase-buffer)
13293 (if (memq org-log-note-how '(time state))
13294 (org-store-log-note)
13295 (let ((org-inhibit-startup t)) (org-mode))
13296 (insert (format "# Insert note for %s.
13297 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13298 (cond
13299 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13300 ((eq org-log-note-purpose 'done) "closed todo item")
13301 ((eq org-log-note-purpose 'state)
13302 (format "state change from \"%s\" to \"%s\""
13303 (or org-log-note-previous-state "")
13304 (or org-log-note-state "")))
13305 ((eq org-log-note-purpose 'reschedule)
13306 "rescheduling")
13307 ((eq org-log-note-purpose 'delschedule)
13308 "no longer scheduled")
13309 ((eq org-log-note-purpose 'redeadline)
13310 "changing deadline")
13311 ((eq org-log-note-purpose 'deldeadline)
13312 "removing deadline")
13313 ((eq org-log-note-purpose 'refile)
13314 "refiling")
13315 ((eq org-log-note-purpose 'note)
13316 "this entry")
13317 (t (error "This should not happen")))))
13318 (when org-log-note-extra (insert org-log-note-extra))
13319 (setq-local org-finish-function 'org-store-log-note)
13320 (run-hooks 'org-log-buffer-setup-hook)))
13322 (defvar org-note-abort nil) ; dynamically scoped
13323 (defun org-store-log-note ()
13324 "Finish taking a log note, and insert it to where it belongs."
13325 (let ((txt (prog1 (buffer-string)
13326 (kill-buffer)))
13327 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13328 lines)
13329 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13330 (setq txt (replace-match "" t t txt)))
13331 (when (string-match "\\s-+\\'" txt)
13332 (setq txt (replace-match "" t t txt)))
13333 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13334 (when (org-string-nw-p note)
13335 (setq note
13336 (org-replace-escapes
13337 note
13338 (list (cons "%u" (user-login-name))
13339 (cons "%U" user-full-name)
13340 (cons "%t" (format-time-string
13341 (org-time-stamp-format 'long 'inactive)
13342 org-log-note-effective-time))
13343 (cons "%T" (format-time-string
13344 (org-time-stamp-format 'long nil)
13345 org-log-note-effective-time))
13346 (cons "%d" (format-time-string
13347 (org-time-stamp-format nil 'inactive)
13348 org-log-note-effective-time))
13349 (cons "%D" (format-time-string
13350 (org-time-stamp-format nil nil)
13351 org-log-note-effective-time))
13352 (cons "%s" (cond
13353 ((not org-log-note-state) "")
13354 ((string-match-p org-ts-regexp
13355 org-log-note-state)
13356 (format "\"[%s]\""
13357 (substring org-log-note-state 1 -1)))
13358 (t (format "\"%s\"" org-log-note-state))))
13359 (cons "%S"
13360 (cond
13361 ((not org-log-note-previous-state) "")
13362 ((string-match-p org-ts-regexp
13363 org-log-note-previous-state)
13364 (format "\"[%s]\""
13365 (substring
13366 org-log-note-previous-state 1 -1)))
13367 (t (format "\"%s\""
13368 org-log-note-previous-state)))))))
13369 (when lines (setq note (concat note " \\\\")))
13370 (push note lines))
13371 (when (and lines (not org-note-abort))
13372 (with-current-buffer (marker-buffer org-log-note-marker)
13373 (org-with-wide-buffer
13374 ;; Find location for the new note.
13375 (goto-char org-log-note-marker)
13376 (set-marker org-log-note-marker nil)
13377 ;; Note associated to a clock is to be located right after
13378 ;; the clock. Do not move point.
13379 (unless (eq org-log-note-purpose 'clock-out)
13380 (goto-char (org-log-beginning t)))
13381 ;; Make sure point is at the beginning of an empty line.
13382 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13383 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13384 ;; In an existing list, add a new item at the top level.
13385 ;; Otherwise, indent line like a regular one.
13386 (let ((itemp (org-in-item-p)))
13387 (if itemp
13388 (indent-line-to
13389 (let ((struct (save-excursion
13390 (goto-char itemp) (org-list-struct))))
13391 (org-list-get-ind (org-list-get-top-point struct) struct)))
13392 (org-indent-line)))
13393 (insert (org-list-bullet-string "-") (pop lines))
13394 (let ((ind (org-list-item-body-column (line-beginning-position))))
13395 (dolist (line lines)
13396 (insert "\n")
13397 (indent-line-to ind)
13398 (insert line)))
13399 (message "Note stored")
13400 (org-back-to-heading t)
13401 (org-cycle-hide-drawers 'children))
13402 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13403 ;; from within `org-add-log-note' because `buffer-undo-list'
13404 ;; is then modified outside of `org-with-remote-undo'.
13405 (when (eq this-command 'org-agenda-todo)
13406 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13407 ;; Don't add undo information when called from `org-agenda-todo'.
13408 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13409 (set-window-configuration org-log-note-window-configuration)
13410 (with-current-buffer (marker-buffer org-log-note-return-to)
13411 (goto-char org-log-note-return-to))
13412 (move-marker org-log-note-return-to nil)
13413 (when org-log-post-message (message "%s" org-log-post-message))))
13415 (defun org-remove-empty-drawer-at (pos)
13416 "Remove an empty drawer at position POS.
13417 POS may also be a marker."
13418 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13419 (org-with-wide-buffer
13420 (goto-char pos)
13421 (let ((drawer (org-element-at-point)))
13422 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13423 (not (org-element-property :contents-begin drawer)))
13424 (delete-region (org-element-property :begin drawer)
13425 (progn (goto-char (org-element-property :end drawer))
13426 (skip-chars-backward " \r\t\n")
13427 (forward-line)
13428 (point))))))))
13430 (defvar org-ts-type nil)
13431 (defun org-sparse-tree (&optional arg type)
13432 "Create a sparse tree, prompt for the details.
13433 This command can create sparse trees. You first need to select the type
13434 of match used to create the tree:
13436 t Show all TODO entries.
13437 T Show entries with a specific TODO keyword.
13438 m Show entries selected by a tags/property match.
13439 p Enter a property name and its value (both with completion on existing
13440 names/values) and show entries with that property.
13441 r Show entries matching a regular expression (`/' can be used as well).
13442 b Show deadlines and scheduled items before a date.
13443 a Show deadlines and scheduled items after a date.
13444 d Show deadlines due within `org-deadline-warning-days'.
13445 D Show deadlines and scheduled items between a date range."
13446 (interactive "P")
13447 (setq type (or type org-sparse-tree-default-date-type))
13448 (setq org-ts-type type)
13449 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13450 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13451 \[c]ycle through date types: %s"
13452 (cl-case type
13453 (all "all timestamps")
13454 (scheduled "only scheduled")
13455 (deadline "only deadline")
13456 (active "only active timestamps")
13457 (inactive "only inactive timestamps")
13458 (closed "with a closed time-stamp")
13459 (otherwise "scheduled/deadline")))
13460 (let ((answer (read-char-exclusive)))
13461 (cl-case answer
13463 (org-sparse-tree
13465 (cadr
13466 (memq type '(nil all scheduled deadline active inactive closed)))))
13467 (?d (call-interactively 'org-check-deadlines))
13468 (?b (call-interactively 'org-check-before-date))
13469 (?a (call-interactively 'org-check-after-date))
13470 (?D (call-interactively 'org-check-dates-range))
13471 (?t (call-interactively 'org-show-todo-tree))
13472 (?T (org-show-todo-tree '(4)))
13473 (?m (call-interactively 'org-match-sparse-tree))
13474 ((?p ?P)
13475 (let* ((kwd (completing-read
13476 "Property: " (mapcar #'list (org-buffer-property-keys))))
13477 (value (completing-read
13478 "Value: " (mapcar #'list (org-property-values kwd)))))
13479 (unless (string-match "\\`{.*}\\'" value)
13480 (setq value (concat "\"" value "\"")))
13481 (org-match-sparse-tree arg (concat kwd "=" value))))
13482 ((?r ?R ?/) (call-interactively 'org-occur))
13483 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13485 (defvar-local org-occur-highlights nil
13486 "List of overlays used for occur matches.")
13487 (defvar-local org-occur-parameters nil
13488 "Parameters of the active org-occur calls.
13489 This is a list, each call to org-occur pushes as cons cell,
13490 containing the regular expression and the callback, onto the list.
13491 The list can contain several entries if `org-occur' has been called
13492 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13493 will only contain one set of parameters. When the highlights are
13494 removed (for example with `C-c C-c', or with the next edit (depending
13495 on `org-remove-highlights-with-change'), this variable is emptied
13496 as well.")
13498 (defun org-occur (regexp &optional keep-previous callback)
13499 "Make a compact tree which shows all matches of REGEXP.
13501 The tree will show the lines where the regexp matches, and any other context
13502 defined in `org-show-context-detail', which see.
13504 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13505 done by a previous call to `org-occur' will be kept, to allow stacking of
13506 calls to this command.
13508 Optional argument CALLBACK can be a function of no argument. In this case,
13509 it is called with point at the end of the match, match data being set
13510 accordingly. Current match is shown only if the return value is non-nil.
13511 The function must neither move point nor alter narrowing."
13512 (interactive "sRegexp: \nP")
13513 (when (equal regexp "")
13514 (user-error "Regexp cannot be empty"))
13515 (unless keep-previous
13516 (org-remove-occur-highlights nil nil t))
13517 (push (cons regexp callback) org-occur-parameters)
13518 (let ((cnt 0))
13519 (save-excursion
13520 (goto-char (point-min))
13521 (when (or (not keep-previous) ; do not want to keep
13522 (not org-occur-highlights)) ; no previous matches
13523 ;; hide everything
13524 (org-overview))
13525 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13526 (isearch-no-upper-case-p regexp t)
13527 org-occur-case-fold-search)))
13528 (while (re-search-forward regexp nil t)
13529 (when (or (not callback)
13530 (save-match-data (funcall callback)))
13531 (setq cnt (1+ cnt))
13532 (when org-highlight-sparse-tree-matches
13533 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13534 (org-show-context 'occur-tree)))))
13535 (when org-remove-highlights-with-change
13536 (add-hook 'before-change-functions 'org-remove-occur-highlights
13537 nil 'local))
13538 (unless org-sparse-tree-open-archived-trees
13539 (org-hide-archived-subtrees (point-min) (point-max)))
13540 (run-hooks 'org-occur-hook)
13541 (when (called-interactively-p 'interactive)
13542 (message "%d match(es) for regexp %s" cnt regexp))
13543 cnt))
13545 (defun org-occur-next-match (&optional n _reset)
13546 "Function for `next-error-function' to find sparse tree matches.
13547 N is the number of matches to move, when negative move backwards.
13548 This function always goes back to the starting point when no
13549 match is found."
13550 (let* ((limit (if (< n 0) (point-min) (point-max)))
13551 (search-func (if (< n 0)
13552 'previous-single-char-property-change
13553 'next-single-char-property-change))
13554 (n (abs n))
13555 (pos (point))
13557 (catch 'exit
13558 (while (setq p1 (funcall search-func (point) 'org-type))
13559 (when (equal p1 limit)
13560 (goto-char pos)
13561 (user-error "No more matches"))
13562 (when (equal (get-char-property p1 'org-type) 'org-occur)
13563 (setq n (1- n))
13564 (when (= n 0)
13565 (goto-char p1)
13566 (throw 'exit (point))))
13567 (goto-char p1))
13568 (goto-char p1)
13569 (user-error "No more matches"))))
13571 (defun org-show-context (&optional key)
13572 "Make sure point and context are visible.
13573 Optional argument KEY, when non-nil, is a symbol. See
13574 `org-show-context-detail' for allowed values and how much is to
13575 be shown."
13576 (org-show-set-visibility
13577 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13578 ((cdr (assq key org-show-context-detail)))
13579 (t (cdr (assq 'default org-show-context-detail))))))
13581 (defun org-show-set-visibility (detail)
13582 "Set visibility around point according to DETAIL.
13583 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13584 `tree', `canonical' or t. See `org-show-context-detail' for more
13585 information."
13586 ;; Show current heading and possibly its entry, following headline
13587 ;; or all children.
13588 (if (and (org-at-heading-p) (not (eq detail 'local)))
13589 (org-flag-heading nil)
13590 (org-show-entry)
13591 ;; If point is hidden within a drawer or a block, make sure to
13592 ;; expose it.
13593 (dolist (o (overlays-at (point)))
13594 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13595 (delete-overlay o)))
13596 (unless (org-before-first-heading-p)
13597 (org-with-limited-levels
13598 (cl-case detail
13599 ((tree canonical t) (org-show-children))
13600 ((nil minimal ancestors))
13601 (t (save-excursion
13602 (outline-next-heading)
13603 (org-flag-heading nil)))))))
13604 ;; Show all siblings.
13605 (when (eq detail 'lineage) (org-show-siblings))
13606 ;; Show ancestors, possibly with their children.
13607 (when (memq detail '(ancestors lineage tree canonical t))
13608 (save-excursion
13609 (while (org-up-heading-safe)
13610 (org-flag-heading nil)
13611 (when (memq detail '(canonical t)) (org-show-entry))
13612 (when (memq detail '(tree canonical t)) (org-show-children))))))
13614 (defvar org-reveal-start-hook nil
13615 "Hook run before revealing a location.")
13617 (defun org-reveal (&optional siblings)
13618 "Show current entry, hierarchy above it, and the following headline.
13620 This can be used to show a consistent set of context around
13621 locations exposed with `org-show-context'.
13623 With optional argument SIBLINGS, on each level of the hierarchy all
13624 siblings are shown. This repairs the tree structure to what it would
13625 look like when opened with hierarchical calls to `org-cycle'.
13627 With a \\[universal-argument] \\[universal-argument] prefix, \
13628 go to the parent and show the entire tree."
13629 (interactive "P")
13630 (run-hooks 'org-reveal-start-hook)
13631 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13632 ((equal siblings '(16))
13633 (save-excursion
13634 (when (org-up-heading-safe)
13635 (org-show-subtree)
13636 (run-hook-with-args 'org-cycle-hook 'subtree))))
13637 (t (org-show-set-visibility 'lineage))))
13639 (defun org-highlight-new-match (beg end)
13640 "Highlight from BEG to END and mark the highlight is an occur headline."
13641 (let ((ov (make-overlay beg end)))
13642 (overlay-put ov 'face 'secondary-selection)
13643 (overlay-put ov 'org-type 'org-occur)
13644 (push ov org-occur-highlights)))
13646 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13647 "Remove the occur highlights from the buffer.
13648 BEG and END are ignored. If NOREMOVE is nil, remove this function
13649 from the `before-change-functions' in the current buffer."
13650 (interactive)
13651 (unless org-inhibit-highlight-removal
13652 (mapc #'delete-overlay org-occur-highlights)
13653 (setq org-occur-highlights nil)
13654 (setq org-occur-parameters nil)
13655 (unless noremove
13656 (remove-hook 'before-change-functions
13657 'org-remove-occur-highlights 'local))))
13659 ;;;; Priorities
13661 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13662 "Regular expression matching the priority indicator.")
13664 (defvar org-remove-priority-next-time nil)
13666 (defun org-priority-up ()
13667 "Increase the priority of the current item."
13668 (interactive)
13669 (org-priority 'up))
13671 (defun org-priority-down ()
13672 "Decrease the priority of the current item."
13673 (interactive)
13674 (org-priority 'down))
13676 (defun org-priority (&optional action _show)
13677 "Change the priority of an item.
13678 ACTION can be `set', `up', `down', or a character."
13679 (interactive "P")
13680 (if (equal action '(4))
13681 (org-show-priority)
13682 (unless org-enable-priority-commands
13683 (user-error "Priority commands are disabled"))
13684 (setq action (or action 'set))
13685 (let (current new news have remove)
13686 (save-excursion
13687 (org-back-to-heading t)
13688 (when (looking-at org-priority-regexp)
13689 (setq current (string-to-char (match-string 2))
13690 have t))
13691 (cond
13692 ((eq action 'remove)
13693 (setq remove t new ?\ ))
13694 ((or (eq action 'set)
13695 (integerp action))
13696 (if (not (eq action 'set))
13697 (setq new action)
13698 (message "Priority %c-%c, SPC to remove: "
13699 org-highest-priority org-lowest-priority)
13700 (save-match-data
13701 (setq new (read-char-exclusive))))
13702 (when (and (= (upcase org-highest-priority) org-highest-priority)
13703 (= (upcase org-lowest-priority) org-lowest-priority))
13704 (setq new (upcase new)))
13705 (cond ((equal new ?\ ) (setq remove t))
13706 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13707 (user-error "Priority must be between `%c' and `%c'"
13708 org-highest-priority org-lowest-priority))))
13709 ((eq action 'up)
13710 (setq new (if have
13711 (1- current) ; normal cycling
13712 ;; last priority was empty
13713 (if (eq last-command this-command)
13714 org-lowest-priority ; wrap around empty to lowest
13715 ;; default
13716 (if org-priority-start-cycle-with-default
13717 org-default-priority
13718 (1- org-default-priority))))))
13719 ((eq action 'down)
13720 (setq new (if have
13721 (1+ current) ; normal cycling
13722 ;; last priority was empty
13723 (if (eq last-command this-command)
13724 org-highest-priority ; wrap around empty to highest
13725 ;; default
13726 (if org-priority-start-cycle-with-default
13727 org-default-priority
13728 (1+ org-default-priority))))))
13729 (t (user-error "Invalid action")))
13730 (when (or (< (upcase new) org-highest-priority)
13731 (> (upcase new) org-lowest-priority))
13732 (if (and (memq action '(up down))
13733 (not have) (not (eq last-command this-command)))
13734 ;; `new' is from default priority
13735 (error
13736 "The default can not be set, see `org-default-priority' why")
13737 ;; normal cycling: `new' is beyond highest/lowest priority
13738 ;; and is wrapped around to the empty priority
13739 (setq remove t)))
13740 (setq news (format "%c" new))
13741 (if have
13742 (if remove
13743 (replace-match "" t t nil 1)
13744 (replace-match news t t nil 2))
13745 (if remove
13746 (user-error "No priority cookie found in line")
13747 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13748 (if (match-end 2)
13749 (progn
13750 (goto-char (match-end 2))
13751 (insert " [#" news "]"))
13752 (goto-char (match-beginning 3))
13753 (insert "[#" news "] "))))
13754 (org-set-tags nil 'align))
13755 (if remove
13756 (message "Priority removed")
13757 (message "Priority of current item set to %s" news)))))
13759 (defun org-show-priority ()
13760 "Show the priority of the current item.
13761 This priority is composed of the main priority given with the [#A] cookies,
13762 and by additional input from the age of a schedules or deadline entry."
13763 (interactive)
13764 (let ((pri (if (eq major-mode 'org-agenda-mode)
13765 (org-get-at-bol 'priority)
13766 (save-excursion
13767 (save-match-data
13768 (beginning-of-line)
13769 (and (looking-at org-heading-regexp)
13770 (org-get-priority (match-string 0))))))))
13771 (message "Priority is %d" (if pri pri -1000))))
13773 (defun org-get-priority (s)
13774 "Find priority cookie and return priority."
13775 (save-match-data
13776 (if (functionp org-get-priority-function)
13777 (funcall org-get-priority-function)
13778 (if (not (string-match org-priority-regexp s))
13779 (* 1000 (- org-lowest-priority org-default-priority))
13780 (* 1000 (- org-lowest-priority
13781 (string-to-char (match-string 2 s))))))))
13783 ;;;; Tags
13785 (defvar org-agenda-archives-mode)
13786 (defvar org-map-continue-from nil
13787 "Position from where mapping should continue.
13788 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13790 (defvar org-scanner-tags nil
13791 "The current tag list while the tags scanner is running.")
13793 (defvar org-trust-scanner-tags nil
13794 "Should `org-get-tags-at' use the tags for the scanner.
13795 This is for internal dynamical scoping only.
13796 When this is non-nil, the function `org-get-tags-at' will return the value
13797 of `org-scanner-tags' instead of building the list by itself. This
13798 can lead to large speed-ups when the tags scanner is used in a file with
13799 many entries, and when the list of tags is retrieved, for example to
13800 obtain a list of properties. Building the tags list for each entry in such
13801 a file becomes an N^2 operation - but with this variable set, it scales
13802 as N.")
13804 (defvar org--matcher-tags-todo-only nil)
13806 (defun org-scan-tags (action matcher todo-only &optional start-level)
13807 "Scan headline tags with inheritance and produce output ACTION.
13809 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13810 or `agenda' to produce an entry list for an agenda view. It can also be
13811 a Lisp form or a function that should be called at each matched headline, in
13812 this case the return value is a list of all return values from these calls.
13814 MATCHER is a function accepting three arguments, returning
13815 a non-nil value whenever a given set of tags qualifies a headline
13816 for inclusion. See `org-make-tags-matcher' for more information.
13817 As a special case, it can also be set to t (respectively nil) in
13818 order to match all (respectively none) headline.
13820 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13821 included in the output.
13823 START-LEVEL can be a string with asterisks, reducing the scope to
13824 headlines matching this string."
13825 (require 'org-agenda)
13826 (let* ((re (concat "^"
13827 (if start-level
13828 ;; Get the correct level to match
13829 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13830 org-outline-regexp)
13831 " *\\(\\<\\("
13832 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13833 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13834 (props (list 'face 'default
13835 'done-face 'org-agenda-done
13836 'undone-face 'default
13837 'mouse-face 'highlight
13838 'org-not-done-regexp org-not-done-regexp
13839 'org-todo-regexp org-todo-regexp
13840 'org-complex-heading-regexp org-complex-heading-regexp
13841 'help-echo
13842 (format "mouse-2 or RET jump to org file %s"
13843 (abbreviate-file-name
13844 (or (buffer-file-name (buffer-base-buffer))
13845 (buffer-name (buffer-base-buffer)))))))
13846 (org-map-continue-from nil)
13847 lspos tags tags-list
13848 (tags-alist (list (cons 0 org-file-tags)))
13849 (llast 0) rtn rtn1 level category i txt
13850 todo marker entry priority
13851 ts-date ts-date-type ts-date-pair)
13852 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13853 (setq action (list 'lambda nil action)))
13854 (save-excursion
13855 (goto-char (point-min))
13856 (when (eq action 'sparse-tree)
13857 (org-overview)
13858 (org-remove-occur-highlights))
13859 (while (let (case-fold-search)
13860 (re-search-forward re nil t))
13861 (setq org-map-continue-from nil)
13862 (catch :skip
13863 (setq todo
13864 ;; TODO: is the 1-2 difference a bug?
13865 (when (match-end 1) (match-string-no-properties 2))
13866 tags (when (match-end 4) (match-string-no-properties 4)))
13867 (goto-char (setq lspos (match-beginning 0)))
13868 (setq level (org-reduced-level (org-outline-level))
13869 category (org-get-category))
13870 (when (eq action 'agenda)
13871 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13872 ts-date (car ts-date-pair)
13873 ts-date-type (cdr ts-date-pair)))
13874 (setq i llast llast level)
13875 ;; remove tag lists from same and sublevels
13876 (while (>= i level)
13877 (when (setq entry (assoc i tags-alist))
13878 (setq tags-alist (delete entry tags-alist)))
13879 (setq i (1- i)))
13880 ;; add the next tags
13881 (when tags
13882 (setq tags (org-split-string tags ":")
13883 tags-alist
13884 (cons (cons level tags) tags-alist)))
13885 ;; compile tags for current headline
13886 (setq tags-list
13887 (if org-use-tag-inheritance
13888 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13889 tags)
13890 org-scanner-tags tags-list)
13891 (when org-use-tag-inheritance
13892 (setcdr (car tags-alist)
13893 (mapcar (lambda (x)
13894 (setq x (copy-sequence x))
13895 (org-add-prop-inherited x))
13896 (cdar tags-alist))))
13897 (when (and tags org-use-tag-inheritance
13898 (or (not (eq t org-use-tag-inheritance))
13899 org-tags-exclude-from-inheritance))
13900 ;; Selective inheritance, remove uninherited ones.
13901 (setcdr (car tags-alist)
13902 (org-remove-uninherited-tags (cdar tags-alist))))
13903 (when (and
13905 ;; eval matcher only when the todo condition is OK
13906 (and (or (not todo-only) (member todo org-todo-keywords-1))
13907 (if (functionp matcher)
13908 (let ((case-fold-search t) (org-trust-scanner-tags t))
13909 (funcall matcher todo tags-list level))
13910 matcher))
13912 ;; Call the skipper, but return t if it does not
13913 ;; skip, so that the `and' form continues evaluating.
13914 (progn
13915 (unless (eq action 'sparse-tree) (org-agenda-skip))
13918 ;; Check if timestamps are deselecting this entry
13919 (or (not todo-only)
13920 (and (member todo org-todo-keywords-1)
13921 (or (not org-agenda-tags-todo-honor-ignore-options)
13922 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13924 ;; select this headline
13925 (cond
13926 ((eq action 'sparse-tree)
13927 (and org-highlight-sparse-tree-matches
13928 (org-get-heading) (match-end 0)
13929 (org-highlight-new-match
13930 (match-beginning 1) (match-end 1)))
13931 (org-show-context 'tags-tree))
13932 ((eq action 'agenda)
13933 (setq txt (org-agenda-format-item
13935 (concat
13936 (if (eq org-tags-match-list-sublevels 'indented)
13937 (make-string (1- level) ?.) "")
13938 (org-get-heading))
13939 (make-string level ?\s)
13940 category
13941 tags-list)
13942 priority (org-get-priority txt))
13943 (goto-char lspos)
13944 (setq marker (org-agenda-new-marker))
13945 (org-add-props txt props
13946 'org-marker marker 'org-hd-marker marker 'org-category category
13947 'todo-state todo
13948 'ts-date ts-date
13949 'priority priority
13950 'type (concat "tagsmatch" ts-date-type))
13951 (push txt rtn))
13952 ((functionp action)
13953 (setq org-map-continue-from nil)
13954 (save-excursion
13955 (setq rtn1 (funcall action))
13956 (push rtn1 rtn)))
13957 (t (user-error "Invalid action")))
13959 ;; if we are to skip sublevels, jump to end of subtree
13960 (unless org-tags-match-list-sublevels
13961 (org-end-of-subtree t)
13962 (backward-char 1))))
13963 ;; Get the correct position from where to continue
13964 (if org-map-continue-from
13965 (goto-char org-map-continue-from)
13966 (and (= (point) lspos) (end-of-line 1)))))
13967 (when (and (eq action 'sparse-tree)
13968 (not org-sparse-tree-open-archived-trees))
13969 (org-hide-archived-subtrees (point-min) (point-max)))
13970 (nreverse rtn)))
13972 (defun org-remove-uninherited-tags (tags)
13973 "Remove all tags that are not inherited from the list TAGS."
13974 (cond
13975 ((eq org-use-tag-inheritance t)
13976 (if org-tags-exclude-from-inheritance
13977 (org-delete-all org-tags-exclude-from-inheritance tags)
13978 tags))
13979 ((not org-use-tag-inheritance) nil)
13980 ((stringp org-use-tag-inheritance)
13981 (delq nil (mapcar
13982 (lambda (x)
13983 (if (and (string-match org-use-tag-inheritance x)
13984 (not (member x org-tags-exclude-from-inheritance)))
13985 x nil))
13986 tags)))
13987 ((listp org-use-tag-inheritance)
13988 (delq nil (mapcar
13989 (lambda (x)
13990 (if (member x org-use-tag-inheritance) x nil))
13991 tags)))))
13993 (defun org-match-sparse-tree (&optional todo-only match)
13994 "Create a sparse tree according to tags string MATCH.
13996 MATCH is a string with match syntax. It can contain a selection
13997 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13998 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13999 those. See the manual for details.
14001 If optional argument TODO-ONLY is non-nil, only select lines that
14002 are also TODO tasks."
14003 (interactive "P")
14004 (org-agenda-prepare-buffers (list (current-buffer)))
14005 (let ((org--matcher-tags-todo-only todo-only))
14006 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14007 org--matcher-tags-todo-only)))
14009 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14011 (defvar org-cached-props nil)
14012 (defun org-cached-entry-get (pom property)
14013 (if (or (eq t org-use-property-inheritance)
14014 (and (stringp org-use-property-inheritance)
14015 (let ((case-fold-search t))
14016 (string-match-p org-use-property-inheritance property)))
14017 (and (listp org-use-property-inheritance)
14018 (member-ignore-case property org-use-property-inheritance)))
14019 ;; Caching is not possible, check it directly.
14020 (org-entry-get pom property 'inherit)
14021 ;; Get all properties, so we can do complicated checks easily.
14022 (cdr (assoc-string property
14023 (or org-cached-props
14024 (setq org-cached-props (org-entry-properties pom)))
14025 t))))
14027 (defun org-global-tags-completion-table (&optional files)
14028 "Return the list of all tags in all agenda buffer/files.
14029 Optional FILES argument is a list of files which can be used
14030 instead of the agenda files."
14031 (save-excursion
14032 (org-uniquify
14033 (delq nil
14034 (apply #'append
14035 (mapcar
14036 (lambda (file)
14037 (set-buffer (find-file-noselect file))
14038 (mapcar (lambda (x)
14039 (and (stringp (car-safe x))
14040 (list (car-safe x))))
14041 (or org-current-tag-alist (org-get-buffer-tags))))
14042 (if (car-safe files) files
14043 (org-agenda-files))))))))
14045 (defun org-make-tags-matcher (match)
14046 "Create the TAGS/TODO matcher form for the selection string MATCH.
14048 Returns a cons of the selection string MATCH and a function
14049 implementing the matcher.
14051 The matcher is to be called at an Org entry, with point on the
14052 headline, and returns non-nil if the entry matches the selection
14053 string MATCH. It must be called with three arguments: the TODO
14054 keyword at the entry (or nil if none), the list of all tags at
14055 the entry including inherited ones and the reduced level of the
14056 headline. Additionally, the category of the entry, if any, must
14057 be specified as the text property `org-category' on the headline.
14059 This function sets the variable `org--matcher-tags-todo-only' to
14060 a non-nil value if the matcher restricts matching to TODO
14061 entries, otherwise it is not touched.
14063 See also `org-scan-tags'."
14064 (unless match
14065 ;; Get a new match request, with completion against the global
14066 ;; tags table and the local tags in current buffer.
14067 (let ((org-last-tags-completion-table
14068 (org-uniquify
14069 (delq nil (append (org-get-buffer-tags)
14070 (org-global-tags-completion-table))))))
14071 (setq match
14072 (completing-read
14073 "Match: "
14074 'org-tags-completion-function nil nil nil 'org-tags-history))))
14076 (let ((match0 match)
14077 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14078 (start 0)
14079 tagsmatch todomatch tagsmatcher todomatcher)
14081 ;; Expand group tags.
14082 (setq match (org-tags-expand match))
14084 ;; Check if there is a TODO part of this match, which would be the
14085 ;; part after a "/". To make sure that this slash is not part of
14086 ;; a property value to be matched against, we also check that
14087 ;; there is no / after that slash. First, find the last slash.
14088 (let ((s 0))
14089 (while (string-match "/+" match s)
14090 (setq start (match-beginning 0))
14091 (setq s (match-end 0))))
14092 (if (and (string-match "/+" match start)
14093 (not (string-match-p "\"" match start)))
14094 ;; Match contains also a TODO-matching request.
14095 (progn
14096 (setq tagsmatch (substring match 0 (match-beginning 0)))
14097 (setq todomatch (substring match (match-end 0)))
14098 (when (string-prefix-p "!" todomatch)
14099 (setq org--matcher-tags-todo-only t)
14100 (setq todomatch (substring todomatch 1)))
14101 (when (string-match "\\`\\s-*\\'" todomatch)
14102 (setq todomatch nil)))
14103 ;; Only matching tags.
14104 (setq tagsmatch match)
14105 (setq todomatch nil))
14107 ;; Make the tags matcher.
14108 (when (org-string-nw-p tagsmatch)
14109 (let ((orlist nil)
14110 (orterms (org-split-string tagsmatch "|"))
14111 term)
14112 (while (setq term (pop orterms))
14113 (while (and (equal (substring term -1) "\\") orterms)
14114 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14115 (while (string-match re term)
14116 (let* ((rest (substring term (match-end 0)))
14117 (minus (and (match-end 1)
14118 (equal (match-string 1 term) "-")))
14119 (tag (save-match-data
14120 (replace-regexp-in-string
14121 "\\\\-" "-" (match-string 2 term))))
14122 (regexp (eq (string-to-char tag) ?{))
14123 (levelp (match-end 4))
14124 (propp (match-end 5))
14126 (cond
14127 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14128 (levelp
14129 `(,(org-op-to-function (match-string 3 term))
14130 level
14131 ,(string-to-number (match-string 4 term))))
14132 (propp
14133 (let* ((gv (pcase (upcase (match-string 5 term))
14134 ("CATEGORY"
14135 '(get-text-property (point) 'org-category))
14136 ("TODO" 'todo)
14137 (p `(org-cached-entry-get nil ,p))))
14138 (pv (match-string 7 term))
14139 (regexp (eq (string-to-char pv) ?{))
14140 (strp (eq (string-to-char pv) ?\"))
14141 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14142 (po (org-op-to-function (match-string 6 term)
14143 (if timep 'time strp))))
14144 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14145 (when timep (setq pv (org-matcher-time pv)))
14146 (cond ((and regexp (eq po 'org<>))
14147 `(not (string-match ,pv (or ,gv ""))))
14148 (regexp `(string-match ,pv (or ,gv "")))
14149 (strp `(,po (or ,gv "") ,pv))
14151 `(,po
14152 (string-to-number (or ,gv ""))
14153 ,(string-to-number pv))))))
14154 (t `(member ,tag tags-list)))))
14155 (push (if minus `(not ,mm) mm) tagsmatcher)
14156 (setq term rest)))
14157 (push `(and ,@tagsmatcher) orlist)
14158 (setq tagsmatcher nil))
14159 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14161 ;; Make the TODO matcher.
14162 (when (org-string-nw-p todomatch)
14163 (let ((orlist nil))
14164 (dolist (term (org-split-string todomatch "|"))
14165 (while (string-match re term)
14166 (let* ((minus (and (match-end 1)
14167 (equal (match-string 1 term) "-")))
14168 (kwd (match-string 2 term))
14169 (regexp (eq (string-to-char kwd) ?{))
14170 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14171 `(equal todo ,kwd))))
14172 (push (if minus `(not ,mm) mm) todomatcher))
14173 (setq term (substring term (match-end 0))))
14174 (push (if (> (length todomatcher) 1)
14175 (cons 'and todomatcher)
14176 (car todomatcher))
14177 orlist)
14178 (setq todomatcher nil))
14179 (setq todomatcher (cons 'or orlist))))
14181 ;; Return the string and function of the matcher. If no
14182 ;; tags-specific or todo-specific matcher exists, match
14183 ;; everything.
14184 (let ((matcher (if (and tagsmatcher todomatcher)
14185 `(and ,tagsmatcher ,todomatcher)
14186 (or tagsmatcher todomatcher t))))
14187 (when org--matcher-tags-todo-only
14188 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14189 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14191 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14192 "Expand group tags in MATCH.
14194 This replaces every group tag in MATCH with a regexp tag search.
14195 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14196 will be replaced like this:
14198 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14199 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14200 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14202 Replacing by a regexp preserves the structure of the match.
14203 E.g., this expansion
14205 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14207 will match anything tagged with \"Lab\" and \"Home\", or tagged
14208 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14210 A group tag in MATCH can contain regular expressions of its own.
14211 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14212 will be replaced like this:
14214 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14216 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14217 assumed to be a single group tag, and the function will return
14218 the list of tags in this group.
14220 When DOWNCASE is non-nil, expand downcased TAGS."
14221 (if org-group-tags
14222 (let* ((case-fold-search t)
14223 (stable org-mode-syntax-table)
14224 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14225 (taggroups (if downcased
14226 (mapcar (lambda (tg) (mapcar #'downcase tg))
14227 taggroups)
14228 taggroups))
14229 (taggroups-keys (mapcar #'car taggroups))
14230 (return-match (if downcased (downcase match) match))
14231 (count 0)
14232 (work-already-expanded tags-already-expanded)
14233 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14234 ;; @ and _ are allowed as word-components in tags.
14235 (modify-syntax-entry ?@ "w" stable)
14236 (modify-syntax-entry ?_ "w" stable)
14237 ;; Temporarily replace regexp-expressions in the match-expression.
14238 (while (string-match "{.+?}" return-match)
14239 (cl-incf count)
14240 (push (match-string 0 return-match) regexps-in-match)
14241 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14242 (while (and taggroups-keys
14243 (with-syntax-table stable
14244 (string-match
14245 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14246 (regexp-opt taggroups-keys) "\\>\\)")
14247 return-match)))
14248 (let* ((dir (match-string 1 return-match))
14249 (tag (match-string 2 return-match))
14250 (tag (if downcased (downcase tag) tag)))
14251 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14252 (member tag work-already-expanded))
14253 (setq tags-in-group (assoc tag taggroups))
14254 (push tag work-already-expanded)
14255 ;; Recursively expand each tag in the group, if the tag hasn't
14256 ;; already been expanded. Restore the match-data after all recursive calls.
14257 (save-match-data
14258 (let (tags-expanded)
14259 (dolist (x (cdr tags-in-group))
14260 (if (and (member x taggroups-keys)
14261 (not (member x work-already-expanded)))
14262 (setq tags-expanded
14263 (delete-dups
14264 (append
14265 (org-tags-expand x t downcased
14266 work-already-expanded)
14267 tags-expanded)))
14268 (setq tags-expanded
14269 (append (list x) tags-expanded)))
14270 (setq work-already-expanded
14271 (delete-dups
14272 (append tags-expanded
14273 work-already-expanded))))
14274 (setq tags-in-group
14275 (delete-dups (cons (car tags-in-group)
14276 tags-expanded)))))
14277 ;; Filter tag-regexps from tags.
14278 (setq regexp-in-group-escaped
14279 (delq nil (mapcar (lambda (x)
14280 (if (stringp x)
14281 (and (equal "{" (substring x 0 1))
14282 (equal "}" (substring x -1))
14285 tags-in-group))
14286 regexp-in-group
14287 (mapcar (lambda (x)
14288 (substring x 1 -1))
14289 regexp-in-group-escaped)
14290 tags-in-group
14291 (delq nil (mapcar (lambda (x)
14292 (if (stringp x)
14293 (and (not (equal "{" (substring x 0 1)))
14294 (not (equal "}" (substring x -1)))
14297 tags-in-group)))
14298 ;; If single-as-list, do no more in the while-loop.
14299 (if (not single-as-list)
14300 (progn
14301 (when regexp-in-group
14302 (setq regexp-in-group
14303 (concat "\\|"
14304 (mapconcat 'identity regexp-in-group
14305 "\\|"))))
14306 (setq tags-in-group
14307 (concat dir
14308 "{\\<"
14309 (regexp-opt tags-in-group)
14310 "\\>"
14311 regexp-in-group
14312 "}"))
14313 (when (stringp tags-in-group)
14314 (org-add-props tags-in-group '(grouptag t)))
14315 (setq return-match
14316 (replace-match tags-in-group t t return-match)))
14317 (setq tags-in-group
14318 (append regexp-in-group-escaped tags-in-group))))
14319 (setq taggroups-keys (delete tag taggroups-keys))))
14320 ;; Add the regular expressions back into the match-expression again.
14321 (while regexps-in-match
14322 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14323 (pop regexps-in-match)
14324 return-match t t))
14325 (cl-decf count))
14326 (if single-as-list
14327 (if tags-in-group tags-in-group (list return-match))
14328 return-match))
14329 (if single-as-list
14330 (list (if downcased (downcase match) match))
14331 match)))
14333 (defun org-op-to-function (op &optional stringp)
14334 "Turn an operator into the appropriate function."
14335 (setq op
14336 (cond
14337 ((equal op "<" ) '(< string< org-time<))
14338 ((equal op ">" ) '(> org-string> org-time>))
14339 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14340 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14341 ((member op '("=" "==")) '(= string= org-time=))
14342 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14343 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14345 (defun org<> (a b) (not (= a b)))
14346 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14347 (defun org-string>= (a b) (not (string< a b)))
14348 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14349 (defun org-string<> (a b) (not (string= a b)))
14350 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14351 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14352 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14353 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14354 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14355 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14356 (defun org-2ft (s)
14357 "Convert S to a floating point time.
14358 If S is already a number, just return it. If it is a string, parse
14359 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14360 (cond
14361 ((numberp s) s)
14362 ((stringp s)
14363 (condition-case nil
14364 (float-time (apply #'encode-time (org-parse-time-string s)))
14365 (error 0.)))
14366 (t 0.)))
14368 (defun org-time-today ()
14369 "Time in seconds today at 0:00.
14370 Returns the float number of seconds since the beginning of the
14371 epoch to the beginning of today (00:00)."
14372 (float-time (apply 'encode-time
14373 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14375 (defun org-matcher-time (s)
14376 "Interpret a time comparison value."
14377 (save-match-data
14378 (cond
14379 ((string= s "<now>") (float-time))
14380 ((string= s "<today>") (org-time-today))
14381 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14382 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14383 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14384 (+ (org-time-today)
14385 (* (string-to-number (match-string 1 s))
14386 (cdr (assoc (match-string 2 s)
14387 '(("d" . 86400.0) ("w" . 604800.0)
14388 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14389 (t (org-2ft s)))))
14391 (defun org-match-any-p (re list)
14392 "Does re match any element of list?"
14393 (setq list (mapcar (lambda (x) (string-match re x)) list))
14394 (delq nil list))
14396 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14397 (defvar org-tags-overlay (make-overlay 1 1))
14398 (delete-overlay org-tags-overlay)
14400 (defun org-get-local-tags-at (&optional pos)
14401 "Get a list of tags defined in the current headline."
14402 (org-get-tags-at pos 'local))
14404 (defun org-get-local-tags ()
14405 "Get a list of tags defined in the current headline."
14406 (org-get-tags-at nil 'local))
14408 (defun org-get-tags-at (&optional pos local)
14409 "Get a list of all headline tags applicable at POS.
14410 POS defaults to point. If tags are inherited, the list contains
14411 the targets in the same sequence as the headlines appear, i.e.
14412 the tags of the current headline come last.
14413 When LOCAL is non-nil, only return tags from the current headline,
14414 ignore inherited ones."
14415 (interactive)
14416 (if (and org-trust-scanner-tags
14417 (or (not pos) (equal pos (point)))
14418 (not local))
14419 org-scanner-tags
14420 (let (tags ltags lastpos parent)
14421 (save-excursion
14422 (save-restriction
14423 (widen)
14424 (goto-char (or pos (point)))
14425 (save-match-data
14426 (catch 'done
14427 (condition-case nil
14428 (progn
14429 (org-back-to-heading t)
14430 (while (not (equal lastpos (point)))
14431 (setq lastpos (point))
14432 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14433 (setq ltags (org-split-string
14434 (match-string-no-properties 1) ":"))
14435 (when parent
14436 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14437 (setq tags (append
14438 (if parent
14439 (org-remove-uninherited-tags ltags)
14440 ltags)
14441 tags)))
14442 (or org-use-tag-inheritance (throw 'done t))
14443 (when local (throw 'done t))
14444 (or (org-up-heading-safe) (error nil))
14445 (setq parent t)))
14446 (error nil)))))
14447 (if local
14448 tags
14449 (reverse (delete-dups
14450 (reverse (append
14451 (org-remove-uninherited-tags
14452 org-file-tags)
14453 tags)))))))))
14455 (defun org-add-prop-inherited (s)
14456 (add-text-properties 0 (length s) '(inherited t) s)
14459 (defun org-toggle-tag (tag &optional onoff)
14460 "Toggle the tag TAG for the current line.
14461 If ONOFF is `on' or `off', don't toggle but set to this state."
14462 (save-excursion
14463 (org-back-to-heading t)
14464 (let ((current
14465 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14466 (line-end-position) t)
14467 (let ((tags (match-string 1)))
14468 ;; Clear current tags.
14469 (replace-match "")
14470 ;; Reverse the tags list so any new tag is appended to
14471 ;; the current list of tags.
14472 (nreverse (org-split-string tags ":")))))
14473 res)
14474 (pcase onoff
14475 (`off (setq current (delete tag current)))
14476 ((or `on (guard (not (member tag current))))
14477 (setq res t)
14478 (cl-pushnew tag current :test #'equal))
14479 (_ (setq current (delete tag current))))
14480 (end-of-line)
14481 (if current
14482 (progn
14483 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14484 (org-set-tags nil t))
14485 (delete-horizontal-space))
14486 (run-hooks 'org-after-tags-change-hook)
14487 res)))
14489 (defun org--align-tags-here (to-col)
14490 "Align tags on the current headline to TO-COL.
14491 Assume point is on a headline."
14492 (let ((pos (point)))
14493 (beginning-of-line)
14494 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14495 (>= pos (match-beginning 2)))
14496 ;; No tags or point within tags: do not align.
14497 (goto-char pos)
14498 (goto-char (match-beginning 1))
14499 (let ((shift (max (- (if (>= to-col 0) to-col
14500 (- (abs to-col) (string-width (match-string 2))))
14501 (current-column))
14502 1)))
14503 (replace-match (make-string shift ?\s) nil nil nil 1)
14504 ;; Preserve initial position, if possible. In any case, stop
14505 ;; before tags.
14506 (when (< pos (point)) (goto-char pos))))))
14508 (defun org-set-tags-command (&optional arg just-align)
14509 "Call the set-tags command for the current entry."
14510 (interactive "P")
14511 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14512 (org-set-tags arg just-align)
14513 (save-excursion
14514 (unless (and (org-region-active-p)
14515 org-loop-over-headlines-in-active-region)
14516 (org-back-to-heading t))
14517 (org-set-tags arg just-align))))
14519 (defun org-set-tags-to (data)
14520 "Set the tags of the current entry to DATA, replacing the current tags.
14521 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14522 If DATA is nil or the empty string, any tags will be removed."
14523 (interactive "sTags: ")
14524 (setq data
14525 (cond
14526 ((eq data nil) "")
14527 ((equal data "") "")
14528 ((stringp data)
14529 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14530 ":"))
14531 ((listp data)
14532 (concat ":" (mapconcat 'identity data ":") ":"))))
14533 (when data
14534 (save-excursion
14535 (org-back-to-heading t)
14536 (when (let ((case-fold-search nil))
14537 (looking-at org-complex-heading-regexp))
14538 (if (match-end 5)
14539 (progn
14540 (goto-char (match-beginning 5))
14541 (insert data)
14542 (delete-region (point) (point-at-eol))
14543 (org-set-tags nil 'align))
14544 (goto-char (point-at-eol))
14545 (insert " " data)
14546 (org-set-tags nil 'align)))
14547 (beginning-of-line 1)
14548 (when (looking-at ".*?\\([ \t]+\\)$")
14549 (delete-region (match-beginning 1) (match-end 1))))))
14551 (defun org-align-all-tags ()
14552 "Align the tags in all headings."
14553 (interactive)
14554 (save-excursion
14555 (or (ignore-errors (org-back-to-heading t))
14556 (outline-next-heading))
14557 (if (org-at-heading-p)
14558 (org-set-tags t)
14559 (message "No headings"))))
14561 (defvar org-indent-indentation-per-level)
14562 (defun org-set-tags (&optional arg just-align)
14563 "Set the tags for the current headline.
14564 With prefix ARG, realign all tags in headings in the current buffer.
14565 When JUST-ALIGN is non-nil, only align tags."
14566 (interactive "P")
14567 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14568 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14569 'region-start-level
14570 'region))
14571 org-loop-over-headlines-in-active-region)
14572 (org-map-entries
14573 ;; We don't use ARG and JUST-ALIGN here because these args
14574 ;; are not useful when looping over headlines.
14575 #'org-set-tags
14576 org-loop-over-headlines-in-active-region
14578 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14579 (let ((org-setting-tags t))
14580 (if arg
14581 (save-excursion
14582 (goto-char (point-min))
14583 (while (re-search-forward org-outline-regexp-bol nil t)
14584 (org-set-tags nil t)
14585 (end-of-line))
14586 (message "All tags realigned to column %d" org-tags-column))
14587 (let* ((current (org-get-tags-string))
14588 (tags
14589 (if just-align current
14590 ;; Get a new set of tags from the user.
14591 (save-excursion
14592 (let* ((seen)
14593 (table
14594 (setq
14595 org-last-tags-completion-table
14596 ;; Uniquify tags in alists, yet preserve
14597 ;; structure (i.e., keywords).
14598 (delq nil
14599 (mapcar
14600 (lambda (pair)
14601 (let ((head (car pair)))
14602 (cond ((symbolp head) pair)
14603 ((member head seen) nil)
14604 (t (push head seen)
14605 pair))))
14606 (append
14607 (or org-current-tag-alist
14608 (org-get-buffer-tags))
14609 (and
14610 org-complete-tags-always-offer-all-agenda-tags
14611 (org-global-tags-completion-table
14612 (org-agenda-files))))))))
14613 (current-tags (org-split-string current ":"))
14614 (inherited-tags
14615 (nreverse (nthcdr (length current-tags)
14616 (nreverse (org-get-tags-at))))))
14617 (replace-regexp-in-string
14618 "\\([-+&]+\\|,\\)"
14620 (if (or (eq t org-use-fast-tag-selection)
14621 (and org-use-fast-tag-selection
14622 (delq nil (mapcar #'cdr table))))
14623 (org-fast-tag-selection
14624 current-tags inherited-tags table
14625 (and org-fast-tag-selection-include-todo
14626 org-todo-key-alist))
14627 (let ((org-add-colon-after-tag-completion
14628 (< 1 (length table))))
14629 (org-trim
14630 (completing-read
14631 "Tags: "
14632 #'org-tags-completion-function
14633 nil nil current 'org-tags-history))))))))))
14635 (when org-tags-sort-function
14636 (setq tags
14637 (mapconcat
14638 #'identity
14639 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14640 org-tags-sort-function)
14641 ":")))
14643 (if (or (string= ":" tags)
14644 (string= "::" tags))
14645 (setq tags ""))
14646 (if (not (org-string-nw-p tags)) (setq tags "")
14647 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14648 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14650 ;; Insert new tags at the correct column.
14651 (unless (equal current tags)
14652 (save-excursion
14653 (beginning-of-line)
14654 (let ((case-fold-search nil))
14655 (looking-at org-complex-heading-regexp))
14656 ;; Remove current tags, if any.
14657 (when (match-end 5) (replace-match "" nil nil nil 5))
14658 ;; Insert new tags, if any. Otherwise, remove trailing
14659 ;; white spaces.
14660 (end-of-line)
14661 (if (not (equal tags ""))
14662 ;; When text is being inserted on an invisible
14663 ;; region boundary, it can be inadvertently sucked
14664 ;; into invisibility.
14665 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14666 (skip-chars-backward " \t")
14667 (delete-region (point) (line-end-position)))))
14668 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14669 ;; is on.
14670 (unless (equal tags "")
14671 (let* ((level (save-excursion
14672 (beginning-of-line)
14673 (skip-chars-forward "\\*")))
14674 (offset (if (bound-and-true-p org-indent-mode)
14675 (* (1- org-indent-indentation-per-level)
14676 (1- level))
14678 (tags-column
14679 (+ org-tags-column
14680 (if (> org-tags-column 0) (- offset) offset))))
14681 (org--align-tags-here tags-column))))
14682 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14684 (defun org-change-tag-in-region (beg end tag off)
14685 "Add or remove TAG for each entry in the region.
14686 This works in the agenda, and also in an Org buffer."
14687 (interactive
14688 (list (region-beginning) (region-end)
14689 (let ((org-last-tags-completion-table
14690 (if (derived-mode-p 'org-mode)
14691 (org-uniquify
14692 (delq nil (append (org-get-buffer-tags)
14693 (org-global-tags-completion-table))))
14694 (org-global-tags-completion-table))))
14695 (completing-read
14696 "Tag: " 'org-tags-completion-function nil nil nil
14697 'org-tags-history))
14698 (progn
14699 (message "[s]et or [r]emove? ")
14700 (equal (read-char-exclusive) ?r))))
14701 (when (fboundp 'deactivate-mark) (deactivate-mark))
14702 (let ((agendap (equal major-mode 'org-agenda-mode))
14703 l1 l2 m buf pos newhead (cnt 0))
14704 (goto-char end)
14705 (setq l2 (1- (org-current-line)))
14706 (goto-char beg)
14707 (setq l1 (org-current-line))
14708 (cl-loop for l from l1 to l2 do
14709 (org-goto-line l)
14710 (setq m (get-text-property (point) 'org-hd-marker))
14711 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14712 (and agendap m))
14713 (setq buf (if agendap (marker-buffer m) (current-buffer))
14714 pos (if agendap m (point)))
14715 (with-current-buffer buf
14716 (save-excursion
14717 (save-restriction
14718 (goto-char pos)
14719 (setq cnt (1+ cnt))
14720 (org-toggle-tag tag (if off 'off 'on))
14721 (setq newhead (org-get-heading)))))
14722 (and agendap (org-agenda-change-all-lines newhead m))))
14723 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14725 (defun org-tags-completion-function (string _predicate &optional flag)
14726 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14727 (confirm (lambda (x) (stringp (car x)))))
14728 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14729 (setq s1 (match-string 1 string)
14730 s2 (match-string 2 string))
14731 (setq s1 "" s2 string))
14732 (cond
14733 ((eq flag nil)
14734 ;; try completion
14735 (setq rtn (try-completion s2 ctable confirm))
14736 (when (stringp rtn)
14737 (setq rtn
14738 (concat s1 s2 (substring rtn (length s2))
14739 (if (and org-add-colon-after-tag-completion
14740 (assoc rtn ctable))
14741 ":" ""))))
14742 rtn)
14743 ((eq flag t)
14744 ;; all-completions
14745 (all-completions s2 ctable confirm))
14746 ((eq flag 'lambda)
14747 ;; exact match?
14748 (assoc s2 ctable)))))
14750 (defun org-fast-tag-insert (kwd tags face &optional end)
14751 "Insert KDW, and the TAGS, the latter with face FACE.
14752 Also insert END."
14753 (insert (format "%-12s" (concat kwd ":"))
14754 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14755 (or end "")))
14757 (defun org-fast-tag-show-exit (flag)
14758 (save-excursion
14759 (org-goto-line 3)
14760 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14761 (replace-match ""))
14762 (when flag
14763 (end-of-line 1)
14764 (org-move-to-column (- (window-width) 19) t)
14765 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14767 (defun org-set-current-tags-overlay (current prefix)
14768 "Add an overlay to CURRENT tag with PREFIX."
14769 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14770 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14771 (org-overlay-display org-tags-overlay (concat prefix s))))
14773 (defvar org-last-tag-selection-key nil)
14774 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14775 "Fast tag selection with single keys.
14776 CURRENT is the current list of tags in the headline, INHERITED is the
14777 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14778 possibly with grouping information. TODO-TABLE is a similar table with
14779 TODO keywords, should these have keys assigned to them.
14780 If the keys are nil, a-z are automatically assigned.
14781 Returns the new tags string, or nil to not change the current settings."
14782 (let* ((fulltable (append table todo-table))
14783 (maxlen (apply 'max (mapcar
14784 (lambda (x)
14785 (if (stringp (car x)) (string-width (car x)) 0))
14786 fulltable)))
14787 (buf (current-buffer))
14788 (expert (eq org-fast-tag-selection-single-key 'expert))
14789 (buffer-tags nil)
14790 (fwidth (+ maxlen 3 1 3))
14791 (ncol (/ (- (window-width) 4) fwidth))
14792 (i-face 'org-done)
14793 (c-face 'org-todo)
14794 tg cnt e c char c1 c2 ntable tbl rtn
14795 ov-start ov-end ov-prefix
14796 (exit-after-next org-fast-tag-selection-single-key)
14797 (done-keywords org-done-keywords)
14798 groups ingroup intaggroup)
14799 (save-excursion
14800 (beginning-of-line 1)
14801 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14802 (setq ov-start (match-beginning 1)
14803 ov-end (match-end 1)
14804 ov-prefix "")
14805 (setq ov-start (1- (point-at-eol))
14806 ov-end (1+ ov-start))
14807 (skip-chars-forward "^\n\r")
14808 (setq ov-prefix
14809 (concat
14810 (buffer-substring (1- (point)) (point))
14811 (if (> (current-column) org-tags-column)
14813 (make-string (- org-tags-column (current-column)) ?\ ))))))
14814 (move-overlay org-tags-overlay ov-start ov-end)
14815 (save-window-excursion
14816 (if expert
14817 (set-buffer (get-buffer-create " *Org tags*"))
14818 (delete-other-windows)
14819 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14820 (org-switch-to-buffer-other-window " *Org tags*"))
14821 (erase-buffer)
14822 (setq-local org-done-keywords done-keywords)
14823 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14824 (org-fast-tag-insert "Current" current c-face "\n\n")
14825 (org-fast-tag-show-exit exit-after-next)
14826 (org-set-current-tags-overlay current ov-prefix)
14827 (setq tbl fulltable char ?a cnt 0)
14828 (while (setq e (pop tbl))
14829 (cond
14830 ((eq (car e) :startgroup)
14831 (push '() groups) (setq ingroup t)
14832 (unless (zerop cnt)
14833 (setq cnt 0)
14834 (insert "\n"))
14835 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14836 ((eq (car e) :endgroup)
14837 (setq ingroup nil cnt 0)
14838 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14839 ((eq (car e) :startgrouptag)
14840 (setq intaggroup t)
14841 (unless (zerop cnt)
14842 (setq cnt 0)
14843 (insert "\n"))
14844 (insert "[ "))
14845 ((eq (car e) :endgrouptag)
14846 (setq intaggroup nil cnt 0)
14847 (insert "]\n"))
14848 ((equal e '(:newline))
14849 (unless (zerop cnt)
14850 (setq cnt 0)
14851 (insert "\n")
14852 (setq e (car tbl))
14853 (while (equal (car tbl) '(:newline))
14854 (insert "\n")
14855 (setq tbl (cdr tbl)))))
14856 ((equal e '(:grouptags)) (insert " : "))
14858 (setq tg (copy-sequence (car e)) c2 nil)
14859 (if (cdr e)
14860 (setq c (cdr e))
14861 ;; automatically assign a character.
14862 (setq c1 (string-to-char
14863 (downcase (substring
14864 tg (if (= (string-to-char tg) ?@) 1 0)))))
14865 (if (or (rassoc c1 ntable) (rassoc c1 table))
14866 (while (or (rassoc char ntable) (rassoc char table))
14867 (setq char (1+ char)))
14868 (setq c2 c1))
14869 (setq c (or c2 char)))
14870 (when ingroup (push tg (car groups)))
14871 (setq tg (org-add-props tg nil 'face
14872 (cond
14873 ((not (assoc tg table))
14874 (org-get-todo-face tg))
14875 ((member tg current) c-face)
14876 ((member tg inherited) i-face))))
14877 (when (equal (caar tbl) :grouptags)
14878 (org-add-props tg nil 'face 'org-tag-group))
14879 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14880 (insert "[" c "] " tg (make-string
14881 (- fwidth 4 (length tg)) ?\ ))
14882 (push (cons tg c) ntable)
14883 (when (= (cl-incf cnt) ncol)
14884 (insert "\n")
14885 (when (or ingroup intaggroup) (insert " "))
14886 (setq cnt 0)))))
14887 (setq ntable (nreverse ntable))
14888 (insert "\n")
14889 (goto-char (point-min))
14890 (unless expert (org-fit-window-to-buffer))
14891 (setq rtn
14892 (catch 'exit
14893 (while t
14894 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14895 (if (not groups) "no " "")
14896 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14897 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14898 (setq org-last-tag-selection-key c)
14899 (cond
14900 ((= c ?\r) (throw 'exit t))
14901 ((= c ?!)
14902 (setq groups (not groups))
14903 (goto-char (point-min))
14904 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14905 ((= c ?\C-c)
14906 (if (not expert)
14907 (org-fast-tag-show-exit
14908 (setq exit-after-next (not exit-after-next)))
14909 (setq expert nil)
14910 (delete-other-windows)
14911 (set-window-buffer (split-window-vertically) " *Org tags*")
14912 (org-switch-to-buffer-other-window " *Org tags*")
14913 (org-fit-window-to-buffer)))
14914 ((or (= c ?\C-g)
14915 (and (= c ?q) (not (rassoc c ntable))))
14916 (delete-overlay org-tags-overlay)
14917 (setq quit-flag t))
14918 ((= c ?\ )
14919 (setq current nil)
14920 (when exit-after-next (setq exit-after-next 'now)))
14921 ((= c ?\t)
14922 (condition-case nil
14923 (setq tg (completing-read
14924 "Tag: "
14925 (or buffer-tags
14926 (with-current-buffer buf
14927 (setq buffer-tags
14928 (org-get-buffer-tags))))))
14929 (quit (setq tg "")))
14930 (when (string-match "\\S-" tg)
14931 (cl-pushnew (list tg) buffer-tags :test #'equal)
14932 (if (member tg current)
14933 (setq current (delete tg current))
14934 (push tg current)))
14935 (when exit-after-next (setq exit-after-next 'now)))
14936 ((setq e (rassoc c todo-table) tg (car e))
14937 (with-current-buffer buf
14938 (save-excursion (org-todo tg)))
14939 (when exit-after-next (setq exit-after-next 'now)))
14940 ((setq e (rassoc c ntable) tg (car e))
14941 (if (member tg current)
14942 (setq current (delete tg current))
14943 (cl-loop for g in groups do
14944 (when (member tg g)
14945 (dolist (x g) (setq current (delete x current)))))
14946 (push tg current))
14947 (when exit-after-next (setq exit-after-next 'now))))
14949 ;; Create a sorted list
14950 (setq current
14951 (sort current
14952 (lambda (a b)
14953 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14954 (when (eq exit-after-next 'now) (throw 'exit t))
14955 (goto-char (point-min))
14956 (beginning-of-line 2)
14957 (delete-region (point) (point-at-eol))
14958 (org-fast-tag-insert "Current" current c-face)
14959 (org-set-current-tags-overlay current ov-prefix)
14960 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14961 (setq tg (match-string 1))
14962 (add-text-properties
14963 (match-beginning 1) (match-end 1)
14964 (list 'face
14965 (cond
14966 ((member tg current) c-face)
14967 ((member tg inherited) i-face)
14968 (t (get-text-property (match-beginning 1) 'face))))))
14969 (goto-char (point-min)))))
14970 (delete-overlay org-tags-overlay)
14971 (if rtn
14972 (mapconcat 'identity current ":")
14973 nil))))
14975 (defun org-get-tags-string ()
14976 "Get the TAGS string in the current headline."
14977 (unless (org-at-heading-p t)
14978 (user-error "Not on a heading"))
14979 (save-excursion
14980 (beginning-of-line 1)
14981 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14982 (match-string-no-properties 1)
14983 "")))
14985 (defun org-get-tags ()
14986 "Get the list of tags specified in the current headline."
14987 (org-split-string (org-get-tags-string) ":"))
14989 (defun org-get-buffer-tags ()
14990 "Get a table of all tags used in the buffer, for completion."
14991 (org-with-wide-buffer
14992 (goto-char (point-min))
14993 (let ((tag-re (concat org-outline-regexp-bol
14994 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14995 tags)
14996 (while (re-search-forward tag-re nil t)
14997 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14998 (push tag tags)))
14999 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15001 ;;;; The mapping API
15003 (defvar org-agenda-skip-comment-trees)
15004 (defvar org-agenda-skip-function)
15005 (defun org-map-entries (func &optional match scope &rest skip)
15006 "Call FUNC at each headline selected by MATCH in SCOPE.
15008 FUNC is a function or a lisp form. The function will be called without
15009 arguments, with the cursor positioned at the beginning of the headline.
15010 The return values of all calls to the function will be collected and
15011 returned as a list.
15013 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15014 does not need to preserve point. After evaluation, the cursor will be
15015 moved to the end of the line (presumably of the headline of the
15016 processed entry) and search continues from there. Under some
15017 circumstances, this may not produce the wanted results. For example,
15018 if you have removed (e.g. archived) the current (sub)tree it could
15019 mean that the next entry will be skipped entirely. In such cases, you
15020 can specify the position from where search should continue by making
15021 FUNC set the variable `org-map-continue-from' to the desired buffer
15022 position.
15024 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15025 Only headlines that are matched by this query will be considered during
15026 the iteration. When MATCH is nil or t, all headlines will be
15027 visited by the iteration.
15029 SCOPE determines the scope of this command. It can be any of:
15031 nil The current buffer, respecting the restriction if any
15032 tree The subtree started with the entry at point
15033 region The entries within the active region, if any
15034 region-start-level
15035 The entries within the active region, but only those at
15036 the same level than the first one.
15037 file The current buffer, without restriction
15038 file-with-archives
15039 The current buffer, and any archives associated with it
15040 agenda All agenda files
15041 agenda-with-archives
15042 All agenda files with any archive files associated with them
15043 \(file1 file2 ...)
15044 If this is a list, all files in the list will be scanned
15046 The remaining args are treated as settings for the skipping facilities of
15047 the scanner. The following items can be given here:
15049 archive skip trees with the archive tag
15050 comment skip trees with the COMMENT keyword
15051 function or Emacs Lisp form:
15052 will be used as value for `org-agenda-skip-function', so
15053 whenever the function returns a position, FUNC will not be
15054 called for that entry and search will continue from the
15055 position returned
15057 If your function needs to retrieve the tags including inherited tags
15058 at the *current* entry, you can use the value of the variable
15059 `org-scanner-tags' which will be much faster than getting the value
15060 with `org-get-tags-at'. If your function gets properties with
15061 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15062 to t around the call to `org-entry-properties' to get the same speedup.
15063 Note that if your function moves around to retrieve tags and properties at
15064 a *different* entry, you cannot use these techniques."
15065 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15066 (not (org-region-active-p)))
15067 (let* ((org-agenda-archives-mode nil) ; just to make sure
15068 (org-agenda-skip-archived-trees (memq 'archive skip))
15069 (org-agenda-skip-comment-trees (memq 'comment skip))
15070 (org-agenda-skip-function
15071 (car (org-delete-all '(comment archive) skip)))
15072 (org-tags-match-list-sublevels t)
15073 (start-level (eq scope 'region-start-level))
15074 matcher res
15075 org-todo-keywords-for-agenda
15076 org-done-keywords-for-agenda
15077 org-todo-keyword-alist-for-agenda
15078 org-tag-alist-for-agenda
15079 org--matcher-tags-todo-only)
15081 (cond
15082 ((eq match t) (setq matcher t))
15083 ((eq match nil) (setq matcher t))
15084 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15086 (save-excursion
15087 (save-restriction
15088 (cond ((eq scope 'tree)
15089 (org-back-to-heading t)
15090 (org-narrow-to-subtree)
15091 (setq scope nil))
15092 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15093 (org-region-active-p))
15094 ;; If needed, set start-level to a string like "2"
15095 (when start-level
15096 (save-excursion
15097 (goto-char (region-beginning))
15098 (unless (org-at-heading-p) (outline-next-heading))
15099 (setq start-level (org-current-level))))
15100 (narrow-to-region (region-beginning)
15101 (save-excursion
15102 (goto-char (region-end))
15103 (unless (and (bolp) (org-at-heading-p))
15104 (outline-next-heading))
15105 (point)))
15106 (setq scope nil)))
15108 (if (not scope)
15109 (progn
15110 (org-agenda-prepare-buffers
15111 (and buffer-file-name (list buffer-file-name)))
15112 (setq res
15113 (org-scan-tags
15114 func matcher org--matcher-tags-todo-only start-level)))
15115 ;; Get the right scope
15116 (cond
15117 ((and scope (listp scope) (symbolp (car scope)))
15118 (setq scope (eval scope)))
15119 ((eq scope 'agenda)
15120 (setq scope (org-agenda-files t)))
15121 ((eq scope 'agenda-with-archives)
15122 (setq scope (org-agenda-files t))
15123 (setq scope (org-add-archive-files scope)))
15124 ((eq scope 'file)
15125 (setq scope (and buffer-file-name (list buffer-file-name))))
15126 ((eq scope 'file-with-archives)
15127 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15128 (org-agenda-prepare-buffers scope)
15129 (dolist (file scope)
15130 (with-current-buffer (org-find-base-buffer-visiting file)
15131 (org-with-wide-buffer
15132 (goto-char (point-min))
15133 (setq res
15134 (append
15136 (org-scan-tags
15137 func matcher org--matcher-tags-todo-only)))))))))
15138 res)))
15140 ;;; Properties API
15142 (defconst org-special-properties
15143 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15144 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15145 "The special properties valid in Org mode.
15146 These are properties that are not defined in the property drawer,
15147 but in some other way.")
15149 (defconst org-default-properties
15150 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15151 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15152 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15153 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15154 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15155 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15156 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15157 "Some properties that are used by Org mode for various purposes.
15158 Being in this list makes sure that they are offered for completion.")
15160 (defun org--valid-property-p (property)
15161 "Non nil when string PROPERTY is a valid property name."
15162 (not
15163 (or (equal property "")
15164 (string-match-p "\\s-" property))))
15166 (defun org--update-property-plist (key val props)
15167 "Associate KEY to VAL in alist PROPS.
15168 Modifications are made by side-effect. Return new alist."
15169 (let* ((appending (string= (substring key -1) "+"))
15170 (key (if appending (substring key 0 -1) key))
15171 (old (assoc-string key props t)))
15172 (if (not old) (cons (cons key val) props)
15173 (setcdr old (if appending (concat (cdr old) " " val) val))
15174 props)))
15176 (defun org-get-property-block (&optional beg force)
15177 "Return the (beg . end) range of the body of the property drawer.
15178 BEG is the beginning of the current subtree, or of the part
15179 before the first headline. If it is not given, it will be found.
15180 If the drawer does not exist, create it if FORCE is non-nil, or
15181 return nil."
15182 (org-with-wide-buffer
15183 (when beg (goto-char beg))
15184 (unless (org-before-first-heading-p)
15185 (let ((beg (cond (beg)
15186 ((or (not (featurep 'org-inlinetask))
15187 (org-inlinetask-in-task-p))
15188 (org-back-to-heading t))
15189 (t (org-with-limited-levels (org-back-to-heading t))))))
15190 (forward-line)
15191 (when (looking-at-p org-planning-line-re) (forward-line))
15192 (cond ((looking-at org-property-drawer-re)
15193 (forward-line)
15194 (cons (point) (progn (goto-char (match-end 0))
15195 (line-beginning-position))))
15196 (force
15197 (goto-char beg)
15198 (org-insert-property-drawer)
15199 (let ((pos (save-excursion (search-forward ":END:")
15200 (line-beginning-position))))
15201 (cons pos pos))))))))
15203 (defun org-at-property-p ()
15204 "Non-nil when point is inside a property drawer.
15205 See `org-property-re' for match data, if applicable."
15206 (save-excursion
15207 (beginning-of-line)
15208 (and (looking-at org-property-re)
15209 (let ((property-drawer (save-match-data (org-get-property-block))))
15210 (and property-drawer
15211 (>= (point) (car property-drawer))
15212 (< (point) (cdr property-drawer)))))))
15214 (defun org-property-action ()
15215 "Do an action on properties."
15216 (interactive)
15217 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15218 (let ((c (read-char-exclusive)))
15219 (cl-case c
15220 (?s (call-interactively #'org-set-property))
15221 (?d (call-interactively #'org-delete-property))
15222 (?D (call-interactively #'org-delete-property-globally))
15223 (?c (call-interactively #'org-compute-property-at-point))
15224 (otherwise (user-error "No such property action %c" c)))))
15226 (defun org-inc-effort ()
15227 "Increment the value of the effort property in the current entry."
15228 (interactive)
15229 (org-set-effort nil t))
15231 (defvar org-clock-effort) ; Defined in org-clock.el.
15232 (defvar org-clock-current-task) ; Defined in org-clock.el.
15233 (defun org-set-effort (&optional value increment)
15234 "Set the effort property of the current entry.
15235 With numerical prefix arg, use the nth allowed value, 0 stands for the
15236 10th allowed value.
15238 When INCREMENT is non-nil, set the property to the next allowed value."
15239 (interactive "P")
15240 (when (equal value 0) (setq value 10))
15241 (let* ((completion-ignore-case t)
15242 (prop org-effort-property)
15243 (cur (org-entry-get nil prop))
15244 (allowed (org-property-get-allowed-values nil prop 'table))
15245 (existing (mapcar 'list (org-property-values prop)))
15246 (heading (nth 4 (org-heading-components)))
15248 (val (cond
15249 ((stringp value) value)
15250 ((and allowed (integerp value))
15251 (or (car (nth (1- value) allowed))
15252 (car (org-last allowed))))
15253 ((and allowed increment)
15254 (or (cl-caadr (member (list cur) allowed))
15255 (user-error "Allowed effort values are not set")))
15256 (allowed
15257 (message "Select 1-9,0, [RET%s]: %s"
15258 (if cur (concat "=" cur) "")
15259 (mapconcat 'car allowed " "))
15260 (setq rpl (read-char-exclusive))
15261 (if (equal rpl ?\r)
15263 (setq rpl (- rpl ?0))
15264 (when (equal rpl 0) (setq rpl 10))
15265 (if (and (> rpl 0) (<= rpl (length allowed)))
15266 (car (nth (1- rpl) allowed))
15267 (org-completing-read "Effort: " allowed nil))))
15269 (org-completing-read
15270 (concat "Effort" (and cur (string-match "\\S-" cur)
15271 (concat " [" cur "]"))
15272 ": ")
15273 existing nil nil "" nil cur)))))
15274 (unless (equal (org-entry-get nil prop) val)
15275 (org-entry-put nil prop val))
15276 (org-refresh-property
15277 '((effort . identity)
15278 (effort-minutes . org-duration-to-minutes))
15279 val)
15280 (when (equal heading (bound-and-true-p org-clock-current-task))
15281 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15282 (org-clock-update-mode-line))
15283 (message "%s is now %s" prop val)))
15285 (defun org-entry-properties (&optional pom which)
15286 "Get all properties of the current entry.
15288 When POM is a buffer position, get all properties from the entry
15289 there instead.
15291 This includes the TODO keyword, the tags, time strings for
15292 deadline, scheduled, and clocking, and any additional properties
15293 defined in the entry.
15295 If WHICH is nil or `all', get all properties. If WHICH is
15296 `special' or `standard', only get that subclass. If WHICH is
15297 a string, only get that property.
15299 Return value is an alist. Keys are properties, as upcased
15300 strings."
15301 (org-with-point-at pom
15302 (when (and (derived-mode-p 'org-mode)
15303 (ignore-errors (org-back-to-heading t)))
15304 (catch 'exit
15305 (let* ((beg (point))
15306 (specific (and (stringp which) (upcase which)))
15307 (which (cond ((not specific) which)
15308 ((member specific org-special-properties) 'special)
15309 (t 'standard)))
15310 props)
15311 ;; Get the special properties, like TODO and TAGS.
15312 (when (memq which '(nil all special))
15313 (when (or (not specific) (string= specific "CLOCKSUM"))
15314 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15315 (when clocksum
15316 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15317 props)))
15318 (when specific (throw 'exit props)))
15319 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15320 (let ((clocksumt (get-text-property (point)
15321 :org-clock-minutes-today)))
15322 (when clocksumt
15323 (push (cons "CLOCKSUM_T"
15324 (org-duration-from-minutes clocksumt))
15325 props)))
15326 (when specific (throw 'exit props)))
15327 (when (or (not specific) (string= specific "ITEM"))
15328 (let ((case-fold-search nil))
15329 (when (looking-at org-complex-heading-regexp)
15330 (push (cons "ITEM"
15331 (let ((title (match-string-no-properties 4)))
15332 (if (org-string-nw-p title)
15333 (org-remove-tabs title)
15334 "")))
15335 props)))
15336 (when specific (throw 'exit props)))
15337 (when (or (not specific) (string= specific "TODO"))
15338 (let ((case-fold-search nil))
15339 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15340 (push (cons "TODO" (match-string-no-properties 2)) props)))
15341 (when specific (throw 'exit props)))
15342 (when (or (not specific) (string= specific "PRIORITY"))
15343 (push (cons "PRIORITY"
15344 (if (looking-at org-priority-regexp)
15345 (match-string-no-properties 2)
15346 (char-to-string org-default-priority)))
15347 props)
15348 (when specific (throw 'exit props)))
15349 (when (or (not specific) (string= specific "FILE"))
15350 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15351 props)
15352 (when specific (throw 'exit props)))
15353 (when (or (not specific) (string= specific "TAGS"))
15354 (let ((value (org-string-nw-p (org-get-tags-string))))
15355 (when value (push (cons "TAGS" value) props)))
15356 (when specific (throw 'exit props)))
15357 (when (or (not specific) (string= specific "ALLTAGS"))
15358 (let ((value (org-get-tags-at)))
15359 (when value
15360 (push (cons "ALLTAGS"
15361 (format ":%s:" (mapconcat #'identity value ":")))
15362 props)))
15363 (when specific (throw 'exit props)))
15364 (when (or (not specific) (string= specific "BLOCKED"))
15365 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15366 (when specific (throw 'exit props)))
15367 (when (or (not specific)
15368 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15369 (forward-line)
15370 (when (looking-at-p org-planning-line-re)
15371 (end-of-line)
15372 (let ((bol (line-beginning-position))
15373 ;; Backward compatibility: time keywords used to
15374 ;; be configurable (before 8.3). Make sure we
15375 ;; get the correct keyword.
15376 (key-assoc `(("CLOSED" . ,org-closed-string)
15377 ("DEADLINE" . ,org-deadline-string)
15378 ("SCHEDULED" . ,org-scheduled-string))))
15379 (dolist (pair (if specific (list (assoc specific key-assoc))
15380 key-assoc))
15381 (save-excursion
15382 (when (search-backward (cdr pair) bol t)
15383 (goto-char (match-end 0))
15384 (skip-chars-forward " \t")
15385 (and (looking-at org-ts-regexp-both)
15386 (push (cons (car pair)
15387 (match-string-no-properties 0))
15388 props)))))))
15389 (when specific (throw 'exit props)))
15390 (when (or (not specific)
15391 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15392 (let ((find-ts
15393 (lambda (end ts)
15394 ;; Fix next time-stamp before END. TS is the
15395 ;; list of time-stamps found so far.
15396 (let ((ts ts)
15397 (regexp (cond
15398 ((string= specific "TIMESTAMP")
15399 org-ts-regexp)
15400 ((string= specific "TIMESTAMP_IA")
15401 org-ts-regexp-inactive)
15402 ((assoc "TIMESTAMP_IA" ts)
15403 org-ts-regexp)
15404 ((assoc "TIMESTAMP" ts)
15405 org-ts-regexp-inactive)
15406 (t org-ts-regexp-both))))
15407 (catch 'next
15408 (while (re-search-forward regexp end t)
15409 (backward-char)
15410 (let ((object (org-element-context)))
15411 ;; Accept to match timestamps in node
15412 ;; properties, too.
15413 (when (memq (org-element-type object)
15414 '(node-property timestamp))
15415 (let ((type
15416 (org-element-property :type object)))
15417 (cond
15418 ((and (memq type '(active active-range))
15419 (not (equal specific "TIMESTAMP_IA")))
15420 (unless (assoc "TIMESTAMP" ts)
15421 (push (cons "TIMESTAMP"
15422 (org-element-property
15423 :raw-value object))
15425 (when specific (throw 'exit ts))))
15426 ((and (memq type '(inactive inactive-range))
15427 (not (string= specific "TIMESTAMP")))
15428 (unless (assoc "TIMESTAMP_IA" ts)
15429 (push (cons "TIMESTAMP_IA"
15430 (org-element-property
15431 :raw-value object))
15433 (when specific (throw 'exit ts))))))
15434 ;; Both timestamp types are found,
15435 ;; move to next part.
15436 (when (= (length ts) 2) (throw 'next ts)))))
15437 ts)))))
15438 (goto-char beg)
15439 ;; First look for timestamps within headline.
15440 (let ((ts (funcall find-ts (line-end-position) nil)))
15441 (if (= (length ts) 2) (setq props (nconc ts props))
15442 ;; Then find timestamps in the section, skipping
15443 ;; planning line.
15444 (let ((end (save-excursion (outline-next-heading))))
15445 (forward-line)
15446 (when (looking-at-p org-planning-line-re) (forward-line))
15447 (setq props (nconc (funcall find-ts end ts) props))))))))
15448 ;; Get the standard properties, like :PROP:.
15449 (when (memq which '(nil all standard))
15450 ;; If we are looking after a specific property, delegate
15451 ;; to `org-entry-get', which is faster. However, make an
15452 ;; exception for "CATEGORY", since it can be also set
15453 ;; through keywords (i.e. #+CATEGORY).
15454 (if (and specific (not (equal specific "CATEGORY")))
15455 (let ((value (org-entry-get beg specific nil t)))
15456 (throw 'exit (and value (list (cons specific value)))))
15457 (let ((range (org-get-property-block beg)))
15458 (when range
15459 (let ((end (cdr range)) seen-base)
15460 (goto-char (car range))
15461 ;; Unlike to `org--update-property-plist', we
15462 ;; handle the case where base values is found
15463 ;; after its extension. We also forbid standard
15464 ;; properties to be named as special properties.
15465 (while (re-search-forward org-property-re end t)
15466 (let* ((key (upcase (match-string-no-properties 2)))
15467 (extendp (string-match-p "\\+\\'" key))
15468 (key-base (if extendp (substring key 0 -1) key))
15469 (value (match-string-no-properties 3)))
15470 (cond
15471 ((member-ignore-case key-base org-special-properties))
15472 (extendp
15473 (setq props
15474 (org--update-property-plist key value props)))
15475 ((member key seen-base))
15476 (t (push key seen-base)
15477 (let ((p (assoc-string key props t)))
15478 (if p (setcdr p (concat value " " (cdr p)))
15479 (push (cons key value) props))))))))))))
15480 (unless (assoc "CATEGORY" props)
15481 (push (cons "CATEGORY" (org-get-category beg)) props)
15482 (when (string= specific "CATEGORY") (throw 'exit props)))
15483 ;; Return value.
15484 props)))))
15486 (defun org--property-local-values (property literal-nil)
15487 "Return value for PROPERTY in current entry.
15488 Value is a list whose car is the base value for PROPERTY and cdr
15489 a list of accumulated values. Return nil if neither is found in
15490 the entry. Also return nil when PROPERTY is set to \"nil\",
15491 unless LITERAL-NIL is non-nil."
15492 (let ((range (org-get-property-block)))
15493 (when range
15494 (goto-char (car range))
15495 (let* ((case-fold-search t)
15496 (end (cdr range))
15497 (value
15498 ;; Base value.
15499 (save-excursion
15500 (let ((v (and (re-search-forward
15501 (org-re-property property nil t) end t)
15502 (match-string-no-properties 3))))
15503 (list (if literal-nil v (org-not-nil v)))))))
15504 ;; Find additional values.
15505 (let* ((property+ (org-re-property (concat property "+") nil t)))
15506 (while (re-search-forward property+ end t)
15507 (push (match-string-no-properties 3) value)))
15508 ;; Return final values.
15509 (and (not (equal value '(nil))) (nreverse value))))))
15511 (defun org--property-global-value (property literal-nil)
15512 "Return value for PROPERTY in current buffer.
15513 Return value is a string. Return nil if property is not set
15514 globally. Also return nil when PROPERTY is set to \"nil\",
15515 unless LITERAL-NIL is non-nil."
15516 (let ((global
15517 (cdr (or (assoc-string property org-file-properties t)
15518 (assoc-string property org-global-properties t)
15519 (assoc-string property org-global-properties-fixed t)))))
15520 (if literal-nil global (org-not-nil global))))
15522 (defun org-entry-get (pom property &optional inherit literal-nil)
15523 "Get value of PROPERTY for entry or content at point-or-marker POM.
15525 If INHERIT is non-nil and the entry does not have the property,
15526 then also check higher levels of the hierarchy. If INHERIT is
15527 the symbol `selective', use inheritance only if the setting in
15528 `org-use-property-inheritance' selects PROPERTY for inheritance.
15530 If the property is present but empty, the return value is the
15531 empty string. If the property is not present at all, nil is
15532 returned. In any other case, return the value as a string.
15533 Search is case-insensitive.
15535 If LITERAL-NIL is set, return the string value \"nil\" as
15536 a string, do not interpret it as the list atom nil. This is used
15537 for inheritance when a \"nil\" value can supersede a non-nil
15538 value higher up the hierarchy."
15539 (org-with-point-at pom
15540 (cond
15541 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15542 ;; We need a special property. Use `org-entry-properties' to
15543 ;; retrieve it, but specify the wanted property.
15544 (cdr (assoc-string property (org-entry-properties nil property))))
15545 ((and inherit
15546 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15547 (org-entry-get-with-inheritance property literal-nil))
15549 (let* ((local (org--property-local-values property literal-nil))
15550 (value (and local (mapconcat #'identity (delq nil local) " "))))
15551 (if literal-nil value (org-not-nil value)))))))
15553 (defun org-property-or-variable-value (var &optional inherit)
15554 "Check if there is a property fixing the value of VAR.
15555 If yes, return this value. If not, return the current value of the variable."
15556 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15557 (if (and prop (stringp prop) (string-match "\\S-" prop))
15558 (read prop)
15559 (symbol-value var))))
15561 (defun org-entry-delete (pom property)
15562 "Delete PROPERTY from entry at point-or-marker POM.
15563 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15564 non-nil when a property was removed."
15565 (org-with-point-at pom
15566 (pcase (org-get-property-block)
15567 (`(,begin . ,origin)
15568 (let* ((end (copy-marker origin))
15569 (re (org-re-property
15570 (concat (regexp-quote property) "\\+?") t t)))
15571 (goto-char begin)
15572 (while (re-search-forward re end t)
15573 (delete-region (match-beginning 0) (line-beginning-position 2)))
15574 ;; If drawer is empty, remove it altogether.
15575 (when (= begin end)
15576 (delete-region (line-beginning-position 0)
15577 (line-beginning-position 2)))
15578 ;; Return non-nil if some property was removed.
15579 (prog1 (/= end origin) (set-marker end nil))))
15580 (_ nil))))
15582 ;; Multi-values properties are properties that contain multiple values
15583 ;; These values are assumed to be single words, separated by whitespace.
15584 (defun org-entry-add-to-multivalued-property (pom property value)
15585 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15586 (let* ((old (org-entry-get pom property))
15587 (values (and old (split-string old))))
15588 (setq value (org-entry-protect-space value))
15589 (unless (member value values)
15590 (setq values (append values (list value)))
15591 (org-entry-put pom property (mapconcat #'identity values " ")))))
15593 (defun org-entry-remove-from-multivalued-property (pom property value)
15594 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15595 (let* ((old (org-entry-get pom property))
15596 (values (and old (split-string old))))
15597 (setq value (org-entry-protect-space value))
15598 (when (member value values)
15599 (setq values (delete value values))
15600 (org-entry-put pom property (mapconcat #'identity values " ")))))
15602 (defun org-entry-member-in-multivalued-property (pom property value)
15603 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15604 (let* ((old (org-entry-get pom property))
15605 (values (and old (split-string old))))
15606 (setq value (org-entry-protect-space value))
15607 (member value values)))
15609 (defun org-entry-get-multivalued-property (pom property)
15610 "Return a list of values in a multivalued property."
15611 (let* ((value (org-entry-get pom property))
15612 (values (and value (split-string value))))
15613 (mapcar #'org-entry-restore-space values)))
15615 (defun org-entry-put-multivalued-property (pom property &rest values)
15616 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15617 VALUES should be a list of strings. Spaces will be protected."
15618 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15619 (let* ((value (org-entry-get pom property))
15620 (values (and value (split-string value))))
15621 (mapcar #'org-entry-restore-space values)))
15623 (defun org-entry-protect-space (s)
15624 "Protect spaces and newline in string S."
15625 (while (string-match " " s)
15626 (setq s (replace-match "%20" t t s)))
15627 (while (string-match "\n" s)
15628 (setq s (replace-match "%0A" t t s)))
15631 (defun org-entry-restore-space (s)
15632 "Restore spaces and newline in string S."
15633 (while (string-match "%20" s)
15634 (setq s (replace-match " " t t s)))
15635 (while (string-match "%0A" s)
15636 (setq s (replace-match "\n" t t s)))
15639 (defvar org-entry-property-inherited-from (make-marker)
15640 "Marker pointing to the entry from where a property was inherited.
15641 Each call to `org-entry-get-with-inheritance' will set this marker to the
15642 location of the entry where the inheritance search matched. If there was
15643 no match, the marker will point nowhere.
15644 Note that also `org-entry-get' calls this function, if the INHERIT flag
15645 is set.")
15647 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15648 "Get PROPERTY of entry or content at point, search higher levels if needed.
15649 The search will stop at the first ancestor which has the property defined.
15650 If the value found is \"nil\", return nil to show that the property
15651 should be considered as undefined (this is the meaning of nil here).
15652 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15653 (move-marker org-entry-property-inherited-from nil)
15654 (org-with-wide-buffer
15655 (let (value)
15656 (catch 'exit
15657 (while t
15658 (let ((v (org--property-local-values property literal-nil)))
15659 (when v
15660 (setq value
15661 (concat (mapconcat #'identity (delq nil v) " ")
15662 (and value " ")
15663 value)))
15664 (cond
15665 ((car v)
15666 (org-back-to-heading t)
15667 (move-marker org-entry-property-inherited-from (point))
15668 (throw 'exit nil))
15669 ((org-up-heading-safe))
15671 (let ((global (org--property-global-value property literal-nil)))
15672 (cond ((not global))
15673 (value (setq value (concat global " " value)))
15674 (t (setq value global))))
15675 (throw 'exit nil))))))
15676 (if literal-nil value (org-not-nil value)))))
15678 (defvar org-property-changed-functions nil
15679 "Hook called when the value of a property has changed.
15680 Each hook function should accept two arguments, the name of the property
15681 and the new value.")
15683 (defun org-entry-put (pom property value)
15684 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15686 If the value is nil, it is converted to the empty string. If it
15687 is not a string, an error is raised. Also raise an error on
15688 invalid property names.
15690 PROPERTY can be any regular property (see
15691 `org-special-properties'). It can also be \"TODO\",
15692 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15694 For the last two properties, VALUE may have any of the special
15695 values \"earlier\" and \"later\". The function then increases or
15696 decreases scheduled or deadline date by one day."
15697 (cond ((null value) (setq value ""))
15698 ((not (stringp value)) (error "Properties values should be strings"))
15699 ((not (org--valid-property-p property))
15700 (user-error "Invalid property name: \"%s\"" property)))
15701 (org-with-point-at pom
15702 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15703 (org-back-to-heading t)
15704 (org-with-limited-levels (org-back-to-heading t)))
15705 (let ((beg (point)))
15706 (cond
15707 ((equal property "TODO")
15708 (cond ((not (org-string-nw-p value)) (setq value 'none))
15709 ((not (member value org-todo-keywords-1))
15710 (user-error "\"%s\" is not a valid TODO state" value)))
15711 (org-todo value)
15712 (org-set-tags nil 'align))
15713 ((equal property "PRIORITY")
15714 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15715 (org-set-tags nil 'align))
15716 ((equal property "SCHEDULED")
15717 (forward-line)
15718 (if (and (looking-at-p org-planning-line-re)
15719 (re-search-forward
15720 org-scheduled-time-regexp (line-end-position) t))
15721 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15722 ((string= value "later") (org-timestamp-change 1 'day))
15723 ((string= value "") (org-schedule '(4)))
15724 (t (org-schedule nil value)))
15725 (if (member value '("earlier" "later" ""))
15726 (call-interactively #'org-schedule)
15727 (org-schedule nil value))))
15728 ((equal property "DEADLINE")
15729 (forward-line)
15730 (if (and (looking-at-p org-planning-line-re)
15731 (re-search-forward
15732 org-deadline-time-regexp (line-end-position) t))
15733 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15734 ((string= value "later") (org-timestamp-change 1 'day))
15735 ((string= value "") (org-deadline '(4)))
15736 (t (org-deadline nil value)))
15737 (if (member value '("earlier" "later" ""))
15738 (call-interactively #'org-deadline)
15739 (org-deadline nil value))))
15740 ((member property org-special-properties)
15741 (error "The %s property cannot be set with `org-entry-put'" property))
15743 (let* ((range (org-get-property-block beg 'force))
15744 (end (cdr range))
15745 (case-fold-search t))
15746 (goto-char (car range))
15747 (if (re-search-forward (org-re-property property nil t) end t)
15748 (progn (delete-region (match-beginning 0) (match-end 0))
15749 (goto-char (match-beginning 0)))
15750 (goto-char end)
15751 (insert "\n")
15752 (backward-char))
15753 (insert ":" property ":")
15754 (when value (insert " " value))
15755 (org-indent-line)))))
15756 (run-hook-with-args 'org-property-changed-functions property value)))
15758 (defun org-buffer-property-keys (&optional specials defaults columns)
15759 "Get all property keys in the current buffer.
15761 When SPECIALS is non-nil, also list the special properties that
15762 reflect things like tags and TODO state.
15764 When DEFAULTS is non-nil, also include properties that has
15765 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15766 DESCRIPTION, LOCATION, and LOGGING and others.
15768 When COLUMNS in non-nil, also include property names given in
15769 COLUMN formats in the current buffer."
15770 (let ((case-fold-search t)
15771 (props (append
15772 (and specials org-special-properties)
15773 (and defaults (cons org-effort-property org-default-properties))
15774 nil)))
15775 (org-with-wide-buffer
15776 (goto-char (point-min))
15777 (while (re-search-forward org-property-start-re nil t)
15778 (catch :skip
15779 (let ((range (org-get-property-block)))
15780 (unless range (throw :skip nil))
15781 (goto-char (car range))
15782 (let ((begin (car range))
15783 (end (cdr range)))
15784 ;; Make sure that found property block is not located
15785 ;; before current point, as it would generate an infloop.
15786 ;; It can happen, for example, in the following
15787 ;; situation:
15789 ;; * Headline
15790 ;; :PROPERTIES:
15791 ;; ...
15792 ;; :END:
15793 ;; *************** Inlinetask
15794 ;; #+BEGIN_EXAMPLE
15795 ;; :PROPERTIES:
15796 ;; #+END_EXAMPLE
15798 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15799 (while (< (point) end)
15800 (let ((p (progn (looking-at org-property-re)
15801 (match-string-no-properties 2))))
15802 ;; Only add true property name, not extension symbol.
15803 (push (if (not (string-match-p "\\+\\'" p)) p
15804 (substring p 0 -1))
15805 props))
15806 (forward-line))))
15807 (outline-next-heading)))
15808 (when columns
15809 (goto-char (point-min))
15810 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15811 (let ((element (org-element-at-point)))
15812 (when (memq (org-element-type element) '(keyword node-property))
15813 (let ((value (org-element-property :value element))
15814 (start 0))
15815 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15816 \\(?:{[^}]+}\\)?"
15817 value start)
15818 (setq start (match-end 0))
15819 (let ((p (match-string-no-properties 1 value)))
15820 (unless (member-ignore-case p org-special-properties)
15821 (push p props))))))))))
15822 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15824 (defun org-property-values (key)
15825 "List all non-nil values of property KEY in current buffer."
15826 (org-with-wide-buffer
15827 (goto-char (point-min))
15828 (let ((case-fold-search t)
15829 (re (org-re-property key))
15830 values)
15831 (while (re-search-forward re nil t)
15832 (push (org-entry-get (point) key) values))
15833 (delete-dups values))))
15835 (defun org-insert-property-drawer ()
15836 "Insert a property drawer into the current entry."
15837 (org-with-wide-buffer
15838 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15839 (org-back-to-heading t)
15840 (org-with-limited-levels (org-back-to-heading t)))
15841 (forward-line)
15842 (when (looking-at-p org-planning-line-re) (forward-line))
15843 (unless (looking-at-p org-property-drawer-re)
15844 ;; Make sure we start editing a line from current entry, not from
15845 ;; next one. It prevents extending text properties or overlays
15846 ;; belonging to the latter.
15847 (when (bolp) (backward-char))
15848 (let ((begin (1+ (point)))
15849 (inhibit-read-only t))
15850 (insert "\n:PROPERTIES:\n:END:")
15851 (when (eobp) (insert "\n"))
15852 (org-indent-region begin (point))))))
15854 (defun org-insert-drawer (&optional arg drawer)
15855 "Insert a drawer at point.
15857 When optional argument ARG is non-nil, insert a property drawer.
15859 Optional argument DRAWER, when non-nil, is a string representing
15860 drawer's name. Otherwise, the user is prompted for a name.
15862 If a region is active, insert the drawer around that region
15863 instead.
15865 Point is left between drawer's boundaries."
15866 (interactive "P")
15867 (let* ((drawer (if arg "PROPERTIES"
15868 (or drawer (read-from-minibuffer "Drawer: ")))))
15869 (cond
15870 ;; With C-u, fall back on `org-insert-property-drawer'
15871 (arg (org-insert-property-drawer))
15872 ;; Check validity of suggested drawer's name.
15873 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15874 (user-error "Invalid drawer name"))
15875 ;; With an active region, insert a drawer at point.
15876 ((not (org-region-active-p))
15877 (progn
15878 (unless (bolp) (insert "\n"))
15879 (insert (format ":%s:\n\n:END:\n" drawer))
15880 (forward-line -2)))
15881 ;; Otherwise, insert the drawer at point
15883 (let ((rbeg (region-beginning))
15884 (rend (copy-marker (region-end))))
15885 (unwind-protect
15886 (progn
15887 (goto-char rbeg)
15888 (beginning-of-line)
15889 (when (save-excursion
15890 (re-search-forward org-outline-regexp-bol rend t))
15891 (user-error "Drawers cannot contain headlines"))
15892 ;; Position point at the beginning of the first
15893 ;; non-blank line in region. Insert drawer's opening
15894 ;; there, then indent it.
15895 (org-skip-whitespace)
15896 (beginning-of-line)
15897 (insert ":" drawer ":\n")
15898 (forward-line -1)
15899 (indent-for-tab-command)
15900 ;; Move point to the beginning of the first blank line
15901 ;; after the last non-blank line in region. Insert
15902 ;; drawer's closing, then indent it.
15903 (goto-char rend)
15904 (skip-chars-backward " \r\t\n")
15905 (insert "\n:END:")
15906 (deactivate-mark t)
15907 (indent-for-tab-command)
15908 (unless (eolp) (insert "\n")))
15909 ;; Clear marker, whatever the outcome of insertion is.
15910 (set-marker rend nil)))))))
15912 (defvar org-property-set-functions-alist nil
15913 "Property set function alist.
15914 Each entry should have the following format:
15916 (PROPERTY . READ-FUNCTION)
15918 The read function will be called with the same argument as
15919 `org-completing-read'.")
15921 (defun org-set-property-function (property)
15922 "Get the function that should be used to set PROPERTY.
15923 This is computed according to `org-property-set-functions-alist'."
15924 (or (cdr (assoc property org-property-set-functions-alist))
15925 'org-completing-read))
15927 (defun org-read-property-value (property)
15928 "Read PROPERTY value from user."
15929 (let* ((completion-ignore-case t)
15930 (allowed (org-property-get-allowed-values nil property 'table))
15931 (cur (org-entry-get nil property))
15932 (prompt (concat property " value"
15933 (if (and cur (string-match "\\S-" cur))
15934 (concat " [" cur "]") "") ": "))
15935 (set-function (org-set-property-function property))
15936 (val (if allowed
15937 (funcall set-function prompt allowed nil
15938 (not (get-text-property 0 'org-unrestricted
15939 (caar allowed))))
15940 (funcall set-function prompt
15941 (mapcar 'list (org-property-values property))
15942 nil nil "" nil cur))))
15943 (org-trim val)))
15945 (defvar org-last-set-property nil)
15946 (defvar org-last-set-property-value nil)
15947 (defun org-read-property-name ()
15948 "Read a property name."
15949 (let ((completion-ignore-case t)
15950 (default-prop (or (and (org-at-property-p)
15951 (match-string-no-properties 2))
15952 org-last-set-property)))
15953 (org-completing-read
15954 (concat "Property"
15955 (if default-prop (concat " [" default-prop "]") "")
15956 ": ")
15957 (mapcar #'list (org-buffer-property-keys nil t t))
15958 nil nil nil nil default-prop)))
15960 (defun org-set-property-and-value (use-last)
15961 "Allow to set [PROPERTY]: [value] direction from prompt.
15962 When use-default, don't even ask, just use the last
15963 \"[PROPERTY]: [value]\" string from the history."
15964 (interactive "P")
15965 (let* ((completion-ignore-case t)
15966 (pv (or (and use-last org-last-set-property-value)
15967 (org-completing-read
15968 "Enter a \"[Property]: [value]\" pair: "
15969 nil nil nil nil nil
15970 org-last-set-property-value)))
15971 prop val)
15972 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15973 (setq prop (match-string 1 pv)
15974 val (match-string 2 pv))
15975 (org-set-property prop val))))
15977 (defun org-set-property (property value)
15978 "In the current entry, set PROPERTY to VALUE.
15980 When called interactively, this will prompt for a property name, offering
15981 completion on existing and default properties. And then it will prompt
15982 for a value, offering completion either on allowed values (via an inherited
15983 xxx_ALL property) or on existing values in other instances of this property
15984 in the current file.
15986 Throw an error when trying to set a property with an invalid name."
15987 (interactive (list nil nil))
15988 (let ((property (or property (org-read-property-name))))
15989 ;; `org-entry-put' also makes the following check, but this one
15990 ;; avoids polluting `org-last-set-property' and
15991 ;; `org-last-set-property-value' needlessly.
15992 (unless (org--valid-property-p property)
15993 (user-error "Invalid property name: \"%s\"" property))
15994 (let ((value (or value (org-read-property-value property)))
15995 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15996 (setq org-last-set-property property)
15997 (setq org-last-set-property-value (concat property ": " value))
15998 ;; Possibly postprocess the inserted value:
15999 (when fn (setq value (funcall fn value)))
16000 (unless (equal (org-entry-get nil property) value)
16001 (org-entry-put nil property value)))))
16003 (defun org-find-property (property &optional value)
16004 "Find first entry in buffer that sets PROPERTY.
16006 When optional argument VALUE is non-nil, only consider an entry
16007 if it contains PROPERTY set to this value. If PROPERTY should be
16008 explicitly set to nil, use string \"nil\" for VALUE.
16010 Return position where the entry begins, or nil if there is no
16011 such entry. If narrowing is in effect, only search the visible
16012 part of the buffer."
16013 (save-excursion
16014 (goto-char (point-min))
16015 (let ((case-fold-search t)
16016 (re (org-re-property property nil (not value) value)))
16017 (catch 'exit
16018 (while (re-search-forward re nil t)
16019 (when (if value (org-at-property-p)
16020 (org-entry-get (point) property nil t))
16021 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16023 (defun org-delete-property (property)
16024 "In the current entry, delete PROPERTY."
16025 (interactive
16026 (let* ((completion-ignore-case t)
16027 (cat (org-entry-get (point) "CATEGORY"))
16028 (props0 (org-entry-properties nil 'standard))
16029 (props (if cat props0
16030 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16031 (prop (if (< 1 (length props))
16032 (completing-read "Property: " props nil t)
16033 (caar props))))
16034 (list prop)))
16035 (if (not property)
16036 (message "No property to delete in this entry")
16037 (org-entry-delete nil property)
16038 (message "Property \"%s\" deleted" property)))
16040 (defun org-delete-property-globally (property)
16041 "Remove PROPERTY globally, from all entries.
16042 This function ignores narrowing, if any."
16043 (interactive
16044 (let* ((completion-ignore-case t)
16045 (prop (completing-read
16046 "Globally remove property: "
16047 (mapcar #'list (org-buffer-property-keys)))))
16048 (list prop)))
16049 (org-with-wide-buffer
16050 (goto-char (point-min))
16051 (let ((count 0)
16052 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16053 (while (re-search-forward re nil t)
16054 (when (org-entry-delete (point) property) (cl-incf count)))
16055 (message "Property \"%s\" removed from %d entries" property count))))
16057 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16059 (defun org-compute-property-at-point ()
16060 "Compute the property at point.
16061 This looks for an enclosing column format, extracts the operator and
16062 then applies it to the property in the column format's scope."
16063 (interactive)
16064 (unless (org-at-property-p)
16065 (user-error "Not at a property"))
16066 (let ((prop (match-string-no-properties 2)))
16067 (org-columns-get-format-and-top-level)
16068 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16069 (user-error "No operator defined for property %s" prop))
16070 (org-columns-compute prop)))
16072 (defvar org-property-allowed-value-functions nil
16073 "Hook for functions supplying allowed values for a specific property.
16074 The functions must take a single argument, the name of the property, and
16075 return a flat list of allowed values. If \":ETC\" is one of
16076 the values, this means that these values are intended as defaults for
16077 completion, but that other values should be allowed too.
16078 The functions must return nil if they are not responsible for this
16079 property.")
16081 (defun org-property-get-allowed-values (pom property &optional table)
16082 "Get allowed values for the property PROPERTY.
16083 When TABLE is non-nil, return an alist that can directly be used for
16084 completion."
16085 (let (vals)
16086 (cond
16087 ((equal property "TODO")
16088 (setq vals (org-with-point-at pom
16089 (append org-todo-keywords-1 '("")))))
16090 ((equal property "PRIORITY")
16091 (let ((n org-lowest-priority))
16092 (while (>= n org-highest-priority)
16093 (push (char-to-string n) vals)
16094 (setq n (1- n)))))
16095 ((equal property "CATEGORY"))
16096 ((member property org-special-properties))
16097 ((setq vals (run-hook-with-args-until-success
16098 'org-property-allowed-value-functions property)))
16100 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16101 (when (and vals (string-match "\\S-" vals))
16102 (setq vals (car (read-from-string (concat "(" vals ")"))))
16103 (setq vals (mapcar (lambda (x)
16104 (cond ((stringp x) x)
16105 ((numberp x) (number-to-string x))
16106 ((symbolp x) (symbol-name x))
16107 (t "???")))
16108 vals)))))
16109 (when (member ":ETC" vals)
16110 (setq vals (remove ":ETC" vals))
16111 (org-add-props (car vals) '(org-unrestricted t)))
16112 (if table (mapcar 'list vals) vals)))
16114 (defun org-property-previous-allowed-value (&optional _previous)
16115 "Switch to the next allowed value for this property."
16116 (interactive)
16117 (org-property-next-allowed-value t))
16119 (defun org-property-next-allowed-value (&optional previous)
16120 "Switch to the next allowed value for this property."
16121 (interactive)
16122 (unless (org-at-property-p)
16123 (user-error "Not at a property"))
16124 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16125 (key (match-string 2))
16126 (value (match-string 3))
16127 (allowed (or (org-property-get-allowed-values (point) key)
16128 (and (member value '("[ ]" "[-]" "[X]"))
16129 '("[ ]" "[X]"))))
16130 (heading (save-match-data (nth 4 (org-heading-components))))
16131 nval)
16132 (unless allowed
16133 (user-error "Allowed values for this property have not been defined"))
16134 (when previous (setq allowed (reverse allowed)))
16135 (when (member value allowed)
16136 (setq nval (car (cdr (member value allowed)))))
16137 (setq nval (or nval (car allowed)))
16138 (when (equal nval value)
16139 (user-error "Only one allowed value for this property"))
16140 (org-at-property-p)
16141 (replace-match (concat " :" key ": " nval) t t)
16142 (org-indent-line)
16143 (beginning-of-line 1)
16144 (skip-chars-forward " \t")
16145 (when (equal prop org-effort-property)
16146 (org-refresh-property
16147 '((effort . identity)
16148 (effort-minutes . org-duration-to-minutes))
16149 nval)
16150 (when (string= org-clock-current-task heading)
16151 (setq org-clock-effort nval)
16152 (org-clock-update-mode-line)))
16153 (run-hook-with-args 'org-property-changed-functions key nval)))
16155 (defun org-find-olp (path &optional this-buffer)
16156 "Return a marker pointing to the entry at outline path OLP.
16157 If anything goes wrong, throw an error.
16158 You can wrap this call to catch the error like this:
16160 (condition-case msg
16161 (org-mobile-locate-entry (match-string 4))
16162 (error (nth 1 msg)))
16164 The return value will then be either a string with the error message,
16165 or a marker if everything is OK.
16167 If THIS-BUFFER is set, the outline path does not contain a file,
16168 only headings."
16169 (let* ((file (if this-buffer buffer-file-name (pop path)))
16170 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16171 (level 1)
16172 (lmin 1)
16173 (lmax 1)
16174 end found flevel)
16175 (unless buffer (error "File not found :%s" file))
16176 (with-current-buffer buffer
16177 (unless (derived-mode-p 'org-mode)
16178 (error "Buffer %s needs to be in Org mode" buffer))
16179 (org-with-wide-buffer
16180 (goto-char (point-min))
16181 (dolist (heading path)
16182 (let ((re (format org-complex-heading-regexp-format
16183 (regexp-quote heading)))
16184 (cnt 0))
16185 (while (re-search-forward re end t)
16186 (setq level (- (match-end 1) (match-beginning 1)))
16187 (when (and (>= level lmin) (<= level lmax))
16188 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16189 (when (= cnt 0)
16190 (error "Heading not found on level %d: %s" lmax heading))
16191 (when (> cnt 1)
16192 (error "Heading not unique on level %d: %s" lmax heading))
16193 (goto-char found)
16194 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16195 (setq end (save-excursion (org-end-of-subtree t t)))))
16196 (when (org-at-heading-p)
16197 (point-marker))))))
16199 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16200 "Find node HEADING in BUFFER.
16201 Return a marker to the heading if it was found, or nil if not.
16202 If POS-ONLY is set, return just the position instead of a marker.
16204 The heading text must match exact, but it may have a TODO keyword,
16205 a priority cookie and tags in the standard locations."
16206 (with-current-buffer (or buffer (current-buffer))
16207 (org-with-wide-buffer
16208 (goto-char (point-min))
16209 (let (case-fold-search)
16210 (when (re-search-forward
16211 (format org-complex-heading-regexp-format
16212 (regexp-quote heading)) nil t)
16213 (if pos-only
16214 (match-beginning 0)
16215 (move-marker (make-marker) (match-beginning 0))))))))
16217 (defun org-find-exact-heading-in-directory (heading &optional dir)
16218 "Find Org node headline HEADING in all .org files in directory DIR.
16219 When the target headline is found, return a marker to this location."
16220 (let ((files (directory-files (or dir default-directory)
16221 t "\\`[^.#].*\\.org\\'"))
16222 visiting m buffer)
16223 (catch 'found
16224 (dolist (file files)
16225 (message "trying %s" file)
16226 (setq visiting (org-find-base-buffer-visiting file))
16227 (setq buffer (or visiting (find-file-noselect file)))
16228 (setq m (org-find-exact-headline-in-buffer
16229 heading buffer))
16230 (when (and (not m) (not visiting)) (kill-buffer buffer))
16231 (and m (throw 'found m))))))
16233 (defun org-find-entry-with-id (ident)
16234 "Locate the entry that contains the ID property with exact value IDENT.
16235 IDENT can be a string, a symbol or a number, this function will search for
16236 the string representation of it.
16237 Return the position where this entry starts, or nil if there is no such entry."
16238 (interactive "sID: ")
16239 (let ((id (cond
16240 ((stringp ident) ident)
16241 ((symbolp ident) (symbol-name ident))
16242 ((numberp ident) (number-to-string ident))
16243 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16244 (org-with-wide-buffer (org-find-property "ID" id))))
16246 ;;;; Timestamps
16248 (defvar org-last-changed-timestamp nil)
16249 (defvar org-last-inserted-timestamp nil
16250 "The last time stamp inserted with `org-insert-time-stamp'.")
16252 (defun org-time-stamp (arg &optional inactive)
16253 "Prompt for a date/time and insert a time stamp.
16255 If the user specifies a time like HH:MM or if this command is
16256 called with at least one prefix argument, the time stamp contains
16257 the date and the time. Otherwise, only the date is included.
16259 All parts of a date not specified by the user are filled in from
16260 the timestamp at point, if any, or the current date/time
16261 otherwise.
16263 If there is already a timestamp at the cursor, it is replaced.
16265 With two universal prefix arguments, insert an active timestamp
16266 with the current time without prompting the user.
16268 When called from lisp, the timestamp is inactive if INACTIVE is
16269 non-nil."
16270 (interactive "P")
16271 (let* ((ts (cond
16272 ((org-at-date-range-p t)
16273 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16274 ((org-at-timestamp-p 'lax) (match-string 0))))
16275 ;; Default time is either the timestamp at point or today.
16276 ;; When entering a range, only the range start is considered.
16277 (default-time (if (not ts) (current-time)
16278 (apply #'encode-time (org-parse-time-string ts))))
16279 (default-input (and ts (org-get-compact-tod ts)))
16280 (repeater (and ts
16281 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16282 (match-string 0 ts)))
16283 org-time-was-given
16284 org-end-time-was-given
16285 (time
16286 (and (if (equal arg '(16)) (current-time)
16287 ;; Preserve `this-command' and `last-command'.
16288 (let ((this-command this-command)
16289 (last-command last-command))
16290 (org-read-date
16291 arg 'totime nil nil default-time default-input
16292 inactive))))))
16293 (cond
16294 ((and ts
16295 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16296 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16297 (insert "--")
16298 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16300 ;; Make sure we're on a timestamp. When in the middle of a date
16301 ;; range, move arbitrarily to range end.
16302 (unless (org-at-timestamp-p 'lax)
16303 (skip-chars-forward "-")
16304 (org-at-timestamp-p 'lax))
16305 (replace-match "")
16306 (setq org-last-changed-timestamp
16307 (org-insert-time-stamp
16308 time (or org-time-was-given arg)
16309 inactive nil nil (list org-end-time-was-given)))
16310 (when repeater
16311 (backward-char)
16312 (insert " " repeater)
16313 (setq org-last-changed-timestamp
16314 (concat (substring org-last-inserted-timestamp 0 -1)
16315 " " repeater ">")))
16316 (message "Timestamp updated"))
16317 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16318 (t (org-insert-time-stamp
16319 time (or org-time-was-given arg) inactive nil nil
16320 (list org-end-time-was-given))))))
16322 ;; FIXME: can we use this for something else, like computing time differences?
16323 (defun org-get-compact-tod (s)
16324 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16325 (let* ((t1 (match-string 1 s))
16326 (h1 (string-to-number (match-string 2 s)))
16327 (m1 (string-to-number (match-string 3 s)))
16328 (t2 (and (match-end 4) (match-string 5 s)))
16329 (h2 (and t2 (string-to-number (match-string 6 s))))
16330 (m2 (and t2 (string-to-number (match-string 7 s))))
16331 dh dm)
16332 (if (not t2)
16334 (setq dh (- h2 h1) dm (- m2 m1))
16335 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16336 (concat t1 "+" (number-to-string dh)
16337 (and (/= 0 dm) (format ":%02d" dm)))))))
16339 (defun org-time-stamp-inactive (&optional arg)
16340 "Insert an inactive time stamp.
16341 An inactive time stamp is enclosed in square brackets instead of angle
16342 brackets. It is inactive in the sense that it does not trigger agenda entries,
16343 does not link to the calendar and cannot be changed with the S-cursor keys.
16344 So these are more for recording a certain time/date."
16345 (interactive "P")
16346 (org-time-stamp arg 'inactive))
16348 (defvar org-date-ovl (make-overlay 1 1))
16349 (overlay-put org-date-ovl 'face 'org-date-selected)
16350 (delete-overlay org-date-ovl)
16352 (defvar org-ans1) ; dynamically scoped parameter
16353 (defvar org-ans2) ; dynamically scoped parameter
16355 (defvar org-plain-time-of-day-regexp) ; defined below
16357 (defvar org-overriding-default-time nil) ; dynamically scoped
16358 (defvar org-read-date-overlay nil)
16359 (defvar org-dcst nil) ; dynamically scoped
16360 (defvar org-read-date-history nil)
16361 (defvar org-read-date-final-answer nil)
16362 (defvar org-read-date-analyze-futurep nil)
16363 (defvar org-read-date-analyze-forced-year nil)
16364 (defvar org-read-date-inactive)
16366 (defvar org-read-date-minibuffer-local-map
16367 (let* ((map (make-sparse-keymap)))
16368 (set-keymap-parent map minibuffer-local-map)
16369 (org-defkey map (kbd ".")
16370 (lambda () (interactive)
16371 ;; Are we at the beginning of the prompt?
16372 (if (looking-back "^[^:]+: "
16373 (let ((inhibit-field-text-motion t))
16374 (line-beginning-position)))
16375 (org-eval-in-calendar '(calendar-goto-today))
16376 (insert "."))))
16377 (org-defkey map (kbd "C-.")
16378 (lambda () (interactive)
16379 (org-eval-in-calendar '(calendar-goto-today))))
16380 (org-defkey map [(meta shift left)]
16381 (lambda () (interactive)
16382 (org-eval-in-calendar '(calendar-backward-month 1))))
16383 (org-defkey map [(meta shift right)]
16384 (lambda () (interactive)
16385 (org-eval-in-calendar '(calendar-forward-month 1))))
16386 (org-defkey map [(meta shift up)]
16387 (lambda () (interactive)
16388 (org-eval-in-calendar '(calendar-backward-year 1))))
16389 (org-defkey map [(meta shift down)]
16390 (lambda () (interactive)
16391 (org-eval-in-calendar '(calendar-forward-year 1))))
16392 (org-defkey map [?\e (shift left)]
16393 (lambda () (interactive)
16394 (org-eval-in-calendar '(calendar-backward-month 1))))
16395 (org-defkey map [?\e (shift right)]
16396 (lambda () (interactive)
16397 (org-eval-in-calendar '(calendar-forward-month 1))))
16398 (org-defkey map [?\e (shift up)]
16399 (lambda () (interactive)
16400 (org-eval-in-calendar '(calendar-backward-year 1))))
16401 (org-defkey map [?\e (shift down)]
16402 (lambda () (interactive)
16403 (org-eval-in-calendar '(calendar-forward-year 1))))
16404 (org-defkey map [(shift up)]
16405 (lambda () (interactive)
16406 (org-eval-in-calendar '(calendar-backward-week 1))))
16407 (org-defkey map [(shift down)]
16408 (lambda () (interactive)
16409 (org-eval-in-calendar '(calendar-forward-week 1))))
16410 (org-defkey map [(shift left)]
16411 (lambda () (interactive)
16412 (org-eval-in-calendar '(calendar-backward-day 1))))
16413 (org-defkey map [(shift right)]
16414 (lambda () (interactive)
16415 (org-eval-in-calendar '(calendar-forward-day 1))))
16416 (org-defkey map "!"
16417 (lambda () (interactive)
16418 (org-eval-in-calendar '(diary-view-entries))
16419 (message "")))
16420 (org-defkey map ">"
16421 (lambda () (interactive)
16422 (org-eval-in-calendar '(calendar-scroll-left 1))))
16423 (org-defkey map "<"
16424 (lambda () (interactive)
16425 (org-eval-in-calendar '(calendar-scroll-right 1))))
16426 (org-defkey map "\C-v"
16427 (lambda () (interactive)
16428 (org-eval-in-calendar
16429 '(calendar-scroll-left-three-months 1))))
16430 (org-defkey map "\M-v"
16431 (lambda () (interactive)
16432 (org-eval-in-calendar
16433 '(calendar-scroll-right-three-months 1))))
16434 map)
16435 "Keymap for minibuffer commands when using `org-read-date'.")
16437 (defvar org-def)
16438 (defvar org-defdecode)
16439 (defvar org-with-time)
16441 (defvar calendar-setup) ; Dynamically scoped.
16442 (defun org-read-date (&optional with-time to-time from-string prompt
16443 default-time default-input inactive)
16444 "Read a date, possibly a time, and make things smooth for the user.
16445 The prompt will suggest to enter an ISO date, but you can also enter anything
16446 which will at least partially be understood by `parse-time-string'.
16447 Unrecognized parts of the date will default to the current day, month, year,
16448 hour and minute. If this command is called to replace a timestamp at point,
16449 or to enter the second timestamp of a range, the default time is taken
16450 from the existing stamp. Furthermore, the command prefers the future,
16451 so if you are giving a date where the year is not given, and the day-month
16452 combination is already past in the current year, it will assume you
16453 mean next year. For details, see the manual. A few examples:
16455 3-2-5 --> 2003-02-05
16456 feb 15 --> currentyear-02-15
16457 2/15 --> currentyear-02-15
16458 sep 12 9 --> 2009-09-12
16459 12:45 --> today 12:45
16460 22 sept 0:34 --> currentyear-09-22 0:34
16461 12 --> currentyear-currentmonth-12
16462 Fri --> nearest Friday after today
16463 -Tue --> last Tuesday
16464 etc.
16466 Furthermore you can specify a relative date by giving, as the *first* thing
16467 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16468 change in days weeks, months, years.
16469 With a single plus or minus, the date is relative to today. With a double
16470 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16471 +4d --> four days from today
16472 +4 --> same as above
16473 +2w --> two weeks from today
16474 ++5 --> five days from default date
16476 The function understands only English month and weekday abbreviations.
16478 While prompting, a calendar is popped up - you can also select the
16479 date with the mouse (button 1). The calendar shows a period of three
16480 months. To scroll it to other months, use the keys `>' and `<'.
16481 If you don't like the calendar, turn it off with
16482 (setq org-read-date-popup-calendar nil)
16484 With optional argument TO-TIME, the date will immediately be converted
16485 to an internal time.
16486 With an optional argument WITH-TIME, the prompt will suggest to
16487 also insert a time. Note that when WITH-TIME is not set, you can
16488 still enter a time, and this function will inform the calling routine
16489 about this change. The calling routine may then choose to change the
16490 format used to insert the time stamp into the buffer to include the time.
16491 With optional argument FROM-STRING, read from this string instead from
16492 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16493 the time/date that is used for everything that is not specified by the
16494 user."
16495 (require 'parse-time)
16496 (let* ((org-with-time with-time)
16497 (org-time-stamp-rounding-minutes
16498 (if (equal org-with-time '(16))
16499 '(0 0)
16500 org-time-stamp-rounding-minutes))
16501 (org-dcst org-display-custom-times)
16502 (ct (org-current-time))
16503 (org-def (or org-overriding-default-time default-time ct))
16504 (org-defdecode (decode-time org-def))
16505 (cur-frame (selected-frame))
16506 (mouse-autoselect-window nil) ; Don't let the mouse jump
16507 (calendar-setup
16508 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16509 (calendar-move-hook nil)
16510 (calendar-view-diary-initially-flag nil)
16511 (calendar-view-holidays-initially-flag nil)
16512 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16513 ;; Rationalize `org-def' and `org-defdecode', if required.
16514 (when (< (nth 2 org-defdecode) org-extend-today-until)
16515 (setf (nth 2 org-defdecode) -1)
16516 (setf (nth 1 org-defdecode) 59)
16517 (setq org-def (apply #'encode-time org-defdecode))
16518 (setq org-defdecode (decode-time org-def)))
16519 (let* ((timestr (format-time-string
16520 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16521 org-def))
16522 (prompt (concat (if prompt (concat prompt " ") "")
16523 (format "Date+time [%s]: " timestr))))
16524 (cond
16525 (from-string (setq ans from-string))
16526 (org-read-date-popup-calendar
16527 (save-excursion
16528 (save-window-excursion
16529 (calendar)
16530 (when (eq calendar-setup 'calendar-only)
16531 (setq cal-frame
16532 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16533 (select-frame cal-frame))
16534 (org-eval-in-calendar '(setq cursor-type nil) t)
16535 (unwind-protect
16536 (progn
16537 (calendar-forward-day (- (time-to-days org-def)
16538 (calendar-absolute-from-gregorian
16539 (calendar-current-date))))
16540 (org-eval-in-calendar nil t)
16541 (let* ((old-map (current-local-map))
16542 (map (copy-keymap calendar-mode-map))
16543 (minibuffer-local-map
16544 (copy-keymap org-read-date-minibuffer-local-map)))
16545 (org-defkey map (kbd "RET") 'org-calendar-select)
16546 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16547 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16548 (unwind-protect
16549 (progn
16550 (use-local-map map)
16551 (setq org-read-date-inactive inactive)
16552 (add-hook 'post-command-hook 'org-read-date-display)
16553 (setq org-ans0
16554 (read-string prompt
16555 default-input
16556 'org-read-date-history
16557 nil))
16558 ;; org-ans0: from prompt
16559 ;; org-ans1: from mouse click
16560 ;; org-ans2: from calendar motion
16561 (setq ans
16562 (concat org-ans0 " " (or org-ans1 org-ans2))))
16563 (remove-hook 'post-command-hook 'org-read-date-display)
16564 (use-local-map old-map)
16565 (when org-read-date-overlay
16566 (delete-overlay org-read-date-overlay)
16567 (setq org-read-date-overlay nil)))))
16568 (bury-buffer "*Calendar*")
16569 (when cal-frame
16570 (delete-frame cal-frame)
16571 (select-frame-set-input-focus cur-frame))))))
16573 (t ; Naked prompt only
16574 (unwind-protect
16575 (setq ans (read-string prompt default-input
16576 'org-read-date-history timestr))
16577 (when org-read-date-overlay
16578 (delete-overlay org-read-date-overlay)
16579 (setq org-read-date-overlay nil))))))
16581 (setq final (org-read-date-analyze ans org-def org-defdecode))
16583 (when org-read-date-analyze-forced-year
16584 (message "Year was forced into %s"
16585 (if org-read-date-force-compatible-dates
16586 "compatible range (1970-2037)"
16587 "range representable on this machine"))
16588 (ding))
16590 ;; One round trip to get rid of 34th of August and stuff like that....
16591 (setq final (decode-time (apply 'encode-time final)))
16593 (setq org-read-date-final-answer ans)
16595 (if to-time
16596 (apply 'encode-time final)
16597 (if (and (boundp 'org-time-was-given) org-time-was-given)
16598 (format "%04d-%02d-%02d %02d:%02d"
16599 (nth 5 final) (nth 4 final) (nth 3 final)
16600 (nth 2 final) (nth 1 final))
16601 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16603 (defun org-read-date-display ()
16604 "Display the current date prompt interpretation in the minibuffer."
16605 (when org-read-date-display-live
16606 (when org-read-date-overlay
16607 (delete-overlay org-read-date-overlay))
16608 (when (minibufferp (current-buffer))
16609 (save-excursion
16610 (end-of-line 1)
16611 (while (not (equal (buffer-substring
16612 (max (point-min) (- (point) 4)) (point))
16613 " "))
16614 (insert " ")))
16615 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16616 " " (or org-ans1 org-ans2)))
16617 (org-end-time-was-given nil)
16618 (f (org-read-date-analyze ans org-def org-defdecode))
16619 (fmts (if org-dcst
16620 org-time-stamp-custom-formats
16621 org-time-stamp-formats))
16622 (fmt (if (or org-with-time
16623 (and (boundp 'org-time-was-given) org-time-was-given))
16624 (cdr fmts)
16625 (car fmts)))
16626 (txt (format-time-string fmt (apply 'encode-time f)))
16627 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16628 (txt (concat "=> " txt)))
16629 (when (and org-end-time-was-given
16630 (string-match org-plain-time-of-day-regexp txt))
16631 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16632 org-end-time-was-given
16633 (substring txt (match-end 0)))))
16634 (when org-read-date-analyze-futurep
16635 (setq txt (concat txt " (=>F)")))
16636 (setq org-read-date-overlay
16637 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16638 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16640 (defun org-read-date-analyze (ans def defdecode)
16641 "Analyze the combined answer of the date prompt."
16642 ;; FIXME: cleanup and comment
16643 ;; Pass `current-time' result to `decode-time' (instead of calling
16644 ;; without arguments) so that only `current-time' has to be
16645 ;; overridden in tests.
16646 (let ((org-def def)
16647 (org-defdecode defdecode)
16648 (nowdecode (decode-time (current-time)))
16649 delta deltan deltaw deltadef year month day
16650 hour minute second wday pm h2 m2 tl wday1
16651 iso-year iso-weekday iso-week iso-date futurep kill-year)
16652 (setq org-read-date-analyze-futurep nil
16653 org-read-date-analyze-forced-year nil)
16654 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16655 (setq ans "+0"))
16657 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16658 (setq ans (replace-match "" t t ans)
16659 deltan (car delta)
16660 deltaw (nth 1 delta)
16661 deltadef (nth 2 delta)))
16663 ;; Check if there is an iso week date in there. If yes, store the
16664 ;; info and postpone interpreting it until the rest of the parsing
16665 ;; is done.
16666 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16667 (setq iso-year (when (match-end 1)
16668 (org-small-year-to-year
16669 (string-to-number (match-string 1 ans))))
16670 iso-weekday (when (match-end 3)
16671 (string-to-number (match-string 3 ans)))
16672 iso-week (string-to-number (match-string 2 ans)))
16673 (setq ans (replace-match "" t t ans)))
16675 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16676 (when (string-match
16677 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16678 (setq year (if (match-end 2)
16679 (string-to-number (match-string 2 ans))
16680 (progn (setq kill-year t)
16681 (string-to-number (format-time-string "%Y"))))
16682 month (string-to-number (match-string 3 ans))
16683 day (string-to-number (match-string 4 ans)))
16684 (setq year (org-small-year-to-year year))
16685 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16686 t nil ans)))
16688 ;; Help matching dotted european dates
16689 (when (string-match
16690 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16691 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16692 (setq kill-year t)
16693 (string-to-number (format-time-string "%Y")))
16694 day (string-to-number (match-string 1 ans))
16695 month (string-to-number (match-string 2 ans))
16696 ans (replace-match (format "%04d-%02d-%02d" year month day)
16697 t nil ans)))
16699 ;; Help matching american dates, like 5/30 or 5/30/7
16700 (when (string-match
16701 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16702 (setq year (if (match-end 4)
16703 (string-to-number (match-string 4 ans))
16704 (progn (setq kill-year t)
16705 (string-to-number (format-time-string "%Y"))))
16706 month (string-to-number (match-string 1 ans))
16707 day (string-to-number (match-string 2 ans)))
16708 (setq year (org-small-year-to-year year))
16709 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16710 t nil ans)))
16711 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16712 ;; If there is a time with am/pm, and *no* time without it, we convert
16713 ;; so that matching will be successful.
16714 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16715 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16716 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16717 (setq hour (string-to-number (match-string 1 ans))
16718 minute (if (match-end 3)
16719 (string-to-number (match-string 3 ans))
16721 pm (equal ?p
16722 (string-to-char (downcase (match-string 4 ans)))))
16723 (if (and (= hour 12) (not pm))
16724 (setq hour 0)
16725 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16726 (setq ans (replace-match (format "%02d:%02d" hour minute)
16727 t t ans))))
16729 ;; Check if a time range is given as a duration
16730 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16731 (setq hour (string-to-number (match-string 1 ans))
16732 h2 (+ hour (string-to-number (match-string 3 ans)))
16733 minute (string-to-number (match-string 2 ans))
16734 m2 (+ minute (if (match-end 5) (string-to-number
16735 (match-string 5 ans))0)))
16736 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16737 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16738 t t ans)))
16740 ;; Check if there is a time range
16741 (when (boundp 'org-end-time-was-given)
16742 (setq org-time-was-given nil)
16743 (when (and (string-match org-plain-time-of-day-regexp ans)
16744 (match-end 8))
16745 (setq org-end-time-was-given (match-string 8 ans))
16746 (setq ans (concat (substring ans 0 (match-beginning 7))
16747 (substring ans (match-end 7))))))
16749 (setq tl (parse-time-string ans)
16750 day (or (nth 3 tl) (nth 3 org-defdecode))
16751 month
16752 (cond ((nth 4 tl))
16753 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16754 ;; Day was specified. Make sure DAY+MONTH
16755 ;; combination happens in the future.
16756 ((nth 3 tl)
16757 (setq futurep t)
16758 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16759 (nth 4 nowdecode)))
16760 (t (nth 4 org-defdecode)))
16761 year
16762 (cond ((and (not kill-year) (nth 5 tl)))
16763 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16764 ;; Month was guessed in the future and is at least
16765 ;; equal to NOWDECODE's. Fix year accordingly.
16766 (futurep
16767 (if (or (> month (nth 4 nowdecode))
16768 (>= day (nth 3 nowdecode)))
16769 (nth 5 nowdecode)
16770 (1+ (nth 5 nowdecode))))
16771 ;; Month was specified. Make sure MONTH+YEAR
16772 ;; combination happens in the future.
16773 ((nth 4 tl)
16774 (setq futurep t)
16775 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16776 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16777 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16778 (t (nth 5 nowdecode))))
16779 (t (nth 5 org-defdecode)))
16780 hour (or (nth 2 tl) (nth 2 org-defdecode))
16781 minute (or (nth 1 tl) (nth 1 org-defdecode))
16782 second (or (nth 0 tl) 0)
16783 wday (nth 6 tl))
16785 (when (and (eq org-read-date-prefer-future 'time)
16786 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16787 (equal day (nth 3 nowdecode))
16788 (equal month (nth 4 nowdecode))
16789 (equal year (nth 5 nowdecode))
16790 (nth 2 tl)
16791 (or (< (nth 2 tl) (nth 2 nowdecode))
16792 (and (= (nth 2 tl) (nth 2 nowdecode))
16793 (nth 1 tl)
16794 (< (nth 1 tl) (nth 1 nowdecode)))))
16795 (setq day (1+ day)
16796 futurep t))
16798 ;; Special date definitions below
16799 (cond
16800 (iso-week
16801 ;; There was an iso week
16802 (require 'cal-iso)
16803 (setq futurep nil)
16804 (setq year (or iso-year year)
16805 day (or iso-weekday wday 1)
16806 wday nil ; to make sure that the trigger below does not match
16807 iso-date (calendar-gregorian-from-absolute
16808 (calendar-iso-to-absolute
16809 (list iso-week day year))))
16810 ; FIXME: Should we also push ISO weeks into the future?
16811 ; (when (and org-read-date-prefer-future
16812 ; (not iso-year)
16813 ; (< (calendar-absolute-from-gregorian iso-date)
16814 ; (time-to-days (current-time))))
16815 ; (setq year (1+ year)
16816 ; iso-date (calendar-gregorian-from-absolute
16817 ; (calendar-iso-to-absolute
16818 ; (list iso-week day year)))))
16819 (setq month (car iso-date)
16820 year (nth 2 iso-date)
16821 day (nth 1 iso-date)))
16822 (deltan
16823 (setq futurep nil)
16824 (unless deltadef
16825 ;; Pass `current-time' result to `decode-time' (instead of
16826 ;; calling without arguments) so that only `current-time' has
16827 ;; to be overridden in tests.
16828 (let ((now (decode-time (current-time))))
16829 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16830 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16831 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16832 ((equal deltaw "m") (setq month (+ month deltan)))
16833 ((equal deltaw "y") (setq year (+ year deltan)))))
16834 ((and wday (not (nth 3 tl)))
16835 ;; Weekday was given, but no day, so pick that day in the week
16836 ;; on or after the derived date.
16837 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16838 (unless (equal wday wday1)
16839 (setq day (+ day (% (- wday wday1 -7) 7))))))
16840 (when (and (boundp 'org-time-was-given)
16841 (nth 2 tl))
16842 (setq org-time-was-given t))
16843 (when (< year 100) (setq year (+ 2000 year)))
16844 ;; Check of the date is representable
16845 (if org-read-date-force-compatible-dates
16846 (progn
16847 (when (< year 1970)
16848 (setq year 1970 org-read-date-analyze-forced-year t))
16849 (when (> year 2037)
16850 (setq year 2037 org-read-date-analyze-forced-year t)))
16851 (condition-case nil
16852 (ignore (encode-time second minute hour day month year))
16853 (error
16854 (setq year (nth 5 org-defdecode))
16855 (setq org-read-date-analyze-forced-year t))))
16856 (setq org-read-date-analyze-futurep futurep)
16857 (list second minute hour day month year)))
16859 (defvar parse-time-weekdays)
16860 (defun org-read-date-get-relative (s today default)
16861 "Check string S for special relative date string.
16862 TODAY and DEFAULT are internal times, for today and for a default.
16863 Return shift list (N what def-flag)
16864 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16865 N is the number of WHATs to shift.
16866 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16867 the DEFAULT date rather than TODAY."
16868 (require 'parse-time)
16869 (when (and
16870 (string-match
16871 (concat
16872 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16873 "\\([0-9]+\\)?"
16874 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16875 "\\([ \t]\\|$\\)") s)
16876 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16877 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16878 (string-to-char (substring (match-string 1 s) -1))
16879 ?+))
16880 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16881 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16882 (what (if (match-end 3) (match-string 3 s) "d"))
16883 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16884 (date (if rel default today))
16885 (wday (nth 6 (decode-time date)))
16886 delta)
16887 (if wday1
16888 (progn
16889 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16890 (when (= delta 0) (setq delta 7))
16891 (when (= dir ?-)
16892 (setq delta (- delta 7))
16893 (when (= delta 0) (setq delta -7)))
16894 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16895 (list delta "d" rel))
16896 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16898 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16899 "Turn a user-specified date into the internal representation.
16900 The internal representation needed by the calendar is (month day year).
16901 This is a wrapper to handle the brain-dead convention in calendar that
16902 user function argument order change dependent on argument order."
16903 (pcase calendar-date-style
16904 (`american (list arg1 arg2 arg3))
16905 (`european (list arg2 arg1 arg3))
16906 (`iso (list arg2 arg3 arg1))))
16908 (defun org-eval-in-calendar (form &optional keepdate)
16909 "Eval FORM in the calendar window and return to current window.
16910 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16911 (let ((sf (selected-frame))
16912 (sw (selected-window)))
16913 (select-window (get-buffer-window "*Calendar*" t))
16914 (eval form)
16915 (when (and (not keepdate) (calendar-cursor-to-date))
16916 (let* ((date (calendar-cursor-to-date))
16917 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16918 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16919 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16920 (select-window sw)
16921 (select-frame-set-input-focus sf)))
16923 (defun org-calendar-select ()
16924 "Return to `org-read-date' with the date currently selected.
16925 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16926 (interactive)
16927 (when (calendar-cursor-to-date)
16928 (let* ((date (calendar-cursor-to-date))
16929 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16930 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16931 (when (active-minibuffer-window) (exit-minibuffer))))
16933 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16934 "Insert a date stamp for the date given by the internal TIME.
16935 See `format-time-string' for the format of TIME.
16936 WITH-HM means use the stamp format that includes the time of the day.
16937 INACTIVE means use square brackets instead of angular ones, so that the
16938 stamp will not contribute to the agenda.
16939 PRE and POST are optional strings to be inserted before and after the
16940 stamp.
16941 The command returns the inserted time stamp."
16942 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16943 stamp)
16944 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16945 (insert-before-markers (or pre ""))
16946 (when (listp extra)
16947 (setq extra (car extra))
16948 (if (and (stringp extra)
16949 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16950 (setq extra (format "-%02d:%02d"
16951 (string-to-number (match-string 1 extra))
16952 (string-to-number (match-string 2 extra))))
16953 (setq extra nil)))
16954 (when extra
16955 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16956 (insert-before-markers (setq stamp (format-time-string fmt time)))
16957 (insert-before-markers (or post ""))
16958 (setq org-last-inserted-timestamp stamp)))
16960 (defun org-toggle-time-stamp-overlays ()
16961 "Toggle the use of custom time stamp formats."
16962 (interactive)
16963 (setq org-display-custom-times (not org-display-custom-times))
16964 (unless org-display-custom-times
16965 (let ((p (point-min)) (bmp (buffer-modified-p)))
16966 (while (setq p (next-single-property-change p 'display))
16967 (when (and (get-text-property p 'display)
16968 (eq (get-text-property p 'face) 'org-date))
16969 (remove-text-properties
16970 p (setq p (next-single-property-change p 'display))
16971 '(display t))))
16972 (set-buffer-modified-p bmp)))
16973 (org-restart-font-lock)
16974 (setq org-table-may-need-update t)
16975 (if org-display-custom-times
16976 (message "Time stamps are overlaid with custom format")
16977 (message "Time stamp overlays removed")))
16979 (defun org-display-custom-time (beg end)
16980 "Overlay modified time stamp format over timestamp between BEG and END."
16981 (let* ((ts (buffer-substring beg end))
16982 t1 with-hm tf time str (off 0))
16983 (save-match-data
16984 (setq t1 (org-parse-time-string ts t))
16985 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16986 (setq off (- (match-end 0) (match-beginning 0)))))
16987 (setq end (- end off))
16988 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16989 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16990 time (org-fix-decoded-time t1)
16991 str (org-add-props
16992 (format-time-string
16993 (substring tf 1 -1) (apply 'encode-time time))
16994 nil 'mouse-face 'highlight))
16995 (put-text-property beg end 'display str)))
16997 (defun org-fix-decoded-time (time)
16998 "Set 0 instead of nil for the first 6 elements of time.
16999 Don't touch the rest."
17000 (let ((n 0))
17001 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17003 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17004 "Difference between TIMESTAMP-STRING and now in days.
17005 If SECONDS is non-nil, return the difference in seconds."
17006 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17007 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17008 (funcall fdiff (current-time)))))
17010 (defun org-deadline-close-p (timestamp-string &optional ndays)
17011 "Is the time in TIMESTAMP-STRING close to the current date?"
17012 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17013 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17014 (not (org-entry-is-done-p))))
17016 (defun org-get-wdays (ts &optional delay zero-delay)
17017 "Get the deadline lead time appropriate for timestring TS.
17018 When DELAY is non-nil, get the delay time for scheduled items
17019 instead of the deadline lead time. When ZERO-DELAY is non-nil
17020 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17021 don't try to find the delay cookie in the scheduled timestamp."
17022 (let ((tv (if delay org-scheduled-delay-days
17023 org-deadline-warning-days)))
17024 (cond
17025 ((or (and delay (< tv 0))
17026 (and delay zero-delay (<= tv 0))
17027 (and (not delay) (<= tv 0)))
17028 ;; Enforce this value no matter what
17029 (- tv))
17030 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17031 ;; lead time is specified.
17032 (floor (* (string-to-number (match-string 1 ts))
17033 (cdr (assoc (match-string 2 ts)
17034 '(("d" . 1) ("w" . 7)
17035 ("m" . 30.4) ("y" . 365.25)
17036 ("h" . 0.041667)))))))
17037 ;; go for the default.
17038 (t tv))))
17040 (defun org-calendar-select-mouse (ev)
17041 "Return to `org-read-date' with the date currently selected.
17042 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17043 (interactive "e")
17044 (mouse-set-point ev)
17045 (when (calendar-cursor-to-date)
17046 (let* ((date (calendar-cursor-to-date))
17047 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17048 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17049 (when (active-minibuffer-window) (exit-minibuffer))))
17051 (defun org-check-deadlines (ndays)
17052 "Check if there are any deadlines due or past due.
17053 A deadline is considered due if it happens within `org-deadline-warning-days'
17054 days from today's date. If the deadline appears in an entry marked DONE,
17055 it is not shown. A numeric prefix argument NDAYS can be used to test that
17056 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17057 are shown."
17058 (interactive "P")
17059 (let* ((org-warn-days
17060 (cond
17061 ((equal ndays '(4)) 100000)
17062 (ndays (prefix-numeric-value ndays))
17063 (t (abs org-deadline-warning-days))))
17064 (case-fold-search nil)
17065 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17066 (callback
17067 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17068 (message "%d deadlines past-due or due within %d days"
17069 (org-occur regexp nil callback)
17070 org-warn-days)))
17072 (defsubst org-re-timestamp (type)
17073 "Return a regexp for timestamp TYPE.
17074 Allowed values for TYPE are:
17076 all: all timestamps
17077 active: only active timestamps (<...>)
17078 inactive: only inactive timestamps ([...])
17079 scheduled: only scheduled timestamps
17080 deadline: only deadline timestamps
17081 closed: only closed time-stamps
17083 When TYPE is nil, fall back on returning a regexp that matches
17084 both scheduled and deadline timestamps."
17085 (cl-case type
17086 (all org-ts-regexp-both)
17087 (active org-ts-regexp)
17088 (inactive org-ts-regexp-inactive)
17089 (scheduled org-scheduled-time-regexp)
17090 (deadline org-deadline-time-regexp)
17091 (closed org-closed-time-regexp)
17092 (otherwise
17093 (concat "\\<"
17094 (regexp-opt (list org-deadline-string org-scheduled-string))
17095 " *<\\([^>]+\\)>"))))
17097 (defun org-check-before-date (d)
17098 "Check if there are deadlines or scheduled entries before date D."
17099 (interactive (list (org-read-date)))
17100 (let* ((case-fold-search nil)
17101 (regexp (org-re-timestamp org-ts-type))
17102 (ts-type org-ts-type)
17103 (callback
17104 (lambda ()
17105 (let ((match (match-string 1)))
17106 (and (if (memq ts-type '(active inactive all))
17107 (eq (org-element-type (save-excursion
17108 (backward-char)
17109 (org-element-context)))
17110 'timestamp)
17111 (org-at-planning-p))
17112 (time-less-p
17113 (org-time-string-to-time match)
17114 (org-time-string-to-time d)))))))
17115 (message "%d entries before %s"
17116 (org-occur regexp nil callback)
17117 d)))
17119 (defun org-check-after-date (d)
17120 "Check if there are deadlines or scheduled entries after date D."
17121 (interactive (list (org-read-date)))
17122 (let* ((case-fold-search nil)
17123 (regexp (org-re-timestamp org-ts-type))
17124 (ts-type org-ts-type)
17125 (callback
17126 (lambda ()
17127 (let ((match (match-string 1)))
17128 (and (if (memq ts-type '(active inactive all))
17129 (eq (org-element-type (save-excursion
17130 (backward-char)
17131 (org-element-context)))
17132 'timestamp)
17133 (org-at-planning-p))
17134 (not (time-less-p
17135 (org-time-string-to-time match)
17136 (org-time-string-to-time d))))))))
17137 (message "%d entries after %s"
17138 (org-occur regexp nil callback)
17139 d)))
17141 (defun org-check-dates-range (start-date end-date)
17142 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17143 (interactive (list (org-read-date nil nil nil "Range starts")
17144 (org-read-date nil nil nil "Range end")))
17145 (let ((case-fold-search nil)
17146 (regexp (org-re-timestamp org-ts-type))
17147 (callback
17148 (let ((type org-ts-type))
17149 (lambda ()
17150 (let ((match (match-string 1)))
17151 (and
17152 (if (memq type '(active inactive all))
17153 (eq (org-element-type (save-excursion
17154 (backward-char)
17155 (org-element-context)))
17156 'timestamp)
17157 (org-at-planning-p))
17158 (not (time-less-p
17159 (org-time-string-to-time match)
17160 (org-time-string-to-time start-date)))
17161 (time-less-p
17162 (org-time-string-to-time match)
17163 (org-time-string-to-time end-date))))))))
17164 (message "%d entries between %s and %s"
17165 (org-occur regexp nil callback) start-date end-date)))
17167 (defun org-evaluate-time-range (&optional to-buffer)
17168 "Evaluate a time range by computing the difference between start and end.
17169 Normally the result is just printed in the echo area, but with prefix arg
17170 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17171 If the time range is actually in a table, the result is inserted into the
17172 next column.
17173 For time difference computation, a year is assumed to be exactly 365
17174 days in order to avoid rounding problems."
17175 (interactive "P")
17177 (org-clock-update-time-maybe)
17178 (save-excursion
17179 (unless (org-at-date-range-p t)
17180 (goto-char (point-at-bol))
17181 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17182 (unless (org-at-date-range-p t)
17183 (user-error "Not at a time-stamp range, and none found in current line")))
17184 (let* ((ts1 (match-string 1))
17185 (ts2 (match-string 2))
17186 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17187 (match-end (match-end 0))
17188 (time1 (org-time-string-to-time ts1))
17189 (time2 (org-time-string-to-time ts2))
17190 (t1 (float-time time1))
17191 (t2 (float-time time2))
17192 (diff (abs (- t2 t1)))
17193 (negative (< (- t2 t1) 0))
17194 ;; (ys (floor (* 365 24 60 60)))
17195 (ds (* 24 60 60))
17196 (hs (* 60 60))
17197 (fy "%dy %dd %02d:%02d")
17198 (fy1 "%dy %dd")
17199 (fd "%dd %02d:%02d")
17200 (fd1 "%dd")
17201 (fh "%02d:%02d")
17202 y d h m align)
17203 (if havetime
17204 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17206 d (floor (/ diff ds)) diff (mod diff ds)
17207 h (floor (/ diff hs)) diff (mod diff hs)
17208 m (floor (/ diff 60)))
17209 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17211 d (floor (+ (/ diff ds) 0.5))
17212 h 0 m 0))
17213 (if (not to-buffer)
17214 (message "%s" (org-make-tdiff-string y d h m))
17215 (if (org-at-table-p)
17216 (progn
17217 (goto-char match-end)
17218 (setq align t)
17219 (and (looking-at " *|") (goto-char (match-end 0))))
17220 (goto-char match-end))
17221 (when (looking-at
17222 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17223 (replace-match ""))
17224 (when negative (insert " -"))
17225 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17226 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17227 (insert " " (format fh h m))))
17228 (when align (org-table-align))
17229 (message "Time difference inserted")))))
17231 (defun org-make-tdiff-string (y d h m)
17232 (let ((fmt "")
17233 (l nil))
17234 (when (> y 0)
17235 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17236 (push y l))
17237 (when (> d 0)
17238 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17239 (push d l))
17240 (when (> h 0)
17241 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17242 (push h l))
17243 (when (> m 0)
17244 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17245 (push m l))
17246 (apply 'format fmt (nreverse l))))
17248 (defun org-time-string-to-time (s)
17249 "Convert timestamp string S into internal time."
17250 (apply #'encode-time (org-parse-time-string s)))
17252 (defun org-time-string-to-seconds (s)
17253 "Convert a timestamp string S into a number of seconds."
17254 (float-time (org-time-string-to-time s)))
17256 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17258 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17259 "Convert time stamp S to an absolute day number.
17261 If DAYNR in non-nil, and there is a specifier for a cyclic time
17262 stamp, get the closest date to DAYNR. If PREFER is
17263 `past' (respectively `future') return a date past (respectively
17264 after) or equal to DAYNR.
17266 POS is the location of time stamp S, as a buffer position in
17267 BUFFER.
17269 Diary sexp timestamps are matched against DAYNR, when non-nil.
17270 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17271 signaled."
17272 (cond
17273 ((string-match "\\`%%\\((.*)\\)" s)
17274 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17275 ;; only able to match individual dates. If it fails, raise an
17276 ;; error.
17277 (if (and daynr
17278 (org-diary-sexp-entry
17279 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17280 daynr
17281 (signal 'org-diary-sexp-no-match (list s))))
17282 (daynr (org-closest-date s daynr prefer))
17283 (t (time-to-days
17284 (condition-case errdata
17285 (apply #'encode-time (org-parse-time-string s))
17286 (error (error "Bad timestamp `%s'%s\nError was: %s"
17288 (if (not (and buffer pos)) ""
17289 (format-message " at %d in buffer `%s'" pos buffer))
17290 (cdr errdata))))))))
17292 (defun org-days-to-iso-week (days)
17293 "Return the iso week number."
17294 (require 'cal-iso)
17295 (car (calendar-iso-from-absolute days)))
17297 (defun org-small-year-to-year (year)
17298 "Convert 2-digit years into 4-digit years.
17299 YEAR is expanded into one of the 30 next years, if possible, or
17300 into a past one. Any year larger than 99 is returned unchanged."
17301 (if (>= year 100) year
17302 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17303 (century (/ current 100))
17304 (offset (- year (% current 100))))
17305 (cond ((> offset 30) (+ (* (1- century) 100) year))
17306 ((> offset -70) (+ (* century 100) year))
17307 (t (+ (* (1+ century) 100) year))))))
17309 (defun org-time-from-absolute (d)
17310 "Return the time corresponding to date D.
17311 D may be an absolute day number, or a calendar-type list (month day year)."
17312 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17313 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17315 (defvar org-agenda-current-date)
17316 (defun org-calendar-holiday ()
17317 "List of holidays, for Diary display in Org mode."
17318 (require 'holidays)
17319 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17320 (and hl (mapconcat #'identity hl "; "))))
17322 (defun org-diary-sexp-entry (sexp entry d)
17323 "Process a SEXP diary ENTRY for date D."
17324 (require 'diary-lib)
17325 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17326 ;; dynamically.
17327 (let* ((sexp `(let ((entry ,entry)
17328 (date ',d))
17329 ,(car (read-from-string sexp))))
17330 (result (if calendar-debug-sexp (eval sexp)
17331 (condition-case nil
17332 (eval sexp)
17333 (error
17334 (beep)
17335 (message "Bad sexp at line %d in %s: %s"
17336 (org-current-line)
17337 (buffer-file-name) sexp)
17338 (sleep-for 2))))))
17339 (cond ((stringp result) (split-string result "; "))
17340 ((and (consp result)
17341 (not (consp (cdr result)))
17342 (stringp (cdr result))) (cdr result))
17343 ((and (consp result)
17344 (stringp (car result))) result)
17345 (result entry))))
17347 (defun org-diary-to-ical-string (frombuf)
17348 "Get iCalendar entries from diary entries in buffer FROMBUF.
17349 This uses the icalendar.el library."
17350 (let* ((tmpdir temporary-file-directory)
17351 (tmpfile (make-temp-name
17352 (expand-file-name "orgics" tmpdir)))
17353 buf rtn b e)
17354 (with-current-buffer frombuf
17355 (icalendar-export-region (point-min) (point-max) tmpfile)
17356 (setq buf (find-buffer-visiting tmpfile))
17357 (set-buffer buf)
17358 (goto-char (point-min))
17359 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17360 (setq b (match-beginning 0)))
17361 (goto-char (point-max))
17362 (when (re-search-backward "^END:VEVENT" nil t)
17363 (setq e (match-end 0)))
17364 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17365 (kill-buffer buf)
17366 (delete-file tmpfile)
17367 rtn))
17369 (defun org-closest-date (start current prefer)
17370 "Return closest date to CURRENT starting from START.
17372 CURRENT and START are both time stamps.
17374 When PREFER is `past', return a date that is either CURRENT or
17375 past. When PREFER is `future', return a date that is either
17376 CURRENT or future.
17378 Only time stamps with a repeater are modified. Any other time
17379 stamp stay unchanged. In any case, return value is an absolute
17380 day number."
17381 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17382 ;; No repeater. Do not shift time stamp.
17383 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17384 (let ((value (string-to-number (match-string 1 start)))
17385 (type (match-string 2 start)))
17386 (if (= 0 value)
17387 ;; Repeater with a 0-value is considered as void.
17388 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17389 (let* ((base (org-date-to-gregorian start))
17390 (target (org-date-to-gregorian current))
17391 (sday (calendar-absolute-from-gregorian base))
17392 (cday (calendar-absolute-from-gregorian target))
17393 n1 n2)
17394 ;; If START is already past CURRENT, just return START.
17395 (if (<= cday sday) sday
17396 ;; Compute closest date before (N1) and closest date past
17397 ;; (N2) CURRENT.
17398 (pcase type
17399 ("h"
17400 (let ((missing-hours
17401 (mod (+ (- (* 24 (- cday sday))
17402 (nth 2 (org-parse-time-string start)))
17403 org-extend-today-until)
17404 value)))
17405 (setf n1 (if (= missing-hours 0) cday
17406 (- cday (1+ (/ missing-hours 24)))))
17407 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17408 ((or "d" "w")
17409 (let ((value (if (equal type "w") (* 7 value) value)))
17410 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17411 (setf n2 (+ n1 value))))
17412 ("m"
17413 (let* ((add-months
17414 (lambda (d n)
17415 ;; Add N months to gregorian date D, i.e.,
17416 ;; a list (MONTH DAY YEAR). Return a valid
17417 ;; gregorian date.
17418 (let ((m (+ (nth 0 d) n)))
17419 (list (mod m 12)
17420 (nth 1 d)
17421 (+ (/ m 12) (nth 2 d))))))
17422 (months ; Complete months to TARGET.
17423 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17424 (- (nth 0 target) (nth 0 base))
17425 ;; If START's day is greater than
17426 ;; TARGET's, remove incomplete month.
17427 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17428 value)
17429 value))
17430 (before (funcall add-months base months)))
17431 (setf n1 (calendar-absolute-from-gregorian before))
17432 (setf n2
17433 (calendar-absolute-from-gregorian
17434 (funcall add-months before value)))))
17436 (let* ((d (nth 1 base))
17437 (m (nth 0 base))
17438 (y (nth 2 base))
17439 (years ; Complete years to TARGET.
17440 (* (/ (- (nth 2 target)
17442 ;; If START's month and day are
17443 ;; greater than TARGET's, remove
17444 ;; incomplete year.
17445 (if (or (> (nth 0 target) m)
17446 (and (= (nth 0 target) m)
17447 (> (nth 1 target) d)))
17450 value)
17451 value))
17452 (before (list m d (+ y years))))
17453 (setf n1 (calendar-absolute-from-gregorian before))
17454 (setf n2 (calendar-absolute-from-gregorian
17455 (list m d (+ (nth 2 before) value)))))))
17456 ;; Handle PREFER parameter, if any.
17457 (cond
17458 ((eq prefer 'past) (if (= cday n2) n2 n1))
17459 ((eq prefer 'future) (if (= cday n1) n1 n2))
17460 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17462 (defun org-date-to-gregorian (d)
17463 "Turn any specification of date D into a Gregorian date for the calendar."
17464 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17465 ((and (listp d) (= (length d) 3)) d)
17466 ((stringp d)
17467 (let ((d (org-parse-time-string d)))
17468 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17469 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17471 (defun org-parse-time-string (s &optional nodefault)
17472 "Parse the standard Org time string.
17474 This should be a lot faster than the normal `parse-time-string'.
17476 If time is not given, defaults to 0:00. However, with optional
17477 NODEFAULT, hour and minute fields will be nil if not given."
17478 (cond ((string-match org-ts-regexp0 s)
17479 (list 0
17480 (when (or (match-beginning 8) (not nodefault))
17481 (string-to-number (or (match-string 8 s) "0")))
17482 (when (or (match-beginning 7) (not nodefault))
17483 (string-to-number (or (match-string 7 s) "0")))
17484 (string-to-number (match-string 4 s))
17485 (string-to-number (match-string 3 s))
17486 (string-to-number (match-string 2 s))
17487 nil nil nil))
17488 ((string-match "^<[^>]+>$" s)
17489 ;; FIXME: `decode-time' needs to be called with ZONE as its
17490 ;; second argument. However, this requires at least Emacs
17491 ;; 25.1. We can do it when we switch to this version as our
17492 ;; minimal requirement.
17493 (decode-time (seconds-to-time (org-matcher-time s))))
17494 (t (error "Not a standard Org time string: %s" s))))
17496 (defun org-timestamp-up (&optional arg)
17497 "Increase the date item at the cursor by one.
17498 If the cursor is on the year, change the year. If it is on the month,
17499 the day or the time, change that.
17500 With prefix ARG, change by that many units."
17501 (interactive "p")
17502 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17504 (defun org-timestamp-down (&optional arg)
17505 "Decrease the date item at the cursor by one.
17506 If the cursor is on the year, change the year. If it is on the month,
17507 the day or the time, change that.
17508 With prefix ARG, change by that many units."
17509 (interactive "p")
17510 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17512 (defun org-timestamp-up-day (&optional arg)
17513 "Increase the date in the time stamp by one day.
17514 With prefix ARG, change that many days."
17515 (interactive "p")
17516 (if (and (not (org-at-timestamp-p 'lax))
17517 (org-at-heading-p))
17518 (org-todo 'up)
17519 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17521 (defun org-timestamp-down-day (&optional arg)
17522 "Decrease the date in the time stamp by one day.
17523 With prefix ARG, change that many days."
17524 (interactive "p")
17525 (if (and (not (org-at-timestamp-p 'lax))
17526 (org-at-heading-p))
17527 (org-todo 'down)
17528 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17530 (defun org-at-timestamp-p (&optional extended)
17531 "Non-nil if point is inside a timestamp.
17533 By default, the function only consider syntactically valid active
17534 timestamps. However, the caller may have a broader definition
17535 for timestamps. As a consequence, optional argument EXTENDED can
17536 be set to the following values
17538 `inactive'
17540 Include also syntactically valid inactive timestamps.
17542 `agenda'
17544 Include timestamps allowed in Agenda, i.e., those in
17545 properties drawers, planning lines and clock lines.
17547 `lax'
17549 Ignore context. The function matches any part of the
17550 document looking like a timestamp. This includes comments,
17551 example blocks...
17553 For backward-compatibility with Org 9.0, every other non-nil
17554 value is equivalent to `inactive'.
17556 When at a timestamp, return the position of the point as a symbol
17557 among `bracket', `after', `year', `month', `hour', `minute',
17558 `day' or a number of character from the last know part of the
17559 time stamp.
17561 When matching, the match groups are the following:
17562 group 1: year
17563 group 2: month
17564 group 3: day number
17565 group 4: day name
17566 group 5: hours, if any
17567 group 6: minutes, if any"
17568 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17569 (pos (point))
17570 (match?
17571 (let ((boundaries (org-in-regexp regexp)))
17572 (save-match-data
17573 (cond ((null boundaries) nil)
17574 ((eq extended 'lax) t)
17576 (or (and (eq extended 'agenda)
17577 (or (org-at-planning-p)
17578 (org-at-property-p)
17579 (and (bound-and-true-p
17580 org-agenda-include-inactive-timestamps)
17581 (org-at-clock-log-p))))
17582 (eq 'timestamp
17583 (save-excursion
17584 (when (= pos (cdr boundaries)) (forward-char -1))
17585 (org-element-type (org-element-context)))))))))))
17586 (cond
17587 ((not match?) nil)
17588 ((= pos (match-beginning 0)) 'bracket)
17589 ;; Distinguish location right before the closing bracket from
17590 ;; right after it.
17591 ((= pos (1- (match-end 0))) 'bracket)
17592 ((= pos (match-end 0)) 'after)
17593 ((org-pos-in-match-range pos 2) 'year)
17594 ((org-pos-in-match-range pos 3) 'month)
17595 ((org-pos-in-match-range pos 7) 'hour)
17596 ((org-pos-in-match-range pos 8) 'minute)
17597 ((or (org-pos-in-match-range pos 4)
17598 (org-pos-in-match-range pos 5)) 'day)
17599 ((and (> pos (or (match-end 8) (match-end 5)))
17600 (< pos (match-end 0)))
17601 (- pos (or (match-end 8) (match-end 5))))
17602 (t 'day))))
17604 (defun org-toggle-timestamp-type ()
17605 "Toggle the type (<active> or [inactive]) of a time stamp."
17606 (interactive)
17607 (when (org-at-timestamp-p 'lax)
17608 (let ((beg (match-beginning 0)) (end (match-end 0))
17609 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17610 (save-excursion
17611 (goto-char beg)
17612 (while (re-search-forward "[][<>]" end t)
17613 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17614 t t)))
17615 (message "Timestamp is now %sactive"
17616 (if (equal (char-after beg) ?<) "" "in")))))
17618 (defun org-at-clock-log-p ()
17619 "Non-nil if point is on a clock log line."
17620 (and (org-match-line org-clock-line-re)
17621 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17623 (defvar org-clock-history) ; defined in org-clock.el
17624 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17625 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17626 "Change the date in the time stamp at point.
17627 The date will be changed by N times WHAT. WHAT can be `day', `month',
17628 `year', `minute', `second'. If WHAT is not given, the cursor position
17629 in the timestamp determines what will be changed.
17630 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17631 (let ((origin (point))
17632 (timestamp? (org-at-timestamp-p 'lax))
17633 origin-cat
17634 with-hm inactive
17635 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17636 extra rem
17637 ts time time0 fixnext clrgx)
17638 (unless timestamp? (user-error "Not at a timestamp"))
17639 (if (and (not what) (eq timestamp? 'bracket))
17640 (org-toggle-timestamp-type)
17641 ;; Point isn't on brackets. Remember the part of the time-stamp
17642 ;; the point was in. Indeed, size of time-stamps may change,
17643 ;; but point must be kept in the same category nonetheless.
17644 (setq origin-cat timestamp?)
17645 (when (and (not what) (not (eq timestamp? 'day))
17646 org-display-custom-times
17647 (get-text-property (point) 'display)
17648 (not (get-text-property (1- (point)) 'display)))
17649 (setq timestamp? 'day))
17650 (setq timestamp? (or what timestamp?)
17651 inactive (= (char-after (match-beginning 0)) ?\[)
17652 ts (match-string 0))
17653 (replace-match "")
17654 (when (string-match
17655 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17657 (setq extra (match-string 1 ts))
17658 (when suppress-tmp-delay
17659 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17660 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17661 (setq with-hm t))
17662 (setq time0 (org-parse-time-string ts))
17663 (when (and updown
17664 (eq timestamp? 'minute)
17665 (not current-prefix-arg))
17666 ;; This looks like s-up and s-down. Change by one rounding step.
17667 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17668 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17669 (setcar (cdr time0) (+ (nth 1 time0)
17670 (if (> n 0) (- rem) (- dm rem))))))
17671 (setq time
17672 (apply #'encode-time
17673 (or (car time0) 0)
17674 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17675 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17676 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17677 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17678 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17679 (nthcdr 6 time0)))
17680 (when (and (memq timestamp? '(hour minute))
17681 extra
17682 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17683 (setq extra (org-modify-ts-extra
17684 extra
17685 (if (eq timestamp? 'hour) 2 5)
17686 n dm)))
17687 (when (integerp timestamp?)
17688 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17689 (when (eq what 'calendar)
17690 (let ((cal-date (org-get-date-from-calendar)))
17691 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17692 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17693 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17694 (setcar time0 (or (car time0) 0))
17695 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17696 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17697 (setq time (apply 'encode-time time0))))
17698 ;; Insert the new time-stamp, and ensure point stays in the same
17699 ;; category as before (i.e. not after the last position in that
17700 ;; category).
17701 (let ((pos (point)))
17702 ;; Stay before inserted string. `save-excursion' is of no use.
17703 (setq org-last-changed-timestamp
17704 (org-insert-time-stamp time with-hm inactive nil nil extra))
17705 (goto-char pos))
17706 (save-match-data
17707 (looking-at org-ts-regexp3)
17708 (goto-char
17709 (pcase origin-cat
17710 ;; `day' category ends before `hour' if any, or at the end
17711 ;; of the day name.
17712 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17713 (`hour (min (match-end 7) origin))
17714 (`minute (min (1- (match-end 8)) origin))
17715 ((pred integerp) (min (1- (match-end 0)) origin))
17716 ;; Point was right after the time-stamp. However, the
17717 ;; time-stamp length might have changed, so refer to
17718 ;; (match-end 0) instead.
17719 (`after (match-end 0))
17720 ;; `year' and `month' have both fixed size: point couldn't
17721 ;; have moved into another part.
17722 (_ origin))))
17723 ;; Update clock if on a CLOCK line.
17724 (org-clock-update-time-maybe)
17725 ;; Maybe adjust the closest clock in `org-clock-history'
17726 (when org-clock-adjust-closest
17727 (if (not (and (org-at-clock-log-p)
17728 (< 1 (length (delq nil (mapcar 'marker-position
17729 org-clock-history))))))
17730 (message "No clock to adjust")
17731 (cond ((save-excursion ; fix previous clock?
17732 (re-search-backward org-ts-regexp0 nil t)
17733 (looking-back (concat org-clock-string " \\[")
17734 (line-beginning-position)))
17735 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17736 ((save-excursion ; fix next clock?
17737 (re-search-backward org-ts-regexp0 nil t)
17738 (looking-at (concat org-ts-regexp0 "\\] =>")))
17739 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17740 (save-window-excursion
17741 ;; Find closest clock to point, adjust the previous/next one in history
17742 (let* ((p (save-excursion (org-back-to-heading t)))
17743 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17744 (clfixnth
17745 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17746 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17747 (if (not clfixpos)
17748 (message "No clock to adjust")
17749 (save-excursion
17750 (org-goto-marker-or-bmk clfixpos)
17751 (org-show-subtree)
17752 (when (re-search-forward clrgx nil t)
17753 (goto-char (match-beginning 1))
17754 (let (org-clock-adjust-closest)
17755 (org-timestamp-change n timestamp? updown))
17756 (message "Clock adjusted in %s for heading: %s"
17757 (file-name-nondirectory (buffer-file-name))
17758 (org-get-heading t t)))))))))
17759 ;; Try to recenter the calendar window, if any.
17760 (when (and org-calendar-follow-timestamp-change
17761 (get-buffer-window "*Calendar*" t)
17762 (memq timestamp? '(day month year)))
17763 (org-recenter-calendar (time-to-days time))))))
17765 (defun org-modify-ts-extra (s pos n dm)
17766 "Change the different parts of the lead-time and repeat fields in timestamp."
17767 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17768 ng h m new rem)
17769 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17770 (cond
17771 ((or (org-pos-in-match-range pos 2)
17772 (org-pos-in-match-range pos 3))
17773 (setq m (string-to-number (match-string 3 s))
17774 h (string-to-number (match-string 2 s)))
17775 (if (org-pos-in-match-range pos 2)
17776 (setq h (+ h n))
17777 (setq n (* dm (with-no-warnings (signum n))))
17778 (unless (= 0 (setq rem (% m dm)))
17779 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17780 (setq m (+ m n)))
17781 (when (< m 0) (setq m (+ m 60) h (1- h)))
17782 (when (> m 59) (setq m (- m 60) h (1+ h)))
17783 (setq h (mod h 24))
17784 (setq ng 1 new (format "-%02d:%02d" h m)))
17785 ((org-pos-in-match-range pos 6)
17786 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17787 ((org-pos-in-match-range pos 5)
17788 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17790 ((org-pos-in-match-range pos 9)
17791 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17792 ((org-pos-in-match-range pos 8)
17793 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17795 (when ng
17796 (setq s (concat
17797 (substring s 0 (match-beginning ng))
17799 (substring s (match-end ng))))))
17802 (defun org-recenter-calendar (d)
17803 "If the calendar is visible, recenter it to date D."
17804 (let ((cwin (get-buffer-window "*Calendar*" t)))
17805 (when cwin
17806 (let ((calendar-move-hook nil))
17807 (with-selected-window cwin
17808 (calendar-goto-date
17809 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17811 (defun org-goto-calendar (&optional arg)
17812 "Go to the Emacs calendar at the current date.
17813 If there is a time stamp in the current line, go to that date.
17814 A prefix ARG can be used to force the current date."
17815 (interactive "P")
17816 (let ((calendar-move-hook nil)
17817 (calendar-view-holidays-initially-flag nil)
17818 (calendar-view-diary-initially-flag nil)
17819 diff)
17820 (when (or (org-at-timestamp-p 'lax)
17821 (org-match-line (concat ".*" org-ts-regexp)))
17822 (let ((d1 (time-to-days (current-time)))
17823 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17824 (setq diff (- d2 d1))))
17825 (calendar)
17826 (calendar-goto-today)
17827 (when (and diff (not arg)) (calendar-forward-day diff))))
17829 (defun org-get-date-from-calendar ()
17830 "Return a list (month day year) of date at point in calendar."
17831 (with-current-buffer "*Calendar*"
17832 (save-match-data
17833 (calendar-cursor-to-date))))
17835 (defun org-date-from-calendar ()
17836 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17837 If there is already a time stamp at the cursor position, update it."
17838 (interactive)
17839 (if (org-at-timestamp-p 'lax)
17840 (org-timestamp-change 0 'calendar)
17841 (let ((cal-date (org-get-date-from-calendar)))
17842 (org-insert-time-stamp
17843 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17845 (defcustom org-effort-durations
17846 `(("min" . 1)
17847 ("h" . 60)
17848 ("d" . ,(* 60 8))
17849 ("w" . ,(* 60 8 5))
17850 ("m" . ,(* 60 8 5 4))
17851 ("y" . ,(* 60 8 5 40)))
17852 "Conversion factor to minutes for an effort modifier.
17854 Each entry has the form (MODIFIER . MINUTES).
17856 In an effort string, a number followed by MODIFIER is multiplied
17857 by the specified number of MINUTES to obtain an effort in
17858 minutes.
17860 For example, if the value of this variable is ((\"hours\" . 60)), then an
17861 effort string \"2hours\" is equivalent to 120 minutes."
17862 :group 'org-agenda
17863 :version "26.1"
17864 :package-version '(Org . "8.3")
17865 :type '(alist :key-type (string :tag "Modifier")
17866 :value-type (number :tag "Minutes")))
17868 (defcustom org-image-actual-width t
17869 "Should we use the actual width of images when inlining them?
17871 When set to t, always use the image width.
17873 When set to a number, use imagemagick (when available) to set
17874 the image's width to this value.
17876 When set to a number in a list, try to get the width from any
17877 #+ATTR.* keyword if it matches a width specification like
17879 #+ATTR_HTML: :width 300px
17881 and fall back on that number if none is found.
17883 When set to nil, try to get the width from an #+ATTR.* keyword
17884 and fall back on the original width if none is found.
17886 This requires Emacs >= 24.1, build with imagemagick support."
17887 :group 'org-appearance
17888 :version "24.4"
17889 :package-version '(Org . "8.0")
17890 :type '(choice
17891 (const :tag "Use the image width" t)
17892 (integer :tag "Use a number of pixels")
17893 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17894 (const :tag "Use #+ATTR* or don't resize" nil)))
17896 (defcustom org-agenda-inhibit-startup nil
17897 "Inhibit startup when preparing agenda buffers.
17898 When this variable is t, the initialization of the Org agenda
17899 buffers is inhibited: e.g. the visibility state is not set, the
17900 tables are not re-aligned, etc."
17901 :type 'boolean
17902 :version "24.3"
17903 :group 'org-agenda)
17905 (defcustom org-agenda-ignore-properties nil
17906 "Avoid updating text properties when building the agenda.
17907 Properties are used to prepare buffers for effort estimates,
17908 appointments, statistics and subtree-local categories.
17909 If you don't use these in the agenda, you can add them to this
17910 list and agenda building will be a bit faster.
17911 The value is a list, with zero or more of the symbols `effort', `appt',
17912 `stats' or `category'."
17913 :type '(set :greedy t
17914 (const effort)
17915 (const appt)
17916 (const stats)
17917 (const category))
17918 :version "26.1"
17919 :package-version '(Org . "8.3")
17920 :group 'org-agenda)
17922 ;;;; Files
17924 (defun org-save-all-org-buffers ()
17925 "Save all Org buffers without user confirmation."
17926 (interactive)
17927 (message "Saving all Org buffers...")
17928 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17929 (when (featurep 'org-id) (org-id-locations-save))
17930 (message "Saving all Org buffers... done"))
17932 (defun org-revert-all-org-buffers ()
17933 "Revert all Org buffers.
17934 Prompt for confirmation when there are unsaved changes.
17935 Be sure you know what you are doing before letting this function
17936 overwrite your changes.
17938 This function is useful in a setup where one tracks org files
17939 with a version control system, to revert on one machine after pulling
17940 changes from another. I believe the procedure must be like this:
17942 1. M-x org-save-all-org-buffers
17943 2. Pull changes from the other machine, resolve conflicts
17944 3. M-x org-revert-all-org-buffers"
17945 (interactive)
17946 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17947 (user-error "Abort"))
17948 (save-excursion
17949 (save-window-excursion
17950 (dolist (b (buffer-list))
17951 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17952 (with-current-buffer b buffer-file-name))
17953 (pop-to-buffer-same-window b)
17954 (revert-buffer t 'no-confirm)))
17955 (when (and (featurep 'org-id) org-id-track-globally)
17956 (org-id-locations-load)))))
17958 ;;;; Agenda files
17960 ;;;###autoload
17961 (defun org-switchb (&optional arg)
17962 "Switch between Org buffers.
17964 With `\\[universal-argument]' prefix, restrict available buffers to files.
17966 With `\\[universal-argument] \\[universal-argument]' \
17967 prefix, restrict available buffers to agenda files."
17968 (interactive "P")
17969 (let ((blist (org-buffer-list
17970 (cond ((equal arg '(4)) 'files)
17971 ((equal arg '(16)) 'agenda)))))
17972 (pop-to-buffer-same-window
17973 (completing-read "Org buffer: "
17974 (mapcar #'list (mapcar #'buffer-name blist))
17975 nil t))))
17977 (defun org-buffer-list (&optional predicate exclude-tmp)
17978 "Return a list of Org buffers.
17979 PREDICATE can be `export', `files' or `agenda'.
17981 export restrict the list to Export buffers.
17982 files restrict the list to buffers visiting Org files.
17983 agenda restrict the list to buffers visiting agenda files.
17985 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17986 (let* ((bfn nil)
17987 (agenda-files (and (eq predicate 'agenda)
17988 (mapcar 'file-truename (org-agenda-files t))))
17989 (filter
17990 (cond
17991 ((eq predicate 'files)
17992 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17993 ((eq predicate 'export)
17994 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17995 ((eq predicate 'agenda)
17996 (lambda (b)
17997 (with-current-buffer b
17998 (and (derived-mode-p 'org-mode)
17999 (setq bfn (buffer-file-name b))
18000 (member (file-truename bfn) agenda-files)))))
18001 (t (lambda (b) (with-current-buffer b
18002 (or (derived-mode-p 'org-mode)
18003 (string-match "\\*Org .*Export"
18004 (buffer-name b)))))))))
18005 (delq nil
18006 (mapcar
18007 (lambda(b)
18008 (if (and (funcall filter b)
18009 (or (not exclude-tmp)
18010 (not (string-match "tmp" (buffer-name b)))))
18012 nil))
18013 (buffer-list)))))
18015 (defun org-agenda-files (&optional unrestricted archives)
18016 "Get the list of agenda files.
18017 Optional UNRESTRICTED means return the full list even if a restriction
18018 is currently in place.
18019 When ARCHIVES is t, include all archive files that are really being
18020 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18021 `org-agenda-archives-mode' is t."
18022 (let ((files
18023 (cond
18024 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18025 ((stringp org-agenda-files) (org-read-agenda-file-list))
18026 ((listp org-agenda-files) org-agenda-files)
18027 (t (error "Invalid value of `org-agenda-files'")))))
18028 (setq files (apply 'append
18029 (mapcar (lambda (f)
18030 (if (file-directory-p f)
18031 (directory-files
18032 f t org-agenda-file-regexp)
18033 (list f)))
18034 files)))
18035 (when org-agenda-skip-unavailable-files
18036 (setq files (delq nil
18037 (mapcar (function
18038 (lambda (file)
18039 (and (file-readable-p file) file)))
18040 files))))
18041 (when (or (eq archives t)
18042 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18043 (setq files (org-add-archive-files files)))
18044 files))
18046 (defun org-agenda-file-p (&optional file)
18047 "Return non-nil, if FILE is an agenda file.
18048 If FILE is omitted, use the file associated with the current
18049 buffer."
18050 (let ((fname (or file (buffer-file-name))))
18051 (and fname
18052 (member (file-truename fname)
18053 (mapcar #'file-truename (org-agenda-files t))))))
18055 (defun org-edit-agenda-file-list ()
18056 "Edit the list of agenda files.
18057 Depending on setup, this either uses customize to edit the variable
18058 `org-agenda-files', or it visits the file that is holding the list. In the
18059 latter case, the buffer is set up in a way that saving it automatically kills
18060 the buffer and restores the previous window configuration."
18061 (interactive)
18062 (if (stringp org-agenda-files)
18063 (let ((cw (current-window-configuration)))
18064 (find-file org-agenda-files)
18065 (setq-local org-window-configuration cw)
18066 (add-hook 'after-save-hook
18067 (lambda ()
18068 (set-window-configuration
18069 (prog1 org-window-configuration
18070 (kill-buffer (current-buffer))))
18071 (org-install-agenda-files-menu)
18072 (message "New agenda file list installed"))
18073 nil 'local)
18074 (message "%s" (substitute-command-keys
18075 "Edit list and finish with \\[save-buffer]")))
18076 (customize-variable 'org-agenda-files)))
18078 (defun org-store-new-agenda-file-list (list)
18079 "Set new value for the agenda file list and save it correctly."
18080 (if (stringp org-agenda-files)
18081 (let ((fe (org-read-agenda-file-list t)) b u)
18082 (while (setq b (find-buffer-visiting org-agenda-files))
18083 (kill-buffer b))
18084 (with-temp-file org-agenda-files
18085 (insert
18086 (mapconcat
18087 (lambda (f) ;; Keep un-expanded entries.
18088 (if (setq u (assoc f fe))
18089 (cdr u)
18091 list "\n")
18092 "\n")))
18093 (let ((org-mode-hook nil) (org-inhibit-startup t)
18094 (org-insert-mode-line-in-empty-file nil))
18095 (setq org-agenda-files list)
18096 (customize-save-variable 'org-agenda-files org-agenda-files))))
18098 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18099 "Read the list of agenda files from a file.
18100 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18101 filenames, used by `org-store-new-agenda-file-list' to write back
18102 un-expanded file names."
18103 (when (file-directory-p org-agenda-files)
18104 (error "`org-agenda-files' cannot be a single directory"))
18105 (when (stringp org-agenda-files)
18106 (with-temp-buffer
18107 (insert-file-contents org-agenda-files)
18108 (mapcar
18109 (lambda (f)
18110 (let ((e (expand-file-name (substitute-in-file-name f)
18111 org-directory)))
18112 (if pair-with-expansion
18113 (cons e f)
18114 e)))
18115 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18117 ;;;###autoload
18118 (defun org-cycle-agenda-files ()
18119 "Cycle through the files in `org-agenda-files'.
18120 If the current buffer visits an agenda file, find the next one in the list.
18121 If the current buffer does not, find the first agenda file."
18122 (interactive)
18123 (let* ((fs (or (org-agenda-files t)
18124 (user-error "No agenda files")))
18125 (files (copy-sequence fs))
18126 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18127 file)
18128 (when tcf
18129 (while (and (setq file (pop files))
18130 (not (equal (file-truename file) tcf)))))
18131 (find-file (car (or files fs)))
18132 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18134 (defun org-agenda-file-to-front (&optional to-end)
18135 "Move/add the current file to the top of the agenda file list.
18136 If the file is not present in the list, it is added to the front. If it is
18137 present, it is moved there. With optional argument TO-END, add/move to the
18138 end of the list."
18139 (interactive "P")
18140 (let ((org-agenda-skip-unavailable-files nil)
18141 (file-alist (mapcar (lambda (x)
18142 (cons (file-truename x) x))
18143 (org-agenda-files t)))
18144 (ctf (file-truename
18145 (or buffer-file-name
18146 (user-error "Please save the current buffer to a file"))))
18147 x had)
18148 (setq x (assoc ctf file-alist) had x)
18150 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18151 (if to-end
18152 (setq file-alist (append (delq x file-alist) (list x)))
18153 (setq file-alist (cons x (delq x file-alist))))
18154 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18155 (org-install-agenda-files-menu)
18156 (message "File %s to %s of agenda file list"
18157 (if had "moved" "added") (if to-end "end" "front"))))
18159 (defun org-remove-file (&optional file)
18160 "Remove current file from the list of files in variable `org-agenda-files'.
18161 These are the files which are being checked for agenda entries.
18162 Optional argument FILE means use this file instead of the current."
18163 (interactive)
18164 (let* ((org-agenda-skip-unavailable-files nil)
18165 (file (or file buffer-file-name
18166 (user-error "Current buffer does not visit a file")))
18167 (true-file (file-truename file))
18168 (afile (abbreviate-file-name file))
18169 (files (delq nil (mapcar
18170 (lambda (x)
18171 (unless (equal true-file
18172 (file-truename x))
18174 (org-agenda-files t)))))
18175 (if (not (= (length files) (length (org-agenda-files t))))
18176 (progn
18177 (org-store-new-agenda-file-list files)
18178 (org-install-agenda-files-menu)
18179 (message "Removed from Org Agenda list: %s" afile))
18180 (message "File was not in list: %s (not removed)" afile))))
18182 (defun org-file-menu-entry (file)
18183 (vector file (list 'find-file file) t))
18185 (defun org-check-agenda-file (file)
18186 "Make sure FILE exists. If not, ask user what to do."
18187 (unless (file-exists-p file)
18188 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18189 (abbreviate-file-name file))
18190 (let ((r (downcase (read-char-exclusive))))
18191 (cond
18192 ((equal r ?r)
18193 (org-remove-file file)
18194 (throw 'nextfile t))
18195 (t (user-error "Abort"))))))
18197 (defun org-get-agenda-file-buffer (file)
18198 "Get an agenda buffer visiting FILE.
18199 If the buffer needs to be created, add it to the list of buffers
18200 which might be released later."
18201 (let ((buf (org-find-base-buffer-visiting file)))
18202 (if buf
18203 buf ; just return it
18204 ;; Make a new buffer and remember it
18205 (setq buf (find-file-noselect file))
18206 (when buf (push buf org-agenda-new-buffers))
18207 buf)))
18209 (defun org-release-buffers (blist)
18210 "Release all buffers in list, asking the user for confirmation when needed.
18211 When a buffer is unmodified, it is just killed. When modified, it is saved
18212 \(if the user agrees) and then killed."
18213 (let (file)
18214 (dolist (buf blist)
18215 (setq file (buffer-file-name buf))
18216 (when (and (buffer-modified-p buf)
18217 file
18218 (y-or-n-p (format "Save file %s? " file)))
18219 (with-current-buffer buf (save-buffer)))
18220 (kill-buffer buf))))
18222 (defun org-agenda-prepare-buffers (files)
18223 "Create buffers for all agenda files, protect archived trees and comments."
18224 (interactive)
18225 (let ((pa '(:org-archived t))
18226 (pc '(:org-comment t))
18227 (pall '(:org-archived t :org-comment t))
18228 (inhibit-read-only t)
18229 (org-inhibit-startup org-agenda-inhibit-startup)
18230 (rea (concat ":" org-archive-tag ":"))
18231 re pos)
18232 (setq org-tag-alist-for-agenda nil
18233 org-tag-groups-alist-for-agenda nil)
18234 (save-excursion
18235 (save-restriction
18236 (dolist (file files)
18237 (catch 'nextfile
18238 (if (bufferp file)
18239 (set-buffer file)
18240 (org-check-agenda-file file)
18241 (set-buffer (org-get-agenda-file-buffer file)))
18242 (widen)
18243 (org-set-regexps-and-options 'tags-only)
18244 (setq pos (point))
18245 (or (memq 'category org-agenda-ignore-properties)
18246 (org-refresh-category-properties))
18247 (or (memq 'stats org-agenda-ignore-properties)
18248 (org-refresh-stats-properties))
18249 (or (memq 'effort org-agenda-ignore-properties)
18250 (org-refresh-effort-properties))
18251 (or (memq 'appt org-agenda-ignore-properties)
18252 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18253 (setq org-todo-keywords-for-agenda
18254 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18255 (setq org-done-keywords-for-agenda
18256 (append org-done-keywords-for-agenda org-done-keywords))
18257 (setq org-todo-keyword-alist-for-agenda
18258 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18259 (setq org-tag-alist-for-agenda
18260 (org-uniquify
18261 (append org-tag-alist-for-agenda
18262 org-current-tag-alist)))
18263 ;; Merge current file's tag groups into global
18264 ;; `org-tag-groups-alist-for-agenda'.
18265 (when org-group-tags
18266 (dolist (alist org-tag-groups-alist)
18267 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18268 (if old
18269 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18270 (push alist org-tag-groups-alist-for-agenda)))))
18271 (org-with-silent-modifications
18272 (save-excursion
18273 (remove-text-properties (point-min) (point-max) pall)
18274 (when org-agenda-skip-archived-trees
18275 (goto-char (point-min))
18276 (while (re-search-forward rea nil t)
18277 (when (org-at-heading-p t)
18278 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18279 (goto-char (point-min))
18280 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18281 (while (re-search-forward re nil t)
18282 (when (save-match-data (org-in-commented-heading-p t))
18283 (add-text-properties
18284 (match-beginning 0) (org-end-of-subtree t) pc)))))
18285 (goto-char pos)))))
18286 (setq org-todo-keywords-for-agenda
18287 (org-uniquify org-todo-keywords-for-agenda))
18288 (setq org-todo-keyword-alist-for-agenda
18289 (org-uniquify org-todo-keyword-alist-for-agenda))))
18292 ;;;; CDLaTeX minor mode
18294 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18295 "Keymap for the minor `org-cdlatex-mode'.")
18297 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18298 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18299 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18300 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18301 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18303 (defvar org-cdlatex-texmathp-advice-is-done nil
18304 "Flag remembering if we have applied the advice to texmathp already.")
18306 (define-minor-mode org-cdlatex-mode
18307 "Toggle the minor `org-cdlatex-mode'.
18308 This mode supports entering LaTeX environment and math in LaTeX fragments
18309 in Org mode.
18310 \\{org-cdlatex-mode-map}"
18311 nil " OCDL" nil
18312 (when org-cdlatex-mode
18313 (require 'cdlatex)
18314 (run-hooks 'cdlatex-mode-hook)
18315 (cdlatex-compute-tables))
18316 (unless org-cdlatex-texmathp-advice-is-done
18317 (setq org-cdlatex-texmathp-advice-is-done t)
18318 (defadvice texmathp (around org-math-always-on activate)
18319 "Always return t in Org buffers.
18320 This is because we want to insert math symbols without dollars even outside
18321 the LaTeX math segments. If Org mode thinks that point is actually inside
18322 an embedded LaTeX fragment, let `texmathp' do its job.
18323 `\\[org-cdlatex-mode-map]'"
18324 (interactive)
18325 (let (p)
18326 (cond
18327 ((not (derived-mode-p 'org-mode)) ad-do-it)
18328 ((eq this-command 'cdlatex-math-symbol)
18329 (setq ad-return-value t
18330 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18332 (let ((p (org-inside-LaTeX-fragment-p)))
18333 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18334 (setq ad-return-value t
18335 texmathp-why '("Org mode embedded math" . 0))
18336 (when p ad-do-it)))))))))
18338 (defun turn-on-org-cdlatex ()
18339 "Unconditionally turn on `org-cdlatex-mode'."
18340 (org-cdlatex-mode 1))
18342 (defun org-try-cdlatex-tab ()
18343 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18344 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18345 - inside a LaTeX fragment, or
18346 - after the first word in a line, where an abbreviation expansion could
18347 insert a LaTeX environment."
18348 (when org-cdlatex-mode
18349 (cond
18350 ;; Before any word on the line: No expansion possible.
18351 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18352 ;; Just after first word on the line: Expand it. Make sure it
18353 ;; cannot happen on headlines, though.
18354 ((save-excursion
18355 (skip-chars-backward "a-zA-Z0-9*")
18356 (skip-chars-backward " \t")
18357 (and (bolp) (not (org-at-heading-p))))
18358 (cdlatex-tab) t)
18359 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18361 (defun org-cdlatex-underscore-caret (&optional _arg)
18362 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18363 Revert to the normal definition outside of these fragments."
18364 (interactive "P")
18365 (if (org-inside-LaTeX-fragment-p)
18366 (call-interactively 'cdlatex-sub-superscript)
18367 (let (org-cdlatex-mode)
18368 (call-interactively (key-binding (vector last-input-event))))))
18370 (defun org-cdlatex-math-modify (&optional _arg)
18371 "Execute `cdlatex-math-modify' in LaTeX fragments.
18372 Revert to the normal definition outside of these fragments."
18373 (interactive "P")
18374 (if (org-inside-LaTeX-fragment-p)
18375 (call-interactively 'cdlatex-math-modify)
18376 (let (org-cdlatex-mode)
18377 (call-interactively (key-binding (vector last-input-event))))))
18379 (defun org-cdlatex-environment-indent (&optional environment item)
18380 "Execute `cdlatex-environment' and indent the inserted environment.
18382 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18384 The inserted environment is indented to current indentation
18385 unless point is at the beginning of the line, in which the
18386 environment remains unintended."
18387 (interactive)
18388 ;; cdlatex-environment always return nil. Therefore, capture output
18389 ;; first and determine if an environment was selected.
18390 (let* ((beg (point-marker))
18391 (end (copy-marker (point) t))
18392 (inserted (progn
18393 (ignore-errors (cdlatex-environment environment item))
18394 (< beg end)))
18395 ;; Figure out how many lines to move forward after the
18396 ;; environment has been inserted.
18397 (lines (when inserted
18398 (save-excursion
18399 (- (cl-loop while (< beg (point))
18400 with x = 0
18401 do (forward-line -1)
18402 (cl-incf x)
18403 finally return x)
18404 (if (progn (goto-char beg)
18405 (and (progn (skip-chars-forward " \t") (eolp))
18406 (progn (skip-chars-backward " \t") (bolp))))
18407 1 0)))))
18408 (env (org-trim (delete-and-extract-region beg end))))
18409 (when inserted
18410 ;; Get indentation of next line unless at column 0.
18411 (let ((ind (if (bolp) 0
18412 (save-excursion
18413 (org-return-indent)
18414 (prog1 (org-get-indentation)
18415 (when (progn (skip-chars-forward " \t") (eolp))
18416 (delete-region beg (point)))))))
18417 (bol (progn (skip-chars-backward " \t") (bolp))))
18418 ;; Insert a newline before environment unless at column zero
18419 ;; to "escape" the current line. Insert a newline if
18420 ;; something is one the same line as \end{ENVIRONMENT}.
18421 (insert
18422 (concat (unless bol "\n") env
18423 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18424 (unless (zerop ind)
18425 (save-excursion
18426 (goto-char beg)
18427 (while (< (point) end)
18428 (unless (eolp) (indent-line-to ind))
18429 (forward-line))))
18430 (goto-char beg)
18431 (forward-line lines)
18432 (indent-line-to ind)))
18433 (set-marker beg nil)
18434 (set-marker end nil)))
18437 ;;;; LaTeX fragments
18439 (defun org-inside-LaTeX-fragment-p ()
18440 "Test if point is inside a LaTeX fragment.
18441 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18442 sequence appearing also before point.
18443 Even though the matchers for math are configurable, this function assumes
18444 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18445 delimiters are skipped when they have been removed by customization.
18446 The return value is nil, or a cons cell with the delimiter and the
18447 position of this delimiter.
18449 This function does a reasonably good job, but can locally be fooled by
18450 for example currency specifications. For example it will assume being in
18451 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18452 fragments that are properly closed, but during editing, we have to live
18453 with the uncertainty caused by missing closing delimiters. This function
18454 looks only before point, not after."
18455 (catch 'exit
18456 (let ((pos (point))
18457 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18458 (lim (save-excursion (org-backward-paragraph) (point)))
18459 dd-on str (start 0) m re)
18460 (goto-char pos)
18461 (when dodollar
18462 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18463 re (nth 1 (assoc "$" org-latex-regexps)))
18464 (while (string-match re str start)
18465 (cond
18466 ((= (match-end 0) (length str))
18467 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18468 ((= (match-end 0) (- (length str) 5))
18469 (throw 'exit nil))
18470 (t (setq start (match-end 0))))))
18471 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18472 (goto-char pos)
18473 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18474 (and (match-beginning 2) (throw 'exit nil))
18475 ;; count $$
18476 (while (re-search-backward "\\$\\$" lim t)
18477 (setq dd-on (not dd-on)))
18478 (goto-char pos)
18479 (when dd-on (cons "$$" m))))))
18481 (defun org-inside-latex-macro-p ()
18482 "Is point inside a LaTeX macro or its arguments?"
18483 (save-match-data
18484 (org-in-regexp
18485 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18487 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18488 "Build an overlay between BEG and END using IMAGE file.
18489 Argument IMAGETYPE is the extension of the displayed image,
18490 as a string. It defaults to \"png\"."
18491 (let ((ov (make-overlay beg end))
18492 (imagetype (or (intern imagetype) 'png)))
18493 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18494 (overlay-put ov 'evaporate t)
18495 (overlay-put ov
18496 'modification-hooks
18497 (list (lambda (o _flag _beg _end &optional _l)
18498 (delete-overlay o))))
18499 (overlay-put ov
18500 'display
18501 (list 'image :type imagetype :file image :ascent 'center))))
18503 (defun org--list-latex-overlays (&optional beg end)
18504 "List all Org LaTeX overlays in current buffer.
18505 Limit to overlays between BEG and END when those are provided."
18506 (cl-remove-if-not
18507 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18508 (overlays-in (or beg (point-min)) (or end (point-max)))))
18510 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18511 "Remove all overlays with LaTeX fragment images in current buffer.
18512 When optional arguments BEG and END are non-nil, remove all
18513 overlays between them instead. Return a non-nil value when some
18514 overlays were removed, nil otherwise."
18515 (let ((overlays (org--list-latex-overlays beg end)))
18516 (mapc #'delete-overlay overlays)
18517 overlays))
18519 (defun org-toggle-latex-fragment (&optional arg)
18520 "Preview the LaTeX fragment at point, or all locally or globally.
18522 If the cursor is on a LaTeX fragment, create the image and overlay
18523 it over the source code, if there is none. Remove it otherwise.
18524 If there is no fragment at point, display all fragments in the
18525 current section.
18527 With prefix ARG, preview or clear image for all fragments in the
18528 current subtree or in the whole buffer when used before the first
18529 headline. With a prefix ARG `\\[universal-argument] \
18530 \\[universal-argument]' preview or clear images
18531 for all fragments in the buffer."
18532 (interactive "P")
18533 (when (display-graphic-p)
18534 (catch 'exit
18535 (save-excursion
18536 (let (beg end msg)
18537 (cond
18538 ((or (equal arg '(16))
18539 (and (equal arg '(4))
18540 (org-with-limited-levels (org-before-first-heading-p))))
18541 (if (org-remove-latex-fragment-image-overlays)
18542 (progn (message "LaTeX fragments images removed from buffer")
18543 (throw 'exit nil))
18544 (setq msg "Creating images for buffer...")))
18545 ((equal arg '(4))
18546 (org-with-limited-levels (org-back-to-heading t))
18547 (setq beg (point))
18548 (setq end (progn (org-end-of-subtree t) (point)))
18549 (if (org-remove-latex-fragment-image-overlays beg end)
18550 (progn
18551 (message "LaTeX fragment images removed from subtree")
18552 (throw 'exit nil))
18553 (setq msg "Creating images for subtree...")))
18554 ((let ((datum (org-element-context)))
18555 (when (memq (org-element-type datum)
18556 '(latex-environment latex-fragment))
18557 (setq beg (org-element-property :begin datum))
18558 (setq end (org-element-property :end datum))
18559 (if (org-remove-latex-fragment-image-overlays beg end)
18560 (progn (message "LaTeX fragment image removed")
18561 (throw 'exit nil))
18562 (setq msg "Creating image...")))))
18564 (org-with-limited-levels
18565 (setq beg (if (org-at-heading-p) (line-beginning-position)
18566 (outline-previous-heading)
18567 (point)))
18568 (setq end (progn (outline-next-heading) (point)))
18569 (if (org-remove-latex-fragment-image-overlays beg end)
18570 (progn
18571 (message "LaTeX fragment images removed from section")
18572 (throw 'exit nil))
18573 (setq msg "Creating images for section...")))))
18574 (let ((file (buffer-file-name (buffer-base-buffer))))
18575 (org-format-latex
18576 (concat org-preview-latex-image-directory "org-ltximg")
18577 beg end
18578 ;; Emacs cannot overlay images from remote hosts. Create
18579 ;; it in `temporary-file-directory' instead.
18580 (if (or (not file) (file-remote-p file))
18581 temporary-file-directory
18582 default-directory)
18583 'overlays msg 'forbuffer org-preview-latex-default-process))
18584 (message (concat msg "done")))))))
18586 (defun org-format-latex
18587 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18588 "Replace LaTeX fragments with links to an image.
18590 The function takes care of creating the replacement image.
18592 Only consider fragments between BEG and END when those are
18593 provided.
18595 When optional argument OVERLAYS is non-nil, display the image on
18596 top of the fragment instead of replacing it.
18598 PROCESSING-TYPE is the conversion method to use, as a symbol.
18600 Some of the options can be changed using the variable
18601 `org-format-latex-options', which see."
18602 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18603 (unless (eq processing-type 'verbatim)
18604 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18605 (cnt 0)
18606 checkdir-flag)
18607 (goto-char (or beg (point-min)))
18608 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18609 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18610 (overlay-recenter (or end (point-max))))
18611 (while (re-search-forward math-regexp end t)
18612 (unless (and overlays
18613 (eq (get-char-property (point) 'org-overlay-type)
18614 'org-latex-overlay))
18615 (let* ((context (org-element-context))
18616 (type (org-element-type context)))
18617 (when (memq type '(latex-environment latex-fragment))
18618 (let ((block-type (eq type 'latex-environment))
18619 (value (org-element-property :value context))
18620 (beg (org-element-property :begin context))
18621 (end (save-excursion
18622 (goto-char (org-element-property :end context))
18623 (skip-chars-backward " \r\t\n")
18624 (point))))
18625 (cond
18626 ((eq processing-type 'mathjax)
18627 ;; Prepare for MathJax processing.
18628 (if (not (string-match "\\`\\$\\$?" value))
18629 (goto-char end)
18630 (delete-region beg end)
18631 (if (string= (match-string 0 value) "$$")
18632 (insert "\\[" (substring value 2 -2) "\\]")
18633 (insert "\\(" (substring value 1 -1) "\\)"))))
18634 ((assq processing-type org-preview-latex-process-alist)
18635 ;; Process to an image.
18636 (cl-incf cnt)
18637 (goto-char beg)
18638 (let* ((processing-info
18639 (cdr (assq processing-type org-preview-latex-process-alist)))
18640 (face (face-at-point))
18641 ;; Get the colors from the face at point.
18643 (let ((color (plist-get org-format-latex-options
18644 :foreground)))
18645 (if (and forbuffer (eq color 'auto))
18646 (face-attribute face :foreground nil 'default)
18647 color)))
18649 (let ((color (plist-get org-format-latex-options
18650 :background)))
18651 (if (and forbuffer (eq color 'auto))
18652 (face-attribute face :background nil 'default)
18653 color)))
18654 (hash (sha1 (prin1-to-string
18655 (list org-format-latex-header
18656 org-latex-default-packages-alist
18657 org-latex-packages-alist
18658 org-format-latex-options
18659 forbuffer value fg bg))))
18660 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18661 (absprefix (expand-file-name prefix dir))
18662 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18663 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18664 (sep (and block-type "\n\n"))
18665 (link (concat sep "[[file:" linkfile "]]" sep))
18666 (options
18667 (org-combine-plists
18668 org-format-latex-options
18669 `(:foreground ,fg :background ,bg))))
18670 (when msg (message msg cnt))
18671 (unless checkdir-flag ; Ensure the directory exists.
18672 (setq checkdir-flag t)
18673 (let ((todir (file-name-directory absprefix)))
18674 (unless (file-directory-p todir)
18675 (make-directory todir t))))
18676 (unless (file-exists-p movefile)
18677 (org-create-formula-image
18678 value movefile options forbuffer processing-type))
18679 (if overlays
18680 (progn
18681 (dolist (o (overlays-in beg end))
18682 (when (eq (overlay-get o 'org-overlay-type)
18683 'org-latex-overlay)
18684 (delete-overlay o)))
18685 (org--format-latex-make-overlay beg end movefile imagetype)
18686 (goto-char end))
18687 (delete-region beg end)
18688 (insert
18689 (org-add-props link
18690 (list 'org-latex-src
18691 (replace-regexp-in-string "\"" "" value)
18692 'org-latex-src-embed-type
18693 (if block-type 'paragraph 'character)))))))
18694 ((eq processing-type 'mathml)
18695 ;; Process to MathML.
18696 (unless (org-format-latex-mathml-available-p)
18697 (user-error "LaTeX to MathML converter not configured"))
18698 (cl-incf cnt)
18699 (when msg (message msg cnt))
18700 (goto-char beg)
18701 (delete-region beg end)
18702 (insert (org-format-latex-as-mathml
18703 value block-type prefix dir)))
18705 (error "Unknown conversion process %s for LaTeX fragments"
18706 processing-type)))))))))))
18708 (defun org-create-math-formula (latex-frag &optional mathml-file)
18709 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18710 Use `org-latex-to-mathml-convert-command'. If the conversion is
18711 sucessful, return the portion between \"<math...> </math>\"
18712 elements otherwise return nil. When MATHML-FILE is specified,
18713 write the results in to that file. When invoked as an
18714 interactive command, prompt for LATEX-FRAG, with initial value
18715 set to the current active region and echo the results for user
18716 inspection."
18717 (interactive (list (let ((frag (when (org-region-active-p)
18718 (buffer-substring-no-properties
18719 (region-beginning) (region-end)))))
18720 (read-string "LaTeX Fragment: " frag nil frag))))
18721 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18722 (let* ((tmp-in-file
18723 (let ((file (file-relative-name
18724 (make-temp-name (expand-file-name "ltxmathml-in")))))
18725 (write-region latex-frag nil file)
18726 file))
18727 (tmp-out-file (file-relative-name
18728 (make-temp-name (expand-file-name "ltxmathml-out"))))
18729 (cmd (format-spec
18730 org-latex-to-mathml-convert-command
18731 `((?j . ,(and org-latex-to-mathml-jar-file
18732 (shell-quote-argument
18733 (expand-file-name
18734 org-latex-to-mathml-jar-file))))
18735 (?I . ,(shell-quote-argument tmp-in-file))
18736 (?i . ,latex-frag)
18737 (?o . ,(shell-quote-argument tmp-out-file)))))
18738 mathml shell-command-output)
18739 (when (called-interactively-p 'any)
18740 (unless (org-format-latex-mathml-available-p)
18741 (user-error "LaTeX to MathML converter not configured")))
18742 (message "Running %s" cmd)
18743 (setq shell-command-output (shell-command-to-string cmd))
18744 (setq mathml
18745 (when (file-readable-p tmp-out-file)
18746 (with-current-buffer (find-file-noselect tmp-out-file t)
18747 (goto-char (point-min))
18748 (when (re-search-forward
18749 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18750 (regexp-quote
18751 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18752 nil t)
18753 (prog1 (match-string 0) (kill-buffer))))))
18754 (cond
18755 (mathml
18756 (setq mathml
18757 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18758 (when mathml-file
18759 (write-region mathml nil mathml-file))
18760 (when (called-interactively-p 'any)
18761 (message mathml)))
18762 ((message "LaTeX to MathML conversion failed")
18763 (message shell-command-output)))
18764 (delete-file tmp-in-file)
18765 (when (file-exists-p tmp-out-file)
18766 (delete-file tmp-out-file))
18767 mathml))
18769 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18770 prefix &optional dir)
18771 "Use `org-create-math-formula' but check local cache first."
18772 (let* ((absprefix (expand-file-name prefix dir))
18773 (print-length nil) (print-level nil)
18774 (formula-id (concat
18775 "formula-"
18776 (sha1
18777 (prin1-to-string
18778 (list latex-frag
18779 org-latex-to-mathml-convert-command)))))
18780 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18781 (formula-cache-dir (file-name-directory formula-cache)))
18783 (unless (file-directory-p formula-cache-dir)
18784 (make-directory formula-cache-dir t))
18786 (unless (file-exists-p formula-cache)
18787 (org-create-math-formula latex-frag formula-cache))
18789 (if (file-exists-p formula-cache)
18790 ;; Successful conversion. Return the link to MathML file.
18791 (org-add-props
18792 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18793 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18794 'org-latex-src-embed-type (if latex-frag-type
18795 'paragraph 'character)))
18796 ;; Failed conversion. Return the LaTeX fragment verbatim
18797 latex-frag)))
18799 (defun org--get-display-dpi ()
18800 "Get the DPI of the display.
18801 The function assumes that the display has the same pixel width in
18802 the horizontal and vertical directions."
18803 (if (display-graphic-p)
18804 (round (/ (display-pixel-height)
18805 (/ (display-mm-height) 25.4)))
18806 (error "Attempt to calculate the dpi of a non-graphic display")))
18808 (defun org-create-formula-image
18809 (string tofile options buffer &optional processing-type)
18810 "Create an image from LaTeX source using external processes.
18812 The LaTeX STRING is saved to a temporary LaTeX file, then
18813 converted to an image file by process PROCESSING-TYPE defined in
18814 `org-preview-latex-process-alist'. A nil value defaults to
18815 `org-preview-latex-default-process'.
18817 The generated image file is eventually moved to TOFILE.
18819 The OPTIONS argument controls the size, foreground color and
18820 background color of the generated image.
18822 When BUFFER non-nil, this function is used for LaTeX previewing.
18823 Otherwise, it is used to deal with LaTeX snippets showed in
18824 a HTML file."
18825 (let* ((processing-type (or processing-type
18826 org-preview-latex-default-process))
18827 (processing-info
18828 (cdr (assq processing-type org-preview-latex-process-alist)))
18829 (programs (plist-get processing-info :programs))
18830 (error-message (or (plist-get processing-info :message) ""))
18831 (use-xcolor (plist-get processing-info :use-xcolor))
18832 (image-input-type (plist-get processing-info :image-input-type))
18833 (image-output-type (plist-get processing-info :image-output-type))
18834 (post-clean (or (plist-get processing-info :post-clean)
18835 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18836 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18837 (latex-header
18838 (or (plist-get processing-info :latex-header)
18839 (org-latex-make-preamble
18840 (org-export-get-environment (org-export-get-backend 'latex))
18841 org-format-latex-header
18842 'snippet)))
18843 (latex-compiler (plist-get processing-info :latex-compiler))
18844 (image-converter (plist-get processing-info :image-converter))
18845 (tmpdir temporary-file-directory)
18846 (texfilebase (make-temp-name
18847 (expand-file-name "orgtex" tmpdir)))
18848 (texfile (concat texfilebase ".tex"))
18849 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18850 '(1.0 . 1.0)))
18851 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18852 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18853 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18854 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18855 "Black"))
18856 (bg (or (plist-get options (if buffer :background :html-background))
18857 "Transparent"))
18858 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18859 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18860 (dolist (program programs)
18861 (org-check-external-command program error-message))
18862 (if use-xcolor
18863 (progn (if (eq fg 'default)
18864 (setq fg (org-latex-color :foreground))
18865 (setq fg (org-latex-color-format fg)))
18866 (if (eq bg 'default)
18867 (setq bg (org-latex-color :background))
18868 (setq bg (org-latex-color-format
18869 (if (string= bg "Transparent") "white" bg))))
18870 (with-temp-file texfile
18871 (insert latex-header)
18872 (insert "\n\\begin{document}\n"
18873 "\\definecolor{fg}{rgb}{" fg "}\n"
18874 "\\definecolor{bg}{rgb}{" bg "}\n"
18875 "\n\\pagecolor{bg}\n"
18876 "\n{\\color{fg}\n"
18877 string
18878 "\n}\n"
18879 "\n\\end{document}\n")))
18880 (if (eq fg 'default)
18881 (setq fg (org-dvipng-color :foreground))
18882 (unless (string= fg "Transparent")
18883 (setq fg (org-dvipng-color-format fg))))
18884 (if (eq bg 'default)
18885 (setq bg (org-dvipng-color :background))
18886 (unless (string= bg "Transparent")
18887 (setq bg (org-dvipng-color-format bg))))
18888 (with-temp-file texfile
18889 (insert latex-header)
18890 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18892 (let* ((err-msg (format "Please adjust `%s' part of \
18893 `org-preview-latex-process-alist'."
18894 processing-type))
18895 (image-input-file
18896 (org-compile-file
18897 texfile latex-compiler image-input-type err-msg log-buf))
18898 (image-output-file
18899 (org-compile-file
18900 image-input-file image-converter image-output-type err-msg log-buf
18901 `((?F . ,(shell-quote-argument fg))
18902 (?B . ,(shell-quote-argument bg))
18903 (?D . ,(shell-quote-argument (format "%s" dpi)))
18904 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18905 (copy-file image-output-file tofile 'replace)
18906 (dolist (e post-clean)
18907 (when (file-exists-p (concat texfilebase e))
18908 (delete-file (concat texfilebase e))))
18909 image-output-file)))
18911 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18912 "Fill a LaTeX header template TPL.
18913 In the template, the following place holders will be recognized:
18915 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18916 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18917 [PACKAGES] \\usepackage statements for PKG
18918 [NO-PACKAGES] do not include PKG
18919 [EXTRA] the string EXTRA
18920 [NO-EXTRA] do not include EXTRA
18922 For backward compatibility, if both the positive and the negative place
18923 holder is missing, the positive one (without the \"NO-\") will be
18924 assumed to be present at the end of the template.
18925 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18926 EXTRA is a string.
18927 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18928 (let (rpl (end ""))
18929 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18930 (setq rpl (if (or (match-end 1) (not def-pkg))
18931 "" (org-latex-packages-to-string def-pkg snippets-p t))
18932 tpl (replace-match rpl t t tpl))
18933 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18935 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18936 (setq rpl (if (or (match-end 1) (not pkg))
18937 "" (org-latex-packages-to-string pkg snippets-p t))
18938 tpl (replace-match rpl t t tpl))
18939 (when pkg (setq end
18940 (concat end "\n"
18941 (org-latex-packages-to-string pkg snippets-p)))))
18943 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18944 (setq rpl (if (or (match-end 1) (not extra))
18945 "" (concat extra "\n"))
18946 tpl (replace-match rpl t t tpl))
18947 (when (and extra (string-match "\\S-" extra))
18948 (setq end (concat end "\n" extra))))
18950 (if (string-match "\\S-" end)
18951 (concat tpl "\n" end)
18952 tpl)))
18954 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18955 "Turn an alist of packages into a string with the \\usepackage macros."
18956 (setq pkg (mapconcat (lambda(p)
18957 (cond
18958 ((stringp p) p)
18959 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18960 (format "%% Package %s omitted" (cadr p)))
18961 ((equal "" (car p))
18962 (format "\\usepackage{%s}" (cadr p)))
18964 (format "\\usepackage[%s]{%s}"
18965 (car p) (cadr p)))))
18967 "\n"))
18968 (if newline (concat pkg "\n") pkg))
18970 (defun org-dvipng-color (attr)
18971 "Return a RGB color specification for dvipng."
18972 (org-dvipng-color-format (face-attribute 'default attr nil)))
18974 (defun org-dvipng-color-format (color-name)
18975 "Convert COLOR-NAME to a RGB color value for dvipng."
18976 (apply #'format "rgb %s %s %s"
18977 (mapcar 'org-normalize-color
18978 (color-values color-name))))
18980 (defun org-latex-color (attr)
18981 "Return a RGB color for the LaTeX color package."
18982 (org-latex-color-format (face-attribute 'default attr nil)))
18984 (defun org-latex-color-format (color-name)
18985 "Convert COLOR-NAME to a RGB color value."
18986 (apply #'format "%s,%s,%s"
18987 (mapcar 'org-normalize-color
18988 (color-values color-name))))
18990 (defun org-normalize-color (value)
18991 "Return string to be used as color value for an RGB component."
18992 (format "%g" (/ value 65535.0)))
18996 ;; Image display
18998 (defvar-local org-inline-image-overlays nil)
19000 (defun org-toggle-inline-images (&optional include-linked)
19001 "Toggle the display of inline images.
19002 INCLUDE-LINKED is passed to `org-display-inline-images'."
19003 (interactive "P")
19004 (if org-inline-image-overlays
19005 (progn
19006 (org-remove-inline-images)
19007 (when (called-interactively-p 'interactive)
19008 (message "Inline image display turned off")))
19009 (org-display-inline-images include-linked)
19010 (when (called-interactively-p 'interactive)
19011 (message (if org-inline-image-overlays
19012 (format "%d images displayed inline"
19013 (length org-inline-image-overlays))
19014 "No images to display inline")))))
19016 (defun org-redisplay-inline-images ()
19017 "Refresh the display of inline images."
19018 (interactive)
19019 (if (not org-inline-image-overlays)
19020 (org-toggle-inline-images)
19021 (org-toggle-inline-images)
19022 (org-toggle-inline-images)))
19024 (defun org-display-inline-images (&optional include-linked refresh beg end)
19025 "Display inline images.
19027 An inline image is a link which follows either of these
19028 conventions:
19030 1. Its path is a file with an extension matching return value
19031 from `image-file-name-regexp' and it has no contents.
19033 2. Its description consists in a single link of the previous
19034 type.
19036 When optional argument INCLUDE-LINKED is non-nil, also links with
19037 a text description part will be inlined. This can be nice for
19038 a quick look at those images, but it does not reflect what
19039 exported files will look like.
19041 When optional argument REFRESH is non-nil, refresh existing
19042 images between BEG and END. This will create new image displays
19043 only if necessary. BEG and END default to the buffer
19044 boundaries."
19045 (interactive "P")
19046 (when (display-graphic-p)
19047 (unless refresh
19048 (org-remove-inline-images)
19049 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19050 (org-with-wide-buffer
19051 (goto-char (or beg (point-min)))
19052 (let* ((case-fold-search t)
19053 (file-extension-re (image-file-name-regexp))
19054 (link-abbrevs (mapcar #'car
19055 (append org-link-abbrev-alist-local
19056 org-link-abbrev-alist)))
19057 ;; Check absolute, relative file names and explicit
19058 ;; "file:" links. Also check link abbreviations since
19059 ;; some might expand to "file" links.
19060 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19061 (if (not link-abbrevs) ""
19062 (format "\\|\\(?:%s:\\)"
19063 (regexp-opt link-abbrevs))))))
19064 (while (re-search-forward file-types-re end t)
19065 (let ((link (save-match-data (org-element-context))))
19066 ;; Check if we're at an inline image, i.e., an image file
19067 ;; link without a description (unless INCLUDE-LINKED is
19068 ;; non-nil).
19069 (when (and (equal "file" (org-element-property :type link))
19070 (or include-linked
19071 (null (org-element-contents link)))
19072 (string-match-p file-extension-re
19073 (org-element-property :path link)))
19074 (let ((file (expand-file-name
19075 (org-link-unescape
19076 (org-element-property :path link)))))
19077 (when (file-exists-p file)
19078 (let ((width
19079 ;; Apply `org-image-actual-width' specifications.
19080 (cond
19081 ((not (image-type-available-p 'imagemagick)) nil)
19082 ((eq org-image-actual-width t) nil)
19083 ((listp org-image-actual-width)
19085 ;; First try to find a width among
19086 ;; attributes associated to the paragraph
19087 ;; containing link.
19088 (let ((paragraph
19089 (let ((e link))
19090 (while (and (setq e (org-element-property
19091 :parent e))
19092 (not (eq (org-element-type e)
19093 'paragraph))))
19094 e)))
19095 (when paragraph
19096 (save-excursion
19097 (goto-char (org-element-property :begin paragraph))
19098 (when
19099 (re-search-forward
19100 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19101 (org-element-property
19102 :post-affiliated paragraph)
19104 (string-to-number (match-string 1))))))
19105 ;; Otherwise, fall-back to provided number.
19106 (car org-image-actual-width)))
19107 ((numberp org-image-actual-width)
19108 org-image-actual-width)))
19109 (old (get-char-property-and-overlay
19110 (org-element-property :begin link)
19111 'org-image-overlay)))
19112 (if (and (car-safe old) refresh)
19113 (image-refresh (overlay-get (cdr old) 'display))
19114 (let ((image (create-image file
19115 (and width 'imagemagick)
19117 :width width)))
19118 (when image
19119 (let ((ov (make-overlay
19120 (org-element-property :begin link)
19121 (progn
19122 (goto-char
19123 (org-element-property :end link))
19124 (skip-chars-backward " \t")
19125 (point)))))
19126 (overlay-put ov 'display image)
19127 (overlay-put ov 'face 'default)
19128 (overlay-put ov 'org-image-overlay t)
19129 (overlay-put
19130 ov 'modification-hooks
19131 (list 'org-display-inline-remove-overlay))
19132 (push ov org-inline-image-overlays)))))))))))))))
19134 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19135 "Remove inline-display overlay if a corresponding region is modified."
19136 (let ((inhibit-modification-hooks t))
19137 (when (and ov after)
19138 (delete ov org-inline-image-overlays)
19139 (delete-overlay ov))))
19141 (defun org-remove-inline-images ()
19142 "Remove inline display of images."
19143 (interactive)
19144 (mapc #'delete-overlay org-inline-image-overlays)
19145 (setq org-inline-image-overlays nil))
19147 ;;;; Key bindings
19149 (defun org-remap (map &rest commands)
19150 "In MAP, remap the functions given in COMMANDS.
19151 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19152 (let (new old)
19153 (while commands
19154 (setq old (pop commands) new (pop commands))
19155 (org-defkey map (vector 'remap old) new))))
19157 ;; Outline functions from `outline-mode-prefix-map'
19158 ;; that can be remapped in Org:
19159 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19160 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19161 (define-key org-mode-map [remap outline-forward-same-level]
19162 'org-forward-heading-same-level)
19163 (define-key org-mode-map [remap outline-backward-same-level]
19164 'org-backward-heading-same-level)
19165 (define-key org-mode-map [remap outline-show-branches]
19166 'org-kill-note-or-show-branches)
19167 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19168 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19169 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19170 (define-key org-mode-map [remap outline-next-visible-heading]
19171 'org-next-visible-heading)
19172 (define-key org-mode-map [remap outline-previous-visible-heading]
19173 'org-previous-visible-heading)
19174 (define-key org-mode-map [remap show-children] 'org-show-children)
19176 ;; Outline functions from `outline-mode-prefix-map' that can not
19177 ;; be remapped in Org:
19179 ;; - the column "key binding" shows whether the Outline function is still
19180 ;; available in Org mode on the same key that it has been bound to in
19181 ;; Outline mode:
19182 ;; - "overridden": key used for a different functionality in Org mode
19183 ;; - else: key still bound to the same Outline function in Org mode
19185 ;; | Outline function | key binding | Org replacement |
19186 ;; |------------------------------------+-------------+--------------------------|
19187 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19188 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19189 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19190 ;; | `show-entry' | overridden | no replacement |
19191 ;; | `show-branches' | `C-c C-k' | still same function |
19192 ;; | `show-subtree' | overridden | visibility cycling |
19193 ;; | `show-all' | overridden | no replacement |
19194 ;; | `hide-subtree' | overridden | visibility cycling |
19195 ;; | `hide-body' | overridden | no replacement |
19196 ;; | `hide-entry' | overridden | visibility cycling |
19197 ;; | `hide-leaves' | overridden | no replacement |
19198 ;; | `hide-sublevels' | overridden | no replacement |
19199 ;; | `hide-other' | overridden | no replacement |
19201 ;; Make `C-c C-x' a prefix key
19202 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19204 ;; TAB key with modifiers
19205 (org-defkey org-mode-map "\C-i" 'org-cycle)
19206 (org-defkey org-mode-map [(tab)] 'org-cycle)
19207 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19208 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19210 ;; The following line is necessary under Suse GNU/Linux
19211 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19212 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19213 (define-key org-mode-map [backtab] 'org-shifttab)
19215 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19216 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19217 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19219 ;; Cursor keys with modifiers
19220 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19221 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19222 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19223 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19225 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19226 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19227 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19228 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19229 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19230 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19232 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19233 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19234 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19235 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19237 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19238 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19239 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19240 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19242 ;; Babel keys
19243 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19244 (dolist (pair org-babel-key-bindings)
19245 (define-key org-babel-map (car pair) (cdr pair)))
19247 ;;; Extra keys for tty access.
19248 ;; We only set them when really needed because otherwise the
19249 ;; menus don't show the simple keys
19251 (when (or org-use-extra-keys (not window-system))
19252 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19253 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19254 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19255 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19256 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19257 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19258 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19259 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19260 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19261 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19262 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19263 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19264 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19265 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19266 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19267 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19268 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19269 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19270 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19271 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19272 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19273 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19274 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19275 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19276 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19277 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19278 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19279 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19281 ;; All the other keys
19282 (org-remap org-mode-map
19283 'self-insert-command 'org-self-insert-command
19284 'delete-char 'org-delete-char
19285 'delete-backward-char 'org-delete-backward-char)
19286 (org-defkey org-mode-map "|" 'org-force-self-insert)
19288 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19289 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19290 (if (boundp 'narrow-map)
19291 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19292 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19293 (if (boundp 'narrow-map)
19294 (org-defkey narrow-map "b" 'org-narrow-to-block)
19295 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19296 (if (boundp 'narrow-map)
19297 (org-defkey narrow-map "e" 'org-narrow-to-element)
19298 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19299 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19300 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19301 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19302 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19303 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19304 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19305 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19306 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19307 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19308 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19309 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19310 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19311 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19312 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19313 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19314 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19315 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19316 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19317 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19318 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19319 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19320 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19321 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19322 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19323 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19324 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19325 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19326 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19327 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19328 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19329 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19330 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19331 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19332 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19333 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19334 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19335 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19336 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19337 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19338 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19339 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19340 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19341 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19342 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19343 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19344 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19345 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19346 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19347 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19348 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19349 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19350 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19351 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19352 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19353 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19354 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19355 (org-defkey org-mode-map "\C-c^" 'org-sort)
19356 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19357 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19358 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19359 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19360 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19361 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19362 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19363 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19364 (org-defkey org-mode-map "\C-m" 'org-return)
19365 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19366 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19367 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19368 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19369 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19370 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19371 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19372 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19373 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19374 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19375 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19376 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19377 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19378 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19379 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19380 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19381 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19382 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19383 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19384 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19385 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19386 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19387 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19388 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19389 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19391 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19392 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19393 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19395 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19396 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19397 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19398 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19399 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19400 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19401 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19402 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19403 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19404 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19405 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19406 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19407 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19408 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19409 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19410 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19411 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19412 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19413 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19414 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19415 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19416 (org-defkey org-mode-map "\C-c\C-xw" 'org-insert-structure-template)
19417 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19419 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19420 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19421 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19422 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19423 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19425 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19427 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19429 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19430 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19432 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19435 (defconst org-speed-commands-default
19437 ("Outline Navigation")
19438 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19439 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19440 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19441 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19442 ("F" . org-next-block)
19443 ("B" . org-previous-block)
19444 ("u" . (org-speed-move-safe 'outline-up-heading))
19445 ("j" . org-goto)
19446 ("g" . (org-refile t))
19447 ("Outline Visibility")
19448 ("c" . org-cycle)
19449 ("C" . org-shifttab)
19450 (" " . org-display-outline-path)
19451 ("s" . org-narrow-to-subtree)
19452 ("=" . org-columns)
19453 ("Outline Structure Editing")
19454 ("U" . org-metaup)
19455 ("D" . org-metadown)
19456 ("r" . org-metaright)
19457 ("l" . org-metaleft)
19458 ("R" . org-shiftmetaright)
19459 ("L" . org-shiftmetaleft)
19460 ("i" . (progn (forward-char 1) (call-interactively
19461 'org-insert-heading-respect-content)))
19462 ("^" . org-sort)
19463 ("w" . org-refile)
19464 ("a" . org-archive-subtree-default-with-confirmation)
19465 ("@" . org-mark-subtree)
19466 ("#" . org-toggle-comment)
19467 ("Clock Commands")
19468 ("I" . org-clock-in)
19469 ("O" . org-clock-out)
19470 ("Meta Data Editing")
19471 ("t" . org-todo)
19472 ("," . (org-priority))
19473 ("0" . (org-priority ?\ ))
19474 ("1" . (org-priority ?A))
19475 ("2" . (org-priority ?B))
19476 ("3" . (org-priority ?C))
19477 (":" . org-set-tags-command)
19478 ("e" . org-set-effort)
19479 ("E" . org-inc-effort)
19480 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19481 (org-entry-put (point) "APPT_WARNTIME" m)))
19482 ("Agenda Views etc")
19483 ("v" . org-agenda)
19484 ("/" . org-sparse-tree)
19485 ("Misc")
19486 ("o" . org-open-at-point)
19487 ("?" . org-speed-command-help)
19488 ("<" . (org-agenda-set-restriction-lock 'subtree))
19489 (">" . (org-agenda-remove-restriction-lock))
19491 "The default speed commands.")
19493 (defun org-print-speed-command (e)
19494 (if (> (length (car e)) 1)
19495 (progn
19496 (princ "\n")
19497 (princ (car e))
19498 (princ "\n")
19499 (princ (make-string (length (car e)) ?-))
19500 (princ "\n"))
19501 (princ (car e))
19502 (princ " ")
19503 (if (symbolp (cdr e))
19504 (princ (symbol-name (cdr e)))
19505 (prin1 (cdr e)))
19506 (princ "\n")))
19508 (defun org-speed-command-help ()
19509 "Show the available speed commands."
19510 (interactive)
19511 (if (not org-use-speed-commands)
19512 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19513 (with-output-to-temp-buffer "*Help*"
19514 (princ "User-defined Speed commands\n===========================\n")
19515 (mapc #'org-print-speed-command org-speed-commands-user)
19516 (princ "\n")
19517 (princ "Built-in Speed commands\n=======================\n")
19518 (mapc #'org-print-speed-command org-speed-commands-default))
19519 (with-current-buffer "*Help*"
19520 (setq truncate-lines t))))
19522 (defun org-speed-move-safe (cmd)
19523 "Execute CMD, but make sure that the cursor always ends up in a headline.
19524 If not, return to the original position and throw an error."
19525 (interactive)
19526 (let ((pos (point)))
19527 (call-interactively cmd)
19528 (unless (and (bolp) (org-at-heading-p))
19529 (goto-char pos)
19530 (error "Boundary reached while executing %s" cmd))))
19532 (defvar org-self-insert-command-undo-counter 0)
19534 (defvar org-table-auto-blank-field) ; defined in org-table.el
19535 (defvar org-speed-command nil)
19537 (defun org-speed-command-activate (keys)
19538 "Hook for activating single-letter speed commands.
19539 `org-speed-commands-default' specifies a minimal command set.
19540 Use `org-speed-commands-user' for further customization."
19541 (when (or (and (bolp) (looking-at org-outline-regexp))
19542 (and (functionp org-use-speed-commands)
19543 (funcall org-use-speed-commands)))
19544 (cdr (assoc keys (append org-speed-commands-user
19545 org-speed-commands-default)))))
19547 (defun org-babel-speed-command-activate (keys)
19548 "Hook for activating single-letter code block commands."
19549 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19550 (cdr (assoc keys org-babel-key-bindings))))
19552 (defcustom org-speed-command-hook
19553 '(org-speed-command-activate org-babel-speed-command-activate)
19554 "Hook for activating speed commands at strategic locations.
19555 Hook functions are called in sequence until a valid handler is
19556 found.
19558 Each hook takes a single argument, a user-pressed command key
19559 which is also a `self-insert-command' from the global map.
19561 Within the hook, examine the cursor position and the command key
19562 and return nil or a valid handler as appropriate. Handler could
19563 be one of an interactive command, a function, or a form.
19565 Set `org-use-speed-commands' to non-nil value to enable this
19566 hook. The default setting is `org-speed-command-activate'."
19567 :group 'org-structure
19568 :version "24.1"
19569 :type 'hook)
19571 (defun org-self-insert-command (N)
19572 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19573 If the cursor is in a table looking at whitespace, the whitespace is
19574 overwritten, and the table is not marked as requiring realignment."
19575 (interactive "p")
19576 (org-check-before-invisible-edit 'insert)
19577 (cond
19578 ((and org-use-speed-commands
19579 (let ((kv (this-command-keys-vector)))
19580 (setq org-speed-command
19581 (run-hook-with-args-until-success
19582 'org-speed-command-hook
19583 (make-string 1 (aref kv (1- (length kv))))))))
19584 (cond
19585 ((commandp org-speed-command)
19586 (setq this-command org-speed-command)
19587 (call-interactively org-speed-command))
19588 ((functionp org-speed-command)
19589 (funcall org-speed-command))
19590 ((and org-speed-command (listp org-speed-command))
19591 (eval org-speed-command))
19592 (t (let (org-use-speed-commands)
19593 (call-interactively 'org-self-insert-command)))))
19594 ((and
19595 (org-at-table-p)
19596 (eq N 1)
19597 (not (org-region-active-p))
19598 (progn
19599 ;; Check if we blank the field, and if that triggers align.
19600 (and (featurep 'org-table) org-table-auto-blank-field
19601 (memq last-command
19602 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19603 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19604 ;; Got extra space, this field does not determine
19605 ;; column width.
19606 (let (org-table-may-need-update) (org-table-blank-field))
19607 ;; No extra space, this field may determine column
19608 ;; width.
19609 (org-table-blank-field)))
19611 (looking-at "[^|\n]* \\( \\)|"))
19612 ;; There is room for insertion without re-aligning the table.
19613 (delete-region (match-beginning 1) (match-end 1))
19614 (self-insert-command N))
19616 (setq org-table-may-need-update t)
19617 (self-insert-command N)
19618 (org-fix-tags-on-the-fly)
19619 (when org-self-insert-cluster-for-undo
19620 (if (not (eq last-command 'org-self-insert-command))
19621 (setq org-self-insert-command-undo-counter 1)
19622 (if (>= org-self-insert-command-undo-counter 20)
19623 (setq org-self-insert-command-undo-counter 1)
19624 (and (> org-self-insert-command-undo-counter 0)
19625 buffer-undo-list (listp buffer-undo-list)
19626 (not (cadr buffer-undo-list)) ; remove nil entry
19627 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19628 (setq org-self-insert-command-undo-counter
19629 (1+ org-self-insert-command-undo-counter))))))))
19631 (defun org-check-before-invisible-edit (kind)
19632 "Check is editing if kind KIND would be dangerous with invisible text around.
19633 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19634 ;; First, try to get out of here as quickly as possible, to reduce overhead
19635 (when (and org-catch-invisible-edits
19636 (or (not (boundp 'visible-mode)) (not visible-mode))
19637 (or (get-char-property (point) 'invisible)
19638 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19639 ;; OK, we need to take a closer look. Do not consider
19640 ;; invisibility obtained through text properties (e.g., link
19641 ;; fontification), as it cannot be toggled.
19642 (let* ((invisible-at-point
19643 (pcase (get-char-property-and-overlay (point) 'invisible)
19644 (`(,_ . ,(and (pred overlayp) o)) o)))
19645 ;; Assume that point cannot land in the middle of an
19646 ;; overlay, or between two overlays.
19647 (invisible-before-point
19648 (and (not invisible-at-point)
19649 (not (bobp))
19650 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19651 (`(,_ . ,(and (pred overlayp) o)) o))))
19652 (border-and-ok-direction
19654 ;; Check if we are acting predictably before invisible
19655 ;; text.
19656 (and invisible-at-point
19657 (memq kind '(insert delete-backward)))
19658 ;; Check if we are acting predictably after invisible text
19659 ;; This works not well, and I have turned it off. It seems
19660 ;; better to always show and stop after invisible text.
19661 ;; (and (not invisible-at-point) invisible-before-point
19662 ;; (memq kind '(insert delete)))
19664 (when (or invisible-at-point invisible-before-point)
19665 (when (eq org-catch-invisible-edits 'error)
19666 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19667 (if (and org-custom-properties-overlays
19668 (y-or-n-p "Display invisible properties in this buffer? "))
19669 (org-toggle-custom-properties-visibility)
19670 ;; Make the area visible
19671 (save-excursion
19672 (when invisible-before-point
19673 (goto-char
19674 (previous-single-char-property-change (point) 'invisible)))
19675 ;; Remove whatever overlay is currently making yet-to-be
19676 ;; edited text invisible. Also remove nested invisibility
19677 ;; related overlays.
19678 (delete-overlay (or invisible-at-point invisible-before-point))
19679 (let ((origin (if invisible-at-point (point) (1- (point)))))
19680 (while (pcase (get-char-property-and-overlay origin 'invisible)
19681 (`(,_ . ,(and (pred overlayp) o))
19682 (delete-overlay o)
19683 t)))))
19684 (cond
19685 ((eq org-catch-invisible-edits 'show)
19686 ;; That's it, we do the edit after showing
19687 (message
19688 "Unfolding invisible region around point before editing")
19689 (sit-for 1))
19690 ((and (eq org-catch-invisible-edits 'smart)
19691 border-and-ok-direction)
19692 (message "Unfolding invisible region around point before editing"))
19694 ;; Don't do the edit, make the user repeat it in full visibility
19695 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19697 (defun org-fix-tags-on-the-fly ()
19698 "Align tags in headline at point.
19699 Unlike to `org-set-tags', it ignores region and sorting."
19700 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19701 (org-at-heading-p))
19702 (let ((org-ignore-region t)
19703 (org-tags-sort-function nil))
19704 (org-set-tags nil t))))
19706 (defun org-delete-backward-char (N)
19707 "Like `delete-backward-char', insert whitespace at field end in tables.
19708 When deleting backwards, in tables this function will insert whitespace in
19709 front of the next \"|\" separator, to keep the table aligned. The table will
19710 still be marked for re-alignment if the field did fill the entire column,
19711 because, in this case the deletion might narrow the column."
19712 (interactive "p")
19713 (save-match-data
19714 (org-check-before-invisible-edit 'delete-backward)
19715 (if (and (org-at-table-p)
19716 (eq N 1)
19717 (not (org-region-active-p))
19718 (string-match "|" (buffer-substring (point-at-bol) (point)))
19719 (looking-at ".*?|"))
19720 (let ((pos (point))
19721 (noalign (looking-at "[^|\n\r]* |"))
19722 (c org-table-may-need-update))
19723 (backward-delete-char N)
19724 (unless overwrite-mode
19725 (skip-chars-forward "^|")
19726 (insert " ")
19727 (goto-char (1- pos)))
19728 ;; noalign: if there were two spaces at the end, this field
19729 ;; does not determine the width of the column.
19730 (when noalign (setq org-table-may-need-update c)))
19731 (backward-delete-char N)
19732 (org-fix-tags-on-the-fly))))
19734 (defun org-delete-char (N)
19735 "Like `delete-char', but insert whitespace at field end in tables.
19736 When deleting characters, in tables this function will insert whitespace in
19737 front of the next \"|\" separator, to keep the table aligned. The table will
19738 still be marked for re-alignment if the field did fill the entire column,
19739 because, in this case the deletion might narrow the column."
19740 (interactive "p")
19741 (save-match-data
19742 (org-check-before-invisible-edit 'delete)
19743 (if (and (org-at-table-p)
19744 (not (bolp))
19745 (not (= (char-after) ?|))
19746 (eq N 1))
19747 (if (looking-at ".*?|")
19748 (let ((pos (point))
19749 (noalign (looking-at "[^|\n\r]* |"))
19750 (c org-table-may-need-update))
19751 (replace-match
19752 (concat (substring (match-string 0) 1 -1) " |") nil t)
19753 (goto-char pos)
19754 ;; noalign: if there were two spaces at the end, this field
19755 ;; does not determine the width of the column.
19756 (when noalign (setq org-table-may-need-update c)))
19757 (delete-char N))
19758 (delete-char N)
19759 (org-fix-tags-on-the-fly))))
19761 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19762 (put 'org-self-insert-command 'delete-selection
19763 (lambda ()
19764 (not (run-hook-with-args-until-success
19765 'self-insert-uses-region-functions))))
19766 (put 'orgtbl-self-insert-command 'delete-selection
19767 (lambda ()
19768 (not (run-hook-with-args-until-success
19769 'self-insert-uses-region-functions))))
19770 (put 'org-delete-char 'delete-selection 'supersede)
19771 (put 'org-delete-backward-char 'delete-selection 'supersede)
19772 (put 'org-yank 'delete-selection 'yank)
19774 ;; Make `flyspell-mode' delay after some commands
19775 (put 'org-self-insert-command 'flyspell-delayed t)
19776 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19777 (put 'org-delete-char 'flyspell-delayed t)
19778 (put 'org-delete-backward-char 'flyspell-delayed t)
19780 ;; Make pabbrev-mode expand after Org mode commands
19781 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19782 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19784 (defun org-transpose-words ()
19785 "Transpose words for Org.
19786 This uses the `org-mode-transpose-word-syntax-table' syntax
19787 table, which interprets characters in `org-emphasis-alist' as
19788 word constituents."
19789 (interactive)
19790 (with-syntax-table org-mode-transpose-word-syntax-table
19791 (call-interactively 'transpose-words)))
19792 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19794 (defvar org-ctrl-c-ctrl-c-hook nil
19795 "Hook for functions attaching themselves to `C-c C-c'.
19797 This can be used to add additional functionality to the C-c C-c
19798 key which executes context-dependent commands. This hook is run
19799 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19800 run after the last test.
19802 Each function will be called with no arguments. The function
19803 must check if the context is appropriate for it to act. If yes,
19804 it should do its thing and then return a non-nil value. If the
19805 context is wrong, just do nothing and return nil.")
19807 (defvar org-ctrl-c-ctrl-c-final-hook nil
19808 "Hook for functions attaching themselves to `C-c C-c'.
19810 This can be used to add additional functionality to the C-c C-c
19811 key which executes context-dependent commands. This hook is run
19812 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19813 before the first test.
19815 Each function will be called with no arguments. The function
19816 must check if the context is appropriate for it to act. If yes,
19817 it should do its thing and then return a non-nil value. If the
19818 context is wrong, just do nothing and return nil.")
19820 (defvar org-tab-first-hook nil
19821 "Hook for functions to attach themselves to TAB.
19822 See `org-ctrl-c-ctrl-c-hook' for more information.
19823 This hook runs as the first action when TAB is pressed, even before
19824 `org-cycle' messes around with the `outline-regexp' to cater for
19825 inline tasks and plain list item folding.
19826 If any function in this hook returns t, any other actions that
19827 would have been caused by TAB (such as table field motion or visibility
19828 cycling) will not occur.")
19830 (defvar org-tab-after-check-for-table-hook nil
19831 "Hook for functions to attach themselves to TAB.
19832 See `org-ctrl-c-ctrl-c-hook' for more information.
19833 This hook runs after it has been established that the cursor is not in a
19834 table, but before checking if the cursor is in a headline or if global cycling
19835 should be done.
19836 If any function in this hook returns t, not other actions like visibility
19837 cycling will be done.")
19839 (defvar org-tab-after-check-for-cycling-hook nil
19840 "Hook for functions to attach themselves to TAB.
19841 See `org-ctrl-c-ctrl-c-hook' for more information.
19842 This hook runs after it has been established that not table field motion and
19843 not visibility should be done because of current context. This is probably
19844 the place where a package like yasnippets can hook in.")
19846 (defvar org-tab-before-tab-emulation-hook nil
19847 "Hook for functions to attach themselves to TAB.
19848 See `org-ctrl-c-ctrl-c-hook' for more information.
19849 This hook runs after every other options for TAB have been exhausted, but
19850 before indentation and \t insertion takes place.")
19852 (defvar org-metaleft-hook nil
19853 "Hook for functions attaching themselves to `M-left'.
19854 See `org-ctrl-c-ctrl-c-hook' for more information.")
19855 (defvar org-metaright-hook nil
19856 "Hook for functions attaching themselves to `M-right'.
19857 See `org-ctrl-c-ctrl-c-hook' for more information.")
19858 (defvar org-metaup-hook nil
19859 "Hook for functions attaching themselves to `M-up'.
19860 See `org-ctrl-c-ctrl-c-hook' for more information.")
19861 (defvar org-metadown-hook nil
19862 "Hook for functions attaching themselves to `M-down'.
19863 See `org-ctrl-c-ctrl-c-hook' for more information.")
19864 (defvar org-shiftmetaleft-hook nil
19865 "Hook for functions attaching themselves to `M-S-left'.
19866 See `org-ctrl-c-ctrl-c-hook' for more information.")
19867 (defvar org-shiftmetaright-hook nil
19868 "Hook for functions attaching themselves to `M-S-right'.
19869 See `org-ctrl-c-ctrl-c-hook' for more information.")
19870 (defvar org-shiftmetaup-hook nil
19871 "Hook for functions attaching themselves to `M-S-up'.
19872 See `org-ctrl-c-ctrl-c-hook' for more information.")
19873 (defvar org-shiftmetadown-hook nil
19874 "Hook for functions attaching themselves to `M-S-down'.
19875 See `org-ctrl-c-ctrl-c-hook' for more information.")
19876 (defvar org-metareturn-hook nil
19877 "Hook for functions attaching themselves to `M-RET'.
19878 See `org-ctrl-c-ctrl-c-hook' for more information.")
19879 (defvar org-shiftup-hook nil
19880 "Hook for functions attaching themselves to `S-up'.
19881 See `org-ctrl-c-ctrl-c-hook' for more information.")
19882 (defvar org-shiftup-final-hook nil
19883 "Hook for functions attaching themselves to `S-up'.
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.")
19886 (defvar org-shiftdown-hook nil
19887 "Hook for functions attaching themselves to `S-down'.
19888 See `org-ctrl-c-ctrl-c-hook' for more information.")
19889 (defvar org-shiftdown-final-hook nil
19890 "Hook for functions attaching themselves to `S-down'.
19891 This one runs after all other options except shift-select have been excluded.
19892 See `org-ctrl-c-ctrl-c-hook' for more information.")
19893 (defvar org-shiftleft-hook nil
19894 "Hook for functions attaching themselves to `S-left'.
19895 See `org-ctrl-c-ctrl-c-hook' for more information.")
19896 (defvar org-shiftleft-final-hook nil
19897 "Hook for functions attaching themselves to `S-left'.
19898 This one runs after all other options except shift-select have been excluded.
19899 See `org-ctrl-c-ctrl-c-hook' for more information.")
19900 (defvar org-shiftright-hook nil
19901 "Hook for functions attaching themselves to `S-right'.
19902 See `org-ctrl-c-ctrl-c-hook' for more information.")
19903 (defvar org-shiftright-final-hook nil
19904 "Hook for functions attaching themselves to `S-right'.
19905 This one runs after all other options except shift-select have been excluded.
19906 See `org-ctrl-c-ctrl-c-hook' for more information.")
19908 (defun org-modifier-cursor-error ()
19909 "Throw an error, a modified cursor command was applied in wrong context."
19910 (user-error "This command is active in special context like tables, headlines or items"))
19912 (defun org-shiftselect-error ()
19913 "Throw an error because Shift-Cursor command was applied in wrong context."
19914 (if (and (boundp 'shift-select-mode) shift-select-mode)
19915 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19916 (user-error "This command works only in special context like headlines or timestamps")))
19918 (defun org-call-for-shift-select (cmd)
19919 (let ((this-command-keys-shift-translated t))
19920 (call-interactively cmd)))
19922 (defun org-shifttab (&optional arg)
19923 "Global visibility cycling or move to previous table field.
19924 Call `org-table-previous-field' within a table.
19925 When ARG is nil, cycle globally through visibility states.
19926 When ARG is a numeric prefix, show contents of this level."
19927 (interactive "P")
19928 (cond
19929 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19930 ((integerp arg)
19931 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19932 (message "Content view to level: %d" arg)
19933 (org-content (prefix-numeric-value arg2))
19934 (org-cycle-show-empty-lines t)
19935 (setq org-cycle-global-status 'overview)))
19936 (t (call-interactively 'org-global-cycle))))
19938 (defun org-shiftmetaleft ()
19939 "Promote subtree or delete table column.
19940 Calls `org-promote-subtree', `org-outdent-item-tree', or
19941 `org-table-delete-column', depending on context. See the
19942 individual commands for more information."
19943 (interactive)
19944 (cond
19945 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19946 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19947 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19948 ((if (not (org-region-active-p)) (org-at-item-p)
19949 (save-excursion (goto-char (region-beginning))
19950 (org-at-item-p)))
19951 (call-interactively 'org-outdent-item-tree))
19952 (t (org-modifier-cursor-error))))
19954 (defun org-shiftmetaright ()
19955 "Demote subtree or insert table column.
19956 Calls `org-demote-subtree', `org-indent-item-tree', or
19957 `org-table-insert-column', depending on context. See the
19958 individual commands for more information."
19959 (interactive)
19960 (cond
19961 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19962 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19963 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19964 ((if (not (org-region-active-p)) (org-at-item-p)
19965 (save-excursion (goto-char (region-beginning))
19966 (org-at-item-p)))
19967 (call-interactively 'org-indent-item-tree))
19968 (t (org-modifier-cursor-error))))
19970 (defun org-shiftmetaup (&optional _arg)
19971 "Drag the line at point up.
19972 In a table, kill the current row.
19973 On a clock timestamp, update the value of the timestamp like `S-<up>'
19974 but also adjust the previous clocked item in the clock history.
19975 Everywhere else, drag the line at point up."
19976 (interactive "P")
19977 (cond
19978 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19979 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19980 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19981 (call-interactively 'org-timestamp-up)))
19982 (t (call-interactively 'org-drag-line-backward))))
19984 (defun org-shiftmetadown (&optional _arg)
19985 "Drag the line at point down.
19986 In a table, insert an empty row at the current line.
19987 On a clock timestamp, update the value of the timestamp like `S-<down>'
19988 but also adjust the previous clocked item in the clock history.
19989 Everywhere else, drag the line at point down."
19990 (interactive "P")
19991 (cond
19992 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19993 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19994 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19995 (call-interactively 'org-timestamp-down)))
19996 (t (call-interactively 'org-drag-line-forward))))
19998 (defsubst org-hidden-tree-error ()
19999 (user-error
20000 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20002 (defun org-metaleft (&optional _arg)
20003 "Promote heading, list item at point or move table column left.
20005 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20006 depending on context. With no specific context, calls the Emacs
20007 default `backward-word'. See the individual commands for more
20008 information.
20010 This function runs the hook `org-metaleft-hook' as a first step,
20011 and returns at first non-nil value."
20012 (interactive "P")
20013 (cond
20014 ((run-hook-with-args-until-success 'org-metaleft-hook))
20015 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20016 ((org-with-limited-levels
20017 (or (org-at-heading-p)
20018 (and (org-region-active-p)
20019 (save-excursion
20020 (goto-char (region-beginning))
20021 (org-at-heading-p)))))
20022 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20023 (call-interactively 'org-do-promote))
20024 ;; At an inline task.
20025 ((org-at-heading-p)
20026 (call-interactively 'org-inlinetask-promote))
20027 ((or (org-at-item-p)
20028 (and (org-region-active-p)
20029 (save-excursion
20030 (goto-char (region-beginning))
20031 (org-at-item-p))))
20032 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20033 (call-interactively 'org-outdent-item))
20034 (t (call-interactively 'backward-word))))
20036 (defun org-metaright (&optional _arg)
20037 "Demote heading, list item at point or move table column right.
20039 In front of a drawer or a block keyword, indent it correctly.
20041 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20042 `org-indent-drawer' or `org-indent-block' depending on context.
20043 With no specific context, calls the Emacs default `forward-word'.
20044 See the individual commands for more information.
20046 This function runs the hook `org-metaright-hook' as a first step,
20047 and returns at first non-nil value."
20048 (interactive "P")
20049 (cond
20050 ((run-hook-with-args-until-success 'org-metaright-hook))
20051 ((org-at-table-p) (call-interactively 'org-table-move-column))
20052 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20053 ((org-at-block-p) (call-interactively 'org-indent-block))
20054 ((org-with-limited-levels
20055 (or (org-at-heading-p)
20056 (and (org-region-active-p)
20057 (save-excursion
20058 (goto-char (region-beginning))
20059 (org-at-heading-p)))))
20060 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20061 (call-interactively 'org-do-demote))
20062 ;; At an inline task.
20063 ((org-at-heading-p)
20064 (call-interactively 'org-inlinetask-demote))
20065 ((or (org-at-item-p)
20066 (and (org-region-active-p)
20067 (save-excursion
20068 (goto-char (region-beginning))
20069 (org-at-item-p))))
20070 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20071 (call-interactively 'org-indent-item))
20072 (t (call-interactively 'forward-word))))
20074 (defun org-check-for-hidden (what)
20075 "Check if there are hidden headlines/items in the current visual line.
20076 WHAT can be either `headlines' or `items'. If the current line is
20077 an outline or item heading and it has a folded subtree below it,
20078 this function returns t, nil otherwise."
20079 (let ((re (cond
20080 ((eq what 'headlines) org-outline-regexp-bol)
20081 ((eq what 'items) (org-item-beginning-re))
20082 (t (error "This should not happen"))))
20083 beg end)
20084 (save-excursion
20085 (catch 'exit
20086 (unless (org-region-active-p)
20087 (setq beg (point-at-bol))
20088 (beginning-of-line 2)
20089 (while (and (not (eobp)) ;; this is like `next-line'
20090 (get-char-property (1- (point)) 'invisible))
20091 (beginning-of-line 2))
20092 (setq end (point))
20093 (goto-char beg)
20094 (goto-char (point-at-eol))
20095 (setq end (max end (point)))
20096 (while (re-search-forward re end t)
20097 (when (get-char-property (match-beginning 0) 'invisible)
20098 (throw 'exit t))))
20099 nil))))
20101 (defun org-metaup (&optional _arg)
20102 "Move subtree up or move table row up.
20103 Calls `org-move-subtree-up' or `org-table-move-row' or
20104 `org-move-item-up', depending on context. See the individual commands
20105 for more information."
20106 (interactive "P")
20107 (cond
20108 ((run-hook-with-args-until-success 'org-metaup-hook))
20109 ((org-region-active-p)
20110 (let* ((a (min (region-beginning) (region-end)))
20111 (b (1- (max (region-beginning) (region-end))))
20112 (c (save-excursion (goto-char a)
20113 (move-beginning-of-line 0)))
20114 (d (save-excursion (goto-char a)
20115 (move-end-of-line 0) (point))))
20116 (transpose-regions a b c d)
20117 (goto-char c)))
20118 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20119 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20120 ((org-at-item-p) (call-interactively 'org-move-item-up))
20121 (t (org-drag-element-backward))))
20123 (defun org-metadown (&optional _arg)
20124 "Move subtree down or move table row down.
20125 Calls `org-move-subtree-down' or `org-table-move-row' or
20126 `org-move-item-down', depending on context. See the individual
20127 commands for more information."
20128 (interactive "P")
20129 (cond
20130 ((run-hook-with-args-until-success 'org-metadown-hook))
20131 ((org-region-active-p)
20132 (let* ((a (min (region-beginning) (region-end)))
20133 (b (max (region-beginning) (region-end)))
20134 (c (save-excursion (goto-char b)
20135 (move-beginning-of-line 1)))
20136 (d (save-excursion (goto-char b)
20137 (move-end-of-line 1) (1+ (point)))))
20138 (transpose-regions a b c d)
20139 (goto-char d)))
20140 ((org-at-table-p) (call-interactively 'org-table-move-row))
20141 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20142 ((org-at-item-p) (call-interactively 'org-move-item-down))
20143 (t (org-drag-element-forward))))
20145 (defun org-shiftup (&optional arg)
20146 "Increase item in timestamp or increase priority of current headline.
20147 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20148 depending on context. See the individual commands for more information."
20149 (interactive "P")
20150 (cond
20151 ((run-hook-with-args-until-success 'org-shiftup-hook))
20152 ((and org-support-shift-select (org-region-active-p))
20153 (org-call-for-shift-select 'previous-line))
20154 ((org-at-timestamp-p 'lax)
20155 (call-interactively (if org-edit-timestamp-down-means-later
20156 'org-timestamp-down 'org-timestamp-up)))
20157 ((and (not (eq org-support-shift-select 'always))
20158 org-enable-priority-commands
20159 (org-at-heading-p))
20160 (call-interactively 'org-priority-up))
20161 ((and (not org-support-shift-select) (org-at-item-p))
20162 (call-interactively 'org-previous-item))
20163 ((org-clocktable-try-shift 'up arg))
20164 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20165 (org-support-shift-select
20166 (org-call-for-shift-select 'previous-line))
20167 (t (org-shiftselect-error))))
20169 (defun org-shiftdown (&optional arg)
20170 "Decrease item in timestamp or decrease priority of current headline.
20171 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20172 depending on context. See the individual commands for more information."
20173 (interactive "P")
20174 (cond
20175 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20176 ((and org-support-shift-select (org-region-active-p))
20177 (org-call-for-shift-select 'next-line))
20178 ((org-at-timestamp-p 'lax)
20179 (call-interactively (if org-edit-timestamp-down-means-later
20180 'org-timestamp-up 'org-timestamp-down)))
20181 ((and (not (eq org-support-shift-select 'always))
20182 org-enable-priority-commands
20183 (org-at-heading-p))
20184 (call-interactively 'org-priority-down))
20185 ((and (not org-support-shift-select) (org-at-item-p))
20186 (call-interactively 'org-next-item))
20187 ((org-clocktable-try-shift 'down arg))
20188 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20189 (org-support-shift-select
20190 (org-call-for-shift-select 'next-line))
20191 (t (org-shiftselect-error))))
20193 (defun org-shiftright (&optional arg)
20194 "Cycle the thing at point or in the current line, depending on context.
20195 Depending on context, this does one of the following:
20197 - switch a timestamp at point one day into the future
20198 - on a headline, switch to the next TODO keyword.
20199 - on an item, switch entire list to the next bullet type
20200 - on a property line, switch to the next allowed value
20201 - on a clocktable definition line, move time block into the future"
20202 (interactive "P")
20203 (cond
20204 ((run-hook-with-args-until-success 'org-shiftright-hook))
20205 ((and org-support-shift-select (org-region-active-p))
20206 (org-call-for-shift-select 'forward-char))
20207 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20208 ((and (not (eq org-support-shift-select 'always))
20209 (org-at-heading-p))
20210 (let ((org-inhibit-logging
20211 (not org-treat-S-cursor-todo-selection-as-state-change))
20212 (org-inhibit-blocking
20213 (not org-treat-S-cursor-todo-selection-as-state-change)))
20214 (org-call-with-arg 'org-todo 'right)))
20215 ((or (and org-support-shift-select
20216 (not (eq org-support-shift-select 'always))
20217 (org-at-item-bullet-p))
20218 (and (not org-support-shift-select) (org-at-item-p)))
20219 (org-call-with-arg 'org-cycle-list-bullet nil))
20220 ((and (not (eq org-support-shift-select 'always))
20221 (org-at-property-p))
20222 (call-interactively 'org-property-next-allowed-value))
20223 ((org-clocktable-try-shift 'right arg))
20224 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20225 (org-support-shift-select
20226 (org-call-for-shift-select 'forward-char))
20227 (t (org-shiftselect-error))))
20229 (defun org-shiftleft (&optional arg)
20230 "Cycle the thing at point or in the current line, depending on context.
20231 Depending on context, this does one of the following:
20233 - switch a timestamp at point one day into the past
20234 - on a headline, switch to the previous TODO keyword.
20235 - on an item, switch entire list to the previous bullet type
20236 - on a property line, switch to the previous allowed value
20237 - on a clocktable definition line, move time block into the past"
20238 (interactive "P")
20239 (cond
20240 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20241 ((and org-support-shift-select (org-region-active-p))
20242 (org-call-for-shift-select 'backward-char))
20243 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20244 ((and (not (eq org-support-shift-select 'always))
20245 (org-at-heading-p))
20246 (let ((org-inhibit-logging
20247 (not org-treat-S-cursor-todo-selection-as-state-change))
20248 (org-inhibit-blocking
20249 (not org-treat-S-cursor-todo-selection-as-state-change)))
20250 (org-call-with-arg 'org-todo 'left)))
20251 ((or (and org-support-shift-select
20252 (not (eq org-support-shift-select 'always))
20253 (org-at-item-bullet-p))
20254 (and (not org-support-shift-select) (org-at-item-p)))
20255 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20256 ((and (not (eq org-support-shift-select 'always))
20257 (org-at-property-p))
20258 (call-interactively 'org-property-previous-allowed-value))
20259 ((org-clocktable-try-shift 'left arg))
20260 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20261 (org-support-shift-select
20262 (org-call-for-shift-select 'backward-char))
20263 (t (org-shiftselect-error))))
20265 (defun org-shiftcontrolright ()
20266 "Switch to next TODO set."
20267 (interactive)
20268 (cond
20269 ((and org-support-shift-select (org-region-active-p))
20270 (org-call-for-shift-select 'forward-word))
20271 ((and (not (eq org-support-shift-select 'always))
20272 (org-at-heading-p))
20273 (org-call-with-arg 'org-todo 'nextset))
20274 (org-support-shift-select
20275 (org-call-for-shift-select 'forward-word))
20276 (t (org-shiftselect-error))))
20278 (defun org-shiftcontrolleft ()
20279 "Switch to previous TODO set."
20280 (interactive)
20281 (cond
20282 ((and org-support-shift-select (org-region-active-p))
20283 (org-call-for-shift-select 'backward-word))
20284 ((and (not (eq org-support-shift-select 'always))
20285 (org-at-heading-p))
20286 (org-call-with-arg 'org-todo 'previousset))
20287 (org-support-shift-select
20288 (org-call-for-shift-select 'backward-word))
20289 (t (org-shiftselect-error))))
20291 (defun org-shiftcontrolup (&optional n)
20292 "Change timestamps synchronously up in CLOCK log lines.
20293 Optional argument N tells to change by that many units."
20294 (interactive "P")
20295 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20296 (let (org-support-shift-select)
20297 (org-clock-timestamps-up n))
20298 (user-error "Not at a clock log")))
20300 (defun org-shiftcontroldown (&optional n)
20301 "Change timestamps synchronously down in CLOCK log lines.
20302 Optional argument N tells to change by that many units."
20303 (interactive "P")
20304 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20305 (let (org-support-shift-select)
20306 (org-clock-timestamps-down n))
20307 (user-error "Not at a clock log")))
20309 (defun org-increase-number-at-point (&optional inc)
20310 "Increment the number at point.
20311 With an optional prefix numeric argument INC, increment using
20312 this numeric value."
20313 (interactive "p")
20314 (if (not (number-at-point))
20315 (user-error "Not on a number")
20316 (unless inc (setq inc 1))
20317 (let ((pos (point))
20318 (beg (skip-chars-backward "-+^/*0-9eE."))
20319 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20320 (setq nap (buffer-substring-no-properties
20321 (+ pos beg) (+ pos beg end)))
20322 (delete-region (+ pos beg) (+ pos beg end))
20323 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20324 (when (org-at-table-p)
20325 (org-table-align)
20326 (org-table-end-of-field 1))))
20328 (defun org-decrease-number-at-point (&optional inc)
20329 "Decrement the number at point.
20330 With an optional prefix numeric argument INC, decrement using
20331 this numeric value."
20332 (interactive "p")
20333 (org-increase-number-at-point (- (or inc 1))))
20335 (defun org-ctrl-c-ret ()
20336 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20337 (interactive)
20338 (cond
20339 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20340 (t (call-interactively 'org-insert-heading))))
20342 (defun org-find-visible ()
20343 (let ((s (point)))
20344 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20345 (get-char-property s 'invisible)))
20347 (defun org-find-invisible ()
20348 (let ((s (point)))
20349 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20350 (not (get-char-property s 'invisible))))
20353 (defun org-copy-visible (beg end)
20354 "Copy the visible parts of the region."
20355 (interactive "r")
20356 (let ((result ""))
20357 (while (/= beg end)
20358 (when (get-char-property beg 'invisible)
20359 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20360 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20361 (setq result (concat result (buffer-substring beg next)))
20362 (setq beg next)))
20363 (kill-new result)))
20365 (defun org-copy-special ()
20366 "Copy region in table or copy current subtree.
20367 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20368 context. See the individual commands for more information."
20369 (interactive)
20370 (call-interactively
20371 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20373 (defun org-cut-special ()
20374 "Cut region in table or cut current subtree.
20375 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20376 context. See the individual commands for more information."
20377 (interactive)
20378 (call-interactively
20379 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20381 (defun org-paste-special (arg)
20382 "Paste rectangular region into table, or past subtree relative to level.
20383 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20384 See the individual commands for more information."
20385 (interactive "P")
20386 (if (org-at-table-p)
20387 (org-table-paste-rectangle)
20388 (org-paste-subtree arg)))
20390 (defun org-edit-special (&optional arg)
20391 "Call a special editor for the element at point.
20392 When at a table, call the formula editor with `org-table-edit-formulas'.
20393 When in a source code block, call `org-edit-src-code'.
20394 When in a fixed-width region, call `org-edit-fixed-width-region'.
20395 When in an export block, call `org-edit-export-block'.
20396 When in a LaTeX environment, call `org-edit-latex-environment'.
20397 When at an #+INCLUDE keyword, visit the included file.
20398 When at a footnote reference, call `org-edit-footnote-reference'
20399 On a link, call `ffap' to visit the link at point.
20400 Otherwise, return a user error."
20401 (interactive "P")
20402 (let ((element (org-element-at-point)))
20403 (barf-if-buffer-read-only)
20404 (pcase (org-element-type element)
20405 (`src-block
20406 (if (not arg) (org-edit-src-code)
20407 (let* ((info (org-babel-get-src-block-info))
20408 (lang (nth 0 info))
20409 (params (nth 2 info))
20410 (session (cdr (assq :session params))))
20411 (if (not session) (org-edit-src-code)
20412 ;; At a src-block with a session and function called with
20413 ;; an ARG: switch to the buffer related to the inferior
20414 ;; process.
20415 (switch-to-buffer
20416 (funcall (intern (concat "org-babel-prep-session:" lang))
20417 session params))))))
20418 (`keyword
20419 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20420 (org-open-link-from-string
20421 (format "[[%s]]"
20422 (expand-file-name
20423 (let ((value (org-element-property :value element)))
20424 (cond ((org-file-url-p value)
20425 (user-error "The file is specified as a URL, cannot be edited"))
20426 ((not (org-string-nw-p value))
20427 (user-error "No file to edit"))
20428 ((string-match "\\`\"\\(.*?\\)\"" value)
20429 (match-string 1 value))
20430 ((string-match "\\`[^ \t\"]\\S-*" value)
20431 (match-string 0 value))
20432 (t (user-error "No valid file specified")))))))
20433 (user-error "No special environment to edit here")))
20434 (`table
20435 (if (eq (org-element-property :type element) 'table.el)
20436 (org-edit-table.el)
20437 (call-interactively 'org-table-edit-formulas)))
20438 ;; Only Org tables contain `table-row' type elements.
20439 (`table-row (call-interactively 'org-table-edit-formulas))
20440 (`example-block (org-edit-src-code))
20441 (`export-block (org-edit-export-block))
20442 (`fixed-width (org-edit-fixed-width-region))
20443 (`latex-environment (org-edit-latex-environment))
20445 ;; No notable element at point. Though, we may be at a link or
20446 ;; a footnote reference, which are objects. Thus, scan deeper.
20447 (let ((context (org-element-context element)))
20448 (pcase (org-element-type context)
20449 (`footnote-reference (org-edit-footnote-reference))
20450 (`inline-src-block (org-edit-inline-src-code))
20451 (`link (call-interactively #'ffap))
20452 (_ (user-error "No special environment to edit here"))))))))
20454 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20455 (defun org-ctrl-c-ctrl-c (&optional arg)
20456 "Set tags in headline, or update according to changed information at point.
20458 This command does many different things, depending on context:
20460 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20461 this is what we do.
20463 - If the cursor is on a statistics cookie, update it.
20465 - If the cursor is in a headline, prompt for tags and insert them
20466 into the current line, aligned to `org-tags-column'. When called
20467 with prefix arg, realign all tags in the current buffer.
20469 - If the cursor is in one of the special #+KEYWORD lines, this
20470 triggers scanning the buffer for these lines and updating the
20471 information.
20473 - If the cursor is inside a table, realign the table. This command
20474 works even if the automatic table editor has been turned off.
20476 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20477 the entire table.
20479 - If the cursor is at a footnote reference or definition, jump to
20480 the corresponding definition or references, respectively.
20482 - If the cursor is a the beginning of a dynamic block, update it.
20484 - If the current buffer is a capture buffer, close note and file it.
20486 - If the cursor is on a <<<target>>>, update radio targets and
20487 corresponding links in this buffer.
20489 - If the cursor is on a numbered item in a plain list, renumber the
20490 ordered list.
20492 - If the cursor is on a checkbox, toggle it.
20494 - If the cursor is on a code block, evaluate it. The variable
20495 `org-confirm-babel-evaluate' can be used to control prompting
20496 before code block evaluation, by default every code block
20497 evaluation requires confirmation. Code block evaluation can be
20498 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20499 (interactive "P")
20500 (cond
20501 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20502 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20503 (org-remove-occur-highlights)
20504 (message "Temporary highlights/overlays removed from current buffer"))
20505 ((and (local-variable-p 'org-finish-function)
20506 (fboundp org-finish-function))
20507 (funcall org-finish-function))
20508 ((org-babel-hash-at-point))
20509 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20511 (let* ((context
20512 (org-element-lineage
20513 (org-element-context)
20514 ;; Limit to supported contexts.
20515 '(babel-call clock dynamic-block footnote-definition
20516 footnote-reference inline-babel-call inline-src-block
20517 inlinetask item keyword node-property paragraph
20518 plain-list planning property-drawer radio-target
20519 src-block statistics-cookie table table-cell table-row
20520 timestamp)
20522 (type (org-element-type context)))
20523 ;; For convenience: at the first line of a paragraph on the same
20524 ;; line as an item, apply function on that item instead.
20525 (when (eq type 'paragraph)
20526 (let ((parent (org-element-property :parent context)))
20527 (when (and (eq (org-element-type parent) 'item)
20528 (= (line-beginning-position)
20529 (org-element-property :begin parent)))
20530 (setq context parent)
20531 (setq type 'item))))
20532 ;; Act according to type of element or object at point.
20534 ;; Do nothing on a blank line, except if it is contained in
20535 ;; a src block. Hence, we first check if point is in such
20536 ;; a block and then if it is at a blank line.
20537 (pcase type
20538 ((or `inline-src-block `src-block)
20539 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20540 (org-babel-eval-wipe-error-buffer)
20541 (org-babel-execute-src-block
20542 current-prefix-arg (org-babel-get-src-block-info nil context))))
20543 ((guard (org-match-line "[ \t]*$"))
20544 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20545 (user-error
20546 (substitute-command-keys
20547 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20548 ((or `babel-call `inline-babel-call)
20549 (let ((info (org-babel-lob-get-info context)))
20550 (when info (org-babel-execute-src-block nil info))))
20551 (`clock (org-clock-update-time-maybe))
20552 (`dynamic-block
20553 (save-excursion
20554 (goto-char (org-element-property :post-affiliated context))
20555 (org-update-dblock)))
20556 (`footnote-definition
20557 (goto-char (org-element-property :post-affiliated context))
20558 (call-interactively 'org-footnote-action))
20559 (`footnote-reference (call-interactively #'org-footnote-action))
20560 ((or `headline `inlinetask)
20561 (save-excursion (goto-char (org-element-property :begin context))
20562 (call-interactively #'org-set-tags)))
20563 (`item
20564 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20565 ;; unconditionally, whereas `C-u' will toggle its presence.
20566 ;; Without a universal argument, if the item has a checkbox,
20567 ;; toggle it. Otherwise repair the list.
20568 (let* ((box (org-element-property :checkbox context))
20569 (struct (org-element-property :structure context))
20570 (old-struct (copy-tree struct))
20571 (parents (org-list-parents-alist struct))
20572 (prevs (org-list-prevs-alist struct))
20573 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20574 (org-list-set-checkbox
20575 (org-element-property :begin context) struct
20576 (cond ((equal arg '(16)) "[-]")
20577 ((and (not box) (equal arg '(4))) "[ ]")
20578 ((or (not box) (equal arg '(4))) nil)
20579 ((eq box 'on) "[ ]")
20580 (t "[X]")))
20581 ;; Mimic `org-list-write-struct' but with grabbing a return
20582 ;; value from `org-list-struct-fix-box'.
20583 (org-list-struct-fix-ind struct parents 2)
20584 (org-list-struct-fix-item-end struct)
20585 (org-list-struct-fix-bul struct prevs)
20586 (org-list-struct-fix-ind struct parents)
20587 (let ((block-item
20588 (org-list-struct-fix-box struct parents prevs orderedp)))
20589 (if (and box (equal struct old-struct))
20590 (if (equal arg '(16))
20591 (message "Checkboxes already reset")
20592 (user-error "Cannot toggle this checkbox: %s"
20593 (if (eq box 'on)
20594 "all subitems checked"
20595 "unchecked subitems")))
20596 (org-list-struct-apply-struct struct old-struct)
20597 (org-update-checkbox-count-maybe))
20598 (when block-item
20599 (message "Checkboxes were removed due to empty box at line %d"
20600 (org-current-line block-item))))))
20601 (`keyword
20602 (let ((org-inhibit-startup-visibility-stuff t)
20603 (org-startup-align-all-tables nil))
20604 (when (boundp 'org-table-coordinate-overlays)
20605 (mapc #'delete-overlay org-table-coordinate-overlays)
20606 (setq org-table-coordinate-overlays nil))
20607 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20608 (message "Local setup has been refreshed"))
20609 (`plain-list
20610 ;; At a plain list, with a double C-u argument, set
20611 ;; checkboxes of each item to "[-]", whereas a single one
20612 ;; will toggle their presence according to the state of the
20613 ;; first item in the list. Without an argument, repair the
20614 ;; list.
20615 (let* ((begin (org-element-property :contents-begin context))
20616 (beginm (move-marker (make-marker) begin))
20617 (struct (org-element-property :structure context))
20618 (old-struct (copy-tree struct))
20619 (first-box (save-excursion
20620 (goto-char begin)
20621 (looking-at org-list-full-item-re)
20622 (match-string-no-properties 3)))
20623 (new-box (cond ((equal arg '(16)) "[-]")
20624 ((equal arg '(4)) (unless first-box "[ ]"))
20625 ((equal first-box "[X]") "[ ]")
20626 (t "[X]"))))
20627 (cond
20628 (arg
20629 (dolist (pos
20630 (org-list-get-all-items
20631 begin struct (org-list-prevs-alist struct)))
20632 (org-list-set-checkbox pos struct new-box)))
20633 ((and first-box (eq (point) begin))
20634 ;; For convenience, when point is at bol on the first
20635 ;; item of the list and no argument is provided, simply
20636 ;; toggle checkbox of that item, if any.
20637 (org-list-set-checkbox begin struct new-box)))
20638 (org-list-write-struct
20639 struct (org-list-parents-alist struct) old-struct)
20640 (org-update-checkbox-count-maybe)
20641 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20642 ((or `property-drawer `node-property)
20643 (call-interactively #'org-property-action))
20644 (`radio-target
20645 (call-interactively #'org-update-radio-target-regexp))
20646 (`statistics-cookie
20647 (call-interactively #'org-update-statistics-cookies))
20648 ((or `table `table-cell `table-row)
20649 ;; At a table, recalculate every field and align it. Also
20650 ;; send the table if necessary. If the table has
20651 ;; a `table.el' type, just give up. At a table row or cell,
20652 ;; maybe recalculate line but always align table.
20653 (if (eq (org-element-property :type context) 'table.el)
20654 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20655 Use `\\[org-edit-special]' to edit table.el tables"))
20656 (if (or (eq type 'table)
20657 ;; Check if point is at a TBLFM line.
20658 (and (eq type 'table-row)
20659 (= (point) (org-element-property :end context))))
20660 (save-excursion
20661 (if (org-at-TBLFM-p)
20662 (progn (require 'org-table)
20663 (org-table-calc-current-TBLFM))
20664 (goto-char (org-element-property :contents-begin context))
20665 (org-call-with-arg 'org-table-recalculate (or arg t))
20666 (orgtbl-send-table 'maybe)))
20667 (org-table-maybe-eval-formula)
20668 (cond (arg (call-interactively #'org-table-recalculate))
20669 ((org-table-maybe-recalculate-line))
20670 (t (org-table-align))))))
20671 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20672 (org-timestamp-change 0 'day))
20673 ((and `nil (guard (org-at-heading-p)))
20674 ;; When point is on an unsupported object type, we can miss
20675 ;; the fact that it also is at a heading. Handle it here.
20676 (call-interactively #'org-set-tags))
20677 ((guard
20678 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20680 (user-error
20681 (substitute-command-keys
20682 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20684 (defun org-mode-restart ()
20685 (interactive)
20686 (let ((indent-status (bound-and-true-p org-indent-mode)))
20687 (funcall major-mode)
20688 (hack-local-variables)
20689 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20690 (org-indent-mode -1))
20691 (org-reset-file-cache))
20692 (message "%s restarted" major-mode))
20694 (defun org-kill-note-or-show-branches ()
20695 "Abort storing current note, or call `outline-show-branches'."
20696 (interactive)
20697 (if (not org-finish-function)
20698 (progn
20699 (outline-hide-subtree)
20700 (call-interactively 'outline-show-branches))
20701 (let ((org-note-abort t))
20702 (funcall org-finish-function))))
20704 (defun org-delete-indentation (&optional arg)
20705 "Join current line to previous and fix whitespace at join.
20707 If previous line is a headline add to headline title. Otherwise
20708 the function calls `delete-indentation'.
20710 With a non-nil optional argument, join it to the following one."
20711 (interactive "*P")
20712 (if (save-excursion
20713 (beginning-of-line (if arg 1 0))
20714 (let ((case-fold-search nil))
20715 (looking-at org-complex-heading-regexp)))
20716 ;; At headline.
20717 (let ((tags-column (when (match-beginning 5)
20718 (save-excursion (goto-char (match-beginning 5))
20719 (current-column))))
20720 (string (concat " " (progn (when arg (forward-line 1))
20721 (org-trim (delete-and-extract-region
20722 (line-beginning-position)
20723 (line-end-position)))))))
20724 (unless (bobp) (delete-region (point) (1- (point))))
20725 (goto-char (or (match-end 4)
20726 (match-beginning 5)
20727 (match-end 0)))
20728 (skip-chars-backward " \t")
20729 (save-excursion (insert string))
20730 ;; Adjust alignment of tags.
20731 (cond
20732 ((not tags-column)) ;no tags
20733 (org-auto-align-tags (org-set-tags nil t))
20734 (t (org--align-tags-here tags-column)))) ;preserve tags column
20735 (delete-indentation arg)))
20737 (defun org-open-line (n)
20738 "Insert a new row in tables, call `open-line' elsewhere.
20739 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20740 As a special case, when a document starts with a table, allow to
20741 call `open-line' on the very first character."
20742 (interactive "*p")
20743 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20744 (org-table-insert-row)
20745 (open-line n)))
20747 (defun org-return (&optional indent)
20748 "Goto next table row or insert a newline.
20750 Calls `org-table-next-row' or `newline', depending on context.
20752 When optional INDENT argument is non-nil, call
20753 `newline-and-indent' instead of `newline'.
20755 When `org-return-follows-link' is non-nil and point is on
20756 a timestamp or a link, call `org-open-at-point'. However, it
20757 will not happen if point is in a table or on a \"dead\"
20758 object (e.g., within a comment). In these case, you need to use
20759 `org-open-at-point' directly."
20760 (interactive)
20761 (let ((context (if org-return-follows-link (org-element-context)
20762 (org-element-at-point))))
20763 (cond
20764 ;; In a table, call `org-table-next-row'. However, before first
20765 ;; column or after last one, split the table.
20766 ((or (and (eq (org-element-type context) 'table)
20767 (>= (point) (org-element-property :contents-begin context))
20768 (< (point) (org-element-property :contents-end context)))
20769 (org-element-lineage context '(table-row table-cell) t))
20770 (if (or (looking-at-p "[ \t]*$")
20771 (save-excursion (skip-chars-backward " \t") (bolp)))
20772 (insert "\n")
20773 (org-table-justify-field-maybe)
20774 (call-interactively #'org-table-next-row)))
20775 ;; On a link or a timestamp, call `org-open-at-point' if
20776 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20777 ;; locations, e.g., in a comment, as `org-open-at-point'.
20778 ((and org-return-follows-link
20779 (or (org-in-regexp org-ts-regexp-both nil t)
20780 (org-in-regexp org-tsr-regexp-both nil t)
20781 (org-in-regexp org-any-link-re nil t)))
20782 (call-interactively #'org-open-at-point))
20783 ;; Insert newline in heading, but preserve tags.
20784 ((and (not (bolp))
20785 (save-excursion (beginning-of-line)
20786 (let ((case-fold-search nil))
20787 (looking-at org-complex-heading-regexp))))
20788 ;; At headline. Split line. However, if point is on keyword,
20789 ;; priority cookie or tags, do not break any of them: add
20790 ;; a newline after the headline instead.
20791 (let ((tags-column (and (match-beginning 5)
20792 (save-excursion (goto-char (match-beginning 5))
20793 (current-column))))
20794 (string
20795 (when (and (match-end 4) (org-point-in-group (point) 4))
20796 (delete-and-extract-region (point) (match-end 4)))))
20797 ;; Adjust tag alignment.
20798 (cond
20799 ((not (and tags-column string)))
20800 (org-auto-align-tags (org-set-tags nil t))
20801 (t (org--align-tags-here tags-column))) ;preserve tags column
20802 (end-of-line)
20803 (org-show-entry)
20804 (if indent (newline-and-indent) (newline))
20805 (when string (save-excursion (insert (org-trim string))))))
20806 ;; In a list, make sure indenting keeps trailing text within.
20807 ((and indent
20808 (not (eolp))
20809 (org-element-lineage context '(item)))
20810 (let ((trailing-data
20811 (delete-and-extract-region (point) (line-end-position))))
20812 (newline-and-indent)
20813 (save-excursion (insert trailing-data))))
20814 (t (if indent (newline-and-indent) (newline))))))
20816 (defun org-return-indent ()
20817 "Goto next table row or insert a newline and indent.
20818 Calls `org-table-next-row' or `newline-and-indent', depending on
20819 context. See the individual commands for more information."
20820 (interactive)
20821 (org-return t))
20823 (defun org-ctrl-c-tab (&optional _arg)
20824 "Toggle columns width in a table, or show children.
20825 Call `org-table-toggle-column-width' if point is in a table.
20826 Otherwise, call `org-show-children'."
20827 (interactive "p")
20828 (call-interactively
20829 (if (org-at-table-p) #'org-table-toggle-column-width
20830 #'org-show-children)))
20832 (defun org-ctrl-c-star ()
20833 "Compute table, or change heading status of lines.
20834 Calls `org-table-recalculate' or `org-toggle-heading',
20835 depending on context."
20836 (interactive)
20837 (cond
20838 ((org-at-table-p)
20839 (call-interactively 'org-table-recalculate))
20841 ;; Convert all lines in region to list items
20842 (call-interactively 'org-toggle-heading))))
20844 (defun org-ctrl-c-minus ()
20845 "Insert separator line in table or modify bullet status of line.
20846 Also turns a plain line or a region of lines into list items.
20847 Calls `org-table-insert-hline', `org-toggle-item', or
20848 `org-cycle-list-bullet', depending on context."
20849 (interactive)
20850 (cond
20851 ((org-at-table-p)
20852 (call-interactively 'org-table-insert-hline))
20853 ((org-region-active-p)
20854 (call-interactively 'org-toggle-item))
20855 ((org-in-item-p)
20856 (call-interactively 'org-cycle-list-bullet))
20858 (call-interactively 'org-toggle-item))))
20860 (defun org-toggle-heading (&optional nstars)
20861 "Convert headings to normal text, or items or text to headings.
20862 If there is no active region, only convert the current line.
20864 With a `\\[universal-argument]' prefix, convert the whole list at
20865 point into heading.
20867 In a region:
20869 - If the first non blank line is a headline, remove the stars
20870 from all headlines in the region.
20872 - If it is a normal line, turn each and every normal line (i.e.,
20873 not an heading or an item) in the region into headings. If you
20874 want to convert only the first line of this region, use one
20875 universal prefix argument.
20877 - If it is a plain list item, turn all plain list items into headings.
20879 When converting a line into a heading, the number of stars is chosen
20880 such that the lines become children of the current entry. However,
20881 when a numeric prefix argument is given, its value determines the
20882 number of stars to add."
20883 (interactive "P")
20884 (let ((skip-blanks
20885 (function
20886 ;; Return beginning of first non-blank line, starting from
20887 ;; line at POS.
20888 (lambda (pos)
20889 (save-excursion
20890 (goto-char pos)
20891 (while (org-at-comment-p) (forward-line))
20892 (skip-chars-forward " \r\t\n")
20893 (point-at-bol)))))
20894 beg end toggled)
20895 ;; Determine boundaries of changes. If a universal prefix has
20896 ;; been given, put the list in a region. If region ends at a bol,
20897 ;; do not consider the last line to be in the region.
20899 (when (and current-prefix-arg (org-at-item-p))
20900 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20901 (org-mark-element))
20903 (if (org-region-active-p)
20904 (setq beg (funcall skip-blanks (region-beginning))
20905 end (copy-marker (save-excursion
20906 (goto-char (region-end))
20907 (if (bolp) (point) (point-at-eol)))))
20908 (setq beg (funcall skip-blanks (point-at-bol))
20909 end (copy-marker (point-at-eol))))
20910 ;; Ensure inline tasks don't count as headings.
20911 (org-with-limited-levels
20912 (save-excursion
20913 (goto-char beg)
20914 (cond
20915 ;; Case 1. Started at an heading: de-star headings.
20916 ((org-at-heading-p)
20917 (while (< (point) end)
20918 (when (org-at-heading-p t)
20919 (looking-at org-outline-regexp) (replace-match "")
20920 (setq toggled t))
20921 (forward-line)))
20922 ;; Case 2. Started at an item: change items into headlines.
20923 ;; One star will be added by `org-list-to-subtree'.
20924 ((org-at-item-p)
20925 (while (< (point) end)
20926 (when (org-at-item-p)
20927 ;; Pay attention to cases when region ends before list.
20928 (let* ((struct (org-list-struct))
20929 (list-end
20930 (min (org-list-get-bottom-point struct) (1+ end))))
20931 (save-restriction
20932 (narrow-to-region (point) list-end)
20933 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20934 (setq toggled t))
20935 (forward-line)))
20936 ;; Case 3. Started at normal text: make every line an heading,
20937 ;; skipping headlines and items.
20938 (t (let* ((stars
20939 (make-string
20940 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20941 (add-stars
20942 (cond (nstars "") ; stars from prefix only
20943 ((equal stars "") "*") ; before first heading
20944 (org-odd-levels-only "**") ; inside heading, odd
20945 (t "*"))) ; inside heading, oddeven
20946 (rpl (concat stars add-stars " "))
20947 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20948 (while (< (point) (if (equal nstars '(4)) lend end))
20949 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20950 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20951 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20952 (forward-line)))))))
20953 (unless toggled (message "Cannot toggle heading from here"))))
20955 (defun org-meta-return (&optional arg)
20956 "Insert a new heading or wrap a region in a table.
20957 Calls `org-insert-heading', `org-insert-item' or
20958 `org-table-wrap-region', depending on context. When called with
20959 an argument, unconditionally call `org-insert-heading'."
20960 (interactive "P")
20961 (org-check-before-invisible-edit 'insert)
20962 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20963 (call-interactively (cond (arg #'org-insert-heading)
20964 ((org-at-table-p) #'org-table-wrap-region)
20965 ((org-in-item-p) #'org-insert-item)
20966 (t #'org-insert-heading)))))
20968 ;;; Menu entries
20970 (defsubst org-in-subtree-not-table-p ()
20971 "Are we in a subtree and not in a table?"
20972 (and (not (org-before-first-heading-p))
20973 (not (org-at-table-p))))
20975 ;; Define the Org mode menus
20976 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20977 '("Tbl"
20978 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20979 ["Next Field" org-cycle (org-at-table-p)]
20980 ["Previous Field" org-shifttab (org-at-table-p)]
20981 ["Next Row" org-return (org-at-table-p)]
20982 "--"
20983 ["Blank Field" org-table-blank-field (org-at-table-p)]
20984 ["Edit Field" org-table-edit-field (org-at-table-p)]
20985 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20986 "--"
20987 ("Column"
20988 ["Move Column Left" org-metaleft (org-at-table-p)]
20989 ["Move Column Right" org-metaright (org-at-table-p)]
20990 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20991 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20992 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20993 ("Row"
20994 ["Move Row Up" org-metaup (org-at-table-p)]
20995 ["Move Row Down" org-metadown (org-at-table-p)]
20996 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20997 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20998 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20999 "--"
21000 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21001 ("Rectangle"
21002 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21003 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21004 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21005 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21006 "--"
21007 ("Calculate"
21008 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21009 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21010 ["Edit Formulas" org-edit-special (org-at-table-p)]
21011 "--"
21012 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21013 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21014 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21015 "--"
21016 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21017 "--"
21018 ["Sum Column/Rectangle" org-table-sum
21019 (or (org-at-table-p) (org-region-active-p))]
21020 ["Which Column?" org-table-current-column (org-at-table-p)])
21021 ["Debug Formulas"
21022 org-table-toggle-formula-debugger
21023 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21024 ["Show Col/Row Numbers"
21025 org-table-toggle-coordinate-overlays
21026 :style toggle
21027 :selected (bound-and-true-p org-table-overlay-coordinates)]
21028 "--"
21029 ["Create" org-table-create (not (org-at-table-p))]
21030 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21031 ["Import from File" org-table-import (not (org-at-table-p))]
21032 ["Export to File" org-table-export (org-at-table-p)]
21033 "--"
21034 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21035 "--"
21036 ("Plot"
21037 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21038 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21040 (easy-menu-define org-org-menu org-mode-map "Org menu"
21041 '("Org"
21042 ("Show/Hide"
21043 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21044 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21045 ["Sparse Tree..." org-sparse-tree t]
21046 ["Reveal Context" org-reveal t]
21047 ["Show All" outline-show-all t]
21048 "--"
21049 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21050 "--"
21051 ["New Heading" org-insert-heading t]
21052 ("Navigate Headings"
21053 ["Up" outline-up-heading t]
21054 ["Next" outline-next-visible-heading t]
21055 ["Previous" outline-previous-visible-heading t]
21056 ["Next Same Level" outline-forward-same-level t]
21057 ["Previous Same Level" outline-backward-same-level t]
21058 "--"
21059 ["Jump" org-goto t])
21060 ("Edit Structure"
21061 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21062 "--"
21063 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21064 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21065 "--"
21066 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21067 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21068 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21069 "--"
21070 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21071 "--"
21072 ["Copy visible text" org-copy-visible t]
21073 "--"
21074 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21075 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21076 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21077 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21078 "--"
21079 ["Sort Region/Children" org-sort t]
21080 "--"
21081 ["Convert to odd levels" org-convert-to-odd-levels t]
21082 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21083 ("Editing"
21084 ["Emphasis..." org-emphasize t]
21085 ["Edit Source Example" org-edit-special t]
21086 "--"
21087 ["Footnote new/jump" org-footnote-action t]
21088 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21089 ("Archive"
21090 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21091 "--"
21092 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21093 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21094 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21096 "--"
21097 ("Hyperlinks"
21098 ["Store Link (Global)" org-store-link t]
21099 ["Find existing link to here" org-occur-link-in-agenda-files t]
21100 ["Insert Link" org-insert-link t]
21101 ["Follow Link" org-open-at-point t]
21102 "--"
21103 ["Next link" org-next-link t]
21104 ["Previous link" org-previous-link t]
21105 "--"
21106 ["Descriptive Links"
21107 org-toggle-link-display
21108 :style radio
21109 :selected org-descriptive-links
21111 ["Literal Links"
21112 org-toggle-link-display
21113 :style radio
21114 :selected (not org-descriptive-links)])
21115 "--"
21116 ("TODO Lists"
21117 ["TODO/DONE/-" org-todo t]
21118 ("Select keyword"
21119 ["Next keyword" org-shiftright (org-at-heading-p)]
21120 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21121 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21122 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21123 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21124 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21125 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
21126 "--"
21127 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21128 :selected org-enforce-todo-dependencies :style toggle :active t]
21129 "Settings for tree at point"
21130 ["Do Children sequentially" org-toggle-ordered-property :style radio
21131 :selected (org-entry-get nil "ORDERED")
21132 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21133 ["Do Children parallel" org-toggle-ordered-property :style radio
21134 :selected (not (org-entry-get nil "ORDERED"))
21135 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21136 "--"
21137 ["Set Priority" org-priority t]
21138 ["Priority Up" org-shiftup t]
21139 ["Priority Down" org-shiftdown t]
21140 "--"
21141 ["Get news from all feeds" org-feed-update-all t]
21142 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21143 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21144 ("TAGS and Properties"
21145 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21146 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21147 "--"
21148 ["Set property" org-set-property (not (org-before-first-heading-p))]
21149 ["Column view of properties" org-columns t]
21150 ["Insert Column View DBlock" org-columns-insert-dblock t])
21151 ("Dates and Scheduling"
21152 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21153 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21154 ("Change Date"
21155 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21156 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21157 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21158 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21159 ["Compute Time Range" org-evaluate-time-range t]
21160 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21161 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21162 "--"
21163 ["Custom time format" org-toggle-time-stamp-overlays
21164 :style radio :selected org-display-custom-times]
21165 "--"
21166 ["Goto Calendar" org-goto-calendar t]
21167 ["Date from Calendar" org-date-from-calendar t]
21168 "--"
21169 ["Start/Restart Timer" org-timer-start t]
21170 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21171 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21172 ["Insert Timer String" org-timer t]
21173 ["Insert Timer Item" org-timer-item t])
21174 ("Logging work"
21175 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21176 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21177 ["Clock out" org-clock-out t]
21178 ["Clock cancel" org-clock-cancel t]
21179 "--"
21180 ["Mark as default task" org-clock-mark-default-task t]
21181 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21182 ["Goto running clock" org-clock-goto t]
21183 "--"
21184 ["Display times" org-clock-display t]
21185 ["Create clock table" org-clock-report t]
21186 "--"
21187 ["Record DONE time"
21188 (progn (setq org-log-done (not org-log-done))
21189 (message "Switching to %s will %s record a timestamp"
21190 (car org-done-keywords)
21191 (if org-log-done "automatically" "not")))
21192 :style toggle :selected org-log-done])
21193 "--"
21194 ["Agenda Command..." org-agenda t]
21195 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21196 ("File List for Agenda")
21197 ("Special views current file"
21198 ["TODO Tree" org-show-todo-tree t]
21199 ["Check Deadlines" org-check-deadlines t]
21200 ["Tags/Property tree" org-match-sparse-tree t])
21201 "--"
21202 ["Export/Publish..." org-export-dispatch t]
21203 ("LaTeX"
21204 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
21205 :style toggle :selected org-cdlatex-mode]
21206 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21207 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21208 ["Modify math symbol" org-cdlatex-math-modify
21209 (org-inside-LaTeX-fragment-p)]
21210 ["Insert citation" org-reftex-citation t])
21211 "--"
21212 ("MobileOrg"
21213 ["Push Files and Views" org-mobile-push t]
21214 ["Get Captured and Flagged" org-mobile-pull t]
21215 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
21216 "--"
21217 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21218 "--"
21219 ("Documentation"
21220 ["Show Version" org-version t]
21221 ["Info Documentation" org-info t])
21222 ("Customize"
21223 ["Browse Org Group" org-customize t]
21224 "--"
21225 ["Expand This Menu" org-create-customize-menu
21226 (fboundp 'customize-menu-create)])
21227 ["Send bug report" org-submit-bug-report t]
21228 "--"
21229 ("Refresh/Reload"
21230 ["Refresh setup current buffer" org-mode-restart t]
21231 ["Reload Org (after update)" org-reload t]
21232 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21235 (defun org-info (&optional node)
21236 "Read documentation for Org in the info system.
21237 With optional NODE, go directly to that node."
21238 (interactive)
21239 (info (format "(org)%s" (or node ""))))
21241 ;;;###autoload
21242 (defun org-submit-bug-report ()
21243 "Submit a bug report on Org via mail.
21245 Don't hesitate to report any problems or inaccurate documentation.
21247 If you don't have setup sending mail from (X)Emacs, please copy the
21248 output buffer into your mail program, as it gives us important
21249 information about your Org version and configuration."
21250 (interactive)
21251 (require 'reporter)
21252 (defvar reporter-prompt-for-summary-p)
21253 (org-load-modules-maybe)
21254 (org-require-autoloaded-modules)
21255 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21256 (reporter-submit-bug-report
21257 "emacs-orgmode@gnu.org"
21258 (org-version nil 'full)
21259 (let (list)
21260 (save-window-excursion
21261 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21262 (delete-other-windows)
21263 (erase-buffer)
21264 (insert "You are about to submit a bug report to the Org mailing list.
21266 We would like to add your full Org and Outline configuration to the
21267 bug report. This greatly simplifies the work of the maintainer and
21268 other experts on the mailing list.
21270 HOWEVER, some variables you have customized may contain private
21271 information. The names of customers, colleagues, or friends, might
21272 appear in the form of file names, tags, todo states, or search strings.
21273 If you answer yes to the prompt, you might want to check and remove
21274 such private information before sending the email.")
21275 (add-text-properties (point-min) (point-max) '(face org-warning))
21276 (when (yes-or-no-p "Include your Org configuration ")
21277 (mapatoms
21278 (lambda (v)
21279 (and (boundp v)
21280 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21281 (or (and (symbol-value v)
21282 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21283 (and
21284 (get v 'custom-type) (get v 'standard-value)
21285 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21286 (push v list)))))
21287 (kill-buffer (get-buffer "*Warn about privacy*"))
21288 list))
21289 nil nil
21290 "Remember to cover the basics, that is, what you expected to happen and
21291 what in fact did happen. You don't know how to make a good report? See
21293 http://orgmode.org/manual/Feedback.html#Feedback
21295 Your bug report will be posted to the Org mailing list.
21296 ------------------------------------------------------------------------")
21297 (save-excursion
21298 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21299 (replace-match "\\1Bug: \\3 [\\2]")))))
21302 (defun org-install-agenda-files-menu ()
21303 (let ((bl (buffer-list)))
21304 (save-excursion
21305 (while bl
21306 (set-buffer (pop bl))
21307 (when (derived-mode-p 'org-mode) (setq bl nil)))
21308 (when (derived-mode-p 'org-mode)
21309 (easy-menu-change
21310 '("Org") "File List for Agenda"
21311 (append
21312 (list
21313 ["Edit File List" (org-edit-agenda-file-list) t]
21314 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21315 ["Remove Current File from List" org-remove-file t]
21316 ["Cycle through agenda files" org-cycle-agenda-files t]
21317 ["Occur in all agenda files" org-occur-in-agenda-files t]
21318 "--")
21319 (mapcar 'org-file-menu-entry
21320 ;; Prevent initialization from failing.
21321 (ignore-errors (org-agenda-files t)))))))))
21323 ;;;; Documentation
21325 (defun org-require-autoloaded-modules ()
21326 (interactive)
21327 (mapc #'require
21328 '(org-agenda org-archive org-attach org-clock org-colview org-id
21329 org-table org-timer)))
21331 ;;;###autoload
21332 (defun org-reload (&optional uncompiled)
21333 "Reload all org lisp files.
21334 With prefix arg UNCOMPILED, load the uncompiled versions."
21335 (interactive "P")
21336 (require 'loadhist)
21337 (let* ((org-dir (org-find-library-dir "org"))
21338 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21339 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21340 (remove-re (format "\\`%s\\'"
21341 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21342 (feats (delete-dups
21343 (mapcar 'file-name-sans-extension
21344 (mapcar 'file-name-nondirectory
21345 (delq nil
21346 (mapcar 'feature-file
21347 features))))))
21348 (lfeat (append
21349 (sort
21350 (setq feats
21351 (delq nil (mapcar
21352 (lambda (f)
21353 (if (and (string-match feature-re f)
21354 (not (string-match remove-re f)))
21355 f nil))
21356 feats)))
21357 'string-lessp)
21358 (list "org-version" "org")))
21359 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21360 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21361 load-uncore load-misses)
21362 (setq load-misses
21363 (delq 't
21364 (mapcar (lambda (f)
21365 (or (org-load-noerror-mustsuffix (concat org-dir f))
21366 (and (string= org-dir contrib-dir)
21367 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21368 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21369 (add-to-list 'load-uncore f 'append)
21372 lfeat)))
21373 (when load-uncore
21374 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21375 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21376 (if load-misses
21377 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21378 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21379 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21381 ;;;###autoload
21382 (defun org-customize ()
21383 "Call the customize function with org as argument."
21384 (interactive)
21385 (org-load-modules-maybe)
21386 (org-require-autoloaded-modules)
21387 (customize-browse 'org))
21389 (defun org-create-customize-menu ()
21390 "Create a full customization menu for Org mode, insert it into the menu."
21391 (interactive)
21392 (org-load-modules-maybe)
21393 (org-require-autoloaded-modules)
21394 (if (fboundp 'customize-menu-create)
21395 (progn
21396 (easy-menu-change
21397 '("Org") "Customize"
21398 `(["Browse Org group" org-customize t]
21399 "--"
21400 ,(customize-menu-create 'org)
21401 ["Set" Custom-set t]
21402 ["Save" Custom-save t]
21403 ["Reset to Current" Custom-reset-current t]
21404 ["Reset to Saved" Custom-reset-saved t]
21405 ["Reset to Standard Settings" Custom-reset-standard t]))
21406 (message "\"Org\"-menu now contains full customization menu"))
21407 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21409 ;;;; Miscellaneous stuff
21411 ;;; Generally useful functions
21413 (defun org-link-display-format (s)
21414 "Replace links in string S with their description.
21415 If there is no description, use the link target."
21416 (save-match-data
21417 (replace-regexp-in-string
21418 org-bracket-link-analytic-regexp
21419 (lambda (m)
21420 (if (match-end 5) (match-string 5 m)
21421 (concat (match-string 1 m) (match-string 3 m))))
21422 s nil t)))
21424 (defun org-toggle-link-display ()
21425 "Toggle the literal or descriptive display of links."
21426 (interactive)
21427 (if org-descriptive-links
21428 (progn (org-remove-from-invisibility-spec '(org-link))
21429 (org-restart-font-lock)
21430 (setq org-descriptive-links nil))
21431 (progn (add-to-invisibility-spec '(org-link))
21432 (org-restart-font-lock)
21433 (setq org-descriptive-links t))))
21435 (defun org-in-clocktable-p ()
21436 "Check if the cursor is in a clocktable."
21437 (let ((pos (point)) start)
21438 (save-excursion
21439 (end-of-line 1)
21440 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21441 (setq start (match-beginning 0))
21442 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21443 (>= (match-end 0) pos)
21444 start))))
21446 (defun org-in-verbatim-emphasis ()
21447 (save-match-data
21448 (and (org-in-regexp org-verbatim-re 2)
21449 (>= (point) (match-beginning 3))
21450 (<= (point) (match-end 4)))))
21452 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21453 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21454 (if (and marker (marker-buffer marker)
21455 (buffer-live-p (marker-buffer marker)))
21456 (progn
21457 (pop-to-buffer-same-window (marker-buffer marker))
21458 (when (or (> marker (point-max)) (< marker (point-min)))
21459 (widen))
21460 (goto-char marker)
21461 (org-show-context 'org-goto))
21462 (if bookmark
21463 (bookmark-jump bookmark)
21464 (error "Cannot find location"))))
21466 (defun org-quote-csv-field (s)
21467 "Quote field for inclusion in CSV material."
21468 (if (string-match "[\",]" s)
21469 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21472 (defun org-force-self-insert (N)
21473 "Needed to enforce self-insert under remapping."
21474 (interactive "p")
21475 (self-insert-command N))
21477 (defun org-get-indentation (&optional line)
21478 "Get the indentation of the current line, interpreting tabs.
21479 When LINE is given, assume it represents a line and compute its indentation."
21480 (if line
21481 (when (string-match "^ *" (org-remove-tabs line))
21482 (match-end 0))
21483 (save-excursion
21484 (beginning-of-line 1)
21485 (skip-chars-forward " \t")
21486 (current-column))))
21488 (defun org-get-string-indentation (s)
21489 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21490 (let ((n -1) (i 0) (w tab-width) c)
21491 (catch 'exit
21492 (while (< (setq n (1+ n)) (length s))
21493 (setq c (aref s n))
21494 (cond ((= c ?\ ) (setq i (1+ i)))
21495 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21496 (t (throw 'exit t)))))
21499 (defun org-fix-indentation (line ind)
21500 "Fix indentation in LINE.
21501 IND is a cons cell with target and minimum indentation.
21502 If the current indentation in LINE is smaller than the minimum,
21503 leave it alone. If it is larger than ind, set it to the target."
21504 (let* ((l (org-remove-tabs line))
21505 (i (org-get-indentation l))
21506 (i1 (car ind)) (i2 (cdr ind)))
21507 (when (>= i i2) (setq l (substring line i2)))
21508 (if (> i1 0)
21509 (concat (make-string i1 ?\ ) l)
21510 l)))
21512 (defun org-fill-template (template alist)
21513 "Find each %key of ALIST in TEMPLATE and replace it."
21514 (let ((case-fold-search nil))
21515 (dolist (entry (sort (copy-sequence alist)
21516 (lambda (a b) (< (length (car a)) (length (car b))))))
21517 (setq template
21518 (replace-regexp-in-string
21519 (concat "%" (regexp-quote (car entry)))
21520 (or (cdr entry) "") template t t)))
21521 template))
21523 (defun org-quote-vert (s)
21524 "Replace \"|\" with \"\\vert\"."
21525 (while (string-match "|" s)
21526 (setq s (replace-match "\\vert" t t s)))
21529 (defun org-uuidgen-p (s)
21530 "Is S an ID created by UUIDGEN?"
21531 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21533 (defun org-in-src-block-p (&optional inside)
21534 "Whether point is in a code source block.
21535 When INSIDE is non-nil, don't consider we are within a src block
21536 when point is at #+BEGIN_SRC or #+END_SRC."
21537 (let ((case-fold-search t))
21538 (or (and (eq (get-char-property (point) 'src-block) t))
21539 (and (not inside)
21540 (save-match-data
21541 (save-excursion
21542 (beginning-of-line)
21543 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21545 (defun org-context ()
21546 "Return a list of contexts of the current cursor position.
21547 If several contexts apply, all are returned.
21548 Each context entry is a list with a symbol naming the context, and
21549 two positions indicating start and end of the context. Possible
21550 contexts are:
21552 :headline anywhere in a headline
21553 :headline-stars on the leading stars in a headline
21554 :todo-keyword on a TODO keyword (including DONE) in a headline
21555 :tags on the TAGS in a headline
21556 :priority on the priority cookie in a headline
21557 :item on the first line of a plain list item
21558 :item-bullet on the bullet/number of a plain list item
21559 :checkbox on the checkbox in a plain list item
21560 :table in an Org table
21561 :table-special on a special filed in a table
21562 :table-table in a table.el table
21563 :clocktable in a clocktable
21564 :src-block in a source block
21565 :link on a hyperlink
21566 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21567 :target on a <<target>>
21568 :radio-target on a <<<radio-target>>>
21569 :latex-fragment on a LaTeX fragment
21570 :latex-preview on a LaTeX fragment with overlaid preview image
21572 This function expects the position to be visible because it uses font-lock
21573 faces as a help to recognize the following contexts: :table-special, :link,
21574 and :keyword."
21575 (let* ((f (get-text-property (point) 'face))
21576 (faces (if (listp f) f (list f)))
21577 (case-fold-search t)
21578 (p (point)) clist o)
21579 ;; First the large context
21580 (cond
21581 ((org-at-heading-p t)
21582 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21583 (when (progn
21584 (beginning-of-line 1)
21585 (looking-at org-todo-line-tags-regexp))
21586 (push (org-point-in-group p 1 :headline-stars) clist)
21587 (push (org-point-in-group p 2 :todo-keyword) clist)
21588 (push (org-point-in-group p 4 :tags) clist))
21589 (goto-char p)
21590 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21591 (when (looking-at "\\[#[A-Z0-9]\\]")
21592 (push (org-point-in-group p 0 :priority) clist)))
21594 ((org-at-item-p)
21595 (push (org-point-in-group p 2 :item-bullet) clist)
21596 (push (list :item (point-at-bol)
21597 (save-excursion (org-end-of-item) (point)))
21598 clist)
21599 (and (org-at-item-checkbox-p)
21600 (push (org-point-in-group p 0 :checkbox) clist)))
21602 ((org-at-table-p)
21603 (push (list :table (org-table-begin) (org-table-end)) clist)
21604 (when (memq 'org-formula faces)
21605 (push (list :table-special
21606 (previous-single-property-change p 'face)
21607 (next-single-property-change p 'face)) clist)))
21608 ((org-at-table-p 'any)
21609 (push (list :table-table) clist)))
21610 (goto-char p)
21612 (let ((case-fold-search t))
21613 ;; New the "medium" contexts: clocktables, source blocks
21614 (cond ((org-in-clocktable-p)
21615 (push (list :clocktable
21616 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21617 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21618 (match-beginning 1))
21619 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21620 (match-end 0))) clist))
21621 ((org-in-src-block-p)
21622 (push (list :src-block
21623 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21624 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21625 (match-beginning 1))
21626 (and (search-forward "#+END_SRC" nil t)
21627 (match-beginning 0))) clist))))
21628 (goto-char p)
21630 ;; Now the small context
21631 (cond
21632 ((org-at-timestamp-p)
21633 (push (org-point-in-group p 0 :timestamp) clist))
21634 ((memq 'org-link faces)
21635 (push (list :link
21636 (previous-single-property-change p 'face)
21637 (next-single-property-change p 'face)) clist))
21638 ((memq 'org-special-keyword faces)
21639 (push (list :keyword
21640 (previous-single-property-change p 'face)
21641 (next-single-property-change p 'face)) clist))
21642 ((org-at-target-p)
21643 (push (org-point-in-group p 0 :target) clist)
21644 (goto-char (1- (match-beginning 0)))
21645 (when (looking-at org-radio-target-regexp)
21646 (push (org-point-in-group p 0 :radio-target) clist))
21647 (goto-char p))
21648 ((setq o (cl-some
21649 (lambda (o)
21650 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21652 (overlays-at (point))))
21653 (push (list :latex-fragment
21654 (overlay-start o) (overlay-end o)) clist)
21655 (push (list :latex-preview
21656 (overlay-start o) (overlay-end o)) clist))
21657 ((org-inside-LaTeX-fragment-p)
21658 ;; FIXME: positions wrong.
21659 (push (list :latex-fragment (point) (point)) clist)))
21661 (setq clist (nreverse (delq nil clist)))
21662 clist))
21664 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21665 "Non-nil when point is between matches of START-RE and END-RE.
21667 Also return a non-nil value when point is on one of the matches.
21669 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21670 buffer positions. Default values are the positions of headlines
21671 surrounding the point.
21673 The functions returns a cons cell whose car (resp. cdr) is the
21674 position before START-RE (resp. after END-RE)."
21675 (save-match-data
21676 (let ((pos (point))
21677 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21678 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21679 beg end)
21680 (save-excursion
21681 ;; Point is on a block when on START-RE or if START-RE can be
21682 ;; found before it...
21683 (and (or (org-in-regexp start-re)
21684 (re-search-backward start-re limit-up t))
21685 (setq beg (match-beginning 0))
21686 ;; ... and END-RE after it...
21687 (goto-char (match-end 0))
21688 (re-search-forward end-re limit-down t)
21689 (> (setq end (match-end 0)) pos)
21690 ;; ... without another START-RE in-between.
21691 (goto-char (match-beginning 0))
21692 (not (re-search-backward start-re (1+ beg) t))
21693 ;; Return value.
21694 (cons beg end))))))
21696 (defun org-in-block-p (names)
21697 "Non-nil when point belongs to a block whose name belongs to NAMES.
21699 NAMES is a list of strings containing names of blocks.
21701 Return first block name matched, or nil. Beware that in case of
21702 nested blocks, the returned name may not belong to the closest
21703 block from point."
21704 (save-match-data
21705 (catch 'exit
21706 (let ((case-fold-search t)
21707 (lim-up (save-excursion (outline-previous-heading)))
21708 (lim-down (save-excursion (outline-next-heading))))
21709 (dolist (name names)
21710 (let ((n (regexp-quote name)))
21711 (when (org-between-regexps-p
21712 (concat "^[ \t]*#\\+begin_" n)
21713 (concat "^[ \t]*#\\+end_" n)
21714 lim-up lim-down)
21715 (throw 'exit n)))))
21716 nil)))
21718 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21719 "Call `multi-occur' with buffers for all agenda files."
21720 (interactive "sOrg-files matching: ")
21721 (let* ((files (org-agenda-files))
21722 (tnames (mapcar #'file-truename files))
21723 (extra org-agenda-text-search-extra-files))
21724 (when (eq (car extra) 'agenda-archives)
21725 (setq extra (cdr extra))
21726 (setq files (org-add-archive-files files)))
21727 (dolist (f extra)
21728 (unless (member (file-truename f) tnames)
21729 (unless (member f files) (setq files (append files (list f))))
21730 (setq tnames (append tnames (list (file-truename f))))))
21731 (multi-occur
21732 (mapcar (lambda (x)
21733 (with-current-buffer
21734 ;; FIXME: Why not just (find-file-noselect x)?
21735 ;; Is it to avoid the "revert buffer" prompt?
21736 (or (get-file-buffer x) (find-file-noselect x))
21737 (widen)
21738 (current-buffer)))
21739 files)
21740 regexp)))
21742 (add-hook 'occur-mode-find-occurrence-hook
21743 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21745 (defun org-occur-link-in-agenda-files ()
21746 "Create a link and search for it in the agendas.
21747 The link is not stored in `org-stored-links', it is just created
21748 for the search purpose."
21749 (interactive)
21750 (let ((link (condition-case nil
21751 (org-store-link nil)
21752 (error "Unable to create a link to here"))))
21753 (org-occur-in-agenda-files (regexp-quote link))))
21755 (defun org-back-over-empty-lines ()
21756 "Move backwards over whitespace, to the beginning of the first empty line.
21757 Returns the number of empty lines passed."
21758 (let ((pos (point)))
21759 (if (cdr (assq 'heading org-blank-before-new-entry))
21760 (skip-chars-backward " \t\n\r")
21761 (unless (eobp)
21762 (forward-line -1)))
21763 (beginning-of-line 2)
21764 (goto-char (min (point) pos))
21765 (count-lines (point) pos)))
21767 (defun org-switch-to-buffer-other-window (&rest args)
21768 "Switch to buffer in a second window on the current frame.
21769 In particular, do not allow pop-up frames.
21770 Returns the newly created buffer."
21771 (org-no-popups
21772 (apply 'switch-to-buffer-other-window args)))
21774 (defun org-replace-escapes (string table)
21775 "Replace %-escapes in STRING with values in TABLE.
21776 TABLE is an association list with keys like \"%a\" and string values.
21777 The sequences in STRING may contain normal field width and padding information,
21778 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21779 so values can contain further %-escapes if they are define later in TABLE."
21780 (let ((tbl (copy-alist table))
21781 (case-fold-search nil)
21782 (pchg 0)
21783 re rpl)
21784 (dolist (e tbl)
21785 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21786 (when (and (cdr e) (string-match re (cdr e)))
21787 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21788 (safe "SREF"))
21789 (add-text-properties 0 3 (list 'sref sref) safe)
21790 (setcdr e (replace-match safe t t (cdr e)))))
21791 (while (string-match re string)
21792 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21793 (cdr e)))
21794 (setq string (replace-match rpl t t string))))
21795 (while (setq pchg (next-property-change pchg string))
21796 (let ((sref (get-text-property pchg 'sref string)))
21797 (when (and sref (string-match "SREF" string pchg))
21798 (setq string (replace-match sref t t string)))))
21799 string))
21801 ;;; TODO: Only called once, from ox-odt which should probably use
21802 ;;; org-export-inline-image-p or something.
21803 (defun org-file-image-p (file)
21804 "Return non-nil if FILE is an image."
21805 (save-match-data
21806 (string-match (image-file-name-regexp) file)))
21808 (defun org-get-cursor-date (&optional with-time)
21809 "Return the date at cursor in as a time.
21810 This works in the calendar and in the agenda, anywhere else it just
21811 returns the current time.
21812 If WITH-TIME is non-nil, returns the time of the event at point (in
21813 the agenda) or the current time of the day."
21814 (let (date day defd tp hod mod)
21815 (when with-time
21816 (setq tp (get-text-property (point) 'time))
21817 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21818 (setq hod (string-to-number (match-string 1 tp))
21819 mod (string-to-number (match-string 2 tp))))
21820 (or tp (let ((now (decode-time)))
21821 (setq hod (nth 2 now)
21822 mod (nth 1 now)))))
21823 (cond
21824 ((eq major-mode 'calendar-mode)
21825 (setq date (calendar-cursor-to-date)
21826 defd (encode-time 0 (or mod 0) (or hod 0)
21827 (nth 1 date) (nth 0 date) (nth 2 date))))
21828 ((eq major-mode 'org-agenda-mode)
21829 (setq day (get-text-property (point) 'day))
21830 (when day
21831 (setq date (calendar-gregorian-from-absolute day)
21832 defd (encode-time 0 (or mod 0) (or hod 0)
21833 (nth 1 date) (nth 0 date) (nth 2 date))))))
21834 (or defd (current-time))))
21836 (defun org-mark-subtree (&optional up)
21837 "Mark the current subtree.
21838 This puts point at the start of the current subtree, and mark at
21839 the end. If a numeric prefix UP is given, move up into the
21840 hierarchy of headlines by UP levels before marking the subtree."
21841 (interactive "P")
21842 (org-with-limited-levels
21843 (cond ((org-at-heading-p) (beginning-of-line))
21844 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21845 (t (outline-previous-visible-heading 1))))
21846 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21847 (if (called-interactively-p 'any)
21848 (call-interactively 'org-mark-element)
21849 (org-mark-element)))
21851 (defun org-file-newer-than-p (file time)
21852 "Non-nil if FILE is newer than TIME.
21853 FILE is a filename, as a string, TIME is a list of integers, as
21854 returned by, e.g., `current-time'."
21855 (and (file-exists-p file)
21856 ;; Only compare times up to whole seconds as some file-systems
21857 ;; (e.g. HFS+) do not retain any finer granularity. As
21858 ;; a consequence, make sure we return non-nil when the two
21859 ;; times are equal.
21860 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21861 (cl-subseq time 0 2)))))
21863 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21864 "Compile a SOURCE file using PROCESS.
21866 PROCESS is either a function or a list of shell commands, as
21867 strings. EXT is a file extension, without the leading dot, as
21868 a string. It is used to check if the process actually succeeded.
21870 PROCESS must create a file with the same base name and directory
21871 as SOURCE, but ending with EXT. The function then returns its
21872 filename. Otherwise, it raises an error. The error message can
21873 then be refined by providing string ERR-MSG, which is appended to
21874 the standard message.
21876 If PROCESS is a function, it is called with a single argument:
21877 the SOURCE file.
21879 If it is a list of commands, each of them is called using
21880 `shell-command'. By default, in each command, %b, %f, %F, %o and
21881 %O are replaced with, respectively, SOURCE base name, name, full
21882 name, directory and absolute output file name. It is possible,
21883 however, to use more place-holders by specifying them in optional
21884 argument SPEC, as an alist following the pattern
21886 (CHARACTER . REPLACEMENT-STRING).
21888 When PROCESS is a list of commands, optional argument LOG-BUF can
21889 be set to a buffer or a buffer name. `shell-command' then uses
21890 it for output."
21891 (let* ((base-name (file-name-base source))
21892 (full-name (file-truename source))
21893 (out-dir (or (file-name-directory source) "./"))
21894 (output (expand-file-name (concat base-name "." ext) out-dir))
21895 (time (current-time))
21896 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21897 (save-window-excursion
21898 (pcase process
21899 ((pred functionp) (funcall process (shell-quote-argument source)))
21900 ((pred consp)
21901 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21902 (spec (append spec
21903 `((?b . ,(shell-quote-argument base-name))
21904 (?f . ,(shell-quote-argument source))
21905 (?F . ,(shell-quote-argument full-name))
21906 (?o . ,(shell-quote-argument out-dir))
21907 (?O . ,(shell-quote-argument output))))))
21908 (dolist (command process)
21909 (shell-command (format-spec command spec) log-buf))
21910 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21911 (_ (error "No valid command to process %S%s" source err-msg))))
21912 ;; Check for process failure. Output file is expected to be
21913 ;; located in the same directory as SOURCE.
21914 (unless (org-file-newer-than-p output time)
21915 (error (format "File %S wasn't produced%s" output err-msg)))
21916 output))
21918 ;;; Indentation
21920 (defvar org-element-greater-elements)
21921 (defun org--get-expected-indentation (element contentsp)
21922 "Expected indentation column for current line, according to ELEMENT.
21923 ELEMENT is an element containing point. CONTENTSP is non-nil
21924 when indentation is to be computed according to contents of
21925 ELEMENT."
21926 (let ((type (org-element-type element))
21927 (start (org-element-property :begin element))
21928 (post-affiliated (org-element-property :post-affiliated element)))
21929 (org-with-wide-buffer
21930 (cond
21931 (contentsp
21932 (cl-case type
21933 ((diary-sexp footnote-definition) 0)
21934 ((headline inlinetask nil)
21935 (if (not org-adapt-indentation) 0
21936 (let ((level (org-current-level)))
21937 (if level (1+ level) 0))))
21938 ((item plain-list) (org-list-item-body-column post-affiliated))
21940 (goto-char start)
21941 (org-get-indentation))))
21942 ((memq type '(headline inlinetask nil))
21943 (if (org-match-line "[ \t]*$")
21944 (org--get-expected-indentation element t)
21946 ((memq type '(diary-sexp footnote-definition)) 0)
21947 ;; First paragraph of a footnote definition or an item.
21948 ;; Indent like parent.
21949 ((< (line-beginning-position) start)
21950 (org--get-expected-indentation
21951 (org-element-property :parent element) t))
21952 ;; At first line: indent according to previous sibling, if any,
21953 ;; ignoring footnote definitions and inline tasks, or parent's
21954 ;; contents.
21955 ((= (line-beginning-position) start)
21956 (catch 'exit
21957 (while t
21958 (if (= (point-min) start) (throw 'exit 0)
21959 (goto-char (1- start))
21960 (let* ((previous (org-element-at-point))
21961 (parent previous))
21962 (while (and parent (<= (org-element-property :end parent) start))
21963 (setq previous parent
21964 parent (org-element-property :parent parent)))
21965 (cond
21966 ((not previous) (throw 'exit 0))
21967 ((> (org-element-property :end previous) start)
21968 (throw 'exit (org--get-expected-indentation previous t)))
21969 ((memq (org-element-type previous)
21970 '(footnote-definition inlinetask))
21971 (setq start (org-element-property :begin previous)))
21972 (t (goto-char (org-element-property :begin previous))
21973 (throw 'exit
21974 (if (bolp) (org-get-indentation)
21975 ;; At first paragraph in an item or
21976 ;; a footnote definition.
21977 (org--get-expected-indentation
21978 (org-element-property :parent previous) t))))))))))
21979 ;; Otherwise, move to the first non-blank line above.
21981 (beginning-of-line)
21982 (let ((pos (point)))
21983 (skip-chars-backward " \r\t\n")
21984 (cond
21985 ;; Two blank lines end a footnote definition or a plain
21986 ;; list. When we indent an empty line after them, the
21987 ;; containing list or footnote definition is over, so it
21988 ;; qualifies as a previous sibling. Therefore, we indent
21989 ;; like its first line.
21990 ((and (memq type '(footnote-definition plain-list))
21991 (> (count-lines (point) pos) 2))
21992 (goto-char start)
21993 (org-get-indentation))
21994 ;; Line above is the first one of a paragraph at the
21995 ;; beginning of an item or a footnote definition. Indent
21996 ;; like parent.
21997 ((< (line-beginning-position) start)
21998 (org--get-expected-indentation
21999 (org-element-property :parent element) t))
22000 ;; Line above is the beginning of an element, i.e., point
22001 ;; was originally on the blank lines between element's start
22002 ;; and contents.
22003 ((= (line-beginning-position) post-affiliated)
22004 (org--get-expected-indentation element t))
22005 ;; POS is after contents in a greater element. Indent like
22006 ;; the beginning of the element.
22007 ((and (memq type org-element-greater-elements)
22008 (let ((cend (org-element-property :contents-end element)))
22009 (and cend (<= cend pos))))
22010 ;; As a special case, if point is at the end of a footnote
22011 ;; definition or an item, indent like the very last element
22012 ;; within. If that last element is an item, indent like
22013 ;; its contents.
22014 (if (memq type '(footnote-definition item plain-list))
22015 (let ((last (org-element-at-point)))
22016 (goto-char pos)
22017 (org--get-expected-indentation
22018 last (eq (org-element-type last) 'item)))
22019 (goto-char start)
22020 (org-get-indentation)))
22021 ;; In any other case, indent like the current line.
22022 (t (org-get-indentation)))))))))
22024 (defun org--align-node-property ()
22025 "Align node property at point.
22026 Alignment is done according to `org-property-format', which see."
22027 (when (save-excursion
22028 (beginning-of-line)
22029 (looking-at org-property-re))
22030 (replace-match
22031 (concat (match-string 4)
22032 (org-trim
22033 (format org-property-format (match-string 1) (match-string 3))))
22034 t t)))
22036 (defun org-indent-line ()
22037 "Indent line depending on context.
22039 Indentation is done according to the following rules:
22041 - Footnote definitions, diary sexps, headlines and inline tasks
22042 have to start at column 0.
22044 - On the very first line of an element, consider, in order, the
22045 next rules until one matches:
22047 1. If there's a sibling element before, ignoring footnote
22048 definitions and inline tasks, indent like its first line.
22050 2. If element has a parent, indent like its contents. More
22051 precisely, if parent is an item, indent after the
22052 description part, if any, or the bullet (see
22053 `org-list-description-max-indent'). Else, indent like
22054 parent's first line.
22056 3. Otherwise, indent relatively to current level, if
22057 `org-adapt-indentation' is non-nil, or to left margin.
22059 - On a blank line at the end of an element, indent according to
22060 the type of the element. More precisely
22062 1. If element is a plain list, an item, or a footnote
22063 definition, indent like the very last element within.
22065 2. If element is a paragraph, indent like its last non blank
22066 line.
22068 3. Otherwise, indent like its very first line.
22070 - In the code part of a source block, use language major mode
22071 to indent current line if `org-src-tab-acts-natively' is
22072 non-nil. If it is nil, do nothing.
22074 - Otherwise, indent like the first non-blank line above.
22076 The function doesn't indent an item as it could break the whole
22077 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22078 `\\[org-shiftmetaright]'.
22080 Also align node properties according to `org-property-format'."
22081 (interactive)
22082 (cond
22083 (orgstruct-is-++
22084 (let ((indent-line-function
22085 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22086 (indent-according-to-mode)))
22087 ((org-at-heading-p) 'noindent)
22089 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22090 (type (org-element-type element)))
22091 (cond ((and (memq type '(plain-list item))
22092 (= (line-beginning-position)
22093 (org-element-property :post-affiliated element)))
22094 'noindent)
22095 ((and (eq type 'latex-environment)
22096 (>= (point) (org-element-property :post-affiliated element))
22097 (< (point) (org-with-wide-buffer
22098 (goto-char (org-element-property :end element))
22099 (skip-chars-backward " \r\t\n")
22100 (line-beginning-position 2))))
22101 'noindent)
22102 ((and (eq type 'src-block)
22103 org-src-tab-acts-natively
22104 (> (line-beginning-position)
22105 (org-element-property :post-affiliated element))
22106 (< (line-beginning-position)
22107 (org-with-wide-buffer
22108 (goto-char (org-element-property :end element))
22109 (skip-chars-backward " \r\t\n")
22110 (line-beginning-position))))
22111 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22113 (let ((column (org--get-expected-indentation element nil)))
22114 ;; Preserve current column.
22115 (if (<= (current-column) (current-indentation))
22116 (indent-line-to column)
22117 (save-excursion (indent-line-to column))))
22118 ;; Align node property. Also preserve current column.
22119 (when (eq type 'node-property)
22120 (let ((column (current-column)))
22121 (org--align-node-property)
22122 (org-move-to-column column)))))))))
22124 (defun org-indent-region (start end)
22125 "Indent each non-blank line in the region.
22126 Called from a program, START and END specify the region to
22127 indent. The function will not indent contents of example blocks,
22128 verse blocks and export blocks as leading white spaces are
22129 assumed to be significant there."
22130 (interactive "r")
22131 (save-excursion
22132 (goto-char start)
22133 (skip-chars-forward " \r\t\n")
22134 (unless (eobp) (beginning-of-line))
22135 (let ((indent-to
22136 (lambda (ind pos)
22137 ;; Set IND as indentation for all lines between point and
22138 ;; POS. Blank lines are ignored. Leave point after POS
22139 ;; once done.
22140 (let ((limit (copy-marker pos)))
22141 (while (< (point) limit)
22142 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22143 (forward-line))
22144 (set-marker limit nil))))
22145 (end (copy-marker end)))
22146 (while (< (point) end)
22147 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22148 (let* ((element (org-element-at-point))
22149 (type (org-element-type element))
22150 (element-end (copy-marker (org-element-property :end element)))
22151 (ind (org--get-expected-indentation element nil)))
22152 (cond
22153 ;; Element indented as a single block. Example blocks
22154 ;; preserving indentation are a special case since the
22155 ;; "contents" must not be indented whereas the block
22156 ;; boundaries can.
22157 ((or (memq type '(export-block latex-environment))
22158 (and (eq type 'example-block)
22159 (not
22160 (or org-src-preserve-indentation
22161 (org-element-property :preserve-indent element)))))
22162 (let ((offset (- ind (org-get-indentation))))
22163 (unless (zerop offset)
22164 (indent-rigidly (org-element-property :begin element)
22165 (org-element-property :end element)
22166 offset)))
22167 (goto-char element-end))
22168 ;; Elements indented line wise. Be sure to exclude
22169 ;; example blocks (preserving indentation) and source
22170 ;; blocks from this category as they are treated
22171 ;; specially later.
22172 ((or (memq type '(paragraph table table-row))
22173 (not (or (org-element-property :contents-begin element)
22174 (memq type '(example-block src-block)))))
22175 (when (eq type 'node-property)
22176 (org--align-node-property)
22177 (beginning-of-line))
22178 (funcall indent-to ind (min element-end end)))
22179 ;; Elements consisting of three parts: before the
22180 ;; contents, the contents, and after the contents. The
22181 ;; contents are treated specially, according to the
22182 ;; element type, or not indented at all. Other parts are
22183 ;; indented as a single block.
22185 (let* ((post (copy-marker
22186 (org-element-property :post-affiliated element)))
22187 (cbeg
22188 (copy-marker
22189 (cond
22190 ((not (org-element-property :contents-begin element))
22191 ;; Fake contents for source blocks.
22192 (org-with-wide-buffer
22193 (goto-char post)
22194 (line-beginning-position 2)))
22195 ((memq type '(footnote-definition item plain-list))
22196 ;; Contents in these elements could start on
22197 ;; the same line as the beginning of the
22198 ;; element. Make sure we start indenting
22199 ;; from the second line.
22200 (org-with-wide-buffer
22201 (goto-char post)
22202 (end-of-line)
22203 (skip-chars-forward " \r\t\n")
22204 (if (eobp) (point) (line-beginning-position))))
22205 (t (org-element-property :contents-begin element)))))
22206 (cend (copy-marker
22207 (or (org-element-property :contents-end element)
22208 ;; Fake contents for source blocks.
22209 (org-with-wide-buffer
22210 (goto-char element-end)
22211 (skip-chars-backward " \r\t\n")
22212 (line-beginning-position)))
22213 t)))
22214 ;; Do not change items indentation individually as it
22215 ;; might break the list as a whole. On the other
22216 ;; hand, when at a plain list, indent it as a whole.
22217 (cond ((eq type 'plain-list)
22218 (let ((offset (- ind (org-get-indentation))))
22219 (unless (zerop offset)
22220 (indent-rigidly (org-element-property :begin element)
22221 (org-element-property :end element)
22222 offset))
22223 (goto-char cbeg)))
22224 ((eq type 'item) (goto-char cbeg))
22225 (t (funcall indent-to ind (min cbeg end))))
22226 (when (< (point) end)
22227 (cl-case type
22228 ((example-block verse-block))
22229 (src-block
22230 ;; In a source block, indent source code
22231 ;; according to language major mode, but only if
22232 ;; `org-src-tab-acts-natively' is non-nil.
22233 (when (and (< (point) end) org-src-tab-acts-natively)
22234 (ignore-errors
22235 (org-babel-do-in-edit-buffer
22236 (indent-region (point-min) (point-max))))))
22237 (t (org-indent-region (point) (min cend end))))
22238 (goto-char (min cend end))
22239 (when (< (point) end)
22240 (funcall indent-to ind (min element-end end))))
22241 (set-marker post nil)
22242 (set-marker cbeg nil)
22243 (set-marker cend nil))))
22244 (set-marker element-end nil))))
22245 (set-marker end nil))))
22247 (defun org-indent-drawer ()
22248 "Indent the drawer at point."
22249 (interactive)
22250 (unless (save-excursion
22251 (beginning-of-line)
22252 (looking-at-p org-drawer-regexp))
22253 (user-error "Not at a drawer"))
22254 (let ((element (org-element-at-point)))
22255 (unless (memq (org-element-type element) '(drawer property-drawer))
22256 (user-error "Not at a drawer"))
22257 (org-with-wide-buffer
22258 (org-indent-region (org-element-property :begin element)
22259 (org-element-property :end element))))
22260 (message "Drawer at point indented"))
22262 (defun org-indent-block ()
22263 "Indent the block at point."
22264 (interactive)
22265 (unless (save-excursion
22266 (beginning-of-line)
22267 (let ((case-fold-search t))
22268 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22269 (user-error "Not at a block"))
22270 (let ((element (org-element-at-point)))
22271 (unless (memq (org-element-type element)
22272 '(comment-block center-block dynamic-block example-block
22273 export-block quote-block special-block
22274 src-block verse-block))
22275 (user-error "Not at a block"))
22276 (org-with-wide-buffer
22277 (org-indent-region (org-element-property :begin element)
22278 (org-element-property :end element))))
22279 (message "Block at point indented"))
22282 ;;; Filling
22284 ;; We use our own fill-paragraph and auto-fill functions.
22286 ;; `org-fill-paragraph' relies on adaptive filling and context
22287 ;; checking. Appropriate `fill-prefix' is computed with
22288 ;; `org-adaptive-fill-function'.
22290 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22291 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22292 ;; `org-adaptive-fill-function' value. Internally,
22293 ;; `org-comment-line-break-function' breaks the line.
22295 ;; `org-setup-filling' installs filling and auto-filling related
22296 ;; variables during `org-mode' initialization.
22298 (defun org-setup-filling ()
22299 (require 'org-element)
22300 ;; Prevent auto-fill from inserting unwanted new items.
22301 (when (boundp 'fill-nobreak-predicate)
22302 (setq-local
22303 fill-nobreak-predicate
22304 (org-uniquify
22305 (append fill-nobreak-predicate
22306 '(org-fill-line-break-nobreak-p
22307 org-fill-n-macro-as-item-nobreak-p
22308 org-fill-paragraph-with-timestamp-nobreak-p)))))
22309 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22310 (setq-local paragraph-start paragraph-ending)
22311 (setq-local paragraph-separate paragraph-ending))
22312 (setq-local fill-paragraph-function 'org-fill-paragraph)
22313 (setq-local auto-fill-inhibit-regexp nil)
22314 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22315 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22316 (setq-local comment-line-break-function 'org-comment-line-break-function))
22318 (defun org-fill-line-break-nobreak-p ()
22319 "Non-nil when a new line at point would create an Org line break."
22320 (save-excursion
22321 (skip-chars-backward "[ \t]")
22322 (skip-chars-backward "\\\\")
22323 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22325 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22326 "Non-nil when a new line at point would split a timestamp."
22327 (and (org-at-timestamp-p 'lax)
22328 (not (looking-at org-ts-regexp-both))))
22330 (defun org-fill-n-macro-as-item-nobreak-p ()
22331 "Non-nil when a new line at point would create a new list."
22332 ;; During export, a "n" macro followed by a dot or a closing
22333 ;; parenthesis can end up being parsed as a new list item.
22334 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22336 (declare-function message-in-body-p "message" ())
22337 (defvar orgtbl-line-start-regexp) ; From org-table.el
22338 (defun org-adaptive-fill-function ()
22339 "Compute a fill prefix for the current line.
22340 Return fill prefix, as a string, or nil if current line isn't
22341 meant to be filled. For convenience, if `adaptive-fill-regexp'
22342 matches in paragraphs or comments, use it."
22343 (catch 'exit
22344 (when (derived-mode-p 'message-mode)
22345 (save-excursion
22346 (beginning-of-line)
22347 (cond ((not (message-in-body-p)) (throw 'exit nil))
22348 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22349 ((looking-at message-cite-prefix-regexp)
22350 (throw 'exit (match-string-no-properties 0)))
22351 ((looking-at org-outline-regexp)
22352 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22353 (org-with-wide-buffer
22354 (unless (org-at-heading-p)
22355 (let* ((p (line-beginning-position))
22356 (element (save-excursion
22357 (beginning-of-line)
22358 (org-element-at-point)))
22359 (type (org-element-type element))
22360 (post-affiliated (org-element-property :post-affiliated element)))
22361 (unless (< p post-affiliated)
22362 (cl-case type
22363 (comment
22364 (save-excursion
22365 (beginning-of-line)
22366 (looking-at "[ \t]*")
22367 (concat (match-string 0) "# ")))
22368 (footnote-definition "")
22369 ((item plain-list)
22370 (make-string (org-list-item-body-column post-affiliated) ?\s))
22371 (paragraph
22372 ;; Fill prefix is usually the same as the current line,
22373 ;; unless the paragraph is at the beginning of an item.
22374 (let ((parent (org-element-property :parent element)))
22375 (save-excursion
22376 (beginning-of-line)
22377 (cond ((eq (org-element-type parent) 'item)
22378 (make-string (org-list-item-body-column
22379 (org-element-property :begin parent))
22380 ?\s))
22381 ((and adaptive-fill-regexp
22382 ;; Locally disable
22383 ;; `adaptive-fill-function' to let
22384 ;; `fill-context-prefix' handle
22385 ;; `adaptive-fill-regexp' variable.
22386 (let (adaptive-fill-function)
22387 (fill-context-prefix
22388 post-affiliated
22389 (org-element-property :end element)))))
22390 ((looking-at "[ \t]+") (match-string 0))
22391 (t "")))))
22392 (comment-block
22393 ;; Only fill contents if P is within block boundaries.
22394 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22395 (forward-line)
22396 (point)))
22397 (cend (save-excursion
22398 (goto-char (org-element-property :end element))
22399 (skip-chars-backward " \r\t\n")
22400 (line-beginning-position))))
22401 (when (and (>= p cbeg) (< p cend))
22402 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22403 (match-string 0)
22404 "")))))))))))
22406 (declare-function message-goto-body "message" ())
22407 (defvar message-cite-prefix-regexp) ; From message.el
22409 (defun org-fill-element (&optional justify)
22410 "Fill element at point, when applicable.
22412 This function only applies to comment blocks, comments, example
22413 blocks and paragraphs. Also, as a special case, re-align table
22414 when point is at one.
22416 If JUSTIFY is non-nil (interactively, with prefix argument),
22417 justify as well. If `sentence-end-double-space' is non-nil, then
22418 period followed by one space does not end a sentence, so don't
22419 break a line there. The variable `fill-column' controls the
22420 width for filling.
22422 For convenience, when point is at a plain list, an item or
22423 a footnote definition, try to fill the first paragraph within."
22424 (with-syntax-table org-mode-transpose-word-syntax-table
22425 ;; Move to end of line in order to get the first paragraph within
22426 ;; a plain list or a footnote definition.
22427 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22428 ;; First check if point is in a blank line at the beginning of
22429 ;; the buffer. In that case, ignore filling.
22430 (cl-case (org-element-type element)
22431 ;; Use major mode filling function is src blocks.
22432 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22433 ;; Align Org tables, leave table.el tables as-is.
22434 (table-row (org-table-align) t)
22435 (table
22436 (when (eq (org-element-property :type element) 'org)
22437 (save-excursion
22438 (goto-char (org-element-property :post-affiliated element))
22439 (org-table-align)))
22441 (paragraph
22442 ;; Paragraphs may contain `line-break' type objects.
22443 (let ((beg (max (point-min)
22444 (org-element-property :contents-begin element)))
22445 (end (min (point-max)
22446 (org-element-property :contents-end element))))
22447 ;; Do nothing if point is at an affiliated keyword.
22448 (if (< (line-end-position) beg) t
22449 (when (derived-mode-p 'message-mode)
22450 ;; In `message-mode', do not fill following citation
22451 ;; in current paragraph nor text before message body.
22452 (let ((body-start (save-excursion (message-goto-body))))
22453 (when body-start (setq beg (max body-start beg))))
22454 (when (save-excursion
22455 (re-search-forward
22456 (concat "^" message-cite-prefix-regexp) end t))
22457 (setq end (match-beginning 0))))
22458 ;; Fill paragraph, taking line breaks into account.
22459 (save-excursion
22460 (goto-char beg)
22461 (let ((cuts (list beg)))
22462 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22463 (when (eq 'line-break
22464 (org-element-type
22465 (save-excursion (backward-char)
22466 (org-element-context))))
22467 (push (point) cuts)))
22468 (dolist (c (delq end cuts))
22469 (fill-region-as-paragraph c end justify)
22470 (setq end c))))
22471 t)))
22472 ;; Contents of `comment-block' type elements should be
22473 ;; filled as plain text, but only if point is within block
22474 ;; markers.
22475 (comment-block
22476 (let* ((case-fold-search t)
22477 (beg (save-excursion
22478 (goto-char (org-element-property :begin element))
22479 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22480 (forward-line)
22481 (point)))
22482 (end (save-excursion
22483 (goto-char (org-element-property :end element))
22484 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22485 (line-beginning-position))))
22486 (if (or (< (point) beg) (> (point) end)) t
22487 (fill-region-as-paragraph
22488 (save-excursion (end-of-line)
22489 (re-search-backward "^[ \t]*$" beg 'move)
22490 (line-beginning-position))
22491 (save-excursion (beginning-of-line)
22492 (re-search-forward "^[ \t]*$" end 'move)
22493 (line-beginning-position))
22494 justify))))
22495 ;; Fill comments.
22496 (comment
22497 (let ((begin (org-element-property :post-affiliated element))
22498 (end (org-element-property :end element)))
22499 (when (and (>= (point) begin) (<= (point) end))
22500 (let ((begin (save-excursion
22501 (end-of-line)
22502 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22503 (progn (forward-line) (point))
22504 begin)))
22505 (end (save-excursion
22506 (end-of-line)
22507 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22508 (1- (line-beginning-position))
22509 (skip-chars-backward " \r\t\n")
22510 (line-end-position)))))
22511 ;; Do not fill comments when at a blank line.
22512 (when (> end begin)
22513 (let ((fill-prefix
22514 (save-excursion
22515 (beginning-of-line)
22516 (looking-at "[ \t]*#")
22517 (let ((comment-prefix (match-string 0)))
22518 (goto-char (match-end 0))
22519 (if (looking-at adaptive-fill-regexp)
22520 (concat comment-prefix (match-string 0))
22521 (concat comment-prefix " "))))))
22522 (save-excursion
22523 (fill-region-as-paragraph begin end justify))))))
22525 ;; Ignore every other element.
22526 (otherwise t)))))
22528 (defun org-fill-paragraph (&optional justify region)
22529 "Fill element at point, when applicable.
22531 This function only applies to comment blocks, comments, example
22532 blocks and paragraphs. Also, as a special case, re-align table
22533 when point is at one.
22535 For convenience, when point is at a plain list, an item or
22536 a footnote definition, try to fill the first paragraph within.
22538 If JUSTIFY is non-nil (interactively, with prefix argument),
22539 justify as well. If `sentence-end-double-space' is non-nil, then
22540 period followed by one space does not end a sentence, so don't
22541 break a line there. The variable `fill-column' controls the
22542 width for filling.
22544 The REGION argument is non-nil if called interactively; in that
22545 case, if Transient Mark mode is enabled and the mark is active,
22546 fill each of the elements in the active region, instead of just
22547 filling the current element."
22548 (interactive (progn
22549 (barf-if-buffer-read-only)
22550 (list (if current-prefix-arg 'full) t)))
22551 (cond
22552 ((and (derived-mode-p 'message-mode)
22553 (or (not (message-in-body-p))
22554 (save-excursion (move-beginning-of-line 1)
22555 (looking-at message-cite-prefix-regexp))))
22556 ;; First ensure filling is correct in message-mode.
22557 (let ((fill-paragraph-function
22558 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22559 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22560 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22561 (paragraph-separate
22562 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22563 (fill-paragraph nil)))
22564 ((and region transient-mark-mode mark-active
22565 (not (eq (region-beginning) (region-end))))
22566 (let ((origin (point-marker))
22567 (start (region-beginning)))
22568 (unwind-protect
22569 (progn
22570 (goto-char (region-end))
22571 (while (> (point) start)
22572 (org-backward-paragraph)
22573 (org-fill-element justify)))
22574 (goto-char origin)
22575 (set-marker origin nil))))
22576 (t (org-fill-element justify))))
22577 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22579 (defun org-auto-fill-function ()
22580 "Auto-fill function."
22581 ;; Check if auto-filling is meaningful.
22582 (let ((fc (current-fill-column)))
22583 (when (and fc (> (current-column) fc))
22584 (let* ((fill-prefix (org-adaptive-fill-function))
22585 ;; Enforce empty fill prefix, if required. Otherwise, it
22586 ;; will be computed again.
22587 (adaptive-fill-mode (not (equal fill-prefix ""))))
22588 (when fill-prefix (do-auto-fill))))))
22590 (defun org-comment-line-break-function (&optional soft)
22591 "Break line at point and indent, continuing comment if within one.
22592 The inserted newline is marked hard if variable
22593 `use-hard-newlines' is true, unless optional argument SOFT is
22594 non-nil."
22595 (if soft (insert-and-inherit ?\n) (newline 1))
22596 (save-excursion (forward-char -1) (delete-horizontal-space))
22597 (delete-horizontal-space)
22598 (indent-to-left-margin)
22599 (insert-before-markers-and-inherit fill-prefix))
22602 ;;; Fixed Width Areas
22604 (defun org-toggle-fixed-width ()
22605 "Toggle fixed-width markup.
22607 Add or remove fixed-width markup on current line, whenever it
22608 makes sense. Return an error otherwise.
22610 If a region is active and if it contains only fixed-width areas
22611 or blank lines, remove all fixed-width markup in it. If the
22612 region contains anything else, convert all non-fixed-width lines
22613 to fixed-width ones.
22615 Blank lines at the end of the region are ignored unless the
22616 region only contains such lines."
22617 (interactive)
22618 (if (not (org-region-active-p))
22619 ;; No region:
22621 ;; Remove fixed width marker only in a fixed-with element.
22623 ;; Add fixed width maker in paragraphs, in blank lines after
22624 ;; elements or at the beginning of a headline or an inlinetask,
22625 ;; and before any one-line elements (e.g., a clock).
22626 (progn
22627 (beginning-of-line)
22628 (let* ((element (org-element-at-point))
22629 (type (org-element-type element)))
22630 (cond
22631 ((and (eq type 'fixed-width)
22632 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22633 (replace-match
22634 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22635 ((and (memq type '(babel-call clock comment diary-sexp headline
22636 horizontal-rule keyword paragraph
22637 planning))
22638 (<= (org-element-property :post-affiliated element) (point)))
22639 (skip-chars-forward " \t")
22640 (insert ": "))
22641 ((and (looking-at-p "[ \t]*$")
22642 (or (eq type 'inlinetask)
22643 (save-excursion
22644 (skip-chars-forward " \r\t\n")
22645 (<= (org-element-property :end element) (point)))))
22646 (delete-region (point) (line-end-position))
22647 (org-indent-line)
22648 (insert ": "))
22649 (t (user-error "Cannot insert a fixed-width line here")))))
22650 ;; Region active.
22651 (let* ((begin (save-excursion
22652 (goto-char (region-beginning))
22653 (line-beginning-position)))
22654 (end (copy-marker
22655 (save-excursion
22656 (goto-char (region-end))
22657 (unless (eolp) (beginning-of-line))
22658 (if (save-excursion (re-search-backward "\\S-" begin t))
22659 (progn (skip-chars-backward " \r\t\n") (point))
22660 (point)))))
22661 (all-fixed-width-p
22662 (catch 'not-all-p
22663 (save-excursion
22664 (goto-char begin)
22665 (skip-chars-forward " \r\t\n")
22666 (when (eobp) (throw 'not-all-p nil))
22667 (while (< (point) end)
22668 (let ((element (org-element-at-point)))
22669 (if (eq (org-element-type element) 'fixed-width)
22670 (goto-char (org-element-property :end element))
22671 (throw 'not-all-p nil))))
22672 t))))
22673 (if all-fixed-width-p
22674 (save-excursion
22675 (goto-char begin)
22676 (while (< (point) end)
22677 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22678 (replace-match
22679 "" nil nil nil
22680 (if (= (line-end-position) (match-end 0)) 0 1)))
22681 (forward-line)))
22682 (let ((min-ind (point-max)))
22683 ;; Find minimum indentation across all lines.
22684 (save-excursion
22685 (goto-char begin)
22686 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22687 (setq min-ind 0)
22688 (catch 'zerop
22689 (while (< (point) end)
22690 (unless (looking-at-p "[ \t]*$")
22691 (let ((ind (org-get-indentation)))
22692 (setq min-ind (min min-ind ind))
22693 (when (zerop ind) (throw 'zerop t))))
22694 (forward-line)))))
22695 ;; Loop over all lines and add fixed-width markup everywhere
22696 ;; but in fixed-width lines.
22697 (save-excursion
22698 (goto-char begin)
22699 (while (< (point) end)
22700 (cond
22701 ((org-at-heading-p)
22702 (insert ": ")
22703 (forward-line)
22704 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22705 (insert ":")
22706 (forward-line)))
22707 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22708 (let* ((element (org-element-at-point))
22709 (element-end (org-element-property :end element)))
22710 (if (eq (org-element-type element) 'fixed-width)
22711 (progn (goto-char element-end)
22712 (skip-chars-backward " \r\t\n")
22713 (forward-line))
22714 (let ((limit (min end element-end)))
22715 (while (< (point) limit)
22716 (org-move-to-column min-ind t)
22717 (insert ": ")
22718 (forward-line))))))
22720 (org-move-to-column min-ind t)
22721 (insert ": ")
22722 (forward-line)))))))
22723 (set-marker end nil))))
22726 ;;; Comments
22728 ;; Org comments syntax is quite complex. It requires the entire line
22729 ;; to be just a comment. Also, even with the right syntax at the
22730 ;; beginning of line, some elements (e.g., verse-block or
22731 ;; example-block) don't accept comments. Usual Emacs comment commands
22732 ;; cannot cope with those requirements. Therefore, Org replaces them.
22734 ;; Org still relies on `comment-dwim', but cannot trust
22735 ;; `comment-only-p'. So, `comment-region-function' and
22736 ;; `uncomment-region-function' both point
22737 ;; to`org-comment-or-uncomment-region'. Eventually,
22738 ;; `org-insert-comment' takes care of insertion of comments at the
22739 ;; beginning of line.
22741 ;; `org-setup-comments-handling' install comments related variables
22742 ;; during `org-mode' initialization.
22744 (defun org-setup-comments-handling ()
22745 (interactive)
22746 (setq-local comment-use-syntax nil)
22747 (setq-local comment-start "# ")
22748 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22749 (setq-local comment-insert-comment-function 'org-insert-comment)
22750 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22751 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22753 (defun org-insert-comment ()
22754 "Insert an empty comment above current line.
22755 If the line is empty, insert comment at its beginning. When
22756 point is within a source block, comment according to the related
22757 major mode."
22758 (if (let ((element (org-element-at-point)))
22759 (and (eq (org-element-type element) 'src-block)
22760 (< (save-excursion
22761 (goto-char (org-element-property :post-affiliated element))
22762 (line-end-position))
22763 (point))
22764 (> (save-excursion
22765 (goto-char (org-element-property :end element))
22766 (skip-chars-backward " \r\t\n")
22767 (line-beginning-position))
22768 (point))))
22769 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22770 (beginning-of-line)
22771 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22772 (open-line 1))
22773 (org-indent-line)
22774 (insert "# ")))
22776 (defvar comment-empty-lines) ; From newcomment.el.
22777 (defun org-comment-or-uncomment-region (beg end &rest _)
22778 "Comment or uncomment each non-blank line in the region.
22779 Uncomment each non-blank line between BEG and END if it only
22780 contains commented lines. Otherwise, comment them. If region is
22781 strictly within a source block, use appropriate comment syntax."
22782 (if (let ((element (org-element-at-point)))
22783 (and (eq (org-element-type element) 'src-block)
22784 (< (save-excursion
22785 (goto-char (org-element-property :post-affiliated element))
22786 (line-end-position))
22787 beg)
22788 (>= (save-excursion
22789 (goto-char (org-element-property :end element))
22790 (skip-chars-backward " \r\t\n")
22791 (line-beginning-position))
22792 end)))
22793 ;; Translate region boundaries for the Org buffer to the source
22794 ;; buffer.
22795 (let ((offset (- end beg)))
22796 (save-excursion
22797 (goto-char beg)
22798 (org-babel-do-in-edit-buffer
22799 (comment-or-uncomment-region (point) (+ offset (point))))))
22800 (save-restriction
22801 ;; Restrict region
22802 (narrow-to-region (save-excursion (goto-char beg)
22803 (skip-chars-forward " \r\t\n" end)
22804 (line-beginning-position))
22805 (save-excursion (goto-char end)
22806 (skip-chars-backward " \r\t\n" beg)
22807 (line-end-position)))
22808 (let ((uncommentp
22809 ;; UNCOMMENTP is non-nil when every non blank line between
22810 ;; BEG and END is a comment.
22811 (save-excursion
22812 (goto-char (point-min))
22813 (while (and (not (eobp))
22814 (let ((element (org-element-at-point)))
22815 (and (eq (org-element-type element) 'comment)
22816 (goto-char (min (point-max)
22817 (org-element-property
22818 :end element)))))))
22819 (eobp))))
22820 (if uncommentp
22821 ;; Only blank lines and comments in region: uncomment it.
22822 (save-excursion
22823 (goto-char (point-min))
22824 (while (not (eobp))
22825 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22826 (replace-match "" nil nil nil 1))
22827 (forward-line)))
22828 ;; Comment each line in region.
22829 (let ((min-indent (point-max)))
22830 ;; First find the minimum indentation across all lines.
22831 (save-excursion
22832 (goto-char (point-min))
22833 (while (and (not (eobp)) (not (zerop min-indent)))
22834 (unless (looking-at "[ \t]*$")
22835 (setq min-indent (min min-indent (current-indentation))))
22836 (forward-line)))
22837 ;; Then loop over all lines.
22838 (save-excursion
22839 (goto-char (point-min))
22840 (while (not (eobp))
22841 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22842 ;; Don't get fooled by invisible text (e.g. link path)
22843 ;; when moving to column MIN-INDENT.
22844 (let ((buffer-invisibility-spec nil))
22845 (org-move-to-column min-indent t))
22846 (insert comment-start))
22847 (forward-line)))))))))
22849 (defun org-comment-dwim (_arg)
22850 "Call the comment command you mean.
22851 Call `org-toggle-comment' if on a heading, otherwise call
22852 `comment-dwim', within a source edit buffer if needed."
22853 (interactive "*P")
22854 (cond ((org-at-heading-p)
22855 (call-interactively #'org-toggle-comment))
22856 ((org-in-src-block-p)
22857 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22858 (t (call-interactively #'comment-dwim))))
22861 ;;; Timestamps API
22863 ;; This section contains tools to operate on timestamp objects, as
22864 ;; returned by, e.g. `org-element-context'.
22866 (defun org-timestamp--to-internal-time (timestamp &optional end)
22867 "Encode TIMESTAMP object into Emacs internal time.
22868 Use end of date range or time range when END is non-nil."
22869 (apply #'encode-time
22870 (cons 0
22871 (mapcar
22872 (lambda (prop) (or (org-element-property prop timestamp) 0))
22873 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22874 '(:minute-start :hour-start :day-start :month-start
22875 :year-start))))))
22877 (defun org-timestamp-has-time-p (timestamp)
22878 "Non-nil when TIMESTAMP has a time specified."
22879 (org-element-property :hour-start timestamp))
22881 (defun org-timestamp-format (timestamp format &optional end utc)
22882 "Format a TIMESTAMP object into a string.
22884 FORMAT is a format specifier to be passed to
22885 `format-time-string'.
22887 When optional argument END is non-nil, use end of date-range or
22888 time-range, if possible.
22890 When optional argument UTC is non-nil, time will be expressed as
22891 Universal Time."
22892 (format-time-string
22893 format (org-timestamp--to-internal-time timestamp end)
22894 (and utc t)))
22896 (defun org-timestamp-split-range (timestamp &optional end)
22897 "Extract a TIMESTAMP object from a date or time range.
22899 END, when non-nil, means extract the end of the range.
22900 Otherwise, extract its start.
22902 Return a new timestamp object."
22903 (let ((type (org-element-property :type timestamp)))
22904 (if (memq type '(active inactive diary)) timestamp
22905 (let ((split-ts (org-element-copy timestamp)))
22906 ;; Set new type.
22907 (org-element-put-property
22908 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22909 ;; Copy start properties over end properties if END is
22910 ;; non-nil. Otherwise, copy end properties over `start' ones.
22911 (let ((p-alist '((:minute-start . :minute-end)
22912 (:hour-start . :hour-end)
22913 (:day-start . :day-end)
22914 (:month-start . :month-end)
22915 (:year-start . :year-end))))
22916 (dolist (p-cell p-alist)
22917 (org-element-put-property
22918 split-ts
22919 (funcall (if end #'car #'cdr) p-cell)
22920 (org-element-property
22921 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22922 ;; Eventually refresh `:raw-value'.
22923 (org-element-put-property split-ts :raw-value nil)
22924 (org-element-put-property
22925 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22927 (defun org-timestamp-translate (timestamp &optional boundary)
22928 "Translate TIMESTAMP object to custom format.
22930 Format string is defined in `org-time-stamp-custom-formats',
22931 which see.
22933 When optional argument BOUNDARY is non-nil, it is either the
22934 symbol `start' or `end'. In this case, only translate the
22935 starting or ending part of TIMESTAMP if it is a date or time
22936 range. Otherwise, translate both parts.
22938 Return timestamp as-is if `org-display-custom-times' is nil or if
22939 it has a `diary' type."
22940 (let ((type (org-element-property :type timestamp)))
22941 (if (or (not org-display-custom-times) (eq type 'diary))
22942 (org-element-interpret-data timestamp)
22943 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22944 org-time-stamp-custom-formats)))
22945 (if (and (not boundary) (memq type '(active-range inactive-range)))
22946 (concat (org-timestamp-format timestamp fmt)
22947 "--"
22948 (org-timestamp-format timestamp fmt t))
22949 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22953 ;;; Other stuff.
22955 (defvar reftex-docstruct-symbol)
22956 (defvar org--rds)
22958 (defun org-reftex-citation ()
22959 "Use reftex-citation to insert a citation into the buffer.
22960 This looks for a line like
22962 #+BIBLIOGRAPHY: foo plain option:-d
22964 and derives from it that foo.bib is the bibliography file relevant
22965 for this document. It then installs the necessary environment for RefTeX
22966 to work in this buffer and calls `reftex-citation' to insert a citation
22967 into the buffer.
22969 Export of such citations to both LaTeX and HTML is handled by the contributed
22970 package ox-bibtex by Taru Karttunen."
22971 (interactive)
22972 (let ((reftex-docstruct-symbol 'org--rds)
22973 org--rds bib)
22974 (org-with-wide-buffer
22975 (let ((case-fold-search t)
22976 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22977 (if (not (save-excursion
22978 (or (re-search-forward re nil t)
22979 (re-search-backward re nil t))))
22980 (user-error "No bibliography defined in file")
22981 (setq bib (concat (match-string 1) ".bib")
22982 org--rds (list (list 'bib bib))))))
22983 (call-interactively 'reftex-citation)))
22985 ;;;; Functions extending outline functionality
22987 (defun org-beginning-of-line (&optional n)
22988 "Go to the beginning of the current visible line.
22990 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22991 tags on the first attempt, and only move to after the tags when
22992 the cursor is already beyond the end of the headline.
22994 With argument N not nil or 1, move forward N - 1 lines first."
22995 (interactive "^p")
22996 (let ((origin (point))
22997 (special (pcase org-special-ctrl-a/e
22998 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22999 deactivate-mark)
23000 ;; First move to a visible line.
23001 (if (bound-and-true-p visual-line-mode)
23002 (beginning-of-visual-line n)
23003 (move-beginning-of-line n)
23004 ;; `move-beginning-of-line' may leave point after invisible
23005 ;; characters if line starts with such of these (e.g., with
23006 ;; a link at column 0). Really move to the beginning of the
23007 ;; current visible line.
23008 (beginning-of-line))
23009 (cond
23010 ;; No special behavior. Point is already at the beginning of
23011 ;; a line, logical or visual.
23012 ((not special))
23013 ;; `beginning-of-visual-line' left point before logical beginning
23014 ;; of line: point is at the beginning of a visual line. Bail
23015 ;; out.
23016 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23017 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23018 ;; At a headline, special position is before the title, but
23019 ;; after any TODO keyword or priority cookie.
23020 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23021 (line-end-position)))
23022 (bol (point)))
23023 (if (eq special 'reversed)
23024 (when (and (= origin bol) (eq last-command this-command))
23025 (goto-char refpos))
23026 (when (or (> origin refpos) (= origin bol))
23027 (goto-char refpos)))))
23028 ((and (looking-at org-list-full-item-re)
23029 (memq (org-element-type (save-match-data (org-element-at-point)))
23030 '(item plain-list)))
23031 ;; Set special position at first white space character after
23032 ;; bullet, and check-box, if any.
23033 (let ((after-bullet
23034 (let ((box (match-end 3)))
23035 (cond ((not box) (match-end 1))
23036 ((eq (char-after box) ?\s) (1+ box))
23037 (t box)))))
23038 (if (eq special 'reversed)
23039 (when (and (= (point) origin) (eq last-command this-command))
23040 (goto-char after-bullet))
23041 (when (or (> origin after-bullet) (= (point) origin))
23042 (goto-char after-bullet)))))
23043 ;; No special context. Point is already at beginning of line.
23044 (t nil))))
23046 (defun org-end-of-line (&optional n)
23047 "Go to the end of the line, but before ellipsis, if any.
23049 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23050 tags on the first attempt, and only move to after the tags when
23051 the cursor is already beyond the end of the headline.
23053 With argument N not nil or 1, move forward N - 1 lines first."
23054 (interactive "^p")
23055 (let ((origin (point))
23056 (special (pcase org-special-ctrl-a/e
23057 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23058 deactivate-mark)
23059 ;; First move to a visible line.
23060 (if (bound-and-true-p visual-line-mode)
23061 (beginning-of-visual-line n)
23062 (move-beginning-of-line n))
23063 (cond
23064 ;; At a headline, with tags.
23065 ((and special
23066 (save-excursion
23067 (beginning-of-line)
23068 (let ((case-fold-search nil))
23069 (looking-at org-complex-heading-regexp)))
23070 (match-end 5))
23071 (let ((tags (save-excursion
23072 (goto-char (match-beginning 5))
23073 (skip-chars-backward " \t")
23074 (point)))
23075 (visual-end (and (bound-and-true-p visual-line-mode)
23076 (save-excursion
23077 (end-of-visual-line)
23078 (point)))))
23079 ;; If `end-of-visual-line' brings us before end of line or
23080 ;; even tags, i.e., the headline spans over multiple visual
23081 ;; lines, move there.
23082 (cond ((and visual-end
23083 (< visual-end tags)
23084 (<= origin visual-end))
23085 (goto-char visual-end))
23086 ((eq special 'reversed)
23087 (if (and (= origin (line-end-position))
23088 (eq this-command last-command))
23089 (goto-char tags)
23090 (end-of-line)))
23092 (if (or (< origin tags) (= origin (line-end-position)))
23093 (goto-char tags)
23094 (end-of-line))))))
23095 ((bound-and-true-p visual-line-mode)
23096 (let ((bol (line-beginning-position)))
23097 (end-of-visual-line)
23098 ;; If `end-of-visual-line' gets us past the ellipsis at the
23099 ;; end of a line, backtrack and use `end-of-line' instead.
23100 (when (/= bol (line-beginning-position))
23101 (goto-char bol)
23102 (end-of-line))))
23103 (t (end-of-line)))))
23105 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23106 (define-key org-mode-map "\C-e" 'org-end-of-line)
23108 (defun org-backward-sentence (&optional _arg)
23109 "Go to beginning of sentence, or beginning of table field.
23110 This will call `backward-sentence' or `org-table-beginning-of-field',
23111 depending on context."
23112 (interactive)
23113 (let* ((element (org-element-at-point))
23114 (contents-begin (org-element-property :contents-begin element))
23115 (table (org-element-lineage element '(table) t)))
23116 (if (and table
23117 (> (point) contents-begin)
23118 (<= (point) (org-element-property :contents-end table)))
23119 (call-interactively #'org-table-beginning-of-field)
23120 (save-restriction
23121 (when (and contents-begin
23122 (< (point-min) contents-begin)
23123 (> (point) contents-begin))
23124 (narrow-to-region contents-begin
23125 (org-element-property :contents-end element)))
23126 (call-interactively #'backward-sentence)))))
23128 (defun org-forward-sentence (&optional _arg)
23129 "Go to end of sentence, or end of table field.
23130 This will call `forward-sentence' or `org-table-end-of-field',
23131 depending on context."
23132 (interactive)
23133 (if (and (org-at-heading-p)
23134 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23135 (save-restriction
23136 (narrow-to-region (line-beginning-position) (line-end-position))
23137 (call-interactively #'forward-sentence))
23138 (let* ((element (org-element-at-point))
23139 (contents-end (org-element-property :contents-end element))
23140 (table (org-element-lineage element '(table) t)))
23141 (if (and table
23142 (>= (point) (org-element-property :contents-begin table))
23143 (< (point) contents-end))
23144 (call-interactively #'org-table-end-of-field)
23145 (save-restriction
23146 (when (and contents-end
23147 (> (point-max) contents-end)
23148 ;; Skip blank lines between elements.
23149 (< (org-element-property :end element)
23150 (save-excursion (goto-char contents-end)
23151 (skip-chars-forward " \r\t\n"))))
23152 (narrow-to-region (org-element-property :contents-begin element)
23153 contents-end))
23154 ;; End of heading is considered as the end of a sentence.
23155 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23156 (call-interactively #'forward-sentence)))))))
23158 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23159 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23161 (defun org-kill-line (&optional _arg)
23162 "Kill line, to tags or end of line."
23163 (interactive)
23164 (cond
23165 ((or (not org-special-ctrl-k)
23166 (bolp)
23167 (not (org-at-heading-p)))
23168 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23169 org-ctrl-k-protect-subtree
23170 (or (eq org-ctrl-k-protect-subtree 'error)
23171 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23172 (user-error "C-k aborted as it would kill a hidden subtree"))
23173 (call-interactively
23174 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23175 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23176 (kill-region (point) (match-beginning 1))
23177 (org-set-tags nil t))
23178 (t (kill-region (point) (point-at-eol)))))
23180 (define-key org-mode-map "\C-k" 'org-kill-line)
23182 (defun org-yank (&optional arg)
23183 "Yank. If the kill is a subtree, treat it specially.
23184 This command will look at the current kill and check if is a single
23185 subtree, or a series of subtrees[1]. If it passes the test, and if the
23186 cursor is at the beginning of a line or after the stars of a currently
23187 empty headline, then the yank is handled specially. How exactly depends
23188 on the value of the following variables.
23190 `org-yank-folded-subtrees'
23191 By default, this variable is non-nil, which results in
23192 subtree(s) being folded after insertion, except if doing so
23193 would swallow text after the yanked text.
23195 `org-yank-adjusted-subtrees'
23196 When non-nil (the default value is nil), the subtree will be
23197 promoted or demoted in order to fit into the local outline tree
23198 structure, which means that the level will be adjusted so that it
23199 becomes the smaller one of the two *visible* surrounding headings.
23201 Any prefix to this command will cause `yank' to be called directly with
23202 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23203 will just
23204 plainly yank the text as it is.
23206 \[1] The test checks if the first non-white line is a heading
23207 and if there are no other headings with fewer stars."
23208 (interactive "P")
23209 (org-yank-generic 'yank arg))
23211 (defun org-yank-generic (command arg)
23212 "Perform some yank-like command.
23214 This function implements the behavior described in the `org-yank'
23215 documentation. However, it has been generalized to work for any
23216 interactive command with similar behavior."
23218 ;; pretend to be command COMMAND
23219 (setq this-command command)
23221 (if arg
23222 (call-interactively command)
23224 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23225 (and (org-kill-is-subtree-p)
23226 (or (bolp)
23227 (and (looking-at "[ \t]*$")
23228 (string-match
23229 "\\`\\*+\\'"
23230 (buffer-substring (point-at-bol) (point)))))))
23231 swallowp)
23232 (cond
23233 ((and subtreep org-yank-folded-subtrees)
23234 (let ((beg (point))
23235 end)
23236 (if (and subtreep org-yank-adjusted-subtrees)
23237 (org-paste-subtree nil nil 'for-yank)
23238 (call-interactively command))
23240 (setq end (point))
23241 (goto-char beg)
23242 (when (and (bolp) subtreep
23243 (not (setq swallowp
23244 (org-yank-folding-would-swallow-text beg end))))
23245 (org-with-limited-levels
23246 (or (looking-at org-outline-regexp)
23247 (re-search-forward org-outline-regexp-bol end t))
23248 (while (and (< (point) end) (looking-at org-outline-regexp))
23249 (outline-hide-subtree)
23250 (org-cycle-show-empty-lines 'folded)
23251 (condition-case nil
23252 (outline-forward-same-level 1)
23253 (error (goto-char end))))))
23254 (when swallowp
23255 (message
23256 "Inserted text not folded because that would swallow text"))
23258 (goto-char end)
23259 (skip-chars-forward " \t\n\r")
23260 (beginning-of-line 1)
23261 (push-mark beg 'nomsg)))
23262 ((and subtreep org-yank-adjusted-subtrees)
23263 (let ((beg (point-at-bol)))
23264 (org-paste-subtree nil nil 'for-yank)
23265 (push-mark beg 'nomsg)))
23267 (call-interactively command))))))
23269 (defun org-yank-folding-would-swallow-text (beg end)
23270 "Would hide-subtree at BEG swallow any text after END?"
23271 (let (level)
23272 (org-with-limited-levels
23273 (save-excursion
23274 (goto-char beg)
23275 (when (or (looking-at org-outline-regexp)
23276 (re-search-forward org-outline-regexp-bol end t))
23277 (setq level (org-outline-level)))
23278 (goto-char end)
23279 (skip-chars-forward " \t\r\n\v\f")
23280 (not (or (eobp)
23281 (and (bolp) (looking-at-p org-outline-regexp)
23282 (<= (org-outline-level) level))))))))
23284 (define-key org-mode-map "\C-y" 'org-yank)
23286 (defun org-back-to-heading (&optional invisible-ok)
23287 "Call `outline-back-to-heading', but provide a better error message."
23288 (condition-case nil
23289 (outline-back-to-heading invisible-ok)
23290 (error (error "Before first headline at position %d in buffer %s"
23291 (point) (current-buffer)))))
23293 (defun org-before-first-heading-p ()
23294 "Before first heading?"
23295 (save-excursion
23296 (end-of-line)
23297 (null (re-search-backward org-outline-regexp-bol nil t))))
23299 (defun org-at-heading-p (&optional ignored)
23300 (outline-on-heading-p t))
23302 (defun org-in-commented-heading-p (&optional no-inheritance)
23303 "Non-nil if point is under a commented heading.
23304 This function also checks ancestors of the current headline,
23305 unless optional argument NO-INHERITANCE is non-nil."
23306 (cond
23307 ((org-before-first-heading-p) nil)
23308 ((let ((headline (nth 4 (org-heading-components))))
23309 (and headline
23310 (let ((case-fold-search nil))
23311 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23312 headline)))))
23313 (no-inheritance nil)
23315 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23317 (defun org-at-comment-p nil
23318 "Is cursor in a commented line?"
23319 (save-excursion
23320 (save-match-data
23321 (beginning-of-line)
23322 (looking-at "^[ \t]*# "))))
23324 (defun org-at-drawer-p nil
23325 "Is cursor at a drawer keyword?"
23326 (save-excursion
23327 (move-beginning-of-line 1)
23328 (looking-at org-drawer-regexp)))
23330 (defun org-at-block-p nil
23331 "Is cursor at a block keyword?"
23332 (save-excursion
23333 (move-beginning-of-line 1)
23334 (looking-at org-block-regexp)))
23336 (defun org-point-at-end-of-empty-headline ()
23337 "If point is at the end of an empty headline, return t, else nil.
23338 If the heading only contains a TODO keyword, it is still still considered
23339 empty."
23340 (let ((case-fold-search nil))
23341 (and (looking-at "[ \t]*$")
23342 org-todo-line-regexp
23343 (save-excursion
23344 (beginning-of-line)
23345 (looking-at org-todo-line-regexp)
23346 (string= (match-string 3) "")))))
23348 (defun org-at-heading-or-item-p ()
23349 (or (org-at-heading-p) (org-at-item-p)))
23351 (defun org-at-target-p ()
23352 (or (org-in-regexp org-radio-target-regexp)
23353 (org-in-regexp org-target-regexp)))
23354 ;; Compatibility alias with Org versions < 7.8.03
23355 (defalias 'org-on-target-p 'org-at-target-p)
23357 (defun org-up-heading-all (arg)
23358 "Move to the heading line of which the present line is a subheading.
23359 This function considers both visible and invisible heading lines.
23360 With argument, move up ARG levels."
23361 (outline-up-heading arg t))
23363 (defun org-up-heading-safe ()
23364 "Move to the heading line of which the present line is a subheading.
23365 This version will not throw an error. It will return the level of the
23366 headline found, or nil if no higher level is found.
23368 Also, this function will be a lot faster than `outline-up-heading',
23369 because it relies on stars being the outline starters. This can really
23370 make a significant difference in outlines with very many siblings."
23371 (when (ignore-errors (org-back-to-heading t))
23372 (let ((level-up (1- (funcall outline-level))))
23373 (and (> level-up 0)
23374 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23375 (funcall outline-level)))))
23377 (defun org-first-sibling-p ()
23378 "Is this heading the first child of its parents?"
23379 (interactive)
23380 (let ((re org-outline-regexp-bol)
23381 level l)
23382 (unless (org-at-heading-p t)
23383 (user-error "Not at a heading"))
23384 (setq level (funcall outline-level))
23385 (save-excursion
23386 (if (not (re-search-backward re nil t))
23388 (setq l (funcall outline-level))
23389 (< l level)))))
23391 (defun org-goto-sibling (&optional previous)
23392 "Goto the next sibling, even if it is invisible.
23393 When PREVIOUS is set, go to the previous sibling instead. Returns t
23394 when a sibling was found. When none is found, return nil and don't
23395 move point."
23396 (let ((fun (if previous 're-search-backward 're-search-forward))
23397 (pos (point))
23398 (re org-outline-regexp-bol)
23399 level l)
23400 (when (ignore-errors (org-back-to-heading t))
23401 (setq level (funcall outline-level))
23402 (catch 'exit
23403 (or previous (forward-char 1))
23404 (while (funcall fun re nil t)
23405 (setq l (funcall outline-level))
23406 (when (< l level) (goto-char pos) (throw 'exit nil))
23407 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23408 (goto-char pos)
23409 nil))))
23411 (defun org-show-siblings ()
23412 "Show all siblings of the current headline."
23413 (save-excursion
23414 (while (org-goto-sibling) (org-flag-heading nil)))
23415 (save-excursion
23416 (while (org-goto-sibling 'previous)
23417 (org-flag-heading nil))))
23419 (defun org-goto-first-child ()
23420 "Goto the first child, even if it is invisible.
23421 Return t when a child was found. Otherwise don't move point and
23422 return nil."
23423 (let (level (pos (point)) (re org-outline-regexp-bol))
23424 (when (ignore-errors (org-back-to-heading t))
23425 (setq level (outline-level))
23426 (forward-char 1)
23427 (if (and (re-search-forward re nil t) (> (outline-level) level))
23428 (progn (goto-char (match-beginning 0)) t)
23429 (goto-char pos) nil))))
23431 (defun org-show-hidden-entry ()
23432 "Show an entry where even the heading is hidden."
23433 (save-excursion
23434 (org-show-entry)))
23436 (defun org-flag-heading (flag &optional entry)
23437 "Flag the current heading. FLAG non-nil means make invisible.
23438 When ENTRY is non-nil, show the entire entry."
23439 (save-excursion
23440 (org-back-to-heading t)
23441 ;; Check if we should show the entire entry
23442 (if entry
23443 (progn
23444 (org-show-entry)
23445 (save-excursion
23446 (and (outline-next-heading)
23447 (org-flag-heading nil))))
23448 (outline-flag-region (max (point-min) (1- (point)))
23449 (save-excursion (outline-end-of-heading) (point))
23450 flag))))
23452 (defun org-get-next-sibling ()
23453 "Move to next heading of the same level, and return point.
23454 If there is no such heading, return nil.
23455 This is like outline-next-sibling, but invisible headings are ok."
23456 (let ((level (funcall outline-level)))
23457 (outline-next-heading)
23458 (while (and (not (eobp)) (> (funcall outline-level) level))
23459 (outline-next-heading))
23460 (unless (or (eobp) (< (funcall outline-level) level))
23461 (point))))
23463 (defun org-get-last-sibling ()
23464 "Move to previous heading of the same level, and return point.
23465 If there is no such heading, return nil."
23466 (let ((opoint (point))
23467 (level (funcall outline-level)))
23468 (outline-previous-heading)
23469 (when (and (/= (point) opoint) (outline-on-heading-p t))
23470 (while (and (> (funcall outline-level) level)
23471 (not (bobp)))
23472 (outline-previous-heading))
23473 (unless (< (funcall outline-level) level)
23474 (point)))))
23476 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23477 "Goto to the end of a subtree."
23478 ;; This contains an exact copy of the original function, but it uses
23479 ;; `org-back-to-heading', to make it work also in invisible
23480 ;; trees. And is uses an invisible-ok argument.
23481 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23482 ;; Furthermore, when used inside Org, finding the end of a large subtree
23483 ;; with many children and grandchildren etc, this can be much faster
23484 ;; than the outline version.
23485 (org-back-to-heading invisible-ok)
23486 (let ((first t)
23487 (level (funcall outline-level)))
23488 (if (and (derived-mode-p 'org-mode) (< level 1000))
23489 ;; A true heading (not a plain list item), in Org
23490 ;; This means we can easily find the end by looking
23491 ;; only for the right number of stars. Using a regexp to do
23492 ;; this is so much faster than using a Lisp loop.
23493 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23494 (forward-char 1)
23495 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23496 ;; something else, do it the slow way
23497 (while (and (not (eobp))
23498 (or first (> (funcall outline-level) level)))
23499 (setq first nil)
23500 (outline-next-heading)))
23501 (unless to-heading
23502 (when (memq (preceding-char) '(?\n ?\^M))
23503 ;; Go to end of line before heading
23504 (forward-char -1)
23505 (when (memq (preceding-char) '(?\n ?\^M))
23506 ;; leave blank line before heading
23507 (forward-char -1)))))
23508 (point))
23510 (defun org-end-of-meta-data (&optional full)
23511 "Skip planning line and properties drawer in current entry.
23512 When optional argument FULL is non-nil, also skip empty lines,
23513 clocking lines and regular drawers at the beginning of the
23514 entry."
23515 (org-back-to-heading t)
23516 (forward-line)
23517 (when (looking-at-p org-planning-line-re) (forward-line))
23518 (when (looking-at org-property-drawer-re)
23519 (goto-char (match-end 0))
23520 (forward-line))
23521 (when (and full (not (org-at-heading-p)))
23522 (catch 'exit
23523 (let ((end (save-excursion (outline-next-heading) (point)))
23524 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23525 (while (not (eobp))
23526 (cond ((looking-at-p org-drawer-regexp)
23527 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23528 (forward-line)
23529 (throw 'exit t)))
23530 ((looking-at-p re) (forward-line))
23531 (t (throw 'exit t))))))))
23533 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23534 "Move forward to the ARG'th subheading at same level as this one.
23535 Stop at the first and last subheadings of a superior heading.
23536 Normally this only looks at visible headings, but when INVISIBLE-OK is
23537 non-nil it will also look at invisible ones."
23538 (interactive "p")
23539 (let ((backward? (and arg (< arg 0))))
23540 (if (org-before-first-heading-p)
23541 (if backward? (goto-char (point-min)) (outline-next-heading))
23542 (org-back-to-heading invisible-ok)
23543 (unless backward? (end-of-line)) ;do not match current headline
23544 (let ((level (- (match-end 0) (match-beginning 0) 1))
23545 (f (if backward? #'re-search-backward #'re-search-forward))
23546 (count (if arg (abs arg) 1))
23547 (result (point)))
23548 (while (and (> count 0)
23549 (funcall f org-outline-regexp-bol nil 'move))
23550 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23551 (cond ((< l level) (setq count 0))
23552 ((and (= l level)
23553 (or invisible-ok
23554 (not (org-invisible-p
23555 (line-beginning-position)))))
23556 (cl-decf count)
23557 (when (= l level) (setq result (point)))))))
23558 (goto-char result))
23559 (beginning-of-line))))
23561 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23562 "Move backward to the ARG'th subheading at same level as this one.
23563 Stop at the first and last subheadings of a superior heading."
23564 (interactive "p")
23565 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23567 (defun org-next-visible-heading (arg)
23568 "Move to the next visible heading.
23570 This function wraps `outline-next-visible-heading' with
23571 `org-with-limited-levels' in order to skip over inline tasks and
23572 respect customization of `org-odd-levels-only'."
23573 (interactive "p")
23574 (org-with-limited-levels
23575 (outline-next-visible-heading arg)))
23577 (defun org-previous-visible-heading (arg)
23578 "Move to the previous visible heading.
23580 This function wraps `outline-previous-visible-heading' with
23581 `org-with-limited-levels' in order to skip over inline tasks and
23582 respect customization of `org-odd-levels-only'."
23583 (interactive "p")
23584 (org-with-limited-levels
23585 (outline-previous-visible-heading arg)))
23587 (defun org-next-block (arg &optional backward block-regexp)
23588 "Jump to the next block.
23590 With a prefix argument ARG, jump forward ARG many blocks.
23592 When BACKWARD is non-nil, jump to the previous block.
23594 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23595 Match data is set according to this regexp when the function
23596 returns.
23598 Return point at beginning of the opening line of found block.
23599 Throw an error if no block is found."
23600 (interactive "p")
23601 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23602 (case-fold-search t)
23603 (search-fn (if backward #'re-search-backward #'re-search-forward))
23604 (count (or arg 1))
23605 (origin (point))
23606 last-element)
23607 (if backward (beginning-of-line) (end-of-line))
23608 (while (and (> count 0) (funcall search-fn re nil t))
23609 (let ((element (save-excursion
23610 (goto-char (match-beginning 0))
23611 (save-match-data (org-element-at-point)))))
23612 (when (and (memq (org-element-type element)
23613 '(center-block comment-block dynamic-block
23614 example-block export-block quote-block
23615 special-block src-block verse-block))
23616 (<= (match-beginning 0)
23617 (org-element-property :post-affiliated element)))
23618 (setq last-element element)
23619 (cl-decf count))))
23620 (if (= count 0)
23621 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23622 (save-match-data (org-show-context)))
23623 (goto-char origin)
23624 (user-error "No %s code blocks" (if backward "previous" "further")))))
23626 (defun org-previous-block (arg &optional block-regexp)
23627 "Jump to the previous block.
23628 With a prefix argument ARG, jump backward ARG many source blocks.
23629 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23630 (interactive "p")
23631 (org-next-block arg t block-regexp))
23633 (defun org-forward-paragraph ()
23634 "Move forward to beginning of next paragraph or equivalent.
23636 The function moves point to the beginning of the next visible
23637 structural element, which can be a paragraph, a table, a list
23638 item, etc. It also provides some special moves for convenience:
23640 - On an affiliated keyword, jump to the beginning of the
23641 relative element.
23642 - On an item or a footnote definition, move to the second
23643 element inside, if any.
23644 - On a table or a property drawer, jump after it.
23645 - On a verse or source block, stop after blank lines."
23646 (interactive)
23647 (unless (eobp)
23648 (let* ((deactivate-mark nil)
23649 (element (org-element-at-point))
23650 (type (org-element-type element))
23651 (post-affiliated (org-element-property :post-affiliated element))
23652 (contents-begin (org-element-property :contents-begin element))
23653 (contents-end (org-element-property :contents-end element))
23654 (end (let ((end (org-element-property :end element)) (parent element))
23655 (while (and (setq parent (org-element-property :parent parent))
23656 (= (org-element-property :contents-end parent) end))
23657 (setq end (org-element-property :end parent)))
23658 end)))
23659 (cond ((not element)
23660 (skip-chars-forward " \r\t\n")
23661 (or (eobp) (beginning-of-line)))
23662 ;; On affiliated keywords, move to element's beginning.
23663 ((< (point) post-affiliated)
23664 (goto-char post-affiliated))
23665 ;; At a table row, move to the end of the table. Similarly,
23666 ;; at a node property, move to the end of the property
23667 ;; drawer.
23668 ((memq type '(node-property table-row))
23669 (goto-char (org-element-property
23670 :end (org-element-property :parent element))))
23671 ((memq type '(property-drawer table)) (goto-char end))
23672 ;; Consider blank lines as separators in verse and source
23673 ;; blocks to ease editing.
23674 ((memq type '(src-block verse-block))
23675 (when (eq type 'src-block)
23676 (setq contents-end
23677 (save-excursion (goto-char end)
23678 (skip-chars-backward " \r\t\n")
23679 (line-beginning-position))))
23680 (beginning-of-line)
23681 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23682 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23683 (goto-char end)
23684 (skip-chars-forward " \r\t\n")
23685 (if (= (point) contents-end) (goto-char end)
23686 (beginning-of-line))))
23687 ;; With no contents, just skip element.
23688 ((not contents-begin) (goto-char end))
23689 ;; If contents are invisible, skip the element altogether.
23690 ((org-invisible-p (line-end-position))
23691 (cl-case type
23692 (headline
23693 (org-with-limited-levels (outline-next-visible-heading 1)))
23694 ;; At a plain list, make sure we move to the next item
23695 ;; instead of skipping the whole list.
23696 (plain-list (forward-char)
23697 (org-forward-paragraph))
23698 (otherwise (goto-char end))))
23699 ((>= (point) contents-end) (goto-char end))
23700 ((>= (point) contents-begin)
23701 ;; This can only happen on paragraphs and plain lists.
23702 (cl-case type
23703 (paragraph (goto-char end))
23704 ;; At a plain list, try to move to second element in
23705 ;; first item, if possible.
23706 (plain-list (end-of-line)
23707 (org-forward-paragraph))))
23708 ;; When contents start on the middle of a line (e.g. in
23709 ;; items and footnote definitions), try to reach first
23710 ;; element starting after current line.
23711 ((> (line-end-position) contents-begin)
23712 (end-of-line)
23713 (org-forward-paragraph))
23714 (t (goto-char contents-begin))))))
23716 (defun org-backward-paragraph ()
23717 "Move backward to start of previous paragraph or equivalent.
23719 The function moves point to the beginning of the current
23720 structural element, which can be a paragraph, a table, a list
23721 item, etc., or to the beginning of the previous visible one if
23722 point is already there. It also provides some special moves for
23723 convenience:
23725 - On an affiliated keyword, jump to the first one.
23726 - On a table or a property drawer, move to its beginning.
23727 - On comment, example, export, src and verse blocks, stop
23728 before blank lines."
23729 (interactive)
23730 (unless (bobp)
23731 (let* ((deactivate-mark nil)
23732 (element (org-element-at-point))
23733 (type (org-element-type element))
23734 (contents-end (org-element-property :contents-end element))
23735 (post-affiliated (org-element-property :post-affiliated element))
23736 (begin (org-element-property :begin element))
23737 (special? ;blocks handled specially
23738 (memq type '(comment-block example-block export-block src-block
23739 verse-block)))
23740 (contents-begin
23741 (if special?
23742 ;; These types have no proper contents. Fake line
23743 ;; below the block opening line as contents beginning.
23744 (save-excursion (goto-char begin) (line-beginning-position 2))
23745 (org-element-property :contents-begin element))))
23746 (cond
23747 ((not element) (goto-char (point-min)))
23748 ((= (point) begin)
23749 (backward-char)
23750 (org-backward-paragraph))
23751 ((<= (point) post-affiliated) (goto-char begin))
23752 ;; Special behavior: on a table or a property drawer, move to
23753 ;; its beginning.
23754 ((memq type '(node-property table-row))
23755 (goto-char (org-element-property
23756 :post-affiliated (org-element-property :parent element))))
23757 (special?
23758 (if (<= (point) contents-begin) (goto-char post-affiliated)
23759 ;; Inside a verse block, see blank lines as paragraph
23760 ;; separators.
23761 (let ((origin (point)))
23762 (skip-chars-backward " \r\t\n" contents-begin)
23763 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23764 (skip-chars-forward " \r\t\n" origin)
23765 (if (= (point) origin) (goto-char contents-begin)
23766 (beginning-of-line))))))
23767 ((eq type 'paragraph) (goto-char contents-begin)
23768 ;; When at first paragraph in an item or a footnote definition,
23769 ;; move directly to beginning of line.
23770 (let ((parent-contents
23771 (org-element-property
23772 :contents-begin (org-element-property :parent element))))
23773 (when (and parent-contents (= parent-contents contents-begin))
23774 (beginning-of-line))))
23775 ;; At the end of a greater element, move to the beginning of
23776 ;; the last element within.
23777 ((and contents-end (>= (point) contents-end))
23778 (goto-char (1- contents-end))
23779 (org-backward-paragraph))
23780 (t (goto-char (or post-affiliated begin))))
23781 ;; Ensure we never leave point invisible.
23782 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23784 (defun org-forward-element ()
23785 "Move forward by one element.
23786 Move to the next element at the same level, when possible."
23787 (interactive)
23788 (cond ((eobp) (user-error "Cannot move further down"))
23789 ((org-with-limited-levels (org-at-heading-p))
23790 (let ((origin (point)))
23791 (goto-char (org-end-of-subtree nil t))
23792 (unless (org-with-limited-levels (org-at-heading-p))
23793 (goto-char origin)
23794 (user-error "Cannot move further down"))))
23796 (let* ((elem (org-element-at-point))
23797 (end (org-element-property :end elem))
23798 (parent (org-element-property :parent elem)))
23799 (cond ((and parent (= (org-element-property :contents-end parent) end))
23800 (goto-char (org-element-property :end parent)))
23801 ((integer-or-marker-p end) (goto-char end))
23802 (t (message "No element at point")))))))
23804 (defun org-backward-element ()
23805 "Move backward by one element.
23806 Move to the previous element at the same level, when possible."
23807 (interactive)
23808 (cond ((bobp) (user-error "Cannot move further up"))
23809 ((org-with-limited-levels (org-at-heading-p))
23810 ;; At a headline, move to the previous one, if any, or stay
23811 ;; here.
23812 (let ((origin (point)))
23813 (org-with-limited-levels (org-backward-heading-same-level 1))
23814 ;; When current headline has no sibling above, move to its
23815 ;; parent.
23816 (when (= (point) origin)
23817 (or (org-with-limited-levels (org-up-heading-safe))
23818 (progn (goto-char origin)
23819 (user-error "Cannot move further up"))))))
23821 (let* ((elem (org-element-at-point))
23822 (beg (org-element-property :begin elem)))
23823 (cond
23824 ;; Move to beginning of current element if point isn't
23825 ;; there already.
23826 ((null beg) (message "No element at point"))
23827 ((/= (point) beg) (goto-char beg))
23828 (t (goto-char beg)
23829 (skip-chars-backward " \r\t\n")
23830 (unless (bobp)
23831 (let ((prev (org-element-at-point)))
23832 (goto-char (org-element-property :begin prev))
23833 (while (and (setq prev (org-element-property :parent prev))
23834 (<= (org-element-property :end prev) beg))
23835 (goto-char (org-element-property :begin prev)))))))))))
23837 (defun org-up-element ()
23838 "Move to upper element."
23839 (interactive)
23840 (if (org-with-limited-levels (org-at-heading-p))
23841 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23842 (let* ((elem (org-element-at-point))
23843 (parent (org-element-property :parent elem)))
23844 (if parent (goto-char (org-element-property :begin parent))
23845 (if (org-with-limited-levels (org-before-first-heading-p))
23846 (user-error "No surrounding element")
23847 (org-with-limited-levels (org-back-to-heading)))))))
23849 (defun org-down-element ()
23850 "Move to inner element."
23851 (interactive)
23852 (let ((element (org-element-at-point)))
23853 (cond
23854 ((memq (org-element-type element) '(plain-list table))
23855 (goto-char (org-element-property :contents-begin element))
23856 (forward-char))
23857 ((memq (org-element-type element) org-element-greater-elements)
23858 ;; If contents are hidden, first disclose them.
23859 (when (org-invisible-p (line-end-position)) (org-cycle))
23860 (goto-char (or (org-element-property :contents-begin element)
23861 (user-error "No content for this element"))))
23862 (t (user-error "No inner element")))))
23864 (defun org-drag-element-backward ()
23865 "Move backward element at point."
23866 (interactive)
23867 (let ((elem (or (org-element-at-point)
23868 (user-error "No element at point"))))
23869 (if (eq (org-element-type elem) 'headline)
23870 ;; Preserve point when moving a whole tree, even if point was
23871 ;; on blank lines below the headline.
23872 (let ((offset (skip-chars-backward " \t\n")))
23873 (unwind-protect (org-move-subtree-up)
23874 (forward-char (- offset))))
23875 (let ((prev-elem
23876 (save-excursion
23877 (goto-char (org-element-property :begin elem))
23878 (skip-chars-backward " \r\t\n")
23879 (unless (bobp)
23880 (let* ((beg (org-element-property :begin elem))
23881 (prev (org-element-at-point))
23882 (up prev))
23883 (while (and (setq up (org-element-property :parent up))
23884 (<= (org-element-property :end up) beg))
23885 (setq prev up))
23886 prev)))))
23887 ;; Error out if no previous element or previous element is
23888 ;; a parent of the current one.
23889 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23890 (user-error "Cannot drag element backward")
23891 (let ((pos (point)))
23892 (org-element-swap-A-B prev-elem elem)
23893 (goto-char (+ (org-element-property :begin prev-elem)
23894 (- pos (org-element-property :begin elem))))))))))
23896 (defun org-drag-element-forward ()
23897 "Move forward element at point."
23898 (interactive)
23899 (let* ((pos (point))
23900 (elem (or (org-element-at-point)
23901 (user-error "No element at point"))))
23902 (when (= (point-max) (org-element-property :end elem))
23903 (user-error "Cannot drag element forward"))
23904 (goto-char (org-element-property :end elem))
23905 (let ((next-elem (org-element-at-point)))
23906 (when (or (org-element-nested-p elem next-elem)
23907 (and (eq (org-element-type next-elem) 'headline)
23908 (not (eq (org-element-type elem) 'headline))))
23909 (goto-char pos)
23910 (user-error "Cannot drag element forward"))
23911 ;; Compute new position of point: it's shifted by NEXT-ELEM
23912 ;; body's length (without final blanks) and by the length of
23913 ;; blanks between ELEM and NEXT-ELEM.
23914 (let ((size-next (- (save-excursion
23915 (goto-char (org-element-property :end next-elem))
23916 (skip-chars-backward " \r\t\n")
23917 (forward-line)
23918 ;; Small correction if buffer doesn't end
23919 ;; with a newline character.
23920 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23921 (org-element-property :begin next-elem)))
23922 (size-blank (- (org-element-property :end elem)
23923 (save-excursion
23924 (goto-char (org-element-property :end elem))
23925 (skip-chars-backward " \r\t\n")
23926 (forward-line)
23927 (point)))))
23928 (org-element-swap-A-B elem next-elem)
23929 (goto-char (+ pos size-next size-blank))))))
23931 (defun org-drag-line-forward (arg)
23932 "Drag the line at point ARG lines forward."
23933 (interactive "p")
23934 (dotimes (_ (abs arg))
23935 (let ((c (current-column)))
23936 (if (< 0 arg)
23937 (progn
23938 (beginning-of-line 2)
23939 (transpose-lines 1)
23940 (beginning-of-line 0))
23941 (transpose-lines 1)
23942 (beginning-of-line -1))
23943 (org-move-to-column c))))
23945 (defun org-drag-line-backward (arg)
23946 "Drag the line at point ARG lines backward."
23947 (interactive "p")
23948 (org-drag-line-forward (- arg)))
23950 (defun org-mark-element ()
23951 "Put point at beginning of this element, mark at end.
23953 Interactively, if this command is repeated or (in Transient Mark
23954 mode) if the mark is active, it marks the next element after the
23955 ones already marked."
23956 (interactive)
23957 (let (deactivate-mark)
23958 (if (and (called-interactively-p 'any)
23959 (or (and (eq last-command this-command) (mark t))
23960 (and transient-mark-mode mark-active)))
23961 (set-mark
23962 (save-excursion
23963 (goto-char (mark))
23964 (goto-char (org-element-property :end (org-element-at-point)))))
23965 (let ((element (org-element-at-point)))
23966 (end-of-line)
23967 (push-mark (org-element-property :end element) t t)
23968 (goto-char (org-element-property :begin element))))))
23970 (defun org-narrow-to-element ()
23971 "Narrow buffer to current element."
23972 (interactive)
23973 (let ((elem (org-element-at-point)))
23974 (cond
23975 ((eq (car elem) 'headline)
23976 (narrow-to-region
23977 (org-element-property :begin elem)
23978 (org-element-property :end elem)))
23979 ((memq (car elem) org-element-greater-elements)
23980 (narrow-to-region
23981 (org-element-property :contents-begin elem)
23982 (org-element-property :contents-end elem)))
23984 (narrow-to-region
23985 (org-element-property :begin elem)
23986 (org-element-property :end elem))))))
23988 (defun org-transpose-element ()
23989 "Transpose current and previous elements, keeping blank lines between.
23990 Point is moved after both elements."
23991 (interactive)
23992 (org-skip-whitespace)
23993 (let ((end (org-element-property :end (org-element-at-point))))
23994 (org-drag-element-backward)
23995 (goto-char end)))
23997 (defun org-unindent-buffer ()
23998 "Un-indent the visible part of the buffer.
23999 Relative indentation (between items, inside blocks, etc.) isn't
24000 modified."
24001 (interactive)
24002 (unless (eq major-mode 'org-mode)
24003 (user-error "Cannot un-indent a buffer not in Org mode"))
24004 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24005 (unindent-tree
24006 (lambda (contents)
24007 (dolist (element (reverse contents))
24008 (if (memq (org-element-type element) '(headline section))
24009 (funcall unindent-tree (org-element-contents element))
24010 (save-excursion
24011 (save-restriction
24012 (narrow-to-region
24013 (org-element-property :begin element)
24014 (org-element-property :end element))
24015 (org-do-remove-indentation))))))))
24016 (funcall unindent-tree (org-element-contents parse-tree))))
24018 (defun org-show-children (&optional level)
24019 "Show all direct subheadings of this heading.
24020 Prefix arg LEVEL is how many levels below the current level
24021 should be shown. Default is enough to cause the following
24022 heading to appear."
24023 (interactive "p")
24024 ;; If `orgstruct-mode' is active, use the slower version.
24025 (if orgstruct-mode (call-interactively #'outline-show-children)
24026 (save-excursion
24027 (org-back-to-heading t)
24028 (let* ((current-level (funcall outline-level))
24029 (max-level (org-get-valid-level
24030 current-level
24031 (if level (prefix-numeric-value level) 1)))
24032 (end (save-excursion (org-end-of-subtree t t)))
24033 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24034 (past-first-child nil)
24035 ;; Make sure to skip inlinetasks.
24036 (re (format regexp-fmt
24037 current-level
24038 (cond
24039 ((not (featurep 'org-inlinetask)) "")
24040 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24042 (t (1- org-inlinetask-min-level))))))
24043 ;; Display parent heading.
24044 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24045 (forward-line)
24046 ;; Display children. First child may be deeper than expected
24047 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24048 ;; MAX-LEVEL accordingly.
24049 (while (re-search-forward re end t)
24050 (unless past-first-child
24051 (setq re (format regexp-fmt
24052 current-level
24053 (max (funcall outline-level) max-level)))
24054 (setq past-first-child t))
24055 (outline-flag-region
24056 (line-end-position 0) (line-end-position) nil))))))
24058 (defun org-show-subtree ()
24059 "Show everything after this heading at deeper levels."
24060 (interactive)
24061 (outline-flag-region
24062 (point)
24063 (save-excursion
24064 (org-end-of-subtree t t))
24065 nil))
24067 (defun org-show-entry ()
24068 "Show the body directly following this heading.
24069 Show the heading too, if it is currently invisible."
24070 (interactive)
24071 (save-excursion
24072 (ignore-errors
24073 (org-back-to-heading t)
24074 (outline-flag-region
24075 (max (point-min) (1- (point)))
24076 (save-excursion
24077 (if (re-search-forward
24078 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24079 (match-beginning 1)
24080 (point-max)))
24081 nil)
24082 (org-cycle-hide-drawers 'children))))
24084 (defun org-make-options-regexp (kwds &optional extra)
24085 "Make a regular expression for keyword lines.
24086 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24087 when non-nil, is a regexp matching keywords names."
24088 (concat "^[ \t]*#\\+\\("
24089 (regexp-opt kwds)
24090 (and extra (concat (and kwds "\\|") extra))
24091 "\\):[ \t]*\\(.*\\)"))
24093 ;;;; Finish up
24095 (provide 'org)
24097 (run-hooks 'org-load-hook)
24099 ;;; org.el ends here