Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob3b26bfd3d5c2c88f21d62528622bb274e184fb2e
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) ;Silence byte-compiler
189 ;; load languages based on value of `org-babel-load-languages'
190 (defvar org-babel-load-languages)
192 ;;;###autoload
193 (defun org-babel-do-load-languages (sym value)
194 "Load the languages defined in `org-babel-load-languages'."
195 (set-default sym value)
196 (dolist (pair org-babel-load-languages)
197 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
198 (if active
199 (require (intern (concat "ob-" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-execute:" lang)))
202 (funcall 'fmakunbound
203 (intern (concat "org-babel-expand-body:" lang)))))))
205 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
206 ;;;###autoload
207 (defun org-babel-load-file (file &optional compile)
208 "Load Emacs Lisp source code blocks in the Org FILE.
209 This function exports the source code using `org-babel-tangle'
210 and then loads the resulting file using `load-file'. With prefix
211 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
212 file to byte-code before it is loaded."
213 (interactive "fFile to load: \nP")
214 (let* ((age (lambda (file)
215 (float-time
216 (time-subtract (current-time)
217 (nth 5 (or (file-attributes (file-truename file))
218 (file-attributes file)))))))
219 (base-name (file-name-sans-extension file))
220 (exported-file (concat base-name ".el")))
221 ;; tangle if the Org file is newer than the elisp file
222 (unless (and (file-exists-p exported-file)
223 (> (funcall age file) (funcall age exported-file)))
224 ;; Tangle-file traversal returns reversed list of tangled files
225 ;; and we want to evaluate the first target.
226 (setq exported-file
227 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
228 (message "%s %s"
229 (if compile
230 (progn (byte-compile-file exported-file 'load)
231 "Compiled and loaded")
232 (progn (load-file exported-file) "Loaded"))
233 exported-file)))
235 (defcustom org-babel-load-languages '((emacs-lisp . t))
236 "Languages which can be evaluated in Org buffers.
237 This list can be used to load support for any of the languages
238 below, note that each language will depend on a different set of
239 system executables and/or Emacs modes. When a language is
240 \"loaded\", then code blocks in that language can be evaluated
241 with `org-babel-execute-src-block' bound by default to C-c
242 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
243 be set to remove code block evaluation from the C-c C-c
244 keybinding. By default only Emacs Lisp (which has no
245 requirements) is loaded."
246 :group 'org-babel
247 :set 'org-babel-do-load-languages
248 :version "24.1"
249 :type '(alist :tag "Babel Languages"
250 :key-type
251 (choice
252 (const :tag "Awk" awk)
253 (const :tag "C" C)
254 (const :tag "R" R)
255 (const :tag "Asymptote" asymptote)
256 (const :tag "Calc" calc)
257 (const :tag "Clojure" clojure)
258 (const :tag "CSS" css)
259 (const :tag "Ditaa" ditaa)
260 (const :tag "Dot" dot)
261 (const :tag "Ebnf2ps" ebnf2ps)
262 (const :tag "Emacs Lisp" emacs-lisp)
263 (const :tag "Forth" forth)
264 (const :tag "Fortran" fortran)
265 (const :tag "Gnuplot" gnuplot)
266 (const :tag "Haskell" haskell)
267 (const :tag "hledger" hledger)
268 (const :tag "IO" io)
269 (const :tag "J" J)
270 (const :tag "Java" java)
271 (const :tag "Javascript" js)
272 (const :tag "LaTeX" latex)
273 (const :tag "Ledger" ledger)
274 (const :tag "Lilypond" lilypond)
275 (const :tag "Lisp" lisp)
276 (const :tag "Makefile" makefile)
277 (const :tag "Maxima" maxima)
278 (const :tag "Matlab" matlab)
279 (const :tag "Mscgen" mscgen)
280 (const :tag "Ocaml" ocaml)
281 (const :tag "Octave" octave)
282 (const :tag "Org" org)
283 (const :tag "Perl" perl)
284 (const :tag "Pico Lisp" picolisp)
285 (const :tag "PlantUML" plantuml)
286 (const :tag "Python" python)
287 (const :tag "Ruby" ruby)
288 (const :tag "Sass" sass)
289 (const :tag "Scala" scala)
290 (const :tag "Scheme" scheme)
291 (const :tag "Screen" screen)
292 (const :tag "Shell Script" shell)
293 (const :tag "Shen" shen)
294 (const :tag "Sql" sql)
295 (const :tag "Sqlite" sqlite)
296 (const :tag "Stan" stan)
297 (const :tag "Vala" vala))
298 :value-type (boolean :tag "Activate" :value t)))
300 ;;;; Customization variables
301 (defcustom org-clone-delete-id nil
302 "Remove ID property of clones of a subtree.
303 When non-nil, clones of a subtree don't inherit the ID property.
304 Otherwise they inherit the ID property with a new unique
305 identifier."
306 :type 'boolean
307 :version "24.1"
308 :group 'org-id)
310 ;;; Version
311 (org-check-version)
313 ;;;###autoload
314 (defun org-version (&optional here full message)
315 "Show the Org version.
316 Interactively, or when MESSAGE is non-nil, show it in echo area.
317 With prefix argument, or when HERE is non-nil, insert it at point.
318 In non-interactive uses, a reduced version string is output unless
319 FULL is given."
320 (interactive (list current-prefix-arg t (not current-prefix-arg)))
321 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
322 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
323 (load-suffixes (list ".el"))
324 (org-install-dir
325 (ignore-errors (org-find-library-dir "org-loaddefs"))))
326 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
327 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
328 (let* ((load-suffixes save-load-suffixes)
329 (release (org-release))
330 (git-version (org-git-version))
331 (version (format "Org mode version %s (%s @ %s)"
332 release
333 git-version
334 (if org-install-dir
335 (if (string= org-dir org-install-dir)
336 org-install-dir
337 (concat "mixed installation! "
338 org-install-dir
339 " and "
340 org-dir))
341 "org-loaddefs.el can not be found!")))
342 (version1 (if full version release)))
343 (when here (insert version1))
344 (when message (message "%s" version1))
345 version1)))
347 (defconst org-version (org-version))
350 ;;; Syntax Constants
352 ;;;; Block
354 (defconst org-block-regexp
355 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
356 "Regular expression for hiding blocks.")
358 (defconst org-dblock-start-re
359 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
360 "Matches the start line of a dynamic block, with parameters.")
362 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
363 "Matches the end of a dynamic block.")
365 ;;;; Clock and Planning
367 (defconst org-clock-string "CLOCK:"
368 "String used as prefix for timestamps clocking work hours on an item.")
370 (defvar org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry.")
373 (defvar org-deadline-string "DEADLINE:"
374 "String to mark deadline entries.
375 \\<org-mode-map>
376 A deadline is this string, followed by a time stamp. It must be
377 a word, terminated by a colon. You can insert a schedule keyword
378 and a timestamp with `\\[org-deadline]'.")
380 (defvar org-scheduled-string "SCHEDULED:"
381 "String to mark scheduled TODO entries.
382 \\<org-mode-map>
383 A schedule is this string, followed by a time stamp. It must be
384 a word, terminated by a colon. You can insert a schedule keyword
385 and a timestamp with `\\[org-schedule]'.")
387 (defconst org-ds-keyword-length
388 (+ 2
389 (apply #'max
390 (mapcar #'length
391 (list org-deadline-string org-scheduled-string
392 org-clock-string org-closed-string))))
393 "Maximum length of the DEADLINE and SCHEDULED keywords.")
395 (defconst org-planning-line-re
396 (concat "^[ \t]*"
397 (regexp-opt
398 (list org-closed-string org-deadline-string org-scheduled-string)
400 "Matches a line with planning info.
401 Matched keyword is in group 1.")
403 (defconst org-clock-line-re
404 (concat "^[ \t]*" org-clock-string)
405 "Matches a line with clock info.")
407 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
408 "Matches the DEADLINE keyword.")
410 (defconst org-deadline-time-regexp
411 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
412 "Matches the DEADLINE keyword together with a time stamp.")
414 (defconst org-deadline-time-hour-regexp
415 (concat "\\<" org-deadline-string
416 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
417 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
419 (defconst org-deadline-line-regexp
420 (concat "\\<\\(" org-deadline-string "\\).*")
421 "Matches the DEADLINE keyword and the rest of the line.")
423 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
424 "Matches the SCHEDULED keyword.")
426 (defconst org-scheduled-time-regexp
427 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
428 "Matches the SCHEDULED keyword together with a time stamp.")
430 (defconst org-scheduled-time-hour-regexp
431 (concat "\\<" org-scheduled-string
432 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
433 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
435 (defconst org-closed-time-regexp
436 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
437 "Matches the CLOSED keyword together with a time stamp.")
439 (defconst org-keyword-time-regexp
440 (concat "\\<"
441 (regexp-opt
442 (list org-scheduled-string org-deadline-string org-closed-string
443 org-clock-string)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 4 keywords, together with the time stamp.")
448 (defconst org-keyword-time-not-clock-regexp
449 (concat
450 "\\<"
451 (regexp-opt
452 (list org-scheduled-string org-deadline-string org-closed-string) t)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 3 keywords, together with the time stamp.")
456 (defconst org-maybe-keyword-time-regexp
457 (concat "\\(\\<"
458 (regexp-opt
459 (list org-scheduled-string org-deadline-string org-closed-string
460 org-clock-string)
462 "\\)?"
463 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
464 "\\|"
465 "<%%([^\r\n>]*>\\)")
466 "Matches a timestamp, possibly preceded by a keyword.")
468 (defconst org-all-time-keywords
469 (mapcar (lambda (w) (substring w 0 -1))
470 (list org-scheduled-string org-deadline-string
471 org-clock-string org-closed-string))
472 "List of time keywords.")
474 ;;;; Drawer
476 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
477 "Matches first or last line of a hidden block.
478 Group 1 contains drawer's name or \"END\".")
480 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
481 "Regular expression matching the first line of a property drawer.")
483 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a property drawer.")
486 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
487 "Regular expression matching the first line of a clock drawer.")
489 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
490 "Regular expression matching the last line of a clock drawer.")
492 (defconst org-property-drawer-re
493 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
494 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
495 "[ \t]*:END:[ \t]*$")
496 "Matches an entire property drawer.")
498 (defconst org-clock-drawer-re
499 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
500 org-clock-drawer-end-re "\\)\n?")
501 "Matches an entire clock drawer.")
503 ;;;; Headline
505 (defconst org-heading-keyword-regexp-format
506 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
507 "Printf format for a regexp matching a headline with some keyword.
508 This regexp will match the headline of any node which has the
509 exact keyword that is put into the format. The keyword isn't in
510 any group by default, but the stars and the body are.")
512 (defconst org-heading-keyword-maybe-regexp-format
513 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
514 "Printf format for a regexp matching a headline, possibly with some keyword.
515 This regexp can match any headline with the specified keyword, or
516 without a keyword. The keyword isn't in any group by default,
517 but the stars and the body are.")
519 (defconst org-archive-tag "ARCHIVE"
520 "The tag that marks a subtree as archived.
521 An archived subtree does not open during visibility cycling, and does
522 not contribute to the agenda listings.")
524 (eval-and-compile
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 \\<org-mode-map>
528 An entry can be toggled between COMMENT and normal with
529 `\\[org-toggle-comment]'."))
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
536 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
543 "Regular expressions for matching embedded LaTeX.")
545 ;;;; Node Property
547 (defconst org-effort-property "Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
551 ;;;; Table
553 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp "^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp "^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
575 ;;;; Timestamp
577 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
610 org-ts-regexp "\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both "\\(--?-?"
615 org-ts-regexp-both "\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
630 (defgroup org nil
631 "Outline-based notes management and organizer."
632 :tag "Org"
633 :group 'outlines
634 :group 'calendar)
636 (defcustom org-mode-hook nil
637 "Mode hook for Org mode, run after the mode was turned on."
638 :group 'org
639 :type 'hook)
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
643 :group 'org
644 :type 'hook)
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
648 :group 'org
649 :version "24.1"
650 :type 'hook)
652 (defvar org-modules) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force)
657 "Load all extensions listed in `org-modules'."
658 (when (or force (not org-modules-loaded))
659 (dolist (ext org-modules)
660 (condition-case nil (require ext)
661 (error (message "Problems while trying to load feature `%s'" ext))))
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " eww: Store link to url of eww" org-eww)
698 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
699 (const :tag " habit: Track your consistency with habits" org-habit)
700 (const :tag " id: Global IDs for identifying entries" org-id)
701 (const :tag " info: Links to Info nodes" org-info)
702 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
703 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
704 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
705 (const :tag " mouse: Additional mouse support" org-mouse)
706 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
707 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
708 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
710 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
711 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
712 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
713 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
714 (const :tag "C collector: Collect properties into tables" org-collector)
715 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
716 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
717 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
718 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
719 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
720 (const :tag "C eval: Include command output as text" org-eval)
721 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
722 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
723 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
724 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
725 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
726 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
727 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
728 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
729 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
730 (const :tag "C man: Support for links to manpages in Org mode" org-man)
731 (const :tag "C mew: Links to Mew folders/messages" org-mew)
732 (const :tag "C mtags: Support for muse-like tags" org-mtags)
733 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
734 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
735 (const :tag "C registry: A registry for Org links" org-registry)
736 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
737 (const :tag "C secretary: Team management with org-mode" org-secretary)
738 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
739 (const :tag "C toc: Table of contents for Org buffer" org-toc)
740 (const :tag "C track: Keep up with Org mode development" org-track)
741 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
742 (const :tag "C vm: Links to VM folders/messages" org-vm)
743 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
744 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
745 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
747 (defvar org-export-registered-backends) ; From ox.el.
748 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
749 (declare-function org-export-backend-name "ox" (backend) t)
750 (defcustom org-export-backends '(ascii html icalendar latex odt)
751 "List of export back-ends that should be always available.
753 If a description starts with <C>, the file is not part of Emacs
754 and loading it will require that you have downloaded and properly
755 installed the Org mode distribution.
757 Unlike to `org-modules', libraries in this list will not be
758 loaded along with Org, but only once the export framework is
759 needed.
761 This variable needs to be set before org.el is loaded. If you
762 need to make a change while Emacs is running, use the customize
763 interface or run the following code, where VAL stands for the new
764 value of the variable, after updating it:
766 (progn
767 (setq org-export-registered-backends
768 (cl-remove-if-not
769 (lambda (backend)
770 (let ((name (org-export-backend-name backend)))
771 (or (memq name val)
772 (catch \\='parentp
773 (dolist (b val)
774 (and (org-export-derived-backend-p b name)
775 (throw \\='parentp t)))))))
776 org-export-registered-backends))
777 (let ((new-list (mapcar #\\='org-export-backend-name
778 org-export-registered-backends)))
779 (dolist (backend val)
780 (cond
781 ((not (load (format \"ox-%s\" backend) t t))
782 (message \"Problems while trying to load export back-end \\=`%s\\='\"
783 backend))
784 ((not (memq backend new-list)) (push backend new-list))))
785 (set-default \\='org-export-backends new-list)))
787 Adding a back-end to this list will also pull the back-end it
788 depends on, if any."
789 :group 'org
790 :group 'org-export
791 :version "26.1"
792 :package-version '(Org . "9.0")
793 :initialize 'custom-initialize-set
794 :set (lambda (var val)
795 (if (not (featurep 'ox)) (set-default var val)
796 ;; Any back-end not required anymore (not present in VAL and not
797 ;; a parent of any back-end in the new value) is removed from the
798 ;; list of registered back-ends.
799 (setq org-export-registered-backends
800 (cl-remove-if-not
801 (lambda (backend)
802 (let ((name (org-export-backend-name backend)))
803 (or (memq name val)
804 (catch 'parentp
805 (dolist (b val)
806 (and (org-export-derived-backend-p b name)
807 (throw 'parentp t)))))))
808 org-export-registered-backends))
809 ;; Now build NEW-LIST of both new back-ends and required
810 ;; parents.
811 (let ((new-list (mapcar #'org-export-backend-name
812 org-export-registered-backends)))
813 (dolist (backend val)
814 (cond
815 ((not (load (format "ox-%s" backend) t t))
816 (message "Problems while trying to load export back-end `%s'"
817 backend))
818 ((not (memq backend new-list)) (push backend new-list))))
819 ;; Set VAR to that list with fixed dependencies.
820 (set-default var new-list))))
821 :type '(set :greedy t
822 (const :tag " ascii Export buffer to ASCII format" ascii)
823 (const :tag " beamer Export buffer to Beamer presentation" beamer)
824 (const :tag " html Export buffer to HTML format" html)
825 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
826 (const :tag " latex Export buffer to LaTeX format" latex)
827 (const :tag " man Export buffer to MAN format" man)
828 (const :tag " md Export buffer to Markdown format" md)
829 (const :tag " odt Export buffer to ODT format" odt)
830 (const :tag " org Export buffer to Org format" org)
831 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
832 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
833 (const :tag "C deck Export buffer to deck.js presentations" deck)
834 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
835 (const :tag "C groff Export buffer to Groff format" groff)
836 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
837 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
838 (const :tag "C s5 Export buffer to s5 presentations" s5)
839 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
841 (eval-after-load 'ox
842 '(dolist (backend org-export-backends)
843 (condition-case nil (require (intern (format "ox-%s" backend)))
844 (error (message "Problems while trying to load export back-end `%s'"
845 backend)))))
847 (defcustom org-support-shift-select nil
848 "Non-nil means make shift-cursor commands select text when possible.
849 \\<org-mode-map>\
851 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
852 start selecting a region, or enlarge regions started in this way.
853 In Org mode, in special contexts, these same keys are used for
854 other purposes, important enough to compete with shift selection.
855 Org tries to balance these needs by supporting `shift-select-mode'
856 outside these special contexts, under control of this variable.
858 The default of this variable is nil, to avoid confusing behavior. Shifted
859 cursor keys will then execute Org commands in the following contexts:
860 - on a headline, changing TODO state (left/right) and priority (up/down)
861 - on a time stamp, changing the time
862 - in a plain list item, changing the bullet type
863 - in a property definition line, switching between allowed values
864 - in the BEGIN line of a clock table (changing the time block).
865 Outside these contexts, the commands will throw an error.
867 When this variable is t and the cursor is not in a special
868 context, Org mode will support shift-selection for making and
869 enlarging regions. To make this more effective, the bullet
870 cycling will no longer happen anywhere in an item line, but only
871 if the cursor is exactly on the bullet.
873 If you set this variable to the symbol `always', then the keys
874 will not be special in headlines, property lines, and item lines,
875 to make shift selection work there as well. If this is what you
876 want, you can use the following alternative commands:
877 `\\[org-todo]' and `\\[org-priority]' \
878 to change TODO state and priority,
879 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
880 can be used to switch TODO sets,
881 `\\[org-ctrl-c-minus]' to cycle item bullet types,
882 and properties can be edited by hand or in column view.
884 However, when the cursor is on a timestamp, shift-cursor commands
885 will still edit the time stamp - this is just too good to give up."
886 :group 'org
887 :type '(choice
888 (const :tag "Never" nil)
889 (const :tag "When outside special context" t)
890 (const :tag "Everywhere except timestamps" always)))
892 (defcustom org-loop-over-headlines-in-active-region nil
893 "Shall some commands act upon headlines in the active region?
895 When set to t, some commands will be performed in all headlines
896 within the active region.
898 When set to `start-level', some commands will be performed in all
899 headlines within the active region, provided that these headlines
900 are of the same level than the first one.
902 When set to a string, those commands will be performed on the
903 matching headlines within the active region. Such string must be
904 a tags/property/todo match as it is used in the agenda tags view.
906 The list of commands is: `org-schedule', `org-deadline',
907 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
908 `org-archive-to-archive-sibling'. The archiving commands skip
909 already archived entries."
910 :type '(choice (const :tag "Don't loop" nil)
911 (const :tag "All headlines in active region" t)
912 (const :tag "In active region, headlines at the same level than the first one" start-level)
913 (string :tag "Tags/Property/Todo matcher"))
914 :version "24.1"
915 :group 'org-todo
916 :group 'org-archive)
918 (defcustom org-startup-folded t
919 "Non-nil means entering Org mode will switch to OVERVIEW.
921 This can also be configured on a per-file basis by adding one of
922 the following lines anywhere in the buffer:
924 #+STARTUP: fold (or `overview', this is equivalent)
925 #+STARTUP: nofold (or `showall', this is equivalent)
926 #+STARTUP: content
927 #+STARTUP: showeverything
929 Set `org-agenda-inhibit-startup' to a non-nil value if you want
930 to ignore this option when Org opens agenda files for the first
931 time."
932 :group 'org-startup
933 :type '(choice
934 (const :tag "nofold: show all" nil)
935 (const :tag "fold: overview" t)
936 (const :tag "content: all headlines" content)
937 (const :tag "show everything, even drawers" showeverything)))
939 (defcustom org-startup-truncated t
940 "Non-nil means entering Org mode will set `truncate-lines'.
941 This is useful since some lines containing links can be very long and
942 uninteresting. Also tables look terrible when wrapped.
944 The variable `org-startup-truncated' allows to configure
945 truncation for Org mode different to the other modes that use the
946 variable `truncate-lines' and as a shortcut instead of putting
947 the variable `truncate-lines' into the `org-mode-hook'. If one
948 wants to configure truncation for Org mode not statically but
949 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
950 the variable `truncate-lines' has to be used because in such a
951 case it is too late to set the variable `org-startup-truncated'."
952 :group 'org-startup
953 :type 'boolean)
955 (defcustom org-startup-indented nil
956 "Non-nil means turn on `org-indent-mode' on startup.
957 This can also be configured on a per-file basis by adding one of
958 the following lines anywhere in the buffer:
960 #+STARTUP: indent
961 #+STARTUP: noindent"
962 :group 'org-structure
963 :type '(choice
964 (const :tag "Not" nil)
965 (const :tag "Globally (slow on startup in large files)" t)))
967 (defcustom org-use-sub-superscripts t
968 "Non-nil means interpret \"_\" and \"^\" for display.
970 If you want to control how Org exports those characters, see
971 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
972 used to be an alias for `org-export-with-sub-superscripts' in
973 Org <8.0, it is not anymore.
975 When this option is turned on, you can use TeX-like syntax for
976 sub- and superscripts within the buffer. Several characters after
977 \"_\" or \"^\" will be considered as a single item - so grouping
978 with {} is normally not needed. For example, the following things
979 will be parsed as single sub- or superscripts:
981 10^24 or 10^tau several digits will be considered 1 item.
982 10^-12 or 10^-tau a leading sign with digits or a word
983 x^2-y^3 will be read as x^2 - y^3, because items are
984 terminated by almost any nonword/nondigit char.
985 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
987 Still, ambiguity is possible. So when in doubt, use {} to enclose
988 the sub/superscript. If you set this variable to the symbol `{}',
989 the braces are *required* in order to trigger interpretations as
990 sub/superscript. This can be helpful in documents that need \"_\"
991 frequently in plain text."
992 :group 'org-startup
993 :version "24.4"
994 :package-version '(Org . "8.0")
995 :type '(choice
996 (const :tag "Always interpret" t)
997 (const :tag "Only with braces" {})
998 (const :tag "Never interpret" nil)))
1000 (defcustom org-startup-with-beamer-mode nil
1001 "Non-nil means turn on `org-beamer-mode' on startup.
1002 This can also be configured on a per-file basis by adding one of
1003 the following lines anywhere in the buffer:
1005 #+STARTUP: beamer"
1006 :group 'org-startup
1007 :version "24.1"
1008 :type 'boolean)
1010 (defcustom org-startup-align-all-tables nil
1011 "Non-nil means align all tables when visiting a file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: align
1015 #+STARTUP: noalign"
1016 :group 'org-startup
1017 :type 'boolean)
1019 (defcustom org-startup-shrink-all-tables nil
1020 "Non-nil means shrink all table columns with a width cookie.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: shrink"
1024 :group 'org-startup
1025 :type 'boolean
1026 :version "27.1"
1027 :package-version '(Org . "9.2")
1028 :safe #'booleanp)
1030 (defcustom org-startup-with-inline-images nil
1031 "Non-nil means show inline images when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: inlineimages
1035 #+STARTUP: noinlineimages"
1036 :group 'org-startup
1037 :version "24.1"
1038 :type 'boolean)
1040 (defcustom org-startup-with-latex-preview nil
1041 "Non-nil means preview LaTeX fragments when loading a new Org file.
1043 This can also be configured on a per-file basis by adding one of
1044 the following lines anywhere in the buffer:
1045 #+STARTUP: latexpreview
1046 #+STARTUP: nolatexpreview"
1047 :group 'org-startup
1048 :version "24.4"
1049 :package-version '(Org . "8.0")
1050 :type 'boolean)
1052 (defcustom org-insert-mode-line-in-empty-file nil
1053 "Non-nil means insert the first line setting Org mode in empty files.
1054 When the function `org-mode' is called interactively in an empty file, this
1055 normally means that the file name does not automatically trigger Org mode.
1056 To ensure that the file will always be in Org mode in the future, a
1057 line enforcing Org mode will be inserted into the buffer, if this option
1058 has been set."
1059 :group 'org-startup
1060 :type 'boolean)
1062 (defcustom org-replace-disputed-keys nil
1063 "Non-nil means use alternative key bindings for some keys.
1064 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1065 These keys are also used by other packages like shift-selection-mode'
1066 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1067 If you want to use Org mode together with one of these other modes,
1068 or more generally if you would like to move some Org mode commands to
1069 other keys, set this variable and configure the keys with the variable
1070 `org-disputed-keys'.
1072 This option is only relevant at load-time of Org mode, and must be set
1073 *before* org.el is loaded. Changing it requires a restart of Emacs to
1074 become effective."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defcustom org-use-extra-keys nil
1079 "Non-nil means use extra key sequence definitions for certain commands.
1080 This happens automatically if `window-system' is nil. This
1081 variable lets you do the same manually. You must set it before
1082 loading Org."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1088 (defcustom org-disputed-keys
1089 '(([(shift up)] . [(meta p)])
1090 ([(shift down)] . [(meta n)])
1091 ([(shift left)] . [(meta -)])
1092 ([(shift right)] . [(meta +)])
1093 ([(control shift right)] . [(meta shift +)])
1094 ([(control shift left)] . [(meta shift -)]))
1095 "Keys for which Org mode and other modes compete.
1096 This is an alist, cars are the default keys, second element specifies
1097 the alternative to use when `org-replace-disputed-keys' is t.
1099 Keys can be specified in any syntax supported by `define-key'.
1100 The value of this option takes effect only at Org mode startup,
1101 therefore you'll have to restart Emacs to apply it after changing."
1102 :group 'org-startup
1103 :type 'alist)
1105 (defun org-key (key)
1106 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1107 Or return the original if not disputed."
1108 (when org-replace-disputed-keys
1109 (let* ((nkey (key-description key))
1110 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 key)
1115 (defun org-defkey (keymap key def)
1116 "Define a key, possibly translated, as returned by `org-key'."
1117 (define-key keymap (org-key key) def))
1119 (defcustom org-ellipsis nil
1120 "The ellipsis to use in the Org mode outline.
1122 When nil, just use the standard three dots. When a non-empty string,
1123 use that string instead.
1125 The change affects only Org mode (which will then use its own display table).
1126 Changing this requires executing `\\[org-mode]' in a buffer to become
1127 effective."
1128 :group 'org-startup
1129 :type '(choice (const :tag "Default" nil)
1130 (string :tag "String" :value "...#"))
1131 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1133 (defvar org-display-table nil
1134 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1136 (defgroup org-keywords nil
1137 "Keywords in Org mode."
1138 :tag "Org Keywords"
1139 :group 'org)
1141 (defcustom org-closed-keep-when-no-todo nil
1142 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1143 :group 'org-todo
1144 :group 'org-keywords
1145 :version "24.4"
1146 :package-version '(Org . "8.0")
1147 :type 'boolean)
1149 (defgroup org-structure nil
1150 "Options concerning the general structure of Org files."
1151 :tag "Org Structure"
1152 :group 'org)
1154 (defgroup org-reveal-location nil
1155 "Options about how to make context of a location visible."
1156 :tag "Org Reveal Location"
1157 :group 'org-structure)
1159 (defcustom org-show-context-detail '((agenda . local)
1160 (bookmark-jump . lineage)
1161 (isearch . lineage)
1162 (default . ancestors))
1163 "Alist between context and visibility span when revealing a location.
1165 \\<org-mode-map>Some actions may move point into invisible
1166 locations. As a consequence, Org always expose a neighborhood
1167 around point. How much is shown depends on the initial action,
1168 or context. Valid contexts are
1170 agenda when exposing an entry from the agenda
1171 org-goto when using the command `org-goto' (`\\[org-goto]')
1172 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1173 tags-tree when constructing a sparse tree based on tags matches
1174 link-search when exposing search matches associated with a link
1175 mark-goto when exposing the jump goal of a mark
1176 bookmark-jump when exposing a bookmark location
1177 isearch when exiting from an incremental search
1178 default default for all contexts not set explicitly
1180 Allowed visibility spans are
1182 minimal show current headline; if point is not on headline,
1183 also show entry
1185 local show current headline, entry and next headline
1187 ancestors show current headline and its direct ancestors; if
1188 point is not on headline, also show entry
1190 lineage show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and first child
1194 tree show current headline, its direct ancestors and all
1195 their children; if point is not on headline, also show
1196 entry and all children
1198 canonical show current headline, its direct ancestors along with
1199 their entries and children; if point is not located on
1200 the headline, also show current entry and all children
1202 As special cases, a nil or t value means show all contexts in
1203 `minimal' or `canonical' view, respectively.
1205 Some views can make displayed information very compact, but also
1206 make it harder to edit the location of the match. In such
1207 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1208 more context."
1209 :group 'org-reveal-location
1210 :version "26.1"
1211 :package-version '(Org . "9.0")
1212 :type '(choice
1213 (const :tag "Canonical" t)
1214 (const :tag "Minimal" nil)
1215 (repeat :greedy t :tag "Individual contexts"
1216 (cons
1217 (choice :tag "Context"
1218 (const agenda)
1219 (const org-goto)
1220 (const occur-tree)
1221 (const tags-tree)
1222 (const link-search)
1223 (const mark-goto)
1224 (const bookmark-jump)
1225 (const isearch)
1226 (const default))
1227 (choice :tag "Detail level"
1228 (const minimal)
1229 (const local)
1230 (const ancestors)
1231 (const lineage)
1232 (const tree)
1233 (const canonical))))))
1235 (defcustom org-indirect-buffer-display 'other-window
1236 "How should indirect tree buffers be displayed?
1238 This applies to indirect buffers created with the commands
1239 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1241 Valid values are:
1242 current-window Display in the current window
1243 other-window Just display in another window.
1244 dedicated-frame Create one new frame, and re-use it each time.
1245 new-frame Make a new frame each time. Note that in this case
1246 previously-made indirect buffers are kept, and you need to
1247 kill these buffers yourself."
1248 :group 'org-structure
1249 :group 'org-agenda-windows
1250 :type '(choice
1251 (const :tag "In current window" current-window)
1252 (const :tag "In current frame, other window" other-window)
1253 (const :tag "Each time a new frame" new-frame)
1254 (const :tag "One dedicated frame" dedicated-frame)))
1256 (defcustom org-use-speed-commands nil
1257 "Non-nil means activate single letter commands at beginning of a headline.
1258 This may also be a function to test for appropriate locations where speed
1259 commands should be active.
1261 For example, to activate speed commands when the point is on any
1262 star at the beginning of the headline, you can do this:
1264 (setq org-use-speed-commands
1265 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1266 :group 'org-structure
1267 :type '(choice
1268 (const :tag "Never" nil)
1269 (const :tag "At beginning of headline stars" t)
1270 (function)))
1272 (defcustom org-speed-commands-user nil
1273 "Alist of additional speed commands.
1274 This list will be checked before `org-speed-commands-default'
1275 when the variable `org-use-speed-commands' is non-nil
1276 and when the cursor is at the beginning of a headline.
1277 The car if each entry is a string with a single letter, which must
1278 be assigned to `self-insert-command' in the global map.
1279 The cdr is either a command to be called interactively, a function
1280 to be called, or a form to be evaluated.
1281 An entry that is just a list with a single string will be interpreted
1282 as a descriptive headline that will be added when listing the speed
1283 commands in the Help buffer using the `?' speed command."
1284 :group 'org-structure
1285 :type '(repeat :value ("k" . ignore)
1286 (choice :value ("k" . ignore)
1287 (list :tag "Descriptive Headline" (string :tag "Headline"))
1288 (cons :tag "Letter and Command"
1289 (string :tag "Command letter")
1290 (choice
1291 (function)
1292 (sexp))))))
1294 (defcustom org-bookmark-names-plist
1295 '(:last-capture "org-capture-last-stored"
1296 :last-refile "org-refile-last-stored"
1297 :last-capture-marker "org-capture-last-stored-marker")
1298 "Names for bookmarks automatically set by some Org commands.
1299 This can provide strings as names for a number of bookmarks Org sets
1300 automatically. The following keys are currently implemented:
1301 :last-capture
1302 :last-capture-marker
1303 :last-refile
1304 When a key does not show up in the property list, the corresponding bookmark
1305 is not set."
1306 :group 'org-structure
1307 :type 'plist)
1309 (defgroup org-cycle nil
1310 "Options concerning visibility cycling in Org mode."
1311 :tag "Org Cycle"
1312 :group 'org-structure)
1314 (defcustom org-cycle-skip-children-state-if-no-children t
1315 "Non-nil means skip CHILDREN state in entries that don't have any."
1316 :group 'org-cycle
1317 :type 'boolean)
1319 (defcustom org-cycle-max-level nil
1320 "Maximum level which should still be subject to visibility cycling.
1321 Levels higher than this will, for cycling, be treated as text, not a headline.
1322 When `org-odd-levels-only' is set, a value of N in this variable actually
1323 means 2N-1 stars as the limiting headline.
1324 When nil, cycle all levels.
1325 Note that the limiting level of cycling is also influenced by
1326 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1327 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1328 than its value."
1329 :group 'org-cycle
1330 :type '(choice
1331 (const :tag "No limit" nil)
1332 (integer :tag "Maximum level")))
1334 (defcustom org-hide-block-startup nil
1335 "Non-nil means entering Org mode will fold all blocks.
1336 This can also be set in on a per-file basis with
1338 #+STARTUP: hideblocks
1339 #+STARTUP: showblocks"
1340 :group 'org-startup
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-global-at-bob nil
1345 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1347 This makes it possible to do global cycling without having to use `S-TAB'
1348 or `\\[universal-argument] TAB'. For this special case to work, the first \
1349 line of the buffer
1350 must not be a headline -- it may be empty or some other text.
1352 When used in this way, `org-cycle-hook' is disabled temporarily to make
1353 sure the cursor stays at the beginning of the buffer.
1355 When this option is nil, don't do anything special at the beginning of
1356 the buffer."
1357 :group 'org-cycle
1358 :type 'boolean)
1360 (defcustom org-cycle-level-after-item/entry-creation t
1361 "Non-nil means cycle entry level or item indentation in new empty entries.
1363 When the cursor is at the end of an empty headline, i.e., with only stars
1364 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1365 and then all possible ancestor states, before returning to the original state.
1366 This makes data entry extremely fast: M-RET to create a new headline,
1367 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1369 When the cursor is at the end of an empty plain list item, one TAB will
1370 make it a subitem, two or more tabs will back up to make this an item
1371 higher up in the item hierarchy."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-emulate-tab t
1376 "Where should `org-cycle' emulate TAB.
1377 nil Never
1378 white Only in completely white lines
1379 whitestart Only at the beginning of lines, before the first non-white char
1380 t Everywhere except in headlines
1381 exc-hl-bol Everywhere except at the start of a headline
1382 If TAB is used in a place where it does not emulate TAB, the current subtree
1383 visibility is cycled."
1384 :group 'org-cycle
1385 :type '(choice (const :tag "Never" nil)
1386 (const :tag "Only in completely white lines" white)
1387 (const :tag "Before first char in a line" whitestart)
1388 (const :tag "Everywhere except in headlines" t)
1389 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1391 (defcustom org-cycle-separator-lines 2
1392 "Number of empty lines needed to keep an empty line between collapsed trees.
1393 If you leave an empty line between the end of a subtree and the following
1394 headline, this empty line is hidden when the subtree is folded.
1395 Org mode will leave (exactly) one empty line visible if the number of
1396 empty lines is equal or larger to the number given in this variable.
1397 So the default 2 means at least 2 empty lines after the end of a subtree
1398 are needed to produce free space between a collapsed subtree and the
1399 following headline.
1401 If the number is negative, and the number of empty lines is at least -N,
1402 all empty lines are shown.
1404 Special case: when 0, never leave empty lines in collapsed view."
1405 :group 'org-cycle
1406 :type 'integer)
1407 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1409 (defcustom org-pre-cycle-hook nil
1410 "Hook that is run before visibility cycling is happening.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that will be set right after running this hook. The
1413 argument is a symbol. Before a global state change, it can have the values
1414 `overview', `content', or `all'. Before a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook)
1419 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1420 org-cycle-hide-drawers
1421 org-cycle-show-empty-lines
1422 org-optimize-window-after-visibility-change)
1423 "Hook that is run after `org-cycle' has changed the buffer visibility.
1424 The function(s) in this hook must accept a single argument which indicates
1425 the new state that was set by the most recent `org-cycle' command. The
1426 argument is a symbol. After a global state change, it can have the values
1427 `overview', `contents', or `all'. After a local state change, it can have
1428 the values `folded', `children', or `subtree'."
1429 :group 'org-cycle
1430 :type 'hook
1431 :version "26.1"
1432 :package-version '(Org . "8.3"))
1434 (defgroup org-edit-structure nil
1435 "Options concerning structure editing in Org mode."
1436 :tag "Org Edit Structure"
1437 :group 'org-structure)
1439 (defcustom org-odd-levels-only nil
1440 "Non-nil means skip even levels and only use odd levels for the outline.
1441 This has the effect that two stars are being added/taken away in
1442 promotion/demotion commands. It also influences how levels are
1443 handled by the exporters.
1444 Changing it requires restart of `font-lock-mode' to become effective
1445 for fontification also in regions already fontified.
1446 You may also set this on a per-file basis by adding one of the following
1447 lines to the buffer:
1449 #+STARTUP: odd
1450 #+STARTUP: oddeven"
1451 :group 'org-edit-structure
1452 :group 'org-appearance
1453 :type 'boolean)
1455 (defcustom org-adapt-indentation t
1456 "Non-nil means adapt indentation to outline node level.
1458 When this variable is set, Org assumes that you write outlines by
1459 indenting text in each node to align with the headline (after the
1460 stars). The following issues are influenced by this variable:
1462 - The indentation is increased by one space in a demotion
1463 command, and decreased by one in a promotion command. However,
1464 in the latter case, if shifting some line in the entry body
1465 would alter document structure (e.g., insert a new headline),
1466 indentation is not changed at all.
1468 - Property drawers and planning information is inserted indented
1469 when this variable is set. When nil, they will not be indented.
1471 - TAB indents a line relative to current level. The lines below
1472 a headline will be indented when this variable is set.
1474 Note that this is all about true indentation, by adding and
1475 removing space characters. See also `org-indent.el' which does
1476 level-dependent indentation in a virtual way, i.e. at display
1477 time in Emacs."
1478 :group 'org-edit-structure
1479 :type 'boolean)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 \\<org-mode-map>
1619 When nil, the new heading is created directly after the current line.
1620 The commands `\\[org-insert-heading-respect-content]' and \
1621 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1622 for the duration of the command."
1623 :group 'org-structure
1624 :type 'boolean)
1626 (defcustom org-blank-before-new-entry '((heading . auto)
1627 (plain-list-item . auto))
1628 "Should `org-insert-heading' leave a blank line before new heading/item?
1629 The value is an alist, with `heading' and `plain-list-item' as CAR,
1630 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1631 which case Org will look at the surrounding headings/items and try to
1632 make an intelligent decision whether to insert a blank line or not."
1633 :group 'org-edit-structure
1634 :type '(list
1635 (cons (const heading)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))
1639 (cons (const plain-list-item)
1640 (choice (const :tag "Never" nil)
1641 (const :tag "Always" t)
1642 (const :tag "Auto" auto)))))
1644 (defcustom org-insert-heading-hook nil
1645 "Hook being run after inserting a new heading."
1646 :group 'org-edit-structure
1647 :type 'hook)
1649 (defcustom org-enable-fixed-width-editor t
1650 "Non-nil means lines starting with \":\" are treated as fixed-width.
1651 This currently only means they are never auto-wrapped.
1652 When nil, such lines will be treated like ordinary lines."
1653 :group 'org-edit-structure
1654 :type 'boolean)
1656 (defgroup org-sparse-trees nil
1657 "Options concerning sparse trees in Org mode."
1658 :tag "Org Sparse Trees"
1659 :group 'org-structure)
1661 (defcustom org-highlight-sparse-tree-matches t
1662 "Non-nil means highlight all matches that define a sparse tree.
1663 The highlights will automatically disappear the next time the buffer is
1664 changed by an edit command."
1665 :group 'org-sparse-trees
1666 :type 'boolean)
1668 (defcustom org-remove-highlights-with-change t
1669 "Non-nil means any change to the buffer will remove temporary highlights.
1670 \\<org-mode-map>\
1671 Such highlights are created by `org-occur' and `org-clock-display'.
1672 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1673 to get rid of the highlights.
1674 The highlights created by `org-toggle-latex-fragment' always need
1675 `\\[org-toggle-latex-fragment]' to be removed."
1676 :group 'org-sparse-trees
1677 :group 'org-time
1678 :type 'boolean)
1680 (defcustom org-occur-case-fold-search t
1681 "Non-nil means `org-occur' should be case-insensitive.
1682 If set to `smart' the search will be case-insensitive only if it
1683 doesn't specify any upper case character."
1684 :group 'org-sparse-trees
1685 :version "26.1"
1686 :type '(choice
1687 (const :tag "Case-sensitive" nil)
1688 (const :tag "Case-insensitive" t)
1689 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1691 (defcustom org-occur-hook '(org-first-headline-recenter)
1692 "Hook that is run after `org-occur' has constructed a sparse tree.
1693 This can be used to recenter the window to show as much of the structure
1694 as possible."
1695 :group 'org-sparse-trees
1696 :type 'hook)
1698 (defgroup org-table nil
1699 "Options concerning tables in Org mode."
1700 :tag "Org Table"
1701 :group 'org)
1703 (defcustom org-self-insert-cluster-for-undo nil
1704 "Non-nil means cluster self-insert commands for undo when possible.
1705 If this is set, then, like in the Emacs command loop, 20 consecutive
1706 characters will be undone together.
1707 This is configurable, because there is some impact on typing performance."
1708 :group 'org-table
1709 :type 'boolean)
1711 (defcustom org-table-tab-recognizes-table.el t
1712 "Non-nil means TAB will automatically notice a table.el table.
1713 When it sees such a table, it moves point into it and - if necessary -
1714 calls `table-recognize-table'."
1715 :group 'org-table-editing
1716 :type 'boolean)
1718 (defgroup org-link nil
1719 "Options concerning links in Org mode."
1720 :tag "Org Link"
1721 :group 'org)
1723 (defvar-local org-link-abbrev-alist-local nil
1724 "Buffer-local version of `org-link-abbrev-alist', which see.
1725 The value of this is taken from the #+LINK lines.")
1727 (defcustom org-link-parameters
1728 '(("doi" :follow org--open-doi-link)
1729 ("elisp" :follow org--open-elisp-link)
1730 ("file" :complete org-file-complete-link)
1731 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1732 ("help" :follow org--open-help-link)
1733 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1734 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1735 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1736 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1737 ("shell" :follow org--open-shell-link))
1738 "An alist of properties that defines all the links in Org mode.
1739 The key in each association is a string of the link type.
1740 Subsequent optional elements make up a p-list of link properties.
1742 :follow - A function that takes the link path as an argument.
1744 :export - A function that takes the link path, description and
1745 export-backend as arguments.
1747 :store - A function responsible for storing the link. See the
1748 function `org-store-link-functions'.
1750 :complete - A function that inserts a link with completion. The
1751 function takes one optional prefix arg.
1753 :face - A face for the link, or a function that returns a face.
1754 The function takes one argument which is the link path. The
1755 default face is `org-link'.
1757 :mouse-face - The mouse-face. The default is `highlight'.
1759 :display - `full' will not fold the link in descriptive
1760 display. Default is `org-link'.
1762 :help-echo - A string or function that takes (window object position)
1763 as arguments and returns a string.
1765 :keymap - A keymap that is active on the link. The default is
1766 `org-mouse-map'.
1768 :htmlize-link - A function for the htmlize-link. Defaults
1769 to (list :uri \"type:path\")
1771 :activate-func - A function to run at the end of font-lock
1772 activation. The function must accept (link-start link-end path bracketp)
1773 as arguments."
1774 :group 'org-link
1775 :type '(alist :tag "Link display parameters"
1776 :value-type plist)
1777 :version "26.1"
1778 :package-version '(Org . "9.1"))
1780 (defun org-link-get-parameter (type key)
1781 "Get TYPE link property for KEY.
1782 TYPE is a string and KEY is a plist keyword."
1783 (plist-get
1784 (cdr (assoc type org-link-parameters))
1785 key))
1787 (defun org-link-set-parameters (type &rest parameters)
1788 "Set link TYPE properties to PARAMETERS.
1789 PARAMETERS should be :key val pairs."
1790 (let ((data (assoc type org-link-parameters)))
1791 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1792 (push (cons type parameters) org-link-parameters)
1793 (org-make-link-regexps)
1794 (org-element-update-syntax))))
1796 (defun org-link-types ()
1797 "Return a list of known link types."
1798 (mapcar #'car org-link-parameters))
1800 (defcustom org-link-abbrev-alist nil
1801 "Alist of link abbreviations.
1802 The car of each element is a string, to be replaced at the start of a link.
1803 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1804 links in Org buffers can have an optional tag after a double colon, e.g.,
1806 [[linkkey:tag][description]]
1808 The `linkkey' must be a single word, starting with a letter, followed
1809 by letters, numbers, `-' or `_'.
1811 If REPLACE is a string, the tag will simply be appended to create the link.
1812 If the string contains \"%s\", the tag will be inserted there. If the string
1813 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1814 at that point (see the function `url-hexify-string'). If the string contains
1815 the specifier \"%(my-function)\", then the custom function `my-function' will
1816 be invoked: this function takes the tag as its only argument and must return
1817 a string.
1819 REPLACE may also be a function that will be called with the tag as the
1820 only argument to create the link, which should be returned as a string.
1822 See the manual for examples."
1823 :group 'org-link
1824 :type '(repeat
1825 (cons
1826 (string :tag "Protocol")
1827 (choice
1828 (string :tag "Format")
1829 (function)))))
1831 (defcustom org-descriptive-links t
1832 "Non-nil means Org will display descriptive links.
1833 E.g. [[http://orgmode.org][Org website]] will be displayed as
1834 \"Org Website\", hiding the link itself and just displaying its
1835 description. When set to nil, Org will display the full links
1836 literally.
1838 You can interactively set the value of this variable by calling
1839 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1840 :group 'org-link
1841 :type 'boolean)
1843 (defcustom org-link-file-path-type 'adaptive
1844 "How the path name in file links should be stored.
1845 Valid values are:
1847 relative Relative to the current directory, i.e. the directory of the file
1848 into which the link is being inserted.
1849 absolute Absolute path, if possible with ~ for home directory.
1850 noabbrev Absolute path, no abbreviation of home directory.
1851 adaptive Use relative path for files in the current directory and sub-
1852 directories of it. For other files, use an absolute path."
1853 :group 'org-link
1854 :type '(choice
1855 (const relative)
1856 (const absolute)
1857 (const noabbrev)
1858 (const adaptive)))
1860 (defvaralias 'org-activate-links 'org-highlight-links)
1861 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1862 "Types of links that should be highlighted in Org files.
1864 This is a list of symbols, each one of them leading to the
1865 highlighting of a certain link type.
1867 You can still open links that are not highlighted.
1869 In principle, it does not hurt to turn on highlighting for all
1870 link types. There may be a small gain when turning off unused
1871 link types. The types are:
1873 bracket The recommended [[link][description]] or [[link]] links with hiding.
1874 angle Links in angular brackets that may contain whitespace like
1875 <bbdb:Carsten Dominik>.
1876 plain Plain links in normal text, no whitespace, like http://google.com.
1877 radio Text that is matched by a radio target, see manual for details.
1878 tag Tag settings in a headline (link to tag search).
1879 date Time stamps (link to calendar).
1880 footnote Footnote labels.
1882 If you set this variable during an Emacs session, use `org-mode-restart'
1883 in the Org buffer so that the change takes effect."
1884 :group 'org-link
1885 :group 'org-appearance
1886 :type '(set :greedy t
1887 (const :tag "Double bracket links" bracket)
1888 (const :tag "Angular bracket links" angle)
1889 (const :tag "Plain text links" plain)
1890 (const :tag "Radio target matches" radio)
1891 (const :tag "Tags" tag)
1892 (const :tag "Timestamps" date)
1893 (const :tag "Footnotes" footnote)))
1895 (defcustom org-make-link-description-function nil
1896 "Function to use for generating link descriptions from links.
1897 This function must take two parameters: the first one is the
1898 link, the second one is the description generated by
1899 `org-insert-link'. The function should return the description to
1900 use."
1901 :group 'org-link
1902 :type '(choice (const nil) (function)))
1904 (defgroup org-link-store nil
1905 "Options concerning storing links in Org mode."
1906 :tag "Org Store Link"
1907 :group 'org-link)
1909 (defcustom org-url-hexify-p t
1910 "When non-nil, hexify URL when creating a link."
1911 :type 'boolean
1912 :version "24.3"
1913 :group 'org-link-store)
1915 (defcustom org-email-link-description-format "Email %c: %.30s"
1916 "Format of the description part of a link to an email or usenet message.
1917 The following %-escapes will be replaced by corresponding information:
1919 %F full \"From\" field
1920 %f name, taken from \"From\" field, address if no name
1921 %T full \"To\" field
1922 %t first name in \"To\" field, address if no name
1923 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1924 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1925 %s subject
1926 %d date
1927 %m message-id.
1929 You may use normal field width specification between the % and the letter.
1930 This is for example useful to limit the length of the subject.
1932 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1933 :group 'org-link-store
1934 :type 'string)
1936 (defcustom org-from-is-user-regexp
1937 (let (r1 r2)
1938 (when (and user-mail-address (not (string= user-mail-address "")))
1939 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1940 (when (and user-full-name (not (string= user-full-name "")))
1941 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1942 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1943 "Regexp matched against the \"From:\" header of an email or usenet message.
1944 It should match if the message is from the user him/herself."
1945 :group 'org-link-store
1946 :type 'regexp)
1948 (defcustom org-context-in-file-links t
1949 "Non-nil means file links from `org-store-link' contain context.
1950 \\<org-mode-map>
1951 A search string will be added to the file name with :: as separator
1952 and used to find the context when the link is activated by the command
1953 `org-open-at-point'. When this option is t, the entire active region
1954 will be placed in the search string of the file link. If set to a
1955 positive integer, only the first n lines of context will be stored.
1957 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1958 \\[org-store-link]')
1959 negates this setting for the duration of the command."
1960 :group 'org-link-store
1961 :type '(choice boolean integer))
1963 (defcustom org-keep-stored-link-after-insertion nil
1964 "Non-nil means keep link in list for entire session.
1965 \\<org-mode-map>
1966 The command `org-store-link' adds a link pointing to the current
1967 location to an internal list. These links accumulate during a session.
1968 The command `org-insert-link' can be used to insert links into any
1969 Org file (offering completion for all stored links).
1971 When this option is nil, every link which has been inserted once using
1972 `\\[org-insert-link]' will be removed from the list, to make completing the \
1973 unused
1974 links more efficient."
1975 :group 'org-link-store
1976 :type 'boolean)
1978 (defgroup org-link-follow nil
1979 "Options concerning following links in Org mode."
1980 :tag "Org Follow Link"
1981 :group 'org-link)
1983 (defcustom org-link-translation-function nil
1984 "Function to translate links with different syntax to Org syntax.
1985 This can be used to translate links created for example by the Planner
1986 or emacs-wiki packages to Org syntax.
1987 The function must accept two parameters, a TYPE containing the link
1988 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1989 which is everything after the link protocol. It should return a cons
1990 with possibly modified values of type and path.
1991 Org contains a function for this, so if you set this variable to
1992 `org-translate-link-from-planner', you should be able follow many
1993 links created by planner."
1994 :group 'org-link-follow
1995 :type '(choice (const nil) (function)))
1997 (defcustom org-follow-link-hook nil
1998 "Hook that is run after a link has been followed."
1999 :group 'org-link-follow
2000 :type 'hook)
2002 (defcustom org-tab-follows-link nil
2003 "Non-nil means on links TAB will follow the link.
2004 Needs to be set before org.el is loaded.
2005 This really should not be used, it does not make sense, and the
2006 implementation is bad."
2007 :group 'org-link-follow
2008 :type 'boolean)
2010 (defcustom org-return-follows-link nil
2011 "Non-nil means on links RET will follow the link.
2012 In tables, the special behavior of RET has precedence."
2013 :group 'org-link-follow
2014 :type 'boolean)
2016 (defcustom org-mouse-1-follows-link
2017 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2018 "Non-nil means mouse-1 on a link will follow the link.
2019 A longer mouse click will still set point. Needs to be set
2020 before org.el is loaded."
2021 :group 'org-link-follow
2022 :version "26.1"
2023 :package-version '(Org . "8.3")
2024 :type '(choice
2025 (const :tag "A double click follows the link" double)
2026 (const :tag "Unconditionally follow the link with mouse-1" t)
2027 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2029 (defcustom org-mark-ring-length 4
2030 "Number of different positions to be recorded in the ring.
2031 Changing this requires a restart of Emacs to work correctly."
2032 :group 'org-link-follow
2033 :type 'integer)
2035 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2036 "Non-nil means internal fuzzy links can only match headlines.
2038 When nil, the a fuzzy link may point to a target or a named
2039 construct in the document. When set to the special value
2040 `query-to-create', offer to create a new headline when none
2041 matched.
2043 Spaces and statistics cookies are ignored during heading searches."
2044 :group 'org-link-follow
2045 :version "24.1"
2046 :type '(choice
2047 (const :tag "Use fuzzy text search" nil)
2048 (const :tag "Match only exact headline" t)
2049 (const :tag "Match exact headline or query to create it"
2050 query-to-create))
2051 :safe #'symbolp)
2053 (defcustom org-link-frame-setup
2054 '((vm . vm-visit-folder-other-frame)
2055 (vm-imap . vm-visit-imap-folder-other-frame)
2056 (gnus . org-gnus-no-new-news)
2057 (file . find-file-other-window)
2058 (wl . wl-other-frame))
2059 "Setup the frame configuration for following links.
2060 When following a link with Emacs, it may often be useful to display
2061 this link in another window or frame. This variable can be used to
2062 set this up for the different types of links.
2063 For VM, use any of
2064 `vm-visit-folder'
2065 `vm-visit-folder-other-window'
2066 `vm-visit-folder-other-frame'
2067 For Gnus, use any of
2068 `gnus'
2069 `gnus-other-frame'
2070 `org-gnus-no-new-news'
2071 For FILE, use any of
2072 `find-file'
2073 `find-file-other-window'
2074 `find-file-other-frame'
2075 For Wanderlust use any of
2076 `wl'
2077 `wl-other-frame'
2078 For the calendar, use the variable `calendar-setup'.
2079 For BBDB, it is currently only possible to display the matches in
2080 another window."
2081 :group 'org-link-follow
2082 :type '(list
2083 (cons (const vm)
2084 (choice
2085 (const vm-visit-folder)
2086 (const vm-visit-folder-other-window)
2087 (const vm-visit-folder-other-frame)))
2088 (cons (const vm-imap)
2089 (choice
2090 (const vm-visit-imap-folder)
2091 (const vm-visit-imap-folder-other-window)
2092 (const vm-visit-imap-folder-other-frame)))
2093 (cons (const gnus)
2094 (choice
2095 (const gnus)
2096 (const gnus-other-frame)
2097 (const org-gnus-no-new-news)))
2098 (cons (const file)
2099 (choice
2100 (const find-file)
2101 (const find-file-other-window)
2102 (const find-file-other-frame)))
2103 (cons (const wl)
2104 (choice
2105 (const wl)
2106 (const wl-other-frame)))))
2108 (defcustom org-display-internal-link-with-indirect-buffer nil
2109 "Non-nil means use indirect buffer to display infile links.
2110 Activating internal links (from one location in a file to another location
2111 in the same file) normally just jumps to the location. When the link is
2112 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2113 is displayed in
2114 another window. When this option is set, the other window actually displays
2115 an indirect buffer clone of the current buffer, to avoid any visibility
2116 changes to the current buffer."
2117 :group 'org-link-follow
2118 :type 'boolean)
2120 (defcustom org-open-non-existing-files nil
2121 "Non-nil means `org-open-file' will open non-existing files.
2122 When nil, an error will be generated.
2123 This variable applies only to external applications because they
2124 might choke on non-existing files. If the link is to a file that
2125 will be opened in Emacs, the variable is ignored."
2126 :group 'org-link-follow
2127 :type 'boolean)
2129 (defcustom org-open-directory-means-index-dot-org nil
2130 "Non-nil means a link to a directory really means to index.org.
2131 When nil, following a directory link will run dired or open a finder/explorer
2132 window on that directory."
2133 :group 'org-link-follow
2134 :type 'boolean)
2136 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2137 "Non-nil means ask for confirmation before executing shell links.
2138 Shell links can be dangerous: just think about a link
2140 [[shell:rm -rf ~/*][Google Search]]
2142 This link would show up in your Org document as \"Google Search\",
2143 but really it would remove your entire home directory.
2144 Therefore we advise against setting this variable to nil.
2145 Just change it to `y-or-n-p' if you want to confirm with a
2146 single keystroke rather than having to type \"yes\"."
2147 :group 'org-link-follow
2148 :type '(choice
2149 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2150 (const :tag "with y-or-n (faster)" y-or-n-p)
2151 (const :tag "no confirmation (dangerous)" nil)))
2152 (put 'org-confirm-shell-link-function
2153 'safe-local-variable
2154 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2156 (defcustom org-confirm-shell-link-not-regexp ""
2157 "A regexp to skip confirmation for shell links."
2158 :group 'org-link-follow
2159 :version "24.1"
2160 :type 'regexp)
2162 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2163 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2164 Elisp links can be dangerous: just think about a link
2166 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2168 This link would show up in your Org document as \"Google Search\",
2169 but really it would remove your entire home directory.
2170 Therefore we advise against setting this variable to nil.
2171 Just change it to `y-or-n-p' if you want to confirm with a
2172 single keystroke rather than having to type \"yes\"."
2173 :group 'org-link-follow
2174 :type '(choice
2175 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2176 (const :tag "with y-or-n (faster)" y-or-n-p)
2177 (const :tag "no confirmation (dangerous)" nil)))
2178 (put 'org-confirm-shell-link-function
2179 'safe-local-variable
2180 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2182 (defcustom org-confirm-elisp-link-not-regexp ""
2183 "A regexp to skip confirmation for Elisp links."
2184 :group 'org-link-follow
2185 :version "24.1"
2186 :type 'regexp)
2188 (defconst org-file-apps-defaults-gnu
2189 '((remote . emacs)
2190 (system . mailcap)
2191 (t . mailcap))
2192 "Default file applications on a UNIX or GNU/Linux system.
2193 See `org-file-apps'.")
2195 (defconst org-file-apps-defaults-macosx
2196 '((remote . emacs)
2197 (system . "open %s")
2198 ("ps.gz" . "gv %s")
2199 ("eps.gz" . "gv %s")
2200 ("dvi" . "xdvi %s")
2201 ("fig" . "xfig %s")
2202 (t . "open %s"))
2203 "Default file applications on a macOS system.
2204 The system \"open\" is known as a default, but we use X11 applications
2205 for some files for which the OS does not have a good default.
2206 See `org-file-apps'.")
2208 (defconst org-file-apps-defaults-windowsnt
2209 (list '(remote . emacs)
2210 (cons 'system (lambda (file _path)
2211 (with-no-warnings (w32-shell-execute "open" file))))
2212 (cons t (lambda (file _path)
2213 (with-no-warnings (w32-shell-execute "open" file)))))
2214 "Default file applications on a Windows NT system.
2215 The system \"open\" is used for most files.
2216 See `org-file-apps'.")
2218 (defcustom org-file-apps
2219 '((auto-mode . emacs)
2220 ("\\.mm\\'" . default)
2221 ("\\.x?html?\\'" . default)
2222 ("\\.pdf\\'" . default))
2223 "External applications for opening `file:path' items in a document.
2224 \\<org-mode-map>\
2226 Org mode uses system defaults for different file types, but
2227 you can use this variable to set the application for a given file
2228 extension. The entries in this list are cons cells where the car identifies
2229 files and the cdr the corresponding command.
2231 Possible values for the file identifier are:
2233 \"string\" A string as a file identifier can be interpreted in different
2234 ways, depending on its contents:
2236 - Alphanumeric characters only:
2237 Match links with this file extension.
2238 Example: (\"pdf\" . \"evince %s\")
2239 to open PDFs with evince.
2241 - Regular expression: Match links where the
2242 filename matches the regexp. If you want to
2243 use groups here, use shy groups.
2245 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2246 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2247 to open *.html and *.xhtml with firefox.
2249 - Regular expression which contains (non-shy) groups:
2250 Match links where the whole link, including \"::\", and
2251 anything after that, matches the regexp.
2252 In a custom command string, %1, %2, etc. are replaced with
2253 the parts of the link that were matched by the groups.
2254 For backwards compatibility, if a command string is given
2255 that does not use any of the group matches, this case is
2256 handled identically to the second one (i.e. match against
2257 file name only).
2258 In a custom function, you can access the group matches with
2259 (match-string n link).
2261 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2262 \"evince -p %1 %s\")
2263 to open [[file:document.pdf::5]] with evince at page 5.
2265 `directory' Matches a directory
2266 `remote' Matches a remote file, accessible through tramp or efs.
2267 Remote files most likely should be visited through Emacs
2268 because external applications cannot handle such paths.
2269 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2270 so all files Emacs knows how to handle. Using this with
2271 command `emacs' will open most files in Emacs. Beware that this
2272 will also open html files inside Emacs, unless you add
2273 (\"html\" . default) to the list as well.
2274 `system' The system command to open files, like `open' on Windows
2275 and macOS, and mailcap under GNU/Linux. This is the command
2276 that will be selected if you call `org-open-at-point' with a
2277 double prefix argument (`\\[universal-argument] \
2278 \\[universal-argument] \\[org-open-at-point]').
2279 t Default for files not matched by any of the other options.
2281 Possible values for the command are:
2283 `emacs' The file will be visited by the current Emacs process.
2284 `default' Use the default application for this file type, which is the
2285 association for t in the list, most likely in the system-specific
2286 part. This can be used to overrule an unwanted setting in the
2287 system-specific variable.
2288 `system' Use the system command for opening files, like \"open\".
2289 This command is specified by the entry whose car is `system'.
2290 Most likely, the system-specific version of this variable
2291 does define this command, but you can overrule/replace it
2292 here.
2293 `mailcap' Use command specified in the mailcaps.
2294 string A command to be executed by a shell; %s will be replaced
2295 by the path to the file.
2296 function A Lisp function, which will be called with two arguments:
2297 the file path and the original link string, without the
2298 \"file:\" prefix.
2300 For more examples, see the system specific constants
2301 `org-file-apps-defaults-macosx'
2302 `org-file-apps-defaults-windowsnt'
2303 `org-file-apps-defaults-gnu'."
2304 :group 'org-link-follow
2305 :type '(repeat
2306 (cons (choice :value ""
2307 (string :tag "Extension")
2308 (const :tag "System command to open files" system)
2309 (const :tag "Default for unrecognized files" t)
2310 (const :tag "Remote file" remote)
2311 (const :tag "Links to a directory" directory)
2312 (const :tag "Any files that have Emacs modes"
2313 auto-mode))
2314 (choice :value ""
2315 (const :tag "Visit with Emacs" emacs)
2316 (const :tag "Use default" default)
2317 (const :tag "Use the system command" system)
2318 (string :tag "Command")
2319 (function :tag "Function")))))
2321 (defcustom org-doi-server-url "http://dx.doi.org/"
2322 "The URL of the DOI server."
2323 :type 'string
2324 :version "24.3"
2325 :group 'org-link-follow)
2327 (defgroup org-refile nil
2328 "Options concerning refiling entries in Org mode."
2329 :tag "Org Refile"
2330 :group 'org)
2332 (defcustom org-directory "~/org"
2333 "Directory with Org files.
2334 This is just a default location to look for Org files. There is no need
2335 at all to put your files into this directory. It is used in the
2336 following situations:
2338 1. When a capture template specifies a target file that is not an
2339 absolute path. The path will then be interpreted relative to
2340 `org-directory'
2341 2. When the value of variable `org-agenda-files' is a single file, any
2342 relative paths in this file will be taken as relative to
2343 `org-directory'."
2344 :group 'org-refile
2345 :group 'org-capture
2346 :type 'directory)
2348 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2349 "Default target for storing notes.
2350 Used as a fall back file for org-capture.el, for templates that
2351 do not specify a target file."
2352 :group 'org-refile
2353 :group 'org-capture
2354 :type 'file)
2356 (defcustom org-reverse-note-order nil
2357 "Non-nil means store new notes at the beginning of a file or entry.
2358 When nil, new notes will be filed to the end of a file or entry.
2359 This can also be a list with cons cells of regular expressions that
2360 are matched against file names, and values."
2361 :group 'org-capture
2362 :group 'org-refile
2363 :type '(choice
2364 (const :tag "Reverse always" t)
2365 (const :tag "Reverse never" nil)
2366 (repeat :tag "By file name regexp"
2367 (cons regexp boolean))))
2369 (defcustom org-log-refile nil
2370 "Information to record when a task is refiled.
2372 Possible values are:
2374 nil Don't add anything
2375 time Add a time stamp to the task
2376 note Prompt for a note and add it with template `org-log-note-headings'
2378 This option can also be set with on a per-file-basis with
2380 #+STARTUP: nologrefile
2381 #+STARTUP: logrefile
2382 #+STARTUP: lognoterefile
2384 You can have local logging settings for a subtree by setting the LOGGING
2385 property to one or more of these keywords.
2387 When bulk-refiling from the agenda, the value `note' is forbidden and
2388 will temporarily be changed to `time'."
2389 :group 'org-refile
2390 :group 'org-progress
2391 :version "24.1"
2392 :type '(choice
2393 (const :tag "No logging" nil)
2394 (const :tag "Record timestamp" time)
2395 (const :tag "Record timestamp with note." note)))
2397 (defcustom org-refile-targets nil
2398 "Targets for refiling entries with `\\[org-refile]'.
2399 This is a list of cons cells. Each cell contains:
2400 - a specification of the files to be considered, either a list of files,
2401 or a symbol whose function or variable value will be used to retrieve
2402 a file name or a list of file names. If you use `org-agenda-files' for
2403 that, all agenda files will be scanned for targets. Nil means consider
2404 headings in the current buffer.
2405 - A specification of how to find candidate refile targets. This may be
2406 any of:
2407 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2408 This tag has to be present in all target headlines, inheritance will
2409 not be considered.
2410 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2411 todo keyword.
2412 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2413 headlines that are refiling targets.
2414 - a cons cell (:level . N). Any headline of level N is considered a target.
2415 Note that, when `org-odd-levels-only' is set, level corresponds to
2416 order in hierarchy, not to the number of stars.
2417 - a cons cell (:maxlevel . N). Any headline with level <= N is 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.
2421 Each element of this list generates a set of possible targets.
2422 The union of these sets is presented (with completion) to
2423 the user by `org-refile'.
2425 You can set the variable `org-refile-target-verify-function' to a function
2426 to verify each headline found by the simple criteria above.
2428 When this variable is nil, all top-level headlines in the current buffer
2429 are used, equivalent to the value `((nil . (:level . 1))'."
2430 :group 'org-refile
2431 :type '(repeat
2432 (cons
2433 (choice :value org-agenda-files
2434 (const :tag "All agenda files" org-agenda-files)
2435 (const :tag "Current buffer" nil)
2436 (function) (variable) (file))
2437 (choice :tag "Identify target headline by"
2438 (cons :tag "Specific tag" (const :value :tag) (string))
2439 (cons :tag "TODO keyword" (const :value :todo) (string))
2440 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2441 (cons :tag "Level number" (const :value :level) (integer))
2442 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2444 (defcustom org-refile-target-verify-function nil
2445 "Function to verify if the headline at point should be a refile target.
2446 The function will be called without arguments, with point at the
2447 beginning of the headline. It should return t and leave point
2448 where it is if the headline is a valid target for refiling.
2450 If the target should not be selected, the function must return nil.
2451 In addition to this, it may move point to a place from where the search
2452 should be continued. For example, the function may decide that the entire
2453 subtree of the current entry should be excluded and move point to the end
2454 of the subtree."
2455 :group 'org-refile
2456 :type '(choice
2457 (const nil)
2458 (function)))
2460 (defcustom org-refile-use-cache nil
2461 "Non-nil means cache refile targets to speed up the process.
2462 \\<org-mode-map>\
2463 The cache for a particular file will be updated automatically when
2464 the buffer has been killed, or when any of the marker used for flagging
2465 refile targets no longer points at a live buffer.
2466 If you have added new entries to a buffer that might themselves be targets,
2467 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2468 if you find that easier, \
2469 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2470 \\[org-refile]'."
2471 :group 'org-refile
2472 :version "24.1"
2473 :type 'boolean)
2475 (defcustom org-refile-use-outline-path nil
2476 "Non-nil means provide refile targets as paths.
2477 So a level 3 headline will be available as level1/level2/level3.
2479 When the value is `file', also include the file name (without directory)
2480 into the path. In this case, you can also stop the completion after
2481 the file name, to get entries inserted as top level in the file.
2483 When `full-file-path', include the full file path.
2485 When `buffer-name', use the buffer name."
2486 :group 'org-refile
2487 :type '(choice
2488 (const :tag "Not" nil)
2489 (const :tag "Yes" t)
2490 (const :tag "Start with file name" file)
2491 (const :tag "Start with full file path" full-file-path)
2492 (const :tag "Start with buffer name" buffer-name)))
2494 (defcustom org-outline-path-complete-in-steps t
2495 "Non-nil means complete the outline path in hierarchical steps.
2496 When Org uses the refile interface to select an outline path (see
2497 `org-refile-use-outline-path'), the completion of the path can be
2498 done in a single go, or it can be done in steps down the headline
2499 hierarchy. Going in steps is probably the best if you do not use
2500 a special completion package like `ido' or `icicles'. However,
2501 when using these packages, going in one step can be very fast,
2502 while still showing the whole path to the entry."
2503 :group 'org-refile
2504 :type 'boolean)
2506 (defcustom org-refile-allow-creating-parent-nodes nil
2507 "Non-nil means allow the creation of new nodes as refile targets.
2508 New nodes are then created by adding \"/new node name\" to the completion
2509 of an existing node. When the value of this variable is `confirm',
2510 new node creation must be confirmed by the user (recommended).
2511 When nil, the completion must match an existing entry.
2513 Note that, if the new heading is not seen by the criteria
2514 listed in `org-refile-targets', multiple instances of the same
2515 heading would be created by trying again to file under the new
2516 heading."
2517 :group 'org-refile
2518 :type '(choice
2519 (const :tag "Never" nil)
2520 (const :tag "Always" t)
2521 (const :tag "Prompt for confirmation" confirm)))
2523 (defcustom org-refile-active-region-within-subtree nil
2524 "Non-nil means also refile active region within a subtree.
2526 By default `org-refile' doesn't allow refiling regions if they
2527 don't contain a set of subtrees, but it might be convenient to
2528 do so sometimes: in that case, the first line of the region is
2529 converted to a headline before refiling."
2530 :group 'org-refile
2531 :version "24.1"
2532 :type 'boolean)
2534 (defgroup org-todo nil
2535 "Options concerning TODO items in Org mode."
2536 :tag "Org TODO"
2537 :group 'org)
2539 (defgroup org-progress nil
2540 "Options concerning Progress logging in Org mode."
2541 :tag "Org Progress"
2542 :group 'org-time)
2544 (defvar org-todo-interpretation-widgets
2545 '((:tag "Sequence (cycling hits every state)" sequence)
2546 (:tag "Type (cycling directly to DONE)" type))
2547 "The available interpretation symbols for customizing `org-todo-keywords'.
2548 Interested libraries should add to this list.")
2550 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2551 "List of TODO entry keyword sequences and their interpretation.
2552 \\<org-mode-map>This is a list of sequences.
2554 Each sequence starts with a symbol, either `sequence' or `type',
2555 indicating if the keywords should be interpreted as a sequence of
2556 action steps, or as different types of TODO items. The first
2557 keywords are states requiring action - these states will select a headline
2558 for inclusion into the global TODO list Org produces. If one of the
2559 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2560 signify that no further action is necessary. If \"|\" is not found,
2561 the last keyword is treated as the only DONE state of the sequence.
2563 The command `\\[org-todo]' cycles an entry through these states, and one
2564 additional state where no keyword is present. For details about this
2565 cycling, see the manual.
2567 TODO keywords and interpretation can also be set on a per-file basis with
2568 the special #+SEQ_TODO and #+TYP_TODO lines.
2570 Each keyword can optionally specify a character for fast state selection
2571 \(in combination with the variable `org-use-fast-todo-selection')
2572 and specifiers for state change logging, using the same syntax that
2573 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2574 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2575 indicates to record a time stamp each time this state is selected.
2577 Each keyword may also specify if a timestamp or a note should be
2578 recorded when entering or leaving the state, by adding additional
2579 characters in the parenthesis after the keyword. This looks like this:
2580 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2581 record only the time of the state change. With X and Y being either
2582 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2583 Y when leaving the state if and only if the *target* state does not
2584 define X. You may omit any of the fast-selection key or X or /Y,
2585 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2587 For backward compatibility, this variable may also be just a list
2588 of keywords. In this case the interpretation (sequence or type) will be
2589 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2590 :group 'org-todo
2591 :group 'org-keywords
2592 :type '(choice
2593 (repeat :tag "Old syntax, just keywords"
2594 (string :tag "Keyword"))
2595 (repeat :tag "New syntax"
2596 (cons
2597 (choice
2598 :tag "Interpretation"
2599 ;;Quick and dirty way to see
2600 ;;`org-todo-interpretations'. This takes the
2601 ;;place of item arguments
2602 :convert-widget
2603 (lambda (widget)
2604 (widget-put widget
2605 :args (mapcar
2606 (lambda (x)
2607 (widget-convert
2608 (cons 'const x)))
2609 org-todo-interpretation-widgets))
2610 widget))
2611 (repeat
2612 (string :tag "Keyword"))))))
2614 (defvar-local org-todo-keywords-1 nil
2615 "All TODO and DONE keywords active in a buffer.")
2616 (defvar org-todo-keywords-for-agenda nil)
2617 (defvar org-done-keywords-for-agenda nil)
2618 (defvar org-todo-keyword-alist-for-agenda nil)
2619 (defvar org-tag-alist-for-agenda nil
2620 "Alist of all tags from all agenda files.")
2621 (defvar org-tag-groups-alist-for-agenda nil
2622 "Alist of all groups tags from all current agenda files.")
2623 (defvar-local org-tag-groups-alist nil)
2624 (defvar org-agenda-contributing-files nil)
2625 (defvar-local org-current-tag-alist nil
2626 "Alist of all tag groups in current buffer.
2627 This variable takes into consideration `org-tag-alist',
2628 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2629 (defvar-local org-not-done-keywords nil)
2630 (defvar-local org-done-keywords nil)
2631 (defvar-local org-todo-heads nil)
2632 (defvar-local org-todo-sets nil)
2633 (defvar-local org-todo-log-states nil)
2634 (defvar-local org-todo-kwd-alist nil)
2635 (defvar-local org-todo-key-alist nil)
2636 (defvar-local org-todo-key-trigger nil)
2638 (defcustom org-todo-interpretation 'sequence
2639 "Controls how TODO keywords are interpreted.
2640 This variable is in principle obsolete and is only used for
2641 backward compatibility, if the interpretation of todo keywords is
2642 not given already in `org-todo-keywords'. See that variable for
2643 more information."
2644 :group 'org-todo
2645 :group 'org-keywords
2646 :type '(choice (const sequence)
2647 (const type)))
2649 (defcustom org-use-fast-todo-selection t
2650 "\\<org-mode-map>\
2651 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2652 This variable describes if and under what circumstances the cycling
2653 mechanism for TODO keywords will be replaced by a single-key, direct
2654 selection scheme.
2656 When nil, fast selection is never used.
2658 When the symbol `prefix', it will be used when `org-todo' is called
2659 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2660 in an Org buffer, and
2661 `\\[universal-argument] t' in an agenda buffer.
2663 When t, fast selection is used by default. In this case, the prefix
2664 argument forces cycling instead.
2666 In all cases, the special interface is only used if access keys have
2667 actually been assigned by the user, i.e. if keywords in the configuration
2668 are followed by a letter in parenthesis, like TODO(t)."
2669 :group 'org-todo
2670 :type '(choice
2671 (const :tag "Never" nil)
2672 (const :tag "By default" t)
2673 (const :tag "Only with C-u C-c C-t" prefix)))
2675 (defcustom org-provide-todo-statistics t
2676 "Non-nil means update todo statistics after insert and toggle.
2677 ALL-HEADLINES means update todo statistics by including headlines
2678 with no TODO keyword as well, counting them as not done.
2679 A list of TODO keywords means the same, but skip keywords that are
2680 not in this list.
2681 When set to a list of two lists, the first list contains keywords
2682 to consider as TODO keywords, the second list contains keywords
2683 to consider as DONE keywords.
2685 When this is set, todo statistics is updated in the parent of the
2686 current entry each time a todo state is changed."
2687 :group 'org-todo
2688 :type '(choice
2689 (const :tag "Yes, only for TODO entries" t)
2690 (const :tag "Yes, including all entries" all-headlines)
2691 (repeat :tag "Yes, for TODOs in this list"
2692 (string :tag "TODO keyword"))
2693 (list :tag "Yes, for TODOs and DONEs in these lists"
2694 (repeat (string :tag "TODO keyword"))
2695 (repeat (string :tag "DONE keyword")))
2696 (other :tag "No TODO statistics" nil)))
2698 (defcustom org-hierarchical-todo-statistics t
2699 "Non-nil means TODO statistics covers just direct children.
2700 When nil, all entries in the subtree are considered.
2701 This has only an effect if `org-provide-todo-statistics' is set.
2702 To set this to nil for only a single subtree, use a COOKIE_DATA
2703 property and include the word \"recursive\" into the value."
2704 :group 'org-todo
2705 :type 'boolean)
2707 (defcustom org-after-todo-state-change-hook nil
2708 "Hook which is run after the state of a TODO item was changed.
2709 The new state (a string with a TODO keyword, or nil) is available in the
2710 Lisp variable `org-state'."
2711 :group 'org-todo
2712 :type 'hook)
2714 (defvar org-blocker-hook nil
2715 "Hook for functions that are allowed to block a state change.
2717 Functions in this hook should not modify the buffer.
2718 Each function gets as its single argument a property list,
2719 see `org-trigger-hook' for more information about this list.
2721 If any of the functions in this hook returns nil, the state change
2722 is blocked.")
2724 (defvar org-trigger-hook nil
2725 "Hook for functions that are triggered by a state change.
2727 Each function gets as its single argument a property list with at
2728 least the following elements:
2730 (:type type-of-change :position pos-at-entry-start
2731 :from old-state :to new-state)
2733 Depending on the type, more properties may be present.
2735 This mechanism is currently implemented for:
2737 TODO state changes
2738 ------------------
2739 :type todo-state-change
2740 :from previous state (keyword as a string), or nil, or a symbol
2741 `todo' or `done', to indicate the general type of state.
2742 :to new state, like in :from")
2744 (defcustom org-enforce-todo-dependencies nil
2745 "Non-nil means undone TODO entries will block switching the parent to DONE.
2746 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2747 be blocked if any prior sibling is not yet done.
2748 Finally, if the parent is blocked because of ordered siblings of its own,
2749 the child will also be blocked."
2750 :set (lambda (var val)
2751 (set var val)
2752 (if val
2753 (add-hook 'org-blocker-hook
2754 'org-block-todo-from-children-or-siblings-or-parent)
2755 (remove-hook 'org-blocker-hook
2756 'org-block-todo-from-children-or-siblings-or-parent)))
2757 :group 'org-todo
2758 :type 'boolean)
2760 (defcustom org-enforce-todo-checkbox-dependencies nil
2761 "Non-nil means unchecked boxes will block switching the parent to DONE.
2762 When this is nil, checkboxes have no influence on switching TODO states.
2763 When non-nil, you first need to check off all check boxes before the TODO
2764 entry can be switched to DONE.
2765 This variable needs to be set before org.el is loaded, and you need to
2766 restart Emacs after a change to make the change effective. The only way
2767 to change is while Emacs is running is through the customize interface."
2768 :set (lambda (var val)
2769 (set var val)
2770 (if val
2771 (add-hook 'org-blocker-hook
2772 'org-block-todo-from-checkboxes)
2773 (remove-hook 'org-blocker-hook
2774 'org-block-todo-from-checkboxes)))
2775 :group 'org-todo
2776 :type 'boolean)
2778 (defcustom org-treat-insert-todo-heading-as-state-change nil
2779 "Non-nil means inserting a TODO heading is treated as state change.
2780 So when the command `\\[org-insert-todo-heading]' is used, state change
2781 logging will apply if appropriate. When nil, the new TODO item will
2782 be inserted directly, and no logging will take place."
2783 :group 'org-todo
2784 :type 'boolean)
2786 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2787 "Non-nil means switching TODO states with S-cursor counts as state change.
2788 This is the default behavior. However, setting this to nil allows a
2789 convenient way to select a TODO state and bypass any logging associated
2790 with that."
2791 :group 'org-todo
2792 :type 'boolean)
2794 (defcustom org-todo-state-tags-triggers nil
2795 "Tag changes that should be triggered by TODO state changes.
2796 This is a list. Each entry is
2798 (state-change (tag . flag) .......)
2800 State-change can be a string with a state, and empty string to indicate the
2801 state that has no TODO keyword, or it can be one of the symbols `todo'
2802 or `done', meaning any not-done or done state, respectively."
2803 :group 'org-todo
2804 :group 'org-tags
2805 :type '(repeat
2806 (cons (choice :tag "When changing to"
2807 (const :tag "Not-done state" todo)
2808 (const :tag "Done state" done)
2809 (string :tag "State"))
2810 (repeat
2811 (cons :tag "Tag action"
2812 (string :tag "Tag")
2813 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2815 (defcustom org-log-done nil
2816 "Information to record when a task moves to the DONE state.
2818 Possible values are:
2820 nil Don't add anything, just change the keyword
2821 time Add a time stamp to the task
2822 note Prompt for a note and add it with template `org-log-note-headings'
2824 This option can also be set with on a per-file-basis with
2826 #+STARTUP: nologdone
2827 #+STARTUP: logdone
2828 #+STARTUP: lognotedone
2830 You can have local logging settings for a subtree by setting the LOGGING
2831 property to one or more of these keywords."
2832 :group 'org-todo
2833 :group 'org-progress
2834 :type '(choice
2835 (const :tag "No logging" nil)
2836 (const :tag "Record CLOSED timestamp" time)
2837 (const :tag "Record CLOSED timestamp with note." note)))
2839 ;; Normalize old uses of org-log-done.
2840 (cond
2841 ((eq org-log-done t) (setq org-log-done 'time))
2842 ((and (listp org-log-done) (memq 'done org-log-done))
2843 (setq org-log-done 'note)))
2845 (defcustom org-log-reschedule nil
2846 "Information to record when the scheduling date of a tasks is modified.
2848 Possible values are:
2850 nil Don't add anything, just change the date
2851 time Add a time stamp to the task
2852 note Prompt for a note and add it with template `org-log-note-headings'
2854 This option can also be set with on a per-file-basis with
2856 #+STARTUP: nologreschedule
2857 #+STARTUP: logreschedule
2858 #+STARTUP: lognotereschedule"
2859 :group 'org-todo
2860 :group 'org-progress
2861 :type '(choice
2862 (const :tag "No logging" nil)
2863 (const :tag "Record timestamp" time)
2864 (const :tag "Record timestamp with note." note)))
2866 (defcustom org-log-redeadline nil
2867 "Information to record when the deadline date of a tasks is modified.
2869 Possible values are:
2871 nil Don't add anything, just change the date
2872 time Add a time stamp to the task
2873 note Prompt for a note and add it with template `org-log-note-headings'
2875 This option can also be set with on a per-file-basis with
2877 #+STARTUP: nologredeadline
2878 #+STARTUP: logredeadline
2879 #+STARTUP: lognoteredeadline
2881 You can have local logging settings for a subtree by setting the LOGGING
2882 property to one or more of these keywords."
2883 :group 'org-todo
2884 :group 'org-progress
2885 :type '(choice
2886 (const :tag "No logging" nil)
2887 (const :tag "Record timestamp" time)
2888 (const :tag "Record timestamp with note." note)))
2890 (defcustom org-log-note-clock-out nil
2891 "Non-nil means record a note when clocking out of an item.
2892 This can also be configured on a per-file basis by adding one of
2893 the following lines anywhere in the buffer:
2895 #+STARTUP: lognoteclock-out
2896 #+STARTUP: nolognoteclock-out"
2897 :group 'org-todo
2898 :group 'org-progress
2899 :type 'boolean)
2901 (defcustom org-log-done-with-time t
2902 "Non-nil means the CLOSED time stamp will contain date and time.
2903 When nil, only the date will be recorded."
2904 :group 'org-progress
2905 :type 'boolean)
2907 (defcustom org-log-note-headings
2908 '((done . "CLOSING NOTE %t")
2909 (state . "State %-12s from %-12S %t")
2910 (note . "Note taken on %t")
2911 (reschedule . "Rescheduled from %S on %t")
2912 (delschedule . "Not scheduled, was %S on %t")
2913 (redeadline . "New deadline from %S on %t")
2914 (deldeadline . "Removed deadline, was %S on %t")
2915 (refile . "Refiled on %t")
2916 (clock-out . ""))
2917 "Headings for notes added to entries.
2919 The value is an alist, with the car being a symbol indicating the
2920 note context, and the cdr is the heading to be used. The heading
2921 may also be the empty string. The following placeholders can be
2922 used:
2924 %t a time stamp.
2925 %T an active time stamp instead the default inactive one
2926 %d a short-format time stamp.
2927 %D an active short-format time stamp.
2928 %s the new TODO state or time stamp (inactive), in double quotes.
2929 %S the old TODO state or time stamp (inactive), in double quotes.
2930 %u the user name.
2931 %U full user name.
2933 In fact, it is not a good idea to change the `state' entry,
2934 because Agenda Log mode depends on the format of these entries."
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type '(list :greedy t
2938 (cons (const :tag "Heading when closing an item" done) string)
2939 (cons (const :tag
2940 "Heading when changing todo state (todo sequence only)"
2941 state) string)
2942 (cons (const :tag "Heading when just taking a note" note) string)
2943 (cons (const :tag "Heading when rescheduling" reschedule) string)
2944 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2945 (cons (const :tag "Heading when changing deadline" redeadline) string)
2946 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2947 (cons (const :tag "Heading when refiling" refile) string)
2948 (cons (const :tag "Heading when clocking out" clock-out) string)))
2950 (unless (assq 'note org-log-note-headings)
2951 (push '(note . "%t") org-log-note-headings))
2953 (defcustom org-log-into-drawer nil
2954 "Non-nil means insert state change notes and time stamps into a drawer.
2955 When nil, state changes notes will be inserted after the headline and
2956 any scheduling and clock lines, but not inside a drawer.
2958 The value of this variable should be the name of the drawer to use.
2959 LOGBOOK is proposed as the default drawer for this purpose, you can
2960 also set this to a string to define the drawer of your choice.
2962 A value of t is also allowed, representing \"LOGBOOK\".
2964 A value of t or nil can also be set with on a per-file-basis with
2966 #+STARTUP: logdrawer
2967 #+STARTUP: nologdrawer
2969 If this variable is set, `org-log-state-notes-insert-after-drawers'
2970 will be ignored.
2972 You can set the property LOG_INTO_DRAWER to overrule this setting for
2973 a subtree.
2975 Do not check directly this variable in a Lisp program. Call
2976 function `org-log-into-drawer' instead."
2977 :group 'org-todo
2978 :group 'org-progress
2979 :type '(choice
2980 (const :tag "Not into a drawer" nil)
2981 (const :tag "LOGBOOK" t)
2982 (string :tag "Other")))
2984 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2986 (defun org-log-into-drawer ()
2987 "Name of the log drawer, as a string, or nil.
2988 This is the value of `org-log-into-drawer'. However, if the
2989 current entry has or inherits a LOG_INTO_DRAWER property, it will
2990 be used instead of the default value."
2991 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2992 (cond ((equal p "nil") nil)
2993 ((equal p "t") "LOGBOOK")
2994 ((stringp p) p)
2995 (p "LOGBOOK")
2996 ((stringp org-log-into-drawer) org-log-into-drawer)
2997 (org-log-into-drawer "LOGBOOK"))))
2999 (defcustom org-log-state-notes-insert-after-drawers nil
3000 "Non-nil means insert state change notes after any drawers in entry.
3001 Only the drawers that *immediately* follow the headline and the
3002 deadline/scheduled line are skipped.
3003 When nil, insert notes right after the heading and perhaps the line
3004 with deadline/scheduling if present.
3006 This variable will have no effect if `org-log-into-drawer' is
3007 set."
3008 :group 'org-todo
3009 :group 'org-progress
3010 :type 'boolean)
3012 (defcustom org-log-states-order-reversed t
3013 "Non-nil means the latest state note will be directly after heading.
3014 When nil, the state change notes will be ordered according to time.
3016 This option can also be set with on a per-file-basis with
3018 #+STARTUP: logstatesreversed
3019 #+STARTUP: nologstatesreversed"
3020 :group 'org-todo
3021 :group 'org-progress
3022 :type 'boolean)
3024 (defcustom org-todo-repeat-to-state nil
3025 "The TODO state to which a repeater should return the repeating task.
3026 By default this is the first task in a TODO sequence, or the previous state
3027 in a TODO_TYP set. But you can specify another task here.
3028 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3029 :group 'org-todo
3030 :version "24.1"
3031 :type '(choice (const :tag "Head of sequence" nil)
3032 (string :tag "Specific state")))
3034 (defcustom org-log-repeat 'time
3035 "Non-nil means record moving through the DONE state when triggering repeat.
3036 An auto-repeating task is immediately switched back to TODO when
3037 marked DONE. If you are not logging state changes (by adding \"@\"
3038 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3039 record a closing note, there will be no record of the task moving
3040 through DONE. This variable forces taking a note anyway.
3042 nil Don't force a record
3043 time Record a time stamp
3044 note Prompt for a note and add it with template `org-log-note-headings'
3046 This option can also be set with on a per-file-basis with
3048 #+STARTUP: nologrepeat
3049 #+STARTUP: logrepeat
3050 #+STARTUP: lognoterepeat
3052 You can have local logging settings for a subtree by setting the LOGGING
3053 property to one or more of these keywords."
3054 :group 'org-todo
3055 :group 'org-progress
3056 :type '(choice
3057 (const :tag "Don't force a record" nil)
3058 (const :tag "Force recording the DONE state" time)
3059 (const :tag "Force recording a note with the DONE state" note)))
3062 (defgroup org-priorities nil
3063 "Priorities in Org mode."
3064 :tag "Org Priorities"
3065 :group 'org-todo)
3067 (defcustom org-enable-priority-commands t
3068 "Non-nil means priority commands are active.
3069 When nil, these commands will be disabled, so that you never accidentally
3070 set a priority."
3071 :group 'org-priorities
3072 :type 'boolean)
3074 (defcustom org-highest-priority ?A
3075 "The highest priority of TODO items. A character like ?A, ?B etc.
3076 Must have a smaller ASCII number than `org-lowest-priority'."
3077 :group 'org-priorities
3078 :type 'character)
3080 (defcustom org-lowest-priority ?C
3081 "The lowest priority of TODO items. A character like ?A, ?B etc.
3082 Must have a larger ASCII number than `org-highest-priority'."
3083 :group 'org-priorities
3084 :type 'character)
3086 (defcustom org-default-priority ?B
3087 "The default priority of TODO items.
3088 This is the priority an item gets if no explicit priority is given.
3089 When starting to cycle on an empty priority the first step in the cycle
3090 depends on `org-priority-start-cycle-with-default'. The resulting first
3091 step priority must not exceed the range from `org-highest-priority' to
3092 `org-lowest-priority' which means that `org-default-priority' has to be
3093 in this range exclusive or inclusive the range boundaries. Else the
3094 first step refuses to set the default and the second will fall back
3095 to (depending on the command used) the highest or lowest priority."
3096 :group 'org-priorities
3097 :type 'character)
3099 (defcustom org-priority-start-cycle-with-default t
3100 "Non-nil means start with default priority when starting to cycle.
3101 When this is nil, the first step in the cycle will be (depending on the
3102 command used) one higher or lower than the default priority.
3103 See also `org-default-priority'."
3104 :group 'org-priorities
3105 :type 'boolean)
3107 (defcustom org-get-priority-function nil
3108 "Function to extract the priority from a string.
3109 The string is normally the headline. If this is nil Org computes the
3110 priority from the priority cookie like [#A] in the headline. It returns
3111 an integer, increasing by 1000 for each priority level.
3112 The user can set a different function here, which should take a string
3113 as an argument and return the numeric priority."
3114 :group 'org-priorities
3115 :version "24.1"
3116 :type '(choice
3117 (const nil)
3118 (function)))
3120 (defgroup org-time nil
3121 "Options concerning time stamps and deadlines in Org mode."
3122 :tag "Org Time"
3123 :group 'org)
3125 (defcustom org-time-stamp-rounding-minutes '(0 5)
3126 "Number of minutes to round time stamps to.
3127 \\<org-mode-map>\
3128 These are two values, the first applies when first creating a time stamp.
3129 The second applies when changing it with the commands `S-up' and `S-down'.
3130 When changing the time stamp, this means that it will change in steps
3131 of N minutes, as given by the second value.
3133 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3134 numbers should be factors of 60, so for example 5, 10, 15.
3136 When this is larger than 1, you can still force an exact time stamp by using
3137 a double prefix argument to a time stamp command like \
3138 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3139 and by using a prefix arg to `S-up/down' to specify the exact number
3140 of minutes to shift."
3141 :group 'org-time
3142 :get (lambda (var) ; Make sure both elements are there
3143 (if (integerp (default-value var))
3144 (list (default-value var) 5)
3145 (default-value var)))
3146 :type '(list
3147 (integer :tag "when inserting times")
3148 (integer :tag "when modifying times")))
3150 ;; Normalize old customizations of this variable.
3151 (when (integerp org-time-stamp-rounding-minutes)
3152 (setq org-time-stamp-rounding-minutes
3153 (list org-time-stamp-rounding-minutes
3154 org-time-stamp-rounding-minutes)))
3156 (defcustom org-display-custom-times nil
3157 "Non-nil means overlay custom formats over all time stamps.
3158 The formats are defined through the variable `org-time-stamp-custom-formats'.
3159 To turn this on on a per-file basis, insert anywhere in the file:
3160 #+STARTUP: customtime"
3161 :group 'org-time
3162 :set 'set-default
3163 :type 'sexp)
3164 (make-variable-buffer-local 'org-display-custom-times)
3166 (defcustom org-time-stamp-custom-formats
3167 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3168 "Custom formats for time stamps. See `format-time-string' for the syntax.
3169 These are overlaid over the default ISO format if the variable
3170 `org-display-custom-times' is set. Time like %H:%M should be at the
3171 end of the second format. The custom formats are also honored by export
3172 commands, if custom time display is turned on at the time of export."
3173 :group 'org-time
3174 :type 'sexp)
3176 (defun org-time-stamp-format (&optional long inactive)
3177 "Get the right format for a time string."
3178 (let ((f (if long (cdr org-time-stamp-formats)
3179 (car org-time-stamp-formats))))
3180 (if inactive
3181 (concat "[" (substring f 1 -1) "]")
3182 f)))
3184 (defcustom org-deadline-warning-days 14
3185 "Number of days before expiration during which a deadline becomes active.
3186 This variable governs the display in sparse trees and in the agenda.
3187 When 0 or negative, it means use this number (the absolute value of it)
3188 even if a deadline has a different individual lead time specified.
3190 Custom commands can set this variable in the options section."
3191 :group 'org-time
3192 :group 'org-agenda-daily/weekly
3193 :type 'integer)
3195 (defcustom org-scheduled-delay-days 0
3196 "Number of days before a scheduled item becomes active.
3197 This variable governs the display in sparse trees and in the agenda.
3198 The default value (i.e. 0) means: don't delay scheduled item.
3199 When negative, it means use this number (the absolute value of it)
3200 even if a scheduled item has a different individual delay time
3201 specified.
3203 Custom commands can set this variable in the options section."
3204 :group 'org-time
3205 :group 'org-agenda-daily/weekly
3206 :version "24.4"
3207 :package-version '(Org . "8.0")
3208 :type 'integer)
3210 (defcustom org-read-date-prefer-future t
3211 "Non-nil means assume future for incomplete date input from user.
3212 This affects the following situations:
3213 1. The user gives a month but not a year.
3214 For example, if it is April and you enter \"feb 2\", this will be read
3215 as Feb 2, *next* year. \"May 5\", however, will be this year.
3216 2. The user gives a day, but no month.
3217 For example, if today is the 15th, and you enter \"3\", Org will read
3218 this as the third of *next* month. However, if you enter \"17\",
3219 it will be considered as *this* month.
3221 If you set this variable to the symbol `time', then also the following
3222 will work:
3224 3. If the user gives a time.
3225 If the time is before now, it will be interpreted as tomorrow.
3227 Currently none of this works for ISO week specifications.
3229 When this option is nil, the current day, month and year will always be
3230 used as defaults.
3232 See also `org-agenda-jump-prefer-future'."
3233 :group 'org-time
3234 :type '(choice
3235 (const :tag "Never" nil)
3236 (const :tag "Check month and day" t)
3237 (const :tag "Check month, day, and time" time)))
3239 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3240 "Should the agenda jump command prefer the future for incomplete dates?
3241 The default is to do the same as configured in `org-read-date-prefer-future'.
3242 But you can also set a deviating value here.
3243 This may t or nil, or the symbol `org-read-date-prefer-future'."
3244 :group 'org-agenda
3245 :group 'org-time
3246 :version "24.1"
3247 :type '(choice
3248 (const :tag "Use org-read-date-prefer-future"
3249 org-read-date-prefer-future)
3250 (const :tag "Never" nil)
3251 (const :tag "Always" t)))
3253 (defcustom org-read-date-force-compatible-dates t
3254 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3256 Depending on the system Emacs is running on, certain dates cannot
3257 be represented with the type used internally to represent time.
3258 Dates between 1970-1-1 and 2038-1-1 can always be represented
3259 correctly. Some systems allow for earlier dates, some for later,
3260 some for both. One way to find out it to insert any date into an
3261 Org buffer, putting the cursor on the year and hitting S-up and
3262 S-down to test the range.
3264 When this variable is set to t, the date/time prompt will not let
3265 you specify dates outside the 1970-2037 range, so it is certain that
3266 these dates will work in whatever version of Emacs you are
3267 running, and also that you can move a file from one Emacs implementation
3268 to another. WHenever Org is forcing the year for you, it will display
3269 a message and beep.
3271 When this variable is nil, Org will check if the date is
3272 representable in the specific Emacs implementation you are using.
3273 If not, it will force a year, usually the current year, and beep
3274 to remind you. Currently this setting is not recommended because
3275 the likelihood that you will open your Org files in an Emacs that
3276 has limited date range is not negligible.
3278 A workaround for this problem is to use diary sexp dates for time
3279 stamps outside of this range."
3280 :group 'org-time
3281 :version "24.1"
3282 :type 'boolean)
3284 (defcustom org-read-date-display-live t
3285 "Non-nil means display current interpretation of date prompt live.
3286 This display will be in an overlay, in the minibuffer."
3287 :group 'org-time
3288 :type 'boolean)
3290 (defcustom org-read-date-popup-calendar t
3291 "Non-nil means pop up a calendar when prompting for a date.
3292 In the calendar, the date can be selected with mouse-1. However, the
3293 minibuffer will also be active, and you can simply enter the date as well.
3294 When nil, only the minibuffer will be available."
3295 :group 'org-time
3296 :type 'boolean)
3297 (defvaralias 'org-popup-calendar-for-date-prompt
3298 'org-read-date-popup-calendar)
3300 (defcustom org-extend-today-until 0
3301 "The hour when your day really ends. Must be an integer.
3302 This has influence for the following applications:
3303 - When switching the agenda to \"today\". It it is still earlier than
3304 the time given here, the day recognized as TODAY is actually yesterday.
3305 - When a date is read from the user and it is still before the time given
3306 here, the current date and time will be assumed to be yesterday, 23:59.
3307 Also, timestamps inserted in capture templates follow this rule.
3309 IMPORTANT: This is a feature whose implementation is and likely will
3310 remain incomplete. Really, it is only here because past midnight seems to
3311 be the favorite working time of John Wiegley :-)"
3312 :group 'org-time
3313 :type 'integer)
3315 (defcustom org-use-effective-time nil
3316 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3317 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3318 \"effective time\" of any timestamps between midnight and 8am will be
3319 23:59 of the previous day."
3320 :group 'org-time
3321 :version "24.1"
3322 :type 'boolean)
3324 (defcustom org-use-last-clock-out-time-as-effective-time nil
3325 "When non-nil, use the last clock out time for `org-todo'.
3326 Note that this option has precedence over the combined use of
3327 `org-use-effective-time' and `org-extend-today-until'."
3328 :group 'org-time
3329 :version "24.4"
3330 :package-version '(Org . "8.0")
3331 :type 'boolean)
3333 (defcustom org-edit-timestamp-down-means-later nil
3334 "Non-nil means S-down will increase the time in a time stamp.
3335 When nil, S-up will increase."
3336 :group 'org-time
3337 :type 'boolean)
3339 (defcustom org-calendar-follow-timestamp-change t
3340 "Non-nil means make the calendar window follow timestamp changes.
3341 When a timestamp is modified and the calendar window is visible, it will be
3342 moved to the new date."
3343 :group 'org-time
3344 :type 'boolean)
3346 (defgroup org-tags nil
3347 "Options concerning tags in Org mode."
3348 :tag "Org Tags"
3349 :group 'org)
3351 (defcustom org-tag-alist nil
3352 "Default tags available in Org files.
3354 The value of this variable is an alist. Associations either:
3356 (TAG)
3357 (TAG . SELECT)
3358 (SPECIAL)
3360 where TAG is a tag as a string, SELECT is character, used to
3361 select that tag through the fast tag selection interface, and
3362 SPECIAL is one of the following keywords: `:startgroup',
3363 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3364 `:newline'. These keywords are used to define a hierarchy of
3365 tags. See manual for details.
3367 When this variable is nil, Org mode bases tag input on what is
3368 already in the buffer. The value can be overridden locally by
3369 using a TAGS keyword, e.g.,
3371 #+TAGS: tag1 tag2
3373 See also `org-tag-persistent-alist' to sidestep this behavior."
3374 :group 'org-tags
3375 :type '(repeat
3376 (choice
3377 (cons :tag "Tag with key"
3378 (string :tag "Tag name")
3379 (character :tag "Access char"))
3380 (list :tag "Tag" (string :tag "Tag name"))
3381 (const :tag "Start radio group" (:startgroup))
3382 (const :tag "Start tag group, non distinct" (:startgrouptag))
3383 (const :tag "Group tags delimiter" (:grouptags))
3384 (const :tag "End radio group" (:endgroup))
3385 (const :tag "End tag group, non distinct" (:endgrouptag))
3386 (const :tag "New line" (:newline)))))
3388 (defcustom org-tag-persistent-alist nil
3389 "Tags always available in Org files.
3391 The value of this variable is an alist. Associations either:
3393 (TAG)
3394 (TAG . SELECT)
3395 (SPECIAL)
3397 where TAG is a tag as a string, SELECT is a character, used to
3398 select that tag through the fast tag selection interface, and
3399 SPECIAL is one of the following keywords: `:startgroup',
3400 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3401 `:newline'. These keywords are used to define a hierarchy of
3402 tags. See manual for details.
3404 Unlike to `org-tag-alist', tags defined in this variable do not
3405 depend on a local TAGS keyword. Instead, to disable these tags
3406 on a per-file basis, insert anywhere in the file:
3408 #+STARTUP: noptag"
3409 :group 'org-tags
3410 :type '(repeat
3411 (choice
3412 (cons :tag "Tag with key"
3413 (string :tag "Tag name")
3414 (character :tag "Access char"))
3415 (list :tag "Tag" (string :tag "Tag name"))
3416 (const :tag "Start radio group" (:startgroup))
3417 (const :tag "Start tag group, non distinct" (:startgrouptag))
3418 (const :tag "Group tags delimiter" (:grouptags))
3419 (const :tag "End radio group" (:endgroup))
3420 (const :tag "End tag group, non distinct" (:endgrouptag))
3421 (const :tag "New line" (:newline)))))
3423 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3424 "If non-nil, always offer completion for all tags of all agenda files.
3425 Instead of customizing this variable directly, you might want to
3426 set it locally for capture buffers, because there no list of
3427 tags in that file can be created dynamically (there are none).
3429 (add-hook \\='org-capture-mode-hook
3430 (lambda ()
3431 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3432 :group 'org-tags
3433 :version "24.1"
3434 :type 'boolean)
3436 (defvar org-file-tags nil
3437 "List of tags that can be inherited by all entries in the file.
3438 The tags will be inherited if the variable `org-use-tag-inheritance'
3439 says they should be.
3440 This variable is populated from #+FILETAGS lines.")
3442 (defcustom org-use-fast-tag-selection 'auto
3443 "Non-nil means use fast tag selection scheme.
3444 This is a special interface to select and deselect tags with single keys.
3445 When nil, fast selection is never used.
3446 When the symbol `auto', fast selection is used if and only if selection
3447 characters for tags have been configured, either through the variable
3448 `org-tag-alist' or through a #+TAGS line in the buffer.
3449 When t, fast selection is always used and selection keys are assigned
3450 automatically if necessary."
3451 :group 'org-tags
3452 :type '(choice
3453 (const :tag "Always" t)
3454 (const :tag "Never" nil)
3455 (const :tag "When selection characters are configured" auto)))
3457 (defcustom org-fast-tag-selection-single-key nil
3458 "Non-nil means fast tag selection exits after first change.
3459 When nil, you have to press RET to exit it.
3460 During fast tag selection, you can toggle this flag with `C-c'.
3461 This variable can also have the value `expert'. In this case, the window
3462 displaying the tags menu is not even shown, until you press C-c again."
3463 :group 'org-tags
3464 :type '(choice
3465 (const :tag "No" nil)
3466 (const :tag "Yes" t)
3467 (const :tag "Expert" expert)))
3469 (defvar org-fast-tag-selection-include-todo nil
3470 "Non-nil means fast tags selection interface will also offer TODO states.
3471 This is an undocumented feature, you should not rely on it.")
3473 (defcustom org-tags-column -77
3474 "The column to which tags should be indented in a headline.
3475 If this number is positive, it specifies the column. If it is negative,
3476 it means that the tags should be flushright to that column. For example,
3477 -80 works well for a normal 80 character screen.
3478 When 0, place tags directly after headline text, with only one space in
3479 between."
3480 :group 'org-tags
3481 :type 'integer)
3483 (defcustom org-auto-align-tags t
3484 "Non-nil keeps tags aligned when modifying headlines.
3485 Some operations (i.e. demoting) change the length of a headline and
3486 therefore shift the tags around. With this option turned on, after
3487 each such operation the tags are again aligned to `org-tags-column'."
3488 :group 'org-tags
3489 :type 'boolean)
3491 (defcustom org-use-tag-inheritance t
3492 "Non-nil means tags in levels apply also for sublevels.
3493 When nil, only the tags directly given in a specific line apply there.
3494 This may also be a list of tags that should be inherited, or a regexp that
3495 matches tags that should be inherited. Additional control is possible
3496 with the variable `org-tags-exclude-from-inheritance' which gives an
3497 explicit list of tags to be excluded from inheritance, even if the value of
3498 `org-use-tag-inheritance' would select it for inheritance.
3500 If this option is t, a match early-on in a tree can lead to a large
3501 number of matches in the subtree when constructing the agenda or creating
3502 a sparse tree. If you only want to see the first match in a tree during
3503 a search, check out the variable `org-tags-match-list-sublevels'."
3504 :group 'org-tags
3505 :type '(choice
3506 (const :tag "Not" nil)
3507 (const :tag "Always" t)
3508 (repeat :tag "Specific tags" (string :tag "Tag"))
3509 (regexp :tag "Tags matched by regexp")))
3511 (defcustom org-tags-exclude-from-inheritance nil
3512 "List of tags that should never be inherited.
3513 This is a way to exclude a few tags from inheritance. For way to do
3514 the opposite, to actively allow inheritance for selected tags,
3515 see the variable `org-use-tag-inheritance'."
3516 :group 'org-tags
3517 :type '(repeat (string :tag "Tag")))
3519 (defun org-tag-inherit-p (tag)
3520 "Check if TAG is one that should be inherited."
3521 (cond
3522 ((member tag org-tags-exclude-from-inheritance) nil)
3523 ((eq org-use-tag-inheritance t) t)
3524 ((not org-use-tag-inheritance) nil)
3525 ((stringp org-use-tag-inheritance)
3526 (string-match org-use-tag-inheritance tag))
3527 ((listp org-use-tag-inheritance)
3528 (member tag org-use-tag-inheritance))
3529 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3531 (defcustom org-tags-match-list-sublevels t
3532 "Non-nil means list also sublevels of headlines matching a search.
3533 This variable applies to tags/property searches, and also to stuck
3534 projects because this search is based on a tags match as well.
3536 When set to the symbol `indented', sublevels are indented with
3537 leading dots.
3539 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3540 the sublevels of a headline matching a tag search often also match
3541 the same search. Listing all of them can create very long lists.
3542 Setting this variable to nil causes subtrees of a match to be skipped.
3544 This variable is semi-obsolete and probably should always be true. It
3545 is better to limit inheritance to certain tags using the variables
3546 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3547 :group 'org-tags
3548 :type '(choice
3549 (const :tag "No, don't list them" nil)
3550 (const :tag "Yes, do list them" t)
3551 (const :tag "List them, indented with leading dots" indented)))
3553 (defcustom org-tags-sort-function nil
3554 "When set, tags are sorted using this function as a comparator."
3555 :group 'org-tags
3556 :type '(choice
3557 (const :tag "No sorting" nil)
3558 (const :tag "Alphabetical" string<)
3559 (const :tag "Reverse alphabetical" string>)
3560 (function :tag "Custom function" nil)))
3562 (defvar org-tags-history nil
3563 "History of minibuffer reads for tags.")
3564 (defvar org-last-tags-completion-table nil
3565 "The last used completion table for tags.")
3566 (defvar org-after-tags-change-hook nil
3567 "Hook that is run after the tags in a line have changed.")
3569 (defgroup org-properties nil
3570 "Options concerning properties in Org mode."
3571 :tag "Org Properties"
3572 :group 'org)
3574 (defcustom org-property-format "%-10s %s"
3575 "How property key/value pairs should be formatted by `indent-line'.
3576 When `indent-line' hits a property definition, it will format the line
3577 according to this format, mainly to make sure that the values are
3578 lined-up with respect to each other."
3579 :group 'org-properties
3580 :type 'string)
3582 (defcustom org-properties-postprocess-alist nil
3583 "Alist of properties and functions to adjust inserted values.
3584 Elements of this alist must be of the form
3586 ([string] [function])
3588 where [string] must be a property name and [function] must be a
3589 lambda expression: this lambda expression must take one argument,
3590 the value to adjust, and return the new value as a string.
3592 For example, this element will allow the property \"Remaining\"
3593 to be updated wrt the relation between the \"Effort\" property
3594 and the clock summary:
3596 ((\"Remaining\" (lambda(value)
3597 (let ((clocksum (org-clock-sum-current-item))
3598 (effort (org-duration-to-minutes
3599 (org-entry-get (point) \"Effort\"))))
3600 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3601 :group 'org-properties
3602 :version "24.1"
3603 :type '(alist :key-type (string :tag "Property")
3604 :value-type (function :tag "Function")))
3606 (defcustom org-use-property-inheritance nil
3607 "Non-nil means properties apply also for sublevels.
3609 This setting is chiefly used during property searches. Turning it on can
3610 cause significant overhead when doing a search, which is why it is not
3611 on by default.
3613 When nil, only the properties directly given in the current entry count.
3614 When t, every property is inherited. The value may also be a list of
3615 properties that should have inheritance, or a regular expression matching
3616 properties that should be inherited.
3618 However, note that some special properties use inheritance under special
3619 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3620 and the properties ending in \"_ALL\" when they are used as descriptor
3621 for valid values of a property.
3623 Note for programmers:
3624 When querying an entry with `org-entry-get', you can control if inheritance
3625 should be used. By default, `org-entry-get' looks only at the local
3626 properties. You can request inheritance by setting the inherit argument
3627 to t (to force inheritance) or to `selective' (to respect the setting
3628 in this variable)."
3629 :group 'org-properties
3630 :type '(choice
3631 (const :tag "Not" nil)
3632 (const :tag "Always" t)
3633 (repeat :tag "Specific properties" (string :tag "Property"))
3634 (regexp :tag "Properties matched by regexp")))
3636 (defun org-property-inherit-p (property)
3637 "Return a non-nil value if PROPERTY should be inherited."
3638 (cond
3639 ((eq org-use-property-inheritance t) t)
3640 ((not org-use-property-inheritance) nil)
3641 ((stringp org-use-property-inheritance)
3642 (string-match org-use-property-inheritance property))
3643 ((listp org-use-property-inheritance)
3644 (member-ignore-case property org-use-property-inheritance))
3645 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3647 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3648 "The default column format, if no other format has been defined.
3649 This variable can be set on the per-file basis by inserting a line
3651 #+COLUMNS: %25ITEM ....."
3652 :group 'org-properties
3653 :type 'string)
3655 (defcustom org-columns-ellipses ".."
3656 "The ellipses to be used when a field in column view is truncated.
3657 When this is the empty string, as many characters as possible are shown,
3658 but then there will be no visual indication that the field has been truncated.
3659 When this is a string of length N, the last N characters of a truncated
3660 field are replaced by this string. If the column is narrower than the
3661 ellipses string, only part of the ellipses string will be shown."
3662 :group 'org-properties
3663 :type 'string)
3665 (defconst org-global-properties-fixed
3666 '(("VISIBILITY_ALL" . "folded children content all")
3667 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3668 "List of property/value pairs that can be inherited by any entry.
3670 These are fixed values, for the preset properties. The user variable
3671 that can be used to add to this list is `org-global-properties'.
3673 The entries in this list are cons cells where the car is a property
3674 name and cdr is a string with the value. If the value represents
3675 multiple items like an \"_ALL\" property, separate the items by
3676 spaces.")
3678 (defcustom org-global-properties nil
3679 "List of property/value pairs that can be inherited by any entry.
3681 This list will be combined with the constant `org-global-properties-fixed'.
3683 The entries in this list are cons cells where the car is a property
3684 name and cdr is a string with the value.
3686 You can set buffer-local values for the same purpose in the variable
3687 `org-file-properties' this by adding lines like
3689 #+PROPERTY: NAME VALUE"
3690 :group 'org-properties
3691 :type '(repeat
3692 (cons (string :tag "Property")
3693 (string :tag "Value"))))
3695 (defvar-local org-file-properties nil
3696 "List of property/value pairs that can be inherited by any entry.
3697 Valid for the current buffer.
3698 This variable is populated from #+PROPERTY lines.")
3700 (defgroup org-agenda nil
3701 "Options concerning agenda views in Org mode."
3702 :tag "Org Agenda"
3703 :group 'org)
3705 (defvar-local org-category nil
3706 "Variable used by org files to set a category for agenda display.
3707 Such files should use a file variable to set it, for example
3709 # -*- mode: org; org-category: \"ELisp\"
3711 or contain a special line
3713 #+CATEGORY: ELisp
3715 If the file does not specify a category, then file's base name
3716 is used instead.")
3717 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3719 (defcustom org-agenda-files nil
3720 "The files to be used for agenda display.
3722 If an entry is a directory, all files in that directory that are matched
3723 by `org-agenda-file-regexp' will be part of the file list.
3725 If the value of the variable is not a list but a single file name, then
3726 the list of agenda files is actually stored and maintained in that file,
3727 one agenda file per line. In this file paths can be given relative to
3728 `org-directory'. Tilde expansion and environment variable substitution
3729 are also made.
3731 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3732 and removed with `\\[org-remove-file]'."
3733 :group 'org-agenda
3734 :type '(choice
3735 (repeat :tag "List of files and directories" file)
3736 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3738 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3739 "Regular expression to match files for `org-agenda-files'.
3740 If any element in the list in that variable contains a directory instead
3741 of a normal file, all files in that directory that are matched by this
3742 regular expression will be included."
3743 :group 'org-agenda
3744 :type 'regexp)
3746 (defcustom org-agenda-text-search-extra-files nil
3747 "List of extra files to be searched by text search commands.
3748 These files will be searched in addition to the agenda files by the
3749 commands `org-search-view' (`\\[org-agenda] s') \
3750 and `org-occur-in-agenda-files'.
3751 Note that these files will only be searched for text search commands,
3752 not for the other agenda views like todo lists, tag searches or the weekly
3753 agenda. This variable is intended to list notes and possibly archive files
3754 that should also be searched by these two commands.
3755 In fact, if the first element in the list is the symbol `agenda-archives',
3756 then all archive files of all agenda files will be added to the search
3757 scope."
3758 :group 'org-agenda
3759 :type '(set :greedy t
3760 (const :tag "Agenda Archives" agenda-archives)
3761 (repeat :inline t (file))))
3763 (defvaralias 'org-agenda-multi-occur-extra-files
3764 'org-agenda-text-search-extra-files)
3766 (defcustom org-agenda-skip-unavailable-files nil
3767 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3768 A nil value means to remove them, after a query, from the list."
3769 :group 'org-agenda
3770 :type 'boolean)
3772 (defcustom org-calendar-to-agenda-key [?c]
3773 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3774 The command `org-calendar-goto-agenda' will be bound to this key. The
3775 default is the character `c' because then `c' can be used to switch back and
3776 forth between agenda and calendar."
3777 :group 'org-agenda
3778 :type 'sexp)
3780 (defcustom org-calendar-insert-diary-entry-key [?i]
3781 "The key to be installed in `calendar-mode-map' for adding diary entries.
3782 This option is irrelevant until `org-agenda-diary-file' has been configured
3783 to point to an Org file. When that is the case, the command
3784 `org-agenda-diary-entry' will be bound to the key given here, by default
3785 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3786 if you want to continue doing this, you need to change this to a different
3787 key."
3788 :group 'org-agenda
3789 :type 'sexp)
3791 (defcustom org-agenda-diary-file 'diary-file
3792 "File to which to add new entries with the `i' key in agenda and calendar.
3793 When this is the symbol `diary-file', the functionality in the Emacs
3794 calendar will be used to add entries to the `diary-file'. But when this
3795 points to a file, `org-agenda-diary-entry' will be used instead."
3796 :group 'org-agenda
3797 :type '(choice
3798 (const :tag "The standard Emacs diary file" diary-file)
3799 (file :tag "Special Org file diary entries")))
3801 (eval-after-load "calendar"
3802 '(progn
3803 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3804 'org-calendar-goto-agenda)
3805 (add-hook 'calendar-mode-hook
3806 (lambda ()
3807 (unless (eq org-agenda-diary-file 'diary-file)
3808 (define-key calendar-mode-map
3809 org-calendar-insert-diary-entry-key
3810 'org-agenda-diary-entry))))))
3812 (defgroup org-latex nil
3813 "Options for embedding LaTeX code into Org mode."
3814 :tag "Org LaTeX"
3815 :group 'org)
3817 (defcustom org-format-latex-options
3818 '(:foreground default :background default :scale 1.0
3819 :html-foreground "Black" :html-background "Transparent"
3820 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3821 "Options for creating images from LaTeX fragments.
3822 This is a property list with the following properties:
3823 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3824 `default' means use the foreground of the default face.
3825 `auto' means use the foreground from the text face.
3826 :background the background color, or \"Transparent\".
3827 `default' means use the background of the default face.
3828 `auto' means use the background from the text face.
3829 :scale a scaling factor for the size of the images, to get more pixels
3830 :html-foreground, :html-background, :html-scale
3831 the same numbers for HTML export.
3832 :matchers a list indicating which matchers should be used to
3833 find LaTeX fragments. Valid members of this list are:
3834 \"begin\" find environments
3835 \"$1\" find single characters surrounded by $.$
3836 \"$\" find math expressions surrounded by $...$
3837 \"$$\" find math expressions surrounded by $$....$$
3838 \"\\(\" find math expressions surrounded by \\(...\\)
3839 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3840 :group 'org-latex
3841 :type 'plist)
3843 (defcustom org-format-latex-signal-error t
3844 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3845 When nil, just push out a message."
3846 :group 'org-latex
3847 :version "24.1"
3848 :type 'boolean)
3850 (defcustom org-latex-to-mathml-jar-file nil
3851 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3852 Use this to specify additional executable file say a jar file.
3854 When using MathToWeb as the converter, specify the full-path to
3855 your mathtoweb.jar file."
3856 :group 'org-latex
3857 :version "24.1"
3858 :type '(choice
3859 (const :tag "None" nil)
3860 (file :tag "JAR file" :must-match t)))
3862 (defcustom org-latex-to-mathml-convert-command nil
3863 "Command to convert LaTeX fragments to MathML.
3864 Replace format-specifiers in the command as noted below and use
3865 `shell-command' to convert LaTeX to MathML.
3866 %j: Executable file in fully expanded form as specified by
3867 `org-latex-to-mathml-jar-file'.
3868 %I: Input LaTeX file in fully expanded form.
3869 %i: The latex fragment to be converted.
3870 %o: Output MathML file.
3872 This command is used by `org-create-math-formula'.
3874 When using MathToWeb as the converter, set this option to
3875 \"java -jar %j -unicode -force -df %o %I\".
3877 When using LaTeXML set this option to
3878 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3879 :group 'org-latex
3880 :version "24.1"
3881 :type '(choice
3882 (const :tag "None" nil)
3883 (string :tag "\nShell command")))
3885 (defcustom org-preview-latex-default-process 'dvipng
3886 "The default process to convert LaTeX fragments to image files.
3887 All available processes and theirs documents can be found in
3888 `org-preview-latex-process-alist', which see."
3889 :group 'org-latex
3890 :version "26.1"
3891 :package-version '(Org . "9.0")
3892 :type 'symbol)
3894 (defcustom org-preview-latex-process-alist
3895 '((dvipng
3896 :programs ("latex" "dvipng")
3897 :description "dvi > png"
3898 :message "you need to install the programs: latex and dvipng."
3899 :image-input-type "dvi"
3900 :image-output-type "png"
3901 :image-size-adjust (1.0 . 1.0)
3902 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3903 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3904 (dvisvgm
3905 :programs ("latex" "dvisvgm")
3906 :description "dvi > svg"
3907 :message "you need to install the programs: latex and dvisvgm."
3908 :use-xcolor t
3909 :image-input-type "dvi"
3910 :image-output-type "svg"
3911 :image-size-adjust (1.7 . 1.5)
3912 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3913 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3914 (imagemagick
3915 :programs ("latex" "convert")
3916 :description "pdf > png"
3917 :message "you need to install the programs: latex and imagemagick."
3918 :use-xcolor t
3919 :image-input-type "pdf"
3920 :image-output-type "png"
3921 :image-size-adjust (1.0 . 1.0)
3922 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3923 :image-converter
3924 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3925 "Definitions of external processes for LaTeX previewing.
3926 Org mode can use some external commands to generate TeX snippet's images for
3927 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3928 `org-create-formula-image' how to call them.
3930 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3931 PROPERTIES accepts the following attributes:
3933 :programs list of strings, required programs.
3934 :description string, describe the process.
3935 :message string, message it when required programs cannot be found.
3936 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3937 :image-output-type string, output file type of image converter (e.g., \"png\").
3938 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3939 deal with background and foreground color of image.
3940 Otherwise, dvipng style background and foreground color
3941 format are generated. You may then refer to them in
3942 command options with \"%F\" and \"%B\".
3943 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3944 image size showed in buffer and the cdr element is for
3945 HTML file. This option is only useful for process
3946 developers, users should use variable
3947 `org-format-latex-options' instead.
3948 :post-clean list of strings, files matched are to be cleaned up once
3949 the image is generated. When nil, the files with \".dvi\",
3950 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3951 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3952 be cleaned up.
3953 :latex-header list of strings, the LaTeX header of the snippet file.
3954 When nil, the fallback value is used instead, which is
3955 controlled by `org-format-latex-header',
3956 `org-latex-default-packages-alist' and
3957 `org-latex-packages-alist', which see.
3958 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3959 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3960 replaced with values defined below.
3961 :image-converter list of image converter commands strings. Each of them is
3962 given to the shell and supports any of the following
3963 place-holders defined below.
3965 Place-holders used by `:image-converter' and `:latex-compiler':
3967 %f input file name
3968 %b base name of input file
3969 %o base directory of input file
3970 %O absolute output file name
3972 Place-holders only used by `:image-converter':
3974 %F foreground of image
3975 %B background of image
3976 %D dpi, which is used to adjust image size by some processing commands.
3977 %S the image size scale ratio, which is used to adjust image size by some
3978 processing commands."
3979 :group 'org-latex
3980 :version "26.1"
3981 :package-version '(Org . "9.0")
3982 :type '(alist :tag "LaTeX to image backends"
3983 :value-type (plist)))
3985 (defcustom org-preview-latex-image-directory "ltximg/"
3986 "Path to store latex preview images.
3987 A relative path here creates many directories relative to the
3988 processed org files paths. An absolute path puts all preview
3989 images at the same place."
3990 :group 'org-latex
3991 :version "26.1"
3992 :package-version '(Org . "9.0")
3993 :type 'string)
3995 (defun org-format-latex-mathml-available-p ()
3996 "Return t if `org-latex-to-mathml-convert-command' is usable."
3997 (save-match-data
3998 (when (and (boundp 'org-latex-to-mathml-convert-command)
3999 org-latex-to-mathml-convert-command)
4000 (let ((executable (car (split-string
4001 org-latex-to-mathml-convert-command))))
4002 (when (executable-find executable)
4003 (if (string-match
4004 "%j" org-latex-to-mathml-convert-command)
4005 (file-readable-p org-latex-to-mathml-jar-file)
4006 t))))))
4008 (defcustom org-format-latex-header "\\documentclass{article}
4009 \\usepackage[usenames]{color}
4010 \[PACKAGES]
4011 \[DEFAULT-PACKAGES]
4012 \\pagestyle{empty} % do not remove
4013 % The settings below are copied from fullpage.sty
4014 \\setlength{\\textwidth}{\\paperwidth}
4015 \\addtolength{\\textwidth}{-3cm}
4016 \\setlength{\\oddsidemargin}{1.5cm}
4017 \\addtolength{\\oddsidemargin}{-2.54cm}
4018 \\setlength{\\evensidemargin}{\\oddsidemargin}
4019 \\setlength{\\textheight}{\\paperheight}
4020 \\addtolength{\\textheight}{-\\headheight}
4021 \\addtolength{\\textheight}{-\\headsep}
4022 \\addtolength{\\textheight}{-\\footskip}
4023 \\addtolength{\\textheight}{-3cm}
4024 \\setlength{\\topmargin}{1.5cm}
4025 \\addtolength{\\topmargin}{-2.54cm}"
4026 "The document header used for processing LaTeX fragments.
4027 It is imperative that this header make sure that no page number
4028 appears on the page. The package defined in the variables
4029 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4030 will either replace the placeholder \"[PACKAGES]\" in this
4031 header, or they will be appended."
4032 :group 'org-latex
4033 :type 'string)
4035 (defun org-set-packages-alist (var val)
4036 "Set the packages alist and make sure it has 3 elements per entry."
4037 (set var (mapcar (lambda (x)
4038 (if (and (consp x) (= (length x) 2))
4039 (list (car x) (nth 1 x) t)
4041 val)))
4043 (defun org-get-packages-alist (var)
4044 "Get the packages alist and make sure it has 3 elements per entry."
4045 (mapcar (lambda (x)
4046 (if (and (consp x) (= (length x) 2))
4047 (list (car x) (nth 1 x) t)
4049 (default-value var)))
4051 (defcustom org-latex-default-packages-alist
4052 '(("AUTO" "inputenc" t ("pdflatex"))
4053 ("T1" "fontenc" t ("pdflatex"))
4054 ("" "graphicx" t)
4055 ("" "grffile" t)
4056 ("" "longtable" nil)
4057 ("" "wrapfig" nil)
4058 ("" "rotating" nil)
4059 ("normalem" "ulem" t)
4060 ("" "amsmath" t)
4061 ("" "textcomp" t)
4062 ("" "amssymb" t)
4063 ("" "capt-of" nil)
4064 ("" "hyperref" nil))
4065 "Alist of default packages to be inserted in the header.
4067 Change this only if one of the packages here causes an
4068 incompatibility with another package you are using.
4070 The packages in this list are needed by one part or another of
4071 Org mode to function properly:
4073 - inputenc, fontenc: for basic font and character selection
4074 - graphicx: for including images
4075 - grffile: allow periods and spaces in graphics file names
4076 - longtable: For multipage tables
4077 - wrapfig: for figure placement
4078 - rotating: for sideways figures and tables
4079 - ulem: for underline and strike-through
4080 - amsmath: for subscript and superscript and math environments
4081 - textcomp, amssymb: for various symbols used
4082 for interpreting the entities in `org-entities'. You can skip
4083 some of these packages if you don't use any of their symbols.
4084 - capt-of: for captions outside of floats
4085 - hyperref: for cross references
4087 Therefore you should not modify this variable unless you know
4088 what you are doing. The one reason to change it anyway is that
4089 you might be loading some other package that conflicts with one
4090 of the default packages. Each element is either a cell or
4091 a string.
4093 A cell is of the format
4095 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4097 If SNIPPET-FLAG is non-nil, the package also needs to be included
4098 when compiling LaTeX snippets into images for inclusion into
4099 non-LaTeX output. COMPILERS is a list of compilers that should
4100 include the package, see `org-latex-compiler'. If the document
4101 compiler is not in the list, and the list is non-nil, the package
4102 will not be inserted in the final document.
4104 A string will be inserted as-is in the header of the document."
4105 :group 'org-latex
4106 :group 'org-export-latex
4107 :set 'org-set-packages-alist
4108 :get 'org-get-packages-alist
4109 :version "26.1"
4110 :package-version '(Org . "8.3")
4111 :type '(repeat
4112 (choice
4113 (list :tag "options/package pair"
4114 (string :tag "options")
4115 (string :tag "package")
4116 (boolean :tag "Snippet"))
4117 (string :tag "A line of LaTeX"))))
4119 (defcustom org-latex-packages-alist nil
4120 "Alist of packages to be inserted in every LaTeX header.
4122 These will be inserted after `org-latex-default-packages-alist'.
4123 Each element is either a cell or a string.
4125 A cell is of the format:
4127 (\"options\" \"package\" SNIPPET-FLAG)
4129 SNIPPET-FLAG, when non-nil, indicates that this package is also
4130 needed when turning LaTeX snippets into images for inclusion into
4131 non-LaTeX output.
4133 A string will be inserted as-is in the header of the document.
4135 Make sure that you only list packages here which:
4137 - you want in every file;
4138 - do not conflict with the setup in `org-format-latex-header';
4139 - do not conflict with the default packages in
4140 `org-latex-default-packages-alist'."
4141 :group 'org-latex
4142 :group 'org-export-latex
4143 :set 'org-set-packages-alist
4144 :get 'org-get-packages-alist
4145 :type '(repeat
4146 (choice
4147 (list :tag "options/package pair"
4148 (string :tag "options")
4149 (string :tag "package")
4150 (boolean :tag "Snippet"))
4151 (string :tag "A line of LaTeX"))))
4153 (defgroup org-appearance nil
4154 "Settings for Org mode appearance."
4155 :tag "Org Appearance"
4156 :group 'org)
4158 (defcustom org-level-color-stars-only nil
4159 "Non-nil means fontify only the stars in each headline.
4160 When nil, the entire headline is fontified.
4161 Changing it requires restart of `font-lock-mode' to become effective
4162 also in regions already fontified."
4163 :group 'org-appearance
4164 :type 'boolean)
4166 (defcustom org-hide-leading-stars nil
4167 "Non-nil means hide the first N-1 stars in a headline.
4168 This works by using the face `org-hide' for these stars. This
4169 face is white for a light background, and black for a dark
4170 background. You may have to customize the face `org-hide' to
4171 make this work.
4172 Changing it requires restart of `font-lock-mode' to become effective
4173 also in regions already fontified.
4174 You may also set this on a per-file basis by adding one of the following
4175 lines to the buffer:
4177 #+STARTUP: hidestars
4178 #+STARTUP: showstars"
4179 :group 'org-appearance
4180 :type 'boolean)
4182 (defcustom org-hidden-keywords nil
4183 "List of symbols corresponding to keywords to be hidden the org buffer.
4184 For example, a value \\='(title) for this list will make the document's title
4185 appear in the buffer without the initial #+TITLE: keyword."
4186 :group 'org-appearance
4187 :version "24.1"
4188 :type '(set (const :tag "#+AUTHOR" author)
4189 (const :tag "#+DATE" date)
4190 (const :tag "#+EMAIL" email)
4191 (const :tag "#+TITLE" title)))
4193 (defcustom org-custom-properties nil
4194 "List of properties (as strings) with a special meaning.
4195 The default use of these custom properties is to let the user
4196 hide them with `org-toggle-custom-properties-visibility'."
4197 :group 'org-properties
4198 :group 'org-appearance
4199 :version "24.3"
4200 :type '(repeat (string :tag "Property Name")))
4202 (defcustom org-fontify-done-headline nil
4203 "Non-nil means change the face of a headline if it is marked DONE.
4204 Normally, only the TODO/DONE keyword indicates the state of a headline.
4205 When this is non-nil, the headline after the keyword is set to the
4206 `org-headline-done' as an additional indication."
4207 :group 'org-appearance
4208 :type 'boolean)
4210 (defcustom org-fontify-emphasized-text t
4211 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4212 Changing this variable requires a restart of Emacs to take effect."
4213 :group 'org-appearance
4214 :type 'boolean)
4216 (defcustom org-fontify-whole-heading-line nil
4217 "Non-nil means fontify the whole line for headings.
4218 This is useful when setting a background color for the
4219 org-level-* faces."
4220 :group 'org-appearance
4221 :type 'boolean)
4223 (defcustom org-highlight-latex-and-related nil
4224 "Non-nil means highlight LaTeX related syntax in the buffer.
4225 When non nil, the value should be a list containing any of the
4226 following symbols:
4227 `latex' Highlight LaTeX snippets and environments.
4228 `script' Highlight subscript and superscript.
4229 `entities' Highlight entities."
4230 :group 'org-appearance
4231 :version "24.4"
4232 :package-version '(Org . "8.0")
4233 :type '(choice
4234 (const :tag "No highlighting" nil)
4235 (set :greedy t :tag "Highlight"
4236 (const :tag "LaTeX snippets and environments" latex)
4237 (const :tag "Subscript and superscript" script)
4238 (const :tag "Entities" entities))))
4240 (defcustom org-hide-emphasis-markers nil
4241 "Non-nil mean font-lock should hide the emphasis marker characters."
4242 :group 'org-appearance
4243 :type 'boolean)
4245 (defcustom org-hide-macro-markers nil
4246 "Non-nil mean font-lock should hide the brackets marking macro calls."
4247 :group 'org-appearance
4248 :type 'boolean)
4250 (defcustom org-pretty-entities nil
4251 "Non-nil means show entities as UTF8 characters.
4252 When nil, the \\name form remains in the buffer."
4253 :group 'org-appearance
4254 :version "24.1"
4255 :type 'boolean)
4257 (defcustom org-pretty-entities-include-sub-superscripts t
4258 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4259 :group 'org-appearance
4260 :version "24.1"
4261 :type 'boolean)
4263 (defvar org-emph-re nil
4264 "Regular expression for matching emphasis.
4265 After a match, the match groups contain these elements:
4266 0 The match of the full regular expression, including the characters
4267 before and after the proper match
4268 1 The character before the proper match, or empty at beginning of line
4269 2 The proper match, including the leading and trailing markers
4270 3 The leading marker like * or /, indicating the type of highlighting
4271 4 The text between the emphasis markers, not including the markers
4272 5 The character after the match, empty at the end of a line")
4274 (defvar org-verbatim-re nil
4275 "Regular expression for matching verbatim text.")
4277 (defvar org-emphasis-regexp-components) ; defined just below
4278 (defvar org-emphasis-alist) ; defined just below
4279 (defun org-set-emph-re (var val)
4280 "Set variable and compute the emphasis regular expression."
4281 (set var val)
4282 (when (and (boundp 'org-emphasis-alist)
4283 (boundp 'org-emphasis-regexp-components)
4284 org-emphasis-alist org-emphasis-regexp-components)
4285 (pcase-let*
4286 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4287 (body (if (<= nl 0) body
4288 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4289 (template
4290 (format (concat "\\([%s]\\|^\\)" ;before markers
4291 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4292 "\\([%s]\\|$\\)") ;after markers
4293 pre border border body border post)))
4294 (setq org-emph-re (format template "*/_+"))
4295 (setq org-verbatim-re (format template "=~")))))
4297 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4298 ;; set this option proved cumbersome. See this message/thread:
4299 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4300 (defvar org-emphasis-regexp-components
4301 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4302 "Components used to build the regular expression for emphasis.
4303 This is a list with five entries. Terminology: In an emphasis string
4304 like \" *strong word* \", we call the initial space PREMATCH, the final
4305 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4306 and \"trong wor\" is the body. The different components in this variable
4307 specify what is allowed/forbidden in each part:
4309 pre Chars allowed as prematch. Beginning of line will be allowed too.
4310 post Chars allowed as postmatch. End of line will be allowed too.
4311 border The chars *forbidden* as border characters.
4312 body-regexp A regexp like \".\" to match a body character. Don't use
4313 non-shy groups here, and don't allow newline here.
4314 newline The maximum number of newlines allowed in an emphasis exp.
4316 You need to reload Org or to restart Emacs after setting this.")
4318 (defcustom org-emphasis-alist
4319 '(("*" bold)
4320 ("/" italic)
4321 ("_" underline)
4322 ("=" org-verbatim verbatim)
4323 ("~" org-code verbatim)
4324 ("+" (:strike-through t)))
4325 "Alist of characters and faces to emphasize text.
4326 Text starting and ending with a special character will be emphasized,
4327 for example *bold*, _underlined_ and /italic/. This variable sets the
4328 marker characters and the face to be used by font-lock for highlighting
4329 in Org buffers.
4331 You need to reload Org or to restart Emacs after customizing this."
4332 :group 'org-appearance
4333 :set 'org-set-emph-re
4334 :version "24.4"
4335 :package-version '(Org . "8.0")
4336 :type '(repeat
4337 (list
4338 (string :tag "Marker character")
4339 (choice
4340 (face :tag "Font-lock-face")
4341 (plist :tag "Face property list"))
4342 (option (const verbatim)))))
4344 (defvar org-protecting-blocks '("src" "example" "export")
4345 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4346 This is needed for font-lock setup.")
4348 ;;; Functions and variables from their packages
4349 ;; Declared here to avoid compiler warnings
4350 (defvar mark-active)
4352 ;; Various packages
4353 (declare-function calc-eval "calc" (str &optional separator &rest args))
4354 (declare-function calendar-forward-day "cal-move" (arg))
4355 (declare-function calendar-goto-date "cal-move" (date))
4356 (declare-function calendar-goto-today "cal-move" ())
4357 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4358 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4359 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4360 (declare-function cdlatex-tab "ext:cdlatex" ())
4361 (declare-function dired-get-filename
4362 "dired"
4363 (&optional localp no-error-if-not-filep))
4364 (declare-function iswitchb-read-buffer
4365 "iswitchb"
4366 (prompt &optional
4367 default require-match _predicate start matches-set))
4368 (declare-function org-agenda-change-all-lines
4369 "org-agenda"
4370 (newhead hdmarker &optional fixface just-this))
4371 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4372 "org-agenda"
4373 (&optional end))
4374 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4375 (declare-function org-agenda-format-item
4376 "org-agenda"
4377 (extra txt &optional level category tags dotime
4378 remove-re habitp))
4379 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4380 (declare-function org-agenda-save-markers-for-cut-and-paste
4381 "org-agenda"
4382 (beg end))
4383 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4384 (declare-function org-agenda-skip "org-agenda" ())
4385 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4386 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4387 (declare-function org-indent-mode "org-indent" (&optional arg))
4388 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4389 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4390 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4391 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4392 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4393 (declare-function parse-time-string "parse-time" (string))
4395 (defvar align-mode-rules-list)
4396 (defvar calc-embedded-close-formula)
4397 (defvar calc-embedded-open-formula)
4398 (defvar calc-embedded-open-mode)
4399 (defvar font-lock-unfontify-region-function)
4400 (defvar iswitchb-temp-buflist)
4401 (defvar org-agenda-tags-todo-honor-ignore-options)
4402 (defvar remember-data-file)
4403 (defvar texmathp-why)
4405 ;;;###autoload
4406 (defun turn-on-orgtbl ()
4407 "Unconditionally turn on `orgtbl-mode'."
4408 (require 'org-table)
4409 (orgtbl-mode 1))
4411 (defun org-at-table-p (&optional table-type)
4412 "Non-nil if the cursor is inside an Org table.
4413 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4414 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4415 (or (not (derived-mode-p 'org-mode))
4416 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4417 (and e (or table-type
4418 (eq 'org (org-element-property :type e))))))))
4420 (defun org-at-table.el-p ()
4421 "Non-nil when point is at a table.el table."
4422 (and (org-match-line "[ \t]*[|+]")
4423 (let ((element (org-element-at-point)))
4424 (and (eq (org-element-type element) 'table)
4425 (eq (org-element-property :type element) 'table.el)))))
4427 (defun org-at-table-hline-p ()
4428 "Non-nil when point is inside a hline in a table.
4429 Assume point is already in a table."
4430 (org-match-line org-table-hline-regexp))
4432 (defun org-table-map-tables (function &optional quietly)
4433 "Apply FUNCTION to the start of all tables in the buffer."
4434 (org-with-wide-buffer
4435 (goto-char (point-min))
4436 (while (re-search-forward org-table-any-line-regexp nil t)
4437 (unless quietly
4438 (message "Mapping tables: %d%%"
4439 (floor (* 100.0 (point)) (buffer-size))))
4440 (beginning-of-line 1)
4441 (when (and (looking-at org-table-line-regexp)
4442 ;; Exclude tables in src/example/verbatim/clocktable blocks
4443 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4444 (save-excursion (funcall function))
4445 (or (looking-at org-table-line-regexp)
4446 (forward-char 1)))
4447 (re-search-forward org-table-any-border-regexp nil 1)))
4448 (unless quietly (message "Mapping tables: done")))
4450 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4451 (declare-function org-clock-update-mode-line "org-clock" ())
4452 (declare-function org-resolve-clocks "org-clock"
4453 (&optional also-non-dangling-p prompt last-valid))
4455 (defun org-at-TBLFM-p (&optional pos)
4456 "Non-nil when point (or POS) is in #+TBLFM line."
4457 (save-excursion
4458 (goto-char (or pos (point)))
4459 (beginning-of-line)
4460 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4461 (eq (org-element-type (org-element-at-point)) 'table))))
4463 (defvar org-clock-start-time)
4464 (defvar org-clock-marker (make-marker)
4465 "Marker recording the last clock-in.")
4466 (defvar org-clock-hd-marker (make-marker)
4467 "Marker recording the last clock-in, but the headline position.")
4468 (defvar org-clock-heading ""
4469 "The heading of the current clock entry.")
4470 (defun org-clock-is-active ()
4471 "Return the buffer where the clock is currently running.
4472 Return nil if no clock is running."
4473 (marker-buffer org-clock-marker))
4475 (defun org-check-running-clock ()
4476 "Check if the current buffer contains the running clock.
4477 If yes, offer to stop it and to save the buffer with the changes."
4478 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4479 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4480 (buffer-name))))
4481 (org-clock-out)
4482 (when (y-or-n-p "Save changed buffer?")
4483 (save-buffer))))
4485 (defun org-clocktable-try-shift (dir n)
4486 "Check if this line starts a clock table, if yes, shift the time block."
4487 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4488 (org-clocktable-shift dir n)))
4490 ;;;###autoload
4491 (defun org-clock-persistence-insinuate ()
4492 "Set up hooks for clock persistence."
4493 (require 'org-clock)
4494 (add-hook 'org-mode-hook 'org-clock-load)
4495 (add-hook 'kill-emacs-hook 'org-clock-save))
4497 (defgroup org-archive nil
4498 "Options concerning archiving in Org mode."
4499 :tag "Org Archive"
4500 :group 'org-structure)
4502 (defcustom org-archive-location "%s_archive::"
4503 "The location where subtrees should be archived.
4505 The value of this variable is a string, consisting of two parts,
4506 separated by a double-colon. The first part is a filename and
4507 the second part is a headline.
4509 When the filename is omitted, archiving happens in the same file.
4510 %s in the filename will be replaced by the current file
4511 name (without the directory part). Archiving to a different file
4512 is useful to keep archived entries from contributing to the
4513 Org Agenda.
4515 The archived entries will be filed as subtrees of the specified
4516 headline. When the headline is omitted, the subtrees are simply
4517 filed away at the end of the file, as top-level entries. Also in
4518 the heading you can use %s to represent the file name, this can be
4519 useful when using the same archive for a number of different files.
4521 Here are a few examples:
4522 \"%s_archive::\"
4523 If the current file is Projects.org, archive in file
4524 Projects.org_archive, as top-level trees. This is the default.
4526 \"::* Archived Tasks\"
4527 Archive in the current file, under the top-level headline
4528 \"* Archived Tasks\".
4530 \"~/org/archive.org::\"
4531 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4533 \"~/org/archive.org::* From %s\"
4534 Archive in file ~/org/archive.org (absolute path), under headlines
4535 \"From FILENAME\" where file name is the current file name.
4537 \"~/org/datetree.org::datetree/* Finished Tasks\"
4538 The \"datetree/\" string is special, signifying to archive
4539 items to the datetree. Items are placed in either the CLOSED
4540 date of the item, or the current date if there is no CLOSED date.
4541 The heading will be a subentry to the current date. There doesn't
4542 need to be a heading, but there always needs to be a slash after
4543 datetree. For example, to store archived items directly in the
4544 datetree, use \"~/org/datetree.org::datetree/\".
4546 \"basement::** Finished Tasks\"
4547 Archive in file ./basement (relative path), as level 3 trees
4548 below the level 2 heading \"** Finished Tasks\".
4550 You may set this option on a per-file basis by adding to the buffer a
4551 line like
4553 #+ARCHIVE: basement::** Finished Tasks
4555 You may also define it locally for a subtree by setting an ARCHIVE property
4556 in the entry. If such a property is found in an entry, or anywhere up
4557 the hierarchy, it will be used."
4558 :group 'org-archive
4559 :type 'string)
4561 (defcustom org-agenda-skip-archived-trees t
4562 "Non-nil means the agenda will skip any items located in archived trees.
4563 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4564 variable is no longer recommended, you should leave it at the value t.
4565 Instead, use the key `v' to cycle the archives-mode in the agenda."
4566 :group 'org-archive
4567 :group 'org-agenda-skip
4568 :type 'boolean)
4570 (defcustom org-columns-skip-archived-trees t
4571 "Non-nil means ignore archived trees when creating column view."
4572 :group 'org-archive
4573 :group 'org-properties
4574 :type 'boolean)
4576 (defcustom org-cycle-open-archived-trees nil
4577 "Non-nil means `org-cycle' will open archived trees.
4578 An archived tree is a tree marked with the tag ARCHIVE.
4579 When nil, archived trees will stay folded. You can still open them with
4580 normal outline commands like `show-all', but not with the cycling commands."
4581 :group 'org-archive
4582 :group 'org-cycle
4583 :type 'boolean)
4585 (defcustom org-sparse-tree-open-archived-trees nil
4586 "Non-nil means sparse tree construction shows matches in archived trees.
4587 When nil, matches in these trees are highlighted, but the trees are kept in
4588 collapsed state."
4589 :group 'org-archive
4590 :group 'org-sparse-trees
4591 :type 'boolean)
4593 (defcustom org-sparse-tree-default-date-type nil
4594 "The default date type when building a sparse tree.
4595 When this is nil, a date is a scheduled or a deadline timestamp.
4596 Otherwise, these types are allowed:
4598 all: all timestamps
4599 active: only active timestamps (<...>)
4600 inactive: only inactive timestamps ([...])
4601 scheduled: only scheduled timestamps
4602 deadline: only deadline timestamps"
4603 :type '(choice (const :tag "Scheduled or deadline" nil)
4604 (const :tag "All timestamps" all)
4605 (const :tag "Only active timestamps" active)
4606 (const :tag "Only inactive timestamps" inactive)
4607 (const :tag "Only scheduled timestamps" scheduled)
4608 (const :tag "Only deadline timestamps" deadline)
4609 (const :tag "Only closed timestamps" closed))
4610 :version "26.1"
4611 :package-version '(Org . "8.3")
4612 :group 'org-sparse-trees)
4614 (defun org-cycle-hide-archived-subtrees (state)
4615 "Re-hide all archived subtrees after a visibility state change.
4616 STATE should be one of the symbols listed in the docstring of
4617 `org-cycle-hook'."
4618 (when (and (not org-cycle-open-archived-trees)
4619 (not (memq state '(overview folded))))
4620 (save-excursion
4621 (let* ((globalp (memq state '(contents all)))
4622 (beg (if globalp (point-min) (point)))
4623 (end (if globalp (point-max) (org-end-of-subtree t))))
4624 (org-hide-archived-subtrees beg end)
4625 (goto-char beg)
4626 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4627 (message "%s" (substitute-command-keys
4628 "Subtree is archived and stays closed. Use \
4629 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4631 (defun org-force-cycle-archived ()
4632 "Cycle subtree even if it is archived."
4633 (interactive)
4634 (setq this-command 'org-cycle)
4635 (let ((org-cycle-open-archived-trees t))
4636 (call-interactively 'org-cycle)))
4638 (defun org-hide-archived-subtrees (beg end)
4639 "Re-hide all archived subtrees after a visibility state change."
4640 (org-with-wide-buffer
4641 (let ((case-fold-search nil)
4642 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4643 (goto-char beg)
4644 ;; Include headline point is currently on.
4645 (beginning-of-line)
4646 (while (and (< (point) end) (re-search-forward re end t))
4647 (when (member org-archive-tag (org-get-tags))
4648 (org-flag-subtree t)
4649 (org-end-of-subtree t))))))
4651 (declare-function outline-end-of-heading "outline" ())
4652 (declare-function outline-flag-region "outline" (from to flag))
4653 (defun org-flag-subtree (flag)
4654 (save-excursion
4655 (org-back-to-heading t)
4656 (outline-end-of-heading)
4657 (outline-flag-region (point)
4658 (progn (org-end-of-subtree t) (point))
4659 flag)))
4661 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4663 ;; Declare Column View Code
4665 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4666 (declare-function org-columns-compute "org-colview" (property))
4668 ;; Declare ID code
4670 (declare-function org-id-store-link "org-id")
4671 (declare-function org-id-locations-load "org-id")
4672 (declare-function org-id-locations-save "org-id")
4673 (defvar org-id-track-globally)
4675 ;;; Variables for pre-computed regular expressions, all buffer local
4677 (defvar-local org-todo-regexp nil
4678 "Matches any of the TODO state keywords.
4679 Since TODO keywords are case-sensitive, `case-fold-search' is
4680 expected to be bound to nil when matching against this regexp.")
4682 (defvar-local org-not-done-regexp nil
4683 "Matches any of the TODO state keywords except the last one.
4684 Since TODO keywords are case-sensitive, `case-fold-search' is
4685 expected to be bound to nil when matching against this regexp.")
4687 (defvar-local org-not-done-heading-regexp nil
4688 "Matches a TODO headline that is not done.
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-todo-line-regexp nil
4693 "Matches a headline and puts TODO state into group 2 if present.
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-complex-heading-regexp nil
4698 "Matches a headline and puts everything into groups:
4700 group 1: Stars
4701 group 2: The TODO keyword, maybe
4702 group 3: Priority cookie
4703 group 4: True headline
4704 group 5: Tags
4706 Since TODO keywords are case-sensitive, `case-fold-search' is
4707 expected to be bound to nil when matching against this regexp.")
4709 (defvar-local org-complex-heading-regexp-format nil
4710 "Printf format to make regexp to match an exact headline.
4711 This regexp will match the headline of any node which has the
4712 exact headline text that is put into the format, but may have any
4713 TODO state, priority and tags.")
4715 (defvar-local org-todo-line-tags-regexp nil
4716 "Matches a headline and puts TODO state into group 2 if present.
4717 Also put tags into group 4 if tags are present.")
4719 (defconst org-plain-time-of-day-regexp
4720 (concat
4721 "\\(\\<[012]?[0-9]"
4722 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4723 "\\(--?"
4724 "\\(\\<[012]?[0-9]"
4725 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4726 "\\)?")
4727 "Regular expression to match a plain time or time range.
4728 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4729 groups carry important information:
4730 0 the full match
4731 1 the first time, range or not
4732 8 the second time, if it is a range.")
4734 (defconst org-plain-time-extension-regexp
4735 (concat
4736 "\\(\\<[012]?[0-9]"
4737 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4738 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4739 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4740 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4741 groups carry important information:
4742 0 the full match
4743 7 hours of duration
4744 9 minutes of duration")
4746 (defconst org-stamp-time-of-day-regexp
4747 (concat
4748 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4749 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4750 "\\(--?"
4751 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4752 "Regular expression to match a timestamp time or time range.
4753 After a match, the following groups carry important information:
4754 0 the full match
4755 1 date plus weekday, for back referencing to make sure both times are on the same day
4756 2 the first time, range or not
4757 4 the second time, if it is a range.")
4759 (defconst org-startup-options
4760 '(("fold" org-startup-folded t)
4761 ("overview" org-startup-folded t)
4762 ("nofold" org-startup-folded nil)
4763 ("showall" org-startup-folded nil)
4764 ("showeverything" org-startup-folded showeverything)
4765 ("content" org-startup-folded content)
4766 ("indent" org-startup-indented t)
4767 ("noindent" org-startup-indented nil)
4768 ("hidestars" org-hide-leading-stars t)
4769 ("showstars" org-hide-leading-stars nil)
4770 ("odd" org-odd-levels-only t)
4771 ("oddeven" org-odd-levels-only nil)
4772 ("align" org-startup-align-all-tables t)
4773 ("noalign" org-startup-align-all-tables nil)
4774 ("shrink" org-startup-shrink-all-tables t)
4775 ("inlineimages" org-startup-with-inline-images t)
4776 ("noinlineimages" org-startup-with-inline-images nil)
4777 ("latexpreview" org-startup-with-latex-preview t)
4778 ("nolatexpreview" org-startup-with-latex-preview nil)
4779 ("customtime" org-display-custom-times t)
4780 ("logdone" org-log-done time)
4781 ("lognotedone" org-log-done note)
4782 ("nologdone" org-log-done nil)
4783 ("lognoteclock-out" org-log-note-clock-out t)
4784 ("nolognoteclock-out" org-log-note-clock-out nil)
4785 ("logrepeat" org-log-repeat state)
4786 ("lognoterepeat" org-log-repeat note)
4787 ("logdrawer" org-log-into-drawer t)
4788 ("nologdrawer" org-log-into-drawer nil)
4789 ("logstatesreversed" org-log-states-order-reversed t)
4790 ("nologstatesreversed" org-log-states-order-reversed nil)
4791 ("nologrepeat" org-log-repeat nil)
4792 ("logreschedule" org-log-reschedule time)
4793 ("lognotereschedule" org-log-reschedule note)
4794 ("nologreschedule" org-log-reschedule nil)
4795 ("logredeadline" org-log-redeadline time)
4796 ("lognoteredeadline" org-log-redeadline note)
4797 ("nologredeadline" org-log-redeadline nil)
4798 ("logrefile" org-log-refile time)
4799 ("lognoterefile" org-log-refile note)
4800 ("nologrefile" org-log-refile nil)
4801 ("fninline" org-footnote-define-inline t)
4802 ("nofninline" org-footnote-define-inline nil)
4803 ("fnlocal" org-footnote-section nil)
4804 ("fnauto" org-footnote-auto-label t)
4805 ("fnprompt" org-footnote-auto-label nil)
4806 ("fnconfirm" org-footnote-auto-label confirm)
4807 ("fnplain" org-footnote-auto-label plain)
4808 ("fnadjust" org-footnote-auto-adjust t)
4809 ("nofnadjust" org-footnote-auto-adjust nil)
4810 ("constcgs" constants-unit-system cgs)
4811 ("constSI" constants-unit-system SI)
4812 ("noptag" org-tag-persistent-alist nil)
4813 ("hideblocks" org-hide-block-startup t)
4814 ("nohideblocks" org-hide-block-startup nil)
4815 ("beamer" org-startup-with-beamer-mode t)
4816 ("entitiespretty" org-pretty-entities t)
4817 ("entitiesplain" org-pretty-entities nil))
4818 "Variable associated with STARTUP options for org-mode.
4819 Each element is a list of three items: the startup options (as written
4820 in the #+STARTUP line), the corresponding variable, and the value to set
4821 this variable to if the option is found. An optional forth element PUSH
4822 means to push this value onto the list in the variable.")
4824 (defcustom org-group-tags t
4825 "When non-nil (the default), use group tags.
4826 This can be turned on/off through `org-toggle-tags-groups'."
4827 :group 'org-tags
4828 :group 'org-startup
4829 :type 'boolean)
4831 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4833 (defun org-toggle-tags-groups ()
4834 "Toggle support for group tags.
4835 Support for group tags is controlled by the option
4836 `org-group-tags', which is non-nil by default."
4837 (interactive)
4838 (setq org-group-tags (not org-group-tags))
4839 (cond ((and (derived-mode-p 'org-agenda-mode)
4840 org-group-tags)
4841 (org-agenda-redo))
4842 ((derived-mode-p 'org-mode)
4843 (let ((org-inhibit-startup t)) (org-mode))))
4844 (message "Groups tags support has been turned %s"
4845 (if org-group-tags "on" "off")))
4847 (defun org-set-regexps-and-options (&optional tags-only)
4848 "Precompute regular expressions used in the current buffer.
4849 When optional argument TAGS-ONLY is non-nil, only compute tags
4850 related expressions."
4851 (when (derived-mode-p 'org-mode)
4852 (let ((alist (org--setup-collect-keywords
4853 (org-make-options-regexp
4854 (append '("FILETAGS" "TAGS" "SETUPFILE")
4855 (and (not tags-only)
4856 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4857 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4858 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4859 ;; Startup options. Get this early since it does change
4860 ;; behavior for other options (e.g., tags).
4861 (let ((startup (cdr (assq 'startup alist))))
4862 (dolist (option startup)
4863 (let ((entry (assoc-string option org-startup-options t)))
4864 (when entry
4865 (let ((var (nth 1 entry))
4866 (val (nth 2 entry)))
4867 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4868 (unless (listp (symbol-value var))
4869 (set (make-local-variable var) nil))
4870 (add-to-list var val)))))))
4871 (setq-local org-file-tags
4872 (mapcar #'org-add-prop-inherited
4873 (cdr (assq 'filetags alist))))
4874 (setq org-current-tag-alist
4875 (append org-tag-persistent-alist
4876 (let ((tags (cdr (assq 'tags alist))))
4877 (if tags (org-tag-string-to-alist tags)
4878 org-tag-alist))))
4879 (setq org-tag-groups-alist
4880 (org-tag-alist-to-groups org-current-tag-alist))
4881 (unless tags-only
4882 ;; File properties.
4883 (setq-local org-file-properties (cdr (assq 'property alist)))
4884 ;; Archive location.
4885 (let ((archive (cdr (assq 'archive alist))))
4886 (when archive (setq-local org-archive-location archive)))
4887 ;; Category.
4888 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4889 (when cat
4890 (setq-local org-category (intern cat))
4891 (setq-local org-file-properties
4892 (org--update-property-plist
4893 "CATEGORY" cat org-file-properties))))
4894 ;; Columns.
4895 (let ((column (cdr (assq 'columns alist))))
4896 (when column (setq-local org-columns-default-format column)))
4897 ;; Constants.
4898 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4899 ;; Link abbreviations.
4900 (let ((links (cdr (assq 'link alist))))
4901 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4902 ;; Priorities.
4903 (let ((priorities (cdr (assq 'priorities alist))))
4904 (when priorities
4905 (setq-local org-highest-priority (nth 0 priorities))
4906 (setq-local org-lowest-priority (nth 1 priorities))
4907 (setq-local org-default-priority (nth 2 priorities))))
4908 ;; Scripts.
4909 (let ((scripts (assq 'scripts alist)))
4910 (when scripts
4911 (setq-local org-use-sub-superscripts (cdr scripts))))
4912 ;; TODO keywords.
4913 (setq-local org-todo-kwd-alist nil)
4914 (setq-local org-todo-key-alist nil)
4915 (setq-local org-todo-key-trigger nil)
4916 (setq-local org-todo-keywords-1 nil)
4917 (setq-local org-done-keywords nil)
4918 (setq-local org-todo-heads nil)
4919 (setq-local org-todo-sets nil)
4920 (setq-local org-todo-log-states nil)
4921 (let ((todo-sequences
4922 (or (nreverse (cdr (assq 'todo alist)))
4923 (let ((d (default-value 'org-todo-keywords)))
4924 (if (not (stringp (car d))) d
4925 ;; XXX: Backward compatibility code.
4926 (list (cons org-todo-interpretation d)))))))
4927 (dolist (sequence todo-sequences)
4928 (let* ((sequence (or (run-hook-with-args-until-success
4929 'org-todo-setup-filter-hook sequence)
4930 sequence))
4931 (sequence-type (car sequence))
4932 (keywords (cdr sequence))
4933 (sep (member "|" keywords))
4934 names alist)
4935 (dolist (k (remove "|" keywords))
4936 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4938 (error "Invalid TODO keyword %s" k))
4939 (let ((name (match-string 1 k))
4940 (key (match-string 2 k))
4941 (log (org-extract-log-state-settings k)))
4942 (push name names)
4943 (push (cons name (and key (string-to-char key))) alist)
4944 (when log (push log org-todo-log-states))))
4945 (let* ((names (nreverse names))
4946 (done (if sep (org-remove-keyword-keys (cdr sep))
4947 (last names)))
4948 (head (car names))
4949 (tail (list sequence-type head (car done) (org-last done))))
4950 (add-to-list 'org-todo-heads head 'append)
4951 (push names org-todo-sets)
4952 (setq org-done-keywords (append org-done-keywords done nil))
4953 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4954 (setq org-todo-key-alist
4955 (append org-todo-key-alist
4956 (and alist
4957 (append '((:startgroup))
4958 (nreverse alist)
4959 '((:endgroup))))))
4960 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4961 (setq org-todo-sets (nreverse org-todo-sets)
4962 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4963 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
4964 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
4965 ;; Compute the regular expressions and other local variables.
4966 ;; Using `org-outline-regexp-bol' would complicate them much,
4967 ;; because of the fixed white space at the end of that string.
4968 (unless org-done-keywords
4969 (setq org-done-keywords
4970 (and org-todo-keywords-1 (last org-todo-keywords-1))))
4971 (setq org-not-done-keywords
4972 (org-delete-all org-done-keywords
4973 (copy-sequence org-todo-keywords-1))
4974 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
4975 org-not-done-regexp (regexp-opt org-not-done-keywords t)
4976 org-not-done-heading-regexp
4977 (format org-heading-keyword-regexp-format org-not-done-regexp)
4978 org-todo-line-regexp
4979 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4980 org-complex-heading-regexp
4981 (concat "^\\(\\*+\\)"
4982 "\\(?: +" org-todo-regexp "\\)?"
4983 "\\(?: +\\(\\[#.\\]\\)\\)?"
4984 "\\(?: +\\(.*?\\)\\)??"
4985 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
4986 "[ \t]*$")
4987 org-complex-heading-regexp-format
4988 (concat "^\\(\\*+\\)"
4989 "\\(?: +" org-todo-regexp "\\)?"
4990 "\\(?: +\\(\\[#.\\]\\)\\)?"
4991 "\\(?: +"
4992 ;; Stats cookies can be stuck to body.
4993 "\\(?:\\[[0-9%%/]+\\] *\\)*"
4994 "\\(%s\\)"
4995 "\\(?: *\\[[0-9%%/]+\\]\\)*"
4996 "\\)"
4997 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
4998 "[ \t]*$")
4999 org-todo-line-tags-regexp
5000 (concat "^\\(\\*+\\)"
5001 "\\(?: +" org-todo-regexp "\\)?"
5002 "\\(?: +\\(.*?\\)\\)??"
5003 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5004 "[ \t]*$"))
5005 (org-compute-latex-and-related-regexp)))))
5007 (defun org--setup-collect-keywords (regexp &optional files alist)
5008 "Return setup keywords values as an alist.
5010 REGEXP matches a subset of setup keywords. FILES is a list of
5011 file names already visited. It is used to avoid circular setup
5012 files. ALIST, when non-nil, is the alist computed so far.
5014 Return value contains the following keys: `archive', `category',
5015 `columns', `constants', `filetags', `link', `priorities',
5016 `property', `scripts', `startup', `tags' and `todo'."
5017 (org-with-wide-buffer
5018 (goto-char (point-min))
5019 (let ((case-fold-search t))
5020 (while (re-search-forward regexp nil t)
5021 (let ((element (org-element-at-point)))
5022 (when (eq (org-element-type element) 'keyword)
5023 (let ((key (org-element-property :key element))
5024 (value (org-element-property :value element)))
5025 (cond
5026 ((equal key "ARCHIVE")
5027 (when (org-string-nw-p value)
5028 (push (cons 'archive value) alist)))
5029 ((equal key "CATEGORY") (push (cons 'category value) alist))
5030 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5031 ((equal key "CONSTANTS")
5032 (let* ((constants (assq 'constants alist))
5033 (store (cdr constants)))
5034 (dolist (pair (split-string value))
5035 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5036 pair)
5037 (let* ((name (match-string 1 pair))
5038 (value (match-string 2 pair))
5039 (old (assoc name store)))
5040 (if old (setcdr old value)
5041 (push (cons name value) store)))))
5042 (if constants (setcdr constants store)
5043 (push (cons 'constants store) alist))))
5044 ((equal key "FILETAGS")
5045 (when (org-string-nw-p value)
5046 (let ((old (assq 'filetags alist))
5047 (new (apply #'nconc
5048 (mapcar (lambda (x) (org-split-string x ":"))
5049 (split-string value)))))
5050 (if old (setcdr old (append new (cdr old)))
5051 (push (cons 'filetags new) alist)))))
5052 ((equal key "LINK")
5053 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5054 (let ((links (assq 'link alist))
5055 (pair (cons (match-string-no-properties 1 value)
5056 (match-string-no-properties 2 value))))
5057 (if links (push pair (cdr links))
5058 (push (list 'link pair) alist)))))
5059 ((equal key "OPTIONS")
5060 (when (and (org-string-nw-p value)
5061 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5062 (push (cons 'scripts (read (match-string 1 value))) alist)))
5063 ((equal key "PRIORITIES")
5064 (push (cons 'priorities
5065 (let ((prio (split-string value)))
5066 (if (< (length prio) 3) '(?A ?C ?B)
5067 (mapcar #'string-to-char prio))))
5068 alist))
5069 ((equal key "PROPERTY")
5070 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5071 (let* ((property (assq 'property alist))
5072 (value (org--update-property-plist
5073 (match-string-no-properties 1 value)
5074 (match-string-no-properties 2 value)
5075 (cdr property))))
5076 (if property (setcdr property value)
5077 (push (cons 'property value) alist)))))
5078 ((equal key "STARTUP")
5079 (let ((startup (assq 'startup alist)))
5080 (if startup
5081 (setcdr startup
5082 (append (cdr startup) (split-string value)))
5083 (push (cons 'startup (split-string value)) alist))))
5084 ((equal key "TAGS")
5085 (let ((tag-cell (assq 'tags alist)))
5086 (if tag-cell
5087 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5088 (push (cons 'tags value) alist))))
5089 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5090 (let ((todo (assq 'todo alist))
5091 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5092 (split-string value))))
5093 (if todo (push value (cdr todo))
5094 (push (list 'todo value) alist))))
5095 ((equal key "SETUPFILE")
5096 (unless buffer-read-only ; Do not check in Gnus messages.
5097 (let ((f (and (org-string-nw-p value)
5098 (expand-file-name
5099 (org-unbracket-string "\"" "\"" value)))))
5100 (when (and f (file-readable-p f) (not (member f files)))
5101 (with-temp-buffer
5102 (setq default-directory (file-name-directory f))
5103 (insert-file-contents f)
5104 (setq alist
5105 ;; Fake Org mode to benefit from cache
5106 ;; without recurring needlessly.
5107 (let ((major-mode 'org-mode))
5108 (org--setup-collect-keywords
5109 regexp (cons f files) alist)))))))))))))))
5110 alist)
5112 (defun org-tag-string-to-alist (s)
5113 "Return tag alist associated to string S.
5114 S is a value for TAGS keyword or produced with
5115 `org-tag-alist-to-string'. Return value is an alist suitable for
5116 `org-tag-alist' or `org-tag-persistent-alist'."
5117 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5118 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5119 "\\|{.+?}\\)" ; regular expression
5120 "\\(?:(\\(.\\))\\)?\\'"))
5121 alist group-flag)
5122 (dolist (tokens lines (cdr (nreverse alist)))
5123 (push '(:newline) alist)
5124 (while tokens
5125 (let ((token (pop tokens)))
5126 (pcase token
5127 ("{"
5128 (push '(:startgroup) alist)
5129 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5130 ("}"
5131 (push '(:endgroup) alist)
5132 (setq group-flag nil))
5133 ("["
5134 (push '(:startgrouptag) alist)
5135 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5136 ("]"
5137 (push '(:endgrouptag) alist)
5138 (setq group-flag nil))
5139 (":"
5140 (push '(:grouptags) alist))
5141 ((guard (string-match tag-re token))
5142 (let ((tag (match-string 1 token))
5143 (key (and (match-beginning 2)
5144 (string-to-char (match-string 2 token)))))
5145 ;; Push all tags in groups, no matter if they already
5146 ;; appear somewhere else in the list.
5147 (when (or group-flag (not (assoc tag alist)))
5148 (push (cons tag key) alist))))))))))
5150 (defun org-tag-alist-to-string (alist &optional skip-key)
5151 "Return tag string associated to ALIST.
5153 ALIST is an alist, as defined in `org-tag-alist' or
5154 `org-tag-persistent-alist', or produced with
5155 `org-tag-string-to-alist'.
5157 Return value is a string suitable as a value for \"TAGS\"
5158 keyword.
5160 When optional argument SKIP-KEY is non-nil, skip selection keys
5161 next to tags."
5162 (mapconcat (lambda (token)
5163 (pcase token
5164 (`(:startgroup) "{")
5165 (`(:endgroup) "}")
5166 (`(:startgrouptag) "[")
5167 (`(:endgrouptag) "]")
5168 (`(:grouptags) ":")
5169 (`(:newline) "\\n")
5170 ((and
5171 (guard (not skip-key))
5172 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5173 (format "%s(%c)" tag key))
5174 (`(,(and tag (pred stringp)) . ,_) tag)
5175 (_ (user-error "Invalid tag token: %S" token))))
5176 alist
5177 " "))
5179 (defun org-tag-alist-to-groups (alist)
5180 "Return group alist from tag ALIST.
5181 ALIST is an alist, as defined in `org-tag-alist' or
5182 `org-tag-persistent-alist', or produced with
5183 `org-tag-string-to-alist'. Return value is an alist following
5184 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5185 a string, summarizing TAGS, as a list of strings."
5186 (let (groups group-status current-group)
5187 (dolist (token alist (nreverse groups))
5188 (pcase token
5189 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5190 (`(,(or :endgroup :endgrouptag))
5191 (when (eq group-status 'append)
5192 (push (nreverse current-group) groups))
5193 (setq group-status nil))
5194 (`(:grouptags) (setq group-status 'append))
5195 ((and `(,tag . ,_) (guard group-status))
5196 (if (eq group-status 'append) (push tag current-group)
5197 (setq current-group (list tag))))
5198 (_ nil)))))
5200 (defvar org--file-cache (make-hash-table :test #'equal)
5201 "Hash table to store contents of files referenced via a URL.
5202 This is the cache of file URLs read using `org-file-contents'.")
5204 (defun org-reset-file-cache ()
5205 "Reset the cache of files downloaded by `org-file-contents'."
5206 (clrhash org--file-cache))
5208 (defun org-file-url-p (file)
5209 "Non-nil if FILE is a URL."
5210 (require 'ffap)
5211 (string-match-p ffap-url-regexp file))
5213 (defun org-file-contents (file &optional noerror nocache)
5214 "Return the contents of FILE, as a string.
5216 FILE can be a file name or URL.
5218 If FILE is a URL, download the contents. If the URL contents are
5219 already cached in the `org--file-cache' hash table, the download step
5220 is skipped.
5222 If NOERROR is non-nil, ignore the error when unable to read the FILE
5223 from file or URL.
5225 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5226 is available. This option applies only if FILE is a URL."
5227 (let* ((is-url (org-file-url-p file))
5228 (cache (and is-url
5229 (not nocache)
5230 (gethash file org--file-cache))))
5231 (cond
5232 (cache)
5233 (is-url
5234 (with-current-buffer (url-retrieve-synchronously file)
5235 (goto-char (point-min))
5236 ;; Move point to after the url-retrieve header.
5237 (search-forward "\n\n" nil :move)
5238 ;; Search for the success code only in the url-retrieve header.
5239 (if (save-excursion
5240 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5241 ;; Update the cache `org--file-cache' and return contents.
5242 (puthash file
5243 (buffer-substring-no-properties (point) (point-max))
5244 org--file-cache)
5245 (funcall (if noerror #'message #'user-error)
5246 "Unable to fetch file from %S"
5247 file))))
5249 (with-temp-buffer
5250 (condition-case nil
5251 (progn
5252 (insert-file-contents file)
5253 (buffer-string))
5254 (file-error
5255 (funcall (if noerror #'message #'user-error)
5256 "Unable to read file %S"
5257 file))))))))
5259 (defun org-extract-log-state-settings (x)
5260 "Extract the log state setting from a TODO keyword string.
5261 This will extract info from a string like \"WAIT(w@/!)\"."
5262 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5263 (let ((kw (match-string 1 x))
5264 (log1 (and (match-end 3) (match-string 3 x)))
5265 (log2 (and (match-end 4) (match-string 4 x))))
5266 (and (or log1 log2)
5267 (list kw
5268 (and log1 (if (equal log1 "!") 'time 'note))
5269 (and log2 (if (equal log2 "!") 'time 'note)))))))
5271 (defun org-remove-keyword-keys (list)
5272 "Remove a pair of parenthesis at the end of each string in LIST."
5273 (mapcar (lambda (x)
5274 (if (string-match "(.*)$" x)
5275 (substring x 0 (match-beginning 0))
5277 list))
5279 (defun org-assign-fast-keys (alist)
5280 "Assign fast keys to a keyword-key alist.
5281 Respect keys that are already there."
5282 (let (new e (alt ?0))
5283 (while (setq e (pop alist))
5284 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5285 (cdr e)) ;; Key already assigned.
5286 (push e new)
5287 (let ((clist (string-to-list (downcase (car e))))
5288 (used (append new alist)))
5289 (when (= (car clist) ?@)
5290 (pop clist))
5291 (while (and clist (rassoc (car clist) used))
5292 (pop clist))
5293 (unless clist
5294 (while (rassoc alt used)
5295 (cl-incf alt)))
5296 (push (cons (car e) (or (car clist) alt)) new))))
5297 (nreverse new)))
5299 ;;; Some variables used in various places
5301 (defvar org-window-configuration nil
5302 "Used in various places to store a window configuration.")
5303 (defvar org-selected-window nil
5304 "Used in various places to store a window configuration.")
5305 (defvar org-finish-function nil
5306 "Function to be called when `C-c C-c' is used.
5307 This is for getting out of special buffers like capture.")
5308 (defvar org-last-state)
5310 ;; Defined somewhere in this file, but used before definition.
5311 (defvar org-entities) ;; defined in org-entities.el
5312 (defvar org-struct-menu)
5313 (defvar org-org-menu)
5314 (defvar org-tbl-menu)
5316 ;;;; Define the Org mode
5318 ;; We use a before-change function to check if a table might need
5319 ;; an update.
5320 (defvar org-table-may-need-update t
5321 "Indicates that a table might need an update.
5322 This variable is set by `org-before-change-function'.
5323 `org-table-align' sets it back to nil.")
5324 (defun org-before-change-function (_beg _end)
5325 "Every change indicates that a table might need an update."
5326 (setq org-table-may-need-update t))
5327 (defvar org-mode-map)
5328 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5329 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5330 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5331 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5332 (defvar org-table-buffer-is-an nil)
5334 (defvar bidi-paragraph-direction)
5335 (defvar buffer-face-mode-face)
5337 (require 'outline)
5339 ;; Other stuff we need.
5340 (require 'time-date)
5341 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5342 (require 'easymenu)
5343 (autoload 'easy-menu-add "easymenu")
5344 (require 'overlay)
5346 ;; (require 'org-macs) moved higher up in the file before it is first used
5347 (require 'org-entities)
5348 ;; (require 'org-compat) moved higher up in the file before it is first used
5349 (require 'org-faces)
5350 (require 'org-list)
5351 (require 'org-pcomplete)
5352 (require 'org-src)
5353 (require 'org-footnote)
5354 (require 'org-macro)
5356 ;; babel
5357 (require 'ob)
5359 ;;;###autoload
5360 (define-derived-mode org-mode outline-mode "Org"
5361 "Outline-based notes management and organizer, alias
5362 \"Carsten's outline-mode for keeping track of everything.\"
5364 Org mode develops organizational tasks around a NOTES file which
5365 contains information about projects as plain text. Org mode is
5366 implemented on top of Outline mode, which is ideal to keep the content
5367 of large files well structured. It supports ToDo items, deadlines and
5368 time stamps, which magically appear in the diary listing of the Emacs
5369 calendar. Tables are easily created with a built-in table editor.
5370 Plain text URL-like links connect to websites, emails (VM), Usenet
5371 messages (Gnus), BBDB entries, and any files related to the project.
5372 For printing and sharing of notes, an Org file (or a part of it)
5373 can be exported as a structured ASCII or HTML file.
5375 The following commands are available:
5377 \\{org-mode-map}"
5379 ;; Get rid of Outline menus, they are not needed
5380 ;; Need to do this here because define-derived-mode sets up
5381 ;; the keymap so late. Still, it is a waste to call this each time
5382 ;; we switch another buffer into Org mode.
5383 (define-key org-mode-map [menu-bar headings] 'undefined)
5384 (define-key org-mode-map [menu-bar hide] 'undefined)
5385 (define-key org-mode-map [menu-bar show] 'undefined)
5387 (org-load-modules-maybe)
5388 (org-install-agenda-files-menu)
5389 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5390 (add-to-invisibility-spec '(org-hide-block . t))
5391 (setq-local outline-regexp org-outline-regexp)
5392 (setq-local outline-level 'org-outline-level)
5393 (setq bidi-paragraph-direction 'left-to-right)
5394 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5395 (unless org-display-table
5396 (setq org-display-table (make-display-table)))
5397 (set-display-table-slot
5398 org-display-table 4
5399 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5400 org-ellipsis)))
5401 (setq buffer-display-table org-display-table))
5402 (org-set-regexps-and-options)
5403 (org-set-font-lock-defaults)
5404 (when (and org-tag-faces (not org-tags-special-faces-re))
5405 ;; tag faces set outside customize.... force initialization.
5406 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5407 ;; Calc embedded
5408 (setq-local calc-embedded-open-mode "# ")
5409 ;; Modify a few syntax entries
5410 (modify-syntax-entry ?@ "w")
5411 (modify-syntax-entry ?\" "\"")
5412 (modify-syntax-entry ?\\ "_")
5413 (modify-syntax-entry ?~ "_")
5414 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5415 ;; Activate before-change-function
5416 (setq-local org-table-may-need-update t)
5417 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5418 ;; Check for running clock before killing a buffer
5419 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5420 ;; Initialize macros templates.
5421 (org-macro-initialize-templates)
5422 ;; Initialize radio targets.
5423 (org-update-radio-target-regexp)
5424 ;; Indentation.
5425 (setq-local indent-line-function 'org-indent-line)
5426 (setq-local indent-region-function 'org-indent-region)
5427 ;; Filling and auto-filling.
5428 (org-setup-filling)
5429 ;; Comments.
5430 (org-setup-comments-handling)
5431 ;; Initialize cache.
5432 (org-element-cache-reset)
5433 ;; Beginning/end of defun
5434 (setq-local beginning-of-defun-function 'org-backward-element)
5435 (setq-local end-of-defun-function
5436 (lambda ()
5437 (if (not (org-at-heading-p))
5438 (org-forward-element)
5439 (org-forward-element)
5440 (forward-char -1))))
5441 ;; Next error for sparse trees
5442 (setq-local next-error-function 'org-occur-next-match)
5443 ;; Make sure dependence stuff works reliably, even for users who set it
5444 ;; too late :-(
5445 (if org-enforce-todo-dependencies
5446 (add-hook 'org-blocker-hook
5447 'org-block-todo-from-children-or-siblings-or-parent)
5448 (remove-hook 'org-blocker-hook
5449 'org-block-todo-from-children-or-siblings-or-parent))
5450 (if org-enforce-todo-checkbox-dependencies
5451 (add-hook 'org-blocker-hook
5452 'org-block-todo-from-checkboxes)
5453 (remove-hook 'org-blocker-hook
5454 'org-block-todo-from-checkboxes))
5456 ;; Align options lines
5457 (setq-local
5458 align-mode-rules-list
5459 '((org-in-buffer-settings
5460 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5461 (modes . '(org-mode)))))
5463 ;; Imenu
5464 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5466 ;; Make isearch reveal context
5467 (setq-local outline-isearch-open-invisible-function
5468 (lambda (&rest _) (org-show-context 'isearch)))
5470 ;; Setup the pcomplete hooks
5471 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5472 (setq-local pcomplete-command-name-function 'org-command-at-point)
5473 (setq-local pcomplete-default-completion-function 'ignore)
5474 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5475 (setq-local pcomplete-termination-string "")
5476 (setq-local buffer-face-mode-face 'org-default)
5478 ;; If empty file that did not turn on Org mode automatically, make
5479 ;; it to.
5480 (when (and org-insert-mode-line-in-empty-file
5481 (called-interactively-p 'any)
5482 (= (point-min) (point-max)))
5483 (insert "# -*- mode: org -*-\n\n"))
5484 (unless org-inhibit-startup
5485 (org-unmodified
5486 (when org-startup-with-beamer-mode (org-beamer-mode))
5487 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5488 (org-table-map-tables
5489 (cond ((and org-startup-align-all-tables
5490 org-startup-shrink-all-tables)
5491 (lambda () (org-table-align) (org-table-shrink)))
5492 (org-startup-align-all-tables #'org-table-align)
5493 (t #'org-table-shrink))
5495 (when org-startup-with-inline-images (org-display-inline-images))
5496 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5497 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5498 (when org-startup-truncated (setq truncate-lines t))
5499 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5500 (org-refresh-effort-properties)))
5501 ;; Try to set `org-hide' face correctly.
5502 (let ((foreground (org-find-invisible-foreground)))
5503 (when foreground
5504 (set-face-foreground 'org-hide foreground))))
5506 ;; Update `customize-package-emacs-version-alist'
5507 (add-to-list 'customize-package-emacs-version-alist
5508 '(Org ("8.0" . "24.4")
5509 ("8.1" . "24.4")
5510 ("8.2" . "24.4")
5511 ("8.2.7" . "24.4")
5512 ("8.3" . "26.1")
5513 ("9.0" . "26.1")
5514 ("9.1" . "26.1")
5515 ("9.2" . "27.1")))
5517 (defvar org-mode-transpose-word-syntax-table
5518 (let ((st (make-syntax-table text-mode-syntax-table)))
5519 (dolist (c org-emphasis-alist st)
5520 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5522 (when (fboundp 'abbrev-table-put)
5523 (abbrev-table-put org-mode-abbrev-table
5524 :parents (list text-mode-abbrev-table)))
5526 (defun org-find-invisible-foreground ()
5527 (let ((candidates (remove
5528 "unspecified-bg"
5529 (nconc
5530 (list (face-background 'default)
5531 (face-background 'org-default))
5532 (mapcar
5533 (lambda (alist)
5534 (when (boundp alist)
5535 (cdr (assq 'background-color (symbol-value alist)))))
5536 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5537 (list (face-foreground 'org-hide))))))
5538 (car (remove nil candidates))))
5540 (defun org-current-time (&optional rounding-minutes past)
5541 "Current time, possibly rounded to ROUNDING-MINUTES.
5542 When ROUNDING-MINUTES is not an integer, fall back on the car of
5543 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5544 the rounding returns a past time."
5545 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5546 (car org-time-stamp-rounding-minutes)))
5547 (time (decode-time)) res)
5548 (if (< r 1)
5549 (current-time)
5550 (setq res
5551 (apply 'encode-time
5552 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5553 (nthcdr 2 time))))
5554 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5555 (seconds-to-time (- (float-time res) (* r 60)))
5556 res))))
5558 (defun org-today ()
5559 "Return today date, considering `org-extend-today-until'."
5560 (time-to-days
5561 (time-subtract (current-time)
5562 (list 0 (* 3600 org-extend-today-until) 0))))
5564 ;;;; Font-Lock stuff, including the activators
5566 (defvar org-mouse-map (make-sparse-keymap))
5567 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5568 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5569 (when org-mouse-1-follows-link
5570 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5571 (when org-tab-follows-link
5572 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5573 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5575 (require 'font-lock)
5577 (defconst org-non-link-chars "]\t\n\r<>")
5578 (defvar org-link-types-re nil
5579 "Matches a link that has a url-like prefix like \"http:\"")
5580 (defvar org-link-re-with-space nil
5581 "Matches a link with spaces, optional angular brackets around it.")
5582 (defvar org-link-re-with-space2 nil
5583 "Matches a link with spaces, optional angular brackets around it.")
5584 (defvar org-link-re-with-space3 nil
5585 "Matches a link with spaces, only for internal part in bracket links.")
5586 (defvar org-angle-link-re nil
5587 "Matches link with angular brackets, spaces are allowed.")
5588 (defvar org-plain-link-re nil
5589 "Matches plain link, without spaces.")
5590 (defvar org-bracket-link-regexp nil
5591 "Matches a link in double brackets.")
5592 (defvar org-bracket-link-analytic-regexp nil
5593 "Regular expression used to analyze links.
5594 Here is what the match groups contain after a match:
5595 1: http:
5596 2: http
5597 3: path
5598 4: [desc]
5599 5: desc")
5600 (defvar org-bracket-link-analytic-regexp++ nil
5601 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5602 (defvar org-any-link-re nil
5603 "Regular expression matching any link.")
5605 (defconst org-match-sexp-depth 3
5606 "Number of stacked braces for sub/superscript matching.")
5608 (defun org-create-multibrace-regexp (left right n)
5609 "Create a regular expression which will match a balanced sexp.
5610 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5611 as single character strings.
5612 The regexp returned will match the entire expression including the
5613 delimiters. It will also define a single group which contains the
5614 match except for the outermost delimiters. The maximum depth of
5615 stacked delimiters is N. Escaping delimiters is not possible."
5616 (let* ((nothing (concat "[^" left right "]*?"))
5617 (or "\\|")
5618 (re nothing)
5619 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5620 (while (> n 1)
5621 (setq n (1- n)
5622 re (concat re or next)
5623 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5624 (concat left "\\(" re "\\)" right)))
5626 (defconst org-match-substring-regexp
5627 (concat
5628 "\\(\\S-\\)\\([_^]\\)\\("
5629 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5630 "\\|"
5631 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5632 "\\|"
5633 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5634 "The regular expression matching a sub- or superscript.")
5636 (defconst org-match-substring-with-braces-regexp
5637 (concat
5638 "\\(\\S-\\)\\([_^]\\)"
5639 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5640 "The regular expression matching a sub- or superscript, forcing braces.")
5642 (defun org-make-link-regexps ()
5643 "Update the link regular expressions.
5644 This should be called after the variable `org-link-parameters' has changed."
5645 (let ((types-re (regexp-opt (org-link-types) t)))
5646 (setq org-link-types-re
5647 (concat "\\`" types-re ":")
5648 org-link-re-with-space
5649 (concat "<?" types-re ":"
5650 "\\([^" org-non-link-chars " ]"
5651 "[^" org-non-link-chars "]*"
5652 "[^" org-non-link-chars " ]\\)>?")
5653 org-link-re-with-space2
5654 (concat "<?" types-re ":"
5655 "\\([^" org-non-link-chars " ]"
5656 "[^\t\n\r]*"
5657 "[^" org-non-link-chars " ]\\)>?")
5658 org-link-re-with-space3
5659 (concat "<?" types-re ":"
5660 "\\([^" org-non-link-chars " ]"
5661 "[^\t\n\r]*\\)")
5662 org-angle-link-re
5663 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5664 types-re)
5665 org-plain-link-re
5666 (concat
5667 "\\<" types-re ":"
5668 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5669 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5670 org-bracket-link-regexp
5671 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5672 org-bracket-link-analytic-regexp
5673 (concat
5674 "\\[\\["
5675 "\\(" types-re ":\\)?"
5676 "\\([^]]+\\)"
5677 "\\]"
5678 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5679 "\\]")
5680 org-bracket-link-analytic-regexp++
5681 (concat
5682 "\\[\\["
5683 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5684 "\\([^]]+\\)"
5685 "\\]"
5686 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5687 "\\]")
5688 org-any-link-re
5689 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5690 org-angle-link-re "\\)\\|\\("
5691 org-plain-link-re "\\)"))))
5693 (org-make-link-regexps)
5695 (defvar org-emph-face nil)
5697 (defun org-do-emphasis-faces (limit)
5698 "Run through the buffer and emphasize strings."
5699 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5700 (car org-emphasis-regexp-components))))
5701 (catch :exit
5702 (while (re-search-forward quick-re limit t)
5703 (let* ((marker (match-string 2))
5704 (verbatim? (member marker '("~" "="))))
5705 (when (save-excursion
5706 (goto-char (match-beginning 0))
5707 (and
5708 ;; Do not match headline stars. Do not consider
5709 ;; stars of a headline as closing marker for bold
5710 ;; markup either.
5711 (not (and (equal marker "*")
5712 (save-excursion
5713 (forward-char)
5714 (skip-chars-backward "*")
5715 (looking-at-p org-outline-regexp-bol))))
5716 ;; Do not match table hlines.
5717 (not (and (equal marker "+")
5718 (org-match-line
5719 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5720 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5721 ;; At a table row, do not cross cell boundaries.
5722 (not (and (save-match-data (org-match-line "[ \t]*|"))
5723 (string-match-p "|" (match-string 4))))))
5724 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5725 (font-lock-prepend-text-property
5726 (match-beginning 2) (match-end 2) 'face face)
5727 (when verbatim?
5728 (org-remove-flyspell-overlays-in
5729 (match-beginning 0) (match-end 0)))
5730 (add-text-properties (match-beginning 2) (match-end 2)
5731 '(font-lock-multiline t org-emphasis t))
5732 (when org-hide-emphasis-markers
5733 (add-text-properties (match-end 4) (match-beginning 5)
5734 '(invisible org-link))
5735 (add-text-properties (match-beginning 3) (match-end 3)
5736 '(invisible org-link)))
5737 (throw :exit t))))))))
5739 (defun org-emphasize (&optional char)
5740 "Insert or change an emphasis, i.e. a font like bold or italic.
5741 If there is an active region, change that region to a new emphasis.
5742 If there is no region, just insert the marker characters and position
5743 the cursor between them.
5744 CHAR should be the marker character. If it is a space, it means to
5745 remove the emphasis of the selected region.
5746 If CHAR is not given (for example in an interactive call) it will be
5747 prompted for."
5748 (interactive)
5749 (let ((erc org-emphasis-regexp-components)
5750 (string "") beg end move s)
5751 (if (org-region-active-p)
5752 (setq beg (region-beginning)
5753 end (region-end)
5754 string (buffer-substring beg end))
5755 (setq move t))
5757 (unless char
5758 (message "Emphasis marker or tag: [%s]"
5759 (mapconcat #'car org-emphasis-alist ""))
5760 (setq char (read-char-exclusive)))
5761 (if (equal char ?\s)
5762 (setq s ""
5763 move nil)
5764 (unless (assoc (char-to-string char) org-emphasis-alist)
5765 (user-error "No such emphasis marker: \"%c\"" char))
5766 (setq s (char-to-string char)))
5767 (while (and (> (length string) 1)
5768 (equal (substring string 0 1) (substring string -1))
5769 (assoc (substring string 0 1) org-emphasis-alist))
5770 (setq string (substring string 1 -1)))
5771 (setq string (concat s string s))
5772 (when beg (delete-region beg end))
5773 (unless (or (bolp)
5774 (string-match (concat "[" (nth 0 erc) "\n]")
5775 (char-to-string (char-before (point)))))
5776 (insert " "))
5777 (unless (or (eobp)
5778 (string-match (concat "[" (nth 1 erc) "\n]")
5779 (char-to-string (char-after (point)))))
5780 (insert " ") (backward-char 1))
5781 (insert string)
5782 (and move (backward-char 1))))
5784 (defconst org-nonsticky-props
5785 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5787 (defsubst org-rear-nonsticky-at (pos)
5788 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5790 (defun org-activate-links (limit)
5791 "Add link properties to links.
5792 This includes angle, plain, and bracket links."
5793 (catch :exit
5794 (while (re-search-forward org-any-link-re limit t)
5795 (let* ((start (match-beginning 0))
5796 (end (match-end 0))
5797 (style (cond ((eq ?< (char-after start)) 'angle)
5798 ((eq ?\[ (char-after (1+ start))) 'bracket)
5799 (t 'plain))))
5800 (when (and (memq style org-highlight-links)
5801 ;; Do not confuse plain links with tags.
5802 (not (and (eq style 'plain)
5803 (let ((face (get-text-property
5804 (max (1- start) (point-min)) 'face)))
5805 (if (consp face) (memq 'org-tag face)
5806 (eq 'org-tag face))))))
5807 (let* ((link-object (save-excursion
5808 (goto-char start)
5809 (save-match-data (org-element-link-parser))))
5810 (link (org-element-property :raw-link link-object))
5811 (type (org-element-property :type link-object))
5812 (path (org-element-property :path link-object))
5813 (properties ;for link's visible part
5814 (list
5815 'face (pcase (org-link-get-parameter type :face)
5816 ((and (pred functionp) face) (funcall face path))
5817 ((and (pred facep) face) face)
5818 ((and (pred consp) face) face) ;anonymous
5819 (_ 'org-link))
5820 'mouse-face (or (org-link-get-parameter type :mouse-face)
5821 'highlight)
5822 'keymap (or (org-link-get-parameter type :keymap)
5823 org-mouse-map)
5824 'help-echo (pcase (org-link-get-parameter type :help-echo)
5825 ((and (pred stringp) echo) echo)
5826 ((and (pred functionp) echo) echo)
5827 (_ (concat "LINK: " link)))
5828 'htmlize-link (pcase (org-link-get-parameter type
5829 :htmlize-link)
5830 ((and (pred functionp) f) (funcall f))
5831 (_ `(:uri ,link)))
5832 'font-lock-multiline t)))
5833 (org-remove-flyspell-overlays-in start end)
5834 (org-rear-nonsticky-at end)
5835 (if (not (eq 'bracket style))
5836 (add-text-properties start end properties)
5837 ;; Handle invisible parts in bracket links.
5838 (remove-text-properties start end '(invisible nil))
5839 (let ((hidden
5840 (append `(invisible
5841 ,(or (org-link-get-parameter type :display)
5842 'org-link))
5843 properties))
5844 (visible-start (or (match-beginning 4) (match-beginning 2)))
5845 (visible-end (or (match-end 4) (match-end 2))))
5846 (add-text-properties start visible-start hidden)
5847 (add-text-properties visible-start visible-end properties)
5848 (add-text-properties visible-end end hidden)
5849 (org-rear-nonsticky-at visible-start)
5850 (org-rear-nonsticky-at visible-end)))
5851 (let ((f (org-link-get-parameter type :activate-func)))
5852 (when (functionp f)
5853 (funcall f start end path (eq style 'bracket))))
5854 (throw :exit t))))) ;signal success
5855 nil))
5857 (defun org-activate-code (limit)
5858 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5859 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5860 (remove-text-properties (match-beginning 0) (match-end 0)
5861 '(display t invisible t intangible t))
5864 (defcustom org-src-fontify-natively t
5865 "When non-nil, fontify code in code blocks.
5866 See also the `org-block' face."
5867 :type 'boolean
5868 :version "26.1"
5869 :package-version '(Org . "8.3")
5870 :group 'org-appearance
5871 :group 'org-babel)
5873 (defcustom org-allow-promoting-top-level-subtree nil
5874 "When non-nil, allow promoting a top level subtree.
5875 The leading star of the top level headline will be replaced
5876 by a #."
5877 :type 'boolean
5878 :version "24.1"
5879 :group 'org-appearance)
5881 (defun org-fontify-meta-lines-and-blocks (limit)
5882 (condition-case nil
5883 (org-fontify-meta-lines-and-blocks-1 limit)
5884 (error (message "org-mode fontification error in %S at %d"
5885 (current-buffer)
5886 (line-number-at-pos)))))
5888 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5889 "Fontify #+ lines and blocks."
5890 (let ((case-fold-search t))
5891 (when (re-search-forward
5892 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5893 limit t)
5894 (let ((beg (match-beginning 0))
5895 (block-start (match-end 0))
5896 (block-end nil)
5897 (lang (match-string 7))
5898 (beg1 (line-beginning-position 2))
5899 (dc1 (downcase (match-string 2)))
5900 (dc3 (downcase (match-string 3)))
5901 end end1 quoting block-type)
5902 (cond
5903 ((and (match-end 4) (equal dc3 "+begin"))
5904 ;; Truly a block
5905 (setq block-type (downcase (match-string 5))
5906 quoting (member block-type org-protecting-blocks))
5907 (when (re-search-forward
5908 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5909 nil t) ;; on purpose, we look further than LIMIT
5910 (setq end (min (point-max) (match-end 0))
5911 end1 (min (point-max) (1- (match-beginning 0))))
5912 (setq block-end (match-beginning 0))
5913 (when quoting
5914 (org-remove-flyspell-overlays-in beg1 end1)
5915 (remove-text-properties beg end
5916 '(display t invisible t intangible t)))
5917 (add-text-properties
5918 beg end '(font-lock-fontified t font-lock-multiline t))
5919 (add-text-properties beg beg1 '(face org-meta-line))
5920 (org-remove-flyspell-overlays-in beg beg1)
5921 (add-text-properties ; For end_src
5922 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5923 (org-remove-flyspell-overlays-in end1 end)
5924 (cond
5925 ((and lang (not (string= lang "")) org-src-fontify-natively)
5926 (org-src-font-lock-fontify-block lang block-start block-end)
5927 (add-text-properties beg1 block-end '(src-block t)))
5928 (quoting
5929 (add-text-properties beg1 (min (point-max) (1+ end1))
5930 (list 'face
5931 (list :inherit
5932 (let ((face-name
5933 (intern (format "org-block-%s" lang))))
5934 (append (and (facep face-name) (list face-name))
5935 '(org-block))))))) ; end of source block
5936 ((not org-fontify-quote-and-verse-blocks))
5937 ((string= block-type "quote")
5938 (add-face-text-property
5939 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5940 ((string= block-type "verse")
5941 (add-face-text-property
5942 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5943 (add-text-properties beg beg1 '(face org-block-begin-line))
5944 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5945 '(face org-block-end-line))
5947 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5948 (org-remove-flyspell-overlays-in
5949 (match-beginning 0)
5950 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5951 (add-text-properties
5952 beg (match-end 3)
5953 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5954 '(font-lock-fontified t invisible t)
5955 '(font-lock-fontified t face org-document-info-keyword)))
5956 (add-text-properties
5957 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5958 (if (string-equal dc1 "+title:")
5959 '(font-lock-fontified t face org-document-title)
5960 '(font-lock-fontified t face org-document-info))))
5961 ((string-prefix-p "+caption" dc1)
5962 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5963 (remove-text-properties (match-beginning 0) (match-end 0)
5964 '(display t invisible t intangible t))
5965 ;; Handle short captions.
5966 (save-excursion
5967 (beginning-of-line)
5968 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
5969 (add-text-properties (line-beginning-position) (match-end 1)
5970 '(font-lock-fontified t face org-meta-line))
5971 (add-text-properties (match-end 0) (line-end-position)
5972 '(font-lock-fontified t face org-block))
5974 ((member dc3 '(" " ""))
5975 (org-remove-flyspell-overlays-in beg (match-end 0))
5976 (add-text-properties
5977 beg (match-end 0)
5978 '(font-lock-fontified t face font-lock-comment-face)))
5979 (t ;; just any other in-buffer setting, but not indented
5980 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5981 (remove-text-properties (match-beginning 0) (match-end 0)
5982 '(display t invisible t intangible t))
5983 (add-text-properties beg (match-end 0)
5984 '(font-lock-fontified t face org-meta-line))
5985 t))))))
5987 (defun org-fontify-drawers (limit)
5988 "Fontify drawers."
5989 (when (re-search-forward org-drawer-regexp limit t)
5990 (add-text-properties
5991 (match-beginning 0) (match-end 0)
5992 '(font-lock-fontified t face org-special-keyword))
5993 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (defun org-fontify-macros (limit)
5997 "Fontify macros."
5998 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5999 (add-text-properties
6000 (match-beginning 0) (match-end 0)
6001 '(font-lock-fontified t face org-macro))
6002 (when org-hide-macro-markers
6003 (add-text-properties (match-end 2) (match-beginning 2)
6004 '(invisible t))
6005 (add-text-properties (match-beginning 1) (match-end 1)
6006 '(invisible t)))
6007 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6010 (defun org-activate-footnote-links (limit)
6011 "Add text properties for footnotes."
6012 (let ((fn (org-footnote-next-reference-or-definition limit)))
6013 (when fn
6014 (let* ((beg (nth 1 fn))
6015 (end (nth 2 fn))
6016 (label (car fn))
6017 (referencep (/= (line-beginning-position) beg)))
6018 (when (and referencep (nth 3 fn))
6019 (save-excursion
6020 (goto-char beg)
6021 (search-forward (or label "fn:"))
6022 (org-remove-flyspell-overlays-in beg (match-end 0))))
6023 (add-text-properties beg end
6024 (list 'mouse-face 'highlight
6025 'keymap org-mouse-map
6026 'help-echo
6027 (if referencep "Footnote reference"
6028 "Footnote definition")
6029 'font-lock-fontified t
6030 'font-lock-multiline t
6031 'face 'org-footnote))))))
6033 (defun org-activate-dates (limit)
6034 "Add text properties for dates."
6035 (when (and (re-search-forward org-tsr-regexp-both limit t)
6036 (not (equal (char-before (match-beginning 0)) 91)))
6037 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6038 (add-text-properties (match-beginning 0) (match-end 0)
6039 (list 'mouse-face 'highlight
6040 'keymap org-mouse-map))
6041 (org-rear-nonsticky-at (match-end 0))
6042 (when org-display-custom-times
6043 ;; If it's a date range, activate custom time for second date.
6044 (when (match-end 3)
6045 (org-display-custom-time (match-beginning 3) (match-end 3)))
6046 (org-display-custom-time (match-beginning 1) (match-end 1)))
6049 (defvar-local org-target-link-regexp nil
6050 "Regular expression matching radio targets in plain text.")
6052 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6053 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6054 border border border))
6055 "Regular expression matching a link target.")
6057 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6058 "Regular expression matching a radio target.")
6060 (defconst org-any-target-regexp
6061 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6062 "Regular expression matching any target.")
6064 (defun org-activate-target-links (limit)
6065 "Add text properties for target matches."
6066 (when org-target-link-regexp
6067 (let ((case-fold-search t))
6068 (when (re-search-forward org-target-link-regexp limit t)
6069 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6070 (add-text-properties (match-beginning 1) (match-end 1)
6071 (list 'mouse-face 'highlight
6072 'keymap org-mouse-map
6073 'help-echo "Radio target link"
6074 'org-linked-text t))
6075 (org-rear-nonsticky-at (match-end 1))
6076 t))))
6078 (defun org-update-radio-target-regexp ()
6079 "Find all radio targets in this file and update the regular expression.
6080 Also refresh fontification if needed."
6081 (interactive)
6082 (let ((old-regexp org-target-link-regexp)
6083 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6084 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6085 (targets
6086 (org-with-wide-buffer
6087 (goto-char (point-min))
6088 (let (rtn)
6089 (while (re-search-forward org-radio-target-regexp nil t)
6090 ;; Make sure point is really within the object.
6091 (backward-char)
6092 (let ((obj (org-element-context)))
6093 (when (eq (org-element-type obj) 'radio-target)
6094 (cl-pushnew (org-element-property :value obj) rtn
6095 :test #'equal))))
6096 rtn))))
6097 (setq org-target-link-regexp
6098 (and targets
6099 (concat before-re
6100 (mapconcat
6101 (lambda (x)
6102 (replace-regexp-in-string
6103 " +" "\\s-+" (regexp-quote x) t t))
6104 targets
6105 "\\|")
6106 after-re)))
6107 (unless (equal old-regexp org-target-link-regexp)
6108 ;; Clean-up cache.
6109 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6110 ((not org-target-link-regexp) old-regexp)
6112 (concat before-re
6113 (mapconcat
6114 (lambda (re)
6115 (substring re (length before-re)
6116 (- (length after-re))))
6117 (list old-regexp org-target-link-regexp)
6118 "\\|")
6119 after-re)))))
6120 (org-with-wide-buffer
6121 (goto-char (point-min))
6122 (while (re-search-forward regexp nil t)
6123 (org-element-cache-refresh (match-beginning 1)))))
6124 ;; Re fontify buffer.
6125 (when (memq 'radio org-highlight-links)
6126 (org-restart-font-lock)))))
6128 (defvar org-latex-and-related-regexp nil
6129 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6131 (defun org-compute-latex-and-related-regexp ()
6132 "Compute regular expression for LaTeX, entities and sub/superscript.
6133 Result depends on variable `org-highlight-latex-and-related'."
6134 (setq-local
6135 org-latex-and-related-regexp
6136 (let* ((re-sub
6137 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6138 ((eq org-use-sub-superscripts '{})
6139 (list org-match-substring-with-braces-regexp))
6140 (org-use-sub-superscripts (list org-match-substring-regexp))))
6141 (re-latex
6142 (when (memq 'latex org-highlight-latex-and-related)
6143 (let ((matchers (plist-get org-format-latex-options :matchers)))
6144 (delq nil
6145 (mapcar (lambda (x)
6146 (and (member (car x) matchers) (nth 1 x)))
6147 org-latex-regexps)))))
6148 (re-entities
6149 (when (memq 'entities org-highlight-latex-and-related)
6150 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6151 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6153 (defun org-do-latex-and-related (limit)
6154 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6155 LIMIT bounds the search for syntax to highlight. Stop at first
6156 highlighted object, if any. Return t if some highlighting was
6157 done, nil otherwise."
6158 (when (org-string-nw-p org-latex-and-related-regexp)
6159 (catch 'found
6160 (while (re-search-forward org-latex-and-related-regexp limit t)
6161 (unless
6162 (cl-some
6163 (lambda (f)
6164 (memq f '(org-code org-verbatim underline org-special-keyword)))
6165 (save-excursion
6166 (goto-char (1+ (match-beginning 0)))
6167 (face-at-point nil t)))
6168 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6169 '(?_ ?^))
6171 0)))
6172 (font-lock-prepend-text-property
6173 (+ offset (match-beginning 0)) (match-end 0)
6174 'face 'org-latex-and-related)
6175 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6176 '(font-lock-multiline t)))
6177 (throw 'found t)))
6178 nil)))
6180 (defun org-restart-font-lock ()
6181 "Restart `font-lock-mode', to force refontification."
6182 (when (and (boundp 'font-lock-mode) font-lock-mode)
6183 (font-lock-mode -1)
6184 (font-lock-mode 1)))
6186 (defun org-activate-tags (limit)
6187 (when (re-search-forward
6188 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6189 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6190 (add-text-properties (match-beginning 1) (match-end 1)
6191 (list 'mouse-face 'highlight
6192 'keymap org-mouse-map))
6193 (org-rear-nonsticky-at (match-end 1))
6196 (defun org-outline-level ()
6197 "Compute the outline level of the heading at point.
6199 If this is called at a normal headline, the level is the number
6200 of stars. Use `org-reduced-level' to remove the effect of
6201 `org-odd-levels'. Unlike to `org-current-level', this function
6202 takes into consideration inlinetasks."
6203 (org-with-wide-buffer
6204 (end-of-line)
6205 (if (re-search-backward org-outline-regexp-bol nil t)
6206 (1- (- (match-end 0) (match-beginning 0)))
6207 0)))
6209 (defvar org-font-lock-keywords nil)
6211 (defsubst org-re-property (property &optional literal allow-null value)
6212 "Return a regexp matching a PROPERTY line.
6214 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6215 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6216 non-nil, match properties even without a value.
6218 Match group 3 is set to the value when it exists. If there is no
6219 value and ALLOW-NULL is non-nil, it is set to the empty string.
6221 With optional argument VALUE, match only property lines with
6222 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6223 unless LITERAL is non-nil."
6224 (concat
6225 "^\\(?4:[ \t]*\\)"
6226 (format "\\(?1::\\(?2:%s\\):\\)"
6227 (if literal property (regexp-quote property)))
6228 (cond (value
6229 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6230 (if literal value (regexp-quote value))))
6231 (allow-null
6232 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6234 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6236 (defconst org-property-re
6237 (org-re-property "\\S-+" 'literal t)
6238 "Regular expression matching a property line.
6239 There are four matching groups:
6240 1: :PROPKEY: including the leading and trailing colon,
6241 2: PROPKEY without the leading and trailing colon,
6242 3: PROPVAL without leading or trailing spaces,
6243 4: the indentation of the current line,
6244 5: trailing whitespace.")
6246 (defvar org-font-lock-hook nil
6247 "Functions to be called for special font lock stuff.")
6249 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6251 (defvar org-font-lock-set-keywords-hook nil
6252 "Functions that can manipulate `org-font-lock-extra-keywords'.
6253 This is called after `org-font-lock-extra-keywords' is defined, but before
6254 it is installed to be used by font lock. This can be useful if something
6255 needs to be inserted at a specific position in the font-lock sequence.")
6257 (defun org-font-lock-hook (limit)
6258 "Run `org-font-lock-hook' within LIMIT."
6259 (run-hook-with-args 'org-font-lock-hook limit))
6261 (defun org-set-font-lock-defaults ()
6262 "Set font lock defaults for the current buffer."
6263 (let* ((em org-fontify-emphasized-text)
6264 (lk org-highlight-links)
6265 (org-font-lock-extra-keywords
6266 (list
6267 ;; Call the hook
6268 '(org-font-lock-hook)
6269 ;; Headlines
6270 `(,(if org-fontify-whole-heading-line
6271 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6272 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6273 (1 (org-get-level-face 1))
6274 (2 (org-get-level-face 2))
6275 (3 (org-get-level-face 3)))
6276 ;; Table lines
6277 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6278 (1 'org-table t))
6279 ;; Table internals
6280 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6281 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6282 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6283 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6284 ;; Drawers
6285 '(org-fontify-drawers)
6286 ;; Properties
6287 (list org-property-re
6288 '(1 'org-special-keyword t)
6289 '(3 'org-property-value t))
6290 ;; Link related fontification.
6291 '(org-activate-links)
6292 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6293 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6294 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6295 (when (memq 'footnote lk) '(org-activate-footnote-links))
6296 ;; Targets.
6297 (list org-any-target-regexp '(0 'org-target t))
6298 ;; Diary sexps.
6299 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6300 ;; Macro
6301 '(org-fontify-macros)
6302 ;; TODO keyword
6303 (list (format org-heading-keyword-regexp-format
6304 org-todo-regexp)
6305 '(2 (org-get-todo-face 2) t))
6306 ;; DONE
6307 (if org-fontify-done-headline
6308 (list (format org-heading-keyword-regexp-format
6309 (concat
6310 "\\(?:"
6311 (mapconcat 'regexp-quote org-done-keywords "\\|")
6312 "\\)"))
6313 '(2 'org-headline-done t))
6314 nil)
6315 ;; Priorities
6316 '(org-font-lock-add-priority-faces)
6317 ;; Tags
6318 '(org-font-lock-add-tag-faces)
6319 ;; Tags groups
6320 (when (and org-group-tags org-tag-groups-alist)
6321 (list (concat org-outline-regexp-bol ".+\\(:"
6322 (regexp-opt (mapcar 'car org-tag-groups-alist))
6323 ":\\).*$")
6324 '(1 'org-tag-group prepend)))
6325 ;; Special keywords
6326 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6327 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6328 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6329 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6330 ;; Emphasis
6331 (when em '(org-do-emphasis-faces))
6332 ;; Checkboxes
6333 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6334 1 'org-checkbox prepend)
6335 (when (cdr (assq 'checkbox org-list-automatic-rules))
6336 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6337 (0 (org-get-checkbox-statistics-face) t)))
6338 ;; Description list items
6339 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6340 1 'org-list-dt prepend)
6341 ;; ARCHIVEd headings
6342 (list (concat
6343 org-outline-regexp-bol
6344 "\\(.*:" org-archive-tag ":.*\\)")
6345 '(1 'org-archived prepend))
6346 ;; Specials
6347 '(org-do-latex-and-related)
6348 '(org-fontify-entities)
6349 '(org-raise-scripts)
6350 ;; Code
6351 '(org-activate-code (1 'org-code t))
6352 ;; COMMENT
6353 (list (format
6354 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6355 org-todo-regexp
6356 org-comment-string)
6357 '(9 'org-special-keyword t))
6358 ;; Blocks and meta lines
6359 '(org-fontify-meta-lines-and-blocks))))
6360 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6361 (run-hooks 'org-font-lock-set-keywords-hook)
6362 ;; Now set the full font-lock-keywords
6363 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6364 (setq-local font-lock-defaults
6365 '(org-font-lock-keywords t nil nil backward-paragraph))
6366 (kill-local-variable 'font-lock-keywords)
6367 nil))
6369 (defun org-toggle-pretty-entities ()
6370 "Toggle the composition display of entities as UTF8 characters."
6371 (interactive)
6372 (setq-local org-pretty-entities (not org-pretty-entities))
6373 (org-restart-font-lock)
6374 (if org-pretty-entities
6375 (message "Entities are now displayed as UTF8 characters")
6376 (save-restriction
6377 (widen)
6378 (decompose-region (point-min) (point-max))
6379 (message "Entities are now displayed as plain text"))))
6381 (defvar-local org-custom-properties-overlays nil
6382 "List of overlays used for custom properties.")
6384 (defun org-toggle-custom-properties-visibility ()
6385 "Display or hide properties in `org-custom-properties'."
6386 (interactive)
6387 (if org-custom-properties-overlays
6388 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6389 (setq org-custom-properties-overlays nil))
6390 (when org-custom-properties
6391 (org-with-wide-buffer
6392 (goto-char (point-min))
6393 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6394 (while (re-search-forward regexp nil t)
6395 (let ((end (cdr (save-match-data (org-get-property-block)))))
6396 (when (and end (< (point) end))
6397 ;; Hide first custom property in current drawer.
6398 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6399 (overlay-put o 'invisible t)
6400 (overlay-put o 'org-custom-property t)
6401 (push o org-custom-properties-overlays))
6402 ;; Hide additional custom properties in the same drawer.
6403 (while (re-search-forward regexp end t)
6404 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6405 (overlay-put o 'invisible t)
6406 (overlay-put o 'org-custom-property t)
6407 (push o org-custom-properties-overlays)))))
6408 ;; Each entry is limited to a single property drawer.
6409 (outline-next-heading)))))))
6411 (defun org-fontify-entities (limit)
6412 "Find an entity to fontify."
6413 (let (ee)
6414 (when org-pretty-entities
6415 (catch 'match
6416 ;; "\_ "-family is left out on purpose. Only the first one,
6417 ;; i.e., "\_ ", could be fontified anyway, and it would be
6418 ;; confusing when adding a second white space character.
6419 (while (re-search-forward
6420 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6421 limit t)
6422 (when (and (not (org-at-comment-p))
6423 (setq ee (org-entity-get (match-string 1)))
6424 (= (length (nth 6 ee)) 1))
6425 (let* ((end (if (equal (match-string 2) "{}")
6426 (match-end 2)
6427 (match-end 1))))
6428 (add-text-properties
6429 (match-beginning 0) end
6430 (list 'font-lock-fontified t))
6431 (compose-region (match-beginning 0) end
6432 (nth 6 ee) nil)
6433 (backward-char 1)
6434 (throw 'match t))))
6435 nil))))
6437 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6438 "Fontify string S like in Org mode."
6439 (with-temp-buffer
6440 (insert s)
6441 (let ((org-odd-levels-only odd-levels))
6442 (org-mode)
6443 (org-font-lock-ensure)
6444 (buffer-string))))
6446 (defvar org-m nil)
6447 (defvar org-l nil)
6448 (defvar org-f nil)
6449 (defun org-get-level-face (n)
6450 "Get the right face for match N in font-lock matching of headlines."
6451 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6452 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6453 (if org-cycle-level-faces
6454 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6455 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6456 (cond
6457 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6458 ((eq n 2) org-f)
6459 (t (unless org-level-color-stars-only org-f))))
6461 (defun org-face-from-face-or-color (context inherit face-or-color)
6462 "Create a face list that inherits INHERIT, but sets the foreground color.
6463 When FACE-OR-COLOR is not a string, just return it."
6464 (if (stringp face-or-color)
6465 (list :inherit inherit
6466 (cdr (assoc context org-faces-easy-properties))
6467 face-or-color)
6468 face-or-color))
6470 (defun org-get-todo-face (kwd)
6471 "Get the right face for a TODO keyword KWD.
6472 If KWD is a number, get the corresponding match group."
6473 (when (numberp kwd) (setq kwd (match-string kwd)))
6474 (or (org-face-from-face-or-color
6475 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6476 (and (member kwd org-done-keywords) 'org-done)
6477 'org-todo))
6479 (defun org-get-priority-face (priority)
6480 "Get the right face for PRIORITY.
6481 PRIORITY is a character."
6482 (or (org-face-from-face-or-color
6483 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6484 'org-priority))
6486 (defun org-get-tag-face (tag)
6487 "Get the right face for TAG.
6488 If TAG is a number, get the corresponding match group."
6489 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6490 (or (org-face-from-face-or-color
6491 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6492 'org-tag)))
6494 (defun org-font-lock-add-priority-faces (limit)
6495 "Add the special priority faces."
6496 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6497 (add-text-properties
6498 (match-beginning 1) (match-end 1)
6499 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6500 'font-lock-fontified t))))
6502 (defun org-font-lock-add-tag-faces (limit)
6503 "Add the special tag faces."
6504 (when (and org-tag-faces org-tags-special-faces-re)
6505 (while (re-search-forward org-tags-special-faces-re limit t)
6506 (add-text-properties (match-beginning 1) (match-end 1)
6507 (list 'face (org-get-tag-face 1)
6508 'font-lock-fontified t))
6509 (backward-char 1))))
6511 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6512 "Remove fontification and activation overlays from links."
6513 (font-lock-default-unfontify-region beg end)
6514 (let* ((buffer-undo-list t)
6515 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6516 (inhibit-modification-hooks t)
6517 deactivate-mark buffer-file-name buffer-file-truename)
6518 (decompose-region beg end)
6519 (remove-text-properties beg end
6520 '(mouse-face t keymap t org-linked-text t
6521 invisible t intangible t
6522 org-emphasis t))
6523 (org-remove-font-lock-display-properties beg end)))
6525 (defconst org-script-display '(((raise -0.3) (height 0.7))
6526 ((raise 0.3) (height 0.7))
6527 ((raise -0.5))
6528 ((raise 0.5)))
6529 "Display properties for showing superscripts and subscripts.")
6531 (defun org-remove-font-lock-display-properties (beg end)
6532 "Remove specific display properties that have been added by font lock.
6533 The will remove the raise properties that are used to show superscripts
6534 and subscripts."
6535 (let (next prop)
6536 (while (< beg end)
6537 (setq next (next-single-property-change beg 'display nil end)
6538 prop (get-text-property beg 'display))
6539 (when (member prop org-script-display)
6540 (put-text-property beg next 'display nil))
6541 (setq beg next))))
6543 (defun org-raise-scripts (limit)
6544 "Add raise properties to sub/superscripts."
6545 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6546 (re-search-forward
6547 (if (eq org-use-sub-superscripts t)
6548 org-match-substring-regexp
6549 org-match-substring-with-braces-regexp)
6550 limit t))
6551 (let* ((pos (point)) table-p comment-p
6552 (mpos (match-beginning 3))
6553 (emph-p (get-text-property mpos 'org-emphasis))
6554 (link-p (get-text-property mpos 'mouse-face))
6555 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6556 (goto-char (point-at-bol))
6557 (setq table-p (looking-at-p org-table-dataline-regexp)
6558 comment-p (looking-at-p "^[ \t]*#[ +]"))
6559 (goto-char pos)
6560 ;; Handle a_b^c
6561 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6562 (unless (or comment-p emph-p link-p keyw-p)
6563 (put-text-property (match-beginning 3) (match-end 0)
6564 'display
6565 (if (equal (char-after (match-beginning 2)) ?^)
6566 (nth (if table-p 3 1) org-script-display)
6567 (nth (if table-p 2 0) org-script-display)))
6568 (add-text-properties (match-beginning 2) (match-end 2)
6569 (list 'invisible t))
6570 (when (and (eq (char-after (match-beginning 3)) ?{)
6571 (eq (char-before (match-end 3)) ?}))
6572 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6573 (list 'invisible t))
6574 (add-text-properties (1- (match-end 3)) (match-end 3)
6575 (list 'invisible t))))
6576 t)))
6578 ;;;; Visibility cycling, including org-goto and indirect buffer
6580 ;;; Cycling
6582 (defvar-local org-cycle-global-status nil)
6583 (put 'org-cycle-global-status 'org-state t)
6584 (defvar-local org-cycle-subtree-status nil)
6585 (put 'org-cycle-subtree-status 'org-state t)
6587 (defvar org-inlinetask-min-level)
6589 (defun org-unlogged-message (&rest args)
6590 "Display a message, but avoid logging it in the *Messages* buffer."
6591 (let ((message-log-max nil))
6592 (apply 'message args)))
6594 ;;;###autoload
6595 (defun org-cycle (&optional arg)
6596 "TAB-action and visibility cycling for Org mode.
6598 This is the command invoked in Org mode by the `TAB' key. Its main
6599 purpose is outline visibility cycling, but it also invokes other actions
6600 in special contexts.
6602 When this function is called with a `\\[universal-argument]' prefix, rotate \
6603 the entire
6604 buffer through 3 states (global cycling)
6605 1. OVERVIEW: Show only top-level headlines.
6606 2. CONTENTS: Show all headlines of all levels, but no body text.
6607 3. SHOW ALL: Show everything.
6609 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6610 switch to the startup visibility,
6611 determined by the variable `org-startup-folded', and by any VISIBILITY
6612 properties in the buffer.
6614 With a `\\[universal-argument] \\[universal-argument] \
6615 \\[universal-argument]' prefix argument, show the entire buffer, including
6616 any drawers.
6618 When inside a table, re-align the table and move to the next field.
6620 When point is at the beginning of a headline, rotate the subtree started
6621 by this line through 3 different states (local cycling)
6622 1. FOLDED: Only the main headline is shown.
6623 2. CHILDREN: The main headline and the direct children are shown.
6624 From this state, you can move to one of the children
6625 and zoom in further.
6626 3. SUBTREE: Show the entire subtree, including body text.
6627 If there is no subtree, switch directly from CHILDREN to FOLDED.
6629 When point is at the beginning of an empty headline and the variable
6630 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6631 of the headline by demoting and promoting it to likely levels. This
6632 speeds up creation document structure by pressing `TAB' once or several
6633 times right after creating a new headline.
6635 When there is a numeric prefix, go up to a heading with level ARG, do
6636 a `show-subtree' and return to the previous cursor position. If ARG
6637 is negative, go up that many levels.
6639 When point is not at the beginning of a headline, execute the global
6640 binding for `TAB', which is re-indenting the line. See the option
6641 `org-cycle-emulate-tab' for details.
6643 As a special case, if point is at the beginning of the buffer and there is
6644 no headline in line 1, this function will act as if called with prefix arg
6645 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6646 prefix arg, but only
6647 if the variable `org-cycle-global-at-bob' is t."
6648 (interactive "P")
6649 (org-load-modules-maybe)
6650 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6651 (and org-cycle-level-after-item/entry-creation
6652 (or (org-cycle-level)
6653 (org-cycle-item-indentation))))
6654 (let* ((limit-level
6655 (or org-cycle-max-level
6656 (and (boundp 'org-inlinetask-min-level)
6657 org-inlinetask-min-level
6658 (1- org-inlinetask-min-level))))
6659 (nstars (and limit-level
6660 (if org-odd-levels-only
6661 (and limit-level (1- (* limit-level 2)))
6662 limit-level)))
6663 (org-outline-regexp
6664 (if (not (derived-mode-p 'org-mode))
6665 outline-regexp
6666 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6667 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6668 (not (looking-at org-outline-regexp))))
6669 (org-cycle-hook
6670 (if bob-special
6671 (delq 'org-optimize-window-after-visibility-change
6672 (copy-sequence org-cycle-hook))
6673 org-cycle-hook))
6674 (pos (point)))
6676 (cond
6678 ((equal arg '(16))
6679 (setq last-command 'dummy)
6680 (org-set-startup-visibility)
6681 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6683 ((equal arg '(64))
6684 (outline-show-all)
6685 (org-unlogged-message "Entire buffer visible, including drawers"))
6687 ((equal arg '(4)) (org-cycle-internal-global))
6689 ;; Try hiding block at point.
6690 ((org-hide-block-toggle-maybe))
6692 ;; Try cdlatex TAB completion
6693 ((org-try-cdlatex-tab))
6695 ;; Table: enter it or move to the next field.
6696 ((org-at-table-p 'any)
6697 (if (org-at-table.el-p)
6698 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6699 Use `\\[org-edit-special]' to edit table.el tables"))
6700 (if arg (org-table-edit-field t)
6701 (org-table-justify-field-maybe)
6702 (call-interactively 'org-table-next-field))))
6704 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6706 ;; Global cycling: delegate to `org-cycle-internal-global'.
6707 (bob-special (org-cycle-internal-global))
6709 ;; Drawers: delegate to `org-flag-drawer'.
6710 ((save-excursion
6711 (beginning-of-line 1)
6712 (looking-at org-drawer-regexp))
6713 (org-flag-drawer ; toggle block visibility
6714 (not (get-char-property (match-end 0) 'invisible))))
6716 ;; Show-subtree, ARG levels up from here.
6717 ((integerp arg)
6718 (save-excursion
6719 (org-back-to-heading)
6720 (outline-up-heading (if (< arg 0) (- arg)
6721 (- (funcall outline-level) arg)))
6722 (org-show-subtree)))
6724 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6725 ((and (featurep 'org-inlinetask)
6726 (org-inlinetask-at-task-p)
6727 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6728 (org-inlinetask-toggle-visibility))
6730 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6731 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6732 (save-excursion (move-beginning-of-line 1)
6733 (looking-at org-outline-regexp)))
6734 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6735 (org-cycle-internal-local))
6737 ;; From there: TAB emulation and template completion.
6738 (buffer-read-only (org-back-to-heading))
6740 ((run-hook-with-args-until-success
6741 'org-tab-after-check-for-cycling-hook))
6743 ((org-try-structure-completion))
6745 ((run-hook-with-args-until-success
6746 'org-tab-before-tab-emulation-hook))
6748 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6749 (or (not (bolp))
6750 (not (looking-at org-outline-regexp))))
6751 (call-interactively (global-key-binding "\t")))
6753 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6754 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6755 (or (and (eq org-cycle-emulate-tab 'white)
6756 (= (match-end 0) (point-at-eol)))
6757 (and (eq org-cycle-emulate-tab 'whitestart)
6758 (>= (match-end 0) pos))))
6760 (eq org-cycle-emulate-tab t))
6761 (call-interactively (global-key-binding "\t")))
6763 (t (save-excursion
6764 (org-back-to-heading)
6765 (org-cycle)))))))
6767 (defun org-cycle-internal-global ()
6768 "Do the global cycling action."
6769 ;; Hack to avoid display of messages for .org attachments in Gnus
6770 (let ((ga (string-match "\\*fontification" (buffer-name))))
6771 (cond
6772 ((and (eq last-command this-command)
6773 (eq org-cycle-global-status 'overview))
6774 ;; We just created the overview - now do table of contents
6775 ;; This can be slow in very large buffers, so indicate action
6776 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6777 (unless ga (org-unlogged-message "CONTENTS..."))
6778 (org-content)
6779 (unless ga (org-unlogged-message "CONTENTS...done"))
6780 (setq org-cycle-global-status 'contents)
6781 (run-hook-with-args 'org-cycle-hook 'contents))
6783 ((and (eq last-command this-command)
6784 (eq org-cycle-global-status 'contents))
6785 ;; We just showed the table of contents - now show everything
6786 (run-hook-with-args 'org-pre-cycle-hook 'all)
6787 (outline-show-all)
6788 (unless ga (org-unlogged-message "SHOW ALL"))
6789 (setq org-cycle-global-status 'all)
6790 (run-hook-with-args 'org-cycle-hook 'all))
6793 ;; Default action: go to overview
6794 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6795 (org-overview)
6796 (unless ga (org-unlogged-message "OVERVIEW"))
6797 (setq org-cycle-global-status 'overview)
6798 (run-hook-with-args 'org-cycle-hook 'overview)))))
6800 (defvar org-called-with-limited-levels nil
6801 "Non-nil when `org-with-limited-levels' is currently active.")
6803 (defun org-cycle-internal-local ()
6804 "Do the local cycling action."
6805 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6806 ;; First, determine end of headline (EOH), end of subtree or item
6807 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6808 (save-excursion
6809 (if (org-at-item-p)
6810 (progn
6811 (beginning-of-line)
6812 (setq struct (org-list-struct))
6813 (setq eoh (point-at-eol))
6814 (setq eos (org-list-get-item-end-before-blank (point) struct))
6815 (setq has-children (org-list-has-child-p (point) struct)))
6816 (org-back-to-heading)
6817 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6818 (setq eos (save-excursion (org-end-of-subtree t t)
6819 (when (bolp) (backward-char)) (point)))
6820 (setq has-children
6821 (or (save-excursion
6822 (let ((level (funcall outline-level)))
6823 (outline-next-heading)
6824 (and (org-at-heading-p t)
6825 (> (funcall outline-level) level))))
6826 (save-excursion
6827 (org-list-search-forward (org-item-beginning-re) eos t)))))
6828 ;; Determine end invisible part of buffer (EOL)
6829 (beginning-of-line 2)
6830 (while (and (not (eobp)) ;This is like `next-line'.
6831 (get-char-property (1- (point)) 'invisible))
6832 (goto-char (next-single-char-property-change (point) 'invisible))
6833 (and (eolp) (beginning-of-line 2)))
6834 (setq eol (point)))
6835 ;; Find out what to do next and set `this-command'
6836 (cond
6837 ((= eos eoh)
6838 ;; Nothing is hidden behind this heading
6839 (unless (org-before-first-heading-p)
6840 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6841 (org-unlogged-message "EMPTY ENTRY")
6842 (setq org-cycle-subtree-status nil)
6843 (save-excursion
6844 (goto-char eos)
6845 (outline-next-heading)
6846 (when (org-invisible-p) (org-flag-heading nil))))
6847 ((and (or (>= eol eos)
6848 (not (string-match "\\S-" (buffer-substring eol eos))))
6849 (or has-children
6850 (not (setq children-skipped
6851 org-cycle-skip-children-state-if-no-children))))
6852 ;; Entire subtree is hidden in one line: children view
6853 (unless (org-before-first-heading-p)
6854 (run-hook-with-args 'org-pre-cycle-hook 'children))
6855 (if (org-at-item-p)
6856 (org-list-set-item-visibility (point-at-bol) struct 'children)
6857 (org-show-entry)
6858 (org-with-limited-levels (org-show-children))
6859 ;; FIXME: This slows down the func way too much.
6860 ;; How keep drawers hidden in subtree anyway?
6861 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6862 ;; (org-cycle-hide-drawers 'subtree))
6864 ;; Fold every list in subtree to top-level items.
6865 (when (eq org-cycle-include-plain-lists 'integrate)
6866 (save-excursion
6867 (org-back-to-heading)
6868 (while (org-list-search-forward (org-item-beginning-re) eos t)
6869 (beginning-of-line 1)
6870 (let* ((struct (org-list-struct))
6871 (prevs (org-list-prevs-alist struct))
6872 (end (org-list-get-bottom-point struct)))
6873 (dolist (e (org-list-get-all-items (point) struct prevs))
6874 (org-list-set-item-visibility e struct 'folded))
6875 (goto-char (if (< end eos) end eos)))))))
6876 (org-unlogged-message "CHILDREN")
6877 (save-excursion
6878 (goto-char eos)
6879 (outline-next-heading)
6880 (when (org-invisible-p) (org-flag-heading nil)))
6881 (setq org-cycle-subtree-status 'children)
6882 (unless (org-before-first-heading-p)
6883 (run-hook-with-args 'org-cycle-hook 'children)))
6884 ((or children-skipped
6885 (and (eq last-command this-command)
6886 (eq org-cycle-subtree-status 'children)))
6887 ;; We just showed the children, or no children are there,
6888 ;; now show everything.
6889 (unless (org-before-first-heading-p)
6890 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6891 (outline-flag-region eoh eos nil)
6892 (org-unlogged-message
6893 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6894 (setq org-cycle-subtree-status 'subtree)
6895 (unless (org-before-first-heading-p)
6896 (run-hook-with-args 'org-cycle-hook 'subtree)))
6898 ;; Default action: hide the subtree.
6899 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6900 (outline-flag-region eoh eos t)
6901 (org-unlogged-message "FOLDED")
6902 (setq org-cycle-subtree-status 'folded)
6903 (unless (org-before-first-heading-p)
6904 (run-hook-with-args 'org-cycle-hook 'folded))))))
6906 ;;;###autoload
6907 (defun org-global-cycle (&optional arg)
6908 "Cycle the global visibility. For details see `org-cycle'.
6909 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6910 With a numeric prefix, show all headlines up to that level."
6911 (interactive "P")
6912 (let ((org-cycle-include-plain-lists
6913 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6914 (cond
6915 ((integerp arg)
6916 (outline-show-all)
6917 (outline-hide-sublevels arg)
6918 (setq org-cycle-global-status 'contents))
6919 ((equal arg '(4))
6920 (org-set-startup-visibility)
6921 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6923 (org-cycle '(4))))))
6925 (defun org-set-startup-visibility ()
6926 "Set the visibility required by startup options and properties."
6927 (cond
6928 ((eq org-startup-folded t)
6929 (org-overview))
6930 ((eq org-startup-folded 'content)
6931 (org-content))
6932 ((or (eq org-startup-folded 'showeverything)
6933 (eq org-startup-folded nil))
6934 (outline-show-all)))
6935 (unless (eq org-startup-folded 'showeverything)
6936 (when org-hide-block-startup (org-hide-block-all))
6937 (org-set-visibility-according-to-property 'no-cleanup)
6938 (org-cycle-hide-archived-subtrees 'all)
6939 (org-cycle-hide-drawers 'all)
6940 (org-cycle-show-empty-lines t)))
6942 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6943 "Switch subtree visibilities according to :VISIBILITY: property."
6944 (interactive)
6945 (org-with-wide-buffer
6946 (goto-char (point-min))
6947 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6948 (if (not (org-at-property-p)) (outline-next-heading)
6949 (let ((state (match-string 3)))
6950 (save-excursion
6951 (org-back-to-heading t)
6952 (outline-hide-subtree)
6953 (org-reveal)
6954 (cond
6955 ((equal state "folded")
6956 (outline-hide-subtree))
6957 ((equal state "children")
6958 (org-show-hidden-entry)
6959 (org-show-children))
6960 ((equal state "content")
6961 (save-excursion
6962 (save-restriction
6963 (org-narrow-to-subtree)
6964 (org-content))))
6965 ((member state '("all" "showall"))
6966 (outline-show-subtree)))))))
6967 (unless no-cleanup
6968 (org-cycle-hide-archived-subtrees 'all)
6969 (org-cycle-hide-drawers 'all)
6970 (org-cycle-show-empty-lines 'all))))
6972 ;; This function uses outline-regexp instead of the more fundamental
6973 ;; org-outline-regexp so that org-cycle-global works outside of Org
6974 ;; buffers, where outline-regexp is needed.
6975 (defun org-overview ()
6976 "Switch to overview mode, showing only top-level headlines.
6977 This shows all headlines with a level equal or greater than the level
6978 of the first headline in the buffer. This is important, because if the
6979 first headline is not level one, then (hide-sublevels 1) gives confusing
6980 results."
6981 (interactive)
6982 (save-excursion
6983 (let ((level
6984 (save-excursion
6985 (goto-char (point-min))
6986 (when (re-search-forward (concat "^" outline-regexp) nil t)
6987 (goto-char (match-beginning 0))
6988 (funcall outline-level)))))
6989 (and level (outline-hide-sublevels level)))))
6991 (defun org-content (&optional arg)
6992 "Show all headlines in the buffer, like a table of contents.
6993 With numerical argument N, show content up to level N."
6994 (interactive "P")
6995 (org-overview)
6996 (save-excursion
6997 ;; Visit all headings and show their offspring
6998 (and (integerp arg) (org-overview))
6999 (goto-char (point-max))
7000 (catch 'exit
7001 (while (and (progn (condition-case nil
7002 (outline-previous-visible-heading 1)
7003 (error (goto-char (point-min))))
7005 (looking-at org-outline-regexp))
7006 (if (integerp arg)
7007 (org-show-children (1- arg))
7008 (outline-show-branches))
7009 (when (bobp) (throw 'exit nil))))))
7011 (defun org-optimize-window-after-visibility-change (state)
7012 "Adjust the window after a change in outline visibility.
7013 This function is the default value of the hook `org-cycle-hook'."
7014 (when (get-buffer-window (current-buffer))
7015 (cond
7016 ((eq state 'content) nil)
7017 ((eq state 'all) nil)
7018 ((eq state 'folded) nil)
7019 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7020 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7022 (defun org-remove-empty-overlays-at (pos)
7023 "Remove outline overlays that do not contain non-white stuff."
7024 (dolist (o (overlays-at pos))
7025 (and (eq 'outline (overlay-get o 'invisible))
7026 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7027 (overlay-end o))))
7028 (delete-overlay o))))
7030 (defun org-clean-visibility-after-subtree-move ()
7031 "Fix visibility issues after moving a subtree."
7032 ;; First, find a reasonable region to look at:
7033 ;; Start two siblings above, end three below
7034 (let* ((beg (save-excursion
7035 (and (org-get-last-sibling)
7036 (org-get-last-sibling))
7037 (point)))
7038 (end (save-excursion
7039 (and (org-get-next-sibling)
7040 (org-get-next-sibling)
7041 (org-get-next-sibling))
7042 (if (org-at-heading-p)
7043 (point-at-eol)
7044 (point))))
7045 (level (looking-at "\\*+"))
7046 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7047 (save-excursion
7048 (save-restriction
7049 (narrow-to-region beg end)
7050 (when re
7051 ;; Properly fold already folded siblings
7052 (goto-char (point-min))
7053 (while (re-search-forward re nil t)
7054 (when (and (not (org-invisible-p))
7055 (save-excursion
7056 (goto-char (point-at-eol)) (org-invisible-p)))
7057 (outline-hide-entry))))
7058 (org-cycle-show-empty-lines 'overview)
7059 (org-cycle-hide-drawers 'overview)))))
7061 (defun org-cycle-show-empty-lines (state)
7062 "Show empty lines above all visible headlines.
7063 The region to be covered depends on STATE when called through
7064 `org-cycle-hook'. Lisp program can use t for STATE to get the
7065 entire buffer covered. Note that an empty line is only shown if there
7066 are at least `org-cycle-separator-lines' empty lines before the headline."
7067 (when (/= org-cycle-separator-lines 0)
7068 (save-excursion
7069 (let* ((n (abs org-cycle-separator-lines))
7070 (re (cond
7071 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7072 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7073 (t (let ((ns (number-to-string (- n 2))))
7074 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7075 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7076 beg end)
7077 (cond
7078 ((memq state '(overview contents t))
7079 (setq beg (point-min) end (point-max)))
7080 ((memq state '(children folded))
7081 (setq beg (point)
7082 end (progn (org-end-of-subtree t t)
7083 (line-beginning-position 2)))))
7084 (when beg
7085 (goto-char beg)
7086 (while (re-search-forward re end t)
7087 (unless (get-char-property (match-end 1) 'invisible)
7088 (let ((e (match-end 1))
7089 (b (if (>= org-cycle-separator-lines 0)
7090 (match-beginning 1)
7091 (save-excursion
7092 (goto-char (match-beginning 0))
7093 (skip-chars-backward " \t\n")
7094 (line-end-position)))))
7095 (outline-flag-region b e nil))))))))
7096 ;; Never hide empty lines at the end of the file.
7097 (save-excursion
7098 (goto-char (point-max))
7099 (outline-previous-heading)
7100 (outline-end-of-heading)
7101 (when (and (looking-at "[ \t\n]+")
7102 (= (match-end 0) (point-max)))
7103 (outline-flag-region (point) (match-end 0) nil))))
7105 (defun org-show-empty-lines-in-parent ()
7106 "Move to the parent and re-show empty lines before visible headlines."
7107 (save-excursion
7108 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7109 (org-cycle-show-empty-lines context))))
7111 (defun org-files-list ()
7112 "Return `org-agenda-files' list, plus all open Org files.
7113 This is useful for operations that need to scan all of a user's
7114 open and agenda-wise Org files."
7115 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7116 (dolist (buf (buffer-list))
7117 (with-current-buffer buf
7118 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7119 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7120 files))
7122 (defsubst org-entry-beginning-position ()
7123 "Return the beginning position of the current entry."
7124 (save-excursion (org-back-to-heading t) (point)))
7126 (defsubst org-entry-end-position ()
7127 "Return the end position of the current entry."
7128 (save-excursion (outline-next-heading) (point)))
7130 (defun org-cycle-hide-drawers (state &optional exceptions)
7131 "Re-hide all drawers after a visibility state change.
7132 STATE should be one of the symbols listed in the docstring of
7133 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7134 a list of strings specifying which drawers should not be hidden."
7135 (when (and (derived-mode-p 'org-mode)
7136 (not (memq state '(overview folded contents))))
7137 (save-excursion
7138 (let* ((globalp (eq state 'all))
7139 (beg (if globalp (point-min) (point)))
7140 (end (if globalp (point-max)
7141 (if (eq state 'children)
7142 (save-excursion (outline-next-heading) (point))
7143 (org-end-of-subtree t)))))
7144 (goto-char beg)
7145 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7146 (unless (member-ignore-case (match-string 1) exceptions)
7147 (let ((drawer (org-element-at-point)))
7148 (when (memq (org-element-type drawer) '(drawer property-drawer))
7149 (org-flag-drawer t drawer)
7150 ;; Make sure to skip drawer entirely or we might flag
7151 ;; it another time when matching its ending line with
7152 ;; `org-drawer-regexp'.
7153 (goto-char (org-element-property :end drawer))))))))))
7155 (defun org-flag-drawer (flag &optional element)
7156 "When FLAG is non-nil, hide the drawer we are at.
7157 Otherwise make it visible. When optional argument ELEMENT is
7158 a parsed drawer, as returned by `org-element-at-point', hide or
7159 show that drawer instead."
7160 (let ((drawer (or element
7161 (and (save-excursion
7162 (beginning-of-line)
7163 (looking-at-p org-drawer-regexp))
7164 (org-element-at-point)))))
7165 (when (memq (org-element-type drawer) '(drawer property-drawer))
7166 (let ((post (org-element-property :post-affiliated drawer)))
7167 (save-excursion
7168 (outline-flag-region
7169 (progn (goto-char post) (line-end-position))
7170 (progn (goto-char (org-element-property :end drawer))
7171 (skip-chars-backward " \r\t\n")
7172 (line-end-position))
7173 flag))
7174 ;; When the drawer is hidden away, make sure point lies in
7175 ;; a visible part of the buffer.
7176 (when (and flag (> (line-beginning-position) post))
7177 (goto-char post))))))
7179 (defun org-subtree-end-visible-p ()
7180 "Is the end of the current subtree visible?"
7181 (pos-visible-in-window-p
7182 (save-excursion (org-end-of-subtree t) (point))))
7184 (defun org-first-headline-recenter ()
7185 "Move cursor to the first headline and recenter the headline."
7186 (let ((window (get-buffer-window)))
7187 (when window
7188 (goto-char (point-min))
7189 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7190 (set-window-start window (line-beginning-position))))))
7192 ;;; Saving and restoring visibility
7194 (defun org-outline-overlay-data (&optional use-markers)
7195 "Return a list of the locations of all outline overlays.
7196 These are overlays with the `invisible' property value `outline'.
7197 The return value is a list of cons cells, with start and stop
7198 positions for each overlay.
7199 If USE-MARKERS is set, return the positions as markers."
7200 (let (beg end)
7201 (org-with-wide-buffer
7202 (delq nil
7203 (mapcar (lambda (o)
7204 (when (eq (overlay-get o 'invisible) 'outline)
7205 (setq beg (overlay-start o)
7206 end (overlay-end o))
7207 (and beg end (> end beg)
7208 (if use-markers
7209 (cons (copy-marker beg)
7210 (copy-marker end t))
7211 (cons beg end)))))
7212 (overlays-in (point-min) (point-max)))))))
7214 (defun org-set-outline-overlay-data (data)
7215 "Create visibility overlays for all positions in DATA.
7216 DATA should have been made by `org-outline-overlay-data'."
7217 (org-with-wide-buffer
7218 (outline-show-all)
7219 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7221 ;;; Folding of blocks
7223 (defvar-local org-hide-block-overlays nil
7224 "Overlays hiding blocks.")
7226 (defun org-block-map (function &optional start end)
7227 "Call FUNCTION at the head of all source blocks in the current buffer.
7228 Optional arguments START and END can be used to limit the range."
7229 (let ((start (or start (point-min)))
7230 (end (or end (point-max))))
7231 (save-excursion
7232 (goto-char start)
7233 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7234 (save-excursion
7235 (save-match-data
7236 (goto-char (match-beginning 0))
7237 (funcall function)))))))
7239 (defun org-hide-block-toggle-all ()
7240 "Toggle the visibility of all blocks in the current buffer."
7241 (org-block-map 'org-hide-block-toggle))
7243 (defun org-hide-block-all ()
7244 "Fold all blocks in the current buffer."
7245 (interactive)
7246 (org-show-block-all)
7247 (org-block-map 'org-hide-block-toggle-maybe))
7249 (defun org-show-block-all ()
7250 "Unfold all blocks in the current buffer."
7251 (interactive)
7252 (mapc #'delete-overlay org-hide-block-overlays)
7253 (setq org-hide-block-overlays nil))
7255 (defun org-hide-block-toggle-maybe ()
7256 "Toggle visibility of block at point.
7257 Unlike to `org-hide-block-toggle', this function does not throw
7258 an error. Return a non-nil value when toggling is successful."
7259 (interactive)
7260 (ignore-errors (org-hide-block-toggle)))
7262 (defun org-hide-block-toggle (&optional force)
7263 "Toggle the visibility of the current block.
7264 When optional argument FORCE is `off', make block visible. If it
7265 is non-nil, hide it unconditionally. Throw an error when not at
7266 a block. Return a non-nil value when toggling is successful."
7267 (interactive)
7268 (let ((element (org-element-at-point)))
7269 (unless (memq (org-element-type element)
7270 '(center-block comment-block dynamic-block example-block
7271 export-block quote-block special-block
7272 src-block verse-block))
7273 (user-error "Not at a block"))
7274 (let* ((start (save-excursion
7275 (goto-char (org-element-property :post-affiliated element))
7276 (line-end-position)))
7277 (end (save-excursion
7278 (goto-char (org-element-property :end element))
7279 (skip-chars-backward " \r\t\n")
7280 (line-end-position)))
7281 (overlays (overlays-at start)))
7282 (cond
7283 ;; Do nothing when not before or at the block opening line or
7284 ;; at the block closing line.
7285 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7286 ((and (not (eq force 'off))
7287 (not (memq t (mapcar
7288 (lambda (o)
7289 (eq (overlay-get o 'invisible) 'org-hide-block))
7290 overlays))))
7291 (let ((ov (make-overlay start end)))
7292 (overlay-put ov 'invisible 'org-hide-block)
7293 ;; Make the block accessible to `isearch'.
7294 (overlay-put
7295 ov 'isearch-open-invisible
7296 (lambda (ov)
7297 (when (memq ov org-hide-block-overlays)
7298 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7299 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7300 (delete-overlay ov))))
7301 (push ov org-hide-block-overlays)
7302 ;; When the block is hidden away, make sure point is left in
7303 ;; a visible part of the buffer.
7304 (when (> (line-beginning-position) start)
7305 (goto-char start)
7306 (beginning-of-line))
7307 ;; Signal successful toggling.
7309 ((or (not force) (eq force 'off))
7310 (dolist (ov overlays t)
7311 (when (memq ov org-hide-block-overlays)
7312 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7313 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7314 (delete-overlay ov))))))))
7316 ;; Remove overlays when changing major mode
7317 (add-hook 'org-mode-hook
7318 (lambda () (add-hook 'change-major-mode-hook
7319 'org-show-block-all 'append 'local)))
7321 ;;; Indirect buffer display of subtrees
7323 (defvar org-indirect-dedicated-frame nil
7324 "This is the frame being used for indirect tree display.")
7325 (defvar org-last-indirect-buffer nil)
7327 (defun org-tree-to-indirect-buffer (&optional arg)
7328 "Create indirect buffer and narrow it to current subtree.
7330 With a numerical prefix ARG, go up to this level and then take that tree.
7331 If ARG is negative, go up that many levels.
7333 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7334 indirect buffer previously made with this command, to avoid proliferation of
7335 indirect buffers. However, when you call the command with a \
7336 `\\[universal-argument]' prefix, or
7337 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7338 so that you can work with several indirect buffers at the same time. If
7339 `org-indirect-buffer-display' is `dedicated-frame', the \
7340 `\\[universal-argument]' prefix also
7341 requests that a new frame be made for the new buffer, so that the dedicated
7342 frame is not changed."
7343 (interactive "P")
7344 (let ((cbuf (current-buffer))
7345 (cwin (selected-window))
7346 (pos (point))
7347 beg end level heading ibuf)
7348 (save-excursion
7349 (org-back-to-heading t)
7350 (when (numberp arg)
7351 (setq level (org-outline-level))
7352 (when (< arg 0) (setq arg (+ level arg)))
7353 (while (> (setq level (org-outline-level)) arg)
7354 (org-up-heading-safe)))
7355 (setq beg (point)
7356 heading (org-get-heading 'no-tags))
7357 (org-end-of-subtree t t)
7358 (when (org-at-heading-p) (backward-char 1))
7359 (setq end (point)))
7360 (when (and (buffer-live-p org-last-indirect-buffer)
7361 (not (eq org-indirect-buffer-display 'new-frame))
7362 (not arg))
7363 (kill-buffer org-last-indirect-buffer))
7364 (setq ibuf (org-get-indirect-buffer cbuf heading)
7365 org-last-indirect-buffer ibuf)
7366 (cond
7367 ((or (eq org-indirect-buffer-display 'new-frame)
7368 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7369 (select-frame (make-frame))
7370 (delete-other-windows)
7371 (pop-to-buffer-same-window ibuf)
7372 (org-set-frame-title heading))
7373 ((eq org-indirect-buffer-display 'dedicated-frame)
7374 (raise-frame
7375 (select-frame (or (and org-indirect-dedicated-frame
7376 (frame-live-p org-indirect-dedicated-frame)
7377 org-indirect-dedicated-frame)
7378 (setq org-indirect-dedicated-frame (make-frame)))))
7379 (delete-other-windows)
7380 (pop-to-buffer-same-window ibuf)
7381 (org-set-frame-title (concat "Indirect: " heading)))
7382 ((eq org-indirect-buffer-display 'current-window)
7383 (pop-to-buffer-same-window ibuf))
7384 ((eq org-indirect-buffer-display 'other-window)
7385 (pop-to-buffer ibuf))
7386 (t (error "Invalid value")))
7387 (narrow-to-region beg end)
7388 (outline-show-all)
7389 (goto-char pos)
7390 (run-hook-with-args 'org-cycle-hook 'all)
7391 (and (window-live-p cwin) (select-window cwin))))
7393 (defun org-get-indirect-buffer (&optional buffer heading)
7394 (setq buffer (or buffer (current-buffer)))
7395 (let ((n 1) (base (buffer-name buffer)) bname)
7396 (while (buffer-live-p
7397 (get-buffer
7398 (setq bname
7399 (concat base "-"
7400 (if heading (concat heading "-" (number-to-string n))
7401 (number-to-string n))))))
7402 (setq n (1+ n)))
7403 (condition-case nil
7404 (make-indirect-buffer buffer bname 'clone)
7405 (error (make-indirect-buffer buffer bname)))))
7407 (defun org-set-frame-title (title)
7408 "Set the title of the current frame to the string TITLE."
7409 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7411 ;;;; Structure editing
7413 ;;; Inserting headlines
7415 (defun org--line-empty-p (n)
7416 "Is the Nth next line empty?
7418 Counts the current line as N = 1 and the previous line as N = 0;
7419 see `beginning-of-line'."
7420 (save-excursion
7421 (and (not (bobp))
7422 (or (beginning-of-line n) t)
7423 (save-match-data
7424 (looking-at "[ \t]*$")))))
7426 (defun org-previous-line-empty-p ()
7427 "Is the previous line a blank line?
7428 When NEXT is non-nil, check the next line instead."
7429 (org--line-empty-p 0))
7431 (defun org-next-line-empty-p ()
7432 "Is the previous line a blank line?
7433 When NEXT is non-nil, check the next line instead."
7434 (org--line-empty-p 2))
7436 (defun org--blank-before-heading-p (&optional parent)
7437 "Non-nil when an empty line should precede a new heading here.
7438 When optional argument PARENT is non-nil, consider parent
7439 headline instead of current one."
7440 (pcase (assq 'heading org-blank-before-new-entry)
7441 (`(heading . auto)
7442 (save-excursion
7443 (org-with-limited-levels
7444 (unless (and (org-before-first-heading-p)
7445 (not (outline-next-heading)))
7446 (org-back-to-heading t)
7447 (when parent (org-up-heading-safe))
7448 (cond ((not (bobp))
7449 (org-previous-line-empty-p))
7450 ((outline-next-heading)
7451 (org-previous-line-empty-p))
7452 ;; Ignore trailing spaces on last buffer line.
7453 ((progn (skip-chars-backward " \t") (bolp))
7454 (org-previous-line-empty-p))
7455 (t nil))))))
7456 (`(heading . ,value) value)
7457 (_ nil)))
7459 (defun org-insert-heading (&optional arg invisible-ok top)
7460 "Insert a new heading or an item with the same depth at point.
7462 If point is at the beginning of a heading, insert a new heading
7463 or a new headline above the current one. When at the beginning
7464 of a regular line of text, turn it into a heading.
7466 If point is in the middle of a line, split it and create a new
7467 headline with the text in the current line after point (see
7468 `org-M-RET-may-split-line' on how to modify this behavior). As
7469 a special case, on a headline, splitting can only happen on the
7470 title itself. E.g., this excludes breaking stars or tags.
7472 With a `\\[universal-argument]' prefix, set \
7473 `org-insert-heading-respect-content' to
7474 a non-nil value for the duration of the command. This forces the
7475 insertion of a heading after the current subtree, independently
7476 on the location of point.
7478 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7479 insert the heading at the end of the tree
7480 above the current heading. For example, if point is within a
7481 2nd-level heading, then it will insert a 2nd-level heading at
7482 the end of the 1st-level parent subtree.
7484 When INVISIBLE-OK is set, stop at invisible headlines when going
7485 back. This is important for non-interactive uses of the
7486 command.
7488 When optional argument TOP is non-nil, insert a level 1 heading,
7489 unconditionally."
7490 (interactive "P")
7491 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7492 (level (org-current-level))
7493 (stars (make-string (if (and level (not top)) level 1) ?*)))
7494 (cond
7495 ((or org-insert-heading-respect-content
7496 (member arg '((4) (16)))
7497 (and (not invisible-ok)
7498 (invisible-p (max (1- (point)) (point-min)))))
7499 ;; Position point at the location of insertion.
7500 (if (not level) ;before first headline
7501 (org-with-limited-levels (outline-next-heading))
7502 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7503 ;; is nil.
7504 (org-with-limited-levels (org-back-to-heading invisible-ok))
7505 (cond ((equal arg '(16))
7506 (org-up-heading-safe)
7507 (org-end-of-subtree t t))
7509 (org-end-of-subtree t t))))
7510 (unless (bolp) (insert "\n")) ;ensure final newline
7511 (unless (and blank? (org-previous-line-empty-p))
7512 (org-N-empty-lines-before-current (if blank? 1 0)))
7513 (insert stars " \n")
7514 (forward-char -1))
7515 ;; At a headline...
7516 ((org-at-heading-p)
7517 (cond ((bolp)
7518 (when blank? (save-excursion (insert "\n")))
7519 (save-excursion (insert stars " \n"))
7520 (unless (and blank? (org-previous-line-empty-p))
7521 (org-N-empty-lines-before-current (if blank? 1 0)))
7522 (end-of-line))
7523 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7524 (org-match-line org-complex-heading-regexp)
7525 (org-pos-in-match-range (point) 4))
7526 ;; Grab the text that should moved to the new headline.
7527 ;; Preserve tags.
7528 (let ((split (delete-and-extract-region (point) (match-end 4))))
7529 (if (looking-at "[ \t]*$") (replace-match "")
7530 (org-set-tags nil t))
7531 (end-of-line)
7532 (when blank? (insert "\n"))
7533 (insert "\n" stars " ")
7534 (when (org-string-nw-p split) (insert split))
7535 (when (eobp) (save-excursion (insert "\n")))))
7537 (end-of-line)
7538 (when blank? (insert "\n"))
7539 (insert "\n" stars " ")
7540 (when (eobp) (save-excursion (insert "\n"))))))
7541 ;; On regular text, turn line into a headline or split, if
7542 ;; appropriate.
7543 ((bolp)
7544 (insert stars " ")
7545 (unless (and blank? (org-previous-line-empty-p))
7546 (org-N-empty-lines-before-current (if blank? 1 0))))
7548 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7549 (end-of-line))
7550 (insert "\n" stars " ")
7551 (unless (and blank? (org-previous-line-empty-p))
7552 (org-N-empty-lines-before-current (if blank? 1 0))))))
7553 (run-hooks 'org-insert-heading-hook))
7555 (defun org-N-empty-lines-before-current (n)
7556 "Make the number of empty lines before current exactly N.
7557 So this will delete or add empty lines."
7558 (let ((column (current-column)))
7559 (beginning-of-line)
7560 (unless (bobp)
7561 (let ((start (save-excursion
7562 (skip-chars-backward " \r\t\n")
7563 (line-end-position))))
7564 (delete-region start (line-end-position 0))))
7565 (insert (make-string n ?\n))
7566 (move-to-column column)))
7568 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7569 "Return the heading of the current entry, without the stars.
7570 When NO-TAGS is non-nil, don't include tags.
7571 When NO-TODO is non-nil, don't include TODO keywords.
7572 When NO-PRIORITY is non-nil, don't include priority cookie.
7573 When NO-COMMENT is non-nil, don't include COMMENT string."
7574 (save-excursion
7575 (org-back-to-heading t)
7576 (let ((case-fold-search nil))
7577 (looking-at org-complex-heading-regexp)
7578 (let ((todo (and (not no-todo) (match-string 2)))
7579 (priority (and (not no-priority) (match-string 3)))
7580 (headline (pcase (match-string 4)
7581 (`nil "")
7582 ((and (guard no-comment) h)
7583 (replace-regexp-in-string
7584 (eval-when-compile
7585 (format "\\`%s[ \t]+" org-comment-string))
7586 "" h))
7587 (h h)))
7588 (tags (and (not no-tags) (match-string 5))))
7589 (mapconcat #'identity
7590 (delq nil (list todo priority headline tags))
7591 " ")))))
7593 (defvar orgstruct-mode) ; defined below
7595 (defun org-heading-components ()
7596 "Return the components of the current heading.
7597 This is a list with the following elements:
7598 - the level as an integer
7599 - the reduced level, different if `org-odd-levels-only' is set.
7600 - the TODO keyword, or nil
7601 - the priority character, like ?A, or nil if no priority is given
7602 - the headline text itself, or the tags string if no headline text
7603 - the tags string, or nil."
7604 (save-excursion
7605 (org-back-to-heading t)
7606 (when (let (case-fold-search)
7607 (looking-at
7608 (if orgstruct-mode
7609 org-heading-regexp
7610 org-complex-heading-regexp)))
7611 (if orgstruct-mode
7612 (list (length (match-string 1))
7613 (org-reduced-level (length (match-string 1)))
7616 (match-string 2)
7617 nil)
7618 (list (length (match-string 1))
7619 (org-reduced-level (length (match-string 1)))
7620 (match-string-no-properties 2)
7621 (and (match-end 3) (aref (match-string 3) 2))
7622 (match-string-no-properties 4)
7623 (match-string-no-properties 5))))))
7625 (defun org-get-entry ()
7626 "Get the entry text, after heading, entire subtree."
7627 (save-excursion
7628 (org-back-to-heading t)
7629 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7631 (defun org-edit-headline (&optional heading)
7632 "Edit the current headline.
7633 Set it to HEADING when provided."
7634 (interactive)
7635 (org-with-wide-buffer
7636 (org-back-to-heading t)
7637 (let ((case-fold-search nil))
7638 (when (looking-at org-complex-heading-regexp)
7639 (let* ((old (match-string-no-properties 4))
7640 (new (save-match-data
7641 (org-trim (or heading (read-string "Edit: " old))))))
7642 (unless (equal old new)
7643 (if old (replace-match new t t nil 4)
7644 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7645 (insert " " new))
7646 (org-set-tags nil t)
7647 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7649 (defun org-insert-heading-after-current ()
7650 "Insert a new heading with same level as current, after current subtree."
7651 (interactive)
7652 (org-back-to-heading)
7653 (org-insert-heading)
7654 (org-move-subtree-down)
7655 (end-of-line 1))
7657 (defun org-insert-heading-respect-content (&optional invisible-ok)
7658 "Insert heading with `org-insert-heading-respect-content' set to t."
7659 (interactive)
7660 (org-insert-heading '(4) invisible-ok))
7662 (defun org-insert-todo-heading-respect-content (&optional force-state)
7663 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7664 (interactive)
7665 (org-insert-todo-heading force-state '(4)))
7667 (defun org-insert-todo-heading (arg &optional force-heading)
7668 "Insert a new heading with the same level and TODO state as current heading.
7670 If the heading has no TODO state, or if the state is DONE, use
7671 the first state (TODO by default). Also with one prefix arg,
7672 force first state. With two prefix args, force inserting at the
7673 end of the parent subtree.
7675 When called at a plain list item, insert a new item with an
7676 unchecked check box."
7677 (interactive "P")
7678 (when (or force-heading (not (org-insert-item 'checkbox)))
7679 (org-insert-heading (or (and (equal arg '(16)) '(16))
7680 force-heading))
7681 (save-excursion
7682 (org-forward-heading-same-level -1)
7683 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7684 (let* ((new-mark-x
7685 (if (or (equal arg '(4))
7686 (not (match-beginning 2))
7687 (member (match-string 2) org-done-keywords))
7688 (car org-todo-keywords-1)
7689 (match-string 2)))
7690 (new-mark
7692 (run-hook-with-args-until-success
7693 'org-todo-get-default-hook new-mark-x nil)
7694 new-mark-x)))
7695 (beginning-of-line 1)
7696 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7697 (if org-treat-insert-todo-heading-as-state-change
7698 (org-todo new-mark)
7699 (insert new-mark " "))))
7700 (when org-provide-todo-statistics
7701 (org-update-parent-todo-statistics))))
7703 (defun org-insert-subheading (arg)
7704 "Insert a new subheading and demote it.
7705 Works for outline headings and for plain lists alike."
7706 (interactive "P")
7707 (org-insert-heading arg)
7708 (cond
7709 ((org-at-heading-p) (org-do-demote))
7710 ((org-at-item-p) (org-indent-item))))
7712 (defun org-insert-todo-subheading (arg)
7713 "Insert a new subheading with TODO keyword or checkbox and demote it.
7714 Works for outline headings and for plain lists alike."
7715 (interactive "P")
7716 (org-insert-todo-heading arg)
7717 (cond
7718 ((org-at-heading-p) (org-do-demote))
7719 ((org-at-item-p) (org-indent-item))))
7721 ;;; Promotion and Demotion
7723 (defvar org-after-demote-entry-hook nil
7724 "Hook run after an entry has been demoted.
7725 The cursor will be at the beginning of the entry.
7726 When a subtree is being demoted, the hook will be called for each node.")
7728 (defvar org-after-promote-entry-hook nil
7729 "Hook run after an entry has been promoted.
7730 The cursor will be at the beginning of the entry.
7731 When a subtree is being promoted, the hook will be called for each node.")
7733 (defun org-promote-subtree ()
7734 "Promote the entire subtree.
7735 See also `org-promote'."
7736 (interactive)
7737 (save-excursion
7738 (org-with-limited-levels (org-map-tree 'org-promote)))
7739 (org-fix-position-after-promote))
7741 (defun org-demote-subtree ()
7742 "Demote the entire subtree.
7743 See `org-demote' and `org-promote'."
7744 (interactive)
7745 (save-excursion
7746 (org-with-limited-levels (org-map-tree 'org-demote)))
7747 (org-fix-position-after-promote))
7749 (defun org-do-promote ()
7750 "Promote the current heading higher up the tree.
7751 If the region is active in `transient-mark-mode', promote all
7752 headings in the region."
7753 (interactive)
7754 (save-excursion
7755 (if (org-region-active-p)
7756 (org-map-region 'org-promote (region-beginning) (region-end))
7757 (org-promote)))
7758 (org-fix-position-after-promote))
7760 (defun org-do-demote ()
7761 "Demote the current heading lower down the tree.
7762 If the region is active in `transient-mark-mode', demote all
7763 headings in the region."
7764 (interactive)
7765 (save-excursion
7766 (if (org-region-active-p)
7767 (org-map-region 'org-demote (region-beginning) (region-end))
7768 (org-demote)))
7769 (org-fix-position-after-promote))
7771 (defun org-fix-position-after-promote ()
7772 "Fix cursor position and indentation after demoting/promoting."
7773 (let ((pos (point)))
7774 (when (save-excursion
7775 (beginning-of-line)
7776 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7777 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7778 (cond ((eobp) (insert " "))
7779 ((eolp) (insert " "))
7780 ((equal (char-after) ?\s) (forward-char 1))))))
7782 (defun org-current-level ()
7783 "Return the level of the current entry, or nil if before the first headline.
7784 The level is the number of stars at the beginning of the
7785 headline. Use `org-reduced-level' to remove the effect of
7786 `org-odd-levels'. Unlike to `org-outline-level', this function
7787 ignores inlinetasks."
7788 (let ((level (org-with-limited-levels (org-outline-level))))
7789 (and (> level 0) level)))
7791 (defun org-get-previous-line-level ()
7792 "Return the outline depth of the last headline before the current line.
7793 Returns 0 for the first headline in the buffer, and nil if before the
7794 first headline."
7795 (and (org-current-level)
7796 (or (and (/= (line-beginning-position) (point-min))
7797 (save-excursion (beginning-of-line 0) (org-current-level)))
7798 0)))
7800 (defun org-reduced-level (l)
7801 "Compute the effective level of a heading.
7802 This takes into account the setting of `org-odd-levels-only'."
7803 (cond
7804 ((zerop l) 0)
7805 (org-odd-levels-only (1+ (floor (/ l 2))))
7806 (t l)))
7808 (defun org-level-increment ()
7809 "Return the number of stars that will be added or removed at a
7810 time to headlines when structure editing, based on the value of
7811 `org-odd-levels-only'."
7812 (if org-odd-levels-only 2 1))
7814 (defun org-get-valid-level (level &optional change)
7815 "Rectify a level change under the influence of `org-odd-levels-only'.
7816 LEVEL is a current level, CHANGE is by how much the level should
7817 be modified. Even if CHANGE is nil, LEVEL may be returned
7818 modified because even level numbers will become the next higher
7819 odd number. Returns values greater than 0."
7820 (if org-odd-levels-only
7821 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7822 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7823 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7824 (max 1 (+ level (or change 0)))))
7826 (defun org-promote ()
7827 "Promote the current heading higher up the tree."
7828 (org-with-wide-buffer
7829 (org-back-to-heading t)
7830 (let* ((after-change-functions (remq 'flyspell-after-change-function
7831 after-change-functions))
7832 (level (save-match-data (funcall outline-level)))
7833 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7834 (diff (abs (- level (length up-head) -1))))
7835 (cond
7836 ((and (= level 1) org-allow-promoting-top-level-subtree)
7837 (replace-match "# " nil t))
7838 ((= level 1)
7839 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7840 (t (replace-match up-head nil t)))
7841 (unless (= level 1)
7842 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7843 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7844 (run-hooks 'org-after-promote-entry-hook))))
7846 (defun org-demote ()
7847 "Demote the current heading lower down the tree."
7848 (org-with-wide-buffer
7849 (org-back-to-heading t)
7850 (let* ((after-change-functions (remq 'flyspell-after-change-function
7851 after-change-functions))
7852 (level (save-match-data (funcall outline-level)))
7853 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7854 (diff (abs (- level (length down-head) -1))))
7855 (replace-match down-head nil t)
7856 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
7857 (when org-adapt-indentation (org-fixup-indentation diff))
7858 (run-hooks 'org-after-demote-entry-hook))))
7860 (defun org-cycle-level ()
7861 "Cycle the level of an empty headline through possible states.
7862 This goes first to child, then to parent, level, then up the hierarchy.
7863 After top level, it switches back to sibling level."
7864 (interactive)
7865 (let ((org-adapt-indentation nil))
7866 (when (org-point-at-end-of-empty-headline)
7867 (setq this-command 'org-cycle-level) ; Only needed for caching
7868 (let ((cur-level (org-current-level))
7869 (prev-level (org-get-previous-line-level)))
7870 (cond
7871 ;; If first headline in file, promote to top-level.
7872 ((= prev-level 0)
7873 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7874 do (org-do-promote)))
7875 ;; If same level as prev, demote one.
7876 ((= prev-level cur-level)
7877 (org-do-demote))
7878 ;; If parent is top-level, promote to top level if not already.
7879 ((= prev-level 1)
7880 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7881 do (org-do-promote)))
7882 ;; If top-level, return to prev-level.
7883 ((= cur-level 1)
7884 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
7885 do (org-do-demote)))
7886 ;; If less than prev-level, promote one.
7887 ((< cur-level prev-level)
7888 (org-do-promote))
7889 ;; If deeper than prev-level, promote until higher than
7890 ;; prev-level.
7891 ((> cur-level prev-level)
7892 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7893 do (org-do-promote))))
7894 t))))
7896 (defun org-map-tree (fun)
7897 "Call FUN for every heading underneath the current one."
7898 (org-back-to-heading t)
7899 (let ((level (funcall outline-level)))
7900 (save-excursion
7901 (funcall fun)
7902 (while (and (progn
7903 (outline-next-heading)
7904 (> (funcall outline-level) level))
7905 (not (eobp)))
7906 (funcall fun)))))
7908 (defun org-map-region (fun beg end)
7909 "Call FUN for every heading between BEG and END."
7910 (let ((org-ignore-region t))
7911 (save-excursion
7912 (setq end (copy-marker end))
7913 (goto-char beg)
7914 (when (and (re-search-forward org-outline-regexp-bol nil t)
7915 (< (point) end))
7916 (funcall fun))
7917 (while (and (progn
7918 (outline-next-heading)
7919 (< (point) end))
7920 (not (eobp)))
7921 (funcall fun)))))
7923 (defun org-fixup-indentation (diff)
7924 "Change the indentation in the current entry by DIFF.
7926 DIFF is an integer. Indentation is done according to the
7927 following rules:
7929 - Planning information and property drawers are always indented
7930 according to the new level of the headline;
7932 - Footnote definitions and their contents are ignored;
7934 - Inlinetasks' boundaries are not shifted;
7936 - Empty lines are ignored;
7938 - Other lines' indentation are shifted by DIFF columns, unless
7939 it would introduce a structural change in the document, in
7940 which case no shifting is done at all.
7942 Assume point is at a heading or an inlinetask beginning."
7943 (org-with-wide-buffer
7944 (narrow-to-region (line-beginning-position)
7945 (save-excursion
7946 (if (org-with-limited-levels (org-at-heading-p))
7947 (org-with-limited-levels (outline-next-heading))
7948 (org-inlinetask-goto-end))
7949 (point)))
7950 (forward-line)
7951 ;; Indent properly planning info and property drawer.
7952 (when (looking-at-p org-planning-line-re)
7953 (org-indent-line)
7954 (forward-line))
7955 (when (looking-at org-property-drawer-re)
7956 (goto-char (match-end 0))
7957 (forward-line)
7958 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
7959 (catch 'no-shift
7960 (when (zerop diff) (throw 'no-shift nil))
7961 ;; If DIFF is negative, first check if a shift is possible at all
7962 ;; (e.g., it doesn't break structure). This can only happen if
7963 ;; some contents are not properly indented.
7964 (let ((case-fold-search t))
7965 (when (< diff 0)
7966 (let ((diff (- diff))
7967 (forbidden-re (concat org-outline-regexp
7968 "\\|"
7969 (substring org-footnote-definition-re 1))))
7970 (save-excursion
7971 (while (not (eobp))
7972 (cond
7973 ((looking-at-p "[ \t]*$") (forward-line))
7974 ((and (looking-at-p org-footnote-definition-re)
7975 (let ((e (org-element-at-point)))
7976 (and (eq (org-element-type e) 'footnote-definition)
7977 (goto-char (org-element-property :end e))))))
7978 ((looking-at-p org-outline-regexp) (forward-line))
7979 ;; Give up if shifting would move before column 0 or
7980 ;; if it would introduce a headline or a footnote
7981 ;; definition.
7983 (skip-chars-forward " \t")
7984 (let ((ind (current-column)))
7985 (when (or (< ind diff)
7986 (and (= ind diff) (looking-at-p forbidden-re)))
7987 (throw 'no-shift nil)))
7988 ;; Ignore contents of example blocks and source
7989 ;; blocks if their indentation is meant to be
7990 ;; preserved. Jump to block's closing line.
7991 (beginning-of-line)
7992 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
7993 (let ((e (org-element-at-point)))
7994 (and (memq (org-element-type e)
7995 '(example-block src-block))
7996 (or org-src-preserve-indentation
7997 (org-element-property :preserve-indent e))
7998 (goto-char (org-element-property :end e))
7999 (progn (skip-chars-backward " \r\t\n")
8000 (beginning-of-line)
8001 t))))
8002 (forward-line))))))))
8003 ;; Shift lines but footnote definitions, inlinetasks boundaries
8004 ;; by DIFF. Also skip contents of source or example blocks
8005 ;; when indentation is meant to be preserved.
8006 (while (not (eobp))
8007 (cond
8008 ((and (looking-at-p org-footnote-definition-re)
8009 (let ((e (org-element-at-point)))
8010 (and (eq (org-element-type e) 'footnote-definition)
8011 (goto-char (org-element-property :end e))))))
8012 ((looking-at-p org-outline-regexp) (forward-line))
8013 ((looking-at-p "[ \t]*$") (forward-line))
8015 (indent-line-to (+ (org-get-indentation) diff))
8016 (beginning-of-line)
8017 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8018 (let ((e (org-element-at-point)))
8019 (and (memq (org-element-type e)
8020 '(example-block src-block))
8021 (or org-src-preserve-indentation
8022 (org-element-property :preserve-indent e))
8023 (goto-char (org-element-property :end e))
8024 (progn (skip-chars-backward " \r\t\n")
8025 (beginning-of-line)
8026 t))))
8027 (forward-line)))))))))
8029 (defun org-convert-to-odd-levels ()
8030 "Convert an Org file with all levels allowed to one with odd levels.
8031 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8032 level 5 etc."
8033 (interactive)
8034 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8035 (let ((outline-level 'org-outline-level)
8036 (org-odd-levels-only nil) n)
8037 (save-excursion
8038 (goto-char (point-min))
8039 (while (re-search-forward "^\\*\\*+ " nil t)
8040 (setq n (- (length (match-string 0)) 2))
8041 (while (>= (setq n (1- n)) 0)
8042 (org-demote))
8043 (end-of-line 1))))))
8045 (defun org-convert-to-oddeven-levels ()
8046 "Convert an Org file with only odd levels to one with odd/even levels.
8047 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8048 file contains a section with an even level, conversion would
8049 destroy the structure of the file. An error is signaled in this
8050 case."
8051 (interactive)
8052 (goto-char (point-min))
8053 ;; First check if there are no even levels
8054 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8055 (org-show-set-visibility 'canonical)
8056 (error "Not all levels are odd in this file. Conversion not possible"))
8057 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8058 (let ((outline-regexp org-outline-regexp)
8059 (outline-level 'org-outline-level)
8060 (org-odd-levels-only nil) n)
8061 (save-excursion
8062 (goto-char (point-min))
8063 (while (re-search-forward "^\\*\\*+ " nil t)
8064 (setq n (/ (1- (length (match-string 0))) 2))
8065 (while (>= (setq n (1- n)) 0)
8066 (org-promote))
8067 (end-of-line 1))))))
8069 (defun org-tr-level (n)
8070 "Make N odd if required."
8071 (if org-odd-levels-only (1+ (/ n 2)) n))
8073 ;;; Vertical tree motion, cutting and pasting of subtrees
8075 (defun org-move-subtree-up (&optional arg)
8076 "Move the current subtree up past ARG headlines of the same level."
8077 (interactive "p")
8078 (org-move-subtree-down (- (prefix-numeric-value arg))))
8080 (defun org-move-subtree-down (&optional arg)
8081 "Move the current subtree down past ARG headlines of the same level."
8082 (interactive "p")
8083 (setq arg (prefix-numeric-value arg))
8084 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8085 'org-get-last-sibling))
8086 (ins-point (make-marker))
8087 (cnt (abs arg))
8088 (col (current-column))
8089 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8090 ;; Select the tree
8091 (org-back-to-heading)
8092 (setq beg0 (point))
8093 (save-excursion
8094 (setq ne-beg (org-back-over-empty-lines))
8095 (setq beg (point)))
8096 (save-match-data
8097 (save-excursion (outline-end-of-heading)
8098 (setq folded (org-invisible-p)))
8099 (progn (org-end-of-subtree nil t)
8100 (unless (eobp) (backward-char))))
8101 (outline-next-heading)
8102 (setq ne-end (org-back-over-empty-lines))
8103 (setq end (point))
8104 (goto-char beg0)
8105 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8106 ;; include less whitespace
8107 (save-excursion
8108 (goto-char beg)
8109 (forward-line (- ne-beg ne-end))
8110 (setq beg (point))))
8111 ;; Find insertion point, with error handling
8112 (while (> cnt 0)
8113 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8114 (progn (goto-char beg0)
8115 (user-error "Cannot move past superior level or buffer limit")))
8116 (setq cnt (1- cnt)))
8117 (when (> arg 0)
8118 ;; Moving forward - still need to move over subtree
8119 (org-end-of-subtree t t)
8120 (save-excursion
8121 (org-back-over-empty-lines)
8122 (or (bolp) (newline))))
8123 (setq ne-ins (org-back-over-empty-lines))
8124 (move-marker ins-point (point))
8125 (setq txt (buffer-substring beg end))
8126 (org-save-markers-in-region beg end)
8127 (delete-region beg end)
8128 (org-remove-empty-overlays-at beg)
8129 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8130 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8131 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8132 (let ((bbb (point)))
8133 (insert-before-markers txt)
8134 (org-reinstall-markers-in-region bbb)
8135 (move-marker ins-point bbb))
8136 (or (bolp) (insert "\n"))
8137 (setq ins-end (point))
8138 (goto-char ins-point)
8139 (org-skip-whitespace)
8140 (when (and (< arg 0)
8141 (org-first-sibling-p)
8142 (> ne-ins ne-beg))
8143 ;; Move whitespace back to beginning
8144 (save-excursion
8145 (goto-char ins-end)
8146 (let ((kill-whole-line t))
8147 (kill-line (- ne-ins ne-beg)) (point)))
8148 (insert (make-string (- ne-ins ne-beg) ?\n)))
8149 (move-marker ins-point nil)
8150 (if folded
8151 (outline-hide-subtree)
8152 (org-show-entry)
8153 (org-show-children)
8154 (org-cycle-hide-drawers 'children))
8155 (org-clean-visibility-after-subtree-move)
8156 ;; move back to the initial column we were at
8157 (move-to-column col)))
8159 (defvar org-subtree-clip ""
8160 "Clipboard for cut and paste of subtrees.
8161 This is actually only a copy of the kill, because we use the normal kill
8162 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8164 (defvar org-subtree-clip-folded nil
8165 "Was the last copied subtree folded?
8166 This is used to fold the tree back after pasting.")
8168 (defun org-cut-subtree (&optional n)
8169 "Cut the current subtree into the clipboard.
8170 With prefix arg N, cut this many sequential subtrees.
8171 This is a short-hand for marking the subtree and then cutting it."
8172 (interactive "p")
8173 (org-copy-subtree n 'cut))
8175 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8176 "Copy the current subtree it in the clipboard.
8177 With prefix arg N, copy this many sequential subtrees.
8178 This is a short-hand for marking the subtree and then copying it.
8179 If CUT is non-nil, actually cut the subtree.
8180 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8181 of some markers in the region, even if CUT is non-nil. This is
8182 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8183 (interactive "p")
8184 (let (beg end folded (beg0 (point)))
8185 (if (called-interactively-p 'any)
8186 (org-back-to-heading nil) ; take what looks like a subtree
8187 (org-back-to-heading t)) ; take what is really there
8188 (setq beg (point))
8189 (skip-chars-forward " \t\r\n")
8190 (save-match-data
8191 (if nosubtrees
8192 (outline-next-heading)
8193 (save-excursion (outline-end-of-heading)
8194 (setq folded (org-invisible-p)))
8195 (ignore-errors (org-forward-heading-same-level (1- n) t))
8196 (org-end-of-subtree t t)))
8197 ;; Include the end of an inlinetask
8198 (when (and (featurep 'org-inlinetask)
8199 (looking-at-p (concat (org-inlinetask-outline-regexp)
8200 "END[ \t]*$")))
8201 (end-of-line))
8202 (setq end (point))
8203 (goto-char beg0)
8204 (when (> end beg)
8205 (setq org-subtree-clip-folded folded)
8206 (when (or cut force-store-markers)
8207 (org-save-markers-in-region beg end))
8208 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8209 (setq org-subtree-clip (current-kill 0))
8210 (message "%s: Subtree(s) with %d characters"
8211 (if cut "Cut" "Copied")
8212 (length org-subtree-clip)))))
8214 (defun org-paste-subtree (&optional level tree for-yank remove)
8215 "Paste the clipboard as a subtree, with modification of headline level.
8216 The entire subtree is promoted or demoted in order to match a new headline
8217 level.
8219 If the cursor is at the beginning of a headline, the same level as
8220 that headline is used to paste the tree.
8222 If not, the new level is derived from the *visible* headings
8223 before and after the insertion point, and taken to be the inferior headline
8224 level of the two. So if the previous visible heading is level 3 and the
8225 next is level 4 (or vice versa), level 4 will be used for insertion.
8226 This makes sure that the subtree remains an independent subtree and does
8227 not swallow low level entries.
8229 You can also force a different level, either by using a numeric prefix
8230 argument, or by inserting the heading marker by hand. For example, if the
8231 cursor is after \"*****\", then the tree will be shifted to level 5.
8233 If optional TREE is given, use this text instead of the kill ring.
8235 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8236 move back over whitespace before inserting, and move point to the end of
8237 the inserted text when done.
8239 When REMOVE is non-nil, remove the subtree from the clipboard."
8240 (interactive "P")
8241 (setq tree (or tree (and kill-ring (current-kill 0))))
8242 (unless (org-kill-is-subtree-p tree)
8243 (user-error "%s"
8244 (substitute-command-keys
8245 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8246 (org-with-limited-levels
8247 (let* ((visp (not (org-invisible-p)))
8248 (txt tree)
8249 (^re_ "\\(\\*+\\)[ \t]*")
8250 (old-level (if (string-match org-outline-regexp-bol txt)
8251 (- (match-end 0) (match-beginning 0) 1)
8252 -1))
8253 (force-level (cond (level (prefix-numeric-value level))
8254 ((and (looking-at "[ \t]*$")
8255 (string-match
8256 "^\\*+$" (buffer-substring
8257 (point-at-bol) (point))))
8258 (- (match-end 0) (match-beginning 0)))
8259 ((and (bolp)
8260 (looking-at org-outline-regexp))
8261 (- (match-end 0) (point) 1))))
8262 (previous-level (save-excursion
8263 (condition-case nil
8264 (progn
8265 (outline-previous-visible-heading 1)
8266 (if (looking-at ^re_)
8267 (- (match-end 0) (match-beginning 0) 1)
8269 (error 1))))
8270 (next-level (save-excursion
8271 (condition-case nil
8272 (progn
8273 (or (looking-at org-outline-regexp)
8274 (outline-next-visible-heading 1))
8275 (if (looking-at ^re_)
8276 (- (match-end 0) (match-beginning 0) 1)
8278 (error 1))))
8279 (new-level (or force-level (max previous-level next-level)))
8280 (shift (if (or (= old-level -1)
8281 (= new-level -1)
8282 (= old-level new-level))
8284 (- new-level old-level)))
8285 (delta (if (> shift 0) -1 1))
8286 (func (if (> shift 0) 'org-demote 'org-promote))
8287 (org-odd-levels-only nil)
8288 beg end newend)
8289 ;; Remove the forced level indicator
8290 (when force-level
8291 (delete-region (point-at-bol) (point)))
8292 ;; Paste
8293 (beginning-of-line (if (bolp) 1 2))
8294 (setq beg (point))
8295 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8296 (insert-before-markers txt)
8297 (unless (string-suffix-p "\n" txt) (insert "\n"))
8298 (setq newend (point))
8299 (org-reinstall-markers-in-region beg)
8300 (setq end (point))
8301 (goto-char beg)
8302 (skip-chars-forward " \t\n\r")
8303 (setq beg (point))
8304 (when (and (org-invisible-p) visp)
8305 (save-excursion (outline-show-heading)))
8306 ;; Shift if necessary
8307 (unless (= shift 0)
8308 (save-restriction
8309 (narrow-to-region beg end)
8310 (while (not (= shift 0))
8311 (org-map-region func (point-min) (point-max))
8312 (setq shift (+ delta shift)))
8313 (goto-char (point-min))
8314 (setq newend (point-max))))
8315 (when (or (called-interactively-p 'interactive) for-yank)
8316 (message "Clipboard pasted as level %d subtree" new-level))
8317 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8318 kill-ring
8319 (eq org-subtree-clip (current-kill 0))
8320 org-subtree-clip-folded)
8321 ;; The tree was folded before it was killed/copied
8322 (outline-hide-subtree))
8323 (and for-yank (goto-char newend))
8324 (and remove (setq kill-ring (cdr kill-ring))))))
8326 (defun org-kill-is-subtree-p (&optional txt)
8327 "Check if the current kill is an outline subtree, or a set of trees.
8328 Returns nil if kill does not start with a headline, or if the first
8329 headline level is not the largest headline level in the tree.
8330 So this will actually accept several entries of equal levels as well,
8331 which is OK for `org-paste-subtree'.
8332 If optional TXT is given, check this string instead of the current kill."
8333 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8334 (re (org-get-limited-outline-regexp))
8335 (^re (concat "^" re))
8336 (start-level (and kill
8337 (string-match
8338 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8339 kill)
8340 (- (match-end 2) (match-beginning 2) 1)))
8341 (start (1+ (or (match-beginning 2) -1))))
8342 (if (not start-level)
8343 (progn
8344 nil) ;; does not even start with a heading
8345 (catch 'exit
8346 (while (setq start (string-match ^re kill (1+ start)))
8347 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8348 (throw 'exit nil)))
8349 t))))
8351 (defvar org-markers-to-move nil
8352 "Markers that should be moved with a cut-and-paste operation.
8353 Those markers are stored together with their positions relative to
8354 the start of the region.")
8356 (defun org-save-markers-in-region (beg end)
8357 "Check markers in region.
8358 If these markers are between BEG and END, record their position relative
8359 to BEG, so that after moving the block of text, we can put the markers back
8360 into place.
8361 This function gets called just before an entry or tree gets cut from the
8362 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8363 called immediately, to move the markers with the entries."
8364 (setq org-markers-to-move nil)
8365 (when (featurep 'org-clock)
8366 (org-clock-save-markers-for-cut-and-paste beg end))
8367 (when (featurep 'org-agenda)
8368 (org-agenda-save-markers-for-cut-and-paste beg end)))
8370 (defun org-check-and-save-marker (marker beg end)
8371 "Check if MARKER is between BEG and END.
8372 If yes, remember the marker and the distance to BEG."
8373 (when (and (marker-buffer marker)
8374 (equal (marker-buffer marker) (current-buffer))
8375 (>= marker beg) (< marker end))
8376 (push (cons marker (- marker beg)) org-markers-to-move)))
8378 (defun org-reinstall-markers-in-region (beg)
8379 "Move all remembered markers to their position relative to BEG."
8380 (dolist (x org-markers-to-move)
8381 (move-marker (car x) (+ beg (cdr x))))
8382 (setq org-markers-to-move nil))
8384 (defun org-narrow-to-subtree ()
8385 "Narrow buffer to the current subtree."
8386 (interactive)
8387 (save-excursion
8388 (save-match-data
8389 (org-with-limited-levels
8390 (narrow-to-region
8391 (progn (org-back-to-heading t) (point))
8392 (progn (org-end-of-subtree t t)
8393 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8394 (point)))))))
8396 (defun org-narrow-to-block ()
8397 "Narrow buffer to the current block."
8398 (interactive)
8399 (let* ((case-fold-search t)
8400 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8401 "^[ \t]*#\\+end_.*")))
8402 (if blockp
8403 (narrow-to-region (car blockp) (cdr blockp))
8404 (user-error "Not in a block"))))
8406 (defun org-clone-subtree-with-time-shift (n &optional shift)
8407 "Clone the task (subtree) at point N times.
8408 The clones will be inserted as siblings.
8410 In interactive use, the user will be prompted for the number of
8411 clones to be produced. If the entry has a timestamp, the user
8412 will also be prompted for a time shift, which may be a repeater
8413 as used in time stamps, for example `+3d'. To disable this,
8414 you can call the function with a universal prefix argument.
8416 When a valid repeater is given and the entry contains any time
8417 stamps, the clones will become a sequence in time, with time
8418 stamps in the subtree shifted for each clone produced. If SHIFT
8419 is nil or the empty string, time stamps will be left alone. The
8420 ID property of the original subtree is removed.
8422 In each clone, all the CLOCK entries will be removed. This
8423 prevents Org from considering that the clocked times overlap.
8425 If the original subtree did contain time stamps with a repeater,
8426 the following will happen:
8427 - the repeater will be removed in each clone
8428 - an additional clone will be produced, with the current, unshifted
8429 date(s) in the entry.
8430 - the original entry will be placed *after* all the clones, with
8431 repeater intact.
8432 - the start days in the repeater in the original entry will be shifted
8433 to past the last clone.
8434 In this way you can spell out a number of instances of a repeating task,
8435 and still retain the repeater to cover future instances of the task.
8437 As described above, N+1 clones are produced when the original
8438 subtree has a repeater. Setting N to 0, then, can be used to
8439 remove the repeater from a subtree and create a shifted clone
8440 with the original repeater."
8441 (interactive "nNumber of clones to produce: ")
8442 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8443 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8444 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8445 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8446 (shift
8447 (or shift
8448 (if (and (not (equal current-prefix-arg '(4)))
8449 (save-excursion
8450 (goto-char beg)
8451 (re-search-forward org-ts-regexp-both end-of-tree t)))
8452 (read-from-minibuffer
8453 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8454 ""))) ;No time shift
8455 (doshift
8456 (and (org-string-nw-p shift)
8457 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8458 shift)
8459 (user-error "Invalid shift specification %s" shift)))))
8460 (goto-char end-of-tree)
8461 (unless (bolp) (insert "\n"))
8462 (let* ((end (point))
8463 (template (buffer-substring beg end))
8464 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8465 (shift-what (pcase (and doshift (match-string 2 shift))
8466 (`nil nil)
8467 ("d" 'day)
8468 ("w" (setq shift-n (* 7 shift-n)) 'day)
8469 ("m" 'month)
8470 ("y" 'year)
8471 (_ (error "Unsupported time unit"))))
8472 (nmin 1)
8473 (nmax n)
8474 (n-no-remove -1)
8475 (idprop (org-entry-get nil "ID")))
8476 (when (and doshift
8477 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8478 template))
8479 (delete-region beg end)
8480 (setq end beg)
8481 (setq nmin 0)
8482 (setq nmax (1+ nmax))
8483 (setq n-no-remove nmax))
8484 (goto-char end)
8485 (cl-loop for n from nmin to nmax do
8486 (insert
8487 ;; Prepare clone.
8488 (with-temp-buffer
8489 (insert template)
8490 (org-mode)
8491 (goto-char (point-min))
8492 (org-show-subtree)
8493 (and idprop (if org-clone-delete-id
8494 (org-entry-delete nil "ID")
8495 (org-id-get-create t)))
8496 (unless (= n 0)
8497 (while (re-search-forward org-clock-line-re nil t)
8498 (delete-region (line-beginning-position)
8499 (line-beginning-position 2)))
8500 (goto-char (point-min))
8501 (while (re-search-forward org-drawer-regexp nil t)
8502 (org-remove-empty-drawer-at (point))))
8503 (goto-char (point-min))
8504 (when doshift
8505 (while (re-search-forward org-ts-regexp-both nil t)
8506 (org-timestamp-change (* n shift-n) shift-what))
8507 (unless (= n n-no-remove)
8508 (goto-char (point-min))
8509 (while (re-search-forward org-ts-regexp nil t)
8510 (save-excursion
8511 (goto-char (match-beginning 0))
8512 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8513 (delete-region (match-beginning 1) (match-end 1)))))))
8514 (buffer-string)))))
8515 (goto-char beg)))
8517 ;;; Outline Sorting
8519 (defun org-sort (&optional with-case)
8520 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8521 Optional argument WITH-CASE means sort case-sensitively."
8522 (interactive "P")
8523 (org-call-with-arg
8524 (cond ((org-at-table-p) #'org-table-sort-lines)
8525 ((org-at-item-p) #'org-sort-list)
8526 (t #'org-sort-entries))
8527 with-case))
8529 (defun org-sort-remove-invisible (s)
8530 "Remove invisible part of links and emphasis markers from string S."
8531 (remove-text-properties 0 (length s) org-rm-props s)
8532 (replace-regexp-in-string
8533 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8534 (replace-regexp-in-string
8535 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8536 (org-link-display-format s)
8537 t t) t t))
8539 (defvar org-priority-regexp) ; defined later in the file
8541 (defvar org-after-sorting-entries-or-items-hook nil
8542 "Hook that is run after a bunch of entries or items have been sorted.
8543 When children are sorted, the cursor is in the parent line when this
8544 hook gets called. When a region or a plain list is sorted, the cursor
8545 will be in the first entry of the sorted region/list.")
8547 (defun org-sort-entries
8548 (&optional with-case sorting-type getkey-func compare-func property
8549 interactive?)
8550 "Sort entries on a certain level of an outline tree.
8551 If there is an active region, the entries in the region are sorted.
8552 Else, if the cursor is before the first entry, sort the top-level items.
8553 Else, the children of the entry at point are sorted.
8555 Sorting can be alphabetically, numerically, by date/time as given by
8556 a time stamp, by a property, by priority order, or by a custom function.
8558 The command prompts for the sorting type unless it has been given to the
8559 function through the SORTING-TYPE argument, which needs to be a character,
8560 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8561 the precise meaning of each character:
8563 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8564 c By creation time, which is assumed to be the first inactive time stamp
8565 at the beginning of a line.
8566 d By deadline date/time.
8567 k By clocking time.
8568 n Numerically, by converting the beginning of the entry/item to a number.
8569 o By order of TODO keywords.
8570 p By priority according to the cookie.
8571 r By the value of a property.
8572 s By scheduled date/time.
8573 t By date/time, either the first active time stamp in the entry, or, if
8574 none exist, by the first inactive one.
8576 Capital letters will reverse the sort order.
8578 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8579 called with point at the beginning of the record. It must return a
8580 value that is compatible with COMPARE-FUNC, the function used to
8581 compare entries.
8583 Comparing entries ignores case by default. However, with an optional argument
8584 WITH-CASE, the sorting considers case as well.
8586 Sorting is done against the visible part of the headlines, it ignores hidden
8587 links.
8589 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8591 A non-nil value for INTERACTIVE? is used to signal that this
8592 function is being called interactively."
8593 (interactive (list current-prefix-arg nil nil nil nil t))
8594 (let ((case-func (if with-case 'identity 'downcase))
8595 start beg end stars re re2
8596 txt what tmp)
8597 ;; Find beginning and end of region to sort
8598 (cond
8599 ((org-region-active-p)
8600 ;; we will sort the region
8601 (setq end (region-end)
8602 what "region")
8603 (goto-char (region-beginning))
8604 (unless (org-at-heading-p) (outline-next-heading))
8605 (setq start (point)))
8606 ((or (org-at-heading-p)
8607 (ignore-errors (progn (org-back-to-heading) t)))
8608 ;; we will sort the children of the current headline
8609 (org-back-to-heading)
8610 (setq start (point)
8611 end (progn (org-end-of-subtree t t)
8612 (or (bolp) (insert "\n"))
8613 (when (>= (org-back-over-empty-lines) 1)
8614 (forward-line 1))
8615 (point))
8616 what "children")
8617 (goto-char start)
8618 (outline-show-subtree)
8619 (outline-next-heading))
8621 ;; we will sort the top-level entries in this file
8622 (goto-char (point-min))
8623 (or (org-at-heading-p) (outline-next-heading))
8624 (setq start (point))
8625 (goto-char (point-max))
8626 (beginning-of-line 1)
8627 (when (looking-at ".*?\\S-")
8628 ;; File ends in a non-white line
8629 (end-of-line 1)
8630 (insert "\n"))
8631 (setq end (point-max))
8632 (setq what "top-level")
8633 (goto-char start)
8634 (outline-show-all)))
8636 (setq beg (point))
8637 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8639 (looking-at "\\(\\*+\\)")
8640 (setq stars (match-string 1)
8641 re (concat "^" (regexp-quote stars) " +")
8642 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8643 txt (buffer-substring beg end))
8644 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8645 (when (and (not (equal stars "*")) (string-match re2 txt))
8646 (user-error "Region to sort contains a level above the first entry"))
8648 (unless sorting-type
8649 (message
8650 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8651 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8652 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8653 what)
8654 (setq sorting-type (read-char-exclusive)))
8656 (unless getkey-func
8657 (and (= (downcase sorting-type) ?f)
8658 (setq getkey-func
8659 (or (and interactive?
8660 (org-read-function
8661 "Function for extracting keys: "))
8662 (error "Missing key extractor")))))
8664 (and (= (downcase sorting-type) ?r)
8665 (not property)
8666 (setq property
8667 (completing-read "Property: "
8668 (mapcar #'list (org-buffer-property-keys t))
8669 nil t)))
8671 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8672 (message "Sorting entries...")
8674 (save-restriction
8675 (narrow-to-region start end)
8676 (let ((restore-clock?
8677 ;; The clock marker is lost when using `sort-subr'; mark
8678 ;; the clock with temporary `:org-clock-marker-backup'
8679 ;; text property.
8680 (when (and (eq (org-clock-is-active) (current-buffer))
8681 (<= start (marker-position org-clock-marker))
8682 (>= end (marker-position org-clock-marker)))
8683 (org-with-silent-modifications
8684 (put-text-property (1- org-clock-marker) org-clock-marker
8685 :org-clock-marker-backup t))
8687 (dcst (downcase sorting-type))
8688 (case-fold-search nil)
8689 (now (current-time)))
8690 (sort-subr
8691 (/= dcst sorting-type)
8692 ;; This function moves to the beginning character of the "record" to
8693 ;; be sorted.
8694 (lambda nil
8695 (if (re-search-forward re nil t)
8696 (goto-char (match-beginning 0))
8697 (goto-char (point-max))))
8698 ;; This function moves to the last character of the "record" being
8699 ;; sorted.
8700 (lambda nil
8701 (save-match-data
8702 (condition-case nil
8703 (outline-forward-same-level 1)
8704 (error
8705 (goto-char (point-max))))))
8706 ;; This function returns the value that gets sorted against.
8707 (lambda nil
8708 (cond
8709 ((= dcst ?n)
8710 (if (looking-at org-complex-heading-regexp)
8711 (string-to-number (org-sort-remove-invisible (match-string 4)))
8712 nil))
8713 ((= dcst ?a)
8714 (if (looking-at org-complex-heading-regexp)
8715 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8716 nil))
8717 ((= dcst ?k)
8718 (or (get-text-property (point) :org-clock-minutes) 0))
8719 ((= dcst ?t)
8720 (let ((end (save-excursion (outline-next-heading) (point))))
8721 (if (or (re-search-forward org-ts-regexp end t)
8722 (re-search-forward org-ts-regexp-both end t))
8723 (org-time-string-to-seconds (match-string 0))
8724 (float-time now))))
8725 ((= dcst ?c)
8726 (let ((end (save-excursion (outline-next-heading) (point))))
8727 (if (re-search-forward
8728 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8729 end t)
8730 (org-time-string-to-seconds (match-string 0))
8731 (float-time now))))
8732 ((= dcst ?s)
8733 (let ((end (save-excursion (outline-next-heading) (point))))
8734 (if (re-search-forward org-scheduled-time-regexp end t)
8735 (org-time-string-to-seconds (match-string 1))
8736 (float-time now))))
8737 ((= dcst ?d)
8738 (let ((end (save-excursion (outline-next-heading) (point))))
8739 (if (re-search-forward org-deadline-time-regexp end t)
8740 (org-time-string-to-seconds (match-string 1))
8741 (float-time now))))
8742 ((= dcst ?p)
8743 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8744 (string-to-char (match-string 2))
8745 org-default-priority))
8746 ((= dcst ?r)
8747 (or (org-entry-get nil property) ""))
8748 ((= dcst ?o)
8749 (when (looking-at org-complex-heading-regexp)
8750 (let* ((m (match-string 2))
8751 (s (if (member m org-done-keywords) '- '+)))
8752 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8753 ((= dcst ?f)
8754 (if getkey-func
8755 (progn
8756 (setq tmp (funcall getkey-func))
8757 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8758 tmp)
8759 (error "Invalid key function `%s'" getkey-func)))
8760 (t (error "Invalid sorting type `%c'" sorting-type))))
8762 (cond
8763 ((= dcst ?a) 'string<)
8764 ((= dcst ?f)
8765 (or compare-func
8766 (and interactive?
8767 (org-read-function
8768 (concat "Function for comparing keys "
8769 "(empty for default `sort-subr' predicate): ")
8770 'allow-empty))))
8771 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
8772 (when restore-clock?
8773 (move-marker org-clock-marker
8774 (1+ (next-single-property-change
8775 start :org-clock-marker-backup)))
8776 (remove-text-properties (1- org-clock-marker) org-clock-marker
8777 '(:org-clock-marker-backup t)))))
8778 (run-hooks 'org-after-sorting-entries-or-items-hook)
8779 (message "Sorting entries...done")))
8781 ;;; The orgstruct minor mode
8783 ;; Define a minor mode which can be used in other modes in order to
8784 ;; integrate the Org mode structure editing commands.
8786 ;; This is really a hack, because the Org mode structure commands use
8787 ;; keys which normally belong to the major mode. Here is how it
8788 ;; works: The minor mode defines all the keys necessary to operate the
8789 ;; structure commands, but wraps the commands into a function which
8790 ;; tests if the cursor is currently at a headline or a plain list
8791 ;; item. If that is the case, the structure command is used,
8792 ;; temporarily setting many Org mode variables like regular
8793 ;; expressions for filling etc. However, when any of those keys is
8794 ;; used at a different location, function uses `key-binding' to look
8795 ;; up if the key has an associated command in another currently active
8796 ;; keymap (minor modes, major mode, global), and executes that
8797 ;; command. There might be problems if any of the keys is otherwise
8798 ;; used as a prefix key.
8800 (defcustom orgstruct-heading-prefix-regexp ""
8801 "Regexp that matches the custom prefix of Org headlines in
8802 orgstruct(++)-mode."
8803 :group 'org
8804 :version "26.1"
8805 :package-version '(Org . "8.3")
8806 :type 'regexp)
8807 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8809 (defcustom orgstruct-setup-hook nil
8810 "Hook run after orgstruct-mode-map is filled."
8811 :group 'org
8812 :version "24.4"
8813 :package-version '(Org . "8.0")
8814 :type 'hook)
8816 (defvar orgstruct-initialized nil)
8818 (defvar org-local-vars nil
8819 "List of local variables, for use by `orgstruct-mode'.")
8821 ;;;###autoload
8822 (define-minor-mode orgstruct-mode
8823 "Toggle the minor mode `orgstruct-mode'.
8824 This mode is for using Org mode structure commands in other
8825 modes. The following keys behave as if Org mode were active, if
8826 the cursor is on a headline, or on a plain list item (both as
8827 defined by Org mode)."
8828 nil " OrgStruct" (make-sparse-keymap)
8829 (funcall (if orgstruct-mode
8830 'add-to-invisibility-spec
8831 'remove-from-invisibility-spec)
8832 '(outline . t))
8833 (when orgstruct-mode
8834 (org-load-modules-maybe)
8835 (unless orgstruct-initialized
8836 (orgstruct-setup)
8837 (setq orgstruct-initialized t))))
8839 ;;;###autoload
8840 (defun turn-on-orgstruct ()
8841 "Unconditionally turn on `orgstruct-mode'."
8842 (orgstruct-mode 1))
8844 (defvar-local orgstruct-is-++ nil
8845 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8846 (defvar-local org-fb-vars nil)
8847 (defun orgstruct++-mode (&optional arg)
8848 "Toggle `orgstruct-mode', the enhanced version of it.
8849 In addition to setting orgstruct-mode, this also exports all
8850 indentation and autofilling variables from Org mode into the
8851 buffer. It will also recognize item context in multiline items."
8852 (interactive "P")
8853 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8854 (if (< arg 1)
8855 (progn (orgstruct-mode -1)
8856 (dolist (v org-fb-vars)
8857 (set (make-local-variable (car v))
8858 (if (eq (car-safe (cadr v)) 'quote)
8859 (cl-cadadr v)
8860 (nth 1 v)))))
8861 (orgstruct-mode 1)
8862 (setq org-fb-vars nil)
8863 (unless org-local-vars
8864 (setq org-local-vars (org-get-local-variables)))
8865 (let (var val)
8866 (dolist (x org-local-vars)
8867 (when (string-match
8868 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
8869 \\|fill-prefix\\|indent-\\)"
8870 (symbol-name (car x)))
8871 (setq var (car x) val (nth 1 x))
8872 (push (list var `(quote ,(eval var))) org-fb-vars)
8873 (set (make-local-variable var)
8874 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8875 (setq-local orgstruct-is-++ t))))
8877 ;;;###autoload
8878 (defun turn-on-orgstruct++ ()
8879 "Unconditionally turn on `orgstruct++-mode'."
8880 (orgstruct++-mode 1))
8882 (defun orgstruct-error ()
8883 "Error when there is no default binding for a structure key."
8884 (interactive)
8885 (funcall (if (fboundp 'user-error)
8886 'user-error
8887 'error)
8888 "This key has no function outside structure elements"))
8890 (defun orgstruct-setup ()
8891 "Setup orgstruct keymap."
8892 (dolist (cell '((org-demote . t)
8893 (org-metaleft . t)
8894 (org-metaright . t)
8895 (org-promote . t)
8896 (org-shiftmetaleft . t)
8897 (org-shiftmetaright . t)
8898 org-backward-element
8899 org-backward-heading-same-level
8900 org-ctrl-c-ret
8901 org-ctrl-c-minus
8902 org-ctrl-c-star
8903 org-cycle
8904 org-force-cycle-archived
8905 org-forward-heading-same-level
8906 org-insert-heading
8907 org-insert-heading-respect-content
8908 org-kill-note-or-show-branches
8909 org-mark-subtree
8910 org-meta-return
8911 org-metadown
8912 org-metaup
8913 org-narrow-to-subtree
8914 org-promote-subtree
8915 org-reveal
8916 org-shiftdown
8917 org-shiftleft
8918 org-shiftmetadown
8919 org-shiftmetaup
8920 org-shiftright
8921 org-shifttab
8922 org-shifttab
8923 org-shiftup
8924 org-show-children
8925 org-show-subtree
8926 org-sort
8927 org-up-element
8928 outline-demote
8929 outline-next-visible-heading
8930 outline-previous-visible-heading
8931 outline-promote
8932 outline-up-heading))
8933 (let ((f (or (car-safe cell) cell))
8934 (disable-when-heading-prefix (cdr-safe cell)))
8935 (when (fboundp f)
8936 (let ((new-bindings))
8937 (dolist (binding (nconc (where-is-internal f org-mode-map)
8938 (where-is-internal f outline-mode-map)))
8939 (push binding new-bindings)
8940 ;; TODO use local-function-key-map
8941 (dolist (rep '(("<tab>" . "TAB")
8942 ("<return>" . "RET")
8943 ("<escape>" . "ESC")
8944 ("<delete>" . "DEL")))
8945 (setq binding (read-kbd-macro
8946 (let ((case-fold-search))
8947 (replace-regexp-in-string
8948 (regexp-quote (cdr rep))
8949 (car rep)
8950 (key-description binding)))))
8951 (cl-pushnew binding new-bindings :test 'equal)))
8952 (dolist (binding new-bindings)
8953 (let ((key (lookup-key orgstruct-mode-map binding)))
8954 (when (or (not key) (numberp key))
8955 (ignore-errors
8956 (org-defkey orgstruct-mode-map
8957 binding
8958 (orgstruct-make-binding
8959 f binding disable-when-heading-prefix))))))))))
8960 (run-hooks 'orgstruct-setup-hook))
8962 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8963 "Create a function for binding in the structure minor mode.
8964 FUN is the command to call inside a table. KEY is the key that
8965 should be checked in for a command to execute outside of tables.
8966 Non-nil `disable-when-heading-prefix' means to disable the command
8967 if `orgstruct-heading-prefix-regexp' is not empty."
8968 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8969 (let ((nname name)
8970 (i 0))
8971 (while (fboundp (intern nname))
8972 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8973 (setq name (intern nname)))
8974 (eval
8975 (let ((bindings '((org-heading-regexp
8976 (concat "^"
8977 orgstruct-heading-prefix-regexp
8978 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8979 (org-outline-regexp
8980 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8981 (org-outline-regexp-bol
8982 (concat "^" org-outline-regexp))
8983 (outline-regexp org-outline-regexp)
8984 (outline-heading-end-regexp "\n")
8985 (outline-level 'org-outline-level)
8986 (outline-heading-alist))))
8987 `(defun ,name (arg)
8988 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8989 "Outside of structure, run the binding of `"
8990 (key-description key) "'."
8991 (when disable-when-heading-prefix
8992 (concat
8993 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
8994 "back to the default binding due to limitations of Org's implementation of\n"
8995 "`" (symbol-name fun) "'.")))
8996 (interactive "p")
8997 (let* ((disable
8998 ,(and disable-when-heading-prefix
8999 '(not (string= orgstruct-heading-prefix-regexp ""))))
9000 (fallback
9001 (or disable
9002 (not
9003 (let* ,bindings
9004 (org-context-p 'headline 'item
9005 ,(when (memq fun
9006 '(org-insert-heading
9007 org-insert-heading-respect-content
9008 org-meta-return))
9009 '(when orgstruct-is-++
9010 'item-body))))))))
9011 (if fallback
9012 (let* ((orgstruct-mode)
9013 (binding
9014 (let ((key ,key))
9015 (catch 'exit
9016 (dolist
9017 (rep
9018 '(nil
9019 ("<\\([^>]*\\)tab>" . "\\1TAB")
9020 ("<\\([^>]*\\)return>" . "\\1RET")
9021 ("<\\([^>]*\\)escape>" . "\\1ESC")
9022 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9023 nil)
9024 (when rep
9025 (setq key (read-kbd-macro
9026 (let ((case-fold-search))
9027 (replace-regexp-in-string
9028 (car rep)
9029 (cdr rep)
9030 (key-description key))))))
9031 (when (key-binding key)
9032 (throw 'exit (key-binding key))))))))
9033 (if (keymapp binding)
9034 (org-set-transient-map binding)
9035 (let ((func (or binding
9036 (unless disable
9037 'orgstruct-error))))
9038 (when func
9039 (call-interactively func)))))
9040 (org-run-like-in-org-mode
9041 (lambda ()
9042 (interactive)
9043 (let* ,bindings
9044 (call-interactively ',fun)))))))))
9045 name))
9047 (defun org-contextualize-keys (alist contexts)
9048 "Return valid elements in ALIST depending on CONTEXTS.
9050 `org-agenda-custom-commands' or `org-capture-templates' are the
9051 values used for ALIST, and `org-agenda-custom-commands-contexts'
9052 or `org-capture-templates-contexts' are the associated contexts
9053 definitions."
9054 (let ((contexts
9055 ;; normalize contexts
9056 (mapcar
9057 (lambda(c) (cond ((listp (cadr c))
9058 (list (car c) (car c) (nth 1 c)))
9059 ((string= "" (cadr c))
9060 (list (car c) (car c) (nth 2 c)))
9061 (t c)))
9062 contexts))
9063 (a alist) r s)
9064 ;; loop over all commands or templates
9065 (dolist (c a)
9066 (let (vrules repl)
9067 (cond
9068 ((not (assoc (car c) contexts))
9069 (push c r))
9070 ((and (assoc (car c) contexts)
9071 (setq vrules (org-contextualize-validate-key
9072 (car c) contexts)))
9073 (mapc (lambda (vr)
9074 (unless (equal (car vr) (cadr vr))
9075 (setq repl vr)))
9076 vrules)
9077 (if (not repl) (push c r)
9078 (push (cadr repl) s)
9079 (push
9080 (cons (car c)
9081 (cdr (or (assoc (cadr repl) alist)
9082 (error "Undefined key `%s' as contextual replacement for `%s'"
9083 (cadr repl) (car c)))))
9084 r))))))
9085 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9086 (delq
9088 (delete-dups
9089 (mapcar (lambda (x)
9090 (let ((tpl (car x)))
9091 (unless (delq
9093 (mapcar (lambda (y)
9094 (equal y tpl))
9096 x)))
9097 (reverse r))))))
9099 (defun org-contextualize-validate-key (key contexts)
9100 "Check CONTEXTS for agenda or capture KEY."
9101 (let (res)
9102 (dolist (r contexts)
9103 (dolist (rr (car (last r)))
9104 (when
9105 (and (equal key (car r))
9106 (if (functionp rr) (funcall rr)
9107 (or (and (eq (car rr) 'in-file)
9108 (buffer-file-name)
9109 (string-match (cdr rr) (buffer-file-name)))
9110 (and (eq (car rr) 'in-mode)
9111 (string-match (cdr rr) (symbol-name major-mode)))
9112 (and (eq (car rr) 'in-buffer)
9113 (string-match (cdr rr) (buffer-name)))
9114 (when (and (eq (car rr) 'not-in-file)
9115 (buffer-file-name))
9116 (not (string-match (cdr rr) (buffer-file-name))))
9117 (when (eq (car rr) 'not-in-mode)
9118 (not (string-match (cdr rr) (symbol-name major-mode))))
9119 (when (eq (car rr) 'not-in-buffer)
9120 (not (string-match (cdr rr) (buffer-name)))))))
9121 (push r res))))
9122 (delete-dups (delq nil res))))
9124 (defun org-context-p (&rest contexts)
9125 "Check if local context is any of CONTEXTS.
9126 Possible values in the list of contexts are `table', `headline', and `item'."
9127 (let ((pos (point)))
9128 (goto-char (point-at-bol))
9129 (prog1 (or (and (memq 'table contexts)
9130 (looking-at "[ \t]*|"))
9131 (and (memq 'headline contexts)
9132 (looking-at org-outline-regexp))
9133 (and (memq 'item contexts)
9134 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9135 (and (memq 'item-body contexts)
9136 (org-in-item-p)))
9137 (goto-char pos))))
9139 ;;;###autoload
9140 (defun org-run-like-in-org-mode (cmd)
9141 "Run a command, pretending that the current buffer is in Org mode.
9142 This will temporarily bind local variables that are typically bound in
9143 Org mode to the values they have in Org mode, and then interactively
9144 call CMD."
9145 (org-load-modules-maybe)
9146 (unless org-local-vars
9147 (setq org-local-vars (org-get-local-variables)))
9148 (let (binds)
9149 (dolist (var org-local-vars)
9150 (when (or (not (boundp (car var)))
9151 (eq (symbol-value (car var))
9152 (default-value (car var))))
9153 (push (list (car var) `(quote ,(cadr var))) binds)))
9154 (eval `(let ,binds
9155 (call-interactively (quote ,cmd))))))
9157 (defun org-get-category (&optional pos force-refresh)
9158 "Get the category applying to position POS."
9159 (save-match-data
9160 (when force-refresh (org-refresh-category-properties))
9161 (let ((pos (or pos (point))))
9162 (or (get-text-property pos 'org-category)
9163 (progn (org-refresh-category-properties)
9164 (get-text-property pos 'org-category))))))
9166 ;;; Refresh properties
9168 (defun org-refresh-properties (dprop tprop)
9169 "Refresh buffer text properties.
9170 DPROP is the drawer property and TPROP is either the
9171 corresponding text property to set, or an alist with each element
9172 being a text property (as a symbol) and a function to apply to
9173 the value of the drawer property."
9174 (let* ((case-fold-search t)
9175 (inhibit-read-only t)
9176 (inherit? (org-property-inherit-p dprop))
9177 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9178 (global (and inherit? (org--property-global-value dprop nil))))
9179 (org-with-silent-modifications
9180 (org-with-point-at 1
9181 ;; Set global values (e.g., values defined through
9182 ;; "#+PROPERTY:" keywords) to the whole buffer.
9183 (when global (put-text-property (point-min) (point-max) tprop global))
9184 ;; Set local values.
9185 (while (re-search-forward property-re nil t)
9186 (when (org-at-property-p)
9187 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9188 (outline-next-heading))))))
9190 (defun org-refresh-property (tprop p &optional inherit)
9191 "Refresh the buffer text property TPROP from the drawer property P.
9192 The refresh happens only for the current headline, or the whole
9193 sub-tree if optional argument INHERIT is non-nil."
9194 (unless (org-before-first-heading-p)
9195 (save-excursion
9196 (org-back-to-heading t)
9197 (let ((start (point))
9198 (end (save-excursion
9199 (if inherit (org-end-of-subtree t t)
9200 (or (outline-next-heading) (point-max))))))
9201 (if (symbolp tprop)
9202 ;; TPROP is a text property symbol.
9203 (put-text-property start end tprop p)
9204 ;; TPROP is an alist with (property . function) elements.
9205 (pcase-dolist (`(,prop . ,f) tprop)
9206 (put-text-property start end prop (funcall f p))))))))
9208 (defun org-refresh-category-properties ()
9209 "Refresh category text properties in the buffer."
9210 (let ((case-fold-search t)
9211 (inhibit-read-only t)
9212 (default-category
9213 (cond ((null org-category)
9214 (if buffer-file-name
9215 (file-name-sans-extension
9216 (file-name-nondirectory buffer-file-name))
9217 "???"))
9218 ((symbolp org-category) (symbol-name org-category))
9219 (t org-category))))
9220 (org-with-silent-modifications
9221 (org-with-wide-buffer
9222 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9223 ;; This is the default category for the buffer. If none is
9224 ;; found, fall-back to `org-category' or buffer file name.
9225 (put-text-property
9226 (point-min) (point-max)
9227 'org-category
9228 (catch 'buffer-category
9229 (goto-char (point-max))
9230 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9231 (let ((element (org-element-at-point)))
9232 (when (eq (org-element-type element) 'keyword)
9233 (throw 'buffer-category
9234 (org-element-property :value element)))))
9235 default-category))
9236 ;; Set sub-tree specific categories.
9237 (goto-char (point-min))
9238 (let ((regexp (org-re-property "CATEGORY")))
9239 (while (re-search-forward regexp nil t)
9240 (let ((value (match-string-no-properties 3)))
9241 (when (org-at-property-p)
9242 (put-text-property
9243 (save-excursion (org-back-to-heading t) (point))
9244 (save-excursion (org-end-of-subtree t t) (point))
9245 'org-category
9246 value)))))))))
9248 (defun org-refresh-stats-properties ()
9249 "Refresh stats text properties in the buffer."
9250 (org-with-silent-modifications
9251 (org-with-point-at 1
9252 (let ((regexp (concat org-outline-regexp-bol
9253 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9254 (while (re-search-forward regexp nil t)
9255 (let* ((numerator (string-to-number (match-string 1)))
9256 (denominator (and (match-end 2)
9257 (string-to-number (match-string 2))))
9258 (stats (cond ((not denominator) numerator) ;percent
9259 ((= denominator 0) 0)
9260 (t (/ (* numerator 100) denominator)))))
9261 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9262 'org-stats stats)))))))
9264 (defun org-refresh-effort-properties ()
9265 "Refresh effort properties"
9266 (org-refresh-properties
9267 org-effort-property
9268 '((effort . identity)
9269 (effort-minutes . org-duration-to-minutes))))
9271 ;;;; Link Stuff
9273 ;;; Link abbreviations
9275 (defun org-link-expand-abbrev (link)
9276 "Apply replacements as defined in `org-link-abbrev-alist'."
9277 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9278 (let* ((key (match-string 1 link))
9279 (as (or (assoc key org-link-abbrev-alist-local)
9280 (assoc key org-link-abbrev-alist)))
9281 (tag (and (match-end 2) (match-string 3 link)))
9282 rpl)
9283 (if (not as)
9284 link
9285 (setq rpl (cdr as))
9286 (cond
9287 ((symbolp rpl) (funcall rpl tag))
9288 ((string-match "%(\\([^)]+\\))" rpl)
9289 (replace-match
9290 (save-match-data
9291 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9292 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9293 ((string-match "%h" rpl)
9294 (replace-match (url-hexify-string (or tag "")) t t rpl))
9295 (t (concat rpl tag)))))
9296 link))
9298 ;;; Storing and inserting links
9300 (defvar org-insert-link-history nil
9301 "Minibuffer history for links inserted with `org-insert-link'.")
9303 (defvar org-stored-links nil
9304 "Contains the links stored with `org-store-link'.")
9306 (defvar org-store-link-plist nil
9307 "Plist with info about the most recently link created with `org-store-link'.")
9309 (defun org-store-link-functions ()
9310 "Return a list of functions that are called to create and store a link.
9311 The functions defined in the :store property of
9312 `org-link-parameters'.
9314 Each function will be called in turn until one returns a non-nil
9315 value. Each function should check if it is responsible for
9316 creating this link (for example by looking at the major mode).
9317 If not, it must exit and return nil. If yes, it should return
9318 a non-nil value after calling `org-store-link-props' with a list
9319 of properties and values. Special properties are:
9321 :type The link prefix, like \"http\". This must be given.
9322 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9323 This is obligatory as well.
9324 :description Optional default description for the second pair
9325 of brackets in an Org mode link. The user can still change
9326 this when inserting this link into an Org mode buffer.
9328 In addition to these, any additional properties can be specified
9329 and then used in capture templates."
9330 (cl-loop for link in org-link-parameters
9331 with store-func
9332 do (setq store-func (org-link-get-parameter (car link) :store))
9333 if store-func
9334 collect store-func))
9336 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9337 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9339 ;;;###autoload
9340 (defun org-store-link (arg)
9341 "Store an org-link to the current location.
9342 \\<org-mode-map>
9343 This link is added to `org-stored-links' and can later be inserted
9344 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9346 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9347 A single
9348 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9349 `org-gnus-prefer-web-links' for links to Usenet articles.
9351 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9352 skipping storing functions that are not
9353 part of Org core.
9355 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9356 prefix ARG forces storing a link for each line in the
9357 active region."
9358 (interactive "P")
9359 (org-load-modules-maybe)
9360 (if (and (equal arg '(64)) (org-region-active-p))
9361 (save-excursion
9362 (let ((end (region-end)))
9363 (goto-char (region-beginning))
9364 (set-mark (point))
9365 (while (< (point-at-eol) end)
9366 (move-end-of-line 1) (activate-mark)
9367 (let (current-prefix-arg)
9368 (call-interactively 'org-store-link))
9369 (move-beginning-of-line 2)
9370 (set-mark (point)))))
9371 (setq org-store-link-plist nil)
9372 (let (link cpltxt desc description search
9373 txt custom-id agenda-link sfuns sfunsn)
9374 (cond
9376 ;; Store a link using an external link type
9377 ((and (not (equal arg '(16)))
9378 (setq sfuns
9379 (delq
9380 nil (mapcar (lambda (f)
9381 (let (fs) (if (funcall f) (push f fs))))
9382 (org-store-link-functions)))
9383 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9384 (or (and (cdr sfuns)
9385 (funcall (intern
9386 (completing-read
9387 "Which function for creating the link? "
9388 sfunsn nil t (car sfunsn)))))
9389 (funcall (caar sfuns)))
9390 (setq link (plist-get org-store-link-plist :link)
9391 desc (or (plist-get org-store-link-plist
9392 :description)
9393 link))))
9395 ;; Store a link from a source code buffer.
9396 ((org-src-edit-buffer-p)
9397 (let ((coderef-format (org-src-coderef-format)))
9398 (cond ((save-excursion
9399 (beginning-of-line)
9400 (looking-at (org-src-coderef-regexp coderef-format)))
9401 (setq link (format "(%s)" (match-string-no-properties 3))))
9402 ((called-interactively-p 'any)
9403 (let ((label (read-string "Code line label: ")))
9404 (end-of-line)
9405 (setq link (format coderef-format label))
9406 (let ((gc (- 79 (length link))))
9407 (if (< (current-column) gc)
9408 (org-move-to-column gc t)
9409 (insert " ")))
9410 (insert link)
9411 (setq link (concat "(" label ")"))
9412 (setq desc nil)))
9413 (t (setq link nil)))))
9415 ;; We are in the agenda, link to referenced location
9416 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9417 (let ((m (or (get-text-property (point) 'org-hd-marker)
9418 (get-text-property (point) 'org-marker))))
9419 (when m
9420 (org-with-point-at m
9421 (setq agenda-link
9422 (if (called-interactively-p 'any)
9423 (call-interactively 'org-store-link)
9424 (org-store-link nil)))))))
9426 ((eq major-mode 'calendar-mode)
9427 (let ((cd (calendar-cursor-to-date)))
9428 (setq link
9429 (format-time-string
9430 (car org-time-stamp-formats)
9431 (apply 'encode-time
9432 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9433 nil nil nil))))
9434 (org-store-link-props :type "calendar" :date cd)))
9436 ((eq major-mode 'help-mode)
9437 (setq link (concat "help:" (save-excursion
9438 (goto-char (point-min))
9439 (looking-at "^[^ ]+")
9440 (match-string 0))))
9441 (org-store-link-props :type "help"))
9443 ((eq major-mode 'w3-mode)
9444 (setq cpltxt (if (and (buffer-name)
9445 (not (string-match "Untitled" (buffer-name))))
9446 (buffer-name)
9447 (url-view-url t))
9448 link (url-view-url t))
9449 (org-store-link-props :type "w3" :url (url-view-url t)))
9451 ((eq major-mode 'image-mode)
9452 (setq cpltxt (concat "file:"
9453 (abbreviate-file-name buffer-file-name))
9454 link cpltxt)
9455 (org-store-link-props :type "image" :file buffer-file-name))
9457 ;; In dired, store a link to the file of the current line
9458 ((derived-mode-p 'dired-mode)
9459 (let ((file (dired-get-filename nil t)))
9460 (setq file (if file
9461 (abbreviate-file-name
9462 (expand-file-name (dired-get-filename nil t)))
9463 ;; otherwise, no file so use current directory.
9464 default-directory))
9465 (setq cpltxt (concat "file:" file)
9466 link cpltxt)))
9468 ((setq search (run-hook-with-args-until-success
9469 'org-create-file-search-functions))
9470 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9471 "::" search))
9472 (setq cpltxt (or description link)))
9474 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9475 (org-with-limited-levels
9476 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9477 (cond
9478 ;; Store a link using the target at point
9479 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9480 (setq cpltxt
9481 (concat "file:"
9482 (abbreviate-file-name
9483 (buffer-file-name (buffer-base-buffer)))
9484 "::" (match-string 1))
9485 link cpltxt))
9486 ((and (featurep 'org-id)
9487 (or (eq org-id-link-to-org-use-id t)
9488 (and (called-interactively-p 'any)
9489 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9490 (and (eq org-id-link-to-org-use-id
9491 'create-if-interactive-and-no-custom-id)
9492 (not custom-id))))
9493 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9494 ;; Store a link using the ID at point
9495 (setq link (condition-case nil
9496 (prog1 (org-id-store-link)
9497 (setq desc (or (plist-get org-store-link-plist
9498 :description)
9499 "")))
9500 (error
9501 ;; Probably before first headline, link only to file
9502 (concat "file:"
9503 (abbreviate-file-name
9504 (buffer-file-name (buffer-base-buffer))))))))
9506 ;; Just link to current headline
9507 (setq cpltxt (concat "file:"
9508 (abbreviate-file-name
9509 (buffer-file-name (buffer-base-buffer)))))
9510 ;; Add a context search string
9511 (when (org-xor org-context-in-file-links
9512 (equal arg '(4)))
9513 (let* ((element (org-element-at-point))
9514 (name (org-element-property :name element)))
9515 (setq txt (cond
9516 ((org-at-heading-p) nil)
9517 (name)
9518 ((org-region-active-p)
9519 (buffer-substring (region-beginning) (region-end)))))
9520 (when (or (null txt) (string-match "\\S-" txt))
9521 (setq cpltxt
9522 (concat cpltxt "::"
9523 (condition-case nil
9524 (org-make-org-heading-search-string txt)
9525 (error "")))
9526 desc (or name
9527 (nth 4 (ignore-errors (org-heading-components)))
9528 "NONE")))))
9529 (when (string-match "::\\'" cpltxt)
9530 (setq cpltxt (substring cpltxt 0 -2)))
9531 (setq link cpltxt)))))
9533 ((buffer-file-name (buffer-base-buffer))
9534 ;; Just link to this file here.
9535 (setq cpltxt (concat "file:"
9536 (abbreviate-file-name
9537 (buffer-file-name (buffer-base-buffer)))))
9538 ;; Add a context string.
9539 (when (org-xor org-context-in-file-links
9540 (equal arg '(4)))
9541 (setq txt (if (org-region-active-p)
9542 (buffer-substring (region-beginning) (region-end))
9543 (buffer-substring (point-at-bol) (point-at-eol))))
9544 ;; Only use search option if there is some text.
9545 (when (string-match "\\S-" txt)
9546 (setq cpltxt
9547 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9548 desc "NONE")))
9549 (setq link cpltxt))
9551 ((called-interactively-p 'interactive)
9552 (user-error "No method for storing a link from this buffer"))
9554 (t (setq link nil)))
9556 ;; We're done setting link and desc, clean up
9557 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9558 (setq link (or link cpltxt)
9559 desc (or desc cpltxt))
9560 (cond ((not desc))
9561 ((equal desc "NONE") (setq desc nil))
9562 (t (setq desc
9563 (replace-regexp-in-string
9564 org-bracket-link-analytic-regexp
9565 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9566 desc))))
9567 ;; Return the link
9568 (if (not (and (or (called-interactively-p 'any)
9569 executing-kbd-macro)
9570 link))
9571 (or agenda-link (and link (org-make-link-string link desc)))
9572 (push (list link desc) org-stored-links)
9573 (message "Stored: %s" (or desc link))
9574 (when custom-id
9575 (setq link (concat "file:" (abbreviate-file-name
9576 (buffer-file-name)) "::#" custom-id))
9577 (push (list link desc) org-stored-links))
9578 (car org-stored-links)))))
9580 (defun org-store-link-props (&rest plist)
9581 "Store link properties.
9582 The properties are pre-processed by extracting names, addresses
9583 and dates."
9584 (let ((x (plist-get plist :from)))
9585 (when x
9586 (let ((adr (mail-extract-address-components x)))
9587 (setq plist (plist-put plist :fromname (car adr)))
9588 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9589 (let ((x (plist-get plist :to)))
9590 (when x
9591 (let ((adr (mail-extract-address-components x)))
9592 (setq plist (plist-put plist :toname (car adr)))
9593 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9594 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9595 (when x
9596 (setq plist (plist-put plist :date-timestamp
9597 (format-time-string
9598 (org-time-stamp-format t) x)))
9599 (setq plist (plist-put plist :date-timestamp-inactive
9600 (format-time-string
9601 (org-time-stamp-format t t) x)))))
9602 (let ((from (plist-get plist :from))
9603 (to (plist-get plist :to)))
9604 (when (and from to org-from-is-user-regexp)
9605 (setq plist
9606 (plist-put plist :fromto
9607 (if (string-match org-from-is-user-regexp from)
9608 (concat "to %t")
9609 (concat "from %f"))))))
9610 (setq org-store-link-plist plist))
9612 (defun org-add-link-props (&rest plist)
9613 "Add these properties to the link property list."
9614 (let (key value)
9615 (while plist
9616 (setq key (pop plist) value (pop plist))
9617 (setq org-store-link-plist
9618 (plist-put org-store-link-plist key value)))))
9620 (defun org-email-link-description (&optional fmt)
9621 "Return the description part of an email link.
9622 This takes information from `org-store-link-plist' and formats it
9623 according to FMT (default from `org-email-link-description-format')."
9624 (setq fmt (or fmt org-email-link-description-format))
9625 (let* ((p org-store-link-plist)
9626 (to (plist-get p :toaddress))
9627 (from (plist-get p :fromaddress))
9628 (table
9629 (list
9630 (cons "%c" (plist-get p :fromto))
9631 (cons "%F" (plist-get p :from))
9632 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9633 (cons "%T" (plist-get p :to))
9634 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9635 (cons "%s" (plist-get p :subject))
9636 (cons "%d" (plist-get p :date))
9637 (cons "%m" (plist-get p :message-id)))))
9638 (when (string-match "%c" fmt)
9639 ;; Check if the user wrote this message
9640 (if (and org-from-is-user-regexp from to
9641 (save-match-data (string-match org-from-is-user-regexp from)))
9642 (setq fmt (replace-match "to %t" t t fmt))
9643 (setq fmt (replace-match "from %f" t t fmt))))
9644 (org-replace-escapes fmt table)))
9646 (defun org-make-org-heading-search-string (&optional string)
9647 "Make search string for the current headline or STRING."
9648 (let ((s (or string
9649 (and (derived-mode-p 'org-mode)
9650 (save-excursion
9651 (org-back-to-heading t)
9652 (org-element-property :raw-value (org-element-at-point))))))
9653 (lines org-context-in-file-links))
9654 (unless string (setq s (concat "*" s))) ;Add * for headlines
9655 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9656 (when (and string (integerp lines) (> lines 0))
9657 (let ((slines (org-split-string s "\n")))
9658 (when (< lines (length slines))
9659 (setq s (mapconcat
9660 'identity
9661 (reverse (nthcdr (- (length slines) lines)
9662 (reverse slines))) "\n")))))
9663 (mapconcat #'identity (split-string s) " ")))
9665 (defun org-make-link-string (link &optional description)
9666 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9667 (unless (org-string-nw-p link) (error "Empty link"))
9668 (let ((uri (cond ((string-match org-link-types-re link)
9669 (concat (match-string 1 link)
9670 (org-link-escape (substring link (match-end 1)))))
9671 ;; For readability, url-encode internal links only
9672 ;; when absolutely needed (i.e, when they contain
9673 ;; square brackets). File links however, are
9674 ;; encoded since, e.g., spaces are significant.
9675 ((or (file-name-absolute-p link)
9676 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9677 (org-link-escape link))
9678 (t link)))
9679 (description
9680 (and (org-string-nw-p description)
9681 ;; Remove brackets from description, as they are fatal.
9682 (replace-regexp-in-string
9683 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9684 (org-trim description)))))
9685 (format "[[%s]%s]"
9687 (if description (format "[%s]" description) ""))))
9689 (defconst org-link-escape-chars
9690 ;;%20 %5B %5D %25
9691 '(?\s ?\[ ?\] ?%)
9692 "List of characters that should be escaped in a link when stored to Org.
9693 This is the list that is used for internal purposes.")
9695 (defun org-link-escape (text &optional table merge)
9696 "Return percent escaped representation of TEXT.
9697 TEXT is a string with the text to escape.
9698 Optional argument TABLE is a list with characters that should be
9699 escaped. When nil, `org-link-escape-chars' is used.
9700 If optional argument MERGE is set, merge TABLE into
9701 `org-link-escape-chars'."
9702 (let ((characters-to-encode
9703 (cond ((null table) org-link-escape-chars)
9704 (merge (append org-link-escape-chars table))
9705 (t table))))
9706 (mapconcat
9707 (lambda (c)
9708 (if (or (memq c characters-to-encode)
9709 (and org-url-hexify-p (or (< c 32) (> c 126))))
9710 (mapconcat (lambda (e) (format "%%%.2X" e))
9711 (or (encode-coding-char c 'utf-8)
9712 (error "Unable to percent escape character: %c" c))
9714 (char-to-string c)))
9715 text "")))
9717 (defun org-link-unescape (str)
9718 "Unhex hexified Unicode parts in string STR.
9719 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9720 reciprocal of `org-link-escape', which see."
9721 (if (org-string-nw-p str)
9722 (replace-regexp-in-string
9723 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9724 str))
9726 (defun org-link-unescape-compound (hex)
9727 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9728 Note: this function also decodes single byte encodings like
9729 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9730 (save-match-data
9731 (let* ((bytes (cdr (split-string hex "%")))
9732 (ret "")
9733 (eat 0)
9734 (sum 0))
9735 (while bytes
9736 (let* ((val (string-to-number (pop bytes) 16))
9737 (shift-xor
9738 (if (= 0 eat)
9739 (cond
9740 ((>= val 252) (cons 6 252))
9741 ((>= val 248) (cons 5 248))
9742 ((>= val 240) (cons 4 240))
9743 ((>= val 224) (cons 3 224))
9744 ((>= val 192) (cons 2 192))
9745 (t (cons 0 0)))
9746 (cons 6 128))))
9747 (when (>= val 192) (setq eat (car shift-xor)))
9748 (setq val (logxor val (cdr shift-xor)))
9749 (setq sum (+ (lsh sum (car shift-xor)) val))
9750 (when (> eat 0) (setq eat (- eat 1)))
9751 (cond
9752 ((= 0 eat) ;multi byte
9753 (setq ret (concat ret (char-to-string sum)))
9754 (setq sum 0))
9755 ((not bytes) ; single byte(s)
9756 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9757 ret)))
9759 (defun org-link-unescape-single-byte-sequence (hex)
9760 "Unhexify hex-encoded single byte character sequences."
9761 (mapconcat (lambda (byte)
9762 (char-to-string (string-to-number byte 16)))
9763 (cdr (split-string hex "%")) ""))
9765 (defun org-fixup-message-id-for-http (s)
9766 "Replace special characters in a message id, so it can be used in an http query."
9767 (when (string-match "%" s)
9768 (setq s (mapconcat (lambda (c)
9769 (if (eq c ?%)
9770 "%25"
9771 (char-to-string c)))
9772 s "")))
9773 (while (string-match "<" s)
9774 (setq s (replace-match "%3C" t t s)))
9775 (while (string-match ">" s)
9776 (setq s (replace-match "%3E" t t s)))
9777 (while (string-match "@" s)
9778 (setq s (replace-match "%40" t t s)))
9781 (defun org-link-prettify (link)
9782 "Return a human-readable representation of LINK.
9783 The car of LINK must be a raw link.
9784 The cdr of LINK must be either a link description or nil."
9785 (let ((desc (or (cadr link) "<no description>")))
9786 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9787 "<" (car link) ">")))
9789 ;;;###autoload
9790 (defun org-insert-link-global ()
9791 "Insert a link like Org mode does.
9792 This command can be called in any mode to insert a link in Org syntax."
9793 (interactive)
9794 (org-load-modules-maybe)
9795 (org-run-like-in-org-mode 'org-insert-link))
9797 (defun org-insert-all-links (arg &optional pre post)
9798 "Insert all links in `org-stored-links'.
9799 When a universal prefix, do not delete the links from `org-stored-links'.
9800 When `ARG' is a number, insert the last N link(s).
9801 `PRE' and `POST' are optional arguments to define a string to
9802 prepend or to append."
9803 (interactive "P")
9804 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9805 (links (copy-sequence org-stored-links))
9806 (pr (or pre "- "))
9807 (po (or post "\n"))
9808 (cnt 1) l)
9809 (if (null org-stored-links)
9810 (message "No link to insert")
9811 (while (and (or (listp arg) (>= arg cnt))
9812 (setq l (if (listp arg)
9813 (pop links)
9814 (pop org-stored-links))))
9815 (setq cnt (1+ cnt))
9816 (insert pr)
9817 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9818 (insert po)))))
9820 (defun org-insert-last-stored-link (arg)
9821 "Insert the last link stored in `org-stored-links'."
9822 (interactive "p")
9823 (org-insert-all-links arg "" "\n"))
9825 (defun org-link-fontify-links-to-this-file ()
9826 "Fontify links to the current file in `org-stored-links'."
9827 (let ((f (buffer-file-name)) a b)
9828 (setq a (mapcar (lambda(l)
9829 (let ((ll (car l)))
9830 (when (and (string-match "^file:\\(.+\\)::" ll)
9831 (equal f (expand-file-name (match-string 1 ll))))
9832 ll)))
9833 org-stored-links))
9834 (when (featurep 'org-id)
9835 (setq b (mapcar (lambda(l)
9836 (let ((ll (car l)))
9837 (when (and (string-match "^id:\\(.+\\)$" ll)
9838 (equal f (expand-file-name
9839 (or (org-id-find-id-file
9840 (match-string 1 ll)) ""))))
9841 ll)))
9842 org-stored-links)))
9843 (mapcar (lambda(l)
9844 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9845 (delq nil (append a b)))))
9847 (defvar org--links-history nil)
9848 (defun org-insert-link (&optional complete-file link-location default-description)
9849 "Insert a link. At the prompt, enter the link.
9851 Completion can be used to insert any of the link protocol prefixes in use.
9853 The history can be used to select a link previously stored with
9854 `org-store-link'. When the empty string is entered (i.e. if you just
9855 press `RET' at the prompt), the link defaults to the most recently
9856 stored link. As `SPC' triggers completion in the minibuffer, you need to
9857 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9859 You will also be prompted for a description, and if one is given, it will
9860 be displayed in the buffer instead of the link.
9862 If there is already a link at point, this command will allow you to edit
9863 link and description parts.
9865 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9866 file name can be
9867 selected using completion. The path to the file will be relative to the
9868 current directory if the file is in the current directory or a subdirectory.
9869 Otherwise, the link will be the absolute path as completed in the minibuffer
9870 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9871 option `org-link-file-path-type'.
9873 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9874 absolute path even if the file is in
9875 the current directory or below.
9877 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9878 prefix negates `org-keep-stored-link-after-insertion'.
9880 If the LINK-LOCATION parameter is non-nil, this value will be used as
9881 the link location instead of reading one interactively.
9883 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9884 be used as the default description. Otherwise, if
9885 `org-make-link-description-function' is non-nil, this function
9886 will be called with the link target, and the result will be the
9887 default link description."
9888 (interactive "P")
9889 (let* ((wcf (current-window-configuration))
9890 (origbuf (current-buffer))
9891 (region (when (org-region-active-p)
9892 (buffer-substring (region-beginning) (region-end))))
9893 (remove (and region (list (region-beginning) (region-end))))
9894 (desc region)
9895 (link link-location)
9896 (abbrevs org-link-abbrev-alist-local)
9897 entry all-prefixes auto-desc)
9898 (cond
9899 (link-location) ; specified by arg, just use it.
9900 ((org-in-regexp org-bracket-link-regexp 1)
9901 ;; We do have a link at point, and we are going to edit it.
9902 (setq remove (list (match-beginning 0) (match-end 0)))
9903 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9904 (setq link (read-string "Link: "
9905 (org-link-unescape
9906 (match-string-no-properties 1)))))
9907 ((or (org-in-regexp org-angle-link-re)
9908 (org-in-regexp org-plain-link-re))
9909 ;; Convert to bracket link
9910 (setq remove (list (match-beginning 0) (match-end 0))
9911 link (read-string "Link: "
9912 (org-unbracket-string "<" ">" (match-string 0)))))
9913 ((member complete-file '((4) (16)))
9914 ;; Completing read for file names.
9915 (setq link (org-file-complete-link complete-file)))
9917 ;; Read link, with completion for stored links.
9918 (org-link-fontify-links-to-this-file)
9919 (org-switch-to-buffer-other-window "*Org Links*")
9920 (with-current-buffer "*Org Links*"
9921 (erase-buffer)
9922 (insert "Insert a link.
9923 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9924 (when org-stored-links
9925 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9926 (insert (mapconcat 'org-link-prettify
9927 (reverse org-stored-links) "\n")))
9928 (goto-char (point-min)))
9929 (let ((cw (selected-window)))
9930 (select-window (get-buffer-window "*Org Links*" 'visible))
9931 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9932 (unless (pos-visible-in-window-p (point-max))
9933 (org-fit-window-to-buffer))
9934 (and (window-live-p cw) (select-window cw)))
9935 (setq all-prefixes (append (mapcar 'car abbrevs)
9936 (mapcar 'car org-link-abbrev-alist)
9937 (org-link-types)))
9938 (unwind-protect
9939 ;; Fake a link history, containing the stored links.
9940 (let ((org--links-history
9941 (append (mapcar #'car org-stored-links)
9942 org-insert-link-history)))
9943 (setq link
9944 (org-completing-read
9945 "Link: "
9946 (append
9947 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9948 (mapcar #'car org-stored-links))
9949 nil nil nil
9950 'org--links-history
9951 (caar org-stored-links)))
9952 (unless (org-string-nw-p link) (user-error "No link selected"))
9953 (dolist (l org-stored-links)
9954 (when (equal link (cadr l))
9955 (setq link (car l))
9956 (setq auto-desc t)))
9957 (when (or (member link all-prefixes)
9958 (and (equal ":" (substring link -1))
9959 (member (substring link 0 -1) all-prefixes)
9960 (setq link (substring link 0 -1))))
9961 (setq link (with-current-buffer origbuf
9962 (org-link-try-special-completion link)))))
9963 (set-window-configuration wcf)
9964 (kill-buffer "*Org Links*"))
9965 (setq entry (assoc link org-stored-links))
9966 (or entry (push link org-insert-link-history))
9967 (setq desc (or desc (nth 1 entry)))))
9969 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9970 (not org-keep-stored-link-after-insertion))
9971 (setq org-stored-links (delq (assoc link org-stored-links)
9972 org-stored-links)))
9974 (when (and (string-match org-plain-link-re link)
9975 (not (string-match org-ts-regexp link)))
9976 ;; URL-like link, normalize the use of angular brackets.
9977 (setq link (org-unbracket-string "<" ">" link)))
9979 ;; Check if we are linking to the current file with a search
9980 ;; option If yes, simplify the link by using only the search
9981 ;; option.
9982 (when (and buffer-file-name
9983 (let ((case-fold-search nil))
9984 (string-match "\\`file:\\(.+?\\)::" link)))
9985 (let ((path (match-string-no-properties 1 link))
9986 (search (substring-no-properties link (match-end 0))))
9987 (save-match-data
9988 (when (equal (file-truename buffer-file-name) (file-truename path))
9989 ;; We are linking to this same file, with a search option
9990 (setq link search)))))
9992 ;; Check if we can/should use a relative path. If yes, simplify the link
9993 (let ((case-fold-search nil))
9994 (when (string-match "\\`\\(file\\|docview\\):" link)
9995 (let* ((type (match-string-no-properties 0 link))
9996 (path (substring-no-properties link (match-end 0)))
9997 (origpath path))
9998 (cond
9999 ((or (eq org-link-file-path-type 'absolute)
10000 (equal complete-file '(16)))
10001 (setq path (abbreviate-file-name (expand-file-name path))))
10002 ((eq org-link-file-path-type 'noabbrev)
10003 (setq path (expand-file-name path)))
10004 ((eq org-link-file-path-type 'relative)
10005 (setq path (file-relative-name path)))
10007 (save-match-data
10008 (if (string-match (concat "^" (regexp-quote
10009 (expand-file-name
10010 (file-name-as-directory
10011 default-directory))))
10012 (expand-file-name path))
10013 ;; We are linking a file with relative path name.
10014 (setq path (substring (expand-file-name path)
10015 (match-end 0)))
10016 (setq path (abbreviate-file-name (expand-file-name path)))))))
10017 (setq link (concat type path))
10018 (when (equal desc origpath)
10019 (setq desc path)))))
10021 (unless auto-desc
10022 (let ((initial-input
10023 (cond
10024 (default-description)
10025 ((not org-make-link-description-function) desc)
10026 (t (condition-case nil
10027 (funcall org-make-link-description-function link desc)
10028 (error
10029 (message "Can't get link description from `%s'"
10030 (symbol-name org-make-link-description-function))
10031 (sit-for 2)
10032 nil))))))
10033 (setq desc (read-string "Description: " initial-input))))
10035 (unless (string-match "\\S-" desc) (setq desc nil))
10036 (when remove (apply 'delete-region remove))
10037 (insert (org-make-link-string link desc))
10038 ;; Redisplay so as the new link has proper invisible characters.
10039 (sit-for 0)))
10041 (defun org-link-try-special-completion (type)
10042 "If there is completion support for link type TYPE, offer it."
10043 (let ((fun (org-link-get-parameter type :complete)))
10044 (if (functionp fun)
10045 (funcall fun)
10046 (read-string "Link (no completion support): " (concat type ":")))))
10048 (defun org-file-complete-link (&optional arg)
10049 "Create a file link using completion."
10050 (let ((file (read-file-name "File: "))
10051 (pwd (file-name-as-directory (expand-file-name ".")))
10052 (pwd1 (file-name-as-directory (abbreviate-file-name
10053 (expand-file-name ".")))))
10054 (cond ((equal arg '(16))
10055 (concat "file:"
10056 (abbreviate-file-name (expand-file-name file))))
10057 ((string-match
10058 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10059 (concat "file:" (match-string 1 file)))
10060 ((string-match
10061 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10062 (expand-file-name file))
10063 (concat "file:"
10064 (match-string 1 (expand-file-name file))))
10065 (t (concat "file:" file)))))
10068 ;;; Opening/following a link
10070 (defvar org-link-search-failed nil)
10072 (defvar org-open-link-functions nil
10073 "Hook for functions finding a plain text link.
10074 These functions must take a single argument, the link content.
10075 They will be called for links that look like [[link text][description]]
10076 when LINK TEXT does not have a protocol like \"http:\" and does not look
10077 like a filename (e.g. \"./blue.png\").
10079 These functions will be called *before* Org attempts to resolve the
10080 link by doing text searches in the current buffer - so if you want a
10081 link \"[[target]]\" to still find \"<<target>>\", your function should
10082 handle this as a special case.
10084 When the function does handle the link, it must return a non-nil value.
10085 If it decides that it is not responsible for this link, it must return
10086 nil to indicate that that Org can continue with other options like
10087 exact and fuzzy text search.")
10089 (defun org-next-link (&optional search-backward)
10090 "Move forward to the next link.
10091 If the link is in hidden text, expose it."
10092 (interactive "P")
10093 (when (and org-link-search-failed (eq this-command last-command))
10094 (goto-char (point-min))
10095 (message "Link search wrapped back to beginning of buffer"))
10096 (setq org-link-search-failed nil)
10097 (let* ((pos (point))
10098 (ct (org-context))
10099 (a (assq :link ct))
10100 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10101 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10102 ((looking-at org-any-link-re)
10103 ;; Don't stay stuck at link without an org-link face
10104 (forward-char (if search-backward -1 1))))
10105 (if (funcall srch-fun org-any-link-re nil t)
10106 (progn
10107 (goto-char (match-beginning 0))
10108 (when (org-invisible-p) (org-show-context)))
10109 (goto-char pos)
10110 (setq org-link-search-failed t)
10111 (message "No further link found"))))
10113 (defun org-previous-link ()
10114 "Move backward to the previous link.
10115 If the link is in hidden text, expose it."
10116 (interactive)
10117 (funcall 'org-next-link t))
10119 (defun org-translate-link (s)
10120 "Translate a link string if a translation function has been defined."
10121 (with-temp-buffer
10122 (insert (org-trim s))
10123 (org-trim (org-element-interpret-data (org-element-context)))))
10125 (defun org-translate-link-from-planner (type path)
10126 "Translate a link from Emacs Planner syntax so that Org can follow it.
10127 This is still an experimental function, your mileage may vary."
10128 (cond
10129 ((member type '("http" "https" "news" "ftp"))
10130 ;; standard Internet links are the same.
10131 nil)
10132 ((and (equal type "irc") (string-match "^//" path))
10133 ;; Planner has two / at the beginning of an irc link, we have 1.
10134 ;; We should have zero, actually....
10135 (setq path (substring path 1)))
10136 ((and (equal type "lisp") (string-match "^/" path))
10137 ;; Planner has a slash, we do not.
10138 (setq type "elisp" path (substring path 1)))
10139 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10140 ;; A typical message link. Planner has the id after the final slash,
10141 ;; we separate it with a hash mark
10142 (setq path (concat (match-string 1 path) "#"
10143 (org-unbracket-string "<" ">" (match-string 2 path))))))
10144 (cons type path))
10146 (defun org-find-file-at-mouse (ev)
10147 "Open file link or URL at mouse."
10148 (interactive "e")
10149 (mouse-set-point ev)
10150 (org-open-at-point 'in-emacs))
10152 (defun org-open-at-mouse (ev)
10153 "Open file link or URL at mouse.
10154 See the docstring of `org-open-file' for details."
10155 (interactive "e")
10156 (mouse-set-point ev)
10157 (when (eq major-mode 'org-agenda-mode)
10158 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10159 (org-open-at-point))
10161 (defvar org-window-config-before-follow-link nil
10162 "The window configuration before following a link.
10163 This is saved in case the need arises to restore it.")
10165 ;;;###autoload
10166 (defun org-open-at-point-global ()
10167 "Follow a link or time-stamp like Org mode does.
10168 This command can be called in any mode to follow an external link
10169 or a time-stamp that has Org mode syntax. Its behavior is
10170 undefined when called on internal links (e.g., fuzzy links).
10171 Raise an error when there is nothing to follow. "
10172 (interactive)
10173 (cond ((org-in-regexp org-any-link-re)
10174 (org-open-link-from-string (match-string-no-properties 0)))
10175 ((or (org-in-regexp org-ts-regexp-both nil t)
10176 (org-in-regexp org-tsr-regexp-both nil t))
10177 (org-follow-timestamp-link))
10178 (t (user-error "No link found"))))
10180 ;;;###autoload
10181 (defun org-open-link-from-string (s &optional arg reference-buffer)
10182 "Open a link in the string S, as if it was in Org mode."
10183 (interactive "sLink: \nP")
10184 (let ((reference-buffer (or reference-buffer (current-buffer))))
10185 (with-temp-buffer
10186 (let ((org-inhibit-startup (not reference-buffer)))
10187 (org-mode)
10188 (insert s)
10189 (goto-char (point-min))
10190 (when reference-buffer
10191 (setq org-link-abbrev-alist-local
10192 (with-current-buffer reference-buffer
10193 org-link-abbrev-alist-local)))
10194 (org-open-at-point arg reference-buffer)))))
10196 (defvar org-open-at-point-functions nil
10197 "Hook that is run when following a link at point.
10199 Functions in this hook must return t if they identify and follow
10200 a link at point. If they don't find anything interesting at point,
10201 they must return nil.")
10203 (defvar org-link-search-inhibit-query nil)
10204 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10205 (defun org--open-doi-link (path)
10206 "Open a \"doi\" type link.
10207 PATH is a the path to search for, as a string."
10208 (browse-url (url-encode-url (concat org-doi-server-url path))))
10210 (defun org--open-elisp-link (path)
10211 "Open a \"elisp\" type link.
10212 PATH is the sexp to evaluate, as a string."
10213 (let ((cmd path))
10214 (if (or (and (org-string-nw-p
10215 org-confirm-elisp-link-not-regexp)
10216 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10217 (not org-confirm-elisp-link-function)
10218 (funcall org-confirm-elisp-link-function
10219 (format "Execute \"%s\" as elisp? "
10220 (org-add-props cmd nil 'face 'org-warning))))
10221 (message "%s => %s" cmd
10222 (if (eq (string-to-char cmd) ?\()
10223 (eval (read cmd))
10224 (call-interactively (read cmd))))
10225 (user-error "Abort"))))
10227 (defun org--open-help-link (path)
10228 "Open a \"help\" type link.
10229 PATH is a symbol name, as a string."
10230 (pcase (intern path)
10231 ((and (pred fboundp) variable) (describe-function variable))
10232 ((and (pred boundp) function) (describe-variable function))
10233 (name (user-error "Unknown function or variable: %s" name))))
10235 (defun org--open-shell-link (path)
10236 "Open a \"shell\" type link.
10237 PATH is the command to execute, as a string."
10238 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10239 (cmd path))
10240 (if (or (and (org-string-nw-p
10241 org-confirm-shell-link-not-regexp)
10242 (string-match
10243 org-confirm-shell-link-not-regexp cmd))
10244 (not org-confirm-shell-link-function)
10245 (funcall org-confirm-shell-link-function
10246 (format "Execute \"%s\" in shell? "
10247 (org-add-props cmd nil
10248 'face 'org-warning))))
10249 (progn
10250 (message "Executing %s" cmd)
10251 (shell-command cmd buf)
10252 (when (featurep 'midnight)
10253 (setq clean-buffer-list-kill-buffer-names
10254 (cons (buffer-name buf)
10255 clean-buffer-list-kill-buffer-names))))
10256 (user-error "Abort"))))
10258 (defun org-open-at-point (&optional arg reference-buffer)
10259 "Open link, timestamp, footnote or tags at point.
10261 When point is on a link, follow it. Normally, files will be
10262 opened by an appropriate application. If the optional prefix
10263 argument ARG is non-nil, Emacs will visit the file. With
10264 a double prefix argument, try to open outside of Emacs, in the
10265 application the system uses for this file type.
10267 When point is on a timestamp, open the agenda at the day
10268 specified.
10270 When point is a footnote definition, move to the first reference
10271 found. If it is on a reference, move to the associated
10272 definition.
10274 When point is on a headline, display a list of every link in the
10275 entry, so it is possible to pick one, or all, of them. If point
10276 is on a tag, call `org-tags-view' instead.
10278 When optional argument REFERENCE-BUFFER is non-nil, it should
10279 specify a buffer from where the link search should happen. This
10280 is used internally by `org-open-link-from-string'.
10282 On top of syntactically correct links, this function will also
10283 try to open links and time-stamps in comments, example
10284 blocks... i.e., whenever point is on something looking like
10285 a timestamp or a link."
10286 (interactive "P")
10287 ;; On a code block, open block's results.
10288 (unless (call-interactively 'org-babel-open-src-block-result)
10289 (org-load-modules-maybe)
10290 (setq org-window-config-before-follow-link (current-window-configuration))
10291 (org-remove-occur-highlights nil nil t)
10292 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10293 (let* ((context
10294 ;; Only consider supported types, even if they are not
10295 ;; the closest one.
10296 (org-element-lineage
10297 (org-element-context)
10298 '(clock footnote-definition footnote-reference headline
10299 inlinetask link timestamp)
10301 (type (org-element-type context))
10302 (value (org-element-property :value context)))
10303 (cond
10304 ;; On a headline or an inlinetask, but not on a timestamp,
10305 ;; a link, a footnote reference.
10306 ((memq type '(headline inlinetask))
10307 (org-match-line org-complex-heading-regexp)
10308 (if (and (match-beginning 5)
10309 (>= (point) (match-beginning 5))
10310 (< (point) (match-end 5)))
10311 ;; On tags.
10312 (org-tags-view arg (substring (match-string 5) 0 -1))
10313 ;; Not on tags.
10314 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10315 (`(nil . ,_)
10316 (require 'org-attach)
10317 (org-attach-reveal 'if-exists))
10318 (`(,links . ,links-end)
10319 (dolist (link (if (stringp links) (list links) links))
10320 (search-forward link nil links-end)
10321 (goto-char (match-beginning 0))
10322 (org-open-at-point))))))
10323 ;; On a footnote reference or at definition's label.
10324 ((or (eq type 'footnote-reference)
10325 (and (eq type 'footnote-definition)
10326 (save-excursion
10327 ;; Do not validate action when point is on the
10328 ;; spaces right after the footnote label, in
10329 ;; order to be on par with behaviour on links.
10330 (skip-chars-forward " \t")
10331 (let ((begin
10332 (org-element-property :contents-begin context)))
10333 (if begin (< (point) begin)
10334 (= (org-element-property :post-affiliated context)
10335 (line-beginning-position)))))))
10336 (org-footnote-action))
10337 ;; No valid context. Ignore catch-all types like `headline'.
10338 ;; If point is on something looking like a link or
10339 ;; a time-stamp, try opening it. It may be useful in
10340 ;; comments, example blocks...
10341 ((memq type '(footnote-definition headline inlinetask nil))
10342 (call-interactively #'org-open-at-point-global))
10343 ;; On a clock line, make sure point is on the timestamp
10344 ;; before opening it.
10345 ((and (eq type 'clock)
10346 value
10347 (>= (point) (org-element-property :begin value))
10348 (<= (point) (org-element-property :end value)))
10349 (org-follow-timestamp-link))
10350 ;; Do nothing on white spaces after an object.
10351 ((>= (point)
10352 (save-excursion
10353 (goto-char (org-element-property :end context))
10354 (skip-chars-backward " \t")
10355 (point)))
10356 (user-error "No link found"))
10357 ((eq type 'timestamp) (org-follow-timestamp-link))
10358 ((eq type 'link)
10359 (let ((type (org-element-property :type context))
10360 (path (org-link-unescape (org-element-property :path context))))
10361 ;; Switch back to REFERENCE-BUFFER needed when called in
10362 ;; a temporary buffer through `org-open-link-from-string'.
10363 (with-current-buffer (or reference-buffer (current-buffer))
10364 (cond
10365 ((equal type "file")
10366 (if (string-match "[*?{]" (file-name-nondirectory path))
10367 (dired path)
10368 ;; Look into `org-link-parameters' in order to find
10369 ;; a DEDICATED-FUNCTION to open file. The function
10370 ;; will be applied on raw link instead of parsed
10371 ;; link due to the limitation in `org-add-link-type'
10372 ;; ("open" function called with a single argument).
10373 ;; If no such function is found, fallback to
10374 ;; `org-open-file'.
10375 (let* ((option (org-element-property :search-option context))
10376 (app (org-element-property :application context))
10377 (dedicated-function
10378 (org-link-get-parameter
10379 (if app (concat type "+" app) type)
10380 :follow)))
10381 (if dedicated-function
10382 (funcall dedicated-function
10383 (concat path
10384 (and option (concat "::" option))))
10385 (apply #'org-open-file
10386 path
10387 (cond (arg)
10388 ((equal app "emacs") 'emacs)
10389 ((equal app "sys") 'system))
10390 (cond ((not option) nil)
10391 ((string-match-p "\\`[0-9]+\\'" option)
10392 (list (string-to-number option)))
10393 (t (list nil
10394 (org-link-unescape option)))))))))
10395 ((functionp (org-link-get-parameter type :follow))
10396 (funcall (org-link-get-parameter type :follow) path))
10397 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10398 (unless (run-hook-with-args-until-success
10399 'org-open-link-functions path)
10400 (if (not arg) (org-mark-ring-push)
10401 (switch-to-buffer-other-window
10402 (org-get-buffer-for-internal-link (current-buffer))))
10403 (let ((destination
10404 (org-with-wide-buffer
10405 (if (equal type "radio")
10406 (org-search-radio-target
10407 (org-element-property :path context))
10408 (org-link-search
10409 (if (member type '("custom-id" "coderef"))
10410 (org-element-property :raw-link context)
10411 path)
10412 ;; Prevent fuzzy links from matching
10413 ;; themselves.
10414 (and (equal type "fuzzy")
10415 (+ 2 (org-element-property :begin context)))))
10416 (point))))
10417 (unless (and (<= (point-min) destination)
10418 (>= (point-max) destination))
10419 (widen))
10420 (goto-char destination))))
10421 (t (browse-url-at-point))))))
10422 (t (user-error "No link found")))))
10423 (run-hook-with-args 'org-follow-link-hook)))
10425 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10426 "Offer links in the current entry and return the selected link.
10427 If there is only one link, return it.
10428 If NTH is an integer, return the NTH link found.
10429 If ZERO is a string, check also this string for a link, and if
10430 there is one, return it."
10431 (with-current-buffer buffer
10432 (org-with-wide-buffer
10433 (goto-char marker)
10434 (let ((cnt ?0)
10435 have-zero end links link c)
10436 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10437 (push (match-string 0 zero) links)
10438 (setq cnt (1- cnt) have-zero t))
10439 (save-excursion
10440 (org-back-to-heading t)
10441 (setq end (save-excursion (outline-next-heading) (point)))
10442 (while (re-search-forward org-any-link-re end t)
10443 (push (match-string 0) links))
10444 (setq links (org-uniquify (reverse links))))
10445 (cond
10446 ((null links)
10447 (message "No links"))
10448 ((equal (length links) 1)
10449 (setq link (car links)))
10450 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10451 (setq link (nth (if have-zero nth (1- nth)) links)))
10452 (t ; we have to select a link
10453 (save-excursion
10454 (save-window-excursion
10455 (delete-other-windows)
10456 (with-output-to-temp-buffer "*Select Link*"
10457 (dolist (l links)
10458 (cond
10459 ((not (string-match org-bracket-link-regexp l))
10460 (princ (format "[%c] %s\n" (cl-incf cnt)
10461 (org-unbracket-string "<" ">" l))))
10462 ((match-end 3)
10463 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10464 (match-string 3 l) (match-string 1 l))))
10465 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10466 (match-string 1 l)))))))
10467 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10468 (message "Select link to open, RET to open all:")
10469 (setq c (read-char-exclusive))
10470 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10471 (when (equal c ?q) (user-error "Abort"))
10472 (if (equal c ?\C-m)
10473 (setq link links)
10474 (setq nth (- c ?0))
10475 (when have-zero (setq nth (1+ nth)))
10476 (unless (and (integerp nth) (>= (length links) nth))
10477 (user-error "Invalid link selection"))
10478 (setq link (nth (1- nth) links)))))
10479 (cons link end)))))
10481 ;; TODO: These functions are deprecated since `org-open-at-point'
10482 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10483 (defun org-open-file-with-system (path)
10484 "Open file at PATH using the system way of opening it."
10485 (org-open-file path 'system))
10486 (defun org-open-file-with-emacs (path)
10487 "Open file at PATH in Emacs."
10488 (org-open-file path 'emacs))
10491 ;;; File search
10493 (defvar org-create-file-search-functions nil
10494 "List of functions to construct the right search string for a file link.
10495 These functions are called in turn with point at the location to
10496 which the link should point.
10498 A function in the hook should first test if it would like to
10499 handle this file type, for example by checking the `major-mode'
10500 or the file extension. If it decides not to handle this file, it
10501 should just return nil to give other functions a chance. If it
10502 does handle the file, it must return the search string to be used
10503 when following the link. The search string will be part of the
10504 file link, given after a double colon, and `org-open-at-point'
10505 will automatically search for it. If special measures must be
10506 taken to make the search successful, another function should be
10507 added to the companion hook `org-execute-file-search-functions',
10508 which see.
10510 A function in this hook may also use `setq' to set the variable
10511 `description' to provide a suggestion for the descriptive text to
10512 be used for this link when it gets inserted into an Org buffer
10513 with \\[org-insert-link].")
10515 (defvar org-execute-file-search-functions nil
10516 "List of functions to execute a file search triggered by a link.
10518 Functions added to this hook must accept a single argument, the
10519 search string that was part of the file link, the part after the
10520 double colon. The function must first check if it would like to
10521 handle this search, for example by checking the `major-mode' or
10522 the file extension. If it decides not to handle this search, it
10523 should just return nil to give other functions a chance. If it
10524 does handle the search, it must return a non-nil value to keep
10525 other functions from trying.
10527 Each function can access the current prefix argument through the
10528 variable `current-prefix-arg'. Note that a single prefix is used
10529 to force opening a link in Emacs, so it may be good to only use a
10530 numeric or double prefix to guide the search function.
10532 In case this is needed, a function in this hook can also restore
10533 the window configuration before `org-open-at-point' was called using:
10535 (set-window-configuration org-window-config-before-follow-link)")
10537 (defun org-search-radio-target (target)
10538 "Search a radio target matching TARGET in current buffer.
10539 White spaces are not significant."
10540 (let ((re (format "<<<%s>>>"
10541 (mapconcat #'regexp-quote
10542 (split-string target)
10543 "[ \t]+\\(?:\n[ \t]*\\)?")))
10544 (origin (point)))
10545 (goto-char (point-min))
10546 (catch :radio-match
10547 (while (re-search-forward re nil t)
10548 (backward-char)
10549 (let ((object (org-element-context)))
10550 (when (eq (org-element-type object) 'radio-target)
10551 (goto-char (org-element-property :begin object))
10552 (org-show-context 'link-search)
10553 (throw :radio-match nil))))
10554 (goto-char origin)
10555 (user-error "No match for radio target: %s" target))))
10557 (defun org-link-search (s &optional avoid-pos stealth)
10558 "Search for a search string S.
10560 If S starts with \"#\", it triggers a custom ID search.
10562 If S is enclosed within parenthesis, it initiates a coderef
10563 search.
10565 If S is surrounded by forward slashes, it is interpreted as
10566 a regular expression. In Org mode files, this will create an
10567 `org-occur' sparse tree. In ordinary files, `occur' will be used
10568 to list matches. If the current buffer is in `dired-mode', grep
10569 will be used to search in all files.
10571 When AVOID-POS is given, ignore matches near that position.
10573 When optional argument STEALTH is non-nil, do not modify
10574 visibility around point, thus ignoring `org-show-context-detail'
10575 variable.
10577 Search is case-insensitive and ignores white spaces. Return type
10578 of matched result, which is either `dedicated' or `fuzzy'."
10579 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10580 (let* ((case-fold-search t)
10581 (origin (point))
10582 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10583 (starred (eq (string-to-char normalized) ?*))
10584 (words (split-string (if starred (substring s 1) s)))
10585 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10586 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10587 type)
10588 (cond
10589 ;; Check if there are any special search functions.
10590 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10591 ((eq (string-to-char s) ?#)
10592 ;; Look for a custom ID S if S starts with "#".
10593 (let* ((id (substring normalized 1))
10594 (match (org-find-property "CUSTOM_ID" id)))
10595 (if match (progn (goto-char match) (setf type 'dedicated))
10596 (error "No match for custom ID: %s" id))))
10597 ((string-match "\\`(\\(.*\\))\\'" normalized)
10598 ;; Look for coderef targets if S is enclosed within parenthesis.
10599 (let ((coderef (match-string-no-properties 1 normalized))
10600 (re (substring s-single-re 1 -1)))
10601 (goto-char (point-min))
10602 (catch :coderef-match
10603 (while (re-search-forward re nil t)
10604 (let ((element (org-element-at-point)))
10605 (when (and (memq (org-element-type element)
10606 '(example-block src-block))
10607 ;; Build proper regexp according to current
10608 ;; block's label format.
10609 (let ((label-fmt
10610 (regexp-quote
10611 (or (org-element-property :label-fmt element)
10612 org-coderef-label-format))))
10613 (save-excursion
10614 (beginning-of-line)
10615 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10616 (format label-fmt coderef))))))
10617 (setq type 'dedicated)
10618 (goto-char (match-beginning 1))
10619 (throw :coderef-match nil))))
10620 (goto-char origin)
10621 (error "No match for coderef: %s" coderef))))
10622 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10623 ;; Look for a regular expression.
10624 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10625 (match-string 1 s)))
10626 ;; From here, we handle fuzzy links.
10628 ;; Look for targets, only if not in a headline search.
10629 ((and (not starred)
10630 (let ((target (format "<<%s>>" s-multi-re)))
10631 (catch :target-match
10632 (goto-char (point-min))
10633 (while (re-search-forward target nil t)
10634 (backward-char)
10635 (let ((context (org-element-context)))
10636 (when (eq (org-element-type context) 'target)
10637 (setq type 'dedicated)
10638 (goto-char (org-element-property :begin context))
10639 (throw :target-match t))))
10640 nil))))
10641 ;; Look for elements named after S, only if not in a headline
10642 ;; search.
10643 ((and (not starred)
10644 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10645 (catch :name-match
10646 (goto-char (point-min))
10647 (while (re-search-forward name nil t)
10648 (let ((element (org-element-at-point)))
10649 (when (equal words
10650 (split-string
10651 (org-element-property :name element)))
10652 (setq type 'dedicated)
10653 (beginning-of-line)
10654 (throw :name-match t))))
10655 nil))))
10656 ;; Regular text search. Prefer headlines in Org mode buffers.
10657 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10658 ;; statistics cookies and tags.
10659 ((and (derived-mode-p 'org-mode)
10660 (let ((title-re
10661 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10662 org-outline-regexp-bol
10663 org-comment-string
10664 (mapconcat #'regexp-quote words ".+")))
10665 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10666 (comment-re (eval-when-compile
10667 (format "\\`%s[ \t]+" org-comment-string))))
10668 (goto-char (point-min))
10669 (catch :found
10670 (while (re-search-forward title-re nil t)
10671 (when (equal words
10672 (split-string
10673 (replace-regexp-in-string
10674 cookie-re ""
10675 (replace-regexp-in-string
10676 comment-re "" (org-get-heading t t t)))))
10677 (throw :found t)))
10678 nil)))
10679 (beginning-of-line)
10680 (setq type 'dedicated))
10681 ;; Offer to create non-existent headline depending on
10682 ;; `org-link-search-must-match-exact-headline'.
10683 ((and (derived-mode-p 'org-mode)
10684 (not org-link-search-inhibit-query)
10685 (eq org-link-search-must-match-exact-headline 'query-to-create)
10686 (yes-or-no-p "No match - create this as a new heading? "))
10687 (goto-char (point-max))
10688 (unless (bolp) (newline))
10689 (org-insert-heading nil t t)
10690 (insert s "\n")
10691 (beginning-of-line 0))
10692 ;; Only headlines are looked after. No need to process
10693 ;; further: throw an error.
10694 ((and (derived-mode-p 'org-mode)
10695 (or starred org-link-search-must-match-exact-headline))
10696 (goto-char origin)
10697 (error "No match for fuzzy expression: %s" normalized))
10698 ;; Regular text search.
10699 ((catch :fuzzy-match
10700 (goto-char (point-min))
10701 (while (re-search-forward s-multi-re nil t)
10702 ;; Skip match if it contains AVOID-POS or it is included in
10703 ;; a link with a description but outside the description.
10704 (unless (or (and avoid-pos
10705 (<= (match-beginning 0) avoid-pos)
10706 (> (match-end 0) avoid-pos))
10707 (and (save-match-data
10708 (org-in-regexp org-bracket-link-regexp))
10709 (match-beginning 3)
10710 (or (> (match-beginning 3) (point))
10711 (<= (match-end 3) (point)))
10712 (org-element-lineage
10713 (save-match-data (org-element-context))
10714 '(link) t)))
10715 (goto-char (match-beginning 0))
10716 (setq type 'fuzzy)
10717 (throw :fuzzy-match t)))
10718 nil))
10719 ;; All failed. Throw an error.
10720 (t (goto-char origin)
10721 (error "No match for fuzzy expression: %s" normalized)))
10722 ;; Disclose surroundings of match, if appropriate.
10723 (when (and (derived-mode-p 'org-mode) (not stealth))
10724 (org-show-context 'link-search))
10725 type))
10727 (defun org-get-buffer-for-internal-link (buffer)
10728 "Return a buffer to be used for displaying the link target of internal links."
10729 (cond
10730 ((not org-display-internal-link-with-indirect-buffer)
10731 buffer)
10732 ((string-suffix-p "(Clone)" (buffer-name buffer))
10733 (message "Buffer is already a clone, not making another one")
10734 ;; we also do not modify visibility in this case
10735 buffer)
10736 (t ; make a new indirect buffer for displaying the link
10737 (let* ((bn (buffer-name buffer))
10738 (ibn (concat bn "(Clone)"))
10739 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10740 (with-current-buffer ib (org-overview))
10741 ib))))
10743 (defun org-do-occur (regexp &optional cleanup)
10744 "Call the Emacs command `occur'.
10745 If CLEANUP is non-nil, remove the printout of the regular expression
10746 in the *Occur* buffer. This is useful if the regex is long and not useful
10747 to read."
10748 (occur regexp)
10749 (when cleanup
10750 (let ((cwin (selected-window)) win beg end)
10751 (when (setq win (get-buffer-window "*Occur*"))
10752 (select-window win))
10753 (goto-char (point-min))
10754 (when (re-search-forward "match[a-z]+" nil t)
10755 (setq beg (match-end 0))
10756 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10757 (setq end (1- (match-beginning 0)))))
10758 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10759 (goto-char (point-min))
10760 (select-window cwin))))
10762 ;;; The mark ring for links jumps
10764 (defvar org-mark-ring nil
10765 "Mark ring for positions before jumps in Org mode.")
10766 (defvar org-mark-ring-last-goto nil
10767 "Last position in the mark ring used to go back.")
10768 ;; Fill and close the ring
10769 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10770 (dotimes (_ org-mark-ring-length)
10771 (push (make-marker) org-mark-ring))
10772 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10773 org-mark-ring)
10775 (defun org-mark-ring-push (&optional pos buffer)
10776 "Put the current position or POS into the mark ring and rotate it."
10777 (interactive)
10778 (setq pos (or pos (point)))
10779 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10780 (move-marker (car org-mark-ring)
10781 (or pos (point))
10782 (or buffer (current-buffer)))
10783 (message "%s"
10784 (substitute-command-keys
10785 "Position saved to mark ring, go back with \
10786 `\\[org-mark-ring-goto]'.")))
10788 (defun org-mark-ring-goto (&optional n)
10789 "Jump to the previous position in the mark ring.
10790 With prefix arg N, jump back that many stored positions. When
10791 called several times in succession, walk through the entire ring.
10792 Org mode commands jumping to a different position in the current file,
10793 or to another Org file, automatically push the old position onto the ring."
10794 (interactive "p")
10795 (let (p m)
10796 (if (eq last-command this-command)
10797 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10798 (setq p org-mark-ring))
10799 (setq org-mark-ring-last-goto p)
10800 (setq m (car p))
10801 (pop-to-buffer-same-window (marker-buffer m))
10802 (goto-char m)
10803 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10805 (defun org-add-angle-brackets (s)
10806 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10807 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10810 ;;; Following specific links
10812 (defvar org-agenda-buffer-tmp-name)
10813 (defvar org-agenda-start-on-weekday)
10814 (defun org-follow-timestamp-link ()
10815 "Open an agenda view for the time-stamp date/range at point."
10816 (cond
10817 ((org-at-date-range-p t)
10818 (let ((org-agenda-start-on-weekday)
10819 (t1 (match-string 1))
10820 (t2 (match-string 2)) tt1 tt2)
10821 (setq tt1 (time-to-days (org-time-string-to-time t1))
10822 tt2 (time-to-days (org-time-string-to-time t2)))
10823 (let ((org-agenda-buffer-tmp-name
10824 (format "*Org Agenda(a:%s)"
10825 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10826 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10827 ((org-at-timestamp-p 'lax)
10828 (let ((org-agenda-buffer-tmp-name
10829 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10830 (org-agenda-list nil (time-to-days (org-time-string-to-time
10831 (substring (match-string 1) 0 10)))
10832 1)))
10833 (t (error "This should not happen"))))
10836 ;;; Following file links
10837 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10838 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10839 (declare-function mailcap-mime-info
10840 "mailcap" (string &optional request no-decode))
10841 (defvar org-wait nil)
10842 (defun org-open-file (path &optional in-emacs line search)
10843 "Open the file at PATH.
10844 First, this expands any special file name abbreviations. Then the
10845 configuration variable `org-file-apps' is checked if it contains an
10846 entry for this file type, and if yes, the corresponding command is launched.
10848 If no application is found, Emacs simply visits the file.
10850 With optional prefix argument IN-EMACS, Emacs will visit the file.
10851 With a double \\[universal-argument] \\[universal-argument] \
10852 prefix arg, Org tries to avoid opening in Emacs
10853 and to use an external application to visit the file.
10855 Optional LINE specifies a line to go to, optional SEARCH a string
10856 to search for. If LINE or SEARCH is given, the file will be
10857 opened in Emacs, unless an entry from org-file-apps that makes
10858 use of groups in a regexp matches.
10860 If you want to change the way frames are used when following a
10861 link, please customize `org-link-frame-setup'.
10863 If the file does not exist, an error is thrown."
10864 (let* ((file (if (equal path "")
10865 buffer-file-name
10866 (substitute-in-file-name (expand-file-name path))))
10867 (file-apps (append org-file-apps (org-default-apps)))
10868 (apps (cl-remove-if
10869 'org-file-apps-entry-match-against-dlink-p file-apps))
10870 (apps-dlink (cl-remove-if-not
10871 'org-file-apps-entry-match-against-dlink-p file-apps))
10872 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10873 (dirp (unless remp (file-directory-p file)))
10874 (file (if (and dirp org-open-directory-means-index-dot-org)
10875 (concat (file-name-as-directory file) "index.org")
10876 file))
10877 (a-m-a-p (assq 'auto-mode apps))
10878 (dfile (downcase file))
10879 ;; Reconstruct the original link from the PATH, LINE and
10880 ;; SEARCH args.
10881 (link (cond (line (concat file "::" (number-to-string line)))
10882 (search (concat file "::" search))
10883 (t file)))
10884 (dlink (downcase link))
10885 (ext
10886 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10887 (match-string 1 dfile)))
10888 (save-position-maybe
10889 (let ((old-buffer (current-buffer))
10890 (old-pos (point))
10891 (old-mode major-mode))
10892 (lambda ()
10893 (and (derived-mode-p 'org-mode)
10894 (eq old-mode 'org-mode)
10895 (or (not (eq old-buffer (current-buffer)))
10896 (not (eq old-pos (point))))
10897 (org-mark-ring-push old-pos old-buffer)))))
10898 cmd link-match-data)
10899 (cond
10900 ((member in-emacs '((16) system))
10901 (setq cmd (cdr (assq 'system apps))))
10902 (in-emacs (setq cmd 'emacs))
10904 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10905 (and dirp (cdr (assq 'directory apps)))
10906 ;; First, try matching against apps-dlink if we
10907 ;; get a match here, store the match data for
10908 ;; later.
10909 (let ((match (assoc-default dlink apps-dlink
10910 'string-match)))
10911 (if match
10912 (progn (setq link-match-data (match-data))
10913 match)
10914 (progn (setq in-emacs (or in-emacs line search))
10915 nil))) ; if we have no match in apps-dlink,
10916 ; always open the file in emacs if line or search
10917 ; is given (for backwards compatibility)
10918 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10919 'string-match)
10920 (cdr (assoc ext apps))
10921 (cdr (assq t apps))))))
10922 (when (eq cmd 'system)
10923 (setq cmd (cdr (assq 'system apps))))
10924 (when (eq cmd 'default)
10925 (setq cmd (cdr (assoc t apps))))
10926 (when (eq cmd 'mailcap)
10927 (require 'mailcap)
10928 (mailcap-parse-mailcaps)
10929 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10930 (command (mailcap-mime-info mime-type)))
10931 (if (stringp command)
10932 (setq cmd command)
10933 (setq cmd 'emacs))))
10934 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10935 (not (file-exists-p file))
10936 (not org-open-non-existing-files))
10937 (user-error "No such file: %s" file))
10938 (cond
10939 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10940 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10941 (while (string-match "['\"]%s['\"]" cmd)
10942 (setq cmd (replace-match "%s" t t cmd)))
10943 (setq cmd (replace-regexp-in-string
10944 "%s"
10945 (shell-quote-argument (convert-standard-filename file))
10947 nil t))
10949 ;; Replace "%1", "%2" etc. in command with group matches from regex
10950 (save-match-data
10951 (let ((match-index 1)
10952 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10953 (set-match-data link-match-data)
10954 (while (<= match-index number-of-groups)
10955 (let ((regex (concat "%" (number-to-string match-index)))
10956 (replace-with (match-string match-index dlink)))
10957 (while (string-match regex cmd)
10958 (setq cmd (replace-match replace-with t t cmd))))
10959 (setq match-index (+ match-index 1)))))
10961 (save-window-excursion
10962 (message "Running %s...done" cmd)
10963 (start-process-shell-command cmd nil cmd)
10964 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10965 ((or (stringp cmd)
10966 (eq cmd 'emacs))
10967 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10968 (widen)
10969 (cond (line (org-goto-line line)
10970 (when (derived-mode-p 'org-mode) (org-reveal)))
10971 (search (condition-case err
10972 (org-link-search search)
10973 ;; Save position before error-ing out so user
10974 ;; can easily move back to the original buffer.
10975 (error (funcall save-position-maybe)
10976 (error (nth 1 err)))))))
10977 ((functionp cmd)
10978 (save-match-data
10979 (set-match-data link-match-data)
10980 (condition-case nil
10981 (funcall cmd file link)
10982 ;; FIXME: Remove this check when most default installations
10983 ;; of Emacs have at least Org 9.0.
10984 ((debug wrong-number-of-arguments wrong-type-argument
10985 invalid-function)
10986 (user-error "Please see Org News for version 9.0 about \
10987 `org-file-apps'--Lisp error: %S" cmd)))))
10988 ((consp cmd)
10989 ;; FIXME: Remove this check when most default installations of
10990 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10991 ;; fall back to `org-link-frame-setup' for an old usage of
10992 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10993 (user-error "Please see Org News for version 9.0 about \
10994 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10995 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10996 (funcall save-position-maybe)))
10998 (defun org-file-apps-entry-match-against-dlink-p (entry)
10999 "This function returns non-nil if `entry' uses a regular
11000 expression which should be matched against the whole link by
11001 org-open-file.
11003 It assumes that is the case when the entry uses a regular
11004 expression which has at least one grouping construct and the
11005 action is either a lisp form or a command string containing
11006 `%1', i.e. using at least one subexpression match as a
11007 parameter."
11008 (let ((selector (car entry))
11009 (action (cdr entry)))
11010 (if (stringp selector)
11011 (and (> (regexp-opt-depth selector) 0)
11012 (or (and (stringp action)
11013 (string-match "%[0-9]" action))
11014 (consp action)))
11015 nil)))
11017 (defun org-default-apps ()
11018 "Return the default applications for this operating system."
11019 (cond
11020 ((eq system-type 'darwin)
11021 org-file-apps-defaults-macosx)
11022 ((eq system-type 'windows-nt)
11023 org-file-apps-defaults-windowsnt)
11024 (t org-file-apps-defaults-gnu)))
11026 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11027 "Convert extensions to regular expressions in the cars of LIST.
11028 Also, weed out any non-string entries, because the return value is used
11029 only for regexp matching.
11030 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11031 point to the symbol `emacs', indicating that the file should
11032 be opened in Emacs."
11033 (append
11034 (delq nil
11035 (mapcar (lambda (x)
11036 (unless (not (stringp (car x)))
11037 (if (string-match "\\W" (car x))
11039 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11040 list))
11041 (when add-auto-mode
11042 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11044 (defvar ange-ftp-name-format)
11045 (defun org-file-remote-p (file)
11046 "Test whether FILE specifies a location on a remote system.
11047 Return non-nil if the location is indeed remote.
11049 For example, the filename \"/user@host:/foo\" specifies a location
11050 on the system \"/user@host:\"."
11051 (cond ((fboundp 'file-remote-p)
11052 (file-remote-p file))
11053 ((fboundp 'tramp-handle-file-remote-p)
11054 (tramp-handle-file-remote-p file))
11055 ((and (boundp 'ange-ftp-name-format)
11056 (string-match (car ange-ftp-name-format) file))
11057 t)))
11060 ;;;; Refiling
11062 (defun org-get-org-file ()
11063 "Read a filename, with default directory `org-directory'."
11064 (let ((default (or org-default-notes-file remember-data-file)))
11065 (read-file-name (format "File name [%s]: " default)
11066 (file-name-as-directory org-directory)
11067 default)))
11069 (defun org-notes-order-reversed-p ()
11070 "Check if the current file should receive notes in reversed order."
11071 (cond
11072 ((not org-reverse-note-order) nil)
11073 ((eq t org-reverse-note-order) t)
11074 ((not (listp org-reverse-note-order)) nil)
11075 (t (catch 'exit
11076 (dolist (entry org-reverse-note-order)
11077 (when (string-match (car entry) buffer-file-name)
11078 (throw 'exit (cdr entry))))))))
11080 (defvar org-refile-target-table nil
11081 "The list of refile targets, created by `org-refile'.")
11083 (defvar org-agenda-new-buffers nil
11084 "Buffers created to visit agenda files.")
11086 (defvar org-refile-cache nil
11087 "Cache for refile targets.")
11089 (defvar org-refile-markers nil
11090 "All the markers used for caching refile locations.")
11092 (defun org-refile-marker (pos)
11093 "Get a new refile marker, but only if caching is in use."
11094 (if (not org-refile-use-cache)
11096 (let ((m (make-marker)))
11097 (move-marker m pos)
11098 (push m org-refile-markers)
11099 m)))
11101 (defun org-refile-cache-clear ()
11102 "Clear the refile cache and disable all the markers."
11103 (dolist (m org-refile-markers) (move-marker m nil))
11104 (setq org-refile-markers nil)
11105 (setq org-refile-cache nil)
11106 (message "Refile cache has been cleared"))
11108 (defun org-refile-cache-check-set (set)
11109 "Check if all the markers in the cache still have live buffers."
11110 (let (marker)
11111 (catch 'exit
11112 (while (and set (setq marker (nth 3 (pop set))))
11113 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11114 (when (and marker (null (marker-buffer marker)))
11115 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11116 (sit-for 3)
11117 (throw 'exit nil)))
11118 t)))
11120 (defun org-refile-cache-put (set &rest identifiers)
11121 "Push the refile targets SET into the cache, under IDENTIFIERS."
11122 (let* ((key (sha1 (prin1-to-string identifiers)))
11123 (entry (assoc key org-refile-cache)))
11124 (if entry
11125 (setcdr entry set)
11126 (push (cons key set) org-refile-cache))))
11128 (defun org-refile-cache-get (&rest identifiers)
11129 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11130 (cond
11131 ((not org-refile-cache) nil)
11132 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11134 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11135 org-refile-cache))))
11136 (and set (org-refile-cache-check-set set) set)))))
11138 (defvar org-outline-path-cache nil
11139 "Alist between buffer positions and outline paths.
11140 It value is an alist (POSITION . PATH) where POSITION is the
11141 buffer position at the beginning of an entry and PATH is a list
11142 of strings describing the outline path for that entry, in reverse
11143 order.")
11145 (defun org-refile-get-targets (&optional default-buffer)
11146 "Produce a table with refile targets."
11147 (let ((case-fold-search nil)
11148 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11149 (entries (or org-refile-targets '((nil . (:level . 1)))))
11150 targets tgs files desc descre)
11151 (message "Getting targets...")
11152 (with-current-buffer (or default-buffer (current-buffer))
11153 (dolist (entry entries)
11154 (setq files (car entry) desc (cdr entry))
11155 (cond
11156 ((null files) (setq files (list (current-buffer))))
11157 ((eq files 'org-agenda-files)
11158 (setq files (org-agenda-files 'unrestricted)))
11159 ((and (symbolp files) (fboundp files))
11160 (setq files (funcall files)))
11161 ((and (symbolp files) (boundp files))
11162 (setq files (symbol-value files))))
11163 (when (stringp files) (setq files (list files)))
11164 (cond
11165 ((eq (car desc) :tag)
11166 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11167 ((eq (car desc) :todo)
11168 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11169 ((eq (car desc) :regexp)
11170 (setq descre (cdr desc)))
11171 ((eq (car desc) :level)
11172 (setq descre (concat "^\\*\\{" (number-to-string
11173 (if org-odd-levels-only
11174 (1- (* 2 (cdr desc)))
11175 (cdr desc)))
11176 "\\}[ \t]")))
11177 ((eq (car desc) :maxlevel)
11178 (setq descre (concat "^\\*\\{1," (number-to-string
11179 (if org-odd-levels-only
11180 (1- (* 2 (cdr desc)))
11181 (cdr desc)))
11182 "\\}[ \t]")))
11183 (t (error "Bad refiling target description %s" desc)))
11184 (dolist (f files)
11185 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11187 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11188 (progn
11189 (when (bufferp f)
11190 (setq f (buffer-file-name (buffer-base-buffer f))))
11191 (setq f (and f (expand-file-name f)))
11192 (when (eq org-refile-use-outline-path 'file)
11193 (push (list (file-name-nondirectory f) f nil nil) tgs))
11194 (when (eq org-refile-use-outline-path 'buffer-name)
11195 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11196 (when (eq org-refile-use-outline-path 'full-file-path)
11197 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11198 (org-with-wide-buffer
11199 (goto-char (point-min))
11200 (setq org-outline-path-cache nil)
11201 (while (re-search-forward descre nil t)
11202 (beginning-of-line)
11203 (let ((case-fold-search nil))
11204 (looking-at org-complex-heading-regexp))
11205 (let ((begin (point))
11206 (heading (match-string-no-properties 4)))
11207 (unless (or (and
11208 org-refile-target-verify-function
11209 (not
11210 (funcall org-refile-target-verify-function)))
11211 (not heading))
11212 (let ((re (format org-complex-heading-regexp-format
11213 (regexp-quote heading)))
11214 (target
11215 (if (not org-refile-use-outline-path) heading
11216 (mapconcat
11217 #'identity
11218 (append
11219 (pcase org-refile-use-outline-path
11220 (`file (list (file-name-nondirectory
11221 (buffer-file-name
11222 (buffer-base-buffer)))))
11223 (`full-file-path
11224 (list (buffer-file-name
11225 (buffer-base-buffer))))
11226 (`buffer-name
11227 (list (buffer-name
11228 (buffer-base-buffer))))
11229 (_ nil))
11230 (mapcar (lambda (s) (replace-regexp-in-string
11231 "/" "\\/" s nil t))
11232 (org-get-outline-path t t)))
11233 "/"))))
11234 (push (list target f re (org-refile-marker (point)))
11235 tgs)))
11236 (when (= (point) begin)
11237 ;; Verification function has not moved point.
11238 (end-of-line)))))))
11239 (when org-refile-use-cache
11240 (org-refile-cache-put tgs (buffer-file-name) descre))
11241 (setq targets (append tgs targets))))))
11242 (message "Getting targets...done")
11243 (delete-dups (nreverse targets))))
11245 (defun org--get-outline-path-1 (&optional use-cache)
11246 "Return outline path to current headline.
11248 Outline path is a list of strings, in reverse order. When
11249 optional argument USE-CACHE is non-nil, make use of a cache. See
11250 `org-get-outline-path' for details.
11252 Assume buffer is widened and point is on a headline."
11253 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11254 (let ((p (point))
11255 (heading (let ((case-fold-search nil))
11256 (looking-at org-complex-heading-regexp)
11257 (if (not (match-end 4)) ""
11258 ;; Remove statistics cookies.
11259 (org-trim
11260 (org-link-display-format
11261 (replace-regexp-in-string
11262 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11263 (match-string-no-properties 4))))))))
11264 (if (org-up-heading-safe)
11265 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11266 (when use-cache
11267 (push (cons p path) org-outline-path-cache))
11268 path)
11269 ;; This is a new root node. Since we assume we are moving
11270 ;; forward, we can drop previous cache so as to limit number
11271 ;; of associations there.
11272 (let ((path (list heading)))
11273 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11274 path)))))
11276 (defun org-get-outline-path (&optional with-self use-cache)
11277 "Return the outline path to the current entry.
11279 An outline path is a list of ancestors for current headline, as
11280 a list of strings. Statistics cookies are removed and links are
11281 replaced with their description, if any, or their path otherwise.
11283 When optional argument WITH-SELF is non-nil, the path also
11284 includes the current headline.
11286 When optional argument USE-CACHE is non-nil, cache outline paths
11287 between calls to this function so as to avoid backtracking. This
11288 argument is useful when planning to find more than one outline
11289 path in the same document. In that case, there are two
11290 conditions to satisfy:
11291 - `org-outline-path-cache' is set to nil before starting the
11292 process;
11293 - outline paths are computed by increasing buffer positions."
11294 (org-with-wide-buffer
11295 (and (or (and with-self (org-back-to-heading t))
11296 (org-up-heading-safe))
11297 (reverse (org--get-outline-path-1 use-cache)))))
11299 (defun org-format-outline-path (path &optional width prefix separator)
11300 "Format the outline path PATH for display.
11301 WIDTH is the maximum number of characters that is available.
11302 PREFIX is a prefix to be included in the returned string,
11303 such as the file name.
11304 SEPARATOR is inserted between the different parts of the path,
11305 the default is \"/\"."
11306 (setq width (or width 79))
11307 (setq path (delq nil path))
11308 (unless (> width 0)
11309 (user-error "Argument `width' must be positive"))
11310 (setq separator (or separator "/"))
11311 (let* ((org-odd-levels-only nil)
11312 (fpath (concat
11313 prefix (and prefix path separator)
11314 (mapconcat
11315 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11316 (cl-loop for head in path
11317 for n from 0
11318 collect (org-add-props
11319 head nil 'face
11320 (nth (% n org-n-level-faces) org-level-faces)))
11321 separator))))
11322 (when (> (length fpath) width)
11323 (if (< width 7)
11324 ;; It's unlikely that `width' will be this small, but don't
11325 ;; waste characters by adding ".." if it is.
11326 (setq fpath (substring fpath 0 width))
11327 (setf (substring fpath (- width 2)) "..")))
11328 fpath))
11330 (defun org-display-outline-path (&optional file current separator just-return-string)
11331 "Display the current outline path in the echo area.
11333 If FILE is non-nil, prepend the output with the file name.
11334 If CURRENT is non-nil, append the current heading to the output.
11335 SEPARATOR is passed through to `org-format-outline-path'. It separates
11336 the different parts of the path and defaults to \"/\".
11337 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11338 (interactive "P")
11339 (let* (case-fold-search
11340 (bfn (buffer-file-name (buffer-base-buffer)))
11341 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11342 res)
11343 (when current (setq path (append path
11344 (save-excursion
11345 (org-back-to-heading t)
11346 (when (looking-at org-complex-heading-regexp)
11347 (list (match-string 4)))))))
11348 (setq res
11349 (org-format-outline-path
11350 path
11351 (1- (frame-width))
11352 (and file bfn (concat (file-name-nondirectory bfn) separator))
11353 separator))
11354 (if just-return-string
11355 (org-no-properties res)
11356 (org-unlogged-message "%s" res))))
11358 (defvar org-refile-history nil
11359 "History for refiling operations.")
11361 (defvar org-after-refile-insert-hook nil
11362 "Hook run after `org-refile' has inserted its stuff at the new location.
11363 Note that this is still *before* the stuff will be removed from
11364 the *old* location.")
11366 (defvar org-capture-last-stored-marker)
11367 (defvar org-refile-keep nil
11368 "Non-nil means `org-refile' will copy instead of refile.")
11370 (defun org-copy ()
11371 "Like `org-refile', but copy."
11372 (interactive)
11373 (let ((org-refile-keep t))
11374 (funcall 'org-refile nil nil nil "Copy")))
11376 (defun org-refile (&optional arg default-buffer rfloc msg)
11377 "Move the entry or entries at point to another heading.
11379 The list of target headings is compiled using the information in
11380 `org-refile-targets', which see.
11382 At the target location, the entry is filed as a subitem of the
11383 target heading. Depending on `org-reverse-note-order', the new
11384 subitem will either be the first or the last subitem.
11386 If there is an active region, all entries in that region will be
11387 refiled. However, the region must fulfill the requirement that
11388 the first heading sets the top-level of the moved text.
11390 With a `\\[universal-argument]' ARG, the command will only visit the target \
11391 location
11392 and not actually move anything.
11394 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11395 location where the last
11396 refiling operation has put the subtree.
11398 With a numeric prefix argument of `2', refile to the running clock.
11400 With a numeric prefix argument of `3', emulate `org-refile-keep'
11401 being set to t and copy to the target location, don't move it.
11402 Beware that keeping refiled entries may result in duplicated ID
11403 properties.
11405 RFLOC can be a refile location obtained in a different way.
11407 MSG is a string to replace \"Refile\" in the default prompt with
11408 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11410 See also `org-refile-use-outline-path'.
11412 If you are using target caching (see `org-refile-use-cache'), you
11413 have to clear the target cache in order to find new targets.
11414 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11415 prefix argument (`C-u C-u C-u C-c C-w')."
11416 (interactive "P")
11417 (if (member arg '(0 (64)))
11418 (org-refile-cache-clear)
11419 (let* ((actionmsg (cond (msg msg)
11420 ((equal arg 3) "Refile (and keep)")
11421 (t "Refile")))
11422 (regionp (org-region-active-p))
11423 (region-start (and regionp (region-beginning)))
11424 (region-end (and regionp (region-end)))
11425 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11426 pos it nbuf file level reversed)
11427 (setq last-command nil)
11428 (when regionp
11429 (goto-char region-start)
11430 (or (bolp) (goto-char (point-at-bol)))
11431 (setq region-start (point))
11432 (unless (or (org-kill-is-subtree-p
11433 (buffer-substring region-start region-end))
11434 (prog1 org-refile-active-region-within-subtree
11435 (let ((s (point-at-eol)))
11436 (org-toggle-heading)
11437 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11438 (user-error "The region is not a (sequence of) subtree(s)")))
11439 (if (equal arg '(16))
11440 (org-refile-goto-last-stored)
11441 (when (or
11442 (and (equal arg 2)
11443 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11444 (prog1
11445 (setq it (list (or org-clock-heading "running clock")
11446 (buffer-file-name
11447 (marker-buffer org-clock-hd-marker))
11449 (marker-position org-clock-hd-marker)))
11450 (setq arg nil)))
11451 (setq it
11452 (or rfloc
11453 (let (heading-text)
11454 (save-excursion
11455 (unless (and arg (listp arg))
11456 (org-back-to-heading t)
11457 (setq heading-text
11458 (replace-regexp-in-string
11459 org-bracket-link-regexp
11460 "\\3"
11461 (or (nth 4 (org-heading-components))
11462 ""))))
11463 (org-refile-get-location
11464 (cond ((and arg (listp arg)) "Goto")
11465 (regionp (concat actionmsg " region to"))
11466 (t (concat actionmsg " subtree \""
11467 heading-text "\" to")))
11468 default-buffer
11469 (and (not (equal '(4) arg))
11470 org-refile-allow-creating-parent-nodes)))))))
11471 (setq file (nth 1 it)
11472 pos (nth 3 it))
11473 (when (and (not arg)
11475 (equal (buffer-file-name) file)
11476 (if regionp
11477 (and (>= pos region-start)
11478 (<= pos region-end))
11479 (and (>= pos (point))
11480 (< pos (save-excursion
11481 (org-end-of-subtree t t))))))
11482 (error "Cannot refile to position inside the tree or region"))
11483 (setq nbuf (or (find-buffer-visiting file)
11484 (find-file-noselect file)))
11485 (if (and arg (not (equal arg 3)))
11486 (progn
11487 (pop-to-buffer-same-window nbuf)
11488 (goto-char (cond (pos)
11489 ((org-notes-order-reversed-p) (point-min))
11490 (t (point-max))))
11491 (org-show-context 'org-goto))
11492 (if regionp
11493 (progn
11494 (org-kill-new (buffer-substring region-start region-end))
11495 (org-save-markers-in-region region-start region-end))
11496 (org-copy-subtree 1 nil t))
11497 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11498 (find-file-noselect file)))
11499 (setq reversed (org-notes-order-reversed-p))
11500 (org-with-wide-buffer
11501 (if pos
11502 (progn
11503 (goto-char pos)
11504 (setq level (org-get-valid-level (funcall outline-level) 1))
11505 (goto-char
11506 (if reversed
11507 (or (outline-next-heading) (point-max))
11508 (or (save-excursion (org-get-next-sibling))
11509 (org-end-of-subtree t t)
11510 (point-max)))))
11511 (setq level 1)
11512 (if (not reversed)
11513 (goto-char (point-max))
11514 (goto-char (point-min))
11515 (or (outline-next-heading) (goto-char (point-max)))))
11516 (unless (bolp) (newline))
11517 (org-paste-subtree level nil nil t)
11518 (when org-log-refile
11519 (org-add-log-setup 'refile nil nil org-log-refile)
11520 (unless (eq org-log-refile 'note)
11521 (save-excursion (org-add-log-note))))
11522 (and org-auto-align-tags
11523 (let ((org-loop-over-headlines-in-active-region nil))
11524 (org-set-tags nil t)))
11525 (let ((bookmark-name (plist-get org-bookmark-names-plist
11526 :last-refile)))
11527 (when bookmark-name
11528 (with-demoted-errors
11529 (bookmark-set bookmark-name))))
11530 ;; If we are refiling for capture, make sure that the
11531 ;; last-capture pointers point here
11532 (when (bound-and-true-p org-capture-is-refiling)
11533 (let ((bookmark-name (plist-get org-bookmark-names-plist
11534 :last-capture-marker)))
11535 (when bookmark-name
11536 (with-demoted-errors
11537 (bookmark-set bookmark-name))))
11538 (move-marker org-capture-last-stored-marker (point)))
11539 (when (fboundp 'deactivate-mark) (deactivate-mark))
11540 (run-hooks 'org-after-refile-insert-hook)))
11541 (unless org-refile-keep
11542 (if regionp
11543 (delete-region (point) (+ (point) (- region-end region-start)))
11544 (delete-region
11545 (and (org-back-to-heading t) (point))
11546 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11547 (when (featurep 'org-inlinetask)
11548 (org-inlinetask-remove-END-maybe))
11549 (setq org-markers-to-move nil)
11550 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11552 (defun org-refile-goto-last-stored ()
11553 "Go to the location where the last refile was stored."
11554 (interactive)
11555 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11556 (message "This is the location of the last refile"))
11558 (defun org-refile--get-location (refloc tbl)
11559 "When user refile to REFLOC, find the associated target in TBL.
11560 Also check `org-refile-target-table'."
11561 (car (delq
11563 (mapcar
11564 (lambda (r) (or (assoc r tbl)
11565 (assoc r org-refile-target-table)))
11566 (list (replace-regexp-in-string "/$" "" refloc)
11567 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11569 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11570 "Prompt the user for a refile location, using PROMPT.
11571 PROMPT should not be suffixed with a colon and a space, because
11572 this function appends the default value from
11573 `org-refile-history' automatically, if that is not empty."
11574 (let ((org-refile-targets org-refile-targets)
11575 (org-refile-use-outline-path org-refile-use-outline-path))
11576 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11577 (unless org-refile-target-table
11578 (user-error "No refile targets"))
11579 (let* ((cbuf (current-buffer))
11580 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11581 (cfunc (if (and org-refile-use-outline-path
11582 org-outline-path-complete-in-steps)
11583 #'org-olpath-completing-read
11584 #'completing-read))
11585 (extra (if org-refile-use-outline-path "/" ""))
11586 (cbnex (concat (buffer-name) extra))
11587 (filename (and cfn (expand-file-name cfn)))
11588 (tbl (mapcar
11589 (lambda (x)
11590 (if (and (not (member org-refile-use-outline-path
11591 '(file full-file-path)))
11592 (not (equal filename (nth 1 x))))
11593 (cons (concat (car x) extra " ("
11594 (file-name-nondirectory (nth 1 x)) ")")
11595 (cdr x))
11596 (cons (concat (car x) extra) (cdr x))))
11597 org-refile-target-table))
11598 (completion-ignore-case t)
11599 cdef
11600 (prompt (concat prompt
11601 (or (and (car org-refile-history)
11602 (concat " (default " (car org-refile-history) ")"))
11603 (and (assoc cbnex tbl) (setq cdef cbnex)
11604 (concat " (default " cbnex ")"))) ": "))
11605 pa answ parent-target child parent old-hist)
11606 (setq old-hist org-refile-history)
11607 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11608 nil 'org-refile-history (or cdef (car org-refile-history))))
11609 (if (setq pa (org-refile--get-location answ tbl))
11610 (progn
11611 (org-refile-check-position pa)
11612 (when (or (not org-refile-history)
11613 (not (eq old-hist org-refile-history))
11614 (not (equal (car pa) (car org-refile-history))))
11615 (setq org-refile-history
11616 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11617 org-refile-history
11618 (cdr org-refile-history))))
11619 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11620 (pop org-refile-history)))
11622 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11623 (progn
11624 (setq parent (match-string 1 answ)
11625 child (match-string 2 answ))
11626 (setq parent-target (org-refile--get-location parent tbl))
11627 (when (and parent-target
11628 (or (eq new-nodes t)
11629 (and (eq new-nodes 'confirm)
11630 (y-or-n-p (format "Create new node \"%s\"? "
11631 child)))))
11632 (org-refile-new-child parent-target child)))
11633 (user-error "Invalid target location")))))
11635 (declare-function org-string-nw-p "org-macs" (s))
11636 (defun org-refile-check-position (refile-pointer)
11637 "Check if the refile pointer matches the headline to which it points."
11638 (let* ((file (nth 1 refile-pointer))
11639 (re (nth 2 refile-pointer))
11640 (pos (nth 3 refile-pointer))
11641 buffer)
11642 (if (and (not (markerp pos)) (not file))
11643 (user-error "Please indicate a target file in the refile path")
11644 (when (org-string-nw-p re)
11645 (setq buffer (if (markerp pos)
11646 (marker-buffer pos)
11647 (or (find-buffer-visiting file)
11648 (find-file-noselect file))))
11649 (with-current-buffer buffer
11650 (org-with-wide-buffer
11651 (goto-char pos)
11652 (beginning-of-line 1)
11653 (unless (looking-at-p re)
11654 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11656 (defun org-refile-new-child (parent-target child)
11657 "Use refile target PARENT-TARGET to add new CHILD below it."
11658 (unless parent-target
11659 (error "Cannot find parent for new node"))
11660 (let ((file (nth 1 parent-target))
11661 (pos (nth 3 parent-target))
11662 level)
11663 (with-current-buffer (or (find-buffer-visiting file)
11664 (find-file-noselect file))
11665 (org-with-wide-buffer
11666 (if pos
11667 (goto-char pos)
11668 (goto-char (point-max))
11669 (unless (bolp) (newline)))
11670 (when (looking-at org-outline-regexp)
11671 (setq level (funcall outline-level))
11672 (org-end-of-subtree t t))
11673 (org-back-over-empty-lines)
11674 (insert "\n" (make-string
11675 (if pos (org-get-valid-level level 1) 1) ?*)
11676 " " child "\n")
11677 (beginning-of-line 0)
11678 (list (concat (car parent-target) "/" child) file "" (point))))))
11680 (defun org-olpath-completing-read (prompt collection &rest args)
11681 "Read an outline path like a file name."
11682 (let ((thetable collection))
11683 (apply #'completing-read
11684 prompt
11685 (lambda (string predicate &optional flag)
11686 (cond
11687 ((eq flag nil) (try-completion string thetable))
11688 ((eq flag t)
11689 (let ((l (length string)))
11690 (mapcar (lambda (x)
11691 (let ((r (substring x l))
11692 (f (if (string-match " ([^)]*)$" x)
11693 (match-string 0 x)
11694 "")))
11695 (if (string-match "/" r)
11696 (concat string (substring r 0 (match-end 0)) f)
11697 x)))
11698 (all-completions string thetable predicate))))
11699 ;; Exact match?
11700 ((eq flag 'lambda) (assoc string thetable))))
11701 args)))
11703 ;;;; Dynamic blocks
11705 (defun org-find-dblock (name)
11706 "Find the first dynamic block with name NAME in the buffer.
11707 If not found, stay at current position and return nil."
11708 (let ((case-fold-search t) pos)
11709 (save-excursion
11710 (goto-char (point-min))
11711 (setq pos (and (re-search-forward
11712 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11713 (match-beginning 0))))
11714 (when pos (goto-char pos))
11715 pos))
11717 (defun org-create-dblock (plist)
11718 "Create a dynamic block section, with parameters taken from PLIST.
11719 PLIST must contain a :name entry which is used as the name of the block."
11720 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11721 (end-of-line 1)
11722 (newline))
11723 (let ((col (current-column))
11724 (name (plist-get plist :name)))
11725 (insert "#+BEGIN: " name)
11726 (while plist
11727 (if (eq (car plist) :name)
11728 (setq plist (cddr plist))
11729 (insert " " (prin1-to-string (pop plist)))))
11730 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11731 (beginning-of-line -2)))
11733 (defun org-prepare-dblock ()
11734 "Prepare dynamic block for refresh.
11735 This empties the block, puts the cursor at the insert position and returns
11736 the property list including an extra property :name with the block name."
11737 (unless (looking-at org-dblock-start-re)
11738 (user-error "Not at a dynamic block"))
11739 (let* ((begdel (1+ (match-end 0)))
11740 (name (org-no-properties (match-string 1)))
11741 (params (append (list :name name)
11742 (read (concat "(" (match-string 3) ")")))))
11743 (save-excursion
11744 (beginning-of-line 1)
11745 (skip-chars-forward " \t")
11746 (setq params (plist-put params :indentation-column (current-column))))
11747 (unless (re-search-forward org-dblock-end-re nil t)
11748 (error "Dynamic block not terminated"))
11749 (setq params
11750 (append params
11751 (list :content (buffer-substring
11752 begdel (match-beginning 0)))))
11753 (delete-region begdel (match-beginning 0))
11754 (goto-char begdel)
11755 (open-line 1)
11756 params))
11758 (defun org-map-dblocks (&optional command)
11759 "Apply COMMAND to all dynamic blocks in the current buffer.
11760 If COMMAND is not given, use `org-update-dblock'."
11761 (let ((cmd (or command 'org-update-dblock)))
11762 (save-excursion
11763 (goto-char (point-min))
11764 (while (re-search-forward org-dblock-start-re nil t)
11765 (goto-char (match-beginning 0))
11766 (save-excursion
11767 (condition-case nil
11768 (funcall cmd)
11769 (error (message "Error during update of dynamic block"))))
11770 (unless (re-search-forward org-dblock-end-re nil t)
11771 (error "Dynamic block not terminated"))))))
11773 (defun org-dblock-update (&optional arg)
11774 "User command for updating dynamic blocks.
11775 Update the dynamic block at point. With prefix ARG, update all dynamic
11776 blocks in the buffer."
11777 (interactive "P")
11778 (if arg
11779 (org-update-all-dblocks)
11780 (or (looking-at org-dblock-start-re)
11781 (org-beginning-of-dblock))
11782 (org-update-dblock)))
11784 (defun org-update-dblock ()
11785 "Update the dynamic block at point.
11786 This means to empty the block, parse for parameters and then call
11787 the correct writing function."
11788 (interactive)
11789 (save-excursion
11790 (let* ((win (selected-window))
11791 (pos (point))
11792 (line (org-current-line))
11793 (params (org-prepare-dblock))
11794 (name (plist-get params :name))
11795 (indent (plist-get params :indentation-column))
11796 (cmd (intern (concat "org-dblock-write:" name))))
11797 (message "Updating dynamic block `%s' at line %d..." name line)
11798 (funcall cmd params)
11799 (message "Updating dynamic block `%s' at line %d...done" name line)
11800 (goto-char pos)
11801 (when (and indent (> indent 0))
11802 (setq indent (make-string indent ?\ ))
11803 (save-excursion
11804 (select-window win)
11805 (org-beginning-of-dblock)
11806 (forward-line 1)
11807 (while (not (looking-at org-dblock-end-re))
11808 (insert indent)
11809 (beginning-of-line 2))
11810 (when (looking-at org-dblock-end-re)
11811 (and (looking-at "[ \t]+")
11812 (replace-match ""))
11813 (insert indent)))))))
11815 (defun org-beginning-of-dblock ()
11816 "Find the beginning of the dynamic block at point.
11817 Error if there is no such block at point."
11818 (let ((pos (point))
11819 beg)
11820 (end-of-line 1)
11821 (if (and (re-search-backward org-dblock-start-re nil t)
11822 (setq beg (match-beginning 0))
11823 (re-search-forward org-dblock-end-re nil t)
11824 (> (match-end 0) pos))
11825 (goto-char beg)
11826 (goto-char pos)
11827 (error "Not in a dynamic block"))))
11829 (defun org-update-all-dblocks ()
11830 "Update all dynamic blocks in the buffer.
11831 This function can be used in a hook."
11832 (interactive)
11833 (when (derived-mode-p 'org-mode)
11834 (org-map-dblocks 'org-update-dblock)))
11837 ;;;; Completion
11839 (declare-function org-export-backend-options "ox" (cl-x) t)
11840 (defun org-get-export-keywords ()
11841 "Return a list of all currently understood export keywords.
11842 Export keywords include options, block names, attributes and
11843 keywords relative to each registered export back-end."
11844 (let (keywords)
11845 (dolist (backend
11846 (bound-and-true-p org-export-registered-backends)
11847 (delq nil keywords))
11848 ;; Back-end name (for keywords, like #+LATEX:)
11849 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11850 (dolist (option-entry (org-export-backend-options backend))
11851 ;; Back-end options.
11852 (push (nth 1 option-entry) keywords)))))
11854 (defconst org-options-keywords
11855 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11856 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11857 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11858 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11859 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11861 (defcustom org-structure-template-alist
11862 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
11863 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
11864 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
11865 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
11866 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
11867 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
11868 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
11869 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
11870 ("L" "#+LaTeX: ")
11871 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
11872 ("H" "#+HTML: ")
11873 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
11874 ("A" "#+ASCII: ")
11875 ("i" "#+INDEX: ?")
11876 ("I" "#+INCLUDE: %file ?"))
11877 "Structure completion elements.
11878 This is a list of abbreviation keys and values. The value gets inserted
11879 if you type `<' followed by the key and then press the completion key,
11880 usually `TAB'. %file will be replaced by a file name after prompting
11881 for the file using completion. The cursor will be placed at the position
11882 of the `?' in the template.
11883 There are two templates for each key, the first uses the original Org syntax,
11884 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11885 the default when the /org-mtags.el/ module has been loaded. See also the
11886 variable `org-mtags-prefer-muse-templates'."
11887 :group 'org-completion
11888 :type '(repeat
11889 (list
11890 (string :tag "Key")
11891 (string :tag "Template")))
11892 :version "26.1"
11893 :package-version '(Org . "8.3"))
11895 (defun org-try-structure-completion ()
11896 "Try to complete a structure template before point.
11897 This looks for strings like \"<e\" on an otherwise empty line and
11898 expands them."
11899 (let ((l (buffer-substring (point-at-bol) (point)))
11901 (when (and (looking-at "[ \t]*$")
11902 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11903 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11904 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11905 (match-beginning 1)) a)
11906 t)))
11908 (defun org-complete-expand-structure-template (start cell)
11909 "Expand a structure template."
11910 (let ((rpl (nth 1 cell))
11911 (ind ""))
11912 (delete-region start (point))
11913 (when (string-match "\\`[ \t]*#\\+" rpl)
11914 (cond
11915 ((bolp))
11916 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11917 (setq ind (buffer-substring (point-at-bol) (point))))
11918 (t (newline))))
11919 (setq start (point))
11920 (when (string-match "%file" rpl)
11921 (setq rpl (replace-match
11922 (concat
11923 "\""
11924 (save-match-data
11925 (abbreviate-file-name (read-file-name "Include file: ")))
11926 "\"")
11927 t t rpl)))
11928 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11929 (concat "\n" ind)))
11930 (insert rpl)
11931 (when (re-search-backward "\\?" start t) (delete-char 1))))
11933 ;;;; TODO, DEADLINE, Comments
11935 (defun org-toggle-comment ()
11936 "Change the COMMENT state of an entry."
11937 (interactive)
11938 (save-excursion
11939 (org-back-to-heading)
11940 (let ((case-fold-search nil))
11941 (looking-at org-complex-heading-regexp))
11942 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11943 (skip-chars-forward " \t")
11944 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11945 (if (org-in-commented-heading-p t)
11946 (delete-region (point)
11947 (progn (search-forward " " (line-end-position) 'move)
11948 (skip-chars-forward " \t")
11949 (point)))
11950 (insert org-comment-string)
11951 (unless (eolp) (insert " ")))))
11953 (defvar org-last-todo-state-is-todo nil
11954 "This is non-nil when the last TODO state change led to a TODO state.
11955 If the last change removed the TODO tag or switched to DONE, then
11956 this is nil.")
11958 (defvar org-setting-tags nil) ; dynamically skipped
11960 (defvar org-todo-setup-filter-hook nil
11961 "Hook for functions that pre-filter todo specs.
11962 Each function takes a todo spec and returns either nil or the spec
11963 transformed into canonical form." )
11965 (defvar org-todo-get-default-hook nil
11966 "Hook for functions that get a default item for todo.
11967 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11968 nil or a string to be used for the todo mark." )
11970 (defvar org-agenda-headline-snapshot-before-repeat)
11972 (defun org-current-effective-time ()
11973 "Return current time adjusted for `org-extend-today-until' variable."
11974 (let* ((ct (org-current-time))
11975 (dct (decode-time ct))
11976 (ct1
11977 (cond
11978 (org-use-last-clock-out-time-as-effective-time
11979 (or (org-clock-get-last-clock-out-time) ct))
11980 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11981 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11982 (t ct))))
11983 ct1))
11985 (defun org-todo-yesterday (&optional arg)
11986 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11987 (interactive "P")
11988 (if (eq major-mode 'org-agenda-mode)
11989 (apply 'org-agenda-todo-yesterday arg)
11990 (let* ((org-use-effective-time t)
11991 (hour (nth 2 (decode-time (org-current-time))))
11992 (org-extend-today-until (1+ hour)))
11993 (org-todo arg))))
11995 (defvar org-block-entry-blocking ""
11996 "First entry preventing the TODO state change.")
11998 (defun org-cancel-repeater ()
11999 "Cancel a repeater by setting its numeric value to zero."
12000 (interactive)
12001 (save-excursion
12002 (org-back-to-heading t)
12003 (let ((bound1 (point))
12004 (bound0 (save-excursion (outline-next-heading) (point))))
12005 (when (and (re-search-forward
12006 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12007 org-deadline-time-regexp "\\)\\|\\("
12008 org-ts-regexp "\\)")
12009 bound0 t)
12010 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12011 bound1 t))
12012 (replace-match "0" t nil nil 1)))))
12014 (defvar org-state)
12015 (defvar org-blocked-by-checkboxes)
12016 (defun org-todo (&optional arg)
12017 "Change the TODO state of an item.
12019 The state of an item is given by a keyword at the start of the heading,
12020 like
12021 *** TODO Write paper
12022 *** DONE Call mom
12024 The different keywords are specified in the variable `org-todo-keywords'.
12025 By default the available states are \"TODO\" and \"DONE\". So, for this
12026 example: when the item starts with TODO, it is changed to DONE.
12027 When it starts with DONE, the DONE is removed. And when neither TODO nor
12028 DONE are present, add TODO at the beginning of the heading.
12030 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12031 state.
12032 With numeric prefix ARG, switch to that state.
12033 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12034 next set of TODO \
12035 keywords (nextset).
12036 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12037 prefix, circumvent any state blocking.
12038 With a numeric prefix arg of 0, inhibit note taking for the change.
12039 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12041 When called through ELisp, arg is also interpreted in the following way:
12042 `none' -> empty state
12043 \"\" -> switch to empty state
12044 `done' -> switch to DONE
12045 `nextset' -> switch to the next set of keywords
12046 `previousset' -> switch to the previous set of keywords
12047 \"WAITING\" -> switch to the specified keyword, but only if it
12048 really is a member of `org-todo-keywords'."
12049 (interactive "P")
12050 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12051 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12052 'region-start-level 'region))
12053 org-loop-over-headlines-in-active-region)
12054 (org-map-entries
12055 `(org-todo ,arg)
12056 org-loop-over-headlines-in-active-region
12057 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12058 (when (equal arg '(16)) (setq arg 'nextset))
12059 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12060 (let ((org-blocker-hook org-blocker-hook)
12061 commentp
12062 case-fold-search)
12063 (when (equal arg '(64))
12064 (setq arg nil org-blocker-hook nil))
12065 (when (and org-blocker-hook
12066 (or org-inhibit-blocking
12067 (org-entry-get nil "NOBLOCKING")))
12068 (setq org-blocker-hook nil))
12069 (save-excursion
12070 (catch 'exit
12071 (org-back-to-heading t)
12072 (when (org-in-commented-heading-p t)
12073 (org-toggle-comment)
12074 (setq commentp t))
12075 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12076 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12077 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12078 (let* ((match-data (match-data))
12079 (startpos (point-at-bol))
12080 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12081 (org-log-done org-log-done)
12082 (org-log-repeat org-log-repeat)
12083 (org-todo-log-states org-todo-log-states)
12084 (org-inhibit-logging
12085 (if (equal arg 0)
12086 (progn (setq arg nil) 'note) org-inhibit-logging))
12087 (this (match-string 1))
12088 (hl-pos (match-beginning 0))
12089 (head (org-get-todo-sequence-head this))
12090 (ass (assoc head org-todo-kwd-alist))
12091 (interpret (nth 1 ass))
12092 (done-word (nth 3 ass))
12093 (final-done-word (nth 4 ass))
12094 (org-last-state (or this ""))
12095 (completion-ignore-case t)
12096 (member (member this org-todo-keywords-1))
12097 (tail (cdr member))
12098 (org-state (cond
12099 ((and org-todo-key-trigger
12100 (or (and (equal arg '(4))
12101 (eq org-use-fast-todo-selection 'prefix))
12102 (and (not arg) org-use-fast-todo-selection
12103 (not (eq org-use-fast-todo-selection
12104 'prefix)))))
12105 ;; Use fast selection.
12106 (org-fast-todo-selection))
12107 ((and (equal arg '(4))
12108 (or (not org-use-fast-todo-selection)
12109 (not org-todo-key-trigger)))
12110 ;; Read a state with completion.
12111 (completing-read
12112 "State: " (mapcar #'list org-todo-keywords-1)
12113 nil t))
12114 ((eq arg 'right)
12115 (if this
12116 (if tail (car tail) nil)
12117 (car org-todo-keywords-1)))
12118 ((eq arg 'left)
12119 (unless (equal member org-todo-keywords-1)
12120 (if this
12121 (nth (- (length org-todo-keywords-1)
12122 (length tail) 2)
12123 org-todo-keywords-1)
12124 (org-last org-todo-keywords-1))))
12125 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12126 (setq arg nil))) ;hack to fall back to cycling
12127 (arg
12128 ;; User or caller requests a specific state.
12129 (cond
12130 ((equal arg "") nil)
12131 ((eq arg 'none) nil)
12132 ((eq arg 'done) (or done-word (car org-done-keywords)))
12133 ((eq arg 'nextset)
12134 (or (car (cdr (member head org-todo-heads)))
12135 (car org-todo-heads)))
12136 ((eq arg 'previousset)
12137 (let ((org-todo-heads (reverse org-todo-heads)))
12138 (or (car (cdr (member head org-todo-heads)))
12139 (car org-todo-heads))))
12140 ((car (member arg org-todo-keywords-1)))
12141 ((stringp arg)
12142 (user-error "State `%s' not valid in this file" arg))
12143 ((nth (1- (prefix-numeric-value arg))
12144 org-todo-keywords-1))))
12145 ((null member) (or head (car org-todo-keywords-1)))
12146 ((equal this final-done-word) nil) ;-> make empty
12147 ((null tail) nil) ;-> first entry
12148 ((memq interpret '(type priority))
12149 (if (eq this-command last-command)
12150 (car tail)
12151 (if (> (length tail) 0)
12152 (or done-word (car org-done-keywords))
12153 nil)))
12155 (car tail))))
12156 (org-state (or
12157 (run-hook-with-args-until-success
12158 'org-todo-get-default-hook org-state org-last-state)
12159 org-state))
12160 (next (if org-state (concat " " org-state " ") " "))
12161 (change-plist (list :type 'todo-state-change :from this :to org-state
12162 :position startpos))
12163 dolog now-done-p)
12164 (when org-blocker-hook
12165 (let (org-blocked-by-checkboxes block-reason)
12166 (setq org-last-todo-state-is-todo
12167 (not (member this org-done-keywords)))
12168 (unless (save-excursion
12169 (save-match-data
12170 (org-with-wide-buffer
12171 (run-hook-with-args-until-failure
12172 'org-blocker-hook change-plist))))
12173 (setq block-reason (if org-blocked-by-checkboxes
12174 "contained checkboxes"
12175 (format "\"%s\"" org-block-entry-blocking)))
12176 (if (called-interactively-p 'interactive)
12177 (user-error "TODO state change from %s to %s blocked (by %s)"
12178 this org-state block-reason)
12179 ;; Fail silently.
12180 (message "TODO state change from %s to %s blocked (by %s)"
12181 this org-state block-reason)
12182 (throw 'exit nil)))))
12183 (store-match-data match-data)
12184 (replace-match next t t)
12185 (cond ((equal this org-state)
12186 (message "TODO state was already %s" (org-trim next)))
12187 ((not (pos-visible-in-window-p hl-pos))
12188 (message "TODO state changed to %s" (org-trim next))))
12189 (unless head
12190 (setq head (org-get-todo-sequence-head org-state)
12191 ass (assoc head org-todo-kwd-alist)
12192 interpret (nth 1 ass)
12193 done-word (nth 3 ass)
12194 final-done-word (nth 4 ass)))
12195 (when (memq arg '(nextset previousset))
12196 (message "Keyword-Set %d/%d: %s"
12197 (- (length org-todo-sets) -1
12198 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12199 (length org-todo-sets)
12200 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12201 (setq org-last-todo-state-is-todo
12202 (not (member org-state org-done-keywords)))
12203 (setq now-done-p (and (member org-state org-done-keywords)
12204 (not (member this org-done-keywords))))
12205 (and logging (org-local-logging logging))
12206 (when (and (or org-todo-log-states org-log-done)
12207 (not (eq org-inhibit-logging t))
12208 (not (memq arg '(nextset previousset))))
12209 ;; We need to look at recording a time and note.
12210 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12211 (nth 2 (assoc this org-todo-log-states))))
12212 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12213 (setq dolog 'time))
12214 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12215 (and org-state
12216 (member org-state org-not-done-keywords)
12217 (not (member this org-not-done-keywords))))
12218 ;; This is now a todo state and was not one before
12219 ;; If there was a CLOSED time stamp, get rid of it.
12220 (org-add-planning-info nil nil 'closed))
12221 (when (and now-done-p org-log-done)
12222 ;; It is now done, and it was not done before.
12223 (org-add-planning-info 'closed (org-current-effective-time))
12224 (when (and (not dolog) (eq 'note org-log-done))
12225 (org-add-log-setup 'done org-state this 'note)))
12226 (when (and org-state dolog)
12227 ;; This is a non-nil state, and we need to log it.
12228 (org-add-log-setup 'state org-state this dolog)))
12229 ;; Fixup tag positioning.
12230 (org-todo-trigger-tag-changes org-state)
12231 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12232 (when org-provide-todo-statistics
12233 (org-update-parent-todo-statistics))
12234 (run-hooks 'org-after-todo-state-change-hook)
12235 (when (and arg (not (member org-state org-done-keywords)))
12236 (setq head (org-get-todo-sequence-head org-state)))
12237 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12238 ;; Do we need to trigger a repeat?
12239 (when now-done-p
12240 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12241 ;; This is for the agenda, take a snapshot of the headline.
12242 (save-match-data
12243 (setq org-agenda-headline-snapshot-before-repeat
12244 (org-get-heading))))
12245 (org-auto-repeat-maybe org-state))
12246 ;; Fixup cursor location if close to the keyword.
12247 (when (and (outline-on-heading-p)
12248 (not (bolp))
12249 (save-excursion (beginning-of-line 1)
12250 (looking-at org-todo-line-regexp))
12251 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12252 (goto-char (or (match-end 2) (match-end 1)))
12253 (and (looking-at " ") (just-one-space)))
12254 (when org-trigger-hook
12255 (save-excursion
12256 (run-hook-with-args 'org-trigger-hook change-plist)))
12257 (when commentp (org-toggle-comment))))))))
12259 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12260 "Block turning an entry into a TODO, using the hierarchy.
12261 This checks whether the current task should be blocked from state
12262 changes. Such blocking occurs when:
12264 1. The task has children which are not all in a completed state.
12266 2. A task has a parent with the property :ORDERED:, and there
12267 are siblings prior to the current task with incomplete
12268 status.
12270 3. The parent of the task is blocked because it has siblings that should
12271 be done first, or is child of a block grandparent TODO entry."
12273 (if (not org-enforce-todo-dependencies)
12274 t ; if locally turned off don't block
12275 (catch 'dont-block
12276 ;; If this is not a todo state change, or if this entry is already DONE,
12277 ;; do not block
12278 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12279 (member (plist-get change-plist :from)
12280 (cons 'done org-done-keywords))
12281 (member (plist-get change-plist :to)
12282 (cons 'todo org-not-done-keywords))
12283 (not (plist-get change-plist :to)))
12284 (throw 'dont-block t))
12285 ;; If this task has children, and any are undone, it's blocked
12286 (save-excursion
12287 (org-back-to-heading t)
12288 (let ((this-level (funcall outline-level)))
12289 (outline-next-heading)
12290 (let ((child-level (funcall outline-level)))
12291 (while (and (not (eobp))
12292 (> child-level this-level))
12293 ;; this todo has children, check whether they are all
12294 ;; completed
12295 (when (and (not (org-entry-is-done-p))
12296 (org-entry-is-todo-p))
12297 (setq org-block-entry-blocking (org-get-heading))
12298 (throw 'dont-block nil))
12299 (outline-next-heading)
12300 (setq child-level (funcall outline-level))))))
12301 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12302 ;; any previous siblings are undone, it's blocked
12303 (save-excursion
12304 (org-back-to-heading t)
12305 (let* ((pos (point))
12306 (parent-pos (and (org-up-heading-safe) (point)))
12307 (case-fold-search nil))
12308 (unless parent-pos (throw 'dont-block t)) ; no parent
12309 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12310 (forward-line 1)
12311 (re-search-forward org-not-done-heading-regexp pos t))
12312 (setq org-block-entry-blocking (match-string 0))
12313 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12314 ;; Search further up the hierarchy, to see if an ancestor is blocked
12315 (while t
12316 (goto-char parent-pos)
12317 (unless (looking-at org-not-done-heading-regexp)
12318 (throw 'dont-block t)) ; do not block, parent is not a TODO
12319 (setq pos (point))
12320 (setq parent-pos (and (org-up-heading-safe) (point)))
12321 (unless parent-pos (throw 'dont-block t)) ; no parent
12322 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12323 (forward-line 1)
12324 (re-search-forward org-not-done-heading-regexp pos t)
12325 (setq org-block-entry-blocking (org-get-heading)))
12326 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12328 (defcustom org-track-ordered-property-with-tag nil
12329 "Should the ORDERED property also be shown as a tag?
12330 The ORDERED property decides if an entry should require subtasks to be
12331 completed in sequence. Since a property is not very visible, setting
12332 this option means that toggling the ORDERED property with the command
12333 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12334 not relevant for the behavior, but it makes things more visible.
12336 Note that toggling the tag with tags commands will not change the property
12337 and therefore not influence behavior!
12339 This can be t, meaning the tag ORDERED should be used, It can also be a
12340 string to select a different tag for this task."
12341 :group 'org-todo
12342 :type '(choice
12343 (const :tag "No tracking" nil)
12344 (const :tag "Track with ORDERED tag" t)
12345 (string :tag "Use other tag")))
12347 (defun org-toggle-ordered-property ()
12348 "Toggle the ORDERED property of the current entry.
12349 For better visibility, you can track the value of this property with a tag.
12350 See variable `org-track-ordered-property-with-tag'."
12351 (interactive)
12352 (let* ((t1 org-track-ordered-property-with-tag)
12353 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12354 (save-excursion
12355 (org-back-to-heading)
12356 (if (org-entry-get nil "ORDERED")
12357 (progn
12358 (org-delete-property "ORDERED")
12359 (and tag (org-toggle-tag tag 'off))
12360 (message "Subtasks can be completed in arbitrary order"))
12361 (org-entry-put nil "ORDERED" "t")
12362 (and tag (org-toggle-tag tag 'on))
12363 (message "Subtasks must be completed in sequence")))))
12365 (defun org-block-todo-from-checkboxes (change-plist)
12366 "Block turning an entry into a TODO, using checkboxes.
12367 This checks whether the current task should be blocked from state
12368 changes because there are unchecked boxes in this entry."
12369 (if (not org-enforce-todo-checkbox-dependencies)
12370 t ; if locally turned off don't block
12371 (catch 'dont-block
12372 ;; If this is not a todo state change, or if this entry is already DONE,
12373 ;; do not block
12374 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12375 (member (plist-get change-plist :from)
12376 (cons 'done org-done-keywords))
12377 (member (plist-get change-plist :to)
12378 (cons 'todo org-not-done-keywords))
12379 (not (plist-get change-plist :to)))
12380 (throw 'dont-block t))
12381 ;; If this task has checkboxes that are not checked, it's blocked
12382 (save-excursion
12383 (org-back-to-heading t)
12384 (let ((beg (point)) end)
12385 (outline-next-heading)
12386 (setq end (point))
12387 (goto-char beg)
12388 (when (org-list-search-forward
12389 (concat (org-item-beginning-re)
12390 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12391 "\\[[- ]\\]")
12392 end t)
12393 (when (boundp 'org-blocked-by-checkboxes)
12394 (setq org-blocked-by-checkboxes t))
12395 (throw 'dont-block nil))))
12396 t))) ; do not block
12398 (defun org-entry-blocked-p ()
12399 "Non-nil if entry at point is blocked."
12400 (and (not (org-entry-get nil "NOBLOCKING"))
12401 (member (org-entry-get nil "TODO") org-not-done-keywords)
12402 (not (run-hook-with-args-until-failure
12403 'org-blocker-hook
12404 (list :type 'todo-state-change
12405 :position (point)
12406 :from 'todo
12407 :to 'done)))))
12409 (defun org-update-statistics-cookies (all)
12410 "Update the statistics cookie, either from TODO or from checkboxes.
12411 This should be called with the cursor in a line with a statistics
12412 cookie. When called with a \\[universal-argument] prefix, update
12413 all statistics cookies in the buffer."
12414 (interactive "P")
12415 (if all
12416 (progn
12417 (org-update-checkbox-count 'all)
12418 (org-map-entries 'org-update-parent-todo-statistics))
12419 (if (not (org-at-heading-p))
12420 (org-update-checkbox-count)
12421 (let ((pos (point-marker))
12422 end l1 l2)
12423 (ignore-errors (org-back-to-heading t))
12424 (if (not (org-at-heading-p))
12425 (org-update-checkbox-count)
12426 (setq l1 (org-outline-level))
12427 (setq end (save-excursion
12428 (outline-next-heading)
12429 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12430 (point)))
12431 (if (and (save-excursion
12432 (re-search-forward
12433 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12434 (not (save-excursion (re-search-forward
12435 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12436 (org-update-checkbox-count)
12437 (if (and l2 (> l2 l1))
12438 (progn
12439 (goto-char end)
12440 (org-update-parent-todo-statistics))
12441 (goto-char pos)
12442 (beginning-of-line 1)
12443 (while (re-search-forward
12444 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12445 (point-at-eol) t)
12446 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12447 (goto-char pos)
12448 (move-marker pos nil)))))
12450 (defvar org-entry-property-inherited-from) ;; defined below
12451 (defun org-update-parent-todo-statistics ()
12452 "Update any statistics cookie in the parent of the current headline.
12453 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12454 the entire subtree and this will travel up the hierarchy and update
12455 statistics everywhere."
12456 (let* ((prop (save-excursion (org-up-heading-safe)
12457 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12458 (recursive (or (not org-hierarchical-todo-statistics)
12459 (and prop (string-match "\\<recursive\\>" prop))))
12460 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12462 (first t)
12463 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12464 level ltoggle l1 new ndel
12465 (cnt-all 0) (cnt-done 0) is-percent kwd
12466 checkbox-beg cookie-present)
12467 (catch 'exit
12468 (save-excursion
12469 (beginning-of-line 1)
12470 (setq ltoggle (funcall outline-level))
12471 ;; Three situations are to consider:
12473 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12474 ;; to the top-level ancestor on the headline;
12476 ;; 2. If parent has "recursive" property, repeat up to the
12477 ;; headline setting that property, taking inheritance into
12478 ;; account;
12480 ;; 3. Else, move up to direct parent and proceed only once.
12481 (while (and (setq level (org-up-heading-safe))
12482 (or recursive first)
12483 (>= (point) lim))
12484 (setq first nil cookie-present nil)
12485 (unless (and level
12486 (not (string-match
12487 "\\<checkbox\\>"
12488 (downcase (or (org-entry-get nil "COOKIE_DATA")
12489 "")))))
12490 (throw 'exit nil))
12491 (while (re-search-forward box-re (point-at-eol) t)
12492 (setq cnt-all 0 cnt-done 0 cookie-present t)
12493 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12494 (save-match-data
12495 (unless (outline-next-heading) (throw 'exit nil))
12496 (while (and (looking-at org-complex-heading-regexp)
12497 (> (setq l1 (length (match-string 1))) level))
12498 (setq kwd (and (or recursive (= l1 ltoggle))
12499 (match-string 2)))
12500 (if (or (eq org-provide-todo-statistics 'all-headlines)
12501 (and (eq org-provide-todo-statistics t)
12502 (or (member kwd org-done-keywords)))
12503 (and (listp org-provide-todo-statistics)
12504 (stringp (car org-provide-todo-statistics))
12505 (or (member kwd org-provide-todo-statistics)
12506 (member kwd org-done-keywords)))
12507 (and (listp org-provide-todo-statistics)
12508 (listp (car org-provide-todo-statistics))
12509 (or (member kwd (car org-provide-todo-statistics))
12510 (and (member kwd org-done-keywords)
12511 (member kwd (cadr org-provide-todo-statistics))))))
12512 (setq cnt-all (1+ cnt-all))
12513 (and (eq org-provide-todo-statistics t)
12515 (setq cnt-all (1+ cnt-all))))
12516 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12517 (member kwd org-done-keywords))
12518 (and (listp org-provide-todo-statistics)
12519 (listp (car org-provide-todo-statistics))
12520 (member kwd org-done-keywords)
12521 (member kwd (cadr org-provide-todo-statistics)))
12522 (and (listp org-provide-todo-statistics)
12523 (stringp (car org-provide-todo-statistics))
12524 (member kwd org-done-keywords)))
12525 (setq cnt-done (1+ cnt-done)))
12526 (outline-next-heading)))
12527 (setq new
12528 (if is-percent
12529 (format "[%d%%]" (floor (* 100.0 cnt-done)
12530 (max 1 cnt-all)))
12531 (format "[%d/%d]" cnt-done cnt-all))
12532 ndel (- (match-end 0) checkbox-beg))
12533 (goto-char checkbox-beg)
12534 (insert new)
12535 (delete-region (point) (+ (point) ndel))
12536 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12537 (when cookie-present
12538 (run-hook-with-args 'org-after-todo-statistics-hook
12539 cnt-done (- cnt-all cnt-done))))))
12540 (run-hooks 'org-todo-statistics-hook)))
12542 (defvar org-after-todo-statistics-hook nil
12543 "Hook that is called after a TODO statistics cookie has been updated.
12544 Each function is called with two arguments: the number of not-done entries
12545 and the number of done entries.
12547 For example, the following function, when added to this hook, will switch
12548 an entry to DONE when all children are done, and back to TODO when new
12549 entries are set to a TODO status. Note that this hook is only called
12550 when there is a statistics cookie in the headline!
12552 (defun org-summary-todo (n-done n-not-done)
12553 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12554 (let (org-log-done org-log-states) ; turn off logging
12555 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12558 (defvar org-todo-statistics-hook nil
12559 "Hook that is run whenever Org thinks TODO statistics should be updated.
12560 This hook runs even if there is no statistics cookie present, in which case
12561 `org-after-todo-statistics-hook' would not run.")
12563 (defun org-todo-trigger-tag-changes (state)
12564 "Apply the changes defined in `org-todo-state-tags-triggers'."
12565 (let ((l org-todo-state-tags-triggers)
12566 changes)
12567 (when (or (not state) (equal state ""))
12568 (setq changes (append changes (cdr (assoc "" l)))))
12569 (when (and (stringp state) (> (length state) 0))
12570 (setq changes (append changes (cdr (assoc state l)))))
12571 (when (member state org-not-done-keywords)
12572 (setq changes (append changes (cdr (assq 'todo l)))))
12573 (when (member state org-done-keywords)
12574 (setq changes (append changes (cdr (assq 'done l)))))
12575 (dolist (c changes)
12576 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12578 (defun org-local-logging (value)
12579 "Get logging settings from a property VALUE."
12580 ;; Directly set the variables, they are already local.
12581 (setq org-log-done nil
12582 org-log-repeat nil
12583 org-todo-log-states nil)
12584 (dolist (w (split-string value))
12585 (let (a)
12586 (cond
12587 ((setq a (assoc w org-startup-options))
12588 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12589 (set (nth 1 a) (nth 2 a))))
12590 ((setq a (org-extract-log-state-settings w))
12591 (and (member (car a) org-todo-keywords-1)
12592 (push a org-todo-log-states)))))))
12594 (defun org-get-todo-sequence-head (kwd)
12595 "Return the head of the TODO sequence to which KWD belongs.
12596 If KWD is not set, check if there is a text property remembering the
12597 right sequence."
12598 (let (p)
12599 (cond
12600 ((not kwd)
12601 (or (get-text-property (point-at-bol) 'org-todo-head)
12602 (progn
12603 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12604 nil (point-at-eol)))
12605 (get-text-property p 'org-todo-head))))
12606 ((not (member kwd org-todo-keywords-1))
12607 (car org-todo-keywords-1))
12608 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12610 (defun org-fast-todo-selection ()
12611 "Fast TODO keyword selection with single keys.
12612 Returns the new TODO keyword, or nil if no state change should occur."
12613 (let* ((fulltable org-todo-key-alist)
12614 (done-keywords org-done-keywords) ;; needed for the faces.
12615 (maxlen (apply 'max (mapcar
12616 (lambda (x)
12617 (if (stringp (car x)) (string-width (car x)) 0))
12618 fulltable)))
12619 (expert nil)
12620 (fwidth (+ maxlen 3 1 3))
12621 (ncol (/ (- (window-width) 4) fwidth))
12622 tg cnt e c tbl
12623 groups ingroup)
12624 (save-excursion
12625 (save-window-excursion
12626 (if expert
12627 (set-buffer (get-buffer-create " *Org todo*"))
12628 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12629 (erase-buffer)
12630 (setq-local org-done-keywords done-keywords)
12631 (setq tbl fulltable cnt 0)
12632 (while (setq e (pop tbl))
12633 (cond
12634 ((equal e '(:startgroup))
12635 (push '() groups) (setq ingroup t)
12636 (unless (= cnt 0)
12637 (setq cnt 0)
12638 (insert "\n"))
12639 (insert "{ "))
12640 ((equal e '(:endgroup))
12641 (setq ingroup nil cnt 0)
12642 (insert "}\n"))
12643 ((equal e '(:newline))
12644 (unless (= cnt 0)
12645 (setq cnt 0)
12646 (insert "\n")
12647 (setq e (car tbl))
12648 (while (equal (car tbl) '(:newline))
12649 (insert "\n")
12650 (setq tbl (cdr tbl)))))
12652 (setq tg (car e) c (cdr e))
12653 (when ingroup (push tg (car groups)))
12654 (setq tg (org-add-props tg nil 'face
12655 (org-get-todo-face tg)))
12656 (when (and (= cnt 0) (not ingroup)) (insert " "))
12657 (insert "[" c "] " tg (make-string
12658 (- fwidth 4 (length tg)) ?\ ))
12659 (when (= (setq cnt (1+ cnt)) ncol)
12660 (insert "\n")
12661 (when ingroup (insert " "))
12662 (setq cnt 0)))))
12663 (insert "\n")
12664 (goto-char (point-min))
12665 (unless expert (org-fit-window-to-buffer))
12666 (message "[a-z..]:Set [SPC]:clear")
12667 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12668 (cond
12669 ((or (= c ?\C-g)
12670 (and (= c ?q) (not (rassoc c fulltable))))
12671 (setq quit-flag t))
12672 ((= c ?\ ) nil)
12673 ((setq e (rassoc c fulltable) tg (car e))
12675 (t (setq quit-flag t)))))))
12677 (defun org-entry-is-todo-p ()
12678 (member (org-get-todo-state) org-not-done-keywords))
12680 (defun org-entry-is-done-p ()
12681 (member (org-get-todo-state) org-done-keywords))
12683 (defun org-get-todo-state ()
12684 "Return the TODO keyword of the current subtree."
12685 (save-excursion
12686 (org-back-to-heading t)
12687 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12688 (match-end 2)
12689 (match-string 2))))
12691 (defun org-at-date-range-p (&optional inactive-ok)
12692 "Non-nil if point is inside a date range.
12694 When optional argument INACTIVE-OK is non-nil, also consider
12695 inactive time ranges.
12697 When this function returns a non-nil value, match data is set
12698 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12699 on INACTIVE-OK."
12700 (interactive)
12701 (save-excursion
12702 (catch 'exit
12703 (let ((pos (point)))
12704 (skip-chars-backward "^[<\r\n")
12705 (skip-chars-backward "<[")
12706 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12707 (>= (match-end 0) pos)
12708 (throw 'exit t))
12709 (skip-chars-backward "^<[\r\n")
12710 (skip-chars-backward "<[")
12711 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12712 (>= (match-end 0) pos)
12713 (throw 'exit t)))
12714 nil)))
12716 (defun org-get-repeat (&optional timestamp)
12717 "Check if there is a time-stamp with repeater in this entry.
12719 Return the repeater, as a string, or nil. Also return nil when
12720 this function is called before first heading.
12722 When optional argument TIMESTAMP is a string, extract the
12723 repeater from there instead."
12724 (save-match-data
12725 (cond (timestamp
12726 (and (string-match org-repeat-re timestamp)
12727 (match-string-no-properties 1 timestamp)))
12728 ((org-before-first-heading-p) nil)
12730 (save-excursion
12731 (org-back-to-heading t)
12732 (let ((end (org-entry-end-position)))
12733 (catch :repeat
12734 (while (re-search-forward org-repeat-re end t)
12735 (when (save-match-data (org-at-timestamp-p 'agenda))
12736 (throw :repeat (match-string-no-properties 1)))))))))))
12738 (defvar org-last-changed-timestamp)
12739 (defvar org-last-inserted-timestamp)
12740 (defvar org-log-post-message)
12741 (defvar org-log-note-purpose)
12742 (defvar org-log-note-how nil)
12743 (defvar org-log-note-extra)
12744 (defun org-auto-repeat-maybe (done-word)
12745 "Check if the current headline contains a repeated time-stamp.
12747 If yes, set TODO state back to what it was and change the base date
12748 of repeating deadline/scheduled time stamps to new date.
12750 This function is run automatically after each state change to a DONE state."
12751 (let* ((repeat (org-get-repeat))
12752 (aa (assoc org-last-state org-todo-kwd-alist))
12753 (interpret (nth 1 aa))
12754 (head (nth 2 aa))
12755 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12756 (msg "Entry repeats: ")
12757 (org-log-done nil)
12758 (org-todo-log-states nil)
12759 (end (copy-marker (org-entry-end-position))))
12760 (unwind-protect
12761 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12762 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12763 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12764 org-todo-repeat-to-state)))
12765 (org-todo (cond
12766 ((and to-state (member to-state org-todo-keywords-1))
12767 to-state)
12768 ((eq interpret 'type) org-last-state)
12769 (head)
12770 (t 'none))))
12771 (org-back-to-heading t)
12772 (org-add-planning-info nil nil 'closed)
12773 ;; When `org-log-repeat' is non-nil or entry contains
12774 ;; a clock, set LAST_REPEAT property.
12775 (when (or org-log-repeat
12776 (catch :clock
12777 (save-excursion
12778 (while (re-search-forward org-clock-line-re end t)
12779 (when (org-at-clock-log-p) (throw :clock t))))))
12780 (org-entry-put nil "LAST_REPEAT" (format-time-string
12781 (org-time-stamp-format t t)
12782 (current-time))))
12783 (when org-log-repeat
12784 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12785 (memq 'org-add-log-note post-command-hook))
12786 ;; We are already setup for some record.
12787 (when (eq org-log-repeat 'note)
12788 ;; Make sure we take a note, not only a time stamp.
12789 (setq org-log-note-how 'note))
12790 ;; Set up for taking a record.
12791 (org-add-log-setup 'state
12792 (or done-word (car org-done-keywords))
12793 org-last-state
12794 org-log-repeat)))
12795 (let ((planning-re (regexp-opt
12796 (list org-scheduled-string org-deadline-string))))
12797 (while (re-search-forward org-ts-regexp end t)
12798 (let* ((ts (match-string 0))
12799 (planning? (org-at-planning-p))
12800 (type (if (not planning?) "Plain:"
12801 (save-excursion
12802 (re-search-backward
12803 planning-re (line-beginning-position) t)
12804 (match-string 0)))))
12805 (cond
12806 ;; Ignore fake time-stamps (e.g., within comments).
12807 ((not (org-at-timestamp-p 'agenda)))
12808 ;; Time-stamps without a repeater are usually
12809 ;; skipped. However, a SCHEDULED time-stamp without
12810 ;; one is removed, as they are no longer relevant.
12811 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12812 ts))
12813 (when (equal type org-scheduled-string)
12814 (org-remove-timestamp-with-keyword type)))
12816 (let ((n (string-to-number (match-string 2 ts)))
12817 (what (match-string 3 ts)))
12818 (when (equal what "w") (setq n (* n 7) what "d"))
12819 (when (and (equal what "h")
12820 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12821 ts)))
12822 (user-error
12823 "Cannot repeat in Repeat in %d hour(s) because no hour \
12824 has been set"
12826 ;; Preparation, see if we need to modify the start
12827 ;; date for the change.
12828 (when (match-end 1)
12829 (let ((time (save-match-data
12830 (org-time-string-to-time ts))))
12831 (cond
12832 ((equal (match-string 1 ts) ".")
12833 ;; Shift starting date to today
12834 (org-timestamp-change
12835 (- (org-today) (time-to-days time))
12836 'day))
12837 ((equal (match-string 1 ts) "+")
12838 (let ((nshiftmax 10)
12839 (nshift 0))
12840 (while (or (= nshift 0)
12841 (not (time-less-p (current-time) time)))
12842 (when (= (cl-incf nshift) nshiftmax)
12843 (or (y-or-n-p
12844 (format "%d repeater intervals were not \
12845 enough to shift date past today. Continue? "
12846 nshift))
12847 (user-error "Abort")))
12848 (org-timestamp-change n (cdr (assoc what whata)))
12849 (org-in-regexp org-ts-regexp3)
12850 (setq ts (match-string 1))
12851 (setq time
12852 (save-match-data
12853 (org-time-string-to-time ts)))))
12854 (org-timestamp-change (- n) (cdr (assoc what whata)))
12855 ;; Rematch, so that we have everything in place
12856 ;; for the real shift.
12857 (org-in-regexp org-ts-regexp3)
12858 (setq ts (match-string 1))
12859 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12860 ts)))))
12861 (save-excursion
12862 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12863 (setq msg
12864 (concat
12865 msg type " " org-last-changed-timestamp " "))))))))
12866 (setq org-log-post-message msg)
12867 (message "%s" msg))
12868 (set-marker end nil))))
12870 (defun org-show-todo-tree (arg)
12871 "Make a compact tree which shows all headlines marked with TODO.
12872 The tree will show the lines where the regexp matches, and all higher
12873 headlines above the match.
12874 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12875 With a numeric prefix N, construct a sparse tree for the Nth element
12876 of `org-todo-keywords-1'."
12877 (interactive "P")
12878 (let ((case-fold-search nil)
12879 (kwd-re
12880 (cond ((null arg) org-not-done-regexp)
12881 ((equal arg '(4))
12882 (let ((kwd
12883 (completing-read "Keyword (or KWD1|KWD2|...): "
12884 (mapcar #'list org-todo-keywords-1))))
12885 (concat "\\("
12886 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12887 "\\)\\>")))
12888 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12889 (regexp-quote (nth (1- (prefix-numeric-value arg))
12890 org-todo-keywords-1)))
12891 (t (user-error "Invalid prefix argument: %s" arg)))))
12892 (message "%d TODO entries found"
12893 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12895 (defun org--deadline-or-schedule (arg type time)
12896 "Insert DEADLINE or SCHEDULE information in current entry.
12897 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12898 `org-schedule' for information about ARG and TIME arguments."
12899 (let* ((deadline? (eq type 'deadline))
12900 (keyword (if deadline? org-deadline-string org-scheduled-string))
12901 (log (if deadline? org-log-redeadline org-log-reschedule))
12902 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12903 (old-date-time (and old-date (org-time-string-to-time old-date)))
12904 ;; Save repeater cookie from either TIME or current scheduled
12905 ;; time stamp. We are going to insert it back at the end of
12906 ;; the process.
12907 (repeater (or (and (org-string-nw-p time)
12908 ;; We use `org-repeat-re' because we need
12909 ;; to tell the difference between a real
12910 ;; repeater and a time delta, e.g. "+2d".
12911 (string-match org-repeat-re time)
12912 (match-string 1 time))
12913 (and (org-string-nw-p old-date)
12914 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12915 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12916 old-date)
12917 (match-string 1 old-date)))))
12918 (pcase arg
12919 (`(4)
12920 (when (and old-date log)
12921 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12922 nil old-date log))
12923 (org-remove-timestamp-with-keyword keyword)
12924 (message (if deadline? "Item no longer has a deadline."
12925 "Item is no longer scheduled.")))
12926 (`(16)
12927 (save-excursion
12928 (org-back-to-heading t)
12929 (let ((regexp (if deadline? org-deadline-time-regexp
12930 org-scheduled-time-regexp)))
12931 (if (not (re-search-forward regexp (line-end-position 2) t))
12932 (user-error (if deadline? "No deadline information to update"
12933 "No scheduled information to update"))
12934 (let* ((rpl0 (match-string 1))
12935 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12936 (msg (if deadline? "Warn starting from" "Delay until")))
12937 (replace-match
12938 (concat keyword
12939 " <" rpl
12940 (format " -%dd"
12941 (abs (- (time-to-days
12942 (save-match-data
12943 (org-read-date
12944 nil t nil msg old-date-time)))
12945 (time-to-days old-date-time))))
12946 ">") t t))))))
12948 (org-add-planning-info type time 'closed)
12949 (when (and old-date
12951 (not (equal old-date org-last-inserted-timestamp)))
12952 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12953 org-last-inserted-timestamp
12954 old-date
12955 log))
12956 (when repeater
12957 (save-excursion
12958 (org-back-to-heading t)
12959 (when (re-search-forward
12960 (concat keyword " " org-last-inserted-timestamp)
12961 (line-end-position 2)
12963 (goto-char (1- (match-end 0)))
12964 (insert " " repeater)
12965 (setq org-last-inserted-timestamp
12966 (concat (substring org-last-inserted-timestamp 0 -1)
12967 " " repeater
12968 (substring org-last-inserted-timestamp -1))))))
12969 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12970 org-last-inserted-timestamp)))))
12972 (defun org-deadline (arg &optional time)
12973 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12974 With one universal prefix argument, remove any deadline from the item.
12975 With two universal prefix arguments, prompt for a warning delay.
12976 With argument TIME, set the deadline at the corresponding date. TIME
12977 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12978 (interactive "P")
12979 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12980 (org-map-entries
12981 (lambda () (org--deadline-or-schedule arg 'deadline time))
12983 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12984 'region-start-level
12985 'region)
12986 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12987 (org--deadline-or-schedule arg 'deadline time)))
12989 (defun org-schedule (arg &optional time)
12990 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12991 With one universal prefix argument, remove any scheduling date from the item.
12992 With two universal prefix arguments, prompt for a delay cookie.
12993 With argument TIME, scheduled at the corresponding date. TIME can
12994 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12995 (interactive "P")
12996 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12997 (org-map-entries
12998 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13000 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13001 'region-start-level
13002 'region)
13003 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13004 (org--deadline-or-schedule arg 'scheduled time)))
13006 (defun org-get-scheduled-time (pom &optional inherit)
13007 "Get the scheduled time as a time tuple, of a format suitable
13008 for calling org-schedule with, or if there is no scheduling,
13009 returns nil."
13010 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13011 (when time
13012 (apply 'encode-time (org-parse-time-string time)))))
13014 (defun org-get-deadline-time (pom &optional inherit)
13015 "Get the deadline as a time tuple, of a format suitable for
13016 calling org-deadline with, or if there is no scheduling, returns
13017 nil."
13018 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13019 (when time
13020 (apply 'encode-time (org-parse-time-string time)))))
13022 (defun org-remove-timestamp-with-keyword (keyword)
13023 "Remove all time stamps with KEYWORD in the current entry."
13024 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13025 beg)
13026 (save-excursion
13027 (org-back-to-heading t)
13028 (setq beg (point))
13029 (outline-next-heading)
13030 (while (re-search-backward re beg t)
13031 (replace-match "")
13032 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13033 (equal (char-before) ?\ ))
13034 (backward-delete-char 1)
13035 (when (string-match "^[ \t]*$" (buffer-substring
13036 (point-at-bol) (point-at-eol)))
13037 (delete-region (point-at-bol)
13038 (min (point-max) (1+ (point-at-eol))))))))))
13040 (defvar org-time-was-given) ; dynamically scoped parameter
13041 (defvar org-end-time-was-given) ; dynamically scoped parameter
13043 (defun org-at-planning-p ()
13044 "Non-nil when point is on a planning info line."
13045 ;; This is as accurate and faster than `org-element-at-point' since
13046 ;; planning info location is fixed in the section.
13047 (org-with-wide-buffer
13048 (beginning-of-line)
13049 (and (looking-at-p org-planning-line-re)
13050 (eq (point)
13051 (ignore-errors
13052 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13053 (org-back-to-heading t)
13054 (org-with-limited-levels (org-back-to-heading t)))
13055 (line-beginning-position 2))))))
13057 (defun org-add-planning-info (what &optional time &rest remove)
13058 "Insert new timestamp with keyword in the planning line.
13059 WHAT indicates what kind of time stamp to add. It is a symbol
13060 among `closed', `deadline', `scheduled' and nil. TIME indicates
13061 the time to use. If none is given, the user is prompted for
13062 a date. REMOVE indicates what kind of entries to remove. An old
13063 WHAT entry will also be removed."
13064 (let (org-time-was-given org-end-time-was-given default-time default-input)
13065 (catch 'exit
13066 (when (and (memq what '(scheduled deadline))
13067 (or (not time)
13068 (and (stringp time)
13069 (string-match "^[-+]+[0-9]" time))))
13070 ;; Try to get a default date/time from existing timestamp
13071 (save-excursion
13072 (org-back-to-heading t)
13073 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13074 (when (re-search-forward (if (eq what 'scheduled)
13075 org-scheduled-time-regexp
13076 org-deadline-time-regexp)
13077 end t)
13078 (setq ts (match-string 1)
13079 default-time (apply 'encode-time (org-parse-time-string ts))
13080 default-input (and ts (org-get-compact-tod ts)))))))
13081 (when what
13082 (setq time
13083 (if (stringp time)
13084 ;; This is a string (relative or absolute), set
13085 ;; proper date.
13086 (apply #'encode-time
13087 (org-read-date-analyze
13088 time default-time (decode-time default-time)))
13089 ;; If necessary, get the time from the user
13090 (or time (org-read-date nil 'to-time nil nil
13091 default-time default-input)))))
13093 (org-with-wide-buffer
13094 (org-back-to-heading t)
13095 (forward-line)
13096 (unless (bolp) (insert "\n"))
13097 (cond ((looking-at-p org-planning-line-re)
13098 ;; Move to current indentation.
13099 (skip-chars-forward " \t")
13100 ;; Check if we have to remove something.
13101 (dolist (type (if what (cons what remove) remove))
13102 (save-excursion
13103 (when (re-search-forward
13104 (cl-case type
13105 (closed org-closed-time-regexp)
13106 (deadline org-deadline-time-regexp)
13107 (scheduled org-scheduled-time-regexp)
13108 (otherwise
13109 (error "Invalid planning type: %s" type)))
13110 (line-end-position) t)
13111 ;; Delete until next keyword or end of line.
13112 (delete-region
13113 (match-beginning 0)
13114 (if (re-search-forward org-keyword-time-not-clock-regexp
13115 (line-end-position)
13117 (match-beginning 0)
13118 (line-end-position))))))
13119 ;; If there is nothing more to add and no more keyword
13120 ;; is left, remove the line completely.
13121 (if (and (looking-at-p "[ \t]*$") (not what))
13122 (delete-region (line-beginning-position)
13123 (line-beginning-position 2))
13124 ;; If we removed last keyword, do not leave trailing
13125 ;; white space at the end of line.
13126 (let ((p (point)))
13127 (save-excursion
13128 (end-of-line)
13129 (unless (= (skip-chars-backward " \t" p) 0)
13130 (delete-region (point) (line-end-position)))))))
13131 ((not what) (throw 'exit nil)) ; Nothing to do.
13132 (t (insert-before-markers "\n")
13133 (backward-char 1)
13134 (when org-adapt-indentation
13135 (indent-to-column (1+ (org-outline-level))))))
13136 (when what
13137 ;; Insert planning keyword.
13138 (insert (cl-case what
13139 (closed org-closed-string)
13140 (deadline org-deadline-string)
13141 (scheduled org-scheduled-string)
13142 (otherwise (error "Invalid planning type: %s" what)))
13143 " ")
13144 ;; Insert associated timestamp.
13145 (let ((ts (org-insert-time-stamp
13146 time
13147 (or org-time-was-given
13148 (and (eq what 'closed) org-log-done-with-time))
13149 (eq what 'closed)
13150 nil nil (list org-end-time-was-given))))
13151 (unless (eolp) (insert " "))
13152 ts))))))
13154 (defvar org-log-note-marker (make-marker)
13155 "Marker pointing at the entry where the note is to be inserted.")
13156 (defvar org-log-note-purpose nil)
13157 (defvar org-log-note-state nil)
13158 (defvar org-log-note-previous-state nil)
13159 (defvar org-log-note-extra nil)
13160 (defvar org-log-note-window-configuration nil)
13161 (defvar org-log-note-return-to (make-marker))
13162 (defvar org-log-note-effective-time nil
13163 "Remembered current time so that dynamically scoped
13164 `org-extend-today-until' affects timestamps in state change log")
13166 (defvar org-log-post-message nil
13167 "Message to be displayed after a log note has been stored.
13168 The auto-repeater uses this.")
13170 (defun org-add-note ()
13171 "Add a note to the current entry.
13172 This is done in the same way as adding a state change note."
13173 (interactive)
13174 (org-add-log-setup 'note))
13176 (defun org-log-beginning (&optional create)
13177 "Return expected start of log notes in current entry.
13178 When optional argument CREATE is non-nil, the function creates
13179 a drawer to store notes, if necessary. Returned position ignores
13180 narrowing."
13181 (org-with-wide-buffer
13182 (let ((drawer (org-log-into-drawer)))
13183 (cond
13184 (drawer
13185 (org-end-of-meta-data)
13186 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13187 (end (if (org-at-heading-p) (point)
13188 (save-excursion (outline-next-heading) (point))))
13189 (case-fold-search t))
13190 (catch 'exit
13191 ;; Try to find existing drawer.
13192 (while (re-search-forward regexp end t)
13193 (let ((element (org-element-at-point)))
13194 (when (eq (org-element-type element) 'drawer)
13195 (let ((cend (org-element-property :contents-end element)))
13196 (when (and (not org-log-states-order-reversed) cend)
13197 (goto-char cend)))
13198 (throw 'exit nil))))
13199 ;; No drawer found. Create one, if permitted.
13200 (when create
13201 (unless (bolp) (insert "\n"))
13202 (let ((beg (point)))
13203 (insert ":" drawer ":\n:END:\n")
13204 (org-indent-region beg (point)))
13205 (end-of-line -1)))))
13207 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13208 (skip-chars-forward " \t\n")
13209 (beginning-of-line)
13210 (unless org-log-states-order-reversed
13211 (org-skip-over-state-notes)
13212 (skip-chars-backward " \t\n")
13213 (forward-line)))))
13214 (if (bolp) (point) (line-beginning-position 2))))
13216 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13217 "Set up the post command hook to take a note.
13218 If this is about to TODO state change, the new state is expected in STATE.
13219 HOW is an indicator what kind of note should be created.
13220 EXTRA is additional text that will be inserted into the notes buffer."
13221 (move-marker org-log-note-marker (point))
13222 (setq org-log-note-purpose purpose
13223 org-log-note-state state
13224 org-log-note-previous-state prev-state
13225 org-log-note-how how
13226 org-log-note-extra extra
13227 org-log-note-effective-time (org-current-effective-time))
13228 (add-hook 'post-command-hook 'org-add-log-note 'append))
13230 (defun org-skip-over-state-notes ()
13231 "Skip past the list of State notes in an entry."
13232 (when (ignore-errors (goto-char (org-in-item-p)))
13233 (let* ((struct (org-list-struct))
13234 (prevs (org-list-prevs-alist struct))
13235 (regexp
13236 (concat "[ \t]*- +"
13237 (replace-regexp-in-string
13238 " +" " +"
13239 (org-replace-escapes
13240 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13241 `(("%d" . ,org-ts-regexp-inactive)
13242 ("%D" . ,org-ts-regexp)
13243 ("%s" . "\"\\S-+\"")
13244 ("%S" . "\"\\S-+\"")
13245 ("%t" . ,org-ts-regexp-inactive)
13246 ("%T" . ,org-ts-regexp)
13247 ("%u" . ".*?")
13248 ("%U" . ".*?")))))))
13249 (while (looking-at-p regexp)
13250 (goto-char (or (org-list-get-next-item (point) struct prevs)
13251 (org-list-get-item-end (point) struct)))))))
13253 (defun org-add-log-note (&optional _purpose)
13254 "Pop up a window for taking a note, and add this note later."
13255 (remove-hook 'post-command-hook 'org-add-log-note)
13256 (setq org-log-note-window-configuration (current-window-configuration))
13257 (delete-other-windows)
13258 (move-marker org-log-note-return-to (point))
13259 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13260 (goto-char org-log-note-marker)
13261 (org-switch-to-buffer-other-window "*Org Note*")
13262 (erase-buffer)
13263 (if (memq org-log-note-how '(time state))
13264 (org-store-log-note)
13265 (let ((org-inhibit-startup t)) (org-mode))
13266 (insert (format "# Insert note for %s.
13267 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13268 (cond
13269 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13270 ((eq org-log-note-purpose 'done) "closed todo item")
13271 ((eq org-log-note-purpose 'state)
13272 (format "state change from \"%s\" to \"%s\""
13273 (or org-log-note-previous-state "")
13274 (or org-log-note-state "")))
13275 ((eq org-log-note-purpose 'reschedule)
13276 "rescheduling")
13277 ((eq org-log-note-purpose 'delschedule)
13278 "no longer scheduled")
13279 ((eq org-log-note-purpose 'redeadline)
13280 "changing deadline")
13281 ((eq org-log-note-purpose 'deldeadline)
13282 "removing deadline")
13283 ((eq org-log-note-purpose 'refile)
13284 "refiling")
13285 ((eq org-log-note-purpose 'note)
13286 "this entry")
13287 (t (error "This should not happen")))))
13288 (when org-log-note-extra (insert org-log-note-extra))
13289 (setq-local org-finish-function 'org-store-log-note)
13290 (run-hooks 'org-log-buffer-setup-hook)))
13292 (defvar org-note-abort nil) ; dynamically scoped
13293 (defun org-store-log-note ()
13294 "Finish taking a log note, and insert it to where it belongs."
13295 (let ((txt (prog1 (buffer-string)
13296 (kill-buffer)))
13297 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13298 lines)
13299 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13300 (setq txt (replace-match "" t t txt)))
13301 (when (string-match "\\s-+\\'" txt)
13302 (setq txt (replace-match "" t t txt)))
13303 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13304 (when (org-string-nw-p note)
13305 (setq note
13306 (org-replace-escapes
13307 note
13308 (list (cons "%u" (user-login-name))
13309 (cons "%U" user-full-name)
13310 (cons "%t" (format-time-string
13311 (org-time-stamp-format 'long 'inactive)
13312 org-log-note-effective-time))
13313 (cons "%T" (format-time-string
13314 (org-time-stamp-format 'long nil)
13315 org-log-note-effective-time))
13316 (cons "%d" (format-time-string
13317 (org-time-stamp-format nil 'inactive)
13318 org-log-note-effective-time))
13319 (cons "%D" (format-time-string
13320 (org-time-stamp-format nil nil)
13321 org-log-note-effective-time))
13322 (cons "%s" (cond
13323 ((not org-log-note-state) "")
13324 ((string-match-p org-ts-regexp
13325 org-log-note-state)
13326 (format "\"[%s]\""
13327 (substring org-log-note-state 1 -1)))
13328 (t (format "\"%s\"" org-log-note-state))))
13329 (cons "%S"
13330 (cond
13331 ((not org-log-note-previous-state) "")
13332 ((string-match-p org-ts-regexp
13333 org-log-note-previous-state)
13334 (format "\"[%s]\""
13335 (substring
13336 org-log-note-previous-state 1 -1)))
13337 (t (format "\"%s\""
13338 org-log-note-previous-state)))))))
13339 (when lines (setq note (concat note " \\\\")))
13340 (push note lines))
13341 (when (and lines (not org-note-abort))
13342 (with-current-buffer (marker-buffer org-log-note-marker)
13343 (org-with-wide-buffer
13344 ;; Find location for the new note.
13345 (goto-char org-log-note-marker)
13346 (set-marker org-log-note-marker nil)
13347 ;; Note associated to a clock is to be located right after
13348 ;; the clock. Do not move point.
13349 (unless (eq org-log-note-purpose 'clock-out)
13350 (goto-char (org-log-beginning t)))
13351 ;; Make sure point is at the beginning of an empty line.
13352 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13353 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13354 ;; In an existing list, add a new item at the top level.
13355 ;; Otherwise, indent line like a regular one.
13356 (let ((itemp (org-in-item-p)))
13357 (if itemp
13358 (indent-line-to
13359 (let ((struct (save-excursion
13360 (goto-char itemp) (org-list-struct))))
13361 (org-list-get-ind (org-list-get-top-point struct) struct)))
13362 (org-indent-line)))
13363 (insert (org-list-bullet-string "-") (pop lines))
13364 (let ((ind (org-list-item-body-column (line-beginning-position))))
13365 (dolist (line lines)
13366 (insert "\n")
13367 (indent-line-to ind)
13368 (insert line)))
13369 (message "Note stored")
13370 (org-back-to-heading t)
13371 (org-cycle-hide-drawers 'children))
13372 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13373 ;; from within `org-add-log-note' because `buffer-undo-list'
13374 ;; is then modified outside of `org-with-remote-undo'.
13375 (when (eq this-command 'org-agenda-todo)
13376 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13377 ;; Don't add undo information when called from `org-agenda-todo'.
13378 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13379 (set-window-configuration org-log-note-window-configuration)
13380 (with-current-buffer (marker-buffer org-log-note-return-to)
13381 (goto-char org-log-note-return-to))
13382 (move-marker org-log-note-return-to nil)
13383 (when org-log-post-message (message "%s" org-log-post-message))))
13385 (defun org-remove-empty-drawer-at (pos)
13386 "Remove an empty drawer at position POS.
13387 POS may also be a marker."
13388 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13389 (org-with-wide-buffer
13390 (goto-char pos)
13391 (let ((drawer (org-element-at-point)))
13392 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13393 (not (org-element-property :contents-begin drawer)))
13394 (delete-region (org-element-property :begin drawer)
13395 (progn (goto-char (org-element-property :end drawer))
13396 (skip-chars-backward " \r\t\n")
13397 (forward-line)
13398 (point))))))))
13400 (defvar org-ts-type nil)
13401 (defun org-sparse-tree (&optional arg type)
13402 "Create a sparse tree, prompt for the details.
13403 This command can create sparse trees. You first need to select the type
13404 of match used to create the tree:
13406 t Show all TODO entries.
13407 T Show entries with a specific TODO keyword.
13408 m Show entries selected by a tags/property match.
13409 p Enter a property name and its value (both with completion on existing
13410 names/values) and show entries with that property.
13411 r Show entries matching a regular expression (`/' can be used as well).
13412 b Show deadlines and scheduled items before a date.
13413 a Show deadlines and scheduled items after a date.
13414 d Show deadlines due within `org-deadline-warning-days'.
13415 D Show deadlines and scheduled items between a date range."
13416 (interactive "P")
13417 (setq type (or type org-sparse-tree-default-date-type))
13418 (setq org-ts-type type)
13419 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13420 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13421 \[c]ycle through date types: %s"
13422 (cl-case type
13423 (all "all timestamps")
13424 (scheduled "only scheduled")
13425 (deadline "only deadline")
13426 (active "only active timestamps")
13427 (inactive "only inactive timestamps")
13428 (closed "with a closed time-stamp")
13429 (otherwise "scheduled/deadline")))
13430 (let ((answer (read-char-exclusive)))
13431 (cl-case answer
13433 (org-sparse-tree
13435 (cadr
13436 (memq type '(nil all scheduled deadline active inactive closed)))))
13437 (?d (call-interactively 'org-check-deadlines))
13438 (?b (call-interactively 'org-check-before-date))
13439 (?a (call-interactively 'org-check-after-date))
13440 (?D (call-interactively 'org-check-dates-range))
13441 (?t (call-interactively 'org-show-todo-tree))
13442 (?T (org-show-todo-tree '(4)))
13443 (?m (call-interactively 'org-match-sparse-tree))
13444 ((?p ?P)
13445 (let* ((kwd (completing-read
13446 "Property: " (mapcar #'list (org-buffer-property-keys))))
13447 (value (completing-read
13448 "Value: " (mapcar #'list (org-property-values kwd)))))
13449 (unless (string-match "\\`{.*}\\'" value)
13450 (setq value (concat "\"" value "\"")))
13451 (org-match-sparse-tree arg (concat kwd "=" value))))
13452 ((?r ?R ?/) (call-interactively 'org-occur))
13453 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13455 (defvar-local org-occur-highlights nil
13456 "List of overlays used for occur matches.")
13457 (defvar-local org-occur-parameters nil
13458 "Parameters of the active org-occur calls.
13459 This is a list, each call to org-occur pushes as cons cell,
13460 containing the regular expression and the callback, onto the list.
13461 The list can contain several entries if `org-occur' has been called
13462 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13463 will only contain one set of parameters. When the highlights are
13464 removed (for example with `C-c C-c', or with the next edit (depending
13465 on `org-remove-highlights-with-change'), this variable is emptied
13466 as well.")
13468 (defun org-occur (regexp &optional keep-previous callback)
13469 "Make a compact tree which shows all matches of REGEXP.
13471 The tree will show the lines where the regexp matches, and any other context
13472 defined in `org-show-context-detail', which see.
13474 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13475 done by a previous call to `org-occur' will be kept, to allow stacking of
13476 calls to this command.
13478 Optional argument CALLBACK can be a function of no argument. In this case,
13479 it is called with point at the end of the match, match data being set
13480 accordingly. Current match is shown only if the return value is non-nil.
13481 The function must neither move point nor alter narrowing."
13482 (interactive "sRegexp: \nP")
13483 (when (equal regexp "")
13484 (user-error "Regexp cannot be empty"))
13485 (unless keep-previous
13486 (org-remove-occur-highlights nil nil t))
13487 (push (cons regexp callback) org-occur-parameters)
13488 (let ((cnt 0))
13489 (save-excursion
13490 (goto-char (point-min))
13491 (when (or (not keep-previous) ; do not want to keep
13492 (not org-occur-highlights)) ; no previous matches
13493 ;; hide everything
13494 (org-overview))
13495 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13496 (isearch-no-upper-case-p regexp t)
13497 org-occur-case-fold-search)))
13498 (while (re-search-forward regexp nil t)
13499 (when (or (not callback)
13500 (save-match-data (funcall callback)))
13501 (setq cnt (1+ cnt))
13502 (when org-highlight-sparse-tree-matches
13503 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13504 (org-show-context 'occur-tree)))))
13505 (when org-remove-highlights-with-change
13506 (add-hook 'before-change-functions 'org-remove-occur-highlights
13507 nil 'local))
13508 (unless org-sparse-tree-open-archived-trees
13509 (org-hide-archived-subtrees (point-min) (point-max)))
13510 (run-hooks 'org-occur-hook)
13511 (when (called-interactively-p 'interactive)
13512 (message "%d match(es) for regexp %s" cnt regexp))
13513 cnt))
13515 (defun org-occur-next-match (&optional n _reset)
13516 "Function for `next-error-function' to find sparse tree matches.
13517 N is the number of matches to move, when negative move backwards.
13518 This function always goes back to the starting point when no
13519 match is found."
13520 (let* ((limit (if (< n 0) (point-min) (point-max)))
13521 (search-func (if (< n 0)
13522 'previous-single-char-property-change
13523 'next-single-char-property-change))
13524 (n (abs n))
13525 (pos (point))
13527 (catch 'exit
13528 (while (setq p1 (funcall search-func (point) 'org-type))
13529 (when (equal p1 limit)
13530 (goto-char pos)
13531 (user-error "No more matches"))
13532 (when (equal (get-char-property p1 'org-type) 'org-occur)
13533 (setq n (1- n))
13534 (when (= n 0)
13535 (goto-char p1)
13536 (throw 'exit (point))))
13537 (goto-char p1))
13538 (goto-char p1)
13539 (user-error "No more matches"))))
13541 (defun org-show-context (&optional key)
13542 "Make sure point and context are visible.
13543 Optional argument KEY, when non-nil, is a symbol. See
13544 `org-show-context-detail' for allowed values and how much is to
13545 be shown."
13546 (org-show-set-visibility
13547 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13548 ((cdr (assq key org-show-context-detail)))
13549 (t (cdr (assq 'default org-show-context-detail))))))
13551 (defun org-show-set-visibility (detail)
13552 "Set visibility around point according to DETAIL.
13553 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13554 `tree', `canonical' or t. See `org-show-context-detail' for more
13555 information."
13556 ;; Show current heading and possibly its entry, following headline
13557 ;; or all children.
13558 (if (and (org-at-heading-p) (not (eq detail 'local)))
13559 (org-flag-heading nil)
13560 (org-show-entry)
13561 ;; If point is hidden within a drawer or a block, make sure to
13562 ;; expose it.
13563 (dolist (o (overlays-at (point)))
13564 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13565 (delete-overlay o)))
13566 (unless (org-before-first-heading-p)
13567 (org-with-limited-levels
13568 (cl-case detail
13569 ((tree canonical t) (org-show-children))
13570 ((nil minimal ancestors))
13571 (t (save-excursion
13572 (outline-next-heading)
13573 (org-flag-heading nil)))))))
13574 ;; Show all siblings.
13575 (when (eq detail 'lineage) (org-show-siblings))
13576 ;; Show ancestors, possibly with their children.
13577 (when (memq detail '(ancestors lineage tree canonical t))
13578 (save-excursion
13579 (while (org-up-heading-safe)
13580 (org-flag-heading nil)
13581 (when (memq detail '(canonical t)) (org-show-entry))
13582 (when (memq detail '(tree canonical t)) (org-show-children))))))
13584 (defvar org-reveal-start-hook nil
13585 "Hook run before revealing a location.")
13587 (defun org-reveal (&optional siblings)
13588 "Show current entry, hierarchy above it, and the following headline.
13590 This can be used to show a consistent set of context around
13591 locations exposed with `org-show-context'.
13593 With optional argument SIBLINGS, on each level of the hierarchy all
13594 siblings are shown. This repairs the tree structure to what it would
13595 look like when opened with hierarchical calls to `org-cycle'.
13597 With a \\[universal-argument] \\[universal-argument] prefix, \
13598 go to the parent and show the entire tree."
13599 (interactive "P")
13600 (run-hooks 'org-reveal-start-hook)
13601 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13602 ((equal siblings '(16))
13603 (save-excursion
13604 (when (org-up-heading-safe)
13605 (org-show-subtree)
13606 (run-hook-with-args 'org-cycle-hook 'subtree))))
13607 (t (org-show-set-visibility 'lineage))))
13609 (defun org-highlight-new-match (beg end)
13610 "Highlight from BEG to END and mark the highlight is an occur headline."
13611 (let ((ov (make-overlay beg end)))
13612 (overlay-put ov 'face 'secondary-selection)
13613 (overlay-put ov 'org-type 'org-occur)
13614 (push ov org-occur-highlights)))
13616 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13617 "Remove the occur highlights from the buffer.
13618 BEG and END are ignored. If NOREMOVE is nil, remove this function
13619 from the `before-change-functions' in the current buffer."
13620 (interactive)
13621 (unless org-inhibit-highlight-removal
13622 (mapc #'delete-overlay org-occur-highlights)
13623 (setq org-occur-highlights nil)
13624 (setq org-occur-parameters nil)
13625 (unless noremove
13626 (remove-hook 'before-change-functions
13627 'org-remove-occur-highlights 'local))))
13629 ;;;; Priorities
13631 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13632 "Regular expression matching the priority indicator.")
13634 (defvar org-remove-priority-next-time nil)
13636 (defun org-priority-up ()
13637 "Increase the priority of the current item."
13638 (interactive)
13639 (org-priority 'up))
13641 (defun org-priority-down ()
13642 "Decrease the priority of the current item."
13643 (interactive)
13644 (org-priority 'down))
13646 (defun org-priority (&optional action _show)
13647 "Change the priority of an item.
13648 ACTION can be `set', `up', `down', or a character."
13649 (interactive "P")
13650 (if (equal action '(4))
13651 (org-show-priority)
13652 (unless org-enable-priority-commands
13653 (user-error "Priority commands are disabled"))
13654 (setq action (or action 'set))
13655 (let (current new news have remove)
13656 (save-excursion
13657 (org-back-to-heading t)
13658 (when (looking-at org-priority-regexp)
13659 (setq current (string-to-char (match-string 2))
13660 have t))
13661 (cond
13662 ((eq action 'remove)
13663 (setq remove t new ?\ ))
13664 ((or (eq action 'set)
13665 (integerp action))
13666 (if (not (eq action 'set))
13667 (setq new action)
13668 (message "Priority %c-%c, SPC to remove: "
13669 org-highest-priority org-lowest-priority)
13670 (save-match-data
13671 (setq new (read-char-exclusive))))
13672 (when (and (= (upcase org-highest-priority) org-highest-priority)
13673 (= (upcase org-lowest-priority) org-lowest-priority))
13674 (setq new (upcase new)))
13675 (cond ((equal new ?\ ) (setq remove t))
13676 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13677 (user-error "Priority must be between `%c' and `%c'"
13678 org-highest-priority org-lowest-priority))))
13679 ((eq action 'up)
13680 (setq new (if have
13681 (1- current) ; normal cycling
13682 ;; last priority was empty
13683 (if (eq last-command this-command)
13684 org-lowest-priority ; wrap around empty to lowest
13685 ;; default
13686 (if org-priority-start-cycle-with-default
13687 org-default-priority
13688 (1- org-default-priority))))))
13689 ((eq action 'down)
13690 (setq new (if have
13691 (1+ current) ; normal cycling
13692 ;; last priority was empty
13693 (if (eq last-command this-command)
13694 org-highest-priority ; wrap around empty to highest
13695 ;; default
13696 (if org-priority-start-cycle-with-default
13697 org-default-priority
13698 (1+ org-default-priority))))))
13699 (t (user-error "Invalid action")))
13700 (when (or (< (upcase new) org-highest-priority)
13701 (> (upcase new) org-lowest-priority))
13702 (if (and (memq action '(up down))
13703 (not have) (not (eq last-command this-command)))
13704 ;; `new' is from default priority
13705 (error
13706 "The default can not be set, see `org-default-priority' why")
13707 ;; normal cycling: `new' is beyond highest/lowest priority
13708 ;; and is wrapped around to the empty priority
13709 (setq remove t)))
13710 (setq news (format "%c" new))
13711 (if have
13712 (if remove
13713 (replace-match "" t t nil 1)
13714 (replace-match news t t nil 2))
13715 (if remove
13716 (user-error "No priority cookie found in line")
13717 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13718 (if (match-end 2)
13719 (progn
13720 (goto-char (match-end 2))
13721 (insert " [#" news "]"))
13722 (goto-char (match-beginning 3))
13723 (insert "[#" news "] "))))
13724 (org-set-tags nil 'align))
13725 (if remove
13726 (message "Priority removed")
13727 (message "Priority of current item set to %s" news)))))
13729 (defun org-show-priority ()
13730 "Show the priority of the current item.
13731 This priority is composed of the main priority given with the [#A] cookies,
13732 and by additional input from the age of a schedules or deadline entry."
13733 (interactive)
13734 (let ((pri (if (eq major-mode 'org-agenda-mode)
13735 (org-get-at-bol 'priority)
13736 (save-excursion
13737 (save-match-data
13738 (beginning-of-line)
13739 (and (looking-at org-heading-regexp)
13740 (org-get-priority (match-string 0))))))))
13741 (message "Priority is %d" (if pri pri -1000))))
13743 (defun org-get-priority (s)
13744 "Find priority cookie and return priority."
13745 (save-match-data
13746 (if (functionp org-get-priority-function)
13747 (funcall org-get-priority-function)
13748 (if (not (string-match org-priority-regexp s))
13749 (* 1000 (- org-lowest-priority org-default-priority))
13750 (* 1000 (- org-lowest-priority
13751 (string-to-char (match-string 2 s))))))))
13753 ;;;; Tags
13755 (defvar org-agenda-archives-mode)
13756 (defvar org-map-continue-from nil
13757 "Position from where mapping should continue.
13758 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13760 (defvar org-scanner-tags nil
13761 "The current tag list while the tags scanner is running.")
13763 (defvar org-trust-scanner-tags nil
13764 "Should `org-get-tags-at' use the tags for the scanner.
13765 This is for internal dynamical scoping only.
13766 When this is non-nil, the function `org-get-tags-at' will return the value
13767 of `org-scanner-tags' instead of building the list by itself. This
13768 can lead to large speed-ups when the tags scanner is used in a file with
13769 many entries, and when the list of tags is retrieved, for example to
13770 obtain a list of properties. Building the tags list for each entry in such
13771 a file becomes an N^2 operation - but with this variable set, it scales
13772 as N.")
13774 (defvar org--matcher-tags-todo-only nil)
13776 (defun org-scan-tags (action matcher todo-only &optional start-level)
13777 "Scan headline tags with inheritance and produce output ACTION.
13779 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13780 or `agenda' to produce an entry list for an agenda view. It can also be
13781 a Lisp form or a function that should be called at each matched headline, in
13782 this case the return value is a list of all return values from these calls.
13784 MATCHER is a function accepting three arguments, returning
13785 a non-nil value whenever a given set of tags qualifies a headline
13786 for inclusion. See `org-make-tags-matcher' for more information.
13787 As a special case, it can also be set to t (respectively nil) in
13788 order to match all (respectively none) headline.
13790 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13791 included in the output.
13793 START-LEVEL can be a string with asterisks, reducing the scope to
13794 headlines matching this string."
13795 (require 'org-agenda)
13796 (let* ((re (concat "^"
13797 (if start-level
13798 ;; Get the correct level to match
13799 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13800 org-outline-regexp)
13801 " *\\(\\<\\("
13802 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
13803 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
13804 (props (list 'face 'default
13805 'done-face 'org-agenda-done
13806 'undone-face 'default
13807 'mouse-face 'highlight
13808 'org-not-done-regexp org-not-done-regexp
13809 'org-todo-regexp org-todo-regexp
13810 'org-complex-heading-regexp org-complex-heading-regexp
13811 'help-echo
13812 (format "mouse-2 or RET jump to org file %s"
13813 (abbreviate-file-name
13814 (or (buffer-file-name (buffer-base-buffer))
13815 (buffer-name (buffer-base-buffer)))))))
13816 (org-map-continue-from nil)
13817 lspos tags tags-list
13818 (tags-alist (list (cons 0 org-file-tags)))
13819 (llast 0) rtn rtn1 level category i txt
13820 todo marker entry priority
13821 ts-date ts-date-type ts-date-pair)
13822 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13823 (setq action (list 'lambda nil action)))
13824 (save-excursion
13825 (goto-char (point-min))
13826 (when (eq action 'sparse-tree)
13827 (org-overview)
13828 (org-remove-occur-highlights))
13829 (while (let (case-fold-search)
13830 (re-search-forward re nil t))
13831 (setq org-map-continue-from nil)
13832 (catch :skip
13833 (setq todo
13834 ;; TODO: is the 1-2 difference a bug?
13835 (when (match-end 1) (match-string-no-properties 2))
13836 tags (when (match-end 4) (match-string-no-properties 4)))
13837 (goto-char (setq lspos (match-beginning 0)))
13838 (setq level (org-reduced-level (org-outline-level))
13839 category (org-get-category))
13840 (when (eq action 'agenda)
13841 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13842 ts-date (car ts-date-pair)
13843 ts-date-type (cdr ts-date-pair)))
13844 (setq i llast llast level)
13845 ;; remove tag lists from same and sublevels
13846 (while (>= i level)
13847 (when (setq entry (assoc i tags-alist))
13848 (setq tags-alist (delete entry tags-alist)))
13849 (setq i (1- i)))
13850 ;; add the next tags
13851 (when tags
13852 (setq tags (org-split-string tags ":")
13853 tags-alist
13854 (cons (cons level tags) tags-alist)))
13855 ;; compile tags for current headline
13856 (setq tags-list
13857 (if org-use-tag-inheritance
13858 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13859 tags)
13860 org-scanner-tags tags-list)
13861 (when org-use-tag-inheritance
13862 (setcdr (car tags-alist)
13863 (mapcar (lambda (x)
13864 (setq x (copy-sequence x))
13865 (org-add-prop-inherited x))
13866 (cdar tags-alist))))
13867 (when (and tags org-use-tag-inheritance
13868 (or (not (eq t org-use-tag-inheritance))
13869 org-tags-exclude-from-inheritance))
13870 ;; Selective inheritance, remove uninherited ones.
13871 (setcdr (car tags-alist)
13872 (org-remove-uninherited-tags (cdar tags-alist))))
13873 (when (and
13875 ;; eval matcher only when the todo condition is OK
13876 (and (or (not todo-only) (member todo org-todo-keywords-1))
13877 (if (functionp matcher)
13878 (let ((case-fold-search t) (org-trust-scanner-tags t))
13879 (funcall matcher todo tags-list level))
13880 matcher))
13882 ;; Call the skipper, but return t if it does not
13883 ;; skip, so that the `and' form continues evaluating.
13884 (progn
13885 (unless (eq action 'sparse-tree) (org-agenda-skip))
13888 ;; Check if timestamps are deselecting this entry
13889 (or (not todo-only)
13890 (and (member todo org-todo-keywords-1)
13891 (or (not org-agenda-tags-todo-honor-ignore-options)
13892 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13894 ;; select this headline
13895 (cond
13896 ((eq action 'sparse-tree)
13897 (and org-highlight-sparse-tree-matches
13898 (org-get-heading) (match-end 0)
13899 (org-highlight-new-match
13900 (match-beginning 1) (match-end 1)))
13901 (org-show-context 'tags-tree))
13902 ((eq action 'agenda)
13903 (setq txt (org-agenda-format-item
13905 (concat
13906 (if (eq org-tags-match-list-sublevels 'indented)
13907 (make-string (1- level) ?.) "")
13908 (org-get-heading))
13909 (make-string level ?\s)
13910 category
13911 tags-list)
13912 priority (org-get-priority txt))
13913 (goto-char lspos)
13914 (setq marker (org-agenda-new-marker))
13915 (org-add-props txt props
13916 'org-marker marker 'org-hd-marker marker 'org-category category
13917 'todo-state todo
13918 'ts-date ts-date
13919 'priority priority
13920 'type (concat "tagsmatch" ts-date-type))
13921 (push txt rtn))
13922 ((functionp action)
13923 (setq org-map-continue-from nil)
13924 (save-excursion
13925 (setq rtn1 (funcall action))
13926 (push rtn1 rtn)))
13927 (t (user-error "Invalid action")))
13929 ;; if we are to skip sublevels, jump to end of subtree
13930 (unless org-tags-match-list-sublevels
13931 (org-end-of-subtree t)
13932 (backward-char 1))))
13933 ;; Get the correct position from where to continue
13934 (if org-map-continue-from
13935 (goto-char org-map-continue-from)
13936 (and (= (point) lspos) (end-of-line 1)))))
13937 (when (and (eq action 'sparse-tree)
13938 (not org-sparse-tree-open-archived-trees))
13939 (org-hide-archived-subtrees (point-min) (point-max)))
13940 (nreverse rtn)))
13942 (defun org-remove-uninherited-tags (tags)
13943 "Remove all tags that are not inherited from the list TAGS."
13944 (cond
13945 ((eq org-use-tag-inheritance t)
13946 (if org-tags-exclude-from-inheritance
13947 (org-delete-all org-tags-exclude-from-inheritance tags)
13948 tags))
13949 ((not org-use-tag-inheritance) nil)
13950 ((stringp org-use-tag-inheritance)
13951 (delq nil (mapcar
13952 (lambda (x)
13953 (if (and (string-match org-use-tag-inheritance x)
13954 (not (member x org-tags-exclude-from-inheritance)))
13955 x nil))
13956 tags)))
13957 ((listp org-use-tag-inheritance)
13958 (delq nil (mapcar
13959 (lambda (x)
13960 (if (member x org-use-tag-inheritance) x nil))
13961 tags)))))
13963 (defun org-match-sparse-tree (&optional todo-only match)
13964 "Create a sparse tree according to tags string MATCH.
13966 MATCH is a string with match syntax. It can contain a selection
13967 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13968 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13969 those. See the manual for details.
13971 If optional argument TODO-ONLY is non-nil, only select lines that
13972 are also TODO tasks."
13973 (interactive "P")
13974 (org-agenda-prepare-buffers (list (current-buffer)))
13975 (let ((org--matcher-tags-todo-only todo-only))
13976 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13977 org--matcher-tags-todo-only)))
13979 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13981 (defvar org-cached-props nil)
13982 (defun org-cached-entry-get (pom property)
13983 (if (or (eq t org-use-property-inheritance)
13984 (and (stringp org-use-property-inheritance)
13985 (let ((case-fold-search t))
13986 (string-match-p org-use-property-inheritance property)))
13987 (and (listp org-use-property-inheritance)
13988 (member-ignore-case property org-use-property-inheritance)))
13989 ;; Caching is not possible, check it directly.
13990 (org-entry-get pom property 'inherit)
13991 ;; Get all properties, so we can do complicated checks easily.
13992 (cdr (assoc-string property
13993 (or org-cached-props
13994 (setq org-cached-props (org-entry-properties pom)))
13995 t))))
13997 (defun org-global-tags-completion-table (&optional files)
13998 "Return the list of all tags in all agenda buffer/files.
13999 Optional FILES argument is a list of files which can be used
14000 instead of the agenda files."
14001 (save-excursion
14002 (org-uniquify
14003 (delq nil
14004 (apply #'append
14005 (mapcar
14006 (lambda (file)
14007 (set-buffer (find-file-noselect file))
14008 (mapcar (lambda (x)
14009 (and (stringp (car-safe x))
14010 (list (car-safe x))))
14011 (or org-current-tag-alist (org-get-buffer-tags))))
14012 (if (car-safe files) files
14013 (org-agenda-files))))))))
14015 (defun org-make-tags-matcher (match)
14016 "Create the TAGS/TODO matcher form for the selection string MATCH.
14018 Returns a cons of the selection string MATCH and a function
14019 implementing the matcher.
14021 The matcher is to be called at an Org entry, with point on the
14022 headline, and returns non-nil if the entry matches the selection
14023 string MATCH. It must be called with three arguments: the TODO
14024 keyword at the entry (or nil if none), the list of all tags at
14025 the entry including inherited ones and the reduced level of the
14026 headline. Additionally, the category of the entry, if any, must
14027 be specified as the text property `org-category' on the headline.
14029 This function sets the variable `org--matcher-tags-todo-only' to
14030 a non-nil value if the matcher restricts matching to TODO
14031 entries, otherwise it is not touched.
14033 See also `org-scan-tags'."
14034 (unless match
14035 ;; Get a new match request, with completion against the global
14036 ;; tags table and the local tags in current buffer.
14037 (let ((org-last-tags-completion-table
14038 (org-uniquify
14039 (delq nil (append (org-get-buffer-tags)
14040 (org-global-tags-completion-table))))))
14041 (setq match
14042 (completing-read
14043 "Match: "
14044 'org-tags-completion-function nil nil nil 'org-tags-history))))
14046 (let ((match0 match)
14047 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14048 (start 0)
14049 tagsmatch todomatch tagsmatcher todomatcher)
14051 ;; Expand group tags.
14052 (setq match (org-tags-expand match))
14054 ;; Check if there is a TODO part of this match, which would be the
14055 ;; part after a "/". To make sure that this slash is not part of
14056 ;; a property value to be matched against, we also check that
14057 ;; there is no / after that slash. First, find the last slash.
14058 (let ((s 0))
14059 (while (string-match "/+" match s)
14060 (setq start (match-beginning 0))
14061 (setq s (match-end 0))))
14062 (if (and (string-match "/+" match start)
14063 (not (string-match-p "\"" match start)))
14064 ;; Match contains also a TODO-matching request.
14065 (progn
14066 (setq tagsmatch (substring match 0 (match-beginning 0)))
14067 (setq todomatch (substring match (match-end 0)))
14068 (when (string-prefix-p "!" todomatch)
14069 (setq org--matcher-tags-todo-only t)
14070 (setq todomatch (substring todomatch 1)))
14071 (when (string-match "\\`\\s-*\\'" todomatch)
14072 (setq todomatch nil)))
14073 ;; Only matching tags.
14074 (setq tagsmatch match)
14075 (setq todomatch nil))
14077 ;; Make the tags matcher.
14078 (when (org-string-nw-p tagsmatch)
14079 (let ((orlist nil)
14080 (orterms (org-split-string tagsmatch "|"))
14081 term)
14082 (while (setq term (pop orterms))
14083 (while (and (equal (substring term -1) "\\") orterms)
14084 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14085 (while (string-match re term)
14086 (let* ((rest (substring term (match-end 0)))
14087 (minus (and (match-end 1)
14088 (equal (match-string 1 term) "-")))
14089 (tag (save-match-data
14090 (replace-regexp-in-string
14091 "\\\\-" "-" (match-string 2 term))))
14092 (regexp (eq (string-to-char tag) ?{))
14093 (levelp (match-end 4))
14094 (propp (match-end 5))
14096 (cond
14097 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14098 (levelp
14099 `(,(org-op-to-function (match-string 3 term))
14100 level
14101 ,(string-to-number (match-string 4 term))))
14102 (propp
14103 (let* ((gv (pcase (upcase (match-string 5 term))
14104 ("CATEGORY"
14105 '(get-text-property (point) 'org-category))
14106 ("TODO" 'todo)
14107 (p `(org-cached-entry-get nil ,p))))
14108 (pv (match-string 7 term))
14109 (regexp (eq (string-to-char pv) ?{))
14110 (strp (eq (string-to-char pv) ?\"))
14111 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14112 (po (org-op-to-function (match-string 6 term)
14113 (if timep 'time strp))))
14114 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14115 (when timep (setq pv (org-matcher-time pv)))
14116 (cond ((and regexp (eq po 'org<>))
14117 `(not (string-match ,pv (or ,gv ""))))
14118 (regexp `(string-match ,pv (or ,gv "")))
14119 (strp `(,po (or ,gv "") ,pv))
14121 `(,po
14122 (string-to-number (or ,gv ""))
14123 ,(string-to-number pv))))))
14124 (t `(member ,tag tags-list)))))
14125 (push (if minus `(not ,mm) mm) tagsmatcher)
14126 (setq term rest)))
14127 (push `(and ,@tagsmatcher) orlist)
14128 (setq tagsmatcher nil))
14129 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14131 ;; Make the TODO matcher.
14132 (when (org-string-nw-p todomatch)
14133 (let ((orlist nil))
14134 (dolist (term (org-split-string todomatch "|"))
14135 (while (string-match re term)
14136 (let* ((minus (and (match-end 1)
14137 (equal (match-string 1 term) "-")))
14138 (kwd (match-string 2 term))
14139 (regexp (eq (string-to-char kwd) ?{))
14140 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14141 `(equal todo ,kwd))))
14142 (push (if minus `(not ,mm) mm) todomatcher))
14143 (setq term (substring term (match-end 0))))
14144 (push (if (> (length todomatcher) 1)
14145 (cons 'and todomatcher)
14146 (car todomatcher))
14147 orlist)
14148 (setq todomatcher nil))
14149 (setq todomatcher (cons 'or orlist))))
14151 ;; Return the string and function of the matcher. If no
14152 ;; tags-specific or todo-specific matcher exists, match
14153 ;; everything.
14154 (let ((matcher (if (and tagsmatcher todomatcher)
14155 `(and ,tagsmatcher ,todomatcher)
14156 (or tagsmatcher todomatcher t))))
14157 (when org--matcher-tags-todo-only
14158 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14159 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14161 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14162 "Expand group tags in MATCH.
14164 This replaces every group tag in MATCH with a regexp tag search.
14165 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14166 will be replaced like this:
14168 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14169 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14170 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14172 Replacing by a regexp preserves the structure of the match.
14173 E.g., this expansion
14175 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14177 will match anything tagged with \"Lab\" and \"Home\", or tagged
14178 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14180 A group tag in MATCH can contain regular expressions of its own.
14181 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14182 will be replaced like this:
14184 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14186 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14187 assumed to be a single group tag, and the function will return
14188 the list of tags in this group.
14190 When DOWNCASE is non-nil, expand downcased TAGS."
14191 (if org-group-tags
14192 (let* ((case-fold-search t)
14193 (stable org-mode-syntax-table)
14194 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14195 (taggroups (if downcased
14196 (mapcar (lambda (tg) (mapcar #'downcase tg))
14197 taggroups)
14198 taggroups))
14199 (taggroups-keys (mapcar #'car taggroups))
14200 (return-match (if downcased (downcase match) match))
14201 (count 0)
14202 (work-already-expanded tags-already-expanded)
14203 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14204 ;; @ and _ are allowed as word-components in tags.
14205 (modify-syntax-entry ?@ "w" stable)
14206 (modify-syntax-entry ?_ "w" stable)
14207 ;; Temporarily replace regexp-expressions in the match-expression.
14208 (while (string-match "{.+?}" return-match)
14209 (cl-incf count)
14210 (push (match-string 0 return-match) regexps-in-match)
14211 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14212 (while (and taggroups-keys
14213 (with-syntax-table stable
14214 (string-match
14215 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14216 (regexp-opt taggroups-keys) "\\>\\)")
14217 return-match)))
14218 (let* ((dir (match-string 1 return-match))
14219 (tag (match-string 2 return-match))
14220 (tag (if downcased (downcase tag) tag)))
14221 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14222 (member tag work-already-expanded))
14223 (setq tags-in-group (assoc tag taggroups))
14224 (push tag work-already-expanded)
14225 ;; Recursively expand each tag in the group, if the tag hasn't
14226 ;; already been expanded. Restore the match-data after all recursive calls.
14227 (save-match-data
14228 (let (tags-expanded)
14229 (dolist (x (cdr tags-in-group))
14230 (if (and (member x taggroups-keys)
14231 (not (member x work-already-expanded)))
14232 (setq tags-expanded
14233 (delete-dups
14234 (append
14235 (org-tags-expand x t downcased
14236 work-already-expanded)
14237 tags-expanded)))
14238 (setq tags-expanded
14239 (append (list x) tags-expanded)))
14240 (setq work-already-expanded
14241 (delete-dups
14242 (append tags-expanded
14243 work-already-expanded))))
14244 (setq tags-in-group
14245 (delete-dups (cons (car tags-in-group)
14246 tags-expanded)))))
14247 ;; Filter tag-regexps from tags.
14248 (setq regexp-in-group-escaped
14249 (delq nil (mapcar (lambda (x)
14250 (if (stringp x)
14251 (and (equal "{" (substring x 0 1))
14252 (equal "}" (substring x -1))
14255 tags-in-group))
14256 regexp-in-group
14257 (mapcar (lambda (x)
14258 (substring x 1 -1))
14259 regexp-in-group-escaped)
14260 tags-in-group
14261 (delq nil (mapcar (lambda (x)
14262 (if (stringp x)
14263 (and (not (equal "{" (substring x 0 1)))
14264 (not (equal "}" (substring x -1)))
14267 tags-in-group)))
14268 ;; If single-as-list, do no more in the while-loop.
14269 (if (not single-as-list)
14270 (progn
14271 (when regexp-in-group
14272 (setq regexp-in-group
14273 (concat "\\|"
14274 (mapconcat 'identity regexp-in-group
14275 "\\|"))))
14276 (setq tags-in-group
14277 (concat dir
14278 "{\\<"
14279 (regexp-opt tags-in-group)
14280 "\\>"
14281 regexp-in-group
14282 "}"))
14283 (when (stringp tags-in-group)
14284 (org-add-props tags-in-group '(grouptag t)))
14285 (setq return-match
14286 (replace-match tags-in-group t t return-match)))
14287 (setq tags-in-group
14288 (append regexp-in-group-escaped tags-in-group))))
14289 (setq taggroups-keys (delete tag taggroups-keys))))
14290 ;; Add the regular expressions back into the match-expression again.
14291 (while regexps-in-match
14292 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14293 (pop regexps-in-match)
14294 return-match t t))
14295 (cl-decf count))
14296 (if single-as-list
14297 (if tags-in-group tags-in-group (list return-match))
14298 return-match))
14299 (if single-as-list
14300 (list (if downcased (downcase match) match))
14301 match)))
14303 (defun org-op-to-function (op &optional stringp)
14304 "Turn an operator into the appropriate function."
14305 (setq op
14306 (cond
14307 ((equal op "<" ) '(< string< org-time<))
14308 ((equal op ">" ) '(> org-string> org-time>))
14309 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14310 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14311 ((member op '("=" "==")) '(= string= org-time=))
14312 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14313 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14315 (defun org<> (a b) (not (= a b)))
14316 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14317 (defun org-string>= (a b) (not (string< a b)))
14318 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14319 (defun org-string<> (a b) (not (string= a b)))
14320 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14321 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14322 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14323 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14324 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14325 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14326 (defun org-2ft (s)
14327 "Convert S to a floating point time.
14328 If S is already a number, just return it. If it is a string, parse
14329 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14330 (cond
14331 ((numberp s) s)
14332 ((stringp s)
14333 (condition-case nil
14334 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14335 (error 0.)))
14336 (t 0.)))
14338 (defun org-time-today ()
14339 "Time in seconds today at 0:00.
14340 Returns the float number of seconds since the beginning of the
14341 epoch to the beginning of today (00:00)."
14342 (float-time (apply 'encode-time
14343 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14345 (defun org-matcher-time (s)
14346 "Interpret a time comparison value."
14347 (save-match-data
14348 (cond
14349 ((string= s "<now>") (float-time))
14350 ((string= s "<today>") (org-time-today))
14351 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14352 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14353 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14354 (+ (org-time-today)
14355 (* (string-to-number (match-string 1 s))
14356 (cdr (assoc (match-string 2 s)
14357 '(("d" . 86400.0) ("w" . 604800.0)
14358 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14359 (t (org-2ft s)))))
14361 (defun org-match-any-p (re list)
14362 "Does re match any element of list?"
14363 (setq list (mapcar (lambda (x) (string-match re x)) list))
14364 (delq nil list))
14366 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14367 (defvar org-tags-overlay (make-overlay 1 1))
14368 (delete-overlay org-tags-overlay)
14370 (defun org-get-local-tags-at (&optional pos)
14371 "Get a list of tags defined in the current headline."
14372 (org-get-tags-at pos 'local))
14374 (defun org-get-local-tags ()
14375 "Get a list of tags defined in the current headline."
14376 (org-get-tags-at nil 'local))
14378 (defun org-get-tags-at (&optional pos local)
14379 "Get a list of all headline tags applicable at POS.
14380 POS defaults to point. If tags are inherited, the list contains
14381 the targets in the same sequence as the headlines appear, i.e.
14382 the tags of the current headline come last.
14383 When LOCAL is non-nil, only return tags from the current headline,
14384 ignore inherited ones."
14385 (interactive)
14386 (if (and org-trust-scanner-tags
14387 (or (not pos) (equal pos (point)))
14388 (not local))
14389 org-scanner-tags
14390 (let (tags ltags lastpos parent)
14391 (save-excursion
14392 (save-restriction
14393 (widen)
14394 (goto-char (or pos (point)))
14395 (save-match-data
14396 (catch 'done
14397 (condition-case nil
14398 (progn
14399 (org-back-to-heading t)
14400 (while (not (equal lastpos (point)))
14401 (setq lastpos (point))
14402 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14403 (setq ltags (org-split-string
14404 (match-string-no-properties 1) ":"))
14405 (when parent
14406 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14407 (setq tags (append
14408 (if parent
14409 (org-remove-uninherited-tags ltags)
14410 ltags)
14411 tags)))
14412 (or org-use-tag-inheritance (throw 'done t))
14413 (when local (throw 'done t))
14414 (or (org-up-heading-safe) (error nil))
14415 (setq parent t)))
14416 (error nil)))))
14417 (if local
14418 tags
14419 (reverse (delete-dups
14420 (reverse (append
14421 (org-remove-uninherited-tags
14422 org-file-tags)
14423 tags)))))))))
14425 (defun org-add-prop-inherited (s)
14426 (add-text-properties 0 (length s) '(inherited t) s)
14429 (defun org-toggle-tag (tag &optional onoff)
14430 "Toggle the tag TAG for the current line.
14431 If ONOFF is `on' or `off', don't toggle but set to this state."
14432 (save-excursion
14433 (org-back-to-heading t)
14434 (let ((current
14435 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14436 (line-end-position) t)
14437 (let ((tags (match-string 1)))
14438 ;; Clear current tags.
14439 (replace-match "")
14440 ;; Reverse the tags list so any new tag is appended to
14441 ;; the current list of tags.
14442 (nreverse (org-split-string tags ":")))))
14443 res)
14444 (pcase onoff
14445 (`off (setq current (delete tag current)))
14446 ((or `on (guard (not (member tag current))))
14447 (setq res t)
14448 (cl-pushnew tag current :test #'equal))
14449 (_ (setq current (delete tag current))))
14450 (end-of-line)
14451 (if current
14452 (progn
14453 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14454 (org-set-tags nil t))
14455 (delete-horizontal-space))
14456 (run-hooks 'org-after-tags-change-hook)
14457 res)))
14459 (defun org--align-tags-here (to-col)
14460 "Align tags on the current headline to TO-COL.
14461 Assume point is on a headline."
14462 (let ((pos (point)))
14463 (beginning-of-line)
14464 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14465 (>= pos (match-beginning 2)))
14466 ;; No tags or point within tags: do not align.
14467 (goto-char pos)
14468 (goto-char (match-beginning 1))
14469 (let ((shift (max (- (if (>= to-col 0) to-col
14470 (- (abs to-col) (string-width (match-string 2))))
14471 (current-column))
14472 1)))
14473 (replace-match (make-string shift ?\s) nil nil nil 1)
14474 ;; Preserve initial position, if possible. In any case, stop
14475 ;; before tags.
14476 (when (< pos (point)) (goto-char pos))))))
14478 (defun org-set-tags-command (&optional arg just-align)
14479 "Call the set-tags command for the current entry."
14480 (interactive "P")
14481 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14482 (org-set-tags arg just-align)
14483 (save-excursion
14484 (unless (and (org-region-active-p)
14485 org-loop-over-headlines-in-active-region)
14486 (org-back-to-heading t))
14487 (org-set-tags arg just-align))))
14489 (defun org-set-tags-to (data)
14490 "Set the tags of the current entry to DATA, replacing the current tags.
14491 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14492 If DATA is nil or the empty string, any tags will be removed."
14493 (interactive "sTags: ")
14494 (setq data
14495 (cond
14496 ((eq data nil) "")
14497 ((equal data "") "")
14498 ((stringp data)
14499 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14500 ":"))
14501 ((listp data)
14502 (concat ":" (mapconcat 'identity data ":") ":"))))
14503 (when data
14504 (save-excursion
14505 (org-back-to-heading t)
14506 (when (let ((case-fold-search nil))
14507 (looking-at org-complex-heading-regexp))
14508 (if (match-end 5)
14509 (progn
14510 (goto-char (match-beginning 5))
14511 (insert data)
14512 (delete-region (point) (point-at-eol))
14513 (org-set-tags nil 'align))
14514 (goto-char (point-at-eol))
14515 (insert " " data)
14516 (org-set-tags nil 'align)))
14517 (beginning-of-line 1)
14518 (when (looking-at ".*?\\([ \t]+\\)$")
14519 (delete-region (match-beginning 1) (match-end 1))))))
14521 (defun org-align-all-tags ()
14522 "Align the tags in all headings."
14523 (interactive)
14524 (save-excursion
14525 (or (ignore-errors (org-back-to-heading t))
14526 (outline-next-heading))
14527 (if (org-at-heading-p)
14528 (org-set-tags t)
14529 (message "No headings"))))
14531 (defvar org-indent-indentation-per-level)
14532 (defun org-set-tags (&optional arg just-align)
14533 "Set the tags for the current headline.
14534 With prefix ARG, realign all tags in headings in the current buffer.
14535 When JUST-ALIGN is non-nil, only align tags."
14536 (interactive "P")
14537 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14538 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14539 'region-start-level
14540 'region))
14541 org-loop-over-headlines-in-active-region)
14542 (org-map-entries
14543 ;; We don't use ARG and JUST-ALIGN here because these args
14544 ;; are not useful when looping over headlines.
14545 #'org-set-tags
14546 org-loop-over-headlines-in-active-region
14548 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14549 (let ((org-setting-tags t))
14550 (if arg
14551 (save-excursion
14552 (goto-char (point-min))
14553 (while (re-search-forward org-outline-regexp-bol nil t)
14554 (org-set-tags nil t)
14555 (end-of-line))
14556 (message "All tags realigned to column %d" org-tags-column))
14557 (let* ((current (org-get-tags-string))
14558 (tags
14559 (if just-align current
14560 ;; Get a new set of tags from the user.
14561 (save-excursion
14562 (let* ((seen)
14563 (table
14564 (setq
14565 org-last-tags-completion-table
14566 ;; Uniquify tags in alists, yet preserve
14567 ;; structure (i.e., keywords).
14568 (delq nil
14569 (mapcar
14570 (lambda (pair)
14571 (let ((head (car pair)))
14572 (cond ((symbolp head) pair)
14573 ((member head seen) nil)
14574 (t (push head seen)
14575 pair))))
14576 (append
14577 (or org-current-tag-alist
14578 (org-get-buffer-tags))
14579 (and
14580 org-complete-tags-always-offer-all-agenda-tags
14581 (org-global-tags-completion-table
14582 (org-agenda-files))))))))
14583 (current-tags (org-split-string current ":"))
14584 (inherited-tags
14585 (nreverse (nthcdr (length current-tags)
14586 (nreverse (org-get-tags-at))))))
14587 (replace-regexp-in-string
14588 "\\([-+&]+\\|,\\)"
14590 (if (or (eq t org-use-fast-tag-selection)
14591 (and org-use-fast-tag-selection
14592 (delq nil (mapcar #'cdr table))))
14593 (org-fast-tag-selection
14594 current-tags inherited-tags table
14595 (and org-fast-tag-selection-include-todo
14596 org-todo-key-alist))
14597 (let ((org-add-colon-after-tag-completion
14598 (< 1 (length table))))
14599 (org-trim
14600 (completing-read
14601 "Tags: "
14602 #'org-tags-completion-function
14603 nil nil current 'org-tags-history))))))))))
14605 (when org-tags-sort-function
14606 (setq tags
14607 (mapconcat
14608 #'identity
14609 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14610 org-tags-sort-function)
14611 ":")))
14613 (if (or (string= ":" tags)
14614 (string= "::" tags))
14615 (setq tags ""))
14616 (if (not (org-string-nw-p tags)) (setq tags "")
14617 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14618 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14620 ;; Insert new tags at the correct column.
14621 (unless (equal current tags)
14622 (save-excursion
14623 (beginning-of-line)
14624 (let ((case-fold-search nil))
14625 (looking-at org-complex-heading-regexp))
14626 ;; Remove current tags, if any.
14627 (when (match-end 5) (replace-match "" nil nil nil 5))
14628 ;; Insert new tags, if any. Otherwise, remove trailing
14629 ;; white spaces.
14630 (end-of-line)
14631 (if (not (equal tags ""))
14632 ;; When text is being inserted on an invisible
14633 ;; region boundary, it can be inadvertently sucked
14634 ;; into invisibility.
14635 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14636 (skip-chars-backward " \t")
14637 (delete-region (point) (line-end-position)))))
14638 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14639 ;; is on.
14640 (unless (equal tags "")
14641 (let* ((level (save-excursion
14642 (beginning-of-line)
14643 (skip-chars-forward "\\*")))
14644 (offset (if (bound-and-true-p org-indent-mode)
14645 (* (1- org-indent-indentation-per-level)
14646 (1- level))
14648 (tags-column
14649 (+ org-tags-column
14650 (if (> org-tags-column 0) (- offset) offset))))
14651 (org--align-tags-here tags-column))))
14652 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14654 (defun org-change-tag-in-region (beg end tag off)
14655 "Add or remove TAG for each entry in the region.
14656 This works in the agenda, and also in an Org buffer."
14657 (interactive
14658 (list (region-beginning) (region-end)
14659 (let ((org-last-tags-completion-table
14660 (if (derived-mode-p 'org-mode)
14661 (org-uniquify
14662 (delq nil (append (org-get-buffer-tags)
14663 (org-global-tags-completion-table))))
14664 (org-global-tags-completion-table))))
14665 (completing-read
14666 "Tag: " 'org-tags-completion-function nil nil nil
14667 'org-tags-history))
14668 (progn
14669 (message "[s]et or [r]emove? ")
14670 (equal (read-char-exclusive) ?r))))
14671 (when (fboundp 'deactivate-mark) (deactivate-mark))
14672 (let ((agendap (equal major-mode 'org-agenda-mode))
14673 l1 l2 m buf pos newhead (cnt 0))
14674 (goto-char end)
14675 (setq l2 (1- (org-current-line)))
14676 (goto-char beg)
14677 (setq l1 (org-current-line))
14678 (cl-loop for l from l1 to l2 do
14679 (org-goto-line l)
14680 (setq m (get-text-property (point) 'org-hd-marker))
14681 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14682 (and agendap m))
14683 (setq buf (if agendap (marker-buffer m) (current-buffer))
14684 pos (if agendap m (point)))
14685 (with-current-buffer buf
14686 (save-excursion
14687 (save-restriction
14688 (goto-char pos)
14689 (setq cnt (1+ cnt))
14690 (org-toggle-tag tag (if off 'off 'on))
14691 (setq newhead (org-get-heading)))))
14692 (and agendap (org-agenda-change-all-lines newhead m))))
14693 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14695 (defun org-tags-completion-function (string _predicate &optional flag)
14696 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14697 (confirm (lambda (x) (stringp (car x)))))
14698 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14699 (setq s1 (match-string 1 string)
14700 s2 (match-string 2 string))
14701 (setq s1 "" s2 string))
14702 (cond
14703 ((eq flag nil)
14704 ;; try completion
14705 (setq rtn (try-completion s2 ctable confirm))
14706 (when (stringp rtn)
14707 (setq rtn
14708 (concat s1 s2 (substring rtn (length s2))
14709 (if (and org-add-colon-after-tag-completion
14710 (assoc rtn ctable))
14711 ":" ""))))
14712 rtn)
14713 ((eq flag t)
14714 ;; all-completions
14715 (all-completions s2 ctable confirm))
14716 ((eq flag 'lambda)
14717 ;; exact match?
14718 (assoc s2 ctable)))))
14720 (defun org-fast-tag-insert (kwd tags face &optional end)
14721 "Insert KDW, and the TAGS, the latter with face FACE.
14722 Also insert END."
14723 (insert (format "%-12s" (concat kwd ":"))
14724 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14725 (or end "")))
14727 (defun org-fast-tag-show-exit (flag)
14728 (save-excursion
14729 (org-goto-line 3)
14730 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14731 (replace-match ""))
14732 (when flag
14733 (end-of-line 1)
14734 (org-move-to-column (- (window-width) 19) t)
14735 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14737 (defun org-set-current-tags-overlay (current prefix)
14738 "Add an overlay to CURRENT tag with PREFIX."
14739 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14740 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14741 (org-overlay-display org-tags-overlay (concat prefix s))))
14743 (defvar org-last-tag-selection-key nil)
14744 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14745 "Fast tag selection with single keys.
14746 CURRENT is the current list of tags in the headline, INHERITED is the
14747 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14748 possibly with grouping information. TODO-TABLE is a similar table with
14749 TODO keywords, should these have keys assigned to them.
14750 If the keys are nil, a-z are automatically assigned.
14751 Returns the new tags string, or nil to not change the current settings."
14752 (let* ((fulltable (append table todo-table))
14753 (maxlen (apply 'max (mapcar
14754 (lambda (x)
14755 (if (stringp (car x)) (string-width (car x)) 0))
14756 fulltable)))
14757 (buf (current-buffer))
14758 (expert (eq org-fast-tag-selection-single-key 'expert))
14759 (buffer-tags nil)
14760 (fwidth (+ maxlen 3 1 3))
14761 (ncol (/ (- (window-width) 4) fwidth))
14762 (i-face 'org-done)
14763 (c-face 'org-todo)
14764 tg cnt e c char c1 c2 ntable tbl rtn
14765 ov-start ov-end ov-prefix
14766 (exit-after-next org-fast-tag-selection-single-key)
14767 (done-keywords org-done-keywords)
14768 groups ingroup intaggroup)
14769 (save-excursion
14770 (beginning-of-line 1)
14771 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14772 (setq ov-start (match-beginning 1)
14773 ov-end (match-end 1)
14774 ov-prefix "")
14775 (setq ov-start (1- (point-at-eol))
14776 ov-end (1+ ov-start))
14777 (skip-chars-forward "^\n\r")
14778 (setq ov-prefix
14779 (concat
14780 (buffer-substring (1- (point)) (point))
14781 (if (> (current-column) org-tags-column)
14783 (make-string (- org-tags-column (current-column)) ?\ ))))))
14784 (move-overlay org-tags-overlay ov-start ov-end)
14785 (save-window-excursion
14786 (if expert
14787 (set-buffer (get-buffer-create " *Org tags*"))
14788 (delete-other-windows)
14789 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14790 (org-switch-to-buffer-other-window " *Org tags*"))
14791 (erase-buffer)
14792 (setq-local org-done-keywords done-keywords)
14793 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14794 (org-fast-tag-insert "Current" current c-face "\n\n")
14795 (org-fast-tag-show-exit exit-after-next)
14796 (org-set-current-tags-overlay current ov-prefix)
14797 (setq tbl fulltable char ?a cnt 0)
14798 (while (setq e (pop tbl))
14799 (cond
14800 ((eq (car e) :startgroup)
14801 (push '() groups) (setq ingroup t)
14802 (unless (zerop cnt)
14803 (setq cnt 0)
14804 (insert "\n"))
14805 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14806 ((eq (car e) :endgroup)
14807 (setq ingroup nil cnt 0)
14808 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14809 ((eq (car e) :startgrouptag)
14810 (setq intaggroup t)
14811 (unless (zerop cnt)
14812 (setq cnt 0)
14813 (insert "\n"))
14814 (insert "[ "))
14815 ((eq (car e) :endgrouptag)
14816 (setq intaggroup nil cnt 0)
14817 (insert "]\n"))
14818 ((equal e '(:newline))
14819 (unless (zerop cnt)
14820 (setq cnt 0)
14821 (insert "\n")
14822 (setq e (car tbl))
14823 (while (equal (car tbl) '(:newline))
14824 (insert "\n")
14825 (setq tbl (cdr tbl)))))
14826 ((equal e '(:grouptags)) (insert " : "))
14828 (setq tg (copy-sequence (car e)) c2 nil)
14829 (if (cdr e)
14830 (setq c (cdr e))
14831 ;; automatically assign a character.
14832 (setq c1 (string-to-char
14833 (downcase (substring
14834 tg (if (= (string-to-char tg) ?@) 1 0)))))
14835 (if (or (rassoc c1 ntable) (rassoc c1 table))
14836 (while (or (rassoc char ntable) (rassoc char table))
14837 (setq char (1+ char)))
14838 (setq c2 c1))
14839 (setq c (or c2 char)))
14840 (when ingroup (push tg (car groups)))
14841 (setq tg (org-add-props tg nil 'face
14842 (cond
14843 ((not (assoc tg table))
14844 (org-get-todo-face tg))
14845 ((member tg current) c-face)
14846 ((member tg inherited) i-face))))
14847 (when (equal (caar tbl) :grouptags)
14848 (org-add-props tg nil 'face 'org-tag-group))
14849 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14850 (insert "[" c "] " tg (make-string
14851 (- fwidth 4 (length tg)) ?\ ))
14852 (push (cons tg c) ntable)
14853 (when (= (cl-incf cnt) ncol)
14854 (insert "\n")
14855 (when (or ingroup intaggroup) (insert " "))
14856 (setq cnt 0)))))
14857 (setq ntable (nreverse ntable))
14858 (insert "\n")
14859 (goto-char (point-min))
14860 (unless expert (org-fit-window-to-buffer))
14861 (setq rtn
14862 (catch 'exit
14863 (while t
14864 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14865 (if (not groups) "no " "")
14866 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14867 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14868 (setq org-last-tag-selection-key c)
14869 (cond
14870 ((= c ?\r) (throw 'exit t))
14871 ((= c ?!)
14872 (setq groups (not groups))
14873 (goto-char (point-min))
14874 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14875 ((= c ?\C-c)
14876 (if (not expert)
14877 (org-fast-tag-show-exit
14878 (setq exit-after-next (not exit-after-next)))
14879 (setq expert nil)
14880 (delete-other-windows)
14881 (set-window-buffer (split-window-vertically) " *Org tags*")
14882 (org-switch-to-buffer-other-window " *Org tags*")
14883 (org-fit-window-to-buffer)))
14884 ((or (= c ?\C-g)
14885 (and (= c ?q) (not (rassoc c ntable))))
14886 (delete-overlay org-tags-overlay)
14887 (setq quit-flag t))
14888 ((= c ?\ )
14889 (setq current nil)
14890 (when exit-after-next (setq exit-after-next 'now)))
14891 ((= c ?\t)
14892 (condition-case nil
14893 (setq tg (completing-read
14894 "Tag: "
14895 (or buffer-tags
14896 (with-current-buffer buf
14897 (setq buffer-tags
14898 (org-get-buffer-tags))))))
14899 (quit (setq tg "")))
14900 (when (string-match "\\S-" tg)
14901 (cl-pushnew (list tg) buffer-tags :test #'equal)
14902 (if (member tg current)
14903 (setq current (delete tg current))
14904 (push tg current)))
14905 (when exit-after-next (setq exit-after-next 'now)))
14906 ((setq e (rassoc c todo-table) tg (car e))
14907 (with-current-buffer buf
14908 (save-excursion (org-todo tg)))
14909 (when exit-after-next (setq exit-after-next 'now)))
14910 ((setq e (rassoc c ntable) tg (car e))
14911 (if (member tg current)
14912 (setq current (delete tg current))
14913 (cl-loop for g in groups do
14914 (when (member tg g)
14915 (dolist (x g) (setq current (delete x current)))))
14916 (push tg current))
14917 (when exit-after-next (setq exit-after-next 'now))))
14919 ;; Create a sorted list
14920 (setq current
14921 (sort current
14922 (lambda (a b)
14923 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14924 (when (eq exit-after-next 'now) (throw 'exit t))
14925 (goto-char (point-min))
14926 (beginning-of-line 2)
14927 (delete-region (point) (point-at-eol))
14928 (org-fast-tag-insert "Current" current c-face)
14929 (org-set-current-tags-overlay current ov-prefix)
14930 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
14931 (setq tg (match-string 1))
14932 (add-text-properties
14933 (match-beginning 1) (match-end 1)
14934 (list 'face
14935 (cond
14936 ((member tg current) c-face)
14937 ((member tg inherited) i-face)
14938 (t (get-text-property (match-beginning 1) 'face))))))
14939 (goto-char (point-min)))))
14940 (delete-overlay org-tags-overlay)
14941 (if rtn
14942 (mapconcat 'identity current ":")
14943 nil))))
14945 (defun org-get-tags-string ()
14946 "Get the TAGS string in the current headline."
14947 (unless (org-at-heading-p t)
14948 (user-error "Not on a heading"))
14949 (save-excursion
14950 (beginning-of-line 1)
14951 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14952 (match-string-no-properties 1)
14953 "")))
14955 (defun org-get-tags ()
14956 "Get the list of tags specified in the current headline."
14957 (org-split-string (org-get-tags-string) ":"))
14959 (defun org-get-buffer-tags ()
14960 "Get a table of all tags used in the buffer, for completion."
14961 (org-with-wide-buffer
14962 (goto-char (point-min))
14963 (let ((tag-re (concat org-outline-regexp-bol
14964 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14965 tags)
14966 (while (re-search-forward tag-re nil t)
14967 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
14968 (push tag tags)))
14969 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
14971 ;;;; The mapping API
14973 (defvar org-agenda-skip-comment-trees)
14974 (defvar org-agenda-skip-function)
14975 (defun org-map-entries (func &optional match scope &rest skip)
14976 "Call FUNC at each headline selected by MATCH in SCOPE.
14978 FUNC is a function or a lisp form. The function will be called without
14979 arguments, with the cursor positioned at the beginning of the headline.
14980 The return values of all calls to the function will be collected and
14981 returned as a list.
14983 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14984 does not need to preserve point. After evaluation, the cursor will be
14985 moved to the end of the line (presumably of the headline of the
14986 processed entry) and search continues from there. Under some
14987 circumstances, this may not produce the wanted results. For example,
14988 if you have removed (e.g. archived) the current (sub)tree it could
14989 mean that the next entry will be skipped entirely. In such cases, you
14990 can specify the position from where search should continue by making
14991 FUNC set the variable `org-map-continue-from' to the desired buffer
14992 position.
14994 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14995 Only headlines that are matched by this query will be considered during
14996 the iteration. When MATCH is nil or t, all headlines will be
14997 visited by the iteration.
14999 SCOPE determines the scope of this command. It can be any of:
15001 nil The current buffer, respecting the restriction if any
15002 tree The subtree started with the entry at point
15003 region The entries within the active region, if any
15004 region-start-level
15005 The entries within the active region, but only those at
15006 the same level than the first one.
15007 file The current buffer, without restriction
15008 file-with-archives
15009 The current buffer, and any archives associated with it
15010 agenda All agenda files
15011 agenda-with-archives
15012 All agenda files with any archive files associated with them
15013 \(file1 file2 ...)
15014 If this is a list, all files in the list will be scanned
15016 The remaining args are treated as settings for the skipping facilities of
15017 the scanner. The following items can be given here:
15019 archive skip trees with the archive tag
15020 comment skip trees with the COMMENT keyword
15021 function or Emacs Lisp form:
15022 will be used as value for `org-agenda-skip-function', so
15023 whenever the function returns a position, FUNC will not be
15024 called for that entry and search will continue from the
15025 position returned
15027 If your function needs to retrieve the tags including inherited tags
15028 at the *current* entry, you can use the value of the variable
15029 `org-scanner-tags' which will be much faster than getting the value
15030 with `org-get-tags-at'. If your function gets properties with
15031 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15032 to t around the call to `org-entry-properties' to get the same speedup.
15033 Note that if your function moves around to retrieve tags and properties at
15034 a *different* entry, you cannot use these techniques."
15035 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15036 (not (org-region-active-p)))
15037 (let* ((org-agenda-archives-mode nil) ; just to make sure
15038 (org-agenda-skip-archived-trees (memq 'archive skip))
15039 (org-agenda-skip-comment-trees (memq 'comment skip))
15040 (org-agenda-skip-function
15041 (car (org-delete-all '(comment archive) skip)))
15042 (org-tags-match-list-sublevels t)
15043 (start-level (eq scope 'region-start-level))
15044 matcher res
15045 org-todo-keywords-for-agenda
15046 org-done-keywords-for-agenda
15047 org-todo-keyword-alist-for-agenda
15048 org-tag-alist-for-agenda
15049 org--matcher-tags-todo-only)
15051 (cond
15052 ((eq match t) (setq matcher t))
15053 ((eq match nil) (setq matcher t))
15054 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15056 (save-excursion
15057 (save-restriction
15058 (cond ((eq scope 'tree)
15059 (org-back-to-heading t)
15060 (org-narrow-to-subtree)
15061 (setq scope nil))
15062 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15063 (org-region-active-p))
15064 ;; If needed, set start-level to a string like "2"
15065 (when start-level
15066 (save-excursion
15067 (goto-char (region-beginning))
15068 (unless (org-at-heading-p) (outline-next-heading))
15069 (setq start-level (org-current-level))))
15070 (narrow-to-region (region-beginning)
15071 (save-excursion
15072 (goto-char (region-end))
15073 (unless (and (bolp) (org-at-heading-p))
15074 (outline-next-heading))
15075 (point)))
15076 (setq scope nil)))
15078 (if (not scope)
15079 (progn
15080 (org-agenda-prepare-buffers
15081 (and buffer-file-name (list buffer-file-name)))
15082 (setq res
15083 (org-scan-tags
15084 func matcher org--matcher-tags-todo-only start-level)))
15085 ;; Get the right scope
15086 (cond
15087 ((and scope (listp scope) (symbolp (car scope)))
15088 (setq scope (eval scope)))
15089 ((eq scope 'agenda)
15090 (setq scope (org-agenda-files t)))
15091 ((eq scope 'agenda-with-archives)
15092 (setq scope (org-agenda-files t))
15093 (setq scope (org-add-archive-files scope)))
15094 ((eq scope 'file)
15095 (setq scope (and buffer-file-name (list buffer-file-name))))
15096 ((eq scope 'file-with-archives)
15097 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15098 (org-agenda-prepare-buffers scope)
15099 (dolist (file scope)
15100 (with-current-buffer (org-find-base-buffer-visiting file)
15101 (org-with-wide-buffer
15102 (goto-char (point-min))
15103 (setq res
15104 (append
15106 (org-scan-tags
15107 func matcher org--matcher-tags-todo-only)))))))))
15108 res)))
15110 ;;; Properties API
15112 (defconst org-special-properties
15113 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15114 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15115 "The special properties valid in Org mode.
15116 These are properties that are not defined in the property drawer,
15117 but in some other way.")
15119 (defconst org-default-properties
15120 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15121 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15122 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15123 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15124 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15125 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15126 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15127 "Some properties that are used by Org mode for various purposes.
15128 Being in this list makes sure that they are offered for completion.")
15130 (defun org--valid-property-p (property)
15131 "Non nil when string PROPERTY is a valid property name."
15132 (not
15133 (or (equal property "")
15134 (string-match-p "\\s-" property))))
15136 (defun org--update-property-plist (key val props)
15137 "Associate KEY to VAL in alist PROPS.
15138 Modifications are made by side-effect. Return new alist."
15139 (let* ((appending (string= (substring key -1) "+"))
15140 (key (if appending (substring key 0 -1) key))
15141 (old (assoc-string key props t)))
15142 (if (not old) (cons (cons key val) props)
15143 (setcdr old (if appending (concat (cdr old) " " val) val))
15144 props)))
15146 (defun org-get-property-block (&optional beg force)
15147 "Return the (beg . end) range of the body of the property drawer.
15148 BEG is the beginning of the current subtree, or of the part
15149 before the first headline. If it is not given, it will be found.
15150 If the drawer does not exist, create it if FORCE is non-nil, or
15151 return nil."
15152 (org-with-wide-buffer
15153 (when beg (goto-char beg))
15154 (unless (org-before-first-heading-p)
15155 (let ((beg (cond (beg)
15156 ((or (not (featurep 'org-inlinetask))
15157 (org-inlinetask-in-task-p))
15158 (org-back-to-heading t))
15159 (t (org-with-limited-levels (org-back-to-heading t))))))
15160 (forward-line)
15161 (when (looking-at-p org-planning-line-re) (forward-line))
15162 (cond ((looking-at org-property-drawer-re)
15163 (forward-line)
15164 (cons (point) (progn (goto-char (match-end 0))
15165 (line-beginning-position))))
15166 (force
15167 (goto-char beg)
15168 (org-insert-property-drawer)
15169 (let ((pos (save-excursion (search-forward ":END:")
15170 (line-beginning-position))))
15171 (cons pos pos))))))))
15173 (defun org-at-property-p ()
15174 "Non-nil when point is inside a property drawer.
15175 See `org-property-re' for match data, if applicable."
15176 (save-excursion
15177 (beginning-of-line)
15178 (and (looking-at org-property-re)
15179 (let ((property-drawer (save-match-data (org-get-property-block))))
15180 (and property-drawer
15181 (>= (point) (car property-drawer))
15182 (< (point) (cdr property-drawer)))))))
15184 (defun org-property-action ()
15185 "Do an action on properties."
15186 (interactive)
15187 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15188 (let ((c (read-char-exclusive)))
15189 (cl-case c
15190 (?s (call-interactively #'org-set-property))
15191 (?d (call-interactively #'org-delete-property))
15192 (?D (call-interactively #'org-delete-property-globally))
15193 (?c (call-interactively #'org-compute-property-at-point))
15194 (otherwise (user-error "No such property action %c" c)))))
15196 (defun org-inc-effort ()
15197 "Increment the value of the effort property in the current entry."
15198 (interactive)
15199 (org-set-effort nil t))
15201 (defvar org-clock-effort) ; Defined in org-clock.el.
15202 (defvar org-clock-current-task) ; Defined in org-clock.el.
15203 (defun org-set-effort (&optional value increment)
15204 "Set the effort property of the current entry.
15205 With numerical prefix arg, use the nth allowed value, 0 stands for the
15206 10th allowed value.
15208 When INCREMENT is non-nil, set the property to the next allowed value."
15209 (interactive "P")
15210 (when (equal value 0) (setq value 10))
15211 (let* ((completion-ignore-case t)
15212 (prop org-effort-property)
15213 (cur (org-entry-get nil prop))
15214 (allowed (org-property-get-allowed-values nil prop 'table))
15215 (existing (mapcar 'list (org-property-values prop)))
15216 (heading (nth 4 (org-heading-components)))
15218 (val (cond
15219 ((stringp value) value)
15220 ((and allowed (integerp value))
15221 (or (car (nth (1- value) allowed))
15222 (car (org-last allowed))))
15223 ((and allowed increment)
15224 (or (cl-caadr (member (list cur) allowed))
15225 (user-error "Allowed effort values are not set")))
15226 (allowed
15227 (message "Select 1-9,0, [RET%s]: %s"
15228 (if cur (concat "=" cur) "")
15229 (mapconcat 'car allowed " "))
15230 (setq rpl (read-char-exclusive))
15231 (if (equal rpl ?\r)
15233 (setq rpl (- rpl ?0))
15234 (when (equal rpl 0) (setq rpl 10))
15235 (if (and (> rpl 0) (<= rpl (length allowed)))
15236 (car (nth (1- rpl) allowed))
15237 (org-completing-read "Effort: " allowed nil))))
15239 (org-completing-read
15240 (concat "Effort" (and cur (string-match "\\S-" cur)
15241 (concat " [" cur "]"))
15242 ": ")
15243 existing nil nil "" nil cur)))))
15244 (unless (equal (org-entry-get nil prop) val)
15245 (org-entry-put nil prop val))
15246 (org-refresh-property
15247 '((effort . identity)
15248 (effort-minutes . org-duration-to-minutes))
15249 val)
15250 (when (equal heading (bound-and-true-p org-clock-current-task))
15251 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15252 (org-clock-update-mode-line))
15253 (message "%s is now %s" prop val)))
15255 (defun org-entry-properties (&optional pom which)
15256 "Get all properties of the current entry.
15258 When POM is a buffer position, get all properties from the entry
15259 there instead.
15261 This includes the TODO keyword, the tags, time strings for
15262 deadline, scheduled, and clocking, and any additional properties
15263 defined in the entry.
15265 If WHICH is nil or `all', get all properties. If WHICH is
15266 `special' or `standard', only get that subclass. If WHICH is
15267 a string, only get that property.
15269 Return value is an alist. Keys are properties, as upcased
15270 strings."
15271 (org-with-point-at pom
15272 (when (and (derived-mode-p 'org-mode)
15273 (ignore-errors (org-back-to-heading t)))
15274 (catch 'exit
15275 (let* ((beg (point))
15276 (specific (and (stringp which) (upcase which)))
15277 (which (cond ((not specific) which)
15278 ((member specific org-special-properties) 'special)
15279 (t 'standard)))
15280 props)
15281 ;; Get the special properties, like TODO and TAGS.
15282 (when (memq which '(nil all special))
15283 (when (or (not specific) (string= specific "CLOCKSUM"))
15284 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15285 (when clocksum
15286 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15287 props)))
15288 (when specific (throw 'exit props)))
15289 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15290 (let ((clocksumt (get-text-property (point)
15291 :org-clock-minutes-today)))
15292 (when clocksumt
15293 (push (cons "CLOCKSUM_T"
15294 (org-duration-from-minutes clocksumt))
15295 props)))
15296 (when specific (throw 'exit props)))
15297 (when (or (not specific) (string= specific "ITEM"))
15298 (let ((case-fold-search nil))
15299 (when (looking-at org-complex-heading-regexp)
15300 (push (cons "ITEM"
15301 (let ((title (match-string-no-properties 4)))
15302 (if (org-string-nw-p title)
15303 (org-remove-tabs title)
15304 "")))
15305 props)))
15306 (when specific (throw 'exit props)))
15307 (when (or (not specific) (string= specific "TODO"))
15308 (let ((case-fold-search nil))
15309 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15310 (push (cons "TODO" (match-string-no-properties 2)) props)))
15311 (when specific (throw 'exit props)))
15312 (when (or (not specific) (string= specific "PRIORITY"))
15313 (push (cons "PRIORITY"
15314 (if (looking-at org-priority-regexp)
15315 (match-string-no-properties 2)
15316 (char-to-string org-default-priority)))
15317 props)
15318 (when specific (throw 'exit props)))
15319 (when (or (not specific) (string= specific "FILE"))
15320 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15321 props)
15322 (when specific (throw 'exit props)))
15323 (when (or (not specific) (string= specific "TAGS"))
15324 (let ((value (org-string-nw-p (org-get-tags-string))))
15325 (when value (push (cons "TAGS" value) props)))
15326 (when specific (throw 'exit props)))
15327 (when (or (not specific) (string= specific "ALLTAGS"))
15328 (let ((value (org-get-tags-at)))
15329 (when value
15330 (push (cons "ALLTAGS"
15331 (format ":%s:" (mapconcat #'identity value ":")))
15332 props)))
15333 (when specific (throw 'exit props)))
15334 (when (or (not specific) (string= specific "BLOCKED"))
15335 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15336 (when specific (throw 'exit props)))
15337 (when (or (not specific)
15338 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15339 (forward-line)
15340 (when (looking-at-p org-planning-line-re)
15341 (end-of-line)
15342 (let ((bol (line-beginning-position))
15343 ;; Backward compatibility: time keywords used to
15344 ;; be configurable (before 8.3). Make sure we
15345 ;; get the correct keyword.
15346 (key-assoc `(("CLOSED" . ,org-closed-string)
15347 ("DEADLINE" . ,org-deadline-string)
15348 ("SCHEDULED" . ,org-scheduled-string))))
15349 (dolist (pair (if specific (list (assoc specific key-assoc))
15350 key-assoc))
15351 (save-excursion
15352 (when (search-backward (cdr pair) bol t)
15353 (goto-char (match-end 0))
15354 (skip-chars-forward " \t")
15355 (and (looking-at org-ts-regexp-both)
15356 (push (cons (car pair)
15357 (match-string-no-properties 0))
15358 props)))))))
15359 (when specific (throw 'exit props)))
15360 (when (or (not specific)
15361 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15362 (let ((find-ts
15363 (lambda (end ts)
15364 ;; Fix next time-stamp before END. TS is the
15365 ;; list of time-stamps found so far.
15366 (let ((ts ts)
15367 (regexp (cond
15368 ((string= specific "TIMESTAMP")
15369 org-ts-regexp)
15370 ((string= specific "TIMESTAMP_IA")
15371 org-ts-regexp-inactive)
15372 ((assoc "TIMESTAMP_IA" ts)
15373 org-ts-regexp)
15374 ((assoc "TIMESTAMP" ts)
15375 org-ts-regexp-inactive)
15376 (t org-ts-regexp-both))))
15377 (catch 'next
15378 (while (re-search-forward regexp end t)
15379 (backward-char)
15380 (let ((object (org-element-context)))
15381 ;; Accept to match timestamps in node
15382 ;; properties, too.
15383 (when (memq (org-element-type object)
15384 '(node-property timestamp))
15385 (let ((type
15386 (org-element-property :type object)))
15387 (cond
15388 ((and (memq type '(active active-range))
15389 (not (equal specific "TIMESTAMP_IA")))
15390 (unless (assoc "TIMESTAMP" ts)
15391 (push (cons "TIMESTAMP"
15392 (org-element-property
15393 :raw-value object))
15395 (when specific (throw 'exit ts))))
15396 ((and (memq type '(inactive inactive-range))
15397 (not (string= specific "TIMESTAMP")))
15398 (unless (assoc "TIMESTAMP_IA" ts)
15399 (push (cons "TIMESTAMP_IA"
15400 (org-element-property
15401 :raw-value object))
15403 (when specific (throw 'exit ts))))))
15404 ;; Both timestamp types are found,
15405 ;; move to next part.
15406 (when (= (length ts) 2) (throw 'next ts)))))
15407 ts)))))
15408 (goto-char beg)
15409 ;; First look for timestamps within headline.
15410 (let ((ts (funcall find-ts (line-end-position) nil)))
15411 (if (= (length ts) 2) (setq props (nconc ts props))
15412 ;; Then find timestamps in the section, skipping
15413 ;; planning line.
15414 (let ((end (save-excursion (outline-next-heading))))
15415 (forward-line)
15416 (when (looking-at-p org-planning-line-re) (forward-line))
15417 (setq props (nconc (funcall find-ts end ts) props))))))))
15418 ;; Get the standard properties, like :PROP:.
15419 (when (memq which '(nil all standard))
15420 ;; If we are looking after a specific property, delegate
15421 ;; to `org-entry-get', which is faster. However, make an
15422 ;; exception for "CATEGORY", since it can be also set
15423 ;; through keywords (i.e. #+CATEGORY).
15424 (if (and specific (not (equal specific "CATEGORY")))
15425 (let ((value (org-entry-get beg specific nil t)))
15426 (throw 'exit (and value (list (cons specific value)))))
15427 (let ((range (org-get-property-block beg)))
15428 (when range
15429 (let ((end (cdr range)) seen-base)
15430 (goto-char (car range))
15431 ;; Unlike to `org--update-property-plist', we
15432 ;; handle the case where base values is found
15433 ;; after its extension. We also forbid standard
15434 ;; properties to be named as special properties.
15435 (while (re-search-forward org-property-re end t)
15436 (let* ((key (upcase (match-string-no-properties 2)))
15437 (extendp (string-match-p "\\+\\'" key))
15438 (key-base (if extendp (substring key 0 -1) key))
15439 (value (match-string-no-properties 3)))
15440 (cond
15441 ((member-ignore-case key-base org-special-properties))
15442 (extendp
15443 (setq props
15444 (org--update-property-plist key value props)))
15445 ((member key seen-base))
15446 (t (push key seen-base)
15447 (let ((p (assoc-string key props t)))
15448 (if p (setcdr p (concat value " " (cdr p)))
15449 (push (cons key value) props))))))))))))
15450 (unless (assoc "CATEGORY" props)
15451 (push (cons "CATEGORY" (org-get-category beg)) props)
15452 (when (string= specific "CATEGORY") (throw 'exit props)))
15453 ;; Return value.
15454 props)))))
15456 (defun org--property-local-values (property literal-nil)
15457 "Return value for PROPERTY in current entry.
15458 Value is a list whose car is the base value for PROPERTY and cdr
15459 a list of accumulated values. Return nil if neither is found in
15460 the entry. Also return nil when PROPERTY is set to \"nil\",
15461 unless LITERAL-NIL is non-nil."
15462 (let ((range (org-get-property-block)))
15463 (when range
15464 (goto-char (car range))
15465 (let* ((case-fold-search t)
15466 (end (cdr range))
15467 (value
15468 ;; Base value.
15469 (save-excursion
15470 (let ((v (and (re-search-forward
15471 (org-re-property property nil t) end t)
15472 (match-string-no-properties 3))))
15473 (list (if literal-nil v (org-not-nil v)))))))
15474 ;; Find additional values.
15475 (let* ((property+ (org-re-property (concat property "+") nil t)))
15476 (while (re-search-forward property+ end t)
15477 (push (match-string-no-properties 3) value)))
15478 ;; Return final values.
15479 (and (not (equal value '(nil))) (nreverse value))))))
15481 (defun org--property-global-value (property literal-nil)
15482 "Return value for PROPERTY in current buffer.
15483 Return value is a string. Return nil if property is not set
15484 globally. Also return nil when PROPERTY is set to \"nil\",
15485 unless LITERAL-NIL is non-nil."
15486 (let ((global
15487 (cdr (or (assoc-string property org-file-properties t)
15488 (assoc-string property org-global-properties t)
15489 (assoc-string property org-global-properties-fixed t)))))
15490 (if literal-nil global (org-not-nil global))))
15492 (defun org-entry-get (pom property &optional inherit literal-nil)
15493 "Get value of PROPERTY for entry or content at point-or-marker POM.
15495 If INHERIT is non-nil and the entry does not have the property,
15496 then also check higher levels of the hierarchy. If INHERIT is
15497 the symbol `selective', use inheritance only if the setting in
15498 `org-use-property-inheritance' selects PROPERTY for inheritance.
15500 If the property is present but empty, the return value is the
15501 empty string. If the property is not present at all, nil is
15502 returned. In any other case, return the value as a string.
15503 Search is case-insensitive.
15505 If LITERAL-NIL is set, return the string value \"nil\" as
15506 a string, do not interpret it as the list atom nil. This is used
15507 for inheritance when a \"nil\" value can supersede a non-nil
15508 value higher up the hierarchy."
15509 (org-with-point-at pom
15510 (cond
15511 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15512 ;; We need a special property. Use `org-entry-properties' to
15513 ;; retrieve it, but specify the wanted property.
15514 (cdr (assoc-string property (org-entry-properties nil property))))
15515 ((and inherit
15516 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15517 (org-entry-get-with-inheritance property literal-nil))
15519 (let* ((local (org--property-local-values property literal-nil))
15520 (value (and local (mapconcat #'identity (delq nil local) " "))))
15521 (if literal-nil value (org-not-nil value)))))))
15523 (defun org-property-or-variable-value (var &optional inherit)
15524 "Check if there is a property fixing the value of VAR.
15525 If yes, return this value. If not, return the current value of the variable."
15526 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15527 (if (and prop (stringp prop) (string-match "\\S-" prop))
15528 (read prop)
15529 (symbol-value var))))
15531 (defun org-entry-delete (pom property)
15532 "Delete PROPERTY from entry at point-or-marker POM.
15533 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15534 non-nil when a property was removed."
15535 (org-with-point-at pom
15536 (pcase (org-get-property-block)
15537 (`(,begin . ,origin)
15538 (let* ((end (copy-marker origin))
15539 (re (org-re-property
15540 (concat (regexp-quote property) "\\+?") t t)))
15541 (goto-char begin)
15542 (while (re-search-forward re end t)
15543 (delete-region (match-beginning 0) (line-beginning-position 2)))
15544 ;; If drawer is empty, remove it altogether.
15545 (when (= begin end)
15546 (delete-region (line-beginning-position 0)
15547 (line-beginning-position 2)))
15548 ;; Return non-nil if some property was removed.
15549 (prog1 (/= end origin) (set-marker end nil))))
15550 (_ nil))))
15552 ;; Multi-values properties are properties that contain multiple values
15553 ;; These values are assumed to be single words, separated by whitespace.
15554 (defun org-entry-add-to-multivalued-property (pom property value)
15555 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15556 (let* ((old (org-entry-get pom property))
15557 (values (and old (split-string old))))
15558 (setq value (org-entry-protect-space value))
15559 (unless (member value values)
15560 (setq values (append values (list value)))
15561 (org-entry-put pom property (mapconcat #'identity values " ")))))
15563 (defun org-entry-remove-from-multivalued-property (pom property value)
15564 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15565 (let* ((old (org-entry-get pom property))
15566 (values (and old (split-string old))))
15567 (setq value (org-entry-protect-space value))
15568 (when (member value values)
15569 (setq values (delete value values))
15570 (org-entry-put pom property (mapconcat #'identity values " ")))))
15572 (defun org-entry-member-in-multivalued-property (pom property value)
15573 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15574 (let* ((old (org-entry-get pom property))
15575 (values (and old (split-string old))))
15576 (setq value (org-entry-protect-space value))
15577 (member value values)))
15579 (defun org-entry-get-multivalued-property (pom property)
15580 "Return a list of values in a multivalued property."
15581 (let* ((value (org-entry-get pom property))
15582 (values (and value (split-string value))))
15583 (mapcar #'org-entry-restore-space values)))
15585 (defun org-entry-put-multivalued-property (pom property &rest values)
15586 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15587 VALUES should be a list of strings. Spaces will be protected."
15588 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15589 (let* ((value (org-entry-get pom property))
15590 (values (and value (split-string value))))
15591 (mapcar #'org-entry-restore-space values)))
15593 (defun org-entry-protect-space (s)
15594 "Protect spaces and newline in string S."
15595 (while (string-match " " s)
15596 (setq s (replace-match "%20" t t s)))
15597 (while (string-match "\n" s)
15598 (setq s (replace-match "%0A" t t s)))
15601 (defun org-entry-restore-space (s)
15602 "Restore spaces and newline in string S."
15603 (while (string-match "%20" s)
15604 (setq s (replace-match " " t t s)))
15605 (while (string-match "%0A" s)
15606 (setq s (replace-match "\n" t t s)))
15609 (defvar org-entry-property-inherited-from (make-marker)
15610 "Marker pointing to the entry from where a property was inherited.
15611 Each call to `org-entry-get-with-inheritance' will set this marker to the
15612 location of the entry where the inheritance search matched. If there was
15613 no match, the marker will point nowhere.
15614 Note that also `org-entry-get' calls this function, if the INHERIT flag
15615 is set.")
15617 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15618 "Get PROPERTY of entry or content at point, search higher levels if needed.
15619 The search will stop at the first ancestor which has the property defined.
15620 If the value found is \"nil\", return nil to show that the property
15621 should be considered as undefined (this is the meaning of nil here).
15622 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15623 (move-marker org-entry-property-inherited-from nil)
15624 (org-with-wide-buffer
15625 (let (value)
15626 (catch 'exit
15627 (while t
15628 (let ((v (org--property-local-values property literal-nil)))
15629 (when v
15630 (setq value
15631 (concat (mapconcat #'identity (delq nil v) " ")
15632 (and value " ")
15633 value)))
15634 (cond
15635 ((car v)
15636 (org-back-to-heading t)
15637 (move-marker org-entry-property-inherited-from (point))
15638 (throw 'exit nil))
15639 ((org-up-heading-safe))
15641 (let ((global (org--property-global-value property literal-nil)))
15642 (cond ((not global))
15643 (value (setq value (concat global " " value)))
15644 (t (setq value global))))
15645 (throw 'exit nil))))))
15646 (if literal-nil value (org-not-nil value)))))
15648 (defvar org-property-changed-functions nil
15649 "Hook called when the value of a property has changed.
15650 Each hook function should accept two arguments, the name of the property
15651 and the new value.")
15653 (defun org-entry-put (pom property value)
15654 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15656 If the value is nil, it is converted to the empty string. If it
15657 is not a string, an error is raised. Also raise an error on
15658 invalid property names.
15660 PROPERTY can be any regular property (see
15661 `org-special-properties'). It can also be \"TODO\",
15662 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15664 For the last two properties, VALUE may have any of the special
15665 values \"earlier\" and \"later\". The function then increases or
15666 decreases scheduled or deadline date by one day."
15667 (cond ((null value) (setq value ""))
15668 ((not (stringp value)) (error "Properties values should be strings"))
15669 ((not (org--valid-property-p property))
15670 (user-error "Invalid property name: \"%s\"" property)))
15671 (org-with-point-at pom
15672 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15673 (org-back-to-heading t)
15674 (org-with-limited-levels (org-back-to-heading t)))
15675 (let ((beg (point)))
15676 (cond
15677 ((equal property "TODO")
15678 (cond ((not (org-string-nw-p value)) (setq value 'none))
15679 ((not (member value org-todo-keywords-1))
15680 (user-error "\"%s\" is not a valid TODO state" value)))
15681 (org-todo value)
15682 (org-set-tags nil 'align))
15683 ((equal property "PRIORITY")
15684 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15685 (org-set-tags nil 'align))
15686 ((equal property "SCHEDULED")
15687 (forward-line)
15688 (if (and (looking-at-p org-planning-line-re)
15689 (re-search-forward
15690 org-scheduled-time-regexp (line-end-position) t))
15691 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15692 ((string= value "later") (org-timestamp-change 1 'day))
15693 ((string= value "") (org-schedule '(4)))
15694 (t (org-schedule nil value)))
15695 (if (member value '("earlier" "later" ""))
15696 (call-interactively #'org-schedule)
15697 (org-schedule nil value))))
15698 ((equal property "DEADLINE")
15699 (forward-line)
15700 (if (and (looking-at-p org-planning-line-re)
15701 (re-search-forward
15702 org-deadline-time-regexp (line-end-position) t))
15703 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15704 ((string= value "later") (org-timestamp-change 1 'day))
15705 ((string= value "") (org-deadline '(4)))
15706 (t (org-deadline nil value)))
15707 (if (member value '("earlier" "later" ""))
15708 (call-interactively #'org-deadline)
15709 (org-deadline nil value))))
15710 ((member property org-special-properties)
15711 (error "The %s property cannot be set with `org-entry-put'" property))
15713 (let* ((range (org-get-property-block beg 'force))
15714 (end (cdr range))
15715 (case-fold-search t))
15716 (goto-char (car range))
15717 (if (re-search-forward (org-re-property property nil t) end t)
15718 (progn (delete-region (match-beginning 0) (match-end 0))
15719 (goto-char (match-beginning 0)))
15720 (goto-char end)
15721 (insert "\n")
15722 (backward-char))
15723 (insert ":" property ":")
15724 (when value (insert " " value))
15725 (org-indent-line)))))
15726 (run-hook-with-args 'org-property-changed-functions property value)))
15728 (defun org-buffer-property-keys (&optional specials defaults columns)
15729 "Get all property keys in the current buffer.
15731 When SPECIALS is non-nil, also list the special properties that
15732 reflect things like tags and TODO state.
15734 When DEFAULTS is non-nil, also include properties that has
15735 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15736 DESCRIPTION, LOCATION, and LOGGING and others.
15738 When COLUMNS in non-nil, also include property names given in
15739 COLUMN formats in the current buffer."
15740 (let ((case-fold-search t)
15741 (props (append
15742 (and specials org-special-properties)
15743 (and defaults (cons org-effort-property org-default-properties))
15744 nil)))
15745 (org-with-wide-buffer
15746 (goto-char (point-min))
15747 (while (re-search-forward org-property-start-re nil t)
15748 (catch :skip
15749 (let ((range (org-get-property-block)))
15750 (unless range (throw :skip nil))
15751 (goto-char (car range))
15752 (let ((begin (car range))
15753 (end (cdr range)))
15754 ;; Make sure that found property block is not located
15755 ;; before current point, as it would generate an infloop.
15756 ;; It can happen, for example, in the following
15757 ;; situation:
15759 ;; * Headline
15760 ;; :PROPERTIES:
15761 ;; ...
15762 ;; :END:
15763 ;; *************** Inlinetask
15764 ;; #+BEGIN_EXAMPLE
15765 ;; :PROPERTIES:
15766 ;; #+END_EXAMPLE
15768 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15769 (while (< (point) end)
15770 (let ((p (progn (looking-at org-property-re)
15771 (match-string-no-properties 2))))
15772 ;; Only add true property name, not extension symbol.
15773 (push (if (not (string-match-p "\\+\\'" p)) p
15774 (substring p 0 -1))
15775 props))
15776 (forward-line))))
15777 (outline-next-heading)))
15778 (when columns
15779 (goto-char (point-min))
15780 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15781 (let ((element (org-element-at-point)))
15782 (when (memq (org-element-type element) '(keyword node-property))
15783 (let ((value (org-element-property :value element))
15784 (start 0))
15785 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15786 \\(?:{[^}]+}\\)?"
15787 value start)
15788 (setq start (match-end 0))
15789 (let ((p (match-string-no-properties 1 value)))
15790 (unless (member-ignore-case p org-special-properties)
15791 (push p props))))))))))
15792 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15794 (defun org-property-values (key)
15795 "List all non-nil values of property KEY in current buffer."
15796 (org-with-wide-buffer
15797 (goto-char (point-min))
15798 (let ((case-fold-search t)
15799 (re (org-re-property key))
15800 values)
15801 (while (re-search-forward re nil t)
15802 (push (org-entry-get (point) key) values))
15803 (delete-dups values))))
15805 (defun org-insert-property-drawer ()
15806 "Insert a property drawer into the current entry."
15807 (org-with-wide-buffer
15808 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15809 (org-back-to-heading t)
15810 (org-with-limited-levels (org-back-to-heading t)))
15811 (forward-line)
15812 (when (looking-at-p org-planning-line-re) (forward-line))
15813 (unless (looking-at-p org-property-drawer-re)
15814 ;; Make sure we start editing a line from current entry, not from
15815 ;; next one. It prevents extending text properties or overlays
15816 ;; belonging to the latter.
15817 (when (bolp) (backward-char))
15818 (let ((begin (1+ (point)))
15819 (inhibit-read-only t))
15820 (insert "\n:PROPERTIES:\n:END:")
15821 (when (eobp) (insert "\n"))
15822 (org-indent-region begin (point))))))
15824 (defun org-insert-drawer (&optional arg drawer)
15825 "Insert a drawer at point.
15827 When optional argument ARG is non-nil, insert a property drawer.
15829 Optional argument DRAWER, when non-nil, is a string representing
15830 drawer's name. Otherwise, the user is prompted for a name.
15832 If a region is active, insert the drawer around that region
15833 instead.
15835 Point is left between drawer's boundaries."
15836 (interactive "P")
15837 (let* ((drawer (if arg "PROPERTIES"
15838 (or drawer (read-from-minibuffer "Drawer: ")))))
15839 (cond
15840 ;; With C-u, fall back on `org-insert-property-drawer'
15841 (arg (org-insert-property-drawer))
15842 ;; Check validity of suggested drawer's name.
15843 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15844 (user-error "Invalid drawer name"))
15845 ;; With an active region, insert a drawer at point.
15846 ((not (org-region-active-p))
15847 (progn
15848 (unless (bolp) (insert "\n"))
15849 (insert (format ":%s:\n\n:END:\n" drawer))
15850 (forward-line -2)))
15851 ;; Otherwise, insert the drawer at point
15853 (let ((rbeg (region-beginning))
15854 (rend (copy-marker (region-end))))
15855 (unwind-protect
15856 (progn
15857 (goto-char rbeg)
15858 (beginning-of-line)
15859 (when (save-excursion
15860 (re-search-forward org-outline-regexp-bol rend t))
15861 (user-error "Drawers cannot contain headlines"))
15862 ;; Position point at the beginning of the first
15863 ;; non-blank line in region. Insert drawer's opening
15864 ;; there, then indent it.
15865 (org-skip-whitespace)
15866 (beginning-of-line)
15867 (insert ":" drawer ":\n")
15868 (forward-line -1)
15869 (indent-for-tab-command)
15870 ;; Move point to the beginning of the first blank line
15871 ;; after the last non-blank line in region. Insert
15872 ;; drawer's closing, then indent it.
15873 (goto-char rend)
15874 (skip-chars-backward " \r\t\n")
15875 (insert "\n:END:")
15876 (deactivate-mark t)
15877 (indent-for-tab-command)
15878 (unless (eolp) (insert "\n")))
15879 ;; Clear marker, whatever the outcome of insertion is.
15880 (set-marker rend nil)))))))
15882 (defvar org-property-set-functions-alist nil
15883 "Property set function alist.
15884 Each entry should have the following format:
15886 (PROPERTY . READ-FUNCTION)
15888 The read function will be called with the same argument as
15889 `org-completing-read'.")
15891 (defun org-set-property-function (property)
15892 "Get the function that should be used to set PROPERTY.
15893 This is computed according to `org-property-set-functions-alist'."
15894 (or (cdr (assoc property org-property-set-functions-alist))
15895 'org-completing-read))
15897 (defun org-read-property-value (property)
15898 "Read PROPERTY value from user."
15899 (let* ((completion-ignore-case t)
15900 (allowed (org-property-get-allowed-values nil property 'table))
15901 (cur (org-entry-get nil property))
15902 (prompt (concat property " value"
15903 (if (and cur (string-match "\\S-" cur))
15904 (concat " [" cur "]") "") ": "))
15905 (set-function (org-set-property-function property))
15906 (val (if allowed
15907 (funcall set-function prompt allowed nil
15908 (not (get-text-property 0 'org-unrestricted
15909 (caar allowed))))
15910 (funcall set-function prompt
15911 (mapcar 'list (org-property-values property))
15912 nil nil "" nil cur))))
15913 (org-trim val)))
15915 (defvar org-last-set-property nil)
15916 (defvar org-last-set-property-value nil)
15917 (defun org-read-property-name ()
15918 "Read a property name."
15919 (let ((completion-ignore-case t)
15920 (default-prop (or (and (org-at-property-p)
15921 (match-string-no-properties 2))
15922 org-last-set-property)))
15923 (org-completing-read
15924 (concat "Property"
15925 (if default-prop (concat " [" default-prop "]") "")
15926 ": ")
15927 (mapcar #'list (org-buffer-property-keys nil t t))
15928 nil nil nil nil default-prop)))
15930 (defun org-set-property-and-value (use-last)
15931 "Allow to set [PROPERTY]: [value] direction from prompt.
15932 When use-default, don't even ask, just use the last
15933 \"[PROPERTY]: [value]\" string from the history."
15934 (interactive "P")
15935 (let* ((completion-ignore-case t)
15936 (pv (or (and use-last org-last-set-property-value)
15937 (org-completing-read
15938 "Enter a \"[Property]: [value]\" pair: "
15939 nil nil nil nil nil
15940 org-last-set-property-value)))
15941 prop val)
15942 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15943 (setq prop (match-string 1 pv)
15944 val (match-string 2 pv))
15945 (org-set-property prop val))))
15947 (defun org-set-property (property value)
15948 "In the current entry, set PROPERTY to VALUE.
15950 When called interactively, this will prompt for a property name, offering
15951 completion on existing and default properties. And then it will prompt
15952 for a value, offering completion either on allowed values (via an inherited
15953 xxx_ALL property) or on existing values in other instances of this property
15954 in the current file.
15956 Throw an error when trying to set a property with an invalid name."
15957 (interactive (list nil nil))
15958 (let ((property (or property (org-read-property-name))))
15959 ;; `org-entry-put' also makes the following check, but this one
15960 ;; avoids polluting `org-last-set-property' and
15961 ;; `org-last-set-property-value' needlessly.
15962 (unless (org--valid-property-p property)
15963 (user-error "Invalid property name: \"%s\"" property))
15964 (let ((value (or value (org-read-property-value property)))
15965 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15966 (setq org-last-set-property property)
15967 (setq org-last-set-property-value (concat property ": " value))
15968 ;; Possibly postprocess the inserted value:
15969 (when fn (setq value (funcall fn value)))
15970 (unless (equal (org-entry-get nil property) value)
15971 (org-entry-put nil property value)))))
15973 (defun org-find-property (property &optional value)
15974 "Find first entry in buffer that sets PROPERTY.
15976 When optional argument VALUE is non-nil, only consider an entry
15977 if it contains PROPERTY set to this value. If PROPERTY should be
15978 explicitly set to nil, use string \"nil\" for VALUE.
15980 Return position where the entry begins, or nil if there is no
15981 such entry. If narrowing is in effect, only search the visible
15982 part of the buffer."
15983 (save-excursion
15984 (goto-char (point-min))
15985 (let ((case-fold-search t)
15986 (re (org-re-property property nil (not value) value)))
15987 (catch 'exit
15988 (while (re-search-forward re nil t)
15989 (when (if value (org-at-property-p)
15990 (org-entry-get (point) property nil t))
15991 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15993 (defun org-delete-property (property)
15994 "In the current entry, delete PROPERTY."
15995 (interactive
15996 (let* ((completion-ignore-case t)
15997 (cat (org-entry-get (point) "CATEGORY"))
15998 (props0 (org-entry-properties nil 'standard))
15999 (props (if cat props0
16000 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16001 (prop (if (< 1 (length props))
16002 (completing-read "Property: " props nil t)
16003 (caar props))))
16004 (list prop)))
16005 (if (not property)
16006 (message "No property to delete in this entry")
16007 (org-entry-delete nil property)
16008 (message "Property \"%s\" deleted" property)))
16010 (defun org-delete-property-globally (property)
16011 "Remove PROPERTY globally, from all entries.
16012 This function ignores narrowing, if any."
16013 (interactive
16014 (let* ((completion-ignore-case t)
16015 (prop (completing-read
16016 "Globally remove property: "
16017 (mapcar #'list (org-buffer-property-keys)))))
16018 (list prop)))
16019 (org-with-wide-buffer
16020 (goto-char (point-min))
16021 (let ((count 0)
16022 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16023 (while (re-search-forward re nil t)
16024 (when (org-entry-delete (point) property) (cl-incf count)))
16025 (message "Property \"%s\" removed from %d entries" property count))))
16027 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16029 (defun org-compute-property-at-point ()
16030 "Compute the property at point.
16031 This looks for an enclosing column format, extracts the operator and
16032 then applies it to the property in the column format's scope."
16033 (interactive)
16034 (unless (org-at-property-p)
16035 (user-error "Not at a property"))
16036 (let ((prop (match-string-no-properties 2)))
16037 (org-columns-get-format-and-top-level)
16038 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16039 (user-error "No operator defined for property %s" prop))
16040 (org-columns-compute prop)))
16042 (defvar org-property-allowed-value-functions nil
16043 "Hook for functions supplying allowed values for a specific property.
16044 The functions must take a single argument, the name of the property, and
16045 return a flat list of allowed values. If \":ETC\" is one of
16046 the values, this means that these values are intended as defaults for
16047 completion, but that other values should be allowed too.
16048 The functions must return nil if they are not responsible for this
16049 property.")
16051 (defun org-property-get-allowed-values (pom property &optional table)
16052 "Get allowed values for the property PROPERTY.
16053 When TABLE is non-nil, return an alist that can directly be used for
16054 completion."
16055 (let (vals)
16056 (cond
16057 ((equal property "TODO")
16058 (setq vals (org-with-point-at pom
16059 (append org-todo-keywords-1 '("")))))
16060 ((equal property "PRIORITY")
16061 (let ((n org-lowest-priority))
16062 (while (>= n org-highest-priority)
16063 (push (char-to-string n) vals)
16064 (setq n (1- n)))))
16065 ((equal property "CATEGORY"))
16066 ((member property org-special-properties))
16067 ((setq vals (run-hook-with-args-until-success
16068 'org-property-allowed-value-functions property)))
16070 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16071 (when (and vals (string-match "\\S-" vals))
16072 (setq vals (car (read-from-string (concat "(" vals ")"))))
16073 (setq vals (mapcar (lambda (x)
16074 (cond ((stringp x) x)
16075 ((numberp x) (number-to-string x))
16076 ((symbolp x) (symbol-name x))
16077 (t "???")))
16078 vals)))))
16079 (when (member ":ETC" vals)
16080 (setq vals (remove ":ETC" vals))
16081 (org-add-props (car vals) '(org-unrestricted t)))
16082 (if table (mapcar 'list vals) vals)))
16084 (defun org-property-previous-allowed-value (&optional _previous)
16085 "Switch to the next allowed value for this property."
16086 (interactive)
16087 (org-property-next-allowed-value t))
16089 (defun org-property-next-allowed-value (&optional previous)
16090 "Switch to the next allowed value for this property."
16091 (interactive)
16092 (unless (org-at-property-p)
16093 (user-error "Not at a property"))
16094 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16095 (key (match-string 2))
16096 (value (match-string 3))
16097 (allowed (or (org-property-get-allowed-values (point) key)
16098 (and (member value '("[ ]" "[-]" "[X]"))
16099 '("[ ]" "[X]"))))
16100 (heading (save-match-data (nth 4 (org-heading-components))))
16101 nval)
16102 (unless allowed
16103 (user-error "Allowed values for this property have not been defined"))
16104 (when previous (setq allowed (reverse allowed)))
16105 (when (member value allowed)
16106 (setq nval (car (cdr (member value allowed)))))
16107 (setq nval (or nval (car allowed)))
16108 (when (equal nval value)
16109 (user-error "Only one allowed value for this property"))
16110 (org-at-property-p)
16111 (replace-match (concat " :" key ": " nval) t t)
16112 (org-indent-line)
16113 (beginning-of-line 1)
16114 (skip-chars-forward " \t")
16115 (when (equal prop org-effort-property)
16116 (org-refresh-property
16117 '((effort . identity)
16118 (effort-minutes . org-duration-to-minutes))
16119 nval)
16120 (when (string= org-clock-current-task heading)
16121 (setq org-clock-effort nval)
16122 (org-clock-update-mode-line)))
16123 (run-hook-with-args 'org-property-changed-functions key nval)))
16125 (defun org-find-olp (path &optional this-buffer)
16126 "Return a marker pointing to the entry at outline path OLP.
16127 If anything goes wrong, throw an error.
16128 You can wrap this call to catch the error like this:
16130 (condition-case msg
16131 (org-mobile-locate-entry (match-string 4))
16132 (error (nth 1 msg)))
16134 The return value will then be either a string with the error message,
16135 or a marker if everything is OK.
16137 If THIS-BUFFER is set, the outline path does not contain a file,
16138 only headings."
16139 (let* ((file (if this-buffer buffer-file-name (pop path)))
16140 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16141 (level 1)
16142 (lmin 1)
16143 (lmax 1)
16144 end found flevel)
16145 (unless buffer (error "File not found :%s" file))
16146 (with-current-buffer buffer
16147 (unless (derived-mode-p 'org-mode)
16148 (error "Buffer %s needs to be in Org mode" buffer))
16149 (org-with-wide-buffer
16150 (goto-char (point-min))
16151 (dolist (heading path)
16152 (let ((re (format org-complex-heading-regexp-format
16153 (regexp-quote heading)))
16154 (cnt 0))
16155 (while (re-search-forward re end t)
16156 (setq level (- (match-end 1) (match-beginning 1)))
16157 (when (and (>= level lmin) (<= level lmax))
16158 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16159 (when (= cnt 0)
16160 (error "Heading not found on level %d: %s" lmax heading))
16161 (when (> cnt 1)
16162 (error "Heading not unique on level %d: %s" lmax heading))
16163 (goto-char found)
16164 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16165 (setq end (save-excursion (org-end-of-subtree t t)))))
16166 (when (org-at-heading-p)
16167 (point-marker))))))
16169 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16170 "Find node HEADING in BUFFER.
16171 Return a marker to the heading if it was found, or nil if not.
16172 If POS-ONLY is set, return just the position instead of a marker.
16174 The heading text must match exact, but it may have a TODO keyword,
16175 a priority cookie and tags in the standard locations."
16176 (with-current-buffer (or buffer (current-buffer))
16177 (org-with-wide-buffer
16178 (goto-char (point-min))
16179 (let (case-fold-search)
16180 (when (re-search-forward
16181 (format org-complex-heading-regexp-format
16182 (regexp-quote heading)) nil t)
16183 (if pos-only
16184 (match-beginning 0)
16185 (move-marker (make-marker) (match-beginning 0))))))))
16187 (defun org-find-exact-heading-in-directory (heading &optional dir)
16188 "Find Org node headline HEADING in all .org files in directory DIR.
16189 When the target headline is found, return a marker to this location."
16190 (let ((files (directory-files (or dir default-directory)
16191 t "\\`[^.#].*\\.org\\'"))
16192 visiting m buffer)
16193 (catch 'found
16194 (dolist (file files)
16195 (message "trying %s" file)
16196 (setq visiting (org-find-base-buffer-visiting file))
16197 (setq buffer (or visiting (find-file-noselect file)))
16198 (setq m (org-find-exact-headline-in-buffer
16199 heading buffer))
16200 (when (and (not m) (not visiting)) (kill-buffer buffer))
16201 (and m (throw 'found m))))))
16203 (defun org-find-entry-with-id (ident)
16204 "Locate the entry that contains the ID property with exact value IDENT.
16205 IDENT can be a string, a symbol or a number, this function will search for
16206 the string representation of it.
16207 Return the position where this entry starts, or nil if there is no such entry."
16208 (interactive "sID: ")
16209 (let ((id (cond
16210 ((stringp ident) ident)
16211 ((symbolp ident) (symbol-name ident))
16212 ((numberp ident) (number-to-string ident))
16213 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16214 (org-with-wide-buffer (org-find-property "ID" id))))
16216 ;;;; Timestamps
16218 (defvar org-last-changed-timestamp nil)
16219 (defvar org-last-inserted-timestamp nil
16220 "The last time stamp inserted with `org-insert-time-stamp'.")
16222 (defun org-time-stamp (arg &optional inactive)
16223 "Prompt for a date/time and insert a time stamp.
16225 If the user specifies a time like HH:MM or if this command is
16226 called with at least one prefix argument, the time stamp contains
16227 the date and the time. Otherwise, only the date is included.
16229 All parts of a date not specified by the user are filled in from
16230 the timestamp at point, if any, or the current date/time
16231 otherwise.
16233 If there is already a timestamp at the cursor, it is replaced.
16235 With two universal prefix arguments, insert an active timestamp
16236 with the current time without prompting the user.
16238 When called from lisp, the timestamp is inactive if INACTIVE is
16239 non-nil."
16240 (interactive "P")
16241 (let* ((ts (cond
16242 ((org-at-date-range-p t)
16243 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16244 ((org-at-timestamp-p 'lax) (match-string 0))))
16245 ;; Default time is either the timestamp at point or today.
16246 ;; When entering a range, only the range start is considered.
16247 (default-time (if (not ts) (current-time)
16248 (apply #'encode-time (org-parse-time-string ts))))
16249 (default-input (and ts (org-get-compact-tod ts)))
16250 (repeater (and ts
16251 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16252 (match-string 0 ts)))
16253 org-time-was-given
16254 org-end-time-was-given
16255 (time
16256 (and (if (equal arg '(16)) (current-time)
16257 ;; Preserve `this-command' and `last-command'.
16258 (let ((this-command this-command)
16259 (last-command last-command))
16260 (org-read-date
16261 arg 'totime nil nil default-time default-input
16262 inactive))))))
16263 (cond
16264 ((and ts
16265 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16266 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16267 (insert "--")
16268 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16270 ;; Make sure we're on a timestamp. When in the middle of a date
16271 ;; range, move arbitrarily to range end.
16272 (unless (org-at-timestamp-p 'lax)
16273 (skip-chars-forward "-")
16274 (org-at-timestamp-p 'lax))
16275 (replace-match "")
16276 (setq org-last-changed-timestamp
16277 (org-insert-time-stamp
16278 time (or org-time-was-given arg)
16279 inactive nil nil (list org-end-time-was-given)))
16280 (when repeater
16281 (backward-char)
16282 (insert " " repeater)
16283 (setq org-last-changed-timestamp
16284 (concat (substring org-last-inserted-timestamp 0 -1)
16285 " " repeater ">")))
16286 (message "Timestamp updated"))
16287 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16288 (t (org-insert-time-stamp
16289 time (or org-time-was-given arg) inactive nil nil
16290 (list org-end-time-was-given))))))
16292 ;; FIXME: can we use this for something else, like computing time differences?
16293 (defun org-get-compact-tod (s)
16294 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16295 (let* ((t1 (match-string 1 s))
16296 (h1 (string-to-number (match-string 2 s)))
16297 (m1 (string-to-number (match-string 3 s)))
16298 (t2 (and (match-end 4) (match-string 5 s)))
16299 (h2 (and t2 (string-to-number (match-string 6 s))))
16300 (m2 (and t2 (string-to-number (match-string 7 s))))
16301 dh dm)
16302 (if (not t2)
16304 (setq dh (- h2 h1) dm (- m2 m1))
16305 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16306 (concat t1 "+" (number-to-string dh)
16307 (and (/= 0 dm) (format ":%02d" dm)))))))
16309 (defun org-time-stamp-inactive (&optional arg)
16310 "Insert an inactive time stamp.
16311 An inactive time stamp is enclosed in square brackets instead of angle
16312 brackets. It is inactive in the sense that it does not trigger agenda entries,
16313 does not link to the calendar and cannot be changed with the S-cursor keys.
16314 So these are more for recording a certain time/date."
16315 (interactive "P")
16316 (org-time-stamp arg 'inactive))
16318 (defvar org-date-ovl (make-overlay 1 1))
16319 (overlay-put org-date-ovl 'face 'org-date-selected)
16320 (delete-overlay org-date-ovl)
16322 (defvar org-ans1) ; dynamically scoped parameter
16323 (defvar org-ans2) ; dynamically scoped parameter
16325 (defvar org-plain-time-of-day-regexp) ; defined below
16327 (defvar org-overriding-default-time nil) ; dynamically scoped
16328 (defvar org-read-date-overlay nil)
16329 (defvar org-dcst nil) ; dynamically scoped
16330 (defvar org-read-date-history nil)
16331 (defvar org-read-date-final-answer nil)
16332 (defvar org-read-date-analyze-futurep nil)
16333 (defvar org-read-date-analyze-forced-year nil)
16334 (defvar org-read-date-inactive)
16336 (defvar org-read-date-minibuffer-local-map
16337 (let* ((map (make-sparse-keymap)))
16338 (set-keymap-parent map minibuffer-local-map)
16339 (org-defkey map (kbd ".")
16340 (lambda () (interactive)
16341 ;; Are we at the beginning of the prompt?
16342 (if (looking-back "^[^:]+: "
16343 (let ((inhibit-field-text-motion t))
16344 (line-beginning-position)))
16345 (org-eval-in-calendar '(calendar-goto-today))
16346 (insert "."))))
16347 (org-defkey map (kbd "C-.")
16348 (lambda () (interactive)
16349 (org-eval-in-calendar '(calendar-goto-today))))
16350 (org-defkey map [(meta shift left)]
16351 (lambda () (interactive)
16352 (org-eval-in-calendar '(calendar-backward-month 1))))
16353 (org-defkey map [(meta shift right)]
16354 (lambda () (interactive)
16355 (org-eval-in-calendar '(calendar-forward-month 1))))
16356 (org-defkey map [(meta shift up)]
16357 (lambda () (interactive)
16358 (org-eval-in-calendar '(calendar-backward-year 1))))
16359 (org-defkey map [(meta shift down)]
16360 (lambda () (interactive)
16361 (org-eval-in-calendar '(calendar-forward-year 1))))
16362 (org-defkey map [?\e (shift left)]
16363 (lambda () (interactive)
16364 (org-eval-in-calendar '(calendar-backward-month 1))))
16365 (org-defkey map [?\e (shift right)]
16366 (lambda () (interactive)
16367 (org-eval-in-calendar '(calendar-forward-month 1))))
16368 (org-defkey map [?\e (shift up)]
16369 (lambda () (interactive)
16370 (org-eval-in-calendar '(calendar-backward-year 1))))
16371 (org-defkey map [?\e (shift down)]
16372 (lambda () (interactive)
16373 (org-eval-in-calendar '(calendar-forward-year 1))))
16374 (org-defkey map [(shift up)]
16375 (lambda () (interactive)
16376 (org-eval-in-calendar '(calendar-backward-week 1))))
16377 (org-defkey map [(shift down)]
16378 (lambda () (interactive)
16379 (org-eval-in-calendar '(calendar-forward-week 1))))
16380 (org-defkey map [(shift left)]
16381 (lambda () (interactive)
16382 (org-eval-in-calendar '(calendar-backward-day 1))))
16383 (org-defkey map [(shift right)]
16384 (lambda () (interactive)
16385 (org-eval-in-calendar '(calendar-forward-day 1))))
16386 (org-defkey map "!"
16387 (lambda () (interactive)
16388 (org-eval-in-calendar '(diary-view-entries))
16389 (message "")))
16390 (org-defkey map ">"
16391 (lambda () (interactive)
16392 (org-eval-in-calendar '(calendar-scroll-left 1))))
16393 (org-defkey map "<"
16394 (lambda () (interactive)
16395 (org-eval-in-calendar '(calendar-scroll-right 1))))
16396 (org-defkey map "\C-v"
16397 (lambda () (interactive)
16398 (org-eval-in-calendar
16399 '(calendar-scroll-left-three-months 1))))
16400 (org-defkey map "\M-v"
16401 (lambda () (interactive)
16402 (org-eval-in-calendar
16403 '(calendar-scroll-right-three-months 1))))
16404 map)
16405 "Keymap for minibuffer commands when using `org-read-date'.")
16407 (defvar org-def)
16408 (defvar org-defdecode)
16409 (defvar org-with-time)
16411 (defvar calendar-setup) ; Dynamically scoped.
16412 (defun org-read-date (&optional with-time to-time from-string prompt
16413 default-time default-input inactive)
16414 "Read a date, possibly a time, and make things smooth for the user.
16415 The prompt will suggest to enter an ISO date, but you can also enter anything
16416 which will at least partially be understood by `parse-time-string'.
16417 Unrecognized parts of the date will default to the current day, month, year,
16418 hour and minute. If this command is called to replace a timestamp at point,
16419 or to enter the second timestamp of a range, the default time is taken
16420 from the existing stamp. Furthermore, the command prefers the future,
16421 so if you are giving a date where the year is not given, and the day-month
16422 combination is already past in the current year, it will assume you
16423 mean next year. For details, see the manual. A few examples:
16425 3-2-5 --> 2003-02-05
16426 feb 15 --> currentyear-02-15
16427 2/15 --> currentyear-02-15
16428 sep 12 9 --> 2009-09-12
16429 12:45 --> today 12:45
16430 22 sept 0:34 --> currentyear-09-22 0:34
16431 12 --> currentyear-currentmonth-12
16432 Fri --> nearest Friday after today
16433 -Tue --> last Tuesday
16434 etc.
16436 Furthermore you can specify a relative date by giving, as the *first* thing
16437 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16438 change in days weeks, months, years.
16439 With a single plus or minus, the date is relative to today. With a double
16440 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16441 +4d --> four days from today
16442 +4 --> same as above
16443 +2w --> two weeks from today
16444 ++5 --> five days from default date
16446 The function understands only English month and weekday abbreviations.
16448 While prompting, a calendar is popped up - you can also select the
16449 date with the mouse (button 1). The calendar shows a period of three
16450 months. To scroll it to other months, use the keys `>' and `<'.
16451 If you don't like the calendar, turn it off with
16452 (setq org-read-date-popup-calendar nil)
16454 With optional argument TO-TIME, the date will immediately be converted
16455 to an internal time.
16456 With an optional argument WITH-TIME, the prompt will suggest to
16457 also insert a time. Note that when WITH-TIME is not set, you can
16458 still enter a time, and this function will inform the calling routine
16459 about this change. The calling routine may then choose to change the
16460 format used to insert the time stamp into the buffer to include the time.
16461 With optional argument FROM-STRING, read from this string instead from
16462 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16463 the time/date that is used for everything that is not specified by the
16464 user."
16465 (require 'parse-time)
16466 (let* ((org-with-time with-time)
16467 (org-time-stamp-rounding-minutes
16468 (if (equal org-with-time '(16))
16469 '(0 0)
16470 org-time-stamp-rounding-minutes))
16471 (org-dcst org-display-custom-times)
16472 (ct (org-current-time))
16473 (org-def (or org-overriding-default-time default-time ct))
16474 (org-defdecode (decode-time org-def))
16475 (cur-frame (selected-frame))
16476 (mouse-autoselect-window nil) ; Don't let the mouse jump
16477 (calendar-setup
16478 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16479 (calendar-move-hook nil)
16480 (calendar-view-diary-initially-flag nil)
16481 (calendar-view-holidays-initially-flag nil)
16482 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16483 ;; Rationalize `org-def' and `org-defdecode', if required.
16484 (when (< (nth 2 org-defdecode) org-extend-today-until)
16485 (setf (nth 2 org-defdecode) -1)
16486 (setf (nth 1 org-defdecode) 59)
16487 (setq org-def (apply #'encode-time org-defdecode))
16488 (setq org-defdecode (decode-time org-def)))
16489 (let* ((timestr (format-time-string
16490 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16491 org-def))
16492 (prompt (concat (if prompt (concat prompt " ") "")
16493 (format "Date+time [%s]: " timestr))))
16494 (cond
16495 (from-string (setq ans from-string))
16496 (org-read-date-popup-calendar
16497 (save-excursion
16498 (save-window-excursion
16499 (calendar)
16500 (when (eq calendar-setup 'calendar-only)
16501 (setq cal-frame
16502 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16503 (select-frame cal-frame))
16504 (org-eval-in-calendar '(setq cursor-type nil) t)
16505 (unwind-protect
16506 (progn
16507 (calendar-forward-day (- (time-to-days org-def)
16508 (calendar-absolute-from-gregorian
16509 (calendar-current-date))))
16510 (org-eval-in-calendar nil t)
16511 (let* ((old-map (current-local-map))
16512 (map (copy-keymap calendar-mode-map))
16513 (minibuffer-local-map
16514 (copy-keymap org-read-date-minibuffer-local-map)))
16515 (org-defkey map (kbd "RET") 'org-calendar-select)
16516 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16517 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16518 (unwind-protect
16519 (progn
16520 (use-local-map map)
16521 (setq org-read-date-inactive inactive)
16522 (add-hook 'post-command-hook 'org-read-date-display)
16523 (setq org-ans0
16524 (read-string prompt
16525 default-input
16526 'org-read-date-history
16527 nil))
16528 ;; org-ans0: from prompt
16529 ;; org-ans1: from mouse click
16530 ;; org-ans2: from calendar motion
16531 (setq ans
16532 (concat org-ans0 " " (or org-ans1 org-ans2))))
16533 (remove-hook 'post-command-hook 'org-read-date-display)
16534 (use-local-map old-map)
16535 (when org-read-date-overlay
16536 (delete-overlay org-read-date-overlay)
16537 (setq org-read-date-overlay nil)))))
16538 (bury-buffer "*Calendar*")
16539 (when cal-frame
16540 (delete-frame cal-frame)
16541 (select-frame-set-input-focus cur-frame))))))
16543 (t ; Naked prompt only
16544 (unwind-protect
16545 (setq ans (read-string prompt default-input
16546 'org-read-date-history timestr))
16547 (when org-read-date-overlay
16548 (delete-overlay org-read-date-overlay)
16549 (setq org-read-date-overlay nil))))))
16551 (setq final (org-read-date-analyze ans org-def org-defdecode))
16553 (when org-read-date-analyze-forced-year
16554 (message "Year was forced into %s"
16555 (if org-read-date-force-compatible-dates
16556 "compatible range (1970-2037)"
16557 "range representable on this machine"))
16558 (ding))
16560 ;; One round trip to get rid of 34th of August and stuff like that....
16561 (setq final (decode-time (apply 'encode-time final)))
16563 (setq org-read-date-final-answer ans)
16565 (if to-time
16566 (apply 'encode-time final)
16567 (if (and (boundp 'org-time-was-given) org-time-was-given)
16568 (format "%04d-%02d-%02d %02d:%02d"
16569 (nth 5 final) (nth 4 final) (nth 3 final)
16570 (nth 2 final) (nth 1 final))
16571 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16573 (defun org-read-date-display ()
16574 "Display the current date prompt interpretation in the minibuffer."
16575 (when org-read-date-display-live
16576 (when org-read-date-overlay
16577 (delete-overlay org-read-date-overlay))
16578 (when (minibufferp (current-buffer))
16579 (save-excursion
16580 (end-of-line 1)
16581 (while (not (equal (buffer-substring
16582 (max (point-min) (- (point) 4)) (point))
16583 " "))
16584 (insert " ")))
16585 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16586 " " (or org-ans1 org-ans2)))
16587 (org-end-time-was-given nil)
16588 (f (org-read-date-analyze ans org-def org-defdecode))
16589 (fmts (if org-dcst
16590 org-time-stamp-custom-formats
16591 org-time-stamp-formats))
16592 (fmt (if (or org-with-time
16593 (and (boundp 'org-time-was-given) org-time-was-given))
16594 (cdr fmts)
16595 (car fmts)))
16596 (txt (format-time-string fmt (apply 'encode-time f)))
16597 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16598 (txt (concat "=> " txt)))
16599 (when (and org-end-time-was-given
16600 (string-match org-plain-time-of-day-regexp txt))
16601 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16602 org-end-time-was-given
16603 (substring txt (match-end 0)))))
16604 (when org-read-date-analyze-futurep
16605 (setq txt (concat txt " (=>F)")))
16606 (setq org-read-date-overlay
16607 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16608 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16610 (defun org-read-date-analyze (ans def defdecode)
16611 "Analyze the combined answer of the date prompt."
16612 ;; FIXME: cleanup and comment
16613 ;; Pass `current-time' result to `decode-time' (instead of calling
16614 ;; without arguments) so that only `current-time' has to be
16615 ;; overridden in tests.
16616 (let ((org-def def)
16617 (org-defdecode defdecode)
16618 (nowdecode (decode-time (current-time)))
16619 delta deltan deltaw deltadef year month day
16620 hour minute second wday pm h2 m2 tl wday1
16621 iso-year iso-weekday iso-week iso-date futurep kill-year)
16622 (setq org-read-date-analyze-futurep nil
16623 org-read-date-analyze-forced-year nil)
16624 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16625 (setq ans "+0"))
16627 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16628 (setq ans (replace-match "" t t ans)
16629 deltan (car delta)
16630 deltaw (nth 1 delta)
16631 deltadef (nth 2 delta)))
16633 ;; Check if there is an iso week date in there. If yes, store the
16634 ;; info and postpone interpreting it until the rest of the parsing
16635 ;; is done.
16636 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16637 (setq iso-year (when (match-end 1)
16638 (org-small-year-to-year
16639 (string-to-number (match-string 1 ans))))
16640 iso-weekday (when (match-end 3)
16641 (string-to-number (match-string 3 ans)))
16642 iso-week (string-to-number (match-string 2 ans)))
16643 (setq ans (replace-match "" t t ans)))
16645 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16646 (when (string-match
16647 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16648 (setq year (if (match-end 2)
16649 (string-to-number (match-string 2 ans))
16650 (progn (setq kill-year t)
16651 (string-to-number (format-time-string "%Y"))))
16652 month (string-to-number (match-string 3 ans))
16653 day (string-to-number (match-string 4 ans)))
16654 (setq year (org-small-year-to-year year))
16655 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16656 t nil ans)))
16658 ;; Help matching dotted european dates
16659 (when (string-match
16660 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16661 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16662 (setq kill-year t)
16663 (string-to-number (format-time-string "%Y")))
16664 day (string-to-number (match-string 1 ans))
16665 month (string-to-number (match-string 2 ans))
16666 ans (replace-match (format "%04d-%02d-%02d" year month day)
16667 t nil ans)))
16669 ;; Help matching american dates, like 5/30 or 5/30/7
16670 (when (string-match
16671 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16672 (setq year (if (match-end 4)
16673 (string-to-number (match-string 4 ans))
16674 (progn (setq kill-year t)
16675 (string-to-number (format-time-string "%Y"))))
16676 month (string-to-number (match-string 1 ans))
16677 day (string-to-number (match-string 2 ans)))
16678 (setq year (org-small-year-to-year year))
16679 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16680 t nil ans)))
16681 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16682 ;; If there is a time with am/pm, and *no* time without it, we convert
16683 ;; so that matching will be successful.
16684 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16685 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16686 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16687 (setq hour (string-to-number (match-string 1 ans))
16688 minute (if (match-end 3)
16689 (string-to-number (match-string 3 ans))
16691 pm (equal ?p
16692 (string-to-char (downcase (match-string 4 ans)))))
16693 (if (and (= hour 12) (not pm))
16694 (setq hour 0)
16695 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16696 (setq ans (replace-match (format "%02d:%02d" hour minute)
16697 t t ans))))
16699 ;; Check if a time range is given as a duration
16700 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16701 (setq hour (string-to-number (match-string 1 ans))
16702 h2 (+ hour (string-to-number (match-string 3 ans)))
16703 minute (string-to-number (match-string 2 ans))
16704 m2 (+ minute (if (match-end 5) (string-to-number
16705 (match-string 5 ans))0)))
16706 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16707 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16708 t t ans)))
16710 ;; Check if there is a time range
16711 (when (boundp 'org-end-time-was-given)
16712 (setq org-time-was-given nil)
16713 (when (and (string-match org-plain-time-of-day-regexp ans)
16714 (match-end 8))
16715 (setq org-end-time-was-given (match-string 8 ans))
16716 (setq ans (concat (substring ans 0 (match-beginning 7))
16717 (substring ans (match-end 7))))))
16719 (setq tl (parse-time-string ans)
16720 day (or (nth 3 tl) (nth 3 org-defdecode))
16721 month
16722 (cond ((nth 4 tl))
16723 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16724 ;; Day was specified. Make sure DAY+MONTH
16725 ;; combination happens in the future.
16726 ((nth 3 tl)
16727 (setq futurep t)
16728 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16729 (nth 4 nowdecode)))
16730 (t (nth 4 org-defdecode)))
16731 year
16732 (cond ((and (not kill-year) (nth 5 tl)))
16733 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16734 ;; Month was guessed in the future and is at least
16735 ;; equal to NOWDECODE's. Fix year accordingly.
16736 (futurep
16737 (if (or (> month (nth 4 nowdecode))
16738 (>= day (nth 3 nowdecode)))
16739 (nth 5 nowdecode)
16740 (1+ (nth 5 nowdecode))))
16741 ;; Month was specified. Make sure MONTH+YEAR
16742 ;; combination happens in the future.
16743 ((nth 4 tl)
16744 (setq futurep t)
16745 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16746 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16747 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16748 (t (nth 5 nowdecode))))
16749 (t (nth 5 org-defdecode)))
16750 hour (or (nth 2 tl) (nth 2 org-defdecode))
16751 minute (or (nth 1 tl) (nth 1 org-defdecode))
16752 second (or (nth 0 tl) 0)
16753 wday (nth 6 tl))
16755 (when (and (eq org-read-date-prefer-future 'time)
16756 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16757 (equal day (nth 3 nowdecode))
16758 (equal month (nth 4 nowdecode))
16759 (equal year (nth 5 nowdecode))
16760 (nth 2 tl)
16761 (or (< (nth 2 tl) (nth 2 nowdecode))
16762 (and (= (nth 2 tl) (nth 2 nowdecode))
16763 (nth 1 tl)
16764 (< (nth 1 tl) (nth 1 nowdecode)))))
16765 (setq day (1+ day)
16766 futurep t))
16768 ;; Special date definitions below
16769 (cond
16770 (iso-week
16771 ;; There was an iso week
16772 (require 'cal-iso)
16773 (setq futurep nil)
16774 (setq year (or iso-year year)
16775 day (or iso-weekday wday 1)
16776 wday nil ; to make sure that the trigger below does not match
16777 iso-date (calendar-gregorian-from-absolute
16778 (calendar-iso-to-absolute
16779 (list iso-week day year))))
16780 ; FIXME: Should we also push ISO weeks into the future?
16781 ; (when (and org-read-date-prefer-future
16782 ; (not iso-year)
16783 ; (< (calendar-absolute-from-gregorian iso-date)
16784 ; (time-to-days (current-time))))
16785 ; (setq year (1+ year)
16786 ; iso-date (calendar-gregorian-from-absolute
16787 ; (calendar-iso-to-absolute
16788 ; (list iso-week day year)))))
16789 (setq month (car iso-date)
16790 year (nth 2 iso-date)
16791 day (nth 1 iso-date)))
16792 (deltan
16793 (setq futurep nil)
16794 (unless deltadef
16795 ;; Pass `current-time' result to `decode-time' (instead of
16796 ;; calling without arguments) so that only `current-time' has
16797 ;; to be overridden in tests.
16798 (let ((now (decode-time (current-time))))
16799 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16800 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16801 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16802 ((equal deltaw "m") (setq month (+ month deltan)))
16803 ((equal deltaw "y") (setq year (+ year deltan)))))
16804 ((and wday (not (nth 3 tl)))
16805 ;; Weekday was given, but no day, so pick that day in the week
16806 ;; on or after the derived date.
16807 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16808 (unless (equal wday wday1)
16809 (setq day (+ day (% (- wday wday1 -7) 7))))))
16810 (when (and (boundp 'org-time-was-given)
16811 (nth 2 tl))
16812 (setq org-time-was-given t))
16813 (when (< year 100) (setq year (+ 2000 year)))
16814 ;; Check of the date is representable
16815 (if org-read-date-force-compatible-dates
16816 (progn
16817 (when (< year 1970)
16818 (setq year 1970 org-read-date-analyze-forced-year t))
16819 (when (> year 2037)
16820 (setq year 2037 org-read-date-analyze-forced-year t)))
16821 (condition-case nil
16822 (ignore (encode-time second minute hour day month year))
16823 (error
16824 (setq year (nth 5 org-defdecode))
16825 (setq org-read-date-analyze-forced-year t))))
16826 (setq org-read-date-analyze-futurep futurep)
16827 (list second minute hour day month year)))
16829 (defvar parse-time-weekdays)
16830 (defun org-read-date-get-relative (s today default)
16831 "Check string S for special relative date string.
16832 TODAY and DEFAULT are internal times, for today and for a default.
16833 Return shift list (N what def-flag)
16834 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16835 N is the number of WHATs to shift.
16836 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16837 the DEFAULT date rather than TODAY."
16838 (require 'parse-time)
16839 (when (and
16840 (string-match
16841 (concat
16842 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16843 "\\([0-9]+\\)?"
16844 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16845 "\\([ \t]\\|$\\)") s)
16846 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16847 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16848 (string-to-char (substring (match-string 1 s) -1))
16849 ?+))
16850 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16851 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16852 (what (if (match-end 3) (match-string 3 s) "d"))
16853 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16854 (date (if rel default today))
16855 (wday (nth 6 (decode-time date)))
16856 delta)
16857 (if wday1
16858 (progn
16859 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16860 (when (= delta 0) (setq delta 7))
16861 (when (= dir ?-)
16862 (setq delta (- delta 7))
16863 (when (= delta 0) (setq delta -7)))
16864 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16865 (list delta "d" rel))
16866 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16868 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16869 "Turn a user-specified date into the internal representation.
16870 The internal representation needed by the calendar is (month day year).
16871 This is a wrapper to handle the brain-dead convention in calendar that
16872 user function argument order change dependent on argument order."
16873 (pcase calendar-date-style
16874 (`american (list arg1 arg2 arg3))
16875 (`european (list arg2 arg1 arg3))
16876 (`iso (list arg2 arg3 arg1))))
16878 (defun org-eval-in-calendar (form &optional keepdate)
16879 "Eval FORM in the calendar window and return to current window.
16880 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16881 (let ((sf (selected-frame))
16882 (sw (selected-window)))
16883 (select-window (get-buffer-window "*Calendar*" t))
16884 (eval form)
16885 (when (and (not keepdate) (calendar-cursor-to-date))
16886 (let* ((date (calendar-cursor-to-date))
16887 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16888 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16889 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16890 (select-window sw)
16891 (select-frame-set-input-focus sf)))
16893 (defun org-calendar-select ()
16894 "Return to `org-read-date' with the date currently selected.
16895 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16896 (interactive)
16897 (when (calendar-cursor-to-date)
16898 (let* ((date (calendar-cursor-to-date))
16899 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16900 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16901 (when (active-minibuffer-window) (exit-minibuffer))))
16903 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16904 "Insert a date stamp for the date given by the internal TIME.
16905 See `format-time-string' for the format of TIME.
16906 WITH-HM means use the stamp format that includes the time of the day.
16907 INACTIVE means use square brackets instead of angular ones, so that the
16908 stamp will not contribute to the agenda.
16909 PRE and POST are optional strings to be inserted before and after the
16910 stamp.
16911 The command returns the inserted time stamp."
16912 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16913 stamp)
16914 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16915 (insert-before-markers (or pre ""))
16916 (when (listp extra)
16917 (setq extra (car extra))
16918 (if (and (stringp extra)
16919 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16920 (setq extra (format "-%02d:%02d"
16921 (string-to-number (match-string 1 extra))
16922 (string-to-number (match-string 2 extra))))
16923 (setq extra nil)))
16924 (when extra
16925 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16926 (insert-before-markers (setq stamp (format-time-string fmt time)))
16927 (insert-before-markers (or post ""))
16928 (setq org-last-inserted-timestamp stamp)))
16930 (defun org-toggle-time-stamp-overlays ()
16931 "Toggle the use of custom time stamp formats."
16932 (interactive)
16933 (setq org-display-custom-times (not org-display-custom-times))
16934 (unless org-display-custom-times
16935 (let ((p (point-min)) (bmp (buffer-modified-p)))
16936 (while (setq p (next-single-property-change p 'display))
16937 (when (and (get-text-property p 'display)
16938 (eq (get-text-property p 'face) 'org-date))
16939 (remove-text-properties
16940 p (setq p (next-single-property-change p 'display))
16941 '(display t))))
16942 (set-buffer-modified-p bmp)))
16943 (org-restart-font-lock)
16944 (setq org-table-may-need-update t)
16945 (if org-display-custom-times
16946 (message "Time stamps are overlaid with custom format")
16947 (message "Time stamp overlays removed")))
16949 (defun org-display-custom-time (beg end)
16950 "Overlay modified time stamp format over timestamp between BEG and END."
16951 (let* ((ts (buffer-substring beg end))
16952 t1 with-hm tf time str (off 0))
16953 (save-match-data
16954 (setq t1 (org-parse-time-string ts t))
16955 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16956 (setq off (- (match-end 0) (match-beginning 0)))))
16957 (setq end (- end off))
16958 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16959 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16960 time (org-fix-decoded-time t1)
16961 str (org-add-props
16962 (format-time-string
16963 (substring tf 1 -1) (apply 'encode-time time))
16964 nil 'mouse-face 'highlight))
16965 (put-text-property beg end 'display str)))
16967 (defun org-fix-decoded-time (time)
16968 "Set 0 instead of nil for the first 6 elements of time.
16969 Don't touch the rest."
16970 (let ((n 0))
16971 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16973 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16974 "Difference between TIMESTAMP-STRING and now in days.
16975 If SECONDS is non-nil, return the difference in seconds."
16976 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16977 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16978 (funcall fdiff (current-time)))))
16980 (defun org-deadline-close-p (timestamp-string &optional ndays)
16981 "Is the time in TIMESTAMP-STRING close to the current date?"
16982 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16983 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16984 (not (org-entry-is-done-p))))
16986 (defun org-get-wdays (ts &optional delay zero-delay)
16987 "Get the deadline lead time appropriate for timestring TS.
16988 When DELAY is non-nil, get the delay time for scheduled items
16989 instead of the deadline lead time. When ZERO-DELAY is non-nil
16990 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16991 don't try to find the delay cookie in the scheduled timestamp."
16992 (let ((tv (if delay org-scheduled-delay-days
16993 org-deadline-warning-days)))
16994 (cond
16995 ((or (and delay (< tv 0))
16996 (and delay zero-delay (<= tv 0))
16997 (and (not delay) (<= tv 0)))
16998 ;; Enforce this value no matter what
16999 (- tv))
17000 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17001 ;; lead time is specified.
17002 (floor (* (string-to-number (match-string 1 ts))
17003 (cdr (assoc (match-string 2 ts)
17004 '(("d" . 1) ("w" . 7)
17005 ("m" . 30.4) ("y" . 365.25)
17006 ("h" . 0.041667)))))))
17007 ;; go for the default.
17008 (t tv))))
17010 (defun org-calendar-select-mouse (ev)
17011 "Return to `org-read-date' with the date currently selected.
17012 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17013 (interactive "e")
17014 (mouse-set-point ev)
17015 (when (calendar-cursor-to-date)
17016 (let* ((date (calendar-cursor-to-date))
17017 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17018 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17019 (when (active-minibuffer-window) (exit-minibuffer))))
17021 (defun org-check-deadlines (ndays)
17022 "Check if there are any deadlines due or past due.
17023 A deadline is considered due if it happens within `org-deadline-warning-days'
17024 days from today's date. If the deadline appears in an entry marked DONE,
17025 it is not shown. A numeric prefix argument NDAYS can be used to test that
17026 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17027 are shown."
17028 (interactive "P")
17029 (let* ((org-warn-days
17030 (cond
17031 ((equal ndays '(4)) 100000)
17032 (ndays (prefix-numeric-value ndays))
17033 (t (abs org-deadline-warning-days))))
17034 (case-fold-search nil)
17035 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17036 (callback
17037 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17038 (message "%d deadlines past-due or due within %d days"
17039 (org-occur regexp nil callback)
17040 org-warn-days)))
17042 (defsubst org-re-timestamp (type)
17043 "Return a regexp for timestamp TYPE.
17044 Allowed values for TYPE are:
17046 all: all timestamps
17047 active: only active timestamps (<...>)
17048 inactive: only inactive timestamps ([...])
17049 scheduled: only scheduled timestamps
17050 deadline: only deadline timestamps
17051 closed: only closed time-stamps
17053 When TYPE is nil, fall back on returning a regexp that matches
17054 both scheduled and deadline timestamps."
17055 (cl-case type
17056 (all org-ts-regexp-both)
17057 (active org-ts-regexp)
17058 (inactive org-ts-regexp-inactive)
17059 (scheduled org-scheduled-time-regexp)
17060 (deadline org-deadline-time-regexp)
17061 (closed org-closed-time-regexp)
17062 (otherwise
17063 (concat "\\<"
17064 (regexp-opt (list org-deadline-string org-scheduled-string))
17065 " *<\\([^>]+\\)>"))))
17067 (defun org-check-before-date (d)
17068 "Check if there are deadlines or scheduled entries before date D."
17069 (interactive (list (org-read-date)))
17070 (let* ((case-fold-search nil)
17071 (regexp (org-re-timestamp org-ts-type))
17072 (ts-type org-ts-type)
17073 (callback
17074 (lambda ()
17075 (let ((match (match-string 1)))
17076 (and (if (memq ts-type '(active inactive all))
17077 (eq (org-element-type (save-excursion
17078 (backward-char)
17079 (org-element-context)))
17080 'timestamp)
17081 (org-at-planning-p))
17082 (time-less-p
17083 (org-time-string-to-time match t)
17084 (org-time-string-to-time d t)))))))
17085 (message "%d entries before %s"
17086 (org-occur regexp nil callback)
17087 d)))
17089 (defun org-check-after-date (d)
17090 "Check if there are deadlines or scheduled entries after date D."
17091 (interactive (list (org-read-date)))
17092 (let* ((case-fold-search nil)
17093 (regexp (org-re-timestamp org-ts-type))
17094 (ts-type org-ts-type)
17095 (callback
17096 (lambda ()
17097 (let ((match (match-string 1)))
17098 (and (if (memq ts-type '(active inactive all))
17099 (eq (org-element-type (save-excursion
17100 (backward-char)
17101 (org-element-context)))
17102 'timestamp)
17103 (org-at-planning-p))
17104 (not (time-less-p
17105 (org-time-string-to-time match t)
17106 (org-time-string-to-time d t))))))))
17107 (message "%d entries after %s"
17108 (org-occur regexp nil callback)
17109 d)))
17111 (defun org-check-dates-range (start-date end-date)
17112 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17113 (interactive (list (org-read-date nil nil nil "Range starts")
17114 (org-read-date nil nil nil "Range end")))
17115 (let ((case-fold-search nil)
17116 (regexp (org-re-timestamp org-ts-type))
17117 (callback
17118 (let ((type org-ts-type))
17119 (lambda ()
17120 (let ((match (match-string 1)))
17121 (and
17122 (if (memq type '(active inactive all))
17123 (eq (org-element-type (save-excursion
17124 (backward-char)
17125 (org-element-context)))
17126 'timestamp)
17127 (org-at-planning-p))
17128 (not (time-less-p
17129 (org-time-string-to-time match t)
17130 (org-time-string-to-time start-date t)))
17131 (time-less-p
17132 (org-time-string-to-time match t)
17133 (org-time-string-to-time end-date t))))))))
17134 (message "%d entries between %s and %s"
17135 (org-occur regexp nil callback) start-date end-date)))
17137 (defun org-evaluate-time-range (&optional to-buffer)
17138 "Evaluate a time range by computing the difference between start and end.
17139 Normally the result is just printed in the echo area, but with prefix arg
17140 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17141 If the time range is actually in a table, the result is inserted into the
17142 next column.
17143 For time difference computation, a year is assumed to be exactly 365
17144 days in order to avoid rounding problems."
17145 (interactive "P")
17147 (org-clock-update-time-maybe)
17148 (save-excursion
17149 (unless (org-at-date-range-p t)
17150 (goto-char (point-at-bol))
17151 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17152 (unless (org-at-date-range-p t)
17153 (user-error "Not at a time-stamp range, and none found in current line")))
17154 (let* ((ts1 (match-string 1))
17155 (ts2 (match-string 2))
17156 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17157 (match-end (match-end 0))
17158 (time1 (org-time-string-to-time ts1))
17159 (time2 (org-time-string-to-time ts2))
17160 (t1 (float-time time1))
17161 (t2 (float-time time2))
17162 (diff (abs (- t2 t1)))
17163 (negative (< (- t2 t1) 0))
17164 ;; (ys (floor (* 365 24 60 60)))
17165 (ds (* 24 60 60))
17166 (hs (* 60 60))
17167 (fy "%dy %dd %02d:%02d")
17168 (fy1 "%dy %dd")
17169 (fd "%dd %02d:%02d")
17170 (fd1 "%dd")
17171 (fh "%02d:%02d")
17172 y d h m align)
17173 (if havetime
17174 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17176 d (floor (/ diff ds)) diff (mod diff ds)
17177 h (floor (/ diff hs)) diff (mod diff hs)
17178 m (floor (/ diff 60)))
17179 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17181 d (floor (+ (/ diff ds) 0.5))
17182 h 0 m 0))
17183 (if (not to-buffer)
17184 (message "%s" (org-make-tdiff-string y d h m))
17185 (if (org-at-table-p)
17186 (progn
17187 (goto-char match-end)
17188 (setq align t)
17189 (and (looking-at " *|") (goto-char (match-end 0))))
17190 (goto-char match-end))
17191 (when (looking-at
17192 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17193 (replace-match ""))
17194 (when negative (insert " -"))
17195 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17196 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17197 (insert " " (format fh h m))))
17198 (when align (org-table-align))
17199 (message "Time difference inserted")))))
17201 (defun org-make-tdiff-string (y d h m)
17202 (let ((fmt "")
17203 (l nil))
17204 (when (> y 0)
17205 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17206 (push y l))
17207 (when (> d 0)
17208 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17209 (push d l))
17210 (when (> h 0)
17211 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17212 (push h l))
17213 (when (> m 0)
17214 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17215 (push m l))
17216 (apply 'format fmt (nreverse l))))
17218 (defun org-time-string-to-time (s &optional zone)
17219 "Convert timestamp string S into internal time.
17220 The optional ZONE is omitted or nil for Emacs local time, t for
17221 Universal Time, ‘wall’ for system wall clock time, or a string as
17222 in the TZ environment variable."
17223 (apply #'encode-time (org-parse-time-string s nil zone)))
17225 (defun org-time-string-to-seconds (s &optional zone)
17226 "Convert a timestamp string S into a number of seconds.
17227 The optional ZONE is omitted or nil for Emacs local time, t for
17228 Universal Time, ‘wall’ for system wall clock time, or a string as
17229 in the TZ environment variable."
17230 (float-time (org-time-string-to-time s zone)))
17232 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17234 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17235 "Convert time stamp S to an absolute day number.
17237 If DAYNR in non-nil, and there is a specifier for a cyclic time
17238 stamp, get the closest date to DAYNR. If PREFER is
17239 `past' (respectively `future') return a date past (respectively
17240 after) or equal to DAYNR.
17242 POS is the location of time stamp S, as a buffer position in
17243 BUFFER.
17245 Diary sexp timestamps are matched against DAYNR, when non-nil.
17246 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17247 signaled."
17248 (cond
17249 ((string-match "\\`%%\\((.*)\\)" s)
17250 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17251 ;; only able to match individual dates. If it fails, raise an
17252 ;; error.
17253 (if (and daynr
17254 (org-diary-sexp-entry
17255 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17256 daynr
17257 (signal 'org-diary-sexp-no-match (list s))))
17258 (daynr (org-closest-date s daynr prefer))
17259 (t (time-to-days
17260 (condition-case errdata
17261 (apply #'encode-time (org-parse-time-string s))
17262 (error (error "Bad timestamp `%s'%s\nError was: %s"
17264 (if (not (and buffer pos)) ""
17265 (format-message " at %d in buffer `%s'" pos buffer))
17266 (cdr errdata))))))))
17268 (defun org-days-to-iso-week (days)
17269 "Return the iso week number."
17270 (require 'cal-iso)
17271 (car (calendar-iso-from-absolute days)))
17273 (defun org-small-year-to-year (year)
17274 "Convert 2-digit years into 4-digit years.
17275 YEAR is expanded into one of the 30 next years, if possible, or
17276 into a past one. Any year larger than 99 is returned unchanged."
17277 (if (>= year 100) year
17278 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17279 (century (/ current 100))
17280 (offset (- year (% current 100))))
17281 (cond ((> offset 30) (+ (* (1- century) 100) year))
17282 ((> offset -70) (+ (* century 100) year))
17283 (t (+ (* (1+ century) 100) year))))))
17285 (defun org-time-from-absolute (d)
17286 "Return the time corresponding to date D.
17287 D may be an absolute day number, or a calendar-type list (month day year)."
17288 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17289 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17291 (defvar org-agenda-current-date)
17292 (defun org-calendar-holiday ()
17293 "List of holidays, for Diary display in Org mode."
17294 (require 'holidays)
17295 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17296 (and hl (mapconcat #'identity hl "; "))))
17298 (defun org-diary-sexp-entry (sexp entry d)
17299 "Process a SEXP diary ENTRY for date D."
17300 (require 'diary-lib)
17301 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17302 ;; dynamically.
17303 (let* ((sexp `(let ((entry ,entry)
17304 (date ',d))
17305 ,(car (read-from-string sexp))))
17306 (result (if calendar-debug-sexp (eval sexp)
17307 (condition-case nil
17308 (eval sexp)
17309 (error
17310 (beep)
17311 (message "Bad sexp at line %d in %s: %s"
17312 (org-current-line)
17313 (buffer-file-name) sexp)
17314 (sleep-for 2))))))
17315 (cond ((stringp result) (split-string result "; "))
17316 ((and (consp result)
17317 (not (consp (cdr result)))
17318 (stringp (cdr result))) (cdr result))
17319 ((and (consp result)
17320 (stringp (car result))) result)
17321 (result entry))))
17323 (defun org-diary-to-ical-string (frombuf)
17324 "Get iCalendar entries from diary entries in buffer FROMBUF.
17325 This uses the icalendar.el library."
17326 (let* ((tmpdir temporary-file-directory)
17327 (tmpfile (make-temp-name
17328 (expand-file-name "orgics" tmpdir)))
17329 buf rtn b e)
17330 (with-current-buffer frombuf
17331 (icalendar-export-region (point-min) (point-max) tmpfile)
17332 (setq buf (find-buffer-visiting tmpfile))
17333 (set-buffer buf)
17334 (goto-char (point-min))
17335 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17336 (setq b (match-beginning 0)))
17337 (goto-char (point-max))
17338 (when (re-search-backward "^END:VEVENT" nil t)
17339 (setq e (match-end 0)))
17340 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17341 (kill-buffer buf)
17342 (delete-file tmpfile)
17343 rtn))
17345 (defun org-closest-date (start current prefer)
17346 "Return closest date to CURRENT starting from START.
17348 CURRENT and START are both time stamps.
17350 When PREFER is `past', return a date that is either CURRENT or
17351 past. When PREFER is `future', return a date that is either
17352 CURRENT or future.
17354 Only time stamps with a repeater are modified. Any other time
17355 stamp stay unchanged. In any case, return value is an absolute
17356 day number."
17357 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17358 ;; No repeater. Do not shift time stamp.
17359 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17360 (let ((value (string-to-number (match-string 1 start)))
17361 (type (match-string 2 start)))
17362 (if (= 0 value)
17363 ;; Repeater with a 0-value is considered as void.
17364 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17365 (let* ((base (org-date-to-gregorian start))
17366 (target (org-date-to-gregorian current))
17367 (sday (calendar-absolute-from-gregorian base))
17368 (cday (calendar-absolute-from-gregorian target))
17369 n1 n2)
17370 ;; If START is already past CURRENT, just return START.
17371 (if (<= cday sday) sday
17372 ;; Compute closest date before (N1) and closest date past
17373 ;; (N2) CURRENT.
17374 (pcase type
17375 ("h"
17376 (let ((missing-hours
17377 (mod (+ (- (* 24 (- cday sday))
17378 (nth 2 (org-parse-time-string start)))
17379 org-extend-today-until)
17380 value)))
17381 (setf n1 (if (= missing-hours 0) cday
17382 (- cday (1+ (/ missing-hours 24)))))
17383 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17384 ((or "d" "w")
17385 (let ((value (if (equal type "w") (* 7 value) value)))
17386 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17387 (setf n2 (+ n1 value))))
17388 ("m"
17389 (let* ((add-months
17390 (lambda (d n)
17391 ;; Add N months to gregorian date D, i.e.,
17392 ;; a list (MONTH DAY YEAR). Return a valid
17393 ;; gregorian date.
17394 (let ((m (+ (nth 0 d) n)))
17395 (list (mod m 12)
17396 (nth 1 d)
17397 (+ (/ m 12) (nth 2 d))))))
17398 (months ; Complete months to TARGET.
17399 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17400 (- (nth 0 target) (nth 0 base))
17401 ;; If START's day is greater than
17402 ;; TARGET's, remove incomplete month.
17403 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17404 value)
17405 value))
17406 (before (funcall add-months base months)))
17407 (setf n1 (calendar-absolute-from-gregorian before))
17408 (setf n2
17409 (calendar-absolute-from-gregorian
17410 (funcall add-months before value)))))
17412 (let* ((d (nth 1 base))
17413 (m (nth 0 base))
17414 (y (nth 2 base))
17415 (years ; Complete years to TARGET.
17416 (* (/ (- (nth 2 target)
17418 ;; If START's month and day are
17419 ;; greater than TARGET's, remove
17420 ;; incomplete year.
17421 (if (or (> (nth 0 target) m)
17422 (and (= (nth 0 target) m)
17423 (> (nth 1 target) d)))
17426 value)
17427 value))
17428 (before (list m d (+ y years))))
17429 (setf n1 (calendar-absolute-from-gregorian before))
17430 (setf n2 (calendar-absolute-from-gregorian
17431 (list m d (+ (nth 2 before) value)))))))
17432 ;; Handle PREFER parameter, if any.
17433 (cond
17434 ((eq prefer 'past) (if (= cday n2) n2 n1))
17435 ((eq prefer 'future) (if (= cday n1) n1 n2))
17436 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17438 (defun org-date-to-gregorian (d)
17439 "Turn any specification of date D into a Gregorian date for the calendar."
17440 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17441 ((and (listp d) (= (length d) 3)) d)
17442 ((stringp d)
17443 (let ((d (org-parse-time-string d)))
17444 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17445 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17447 (defun org-parse-time-string (s &optional nodefault zone)
17448 "Parse the standard Org time string.
17450 This should be a lot faster than the normal `parse-time-string'.
17452 If time is not given, defaults to 0:00. However, with optional
17453 NODEFAULT, hour and minute fields will be nil if not given.
17455 The optional ZONE is omitted or nil for Emacs local time, t for
17456 Universal Time, ‘wall’ for system wall clock time, or a string as
17457 in the TZ environment variable."
17458 (cond ((string-match org-ts-regexp0 s)
17459 (list 0
17460 (when (or (match-beginning 8) (not nodefault))
17461 (string-to-number (or (match-string 8 s) "0")))
17462 (when (or (match-beginning 7) (not nodefault))
17463 (string-to-number (or (match-string 7 s) "0")))
17464 (string-to-number (match-string 4 s))
17465 (string-to-number (match-string 3 s))
17466 (string-to-number (match-string 2 s))
17467 nil nil zone))
17468 ((string-match "^<[^>]+>$" s)
17469 ;; FIXME: `decode-time' needs to be called with ZONE as its
17470 ;; second argument. However, this requires at least Emacs
17471 ;; 25.1. We can do it when we switch to this version as our
17472 ;; minimal requirement.
17473 (decode-time (seconds-to-time (org-matcher-time s))))
17474 (t (error "Not a standard Org time string: %s" s))))
17476 (defun org-timestamp-up (&optional arg)
17477 "Increase the date item at the cursor by one.
17478 If the cursor is on the year, change the year. If it is on the month,
17479 the day or the time, change that.
17480 With prefix ARG, change by that many units."
17481 (interactive "p")
17482 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17484 (defun org-timestamp-down (&optional arg)
17485 "Decrease the date item at the cursor by one.
17486 If the cursor is on the year, change the year. If it is on the month,
17487 the day or the time, change that.
17488 With prefix ARG, change by that many units."
17489 (interactive "p")
17490 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17492 (defun org-timestamp-up-day (&optional arg)
17493 "Increase the date in the time stamp by one day.
17494 With prefix ARG, change that many days."
17495 (interactive "p")
17496 (if (and (not (org-at-timestamp-p 'lax))
17497 (org-at-heading-p))
17498 (org-todo 'up)
17499 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17501 (defun org-timestamp-down-day (&optional arg)
17502 "Decrease the date in the time stamp by one day.
17503 With prefix ARG, change that many days."
17504 (interactive "p")
17505 (if (and (not (org-at-timestamp-p 'lax))
17506 (org-at-heading-p))
17507 (org-todo 'down)
17508 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17510 (defun org-at-timestamp-p (&optional extended)
17511 "Non-nil if point is inside a timestamp.
17513 By default, the function only consider syntactically valid active
17514 timestamps. However, the caller may have a broader definition
17515 for timestamps. As a consequence, optional argument EXTENDED can
17516 be set to the following values
17518 `inactive'
17520 Include also syntactically valid inactive timestamps.
17522 `agenda'
17524 Include timestamps allowed in Agenda, i.e., those in
17525 properties drawers, planning lines and clock lines.
17527 `lax'
17529 Ignore context. The function matches any part of the
17530 document looking like a timestamp. This includes comments,
17531 example blocks...
17533 For backward-compatibility with Org 9.0, every other non-nil
17534 value is equivalent to `inactive'.
17536 When at a timestamp, return the position of the point as a symbol
17537 among `bracket', `after', `year', `month', `hour', `minute',
17538 `day' or a number of character from the last know part of the
17539 time stamp.
17541 When matching, the match groups are the following:
17542 group 1: year
17543 group 2: month
17544 group 3: day number
17545 group 4: day name
17546 group 5: hours, if any
17547 group 6: minutes, if any"
17548 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17549 (pos (point))
17550 (match?
17551 (let ((boundaries (org-in-regexp regexp)))
17552 (save-match-data
17553 (cond ((null boundaries) nil)
17554 ((eq extended 'lax) t)
17556 (or (and (eq extended 'agenda)
17557 (or (org-at-planning-p)
17558 (org-at-property-p)
17559 (and (bound-and-true-p
17560 org-agenda-include-inactive-timestamps)
17561 (org-at-clock-log-p))))
17562 (eq 'timestamp
17563 (save-excursion
17564 (when (= pos (cdr boundaries)) (forward-char -1))
17565 (org-element-type (org-element-context)))))))))))
17566 (cond
17567 ((not match?) nil)
17568 ((= pos (match-beginning 0)) 'bracket)
17569 ;; Distinguish location right before the closing bracket from
17570 ;; right after it.
17571 ((= pos (1- (match-end 0))) 'bracket)
17572 ((= pos (match-end 0)) 'after)
17573 ((org-pos-in-match-range pos 2) 'year)
17574 ((org-pos-in-match-range pos 3) 'month)
17575 ((org-pos-in-match-range pos 7) 'hour)
17576 ((org-pos-in-match-range pos 8) 'minute)
17577 ((or (org-pos-in-match-range pos 4)
17578 (org-pos-in-match-range pos 5)) 'day)
17579 ((and (> pos (or (match-end 8) (match-end 5)))
17580 (< pos (match-end 0)))
17581 (- pos (or (match-end 8) (match-end 5))))
17582 (t 'day))))
17584 (defun org-toggle-timestamp-type ()
17585 "Toggle the type (<active> or [inactive]) of a time stamp."
17586 (interactive)
17587 (when (org-at-timestamp-p 'lax)
17588 (let ((beg (match-beginning 0)) (end (match-end 0))
17589 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17590 (save-excursion
17591 (goto-char beg)
17592 (while (re-search-forward "[][<>]" end t)
17593 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17594 t t)))
17595 (message "Timestamp is now %sactive"
17596 (if (equal (char-after beg) ?<) "" "in")))))
17598 (defun org-at-clock-log-p ()
17599 "Non-nil if point is on a clock log line."
17600 (and (org-match-line org-clock-line-re)
17601 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17603 (defvar org-clock-history) ; defined in org-clock.el
17604 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17605 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17606 "Change the date in the time stamp at point.
17607 The date will be changed by N times WHAT. WHAT can be `day', `month',
17608 `year', `minute', `second'. If WHAT is not given, the cursor position
17609 in the timestamp determines what will be changed.
17610 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17611 (let ((origin (point))
17612 (timestamp? (org-at-timestamp-p 'lax))
17613 origin-cat
17614 with-hm inactive
17615 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17616 extra rem
17617 ts time time0 fixnext clrgx)
17618 (unless timestamp? (user-error "Not at a timestamp"))
17619 (if (and (not what) (eq timestamp? 'bracket))
17620 (org-toggle-timestamp-type)
17621 ;; Point isn't on brackets. Remember the part of the time-stamp
17622 ;; the point was in. Indeed, size of time-stamps may change,
17623 ;; but point must be kept in the same category nonetheless.
17624 (setq origin-cat timestamp?)
17625 (when (and (not what) (not (eq timestamp? 'day))
17626 org-display-custom-times
17627 (get-text-property (point) 'display)
17628 (not (get-text-property (1- (point)) 'display)))
17629 (setq timestamp? 'day))
17630 (setq timestamp? (or what timestamp?)
17631 inactive (= (char-after (match-beginning 0)) ?\[)
17632 ts (match-string 0))
17633 (replace-match "")
17634 (when (string-match
17635 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17637 (setq extra (match-string 1 ts))
17638 (when suppress-tmp-delay
17639 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17640 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17641 (setq with-hm t))
17642 (setq time0 (org-parse-time-string ts))
17643 (when (and updown
17644 (eq timestamp? 'minute)
17645 (not current-prefix-arg))
17646 ;; This looks like s-up and s-down. Change by one rounding step.
17647 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17648 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17649 (setcar (cdr time0) (+ (nth 1 time0)
17650 (if (> n 0) (- rem) (- dm rem))))))
17651 (setq time
17652 (apply #'encode-time
17653 (or (car time0) 0)
17654 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17655 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17656 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17657 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17658 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17659 (nthcdr 6 time0)))
17660 (when (and (memq timestamp? '(hour minute))
17661 extra
17662 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17663 (setq extra (org-modify-ts-extra
17664 extra
17665 (if (eq timestamp? 'hour) 2 5)
17666 n dm)))
17667 (when (integerp timestamp?)
17668 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17669 (when (eq what 'calendar)
17670 (let ((cal-date (org-get-date-from-calendar)))
17671 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17672 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17673 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17674 (setcar time0 (or (car time0) 0))
17675 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17676 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17677 (setq time (apply 'encode-time time0))))
17678 ;; Insert the new time-stamp, and ensure point stays in the same
17679 ;; category as before (i.e. not after the last position in that
17680 ;; category).
17681 (let ((pos (point)))
17682 ;; Stay before inserted string. `save-excursion' is of no use.
17683 (setq org-last-changed-timestamp
17684 (org-insert-time-stamp time with-hm inactive nil nil extra))
17685 (goto-char pos))
17686 (save-match-data
17687 (looking-at org-ts-regexp3)
17688 (goto-char
17689 (pcase origin-cat
17690 ;; `day' category ends before `hour' if any, or at the end
17691 ;; of the day name.
17692 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17693 (`hour (min (match-end 7) origin))
17694 (`minute (min (1- (match-end 8)) origin))
17695 ((pred integerp) (min (1- (match-end 0)) origin))
17696 ;; Point was right after the time-stamp. However, the
17697 ;; time-stamp length might have changed, so refer to
17698 ;; (match-end 0) instead.
17699 (`after (match-end 0))
17700 ;; `year' and `month' have both fixed size: point couldn't
17701 ;; have moved into another part.
17702 (_ origin))))
17703 ;; Update clock if on a CLOCK line.
17704 (org-clock-update-time-maybe)
17705 ;; Maybe adjust the closest clock in `org-clock-history'
17706 (when org-clock-adjust-closest
17707 (if (not (and (org-at-clock-log-p)
17708 (< 1 (length (delq nil (mapcar 'marker-position
17709 org-clock-history))))))
17710 (message "No clock to adjust")
17711 (cond ((save-excursion ; fix previous clock?
17712 (re-search-backward org-ts-regexp0 nil t)
17713 (looking-back (concat org-clock-string " \\[")
17714 (line-beginning-position)))
17715 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17716 ((save-excursion ; fix next clock?
17717 (re-search-backward org-ts-regexp0 nil t)
17718 (looking-at (concat org-ts-regexp0 "\\] =>")))
17719 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17720 (save-window-excursion
17721 ;; Find closest clock to point, adjust the previous/next one in history
17722 (let* ((p (save-excursion (org-back-to-heading t)))
17723 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17724 (clfixnth
17725 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17726 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17727 (if (not clfixpos)
17728 (message "No clock to adjust")
17729 (save-excursion
17730 (org-goto-marker-or-bmk clfixpos)
17731 (org-show-subtree)
17732 (when (re-search-forward clrgx nil t)
17733 (goto-char (match-beginning 1))
17734 (let (org-clock-adjust-closest)
17735 (org-timestamp-change n timestamp? updown))
17736 (message "Clock adjusted in %s for heading: %s"
17737 (file-name-nondirectory (buffer-file-name))
17738 (org-get-heading t t)))))))))
17739 ;; Try to recenter the calendar window, if any.
17740 (when (and org-calendar-follow-timestamp-change
17741 (get-buffer-window "*Calendar*" t)
17742 (memq timestamp? '(day month year)))
17743 (org-recenter-calendar (time-to-days time))))))
17745 (defun org-modify-ts-extra (s pos n dm)
17746 "Change the different parts of the lead-time and repeat fields in timestamp."
17747 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17748 ng h m new rem)
17749 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17750 (cond
17751 ((or (org-pos-in-match-range pos 2)
17752 (org-pos-in-match-range pos 3))
17753 (setq m (string-to-number (match-string 3 s))
17754 h (string-to-number (match-string 2 s)))
17755 (if (org-pos-in-match-range pos 2)
17756 (setq h (+ h n))
17757 (setq n (* dm (with-no-warnings (signum n))))
17758 (unless (= 0 (setq rem (% m dm)))
17759 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17760 (setq m (+ m n)))
17761 (when (< m 0) (setq m (+ m 60) h (1- h)))
17762 (when (> m 59) (setq m (- m 60) h (1+ h)))
17763 (setq h (mod h 24))
17764 (setq ng 1 new (format "-%02d:%02d" h m)))
17765 ((org-pos-in-match-range pos 6)
17766 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17767 ((org-pos-in-match-range pos 5)
17768 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17770 ((org-pos-in-match-range pos 9)
17771 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17772 ((org-pos-in-match-range pos 8)
17773 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17775 (when ng
17776 (setq s (concat
17777 (substring s 0 (match-beginning ng))
17779 (substring s (match-end ng))))))
17782 (defun org-recenter-calendar (d)
17783 "If the calendar is visible, recenter it to date D."
17784 (let ((cwin (get-buffer-window "*Calendar*" t)))
17785 (when cwin
17786 (let ((calendar-move-hook nil))
17787 (with-selected-window cwin
17788 (calendar-goto-date
17789 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17791 (defun org-goto-calendar (&optional arg)
17792 "Go to the Emacs calendar at the current date.
17793 If there is a time stamp in the current line, go to that date.
17794 A prefix ARG can be used to force the current date."
17795 (interactive "P")
17796 (let ((calendar-move-hook nil)
17797 (calendar-view-holidays-initially-flag nil)
17798 (calendar-view-diary-initially-flag nil)
17799 diff)
17800 (when (or (org-at-timestamp-p 'lax)
17801 (org-match-line (concat ".*" org-ts-regexp)))
17802 (let ((d1 (time-to-days (current-time)))
17803 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17804 (setq diff (- d2 d1))))
17805 (calendar)
17806 (calendar-goto-today)
17807 (when (and diff (not arg)) (calendar-forward-day diff))))
17809 (defun org-get-date-from-calendar ()
17810 "Return a list (month day year) of date at point in calendar."
17811 (with-current-buffer "*Calendar*"
17812 (save-match-data
17813 (calendar-cursor-to-date))))
17815 (defun org-date-from-calendar ()
17816 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17817 If there is already a time stamp at the cursor position, update it."
17818 (interactive)
17819 (if (org-at-timestamp-p 'lax)
17820 (org-timestamp-change 0 'calendar)
17821 (let ((cal-date (org-get-date-from-calendar)))
17822 (org-insert-time-stamp
17823 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17825 (defcustom org-effort-durations
17826 `(("min" . 1)
17827 ("h" . 60)
17828 ("d" . ,(* 60 8))
17829 ("w" . ,(* 60 8 5))
17830 ("m" . ,(* 60 8 5 4))
17831 ("y" . ,(* 60 8 5 40)))
17832 "Conversion factor to minutes for an effort modifier.
17834 Each entry has the form (MODIFIER . MINUTES).
17836 In an effort string, a number followed by MODIFIER is multiplied
17837 by the specified number of MINUTES to obtain an effort in
17838 minutes.
17840 For example, if the value of this variable is ((\"hours\" . 60)), then an
17841 effort string \"2hours\" is equivalent to 120 minutes."
17842 :group 'org-agenda
17843 :version "26.1"
17844 :package-version '(Org . "8.3")
17845 :type '(alist :key-type (string :tag "Modifier")
17846 :value-type (number :tag "Minutes")))
17848 (defcustom org-image-actual-width t
17849 "Should we use the actual width of images when inlining them?
17851 When set to t, always use the image width.
17853 When set to a number, use imagemagick (when available) to set
17854 the image's width to this value.
17856 When set to a number in a list, try to get the width from any
17857 #+ATTR.* keyword if it matches a width specification like
17859 #+ATTR_HTML: :width 300px
17861 and fall back on that number if none is found.
17863 When set to nil, try to get the width from an #+ATTR.* keyword
17864 and fall back on the original width if none is found.
17866 This requires Emacs >= 24.1, build with imagemagick support."
17867 :group 'org-appearance
17868 :version "24.4"
17869 :package-version '(Org . "8.0")
17870 :type '(choice
17871 (const :tag "Use the image width" t)
17872 (integer :tag "Use a number of pixels")
17873 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17874 (const :tag "Use #+ATTR* or don't resize" nil)))
17876 (defcustom org-agenda-inhibit-startup nil
17877 "Inhibit startup when preparing agenda buffers.
17878 When this variable is t, the initialization of the Org agenda
17879 buffers is inhibited: e.g. the visibility state is not set, the
17880 tables are not re-aligned, etc."
17881 :type 'boolean
17882 :version "24.3"
17883 :group 'org-agenda)
17885 (defcustom org-agenda-ignore-properties nil
17886 "Avoid updating text properties when building the agenda.
17887 Properties are used to prepare buffers for effort estimates,
17888 appointments, statistics and subtree-local categories.
17889 If you don't use these in the agenda, you can add them to this
17890 list and agenda building will be a bit faster.
17891 The value is a list, with zero or more of the symbols `effort', `appt',
17892 `stats' or `category'."
17893 :type '(set :greedy t
17894 (const effort)
17895 (const appt)
17896 (const stats)
17897 (const category))
17898 :version "26.1"
17899 :package-version '(Org . "8.3")
17900 :group 'org-agenda)
17902 ;;;; Files
17904 (defun org-save-all-org-buffers ()
17905 "Save all Org buffers without user confirmation."
17906 (interactive)
17907 (message "Saving all Org buffers...")
17908 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17909 (when (featurep 'org-id) (org-id-locations-save))
17910 (message "Saving all Org buffers... done"))
17912 (defun org-revert-all-org-buffers ()
17913 "Revert all Org buffers.
17914 Prompt for confirmation when there are unsaved changes.
17915 Be sure you know what you are doing before letting this function
17916 overwrite your changes.
17918 This function is useful in a setup where one tracks org files
17919 with a version control system, to revert on one machine after pulling
17920 changes from another. I believe the procedure must be like this:
17922 1. M-x org-save-all-org-buffers
17923 2. Pull changes from the other machine, resolve conflicts
17924 3. M-x org-revert-all-org-buffers"
17925 (interactive)
17926 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17927 (user-error "Abort"))
17928 (save-excursion
17929 (save-window-excursion
17930 (dolist (b (buffer-list))
17931 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17932 (with-current-buffer b buffer-file-name))
17933 (pop-to-buffer-same-window b)
17934 (revert-buffer t 'no-confirm)))
17935 (when (and (featurep 'org-id) org-id-track-globally)
17936 (org-id-locations-load)))))
17938 ;;;; Agenda files
17940 ;;;###autoload
17941 (defun org-switchb (&optional arg)
17942 "Switch between Org buffers.
17944 With `\\[universal-argument]' prefix, restrict available buffers to files.
17946 With `\\[universal-argument] \\[universal-argument]' \
17947 prefix, restrict available buffers to agenda files."
17948 (interactive "P")
17949 (let ((blist (org-buffer-list
17950 (cond ((equal arg '(4)) 'files)
17951 ((equal arg '(16)) 'agenda)))))
17952 (pop-to-buffer-same-window
17953 (completing-read "Org buffer: "
17954 (mapcar #'list (mapcar #'buffer-name blist))
17955 nil t))))
17957 (defun org-buffer-list (&optional predicate exclude-tmp)
17958 "Return a list of Org buffers.
17959 PREDICATE can be `export', `files' or `agenda'.
17961 export restrict the list to Export buffers.
17962 files restrict the list to buffers visiting Org files.
17963 agenda restrict the list to buffers visiting agenda files.
17965 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17966 (let* ((bfn nil)
17967 (agenda-files (and (eq predicate 'agenda)
17968 (mapcar 'file-truename (org-agenda-files t))))
17969 (filter
17970 (cond
17971 ((eq predicate 'files)
17972 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17973 ((eq predicate 'export)
17974 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17975 ((eq predicate 'agenda)
17976 (lambda (b)
17977 (with-current-buffer b
17978 (and (derived-mode-p 'org-mode)
17979 (setq bfn (buffer-file-name b))
17980 (member (file-truename bfn) agenda-files)))))
17981 (t (lambda (b) (with-current-buffer b
17982 (or (derived-mode-p 'org-mode)
17983 (string-match "\\*Org .*Export"
17984 (buffer-name b)))))))))
17985 (delq nil
17986 (mapcar
17987 (lambda(b)
17988 (if (and (funcall filter b)
17989 (or (not exclude-tmp)
17990 (not (string-match "tmp" (buffer-name b)))))
17992 nil))
17993 (buffer-list)))))
17995 (defun org-agenda-files (&optional unrestricted archives)
17996 "Get the list of agenda files.
17997 Optional UNRESTRICTED means return the full list even if a restriction
17998 is currently in place.
17999 When ARCHIVES is t, include all archive files that are really being
18000 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18001 `org-agenda-archives-mode' is t."
18002 (let ((files
18003 (cond
18004 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18005 ((stringp org-agenda-files) (org-read-agenda-file-list))
18006 ((listp org-agenda-files) org-agenda-files)
18007 (t (error "Invalid value of `org-agenda-files'")))))
18008 (setq files (apply 'append
18009 (mapcar (lambda (f)
18010 (if (file-directory-p f)
18011 (directory-files
18012 f t org-agenda-file-regexp)
18013 (list f)))
18014 files)))
18015 (when org-agenda-skip-unavailable-files
18016 (setq files (delq nil
18017 (mapcar (function
18018 (lambda (file)
18019 (and (file-readable-p file) file)))
18020 files))))
18021 (when (or (eq archives t)
18022 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18023 (setq files (org-add-archive-files files)))
18024 files))
18026 (defun org-agenda-file-p (&optional file)
18027 "Return non-nil, if FILE is an agenda file.
18028 If FILE is omitted, use the file associated with the current
18029 buffer."
18030 (let ((fname (or file (buffer-file-name))))
18031 (and fname
18032 (member (file-truename fname)
18033 (mapcar #'file-truename (org-agenda-files t))))))
18035 (defun org-edit-agenda-file-list ()
18036 "Edit the list of agenda files.
18037 Depending on setup, this either uses customize to edit the variable
18038 `org-agenda-files', or it visits the file that is holding the list. In the
18039 latter case, the buffer is set up in a way that saving it automatically kills
18040 the buffer and restores the previous window configuration."
18041 (interactive)
18042 (if (stringp org-agenda-files)
18043 (let ((cw (current-window-configuration)))
18044 (find-file org-agenda-files)
18045 (setq-local org-window-configuration cw)
18046 (add-hook 'after-save-hook
18047 (lambda ()
18048 (set-window-configuration
18049 (prog1 org-window-configuration
18050 (kill-buffer (current-buffer))))
18051 (org-install-agenda-files-menu)
18052 (message "New agenda file list installed"))
18053 nil 'local)
18054 (message "%s" (substitute-command-keys
18055 "Edit list and finish with \\[save-buffer]")))
18056 (customize-variable 'org-agenda-files)))
18058 (defun org-store-new-agenda-file-list (list)
18059 "Set new value for the agenda file list and save it correctly."
18060 (if (stringp org-agenda-files)
18061 (let ((fe (org-read-agenda-file-list t)) b u)
18062 (while (setq b (find-buffer-visiting org-agenda-files))
18063 (kill-buffer b))
18064 (with-temp-file org-agenda-files
18065 (insert
18066 (mapconcat
18067 (lambda (f) ;; Keep un-expanded entries.
18068 (if (setq u (assoc f fe))
18069 (cdr u)
18071 list "\n")
18072 "\n")))
18073 (let ((org-mode-hook nil) (org-inhibit-startup t)
18074 (org-insert-mode-line-in-empty-file nil))
18075 (setq org-agenda-files list)
18076 (customize-save-variable 'org-agenda-files org-agenda-files))))
18078 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18079 "Read the list of agenda files from a file.
18080 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18081 filenames, used by `org-store-new-agenda-file-list' to write back
18082 un-expanded file names."
18083 (when (file-directory-p org-agenda-files)
18084 (error "`org-agenda-files' cannot be a single directory"))
18085 (when (stringp org-agenda-files)
18086 (with-temp-buffer
18087 (insert-file-contents org-agenda-files)
18088 (mapcar
18089 (lambda (f)
18090 (let ((e (expand-file-name (substitute-in-file-name f)
18091 org-directory)))
18092 (if pair-with-expansion
18093 (cons e f)
18094 e)))
18095 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18097 ;;;###autoload
18098 (defun org-cycle-agenda-files ()
18099 "Cycle through the files in `org-agenda-files'.
18100 If the current buffer visits an agenda file, find the next one in the list.
18101 If the current buffer does not, find the first agenda file."
18102 (interactive)
18103 (let* ((fs (or (org-agenda-files t)
18104 (user-error "No agenda files")))
18105 (files (copy-sequence fs))
18106 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18107 file)
18108 (when tcf
18109 (while (and (setq file (pop files))
18110 (not (equal (file-truename file) tcf)))))
18111 (find-file (car (or files fs)))
18112 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18114 (defun org-agenda-file-to-front (&optional to-end)
18115 "Move/add the current file to the top of the agenda file list.
18116 If the file is not present in the list, it is added to the front. If it is
18117 present, it is moved there. With optional argument TO-END, add/move to the
18118 end of the list."
18119 (interactive "P")
18120 (let ((org-agenda-skip-unavailable-files nil)
18121 (file-alist (mapcar (lambda (x)
18122 (cons (file-truename x) x))
18123 (org-agenda-files t)))
18124 (ctf (file-truename
18125 (or buffer-file-name
18126 (user-error "Please save the current buffer to a file"))))
18127 x had)
18128 (setq x (assoc ctf file-alist) had x)
18130 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18131 (if to-end
18132 (setq file-alist (append (delq x file-alist) (list x)))
18133 (setq file-alist (cons x (delq x file-alist))))
18134 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18135 (org-install-agenda-files-menu)
18136 (message "File %s to %s of agenda file list"
18137 (if had "moved" "added") (if to-end "end" "front"))))
18139 (defun org-remove-file (&optional file)
18140 "Remove current file from the list of files in variable `org-agenda-files'.
18141 These are the files which are being checked for agenda entries.
18142 Optional argument FILE means use this file instead of the current."
18143 (interactive)
18144 (let* ((org-agenda-skip-unavailable-files nil)
18145 (file (or file buffer-file-name
18146 (user-error "Current buffer does not visit a file")))
18147 (true-file (file-truename file))
18148 (afile (abbreviate-file-name file))
18149 (files (delq nil (mapcar
18150 (lambda (x)
18151 (unless (equal true-file
18152 (file-truename x))
18154 (org-agenda-files t)))))
18155 (if (not (= (length files) (length (org-agenda-files t))))
18156 (progn
18157 (org-store-new-agenda-file-list files)
18158 (org-install-agenda-files-menu)
18159 (message "Removed from Org Agenda list: %s" afile))
18160 (message "File was not in list: %s (not removed)" afile))))
18162 (defun org-file-menu-entry (file)
18163 (vector file (list 'find-file file) t))
18165 (defun org-check-agenda-file (file)
18166 "Make sure FILE exists. If not, ask user what to do."
18167 (unless (file-exists-p file)
18168 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18169 (abbreviate-file-name file))
18170 (let ((r (downcase (read-char-exclusive))))
18171 (cond
18172 ((equal r ?r)
18173 (org-remove-file file)
18174 (throw 'nextfile t))
18175 (t (user-error "Abort"))))))
18177 (defun org-get-agenda-file-buffer (file)
18178 "Get an agenda buffer visiting FILE.
18179 If the buffer needs to be created, add it to the list of buffers
18180 which might be released later."
18181 (let ((buf (org-find-base-buffer-visiting file)))
18182 (if buf
18183 buf ; just return it
18184 ;; Make a new buffer and remember it
18185 (setq buf (find-file-noselect file))
18186 (when buf (push buf org-agenda-new-buffers))
18187 buf)))
18189 (defun org-release-buffers (blist)
18190 "Release all buffers in list, asking the user for confirmation when needed.
18191 When a buffer is unmodified, it is just killed. When modified, it is saved
18192 \(if the user agrees) and then killed."
18193 (let (file)
18194 (dolist (buf blist)
18195 (setq file (buffer-file-name buf))
18196 (when (and (buffer-modified-p buf)
18197 file
18198 (y-or-n-p (format "Save file %s? " file)))
18199 (with-current-buffer buf (save-buffer)))
18200 (kill-buffer buf))))
18202 (defun org-agenda-prepare-buffers (files)
18203 "Create buffers for all agenda files, protect archived trees and comments."
18204 (interactive)
18205 (let ((pa '(:org-archived t))
18206 (pc '(:org-comment t))
18207 (pall '(:org-archived t :org-comment t))
18208 (inhibit-read-only t)
18209 (org-inhibit-startup org-agenda-inhibit-startup)
18210 (rea (concat ":" org-archive-tag ":"))
18211 re pos)
18212 (setq org-tag-alist-for-agenda nil
18213 org-tag-groups-alist-for-agenda nil)
18214 (save-excursion
18215 (save-restriction
18216 (dolist (file files)
18217 (catch 'nextfile
18218 (if (bufferp file)
18219 (set-buffer file)
18220 (org-check-agenda-file file)
18221 (set-buffer (org-get-agenda-file-buffer file)))
18222 (widen)
18223 (org-set-regexps-and-options 'tags-only)
18224 (setq pos (point))
18225 (or (memq 'category org-agenda-ignore-properties)
18226 (org-refresh-category-properties))
18227 (or (memq 'stats org-agenda-ignore-properties)
18228 (org-refresh-stats-properties))
18229 (or (memq 'effort org-agenda-ignore-properties)
18230 (org-refresh-effort-properties))
18231 (or (memq 'appt org-agenda-ignore-properties)
18232 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18233 (setq org-todo-keywords-for-agenda
18234 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18235 (setq org-done-keywords-for-agenda
18236 (append org-done-keywords-for-agenda org-done-keywords))
18237 (setq org-todo-keyword-alist-for-agenda
18238 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18239 (setq org-tag-alist-for-agenda
18240 (org-uniquify
18241 (append org-tag-alist-for-agenda
18242 org-current-tag-alist)))
18243 ;; Merge current file's tag groups into global
18244 ;; `org-tag-groups-alist-for-agenda'.
18245 (when org-group-tags
18246 (dolist (alist org-tag-groups-alist)
18247 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18248 (if old
18249 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18250 (push alist org-tag-groups-alist-for-agenda)))))
18251 (org-with-silent-modifications
18252 (save-excursion
18253 (remove-text-properties (point-min) (point-max) pall)
18254 (when org-agenda-skip-archived-trees
18255 (goto-char (point-min))
18256 (while (re-search-forward rea nil t)
18257 (when (org-at-heading-p t)
18258 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18259 (goto-char (point-min))
18260 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18261 (while (re-search-forward re nil t)
18262 (when (save-match-data (org-in-commented-heading-p t))
18263 (add-text-properties
18264 (match-beginning 0) (org-end-of-subtree t) pc)))))
18265 (goto-char pos)))))
18266 (setq org-todo-keywords-for-agenda
18267 (org-uniquify org-todo-keywords-for-agenda))
18268 (setq org-todo-keyword-alist-for-agenda
18269 (org-uniquify org-todo-keyword-alist-for-agenda))))
18272 ;;;; CDLaTeX minor mode
18274 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18275 "Keymap for the minor `org-cdlatex-mode'.")
18277 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18278 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18279 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18280 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18281 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18283 (defvar org-cdlatex-texmathp-advice-is-done nil
18284 "Flag remembering if we have applied the advice to texmathp already.")
18286 (define-minor-mode org-cdlatex-mode
18287 "Toggle the minor `org-cdlatex-mode'.
18288 This mode supports entering LaTeX environment and math in LaTeX fragments
18289 in Org mode.
18290 \\{org-cdlatex-mode-map}"
18291 nil " OCDL" nil
18292 (when org-cdlatex-mode
18293 (require 'cdlatex)
18294 (run-hooks 'cdlatex-mode-hook)
18295 (cdlatex-compute-tables))
18296 (unless org-cdlatex-texmathp-advice-is-done
18297 (setq org-cdlatex-texmathp-advice-is-done t)
18298 (defadvice texmathp (around org-math-always-on activate)
18299 "Always return t in Org buffers.
18300 This is because we want to insert math symbols without dollars even outside
18301 the LaTeX math segments. If Org mode thinks that point is actually inside
18302 an embedded LaTeX fragment, let `texmathp' do its job.
18303 `\\[org-cdlatex-mode-map]'"
18304 (interactive)
18305 (let (p)
18306 (cond
18307 ((not (derived-mode-p 'org-mode)) ad-do-it)
18308 ((eq this-command 'cdlatex-math-symbol)
18309 (setq ad-return-value t
18310 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18312 (let ((p (org-inside-LaTeX-fragment-p)))
18313 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18314 (setq ad-return-value t
18315 texmathp-why '("Org mode embedded math" . 0))
18316 (when p ad-do-it)))))))))
18318 (defun turn-on-org-cdlatex ()
18319 "Unconditionally turn on `org-cdlatex-mode'."
18320 (org-cdlatex-mode 1))
18322 (defun org-try-cdlatex-tab ()
18323 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18324 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18325 - inside a LaTeX fragment, or
18326 - after the first word in a line, where an abbreviation expansion could
18327 insert a LaTeX environment."
18328 (when org-cdlatex-mode
18329 (cond
18330 ;; Before any word on the line: No expansion possible.
18331 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18332 ;; Just after first word on the line: Expand it. Make sure it
18333 ;; cannot happen on headlines, though.
18334 ((save-excursion
18335 (skip-chars-backward "a-zA-Z0-9*")
18336 (skip-chars-backward " \t")
18337 (and (bolp) (not (org-at-heading-p))))
18338 (cdlatex-tab) t)
18339 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18341 (defun org-cdlatex-underscore-caret (&optional _arg)
18342 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18343 Revert to the normal definition outside of these fragments."
18344 (interactive "P")
18345 (if (org-inside-LaTeX-fragment-p)
18346 (call-interactively 'cdlatex-sub-superscript)
18347 (let (org-cdlatex-mode)
18348 (call-interactively (key-binding (vector last-input-event))))))
18350 (defun org-cdlatex-math-modify (&optional _arg)
18351 "Execute `cdlatex-math-modify' in LaTeX fragments.
18352 Revert to the normal definition outside of these fragments."
18353 (interactive "P")
18354 (if (org-inside-LaTeX-fragment-p)
18355 (call-interactively 'cdlatex-math-modify)
18356 (let (org-cdlatex-mode)
18357 (call-interactively (key-binding (vector last-input-event))))))
18359 (defun org-cdlatex-environment-indent (&optional environment item)
18360 "Execute `cdlatex-environment' and indent the inserted environment.
18362 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18364 The inserted environment is indented to current indentation
18365 unless point is at the beginning of the line, in which the
18366 environment remains unintended."
18367 (interactive)
18368 ;; cdlatex-environment always return nil. Therefore, capture output
18369 ;; first and determine if an environment was selected.
18370 (let* ((beg (point-marker))
18371 (end (copy-marker (point) t))
18372 (inserted (progn
18373 (ignore-errors (cdlatex-environment environment item))
18374 (< beg end)))
18375 ;; Figure out how many lines to move forward after the
18376 ;; environment has been inserted.
18377 (lines (when inserted
18378 (save-excursion
18379 (- (cl-loop while (< beg (point))
18380 with x = 0
18381 do (forward-line -1)
18382 (cl-incf x)
18383 finally return x)
18384 (if (progn (goto-char beg)
18385 (and (progn (skip-chars-forward " \t") (eolp))
18386 (progn (skip-chars-backward " \t") (bolp))))
18387 1 0)))))
18388 (env (org-trim (delete-and-extract-region beg end))))
18389 (when inserted
18390 ;; Get indentation of next line unless at column 0.
18391 (let ((ind (if (bolp) 0
18392 (save-excursion
18393 (org-return-indent)
18394 (prog1 (org-get-indentation)
18395 (when (progn (skip-chars-forward " \t") (eolp))
18396 (delete-region beg (point)))))))
18397 (bol (progn (skip-chars-backward " \t") (bolp))))
18398 ;; Insert a newline before environment unless at column zero
18399 ;; to "escape" the current line. Insert a newline if
18400 ;; something is one the same line as \end{ENVIRONMENT}.
18401 (insert
18402 (concat (unless bol "\n") env
18403 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18404 (unless (zerop ind)
18405 (save-excursion
18406 (goto-char beg)
18407 (while (< (point) end)
18408 (unless (eolp) (indent-line-to ind))
18409 (forward-line))))
18410 (goto-char beg)
18411 (forward-line lines)
18412 (indent-line-to ind)))
18413 (set-marker beg nil)
18414 (set-marker end nil)))
18417 ;;;; LaTeX fragments
18419 (defun org-inside-LaTeX-fragment-p ()
18420 "Test if point is inside a LaTeX fragment.
18421 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18422 sequence appearing also before point.
18423 Even though the matchers for math are configurable, this function assumes
18424 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18425 delimiters are skipped when they have been removed by customization.
18426 The return value is nil, or a cons cell with the delimiter and the
18427 position of this delimiter.
18429 This function does a reasonably good job, but can locally be fooled by
18430 for example currency specifications. For example it will assume being in
18431 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18432 fragments that are properly closed, but during editing, we have to live
18433 with the uncertainty caused by missing closing delimiters. This function
18434 looks only before point, not after."
18435 (catch 'exit
18436 (let ((pos (point))
18437 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18438 (lim (save-excursion (org-backward-paragraph) (point)))
18439 dd-on str (start 0) m re)
18440 (goto-char pos)
18441 (when dodollar
18442 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18443 re (nth 1 (assoc "$" org-latex-regexps)))
18444 (while (string-match re str start)
18445 (cond
18446 ((= (match-end 0) (length str))
18447 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18448 ((= (match-end 0) (- (length str) 5))
18449 (throw 'exit nil))
18450 (t (setq start (match-end 0))))))
18451 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18452 (goto-char pos)
18453 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18454 (and (match-beginning 2) (throw 'exit nil))
18455 ;; count $$
18456 (while (re-search-backward "\\$\\$" lim t)
18457 (setq dd-on (not dd-on)))
18458 (goto-char pos)
18459 (when dd-on (cons "$$" m))))))
18461 (defun org-inside-latex-macro-p ()
18462 "Is point inside a LaTeX macro or its arguments?"
18463 (save-match-data
18464 (org-in-regexp
18465 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18467 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18468 "Build an overlay between BEG and END using IMAGE file.
18469 Argument IMAGETYPE is the extension of the displayed image,
18470 as a string. It defaults to \"png\"."
18471 (let ((ov (make-overlay beg end))
18472 (imagetype (or (intern imagetype) 'png)))
18473 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18474 (overlay-put ov 'evaporate t)
18475 (overlay-put ov
18476 'modification-hooks
18477 (list (lambda (o _flag _beg _end &optional _l)
18478 (delete-overlay o))))
18479 (overlay-put ov
18480 'display
18481 (list 'image :type imagetype :file image :ascent 'center))))
18483 (defun org--list-latex-overlays (&optional beg end)
18484 "List all Org LaTeX overlays in current buffer.
18485 Limit to overlays between BEG and END when those are provided."
18486 (cl-remove-if-not
18487 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18488 (overlays-in (or beg (point-min)) (or end (point-max)))))
18490 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18491 "Remove all overlays with LaTeX fragment images in current buffer.
18492 When optional arguments BEG and END are non-nil, remove all
18493 overlays between them instead. Return a non-nil value when some
18494 overlays were removed, nil otherwise."
18495 (let ((overlays (org--list-latex-overlays beg end)))
18496 (mapc #'delete-overlay overlays)
18497 overlays))
18499 (defun org-toggle-latex-fragment (&optional arg)
18500 "Preview the LaTeX fragment at point, or all locally or globally.
18502 If the cursor is on a LaTeX fragment, create the image and overlay
18503 it over the source code, if there is none. Remove it otherwise.
18504 If there is no fragment at point, display all fragments in the
18505 current section.
18507 With prefix ARG, preview or clear image for all fragments in the
18508 current subtree or in the whole buffer when used before the first
18509 headline. With a prefix ARG `\\[universal-argument] \
18510 \\[universal-argument]' preview or clear images
18511 for all fragments in the buffer."
18512 (interactive "P")
18513 (when (display-graphic-p)
18514 (catch 'exit
18515 (save-excursion
18516 (let (beg end msg)
18517 (cond
18518 ((or (equal arg '(16))
18519 (and (equal arg '(4))
18520 (org-with-limited-levels (org-before-first-heading-p))))
18521 (if (org-remove-latex-fragment-image-overlays)
18522 (progn (message "LaTeX fragments images removed from buffer")
18523 (throw 'exit nil))
18524 (setq msg "Creating images for buffer...")))
18525 ((equal arg '(4))
18526 (org-with-limited-levels (org-back-to-heading t))
18527 (setq beg (point))
18528 (setq end (progn (org-end-of-subtree t) (point)))
18529 (if (org-remove-latex-fragment-image-overlays beg end)
18530 (progn
18531 (message "LaTeX fragment images removed from subtree")
18532 (throw 'exit nil))
18533 (setq msg "Creating images for subtree...")))
18534 ((let ((datum (org-element-context)))
18535 (when (memq (org-element-type datum)
18536 '(latex-environment latex-fragment))
18537 (setq beg (org-element-property :begin datum))
18538 (setq end (org-element-property :end datum))
18539 (if (org-remove-latex-fragment-image-overlays beg end)
18540 (progn (message "LaTeX fragment image removed")
18541 (throw 'exit nil))
18542 (setq msg "Creating image...")))))
18544 (org-with-limited-levels
18545 (setq beg (if (org-at-heading-p) (line-beginning-position)
18546 (outline-previous-heading)
18547 (point)))
18548 (setq end (progn (outline-next-heading) (point)))
18549 (if (org-remove-latex-fragment-image-overlays beg end)
18550 (progn
18551 (message "LaTeX fragment images removed from section")
18552 (throw 'exit nil))
18553 (setq msg "Creating images for section...")))))
18554 (let ((file (buffer-file-name (buffer-base-buffer))))
18555 (org-format-latex
18556 (concat org-preview-latex-image-directory "org-ltximg")
18557 beg end
18558 ;; Emacs cannot overlay images from remote hosts. Create
18559 ;; it in `temporary-file-directory' instead.
18560 (if (or (not file) (file-remote-p file))
18561 temporary-file-directory
18562 default-directory)
18563 'overlays msg 'forbuffer org-preview-latex-default-process))
18564 (message (concat msg "done")))))))
18566 (defun org-format-latex
18567 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18568 "Replace LaTeX fragments with links to an image.
18570 The function takes care of creating the replacement image.
18572 Only consider fragments between BEG and END when those are
18573 provided.
18575 When optional argument OVERLAYS is non-nil, display the image on
18576 top of the fragment instead of replacing it.
18578 PROCESSING-TYPE is the conversion method to use, as a symbol.
18580 Some of the options can be changed using the variable
18581 `org-format-latex-options', which see."
18582 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18583 (unless (eq processing-type 'verbatim)
18584 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18585 (cnt 0)
18586 checkdir-flag)
18587 (goto-char (or beg (point-min)))
18588 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18589 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18590 (overlay-recenter (or end (point-max))))
18591 (while (re-search-forward math-regexp end t)
18592 (unless (and overlays
18593 (eq (get-char-property (point) 'org-overlay-type)
18594 'org-latex-overlay))
18595 (let* ((context (org-element-context))
18596 (type (org-element-type context)))
18597 (when (memq type '(latex-environment latex-fragment))
18598 (let ((block-type (eq type 'latex-environment))
18599 (value (org-element-property :value context))
18600 (beg (org-element-property :begin context))
18601 (end (save-excursion
18602 (goto-char (org-element-property :end context))
18603 (skip-chars-backward " \r\t\n")
18604 (point))))
18605 (cond
18606 ((eq processing-type 'mathjax)
18607 ;; Prepare for MathJax processing.
18608 (if (not (string-match "\\`\\$\\$?" value))
18609 (goto-char end)
18610 (delete-region beg end)
18611 (if (string= (match-string 0 value) "$$")
18612 (insert "\\[" (substring value 2 -2) "\\]")
18613 (insert "\\(" (substring value 1 -1) "\\)"))))
18614 ((assq processing-type org-preview-latex-process-alist)
18615 ;; Process to an image.
18616 (cl-incf cnt)
18617 (goto-char beg)
18618 (let* ((processing-info
18619 (cdr (assq processing-type org-preview-latex-process-alist)))
18620 (face (face-at-point))
18621 ;; Get the colors from the face at point.
18623 (let ((color (plist-get org-format-latex-options
18624 :foreground)))
18625 (if (and forbuffer (eq color 'auto))
18626 (face-attribute face :foreground nil 'default)
18627 color)))
18629 (let ((color (plist-get org-format-latex-options
18630 :background)))
18631 (if (and forbuffer (eq color 'auto))
18632 (face-attribute face :background nil 'default)
18633 color)))
18634 (hash (sha1 (prin1-to-string
18635 (list org-format-latex-header
18636 org-latex-default-packages-alist
18637 org-latex-packages-alist
18638 org-format-latex-options
18639 forbuffer value fg bg))))
18640 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18641 (absprefix (expand-file-name prefix dir))
18642 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18643 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18644 (sep (and block-type "\n\n"))
18645 (link (concat sep "[[file:" linkfile "]]" sep))
18646 (options
18647 (org-combine-plists
18648 org-format-latex-options
18649 `(:foreground ,fg :background ,bg))))
18650 (when msg (message msg cnt))
18651 (unless checkdir-flag ; Ensure the directory exists.
18652 (setq checkdir-flag t)
18653 (let ((todir (file-name-directory absprefix)))
18654 (unless (file-directory-p todir)
18655 (make-directory todir t))))
18656 (unless (file-exists-p movefile)
18657 (org-create-formula-image
18658 value movefile options forbuffer processing-type))
18659 (if overlays
18660 (progn
18661 (dolist (o (overlays-in beg end))
18662 (when (eq (overlay-get o 'org-overlay-type)
18663 'org-latex-overlay)
18664 (delete-overlay o)))
18665 (org--format-latex-make-overlay beg end movefile imagetype)
18666 (goto-char end))
18667 (delete-region beg end)
18668 (insert
18669 (org-add-props link
18670 (list 'org-latex-src
18671 (replace-regexp-in-string "\"" "" value)
18672 'org-latex-src-embed-type
18673 (if block-type 'paragraph 'character)))))))
18674 ((eq processing-type 'mathml)
18675 ;; Process to MathML.
18676 (unless (org-format-latex-mathml-available-p)
18677 (user-error "LaTeX to MathML converter not configured"))
18678 (cl-incf cnt)
18679 (when msg (message msg cnt))
18680 (goto-char beg)
18681 (delete-region beg end)
18682 (insert (org-format-latex-as-mathml
18683 value block-type prefix dir)))
18685 (error "Unknown conversion process %s for LaTeX fragments"
18686 processing-type)))))))))))
18688 (defun org-create-math-formula (latex-frag &optional mathml-file)
18689 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18690 Use `org-latex-to-mathml-convert-command'. If the conversion is
18691 sucessful, return the portion between \"<math...> </math>\"
18692 elements otherwise return nil. When MATHML-FILE is specified,
18693 write the results in to that file. When invoked as an
18694 interactive command, prompt for LATEX-FRAG, with initial value
18695 set to the current active region and echo the results for user
18696 inspection."
18697 (interactive (list (let ((frag (when (org-region-active-p)
18698 (buffer-substring-no-properties
18699 (region-beginning) (region-end)))))
18700 (read-string "LaTeX Fragment: " frag nil frag))))
18701 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18702 (let* ((tmp-in-file
18703 (let ((file (file-relative-name
18704 (make-temp-name (expand-file-name "ltxmathml-in")))))
18705 (write-region latex-frag nil file)
18706 file))
18707 (tmp-out-file (file-relative-name
18708 (make-temp-name (expand-file-name "ltxmathml-out"))))
18709 (cmd (format-spec
18710 org-latex-to-mathml-convert-command
18711 `((?j . ,(and org-latex-to-mathml-jar-file
18712 (shell-quote-argument
18713 (expand-file-name
18714 org-latex-to-mathml-jar-file))))
18715 (?I . ,(shell-quote-argument tmp-in-file))
18716 (?i . ,latex-frag)
18717 (?o . ,(shell-quote-argument tmp-out-file)))))
18718 mathml shell-command-output)
18719 (when (called-interactively-p 'any)
18720 (unless (org-format-latex-mathml-available-p)
18721 (user-error "LaTeX to MathML converter not configured")))
18722 (message "Running %s" cmd)
18723 (setq shell-command-output (shell-command-to-string cmd))
18724 (setq mathml
18725 (when (file-readable-p tmp-out-file)
18726 (with-current-buffer (find-file-noselect tmp-out-file t)
18727 (goto-char (point-min))
18728 (when (re-search-forward
18729 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18730 (regexp-quote
18731 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18732 nil t)
18733 (prog1 (match-string 0) (kill-buffer))))))
18734 (cond
18735 (mathml
18736 (setq mathml
18737 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18738 (when mathml-file
18739 (write-region mathml nil mathml-file))
18740 (when (called-interactively-p 'any)
18741 (message mathml)))
18742 ((message "LaTeX to MathML conversion failed")
18743 (message shell-command-output)))
18744 (delete-file tmp-in-file)
18745 (when (file-exists-p tmp-out-file)
18746 (delete-file tmp-out-file))
18747 mathml))
18749 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18750 prefix &optional dir)
18751 "Use `org-create-math-formula' but check local cache first."
18752 (let* ((absprefix (expand-file-name prefix dir))
18753 (print-length nil) (print-level nil)
18754 (formula-id (concat
18755 "formula-"
18756 (sha1
18757 (prin1-to-string
18758 (list latex-frag
18759 org-latex-to-mathml-convert-command)))))
18760 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18761 (formula-cache-dir (file-name-directory formula-cache)))
18763 (unless (file-directory-p formula-cache-dir)
18764 (make-directory formula-cache-dir t))
18766 (unless (file-exists-p formula-cache)
18767 (org-create-math-formula latex-frag formula-cache))
18769 (if (file-exists-p formula-cache)
18770 ;; Successful conversion. Return the link to MathML file.
18771 (org-add-props
18772 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18773 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18774 'org-latex-src-embed-type (if latex-frag-type
18775 'paragraph 'character)))
18776 ;; Failed conversion. Return the LaTeX fragment verbatim
18777 latex-frag)))
18779 (defun org--get-display-dpi ()
18780 "Get the DPI of the display.
18781 The function assumes that the display has the same pixel width in
18782 the horizontal and vertical directions."
18783 (if (display-graphic-p)
18784 (round (/ (display-pixel-height)
18785 (/ (display-mm-height) 25.4)))
18786 (error "Attempt to calculate the dpi of a non-graphic display")))
18788 (defun org-create-formula-image
18789 (string tofile options buffer &optional processing-type)
18790 "Create an image from LaTeX source using external processes.
18792 The LaTeX STRING is saved to a temporary LaTeX file, then
18793 converted to an image file by process PROCESSING-TYPE defined in
18794 `org-preview-latex-process-alist'. A nil value defaults to
18795 `org-preview-latex-default-process'.
18797 The generated image file is eventually moved to TOFILE.
18799 The OPTIONS argument controls the size, foreground color and
18800 background color of the generated image.
18802 When BUFFER non-nil, this function is used for LaTeX previewing.
18803 Otherwise, it is used to deal with LaTeX snippets showed in
18804 a HTML file."
18805 (let* ((processing-type (or processing-type
18806 org-preview-latex-default-process))
18807 (processing-info
18808 (cdr (assq processing-type org-preview-latex-process-alist)))
18809 (programs (plist-get processing-info :programs))
18810 (error-message (or (plist-get processing-info :message) ""))
18811 (use-xcolor (plist-get processing-info :use-xcolor))
18812 (image-input-type (plist-get processing-info :image-input-type))
18813 (image-output-type (plist-get processing-info :image-output-type))
18814 (post-clean (or (plist-get processing-info :post-clean)
18815 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18816 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18817 (latex-header
18818 (or (plist-get processing-info :latex-header)
18819 (org-latex-make-preamble
18820 (org-export-get-environment (org-export-get-backend 'latex))
18821 org-format-latex-header
18822 'snippet)))
18823 (latex-compiler (plist-get processing-info :latex-compiler))
18824 (image-converter (plist-get processing-info :image-converter))
18825 (tmpdir temporary-file-directory)
18826 (texfilebase (make-temp-name
18827 (expand-file-name "orgtex" tmpdir)))
18828 (texfile (concat texfilebase ".tex"))
18829 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18830 '(1.0 . 1.0)))
18831 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18832 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18833 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18834 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18835 "Black"))
18836 (bg (or (plist-get options (if buffer :background :html-background))
18837 "Transparent"))
18838 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18839 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18840 (dolist (program programs)
18841 (org-check-external-command program error-message))
18842 (if use-xcolor
18843 (progn (if (eq fg 'default)
18844 (setq fg (org-latex-color :foreground))
18845 (setq fg (org-latex-color-format fg)))
18846 (if (eq bg 'default)
18847 (setq bg (org-latex-color :background))
18848 (setq bg (org-latex-color-format
18849 (if (string= bg "Transparent") "white" bg))))
18850 (with-temp-file texfile
18851 (insert latex-header)
18852 (insert "\n\\begin{document}\n"
18853 "\\definecolor{fg}{rgb}{" fg "}\n"
18854 "\\definecolor{bg}{rgb}{" bg "}\n"
18855 "\n\\pagecolor{bg}\n"
18856 "\n{\\color{fg}\n"
18857 string
18858 "\n}\n"
18859 "\n\\end{document}\n")))
18860 (if (eq fg 'default)
18861 (setq fg (org-dvipng-color :foreground))
18862 (unless (string= fg "Transparent")
18863 (setq fg (org-dvipng-color-format fg))))
18864 (if (eq bg 'default)
18865 (setq bg (org-dvipng-color :background))
18866 (unless (string= bg "Transparent")
18867 (setq bg (org-dvipng-color-format bg))))
18868 (with-temp-file texfile
18869 (insert latex-header)
18870 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18872 (let* ((err-msg (format "Please adjust `%s' part of \
18873 `org-preview-latex-process-alist'."
18874 processing-type))
18875 (image-input-file
18876 (org-compile-file
18877 texfile latex-compiler image-input-type err-msg log-buf))
18878 (image-output-file
18879 (org-compile-file
18880 image-input-file image-converter image-output-type err-msg log-buf
18881 `((?F . ,(shell-quote-argument fg))
18882 (?B . ,(shell-quote-argument bg))
18883 (?D . ,(shell-quote-argument (format "%s" dpi)))
18884 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18885 (copy-file image-output-file tofile 'replace)
18886 (dolist (e post-clean)
18887 (when (file-exists-p (concat texfilebase e))
18888 (delete-file (concat texfilebase e))))
18889 image-output-file)))
18891 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18892 "Fill a LaTeX header template TPL.
18893 In the template, the following place holders will be recognized:
18895 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18896 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18897 [PACKAGES] \\usepackage statements for PKG
18898 [NO-PACKAGES] do not include PKG
18899 [EXTRA] the string EXTRA
18900 [NO-EXTRA] do not include EXTRA
18902 For backward compatibility, if both the positive and the negative place
18903 holder is missing, the positive one (without the \"NO-\") will be
18904 assumed to be present at the end of the template.
18905 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18906 EXTRA is a string.
18907 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18908 (let (rpl (end ""))
18909 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18910 (setq rpl (if (or (match-end 1) (not def-pkg))
18911 "" (org-latex-packages-to-string def-pkg snippets-p t))
18912 tpl (replace-match rpl t t tpl))
18913 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18915 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18916 (setq rpl (if (or (match-end 1) (not pkg))
18917 "" (org-latex-packages-to-string pkg snippets-p t))
18918 tpl (replace-match rpl t t tpl))
18919 (when pkg (setq end
18920 (concat end "\n"
18921 (org-latex-packages-to-string pkg snippets-p)))))
18923 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18924 (setq rpl (if (or (match-end 1) (not extra))
18925 "" (concat extra "\n"))
18926 tpl (replace-match rpl t t tpl))
18927 (when (and extra (string-match "\\S-" extra))
18928 (setq end (concat end "\n" extra))))
18930 (if (string-match "\\S-" end)
18931 (concat tpl "\n" end)
18932 tpl)))
18934 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18935 "Turn an alist of packages into a string with the \\usepackage macros."
18936 (setq pkg (mapconcat (lambda(p)
18937 (cond
18938 ((stringp p) p)
18939 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18940 (format "%% Package %s omitted" (cadr p)))
18941 ((equal "" (car p))
18942 (format "\\usepackage{%s}" (cadr p)))
18944 (format "\\usepackage[%s]{%s}"
18945 (car p) (cadr p)))))
18947 "\n"))
18948 (if newline (concat pkg "\n") pkg))
18950 (defun org-dvipng-color (attr)
18951 "Return a RGB color specification for dvipng."
18952 (org-dvipng-color-format (face-attribute 'default attr nil)))
18954 (defun org-dvipng-color-format (color-name)
18955 "Convert COLOR-NAME to a RGB color value for dvipng."
18956 (apply #'format "rgb %s %s %s"
18957 (mapcar 'org-normalize-color
18958 (color-values color-name))))
18960 (defun org-latex-color (attr)
18961 "Return a RGB color for the LaTeX color package."
18962 (org-latex-color-format (face-attribute 'default attr nil)))
18964 (defun org-latex-color-format (color-name)
18965 "Convert COLOR-NAME to a RGB color value."
18966 (apply #'format "%s,%s,%s"
18967 (mapcar 'org-normalize-color
18968 (color-values color-name))))
18970 (defun org-normalize-color (value)
18971 "Return string to be used as color value for an RGB component."
18972 (format "%g" (/ value 65535.0)))
18976 ;; Image display
18978 (defvar-local org-inline-image-overlays nil)
18980 (defun org-toggle-inline-images (&optional include-linked)
18981 "Toggle the display of inline images.
18982 INCLUDE-LINKED is passed to `org-display-inline-images'."
18983 (interactive "P")
18984 (if org-inline-image-overlays
18985 (progn
18986 (org-remove-inline-images)
18987 (when (called-interactively-p 'interactive)
18988 (message "Inline image display turned off")))
18989 (org-display-inline-images include-linked)
18990 (when (called-interactively-p 'interactive)
18991 (message (if org-inline-image-overlays
18992 (format "%d images displayed inline"
18993 (length org-inline-image-overlays))
18994 "No images to display inline")))))
18996 (defun org-redisplay-inline-images ()
18997 "Refresh the display of inline images."
18998 (interactive)
18999 (if (not org-inline-image-overlays)
19000 (org-toggle-inline-images)
19001 (org-toggle-inline-images)
19002 (org-toggle-inline-images)))
19004 (defun org-display-inline-images (&optional include-linked refresh beg end)
19005 "Display inline images.
19007 An inline image is a link which follows either of these
19008 conventions:
19010 1. Its path is a file with an extension matching return value
19011 from `image-file-name-regexp' and it has no contents.
19013 2. Its description consists in a single link of the previous
19014 type.
19016 When optional argument INCLUDE-LINKED is non-nil, also links with
19017 a text description part will be inlined. This can be nice for
19018 a quick look at those images, but it does not reflect what
19019 exported files will look like.
19021 When optional argument REFRESH is non-nil, refresh existing
19022 images between BEG and END. This will create new image displays
19023 only if necessary. BEG and END default to the buffer
19024 boundaries."
19025 (interactive "P")
19026 (when (display-graphic-p)
19027 (unless refresh
19028 (org-remove-inline-images)
19029 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19030 (org-with-wide-buffer
19031 (goto-char (or beg (point-min)))
19032 (let* ((case-fold-search t)
19033 (file-extension-re (image-file-name-regexp))
19034 (link-abbrevs (mapcar #'car
19035 (append org-link-abbrev-alist-local
19036 org-link-abbrev-alist)))
19037 ;; Check absolute, relative file names and explicit
19038 ;; "file:" links. Also check link abbreviations since
19039 ;; some might expand to "file" links.
19040 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19041 (and link-abbrevs
19042 (format "\\|\\(?:%s:\\)"
19043 (regexp-opt link-abbrevs))))))
19044 (while (re-search-forward file-types-re end t)
19045 (let ((link (save-match-data (org-element-context))))
19046 ;; Check if we're at an inline image, i.e., an image file
19047 ;; link without a description (unless INCLUDE-LINKED is
19048 ;; non-nil).
19049 (when (and (equal "file" (org-element-property :type link))
19050 (or include-linked
19051 (null (org-element-contents link)))
19052 (string-match-p file-extension-re
19053 (org-element-property :path link)))
19054 (let ((file (expand-file-name
19055 (org-link-unescape
19056 (org-element-property :path link)))))
19057 (when (file-exists-p file)
19058 (let ((width
19059 ;; Apply `org-image-actual-width' specifications.
19060 (cond
19061 ((not (image-type-available-p 'imagemagick)) nil)
19062 ((eq org-image-actual-width t) nil)
19063 ((listp org-image-actual-width)
19065 ;; First try to find a width among
19066 ;; attributes associated to the paragraph
19067 ;; containing link.
19068 (let ((paragraph
19069 (let ((e link))
19070 (while (and (setq e (org-element-property
19071 :parent e))
19072 (not (eq (org-element-type e)
19073 'paragraph))))
19074 e)))
19075 (when paragraph
19076 (save-excursion
19077 (goto-char (org-element-property :begin paragraph))
19078 (when
19079 (re-search-forward
19080 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19081 (org-element-property
19082 :post-affiliated paragraph)
19084 (string-to-number (match-string 1))))))
19085 ;; Otherwise, fall-back to provided number.
19086 (car org-image-actual-width)))
19087 ((numberp org-image-actual-width)
19088 org-image-actual-width)))
19089 (old (get-char-property-and-overlay
19090 (org-element-property :begin link)
19091 'org-image-overlay)))
19092 (if (and (car-safe old) refresh)
19093 (image-refresh (overlay-get (cdr old) 'display))
19094 (let ((image (create-image file
19095 (and width 'imagemagick)
19097 :width width)))
19098 (when image
19099 (let ((ov (make-overlay
19100 (org-element-property :begin link)
19101 (progn
19102 (goto-char
19103 (org-element-property :end link))
19104 (skip-chars-backward " \t")
19105 (point)))))
19106 (overlay-put ov 'display image)
19107 (overlay-put ov 'face 'default)
19108 (overlay-put ov 'org-image-overlay t)
19109 (overlay-put
19110 ov 'modification-hooks
19111 (list 'org-display-inline-remove-overlay))
19112 (push ov org-inline-image-overlays)))))))))))))))
19114 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19115 "Remove inline-display overlay if a corresponding region is modified."
19116 (let ((inhibit-modification-hooks t))
19117 (when (and ov after)
19118 (delete ov org-inline-image-overlays)
19119 (delete-overlay ov))))
19121 (defun org-remove-inline-images ()
19122 "Remove inline display of images."
19123 (interactive)
19124 (mapc #'delete-overlay org-inline-image-overlays)
19125 (setq org-inline-image-overlays nil))
19127 ;;;; Key bindings
19129 (defun org-remap (map &rest commands)
19130 "In MAP, remap the functions given in COMMANDS.
19131 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19132 (let (new old)
19133 (while commands
19134 (setq old (pop commands) new (pop commands))
19135 (org-defkey map (vector 'remap old) new))))
19137 ;; Outline functions from `outline-mode-prefix-map'
19138 ;; that can be remapped in Org:
19139 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19140 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19141 (define-key org-mode-map [remap outline-forward-same-level]
19142 'org-forward-heading-same-level)
19143 (define-key org-mode-map [remap outline-backward-same-level]
19144 'org-backward-heading-same-level)
19145 (define-key org-mode-map [remap outline-show-branches]
19146 'org-kill-note-or-show-branches)
19147 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19148 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19149 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19150 (define-key org-mode-map [remap outline-next-visible-heading]
19151 'org-next-visible-heading)
19152 (define-key org-mode-map [remap outline-previous-visible-heading]
19153 'org-previous-visible-heading)
19154 (define-key org-mode-map [remap show-children] 'org-show-children)
19156 ;; Outline functions from `outline-mode-prefix-map' that can not
19157 ;; be remapped in Org:
19159 ;; - the column "key binding" shows whether the Outline function is still
19160 ;; available in Org mode on the same key that it has been bound to in
19161 ;; Outline mode:
19162 ;; - "overridden": key used for a different functionality in Org mode
19163 ;; - else: key still bound to the same Outline function in Org mode
19165 ;; | Outline function | key binding | Org replacement |
19166 ;; |------------------------------------+-------------+--------------------------|
19167 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19168 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19169 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19170 ;; | `show-entry' | overridden | no replacement |
19171 ;; | `show-branches' | `C-c C-k' | still same function |
19172 ;; | `show-subtree' | overridden | visibility cycling |
19173 ;; | `show-all' | overridden | no replacement |
19174 ;; | `hide-subtree' | overridden | visibility cycling |
19175 ;; | `hide-body' | overridden | no replacement |
19176 ;; | `hide-entry' | overridden | visibility cycling |
19177 ;; | `hide-leaves' | overridden | no replacement |
19178 ;; | `hide-sublevels' | overridden | no replacement |
19179 ;; | `hide-other' | overridden | no replacement |
19181 ;; Make `C-c C-x' a prefix key
19182 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19184 ;; TAB key with modifiers
19185 (org-defkey org-mode-map "\C-i" 'org-cycle)
19186 (org-defkey org-mode-map [(tab)] 'org-cycle)
19187 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19188 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19190 ;; The following line is necessary under Suse GNU/Linux
19191 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19192 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19193 (define-key org-mode-map [backtab] 'org-shifttab)
19195 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19196 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19197 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19199 ;; Cursor keys with modifiers
19200 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19201 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19202 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19203 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19205 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19206 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19207 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19208 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19209 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19210 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19212 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19213 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19214 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19215 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19217 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19218 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19219 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19220 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19222 ;; Babel keys
19223 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19224 (dolist (pair org-babel-key-bindings)
19225 (define-key org-babel-map (car pair) (cdr pair)))
19227 ;;; Extra keys for tty access.
19228 ;; We only set them when really needed because otherwise the
19229 ;; menus don't show the simple keys
19231 (when (or org-use-extra-keys (not window-system))
19232 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19233 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19234 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19235 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19236 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19237 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19238 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19239 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19240 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19241 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19242 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19243 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19244 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19245 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19246 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19247 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19248 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19249 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19250 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19251 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19252 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19253 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19254 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19255 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19256 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19257 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19258 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19259 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19261 ;; All the other keys
19262 (org-remap org-mode-map
19263 'self-insert-command 'org-self-insert-command
19264 'delete-char 'org-delete-char
19265 'delete-backward-char 'org-delete-backward-char)
19266 (org-defkey org-mode-map "|" 'org-force-self-insert)
19268 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19269 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19270 (if (boundp 'narrow-map)
19271 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19272 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19273 (if (boundp 'narrow-map)
19274 (org-defkey narrow-map "b" 'org-narrow-to-block)
19275 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19276 (if (boundp 'narrow-map)
19277 (org-defkey narrow-map "e" 'org-narrow-to-element)
19278 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19279 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19280 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19281 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19282 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19283 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19284 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19285 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19286 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19287 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19288 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19289 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19290 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19291 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19292 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19293 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19294 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19295 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19296 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19297 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19298 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19299 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19300 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19301 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19302 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19303 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19304 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19305 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19306 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19307 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19308 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19309 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19310 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19311 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19312 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19313 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19314 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19315 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19316 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19317 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19318 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19319 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19320 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19321 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19322 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19323 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19324 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19325 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19326 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19327 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19328 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19329 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19330 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19331 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19332 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19333 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19334 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19335 (org-defkey org-mode-map "\C-c^" 'org-sort)
19336 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19337 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19338 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19339 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19340 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19341 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19342 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19343 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19344 (org-defkey org-mode-map "\C-m" 'org-return)
19345 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19346 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19347 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19348 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19349 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19350 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19351 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19352 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19353 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19354 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19355 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19356 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19357 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19358 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19359 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19360 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19361 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19362 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19363 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19364 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19365 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19366 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19367 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19368 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19369 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19371 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19372 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19373 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19375 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19376 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19377 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19378 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19379 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19380 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19381 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19382 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19383 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19384 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19385 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19386 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19387 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19388 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19389 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19390 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19391 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19392 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19393 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19394 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19395 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19396 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19398 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19399 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19400 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19401 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19402 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19404 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19406 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19408 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19409 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19411 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19414 (defconst org-speed-commands-default
19416 ("Outline Navigation")
19417 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19418 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19419 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19420 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19421 ("F" . org-next-block)
19422 ("B" . org-previous-block)
19423 ("u" . (org-speed-move-safe 'outline-up-heading))
19424 ("j" . org-goto)
19425 ("g" . (org-refile t))
19426 ("Outline Visibility")
19427 ("c" . org-cycle)
19428 ("C" . org-shifttab)
19429 (" " . org-display-outline-path)
19430 ("s" . org-narrow-to-subtree)
19431 ("=" . org-columns)
19432 ("Outline Structure Editing")
19433 ("U" . org-metaup)
19434 ("D" . org-metadown)
19435 ("r" . org-metaright)
19436 ("l" . org-metaleft)
19437 ("R" . org-shiftmetaright)
19438 ("L" . org-shiftmetaleft)
19439 ("i" . (progn (forward-char 1) (call-interactively
19440 'org-insert-heading-respect-content)))
19441 ("^" . org-sort)
19442 ("w" . org-refile)
19443 ("a" . org-archive-subtree-default-with-confirmation)
19444 ("@" . org-mark-subtree)
19445 ("#" . org-toggle-comment)
19446 ("Clock Commands")
19447 ("I" . org-clock-in)
19448 ("O" . org-clock-out)
19449 ("Meta Data Editing")
19450 ("t" . org-todo)
19451 ("," . (org-priority))
19452 ("0" . (org-priority ?\ ))
19453 ("1" . (org-priority ?A))
19454 ("2" . (org-priority ?B))
19455 ("3" . (org-priority ?C))
19456 (":" . org-set-tags-command)
19457 ("e" . org-set-effort)
19458 ("E" . org-inc-effort)
19459 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19460 (org-entry-put (point) "APPT_WARNTIME" m)))
19461 ("Agenda Views etc")
19462 ("v" . org-agenda)
19463 ("/" . org-sparse-tree)
19464 ("Misc")
19465 ("o" . org-open-at-point)
19466 ("?" . org-speed-command-help)
19467 ("<" . (org-agenda-set-restriction-lock 'subtree))
19468 (">" . (org-agenda-remove-restriction-lock))
19470 "The default speed commands.")
19472 (defun org-print-speed-command (e)
19473 (if (> (length (car e)) 1)
19474 (progn
19475 (princ "\n")
19476 (princ (car e))
19477 (princ "\n")
19478 (princ (make-string (length (car e)) ?-))
19479 (princ "\n"))
19480 (princ (car e))
19481 (princ " ")
19482 (if (symbolp (cdr e))
19483 (princ (symbol-name (cdr e)))
19484 (prin1 (cdr e)))
19485 (princ "\n")))
19487 (defun org-speed-command-help ()
19488 "Show the available speed commands."
19489 (interactive)
19490 (if (not org-use-speed-commands)
19491 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19492 (with-output-to-temp-buffer "*Help*"
19493 (princ "User-defined Speed commands\n===========================\n")
19494 (mapc #'org-print-speed-command org-speed-commands-user)
19495 (princ "\n")
19496 (princ "Built-in Speed commands\n=======================\n")
19497 (mapc #'org-print-speed-command org-speed-commands-default))
19498 (with-current-buffer "*Help*"
19499 (setq truncate-lines t))))
19501 (defun org-speed-move-safe (cmd)
19502 "Execute CMD, but make sure that the cursor always ends up in a headline.
19503 If not, return to the original position and throw an error."
19504 (interactive)
19505 (let ((pos (point)))
19506 (call-interactively cmd)
19507 (unless (and (bolp) (org-at-heading-p))
19508 (goto-char pos)
19509 (error "Boundary reached while executing %s" cmd))))
19511 (defvar org-self-insert-command-undo-counter 0)
19513 (defvar org-table-auto-blank-field) ; defined in org-table.el
19514 (defvar org-speed-command nil)
19516 (defun org-speed-command-activate (keys)
19517 "Hook for activating single-letter speed commands.
19518 `org-speed-commands-default' specifies a minimal command set.
19519 Use `org-speed-commands-user' for further customization."
19520 (when (or (and (bolp) (looking-at org-outline-regexp))
19521 (and (functionp org-use-speed-commands)
19522 (funcall org-use-speed-commands)))
19523 (cdr (assoc keys (append org-speed-commands-user
19524 org-speed-commands-default)))))
19526 (defun org-babel-speed-command-activate (keys)
19527 "Hook for activating single-letter code block commands."
19528 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19529 (cdr (assoc keys org-babel-key-bindings))))
19531 (defcustom org-speed-command-hook
19532 '(org-speed-command-activate org-babel-speed-command-activate)
19533 "Hook for activating speed commands at strategic locations.
19534 Hook functions are called in sequence until a valid handler is
19535 found.
19537 Each hook takes a single argument, a user-pressed command key
19538 which is also a `self-insert-command' from the global map.
19540 Within the hook, examine the cursor position and the command key
19541 and return nil or a valid handler as appropriate. Handler could
19542 be one of an interactive command, a function, or a form.
19544 Set `org-use-speed-commands' to non-nil value to enable this
19545 hook. The default setting is `org-speed-command-activate'."
19546 :group 'org-structure
19547 :version "24.1"
19548 :type 'hook)
19550 (defun org-self-insert-command (N)
19551 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19552 If the cursor is in a table looking at whitespace, the whitespace is
19553 overwritten, and the table is not marked as requiring realignment."
19554 (interactive "p")
19555 (org-check-before-invisible-edit 'insert)
19556 (cond
19557 ((and org-use-speed-commands
19558 (let ((kv (this-command-keys-vector)))
19559 (setq org-speed-command
19560 (run-hook-with-args-until-success
19561 'org-speed-command-hook
19562 (make-string 1 (aref kv (1- (length kv))))))))
19563 (cond
19564 ((commandp org-speed-command)
19565 (setq this-command org-speed-command)
19566 (call-interactively org-speed-command))
19567 ((functionp org-speed-command)
19568 (funcall org-speed-command))
19569 ((and org-speed-command (listp org-speed-command))
19570 (eval org-speed-command))
19571 (t (let (org-use-speed-commands)
19572 (call-interactively 'org-self-insert-command)))))
19573 ((and
19574 (org-at-table-p)
19575 (eq N 1)
19576 (not (org-region-active-p))
19577 (progn
19578 ;; Check if we blank the field, and if that triggers align.
19579 (and (featurep 'org-table) org-table-auto-blank-field
19580 (memq last-command
19581 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19582 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19583 ;; Got extra space, this field does not determine
19584 ;; column width.
19585 (let (org-table-may-need-update) (org-table-blank-field))
19586 ;; No extra space, this field may determine column
19587 ;; width.
19588 (org-table-blank-field)))
19590 (looking-at "[^|\n]* \\( \\)|"))
19591 ;; There is room for insertion without re-aligning the table.
19592 (delete-region (match-beginning 1) (match-end 1))
19593 (self-insert-command N))
19595 (setq org-table-may-need-update t)
19596 (self-insert-command N)
19597 (org-fix-tags-on-the-fly)
19598 (when org-self-insert-cluster-for-undo
19599 (if (not (eq last-command 'org-self-insert-command))
19600 (setq org-self-insert-command-undo-counter 1)
19601 (if (>= org-self-insert-command-undo-counter 20)
19602 (setq org-self-insert-command-undo-counter 1)
19603 (and (> org-self-insert-command-undo-counter 0)
19604 buffer-undo-list (listp buffer-undo-list)
19605 (not (cadr buffer-undo-list)) ; remove nil entry
19606 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19607 (setq org-self-insert-command-undo-counter
19608 (1+ org-self-insert-command-undo-counter))))))))
19610 (defun org-check-before-invisible-edit (kind)
19611 "Check is editing if kind KIND would be dangerous with invisible text around.
19612 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19613 ;; First, try to get out of here as quickly as possible, to reduce overhead
19614 (when (and org-catch-invisible-edits
19615 (or (not (boundp 'visible-mode)) (not visible-mode))
19616 (or (get-char-property (point) 'invisible)
19617 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19618 ;; OK, we need to take a closer look. Do not consider
19619 ;; invisibility obtained through text properties (e.g., link
19620 ;; fontification), as it cannot be toggled.
19621 (let* ((invisible-at-point
19622 (pcase (get-char-property-and-overlay (point) 'invisible)
19623 (`(,_ . ,(and (pred overlayp) o)) o)))
19624 ;; Assume that point cannot land in the middle of an
19625 ;; overlay, or between two overlays.
19626 (invisible-before-point
19627 (and (not invisible-at-point)
19628 (not (bobp))
19629 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19630 (`(,_ . ,(and (pred overlayp) o)) o))))
19631 (border-and-ok-direction
19633 ;; Check if we are acting predictably before invisible
19634 ;; text.
19635 (and invisible-at-point
19636 (memq kind '(insert delete-backward)))
19637 ;; Check if we are acting predictably after invisible text
19638 ;; This works not well, and I have turned it off. It seems
19639 ;; better to always show and stop after invisible text.
19640 ;; (and (not invisible-at-point) invisible-before-point
19641 ;; (memq kind '(insert delete)))
19643 (when (or invisible-at-point invisible-before-point)
19644 (when (eq org-catch-invisible-edits 'error)
19645 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19646 (if (and org-custom-properties-overlays
19647 (y-or-n-p "Display invisible properties in this buffer? "))
19648 (org-toggle-custom-properties-visibility)
19649 ;; Make the area visible
19650 (save-excursion
19651 (when invisible-before-point
19652 (goto-char
19653 (previous-single-char-property-change (point) 'invisible)))
19654 ;; Remove whatever overlay is currently making yet-to-be
19655 ;; edited text invisible. Also remove nested invisibility
19656 ;; related overlays.
19657 (delete-overlay (or invisible-at-point invisible-before-point))
19658 (let ((origin (if invisible-at-point (point) (1- (point)))))
19659 (while (pcase (get-char-property-and-overlay origin 'invisible)
19660 (`(,_ . ,(and (pred overlayp) o))
19661 (delete-overlay o)
19662 t)))))
19663 (cond
19664 ((eq org-catch-invisible-edits 'show)
19665 ;; That's it, we do the edit after showing
19666 (message
19667 "Unfolding invisible region around point before editing")
19668 (sit-for 1))
19669 ((and (eq org-catch-invisible-edits 'smart)
19670 border-and-ok-direction)
19671 (message "Unfolding invisible region around point before editing"))
19673 ;; Don't do the edit, make the user repeat it in full visibility
19674 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19676 (defun org-fix-tags-on-the-fly ()
19677 "Align tags in headline at point.
19678 Unlike to `org-set-tags', it ignores region and sorting."
19679 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19680 (org-at-heading-p))
19681 (let ((org-ignore-region t)
19682 (org-tags-sort-function nil))
19683 (org-set-tags nil t))))
19685 (defun org-delete-backward-char (N)
19686 "Like `delete-backward-char', insert whitespace at field end in tables.
19687 When deleting backwards, in tables this function will insert whitespace in
19688 front of the next \"|\" separator, to keep the table aligned. The table will
19689 still be marked for re-alignment if the field did fill the entire column,
19690 because, in this case the deletion might narrow the column."
19691 (interactive "p")
19692 (save-match-data
19693 (org-check-before-invisible-edit 'delete-backward)
19694 (if (and (org-at-table-p)
19695 (eq N 1)
19696 (not (org-region-active-p))
19697 (string-match "|" (buffer-substring (point-at-bol) (point)))
19698 (looking-at ".*?|"))
19699 (let ((pos (point))
19700 (noalign (looking-at "[^|\n\r]* |"))
19701 (c org-table-may-need-update))
19702 (backward-delete-char N)
19703 (unless overwrite-mode
19704 (skip-chars-forward "^|")
19705 (insert " ")
19706 (goto-char (1- pos)))
19707 ;; noalign: if there were two spaces at the end, this field
19708 ;; does not determine the width of the column.
19709 (when noalign (setq org-table-may-need-update c)))
19710 (backward-delete-char N)
19711 (org-fix-tags-on-the-fly))))
19713 (defun org-delete-char (N)
19714 "Like `delete-char', but insert whitespace at field end in tables.
19715 When deleting characters, in tables this function will insert whitespace in
19716 front of the next \"|\" separator, to keep the table aligned. The table will
19717 still be marked for re-alignment if the field did fill the entire column,
19718 because, in this case the deletion might narrow the column."
19719 (interactive "p")
19720 (save-match-data
19721 (org-check-before-invisible-edit 'delete)
19722 (if (and (org-at-table-p)
19723 (not (bolp))
19724 (not (= (char-after) ?|))
19725 (eq N 1))
19726 (if (looking-at ".*?|")
19727 (let ((pos (point))
19728 (noalign (looking-at "[^|\n\r]* |"))
19729 (c org-table-may-need-update))
19730 (replace-match
19731 (concat (substring (match-string 0) 1 -1) " |") nil t)
19732 (goto-char pos)
19733 ;; noalign: if there were two spaces at the end, this field
19734 ;; does not determine the width of the column.
19735 (when noalign (setq org-table-may-need-update c)))
19736 (delete-char N))
19737 (delete-char N)
19738 (org-fix-tags-on-the-fly))))
19740 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19741 (put 'org-self-insert-command 'delete-selection
19742 (lambda ()
19743 (not (run-hook-with-args-until-success
19744 'self-insert-uses-region-functions))))
19745 (put 'orgtbl-self-insert-command 'delete-selection
19746 (lambda ()
19747 (not (run-hook-with-args-until-success
19748 'self-insert-uses-region-functions))))
19749 (put 'org-delete-char 'delete-selection 'supersede)
19750 (put 'org-delete-backward-char 'delete-selection 'supersede)
19751 (put 'org-yank 'delete-selection 'yank)
19753 ;; Make `flyspell-mode' delay after some commands
19754 (put 'org-self-insert-command 'flyspell-delayed t)
19755 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19756 (put 'org-delete-char 'flyspell-delayed t)
19757 (put 'org-delete-backward-char 'flyspell-delayed t)
19759 ;; Make pabbrev-mode expand after Org mode commands
19760 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19761 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19763 (defun org-transpose-words ()
19764 "Transpose words for Org.
19765 This uses the `org-mode-transpose-word-syntax-table' syntax
19766 table, which interprets characters in `org-emphasis-alist' as
19767 word constituents."
19768 (interactive)
19769 (with-syntax-table org-mode-transpose-word-syntax-table
19770 (call-interactively 'transpose-words)))
19771 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19773 (defvar org-ctrl-c-ctrl-c-hook nil
19774 "Hook for functions attaching themselves to `C-c C-c'.
19776 This can be used to add additional functionality to the C-c C-c
19777 key which executes context-dependent commands. This hook is run
19778 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19779 run after the last test.
19781 Each function will be called with no arguments. The function
19782 must check if the context is appropriate for it to act. If yes,
19783 it should do its thing and then return a non-nil value. If the
19784 context is wrong, just do nothing and return nil.")
19786 (defvar org-ctrl-c-ctrl-c-final-hook nil
19787 "Hook for functions attaching themselves to `C-c C-c'.
19789 This can be used to add additional functionality to the C-c C-c
19790 key which executes context-dependent commands. This hook is run
19791 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19792 before the first test.
19794 Each function will be called with no arguments. The function
19795 must check if the context is appropriate for it to act. If yes,
19796 it should do its thing and then return a non-nil value. If the
19797 context is wrong, just do nothing and return nil.")
19799 (defvar org-tab-first-hook nil
19800 "Hook for functions to attach themselves to TAB.
19801 See `org-ctrl-c-ctrl-c-hook' for more information.
19802 This hook runs as the first action when TAB is pressed, even before
19803 `org-cycle' messes around with the `outline-regexp' to cater for
19804 inline tasks and plain list item folding.
19805 If any function in this hook returns t, any other actions that
19806 would have been caused by TAB (such as table field motion or visibility
19807 cycling) will not occur.")
19809 (defvar org-tab-after-check-for-table-hook nil
19810 "Hook for functions to attach themselves to TAB.
19811 See `org-ctrl-c-ctrl-c-hook' for more information.
19812 This hook runs after it has been established that the cursor is not in a
19813 table, but before checking if the cursor is in a headline or if global cycling
19814 should be done.
19815 If any function in this hook returns t, not other actions like visibility
19816 cycling will be done.")
19818 (defvar org-tab-after-check-for-cycling-hook nil
19819 "Hook for functions to attach themselves to TAB.
19820 See `org-ctrl-c-ctrl-c-hook' for more information.
19821 This hook runs after it has been established that not table field motion and
19822 not visibility should be done because of current context. This is probably
19823 the place where a package like yasnippets can hook in.")
19825 (defvar org-tab-before-tab-emulation-hook nil
19826 "Hook for functions to attach themselves to TAB.
19827 See `org-ctrl-c-ctrl-c-hook' for more information.
19828 This hook runs after every other options for TAB have been exhausted, but
19829 before indentation and \t insertion takes place.")
19831 (defvar org-metaleft-hook nil
19832 "Hook for functions attaching themselves to `M-left'.
19833 See `org-ctrl-c-ctrl-c-hook' for more information.")
19834 (defvar org-metaright-hook nil
19835 "Hook for functions attaching themselves to `M-right'.
19836 See `org-ctrl-c-ctrl-c-hook' for more information.")
19837 (defvar org-metaup-hook nil
19838 "Hook for functions attaching themselves to `M-up'.
19839 See `org-ctrl-c-ctrl-c-hook' for more information.")
19840 (defvar org-metadown-hook nil
19841 "Hook for functions attaching themselves to `M-down'.
19842 See `org-ctrl-c-ctrl-c-hook' for more information.")
19843 (defvar org-shiftmetaleft-hook nil
19844 "Hook for functions attaching themselves to `M-S-left'.
19845 See `org-ctrl-c-ctrl-c-hook' for more information.")
19846 (defvar org-shiftmetaright-hook nil
19847 "Hook for functions attaching themselves to `M-S-right'.
19848 See `org-ctrl-c-ctrl-c-hook' for more information.")
19849 (defvar org-shiftmetaup-hook nil
19850 "Hook for functions attaching themselves to `M-S-up'.
19851 See `org-ctrl-c-ctrl-c-hook' for more information.")
19852 (defvar org-shiftmetadown-hook nil
19853 "Hook for functions attaching themselves to `M-S-down'.
19854 See `org-ctrl-c-ctrl-c-hook' for more information.")
19855 (defvar org-metareturn-hook nil
19856 "Hook for functions attaching themselves to `M-RET'.
19857 See `org-ctrl-c-ctrl-c-hook' for more information.")
19858 (defvar org-shiftup-hook nil
19859 "Hook for functions attaching themselves to `S-up'.
19860 See `org-ctrl-c-ctrl-c-hook' for more information.")
19861 (defvar org-shiftup-final-hook nil
19862 "Hook for functions attaching themselves to `S-up'.
19863 This one runs after all other options except shift-select have been excluded.
19864 See `org-ctrl-c-ctrl-c-hook' for more information.")
19865 (defvar org-shiftdown-hook nil
19866 "Hook for functions attaching themselves to `S-down'.
19867 See `org-ctrl-c-ctrl-c-hook' for more information.")
19868 (defvar org-shiftdown-final-hook nil
19869 "Hook for functions attaching themselves to `S-down'.
19870 This one runs after all other options except shift-select have been excluded.
19871 See `org-ctrl-c-ctrl-c-hook' for more information.")
19872 (defvar org-shiftleft-hook nil
19873 "Hook for functions attaching themselves to `S-left'.
19874 See `org-ctrl-c-ctrl-c-hook' for more information.")
19875 (defvar org-shiftleft-final-hook nil
19876 "Hook for functions attaching themselves to `S-left'.
19877 This one runs after all other options except shift-select have been excluded.
19878 See `org-ctrl-c-ctrl-c-hook' for more information.")
19879 (defvar org-shiftright-hook nil
19880 "Hook for functions attaching themselves to `S-right'.
19881 See `org-ctrl-c-ctrl-c-hook' for more information.")
19882 (defvar org-shiftright-final-hook nil
19883 "Hook for functions attaching themselves to `S-right'.
19884 This one runs after all other options except shift-select have been excluded.
19885 See `org-ctrl-c-ctrl-c-hook' for more information.")
19887 (defun org-modifier-cursor-error ()
19888 "Throw an error, a modified cursor command was applied in wrong context."
19889 (user-error "This command is active in special context like tables, headlines or items"))
19891 (defun org-shiftselect-error ()
19892 "Throw an error because Shift-Cursor command was applied in wrong context."
19893 (if (and (boundp 'shift-select-mode) shift-select-mode)
19894 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19895 (user-error "This command works only in special context like headlines or timestamps")))
19897 (defun org-call-for-shift-select (cmd)
19898 (let ((this-command-keys-shift-translated t))
19899 (call-interactively cmd)))
19901 (defun org-shifttab (&optional arg)
19902 "Global visibility cycling or move to previous table field.
19903 Call `org-table-previous-field' within a table.
19904 When ARG is nil, cycle globally through visibility states.
19905 When ARG is a numeric prefix, show contents of this level."
19906 (interactive "P")
19907 (cond
19908 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19909 ((integerp arg)
19910 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19911 (message "Content view to level: %d" arg)
19912 (org-content (prefix-numeric-value arg2))
19913 (org-cycle-show-empty-lines t)
19914 (setq org-cycle-global-status 'overview)))
19915 (t (call-interactively 'org-global-cycle))))
19917 (defun org-shiftmetaleft ()
19918 "Promote subtree or delete table column.
19919 Calls `org-promote-subtree', `org-outdent-item-tree', or
19920 `org-table-delete-column', depending on context. See the
19921 individual commands for more information."
19922 (interactive)
19923 (cond
19924 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19925 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19926 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19927 ((if (not (org-region-active-p)) (org-at-item-p)
19928 (save-excursion (goto-char (region-beginning))
19929 (org-at-item-p)))
19930 (call-interactively 'org-outdent-item-tree))
19931 (t (org-modifier-cursor-error))))
19933 (defun org-shiftmetaright ()
19934 "Demote subtree or insert table column.
19935 Calls `org-demote-subtree', `org-indent-item-tree', or
19936 `org-table-insert-column', depending on context. See the
19937 individual commands for more information."
19938 (interactive)
19939 (cond
19940 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19941 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19942 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19943 ((if (not (org-region-active-p)) (org-at-item-p)
19944 (save-excursion (goto-char (region-beginning))
19945 (org-at-item-p)))
19946 (call-interactively 'org-indent-item-tree))
19947 (t (org-modifier-cursor-error))))
19949 (defun org-shiftmetaup (&optional _arg)
19950 "Drag the line at point up.
19951 In a table, kill the current row.
19952 On a clock timestamp, update the value of the timestamp like `S-<up>'
19953 but also adjust the previous clocked item in the clock history.
19954 Everywhere else, drag the line at point up."
19955 (interactive "P")
19956 (cond
19957 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19958 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19959 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19960 (call-interactively 'org-timestamp-up)))
19961 (t (call-interactively 'org-drag-line-backward))))
19963 (defun org-shiftmetadown (&optional _arg)
19964 "Drag the line at point down.
19965 In a table, insert an empty row at the current line.
19966 On a clock timestamp, update the value of the timestamp like `S-<down>'
19967 but also adjust the previous clocked item in the clock history.
19968 Everywhere else, drag the line at point down."
19969 (interactive "P")
19970 (cond
19971 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19972 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19973 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19974 (call-interactively 'org-timestamp-down)))
19975 (t (call-interactively 'org-drag-line-forward))))
19977 (defsubst org-hidden-tree-error ()
19978 (user-error
19979 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19981 (defun org-metaleft (&optional _arg)
19982 "Promote heading, list item at point or move table column left.
19984 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19985 depending on context. With no specific context, calls the Emacs
19986 default `backward-word'. See the individual commands for more
19987 information.
19989 This function runs the hook `org-metaleft-hook' as a first step,
19990 and returns at first non-nil value."
19991 (interactive "P")
19992 (cond
19993 ((run-hook-with-args-until-success 'org-metaleft-hook))
19994 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19995 ((org-with-limited-levels
19996 (or (org-at-heading-p)
19997 (and (org-region-active-p)
19998 (save-excursion
19999 (goto-char (region-beginning))
20000 (org-at-heading-p)))))
20001 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20002 (call-interactively 'org-do-promote))
20003 ;; At an inline task.
20004 ((org-at-heading-p)
20005 (call-interactively 'org-inlinetask-promote))
20006 ((or (org-at-item-p)
20007 (and (org-region-active-p)
20008 (save-excursion
20009 (goto-char (region-beginning))
20010 (org-at-item-p))))
20011 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20012 (call-interactively 'org-outdent-item))
20013 (t (call-interactively 'backward-word))))
20015 (defun org-metaright (&optional _arg)
20016 "Demote heading, list item at point or move table column right.
20018 In front of a drawer or a block keyword, indent it correctly.
20020 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20021 `org-indent-drawer' or `org-indent-block' depending on context.
20022 With no specific context, calls the Emacs default `forward-word'.
20023 See the individual commands for more information.
20025 This function runs the hook `org-metaright-hook' as a first step,
20026 and returns at first non-nil value."
20027 (interactive "P")
20028 (cond
20029 ((run-hook-with-args-until-success 'org-metaright-hook))
20030 ((org-at-table-p) (call-interactively 'org-table-move-column))
20031 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20032 ((org-at-block-p) (call-interactively 'org-indent-block))
20033 ((org-with-limited-levels
20034 (or (org-at-heading-p)
20035 (and (org-region-active-p)
20036 (save-excursion
20037 (goto-char (region-beginning))
20038 (org-at-heading-p)))))
20039 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20040 (call-interactively 'org-do-demote))
20041 ;; At an inline task.
20042 ((org-at-heading-p)
20043 (call-interactively 'org-inlinetask-demote))
20044 ((or (org-at-item-p)
20045 (and (org-region-active-p)
20046 (save-excursion
20047 (goto-char (region-beginning))
20048 (org-at-item-p))))
20049 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20050 (call-interactively 'org-indent-item))
20051 (t (call-interactively 'forward-word))))
20053 (defun org-check-for-hidden (what)
20054 "Check if there are hidden headlines/items in the current visual line.
20055 WHAT can be either `headlines' or `items'. If the current line is
20056 an outline or item heading and it has a folded subtree below it,
20057 this function returns t, nil otherwise."
20058 (let ((re (cond
20059 ((eq what 'headlines) org-outline-regexp-bol)
20060 ((eq what 'items) (org-item-beginning-re))
20061 (t (error "This should not happen"))))
20062 beg end)
20063 (save-excursion
20064 (catch 'exit
20065 (unless (org-region-active-p)
20066 (setq beg (point-at-bol))
20067 (beginning-of-line 2)
20068 (while (and (not (eobp)) ;; this is like `next-line'
20069 (get-char-property (1- (point)) 'invisible))
20070 (beginning-of-line 2))
20071 (setq end (point))
20072 (goto-char beg)
20073 (goto-char (point-at-eol))
20074 (setq end (max end (point)))
20075 (while (re-search-forward re end t)
20076 (when (get-char-property (match-beginning 0) 'invisible)
20077 (throw 'exit t))))
20078 nil))))
20080 (defun org-metaup (&optional _arg)
20081 "Move subtree up or move table row up.
20082 Calls `org-move-subtree-up' or `org-table-move-row' or
20083 `org-move-item-up', depending on context. See the individual commands
20084 for more information."
20085 (interactive "P")
20086 (cond
20087 ((run-hook-with-args-until-success 'org-metaup-hook))
20088 ((org-region-active-p)
20089 (let* ((a (min (region-beginning) (region-end)))
20090 (b (1- (max (region-beginning) (region-end))))
20091 (c (save-excursion (goto-char a)
20092 (move-beginning-of-line 0)))
20093 (d (save-excursion (goto-char a)
20094 (move-end-of-line 0) (point))))
20095 (transpose-regions a b c d)
20096 (goto-char c)))
20097 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20098 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20099 ((org-at-item-p) (call-interactively 'org-move-item-up))
20100 (t (org-drag-element-backward))))
20102 (defun org-metadown (&optional _arg)
20103 "Move subtree down or move table row down.
20104 Calls `org-move-subtree-down' or `org-table-move-row' or
20105 `org-move-item-down', depending on context. See the individual
20106 commands for more information."
20107 (interactive "P")
20108 (cond
20109 ((run-hook-with-args-until-success 'org-metadown-hook))
20110 ((org-region-active-p)
20111 (let* ((a (min (region-beginning) (region-end)))
20112 (b (max (region-beginning) (region-end)))
20113 (c (save-excursion (goto-char b)
20114 (move-beginning-of-line 1)))
20115 (d (save-excursion (goto-char b)
20116 (move-end-of-line 1) (1+ (point)))))
20117 (transpose-regions a b c d)
20118 (goto-char d)))
20119 ((org-at-table-p) (call-interactively 'org-table-move-row))
20120 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20121 ((org-at-item-p) (call-interactively 'org-move-item-down))
20122 (t (org-drag-element-forward))))
20124 (defun org-shiftup (&optional arg)
20125 "Increase item in timestamp or increase priority of current headline.
20126 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20127 depending on context. See the individual commands for more information."
20128 (interactive "P")
20129 (cond
20130 ((run-hook-with-args-until-success 'org-shiftup-hook))
20131 ((and org-support-shift-select (org-region-active-p))
20132 (org-call-for-shift-select 'previous-line))
20133 ((org-at-timestamp-p 'lax)
20134 (call-interactively (if org-edit-timestamp-down-means-later
20135 'org-timestamp-down 'org-timestamp-up)))
20136 ((and (not (eq org-support-shift-select 'always))
20137 org-enable-priority-commands
20138 (org-at-heading-p))
20139 (call-interactively 'org-priority-up))
20140 ((and (not org-support-shift-select) (org-at-item-p))
20141 (call-interactively 'org-previous-item))
20142 ((org-clocktable-try-shift 'up arg))
20143 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20144 (org-support-shift-select
20145 (org-call-for-shift-select 'previous-line))
20146 (t (org-shiftselect-error))))
20148 (defun org-shiftdown (&optional arg)
20149 "Decrease item in timestamp or decrease priority of current headline.
20150 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20151 depending on context. See the individual commands for more information."
20152 (interactive "P")
20153 (cond
20154 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20155 ((and org-support-shift-select (org-region-active-p))
20156 (org-call-for-shift-select 'next-line))
20157 ((org-at-timestamp-p 'lax)
20158 (call-interactively (if org-edit-timestamp-down-means-later
20159 'org-timestamp-up 'org-timestamp-down)))
20160 ((and (not (eq org-support-shift-select 'always))
20161 org-enable-priority-commands
20162 (org-at-heading-p))
20163 (call-interactively 'org-priority-down))
20164 ((and (not org-support-shift-select) (org-at-item-p))
20165 (call-interactively 'org-next-item))
20166 ((org-clocktable-try-shift 'down arg))
20167 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20168 (org-support-shift-select
20169 (org-call-for-shift-select 'next-line))
20170 (t (org-shiftselect-error))))
20172 (defun org-shiftright (&optional arg)
20173 "Cycle the thing at point or in the current line, depending on context.
20174 Depending on context, this does one of the following:
20176 - switch a timestamp at point one day into the future
20177 - on a headline, switch to the next TODO keyword.
20178 - on an item, switch entire list to the next bullet type
20179 - on a property line, switch to the next allowed value
20180 - on a clocktable definition line, move time block into the future"
20181 (interactive "P")
20182 (cond
20183 ((run-hook-with-args-until-success 'org-shiftright-hook))
20184 ((and org-support-shift-select (org-region-active-p))
20185 (org-call-for-shift-select 'forward-char))
20186 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20187 ((and (not (eq org-support-shift-select 'always))
20188 (org-at-heading-p))
20189 (let ((org-inhibit-logging
20190 (not org-treat-S-cursor-todo-selection-as-state-change))
20191 (org-inhibit-blocking
20192 (not org-treat-S-cursor-todo-selection-as-state-change)))
20193 (org-call-with-arg 'org-todo 'right)))
20194 ((or (and org-support-shift-select
20195 (not (eq org-support-shift-select 'always))
20196 (org-at-item-bullet-p))
20197 (and (not org-support-shift-select) (org-at-item-p)))
20198 (org-call-with-arg 'org-cycle-list-bullet nil))
20199 ((and (not (eq org-support-shift-select 'always))
20200 (org-at-property-p))
20201 (call-interactively 'org-property-next-allowed-value))
20202 ((org-clocktable-try-shift 'right arg))
20203 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20204 (org-support-shift-select
20205 (org-call-for-shift-select 'forward-char))
20206 (t (org-shiftselect-error))))
20208 (defun org-shiftleft (&optional arg)
20209 "Cycle the thing at point or in the current line, depending on context.
20210 Depending on context, this does one of the following:
20212 - switch a timestamp at point one day into the past
20213 - on a headline, switch to the previous TODO keyword.
20214 - on an item, switch entire list to the previous bullet type
20215 - on a property line, switch to the previous allowed value
20216 - on a clocktable definition line, move time block into the past"
20217 (interactive "P")
20218 (cond
20219 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20220 ((and org-support-shift-select (org-region-active-p))
20221 (org-call-for-shift-select 'backward-char))
20222 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20223 ((and (not (eq org-support-shift-select 'always))
20224 (org-at-heading-p))
20225 (let ((org-inhibit-logging
20226 (not org-treat-S-cursor-todo-selection-as-state-change))
20227 (org-inhibit-blocking
20228 (not org-treat-S-cursor-todo-selection-as-state-change)))
20229 (org-call-with-arg 'org-todo 'left)))
20230 ((or (and org-support-shift-select
20231 (not (eq org-support-shift-select 'always))
20232 (org-at-item-bullet-p))
20233 (and (not org-support-shift-select) (org-at-item-p)))
20234 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20235 ((and (not (eq org-support-shift-select 'always))
20236 (org-at-property-p))
20237 (call-interactively 'org-property-previous-allowed-value))
20238 ((org-clocktable-try-shift 'left arg))
20239 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20240 (org-support-shift-select
20241 (org-call-for-shift-select 'backward-char))
20242 (t (org-shiftselect-error))))
20244 (defun org-shiftcontrolright ()
20245 "Switch to next TODO set."
20246 (interactive)
20247 (cond
20248 ((and org-support-shift-select (org-region-active-p))
20249 (org-call-for-shift-select 'forward-word))
20250 ((and (not (eq org-support-shift-select 'always))
20251 (org-at-heading-p))
20252 (org-call-with-arg 'org-todo 'nextset))
20253 (org-support-shift-select
20254 (org-call-for-shift-select 'forward-word))
20255 (t (org-shiftselect-error))))
20257 (defun org-shiftcontrolleft ()
20258 "Switch to previous TODO set."
20259 (interactive)
20260 (cond
20261 ((and org-support-shift-select (org-region-active-p))
20262 (org-call-for-shift-select 'backward-word))
20263 ((and (not (eq org-support-shift-select 'always))
20264 (org-at-heading-p))
20265 (org-call-with-arg 'org-todo 'previousset))
20266 (org-support-shift-select
20267 (org-call-for-shift-select 'backward-word))
20268 (t (org-shiftselect-error))))
20270 (defun org-shiftcontrolup (&optional n)
20271 "Change timestamps synchronously up in CLOCK log lines.
20272 Optional argument N tells to change by that many units."
20273 (interactive "P")
20274 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20275 (let (org-support-shift-select)
20276 (org-clock-timestamps-up n))
20277 (user-error "Not at a clock log")))
20279 (defun org-shiftcontroldown (&optional n)
20280 "Change timestamps synchronously down in CLOCK log lines.
20281 Optional argument N tells to change by that many units."
20282 (interactive "P")
20283 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20284 (let (org-support-shift-select)
20285 (org-clock-timestamps-down n))
20286 (user-error "Not at a clock log")))
20288 (defun org-increase-number-at-point (&optional inc)
20289 "Increment the number at point.
20290 With an optional prefix numeric argument INC, increment using
20291 this numeric value."
20292 (interactive "p")
20293 (if (not (number-at-point))
20294 (user-error "Not on a number")
20295 (unless inc (setq inc 1))
20296 (let ((pos (point))
20297 (beg (skip-chars-backward "-+^/*0-9eE."))
20298 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20299 (setq nap (buffer-substring-no-properties
20300 (+ pos beg) (+ pos beg end)))
20301 (delete-region (+ pos beg) (+ pos beg end))
20302 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20303 (when (org-at-table-p)
20304 (org-table-align)
20305 (org-table-end-of-field 1))))
20307 (defun org-decrease-number-at-point (&optional inc)
20308 "Decrement the number at point.
20309 With an optional prefix numeric argument INC, decrement using
20310 this numeric value."
20311 (interactive "p")
20312 (org-increase-number-at-point (- (or inc 1))))
20314 (defun org-ctrl-c-ret ()
20315 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20316 (interactive)
20317 (cond
20318 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20319 (t (call-interactively 'org-insert-heading))))
20321 (defun org-find-visible ()
20322 (let ((s (point)))
20323 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20324 (get-char-property s 'invisible)))
20326 (defun org-find-invisible ()
20327 (let ((s (point)))
20328 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20329 (not (get-char-property s 'invisible))))
20332 (defun org-copy-visible (beg end)
20333 "Copy the visible parts of the region."
20334 (interactive "r")
20335 (let ((result ""))
20336 (while (/= beg end)
20337 (when (get-char-property beg 'invisible)
20338 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20339 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20340 (setq result (concat result (buffer-substring beg next)))
20341 (setq beg next)))
20342 (kill-new result)))
20344 (defun org-copy-special ()
20345 "Copy region in table or copy current subtree.
20346 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20347 context. See the individual commands for more information."
20348 (interactive)
20349 (call-interactively
20350 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20352 (defun org-cut-special ()
20353 "Cut region in table or cut current subtree.
20354 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20355 context. See the individual commands for more information."
20356 (interactive)
20357 (call-interactively
20358 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20360 (defun org-paste-special (arg)
20361 "Paste rectangular region into table, or past subtree relative to level.
20362 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20363 See the individual commands for more information."
20364 (interactive "P")
20365 (if (org-at-table-p)
20366 (org-table-paste-rectangle)
20367 (org-paste-subtree arg)))
20369 (defun org-edit-special (&optional arg)
20370 "Call a special editor for the element at point.
20371 When at a table, call the formula editor with `org-table-edit-formulas'.
20372 When in a source code block, call `org-edit-src-code'.
20373 When in a fixed-width region, call `org-edit-fixed-width-region'.
20374 When in an export block, call `org-edit-export-block'.
20375 When in a LaTeX environment, call `org-edit-latex-environment'.
20376 When at an #+INCLUDE keyword, visit the included file.
20377 When at a footnote reference, call `org-edit-footnote-reference'
20378 On a link, call `ffap' to visit the link at point.
20379 Otherwise, return a user error."
20380 (interactive "P")
20381 (let ((element (org-element-at-point)))
20382 (barf-if-buffer-read-only)
20383 (pcase (org-element-type element)
20384 (`src-block
20385 (if (not arg) (org-edit-src-code)
20386 (let* ((info (org-babel-get-src-block-info))
20387 (lang (nth 0 info))
20388 (params (nth 2 info))
20389 (session (cdr (assq :session params))))
20390 (if (not session) (org-edit-src-code)
20391 ;; At a src-block with a session and function called with
20392 ;; an ARG: switch to the buffer related to the inferior
20393 ;; process.
20394 (switch-to-buffer
20395 (funcall (intern (concat "org-babel-prep-session:" lang))
20396 session params))))))
20397 (`keyword
20398 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20399 (org-open-link-from-string
20400 (format "[[%s]]"
20401 (expand-file-name
20402 (let ((value (org-element-property :value element)))
20403 (cond ((org-file-url-p value)
20404 (user-error "The file is specified as a URL, cannot be edited"))
20405 ((not (org-string-nw-p value))
20406 (user-error "No file to edit"))
20407 ((string-match "\\`\"\\(.*?\\)\"" value)
20408 (match-string 1 value))
20409 ((string-match "\\`[^ \t\"]\\S-*" value)
20410 (match-string 0 value))
20411 (t (user-error "No valid file specified")))))))
20412 (user-error "No special environment to edit here")))
20413 (`table
20414 (if (eq (org-element-property :type element) 'table.el)
20415 (org-edit-table.el)
20416 (call-interactively 'org-table-edit-formulas)))
20417 ;; Only Org tables contain `table-row' type elements.
20418 (`table-row (call-interactively 'org-table-edit-formulas))
20419 (`example-block (org-edit-src-code))
20420 (`export-block (org-edit-export-block))
20421 (`fixed-width (org-edit-fixed-width-region))
20422 (`latex-environment (org-edit-latex-environment))
20424 ;; No notable element at point. Though, we may be at a link or
20425 ;; a footnote reference, which are objects. Thus, scan deeper.
20426 (let ((context (org-element-context element)))
20427 (pcase (org-element-type context)
20428 (`footnote-reference (org-edit-footnote-reference))
20429 (`inline-src-block (org-edit-inline-src-code))
20430 (`link (call-interactively #'ffap))
20431 (_ (user-error "No special environment to edit here"))))))))
20433 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20434 (defun org-ctrl-c-ctrl-c (&optional arg)
20435 "Set tags in headline, or update according to changed information at point.
20437 This command does many different things, depending on context:
20439 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20440 this is what we do.
20442 - If the cursor is on a statistics cookie, update it.
20444 - If the cursor is in a headline, prompt for tags and insert them
20445 into the current line, aligned to `org-tags-column'. When called
20446 with prefix arg, realign all tags in the current buffer.
20448 - If the cursor is in one of the special #+KEYWORD lines, this
20449 triggers scanning the buffer for these lines and updating the
20450 information.
20452 - If the cursor is inside a table, realign the table. This command
20453 works even if the automatic table editor has been turned off.
20455 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20456 the entire table.
20458 - If the cursor is at a footnote reference or definition, jump to
20459 the corresponding definition or references, respectively.
20461 - If the cursor is a the beginning of a dynamic block, update it.
20463 - If the current buffer is a capture buffer, close note and file it.
20465 - If the cursor is on a <<<target>>>, update radio targets and
20466 corresponding links in this buffer.
20468 - If the cursor is on a numbered item in a plain list, renumber the
20469 ordered list.
20471 - If the cursor is on a checkbox, toggle it.
20473 - If the cursor is on a code block, evaluate it. The variable
20474 `org-confirm-babel-evaluate' can be used to control prompting
20475 before code block evaluation, by default every code block
20476 evaluation requires confirmation. Code block evaluation can be
20477 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20478 (interactive "P")
20479 (cond
20480 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20481 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20482 (org-remove-occur-highlights)
20483 (message "Temporary highlights/overlays removed from current buffer"))
20484 ((and (local-variable-p 'org-finish-function)
20485 (fboundp org-finish-function))
20486 (funcall org-finish-function))
20487 ((org-babel-hash-at-point))
20488 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20490 (let* ((context
20491 (org-element-lineage
20492 (org-element-context)
20493 ;; Limit to supported contexts.
20494 '(babel-call clock dynamic-block footnote-definition
20495 footnote-reference inline-babel-call inline-src-block
20496 inlinetask item keyword node-property paragraph
20497 plain-list planning property-drawer radio-target
20498 src-block statistics-cookie table table-cell table-row
20499 timestamp)
20501 (type (org-element-type context)))
20502 ;; For convenience: at the first line of a paragraph on the same
20503 ;; line as an item, apply function on that item instead.
20504 (when (eq type 'paragraph)
20505 (let ((parent (org-element-property :parent context)))
20506 (when (and (eq (org-element-type parent) 'item)
20507 (= (line-beginning-position)
20508 (org-element-property :begin parent)))
20509 (setq context parent)
20510 (setq type 'item))))
20511 ;; Act according to type of element or object at point.
20513 ;; Do nothing on a blank line, except if it is contained in
20514 ;; a src block. Hence, we first check if point is in such
20515 ;; a block and then if it is at a blank line.
20516 (pcase type
20517 ((or `inline-src-block `src-block)
20518 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20519 (org-babel-eval-wipe-error-buffer)
20520 (org-babel-execute-src-block
20521 current-prefix-arg (org-babel-get-src-block-info nil context))))
20522 ((guard (org-match-line "[ \t]*$"))
20523 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20524 (user-error
20525 (substitute-command-keys
20526 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20527 ((or `babel-call `inline-babel-call)
20528 (let ((info (org-babel-lob-get-info context)))
20529 (when info (org-babel-execute-src-block nil info))))
20530 (`clock (org-clock-update-time-maybe))
20531 (`dynamic-block
20532 (save-excursion
20533 (goto-char (org-element-property :post-affiliated context))
20534 (org-update-dblock)))
20535 (`footnote-definition
20536 (goto-char (org-element-property :post-affiliated context))
20537 (call-interactively 'org-footnote-action))
20538 (`footnote-reference (call-interactively #'org-footnote-action))
20539 ((or `headline `inlinetask)
20540 (save-excursion (goto-char (org-element-property :begin context))
20541 (call-interactively #'org-set-tags)))
20542 (`item
20543 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20544 ;; unconditionally, whereas `C-u' will toggle its presence.
20545 ;; Without a universal argument, if the item has a checkbox,
20546 ;; toggle it. Otherwise repair the list.
20547 (let* ((box (org-element-property :checkbox context))
20548 (struct (org-element-property :structure context))
20549 (old-struct (copy-tree struct))
20550 (parents (org-list-parents-alist struct))
20551 (prevs (org-list-prevs-alist struct))
20552 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20553 (org-list-set-checkbox
20554 (org-element-property :begin context) struct
20555 (cond ((equal arg '(16)) "[-]")
20556 ((and (not box) (equal arg '(4))) "[ ]")
20557 ((or (not box) (equal arg '(4))) nil)
20558 ((eq box 'on) "[ ]")
20559 (t "[X]")))
20560 ;; Mimic `org-list-write-struct' but with grabbing a return
20561 ;; value from `org-list-struct-fix-box'.
20562 (org-list-struct-fix-ind struct parents 2)
20563 (org-list-struct-fix-item-end struct)
20564 (org-list-struct-fix-bul struct prevs)
20565 (org-list-struct-fix-ind struct parents)
20566 (let ((block-item
20567 (org-list-struct-fix-box struct parents prevs orderedp)))
20568 (if (and box (equal struct old-struct))
20569 (if (equal arg '(16))
20570 (message "Checkboxes already reset")
20571 (user-error "Cannot toggle this checkbox: %s"
20572 (if (eq box 'on)
20573 "all subitems checked"
20574 "unchecked subitems")))
20575 (org-list-struct-apply-struct struct old-struct)
20576 (org-update-checkbox-count-maybe))
20577 (when block-item
20578 (message "Checkboxes were removed due to empty box at line %d"
20579 (org-current-line block-item))))))
20580 (`keyword
20581 (let ((org-inhibit-startup-visibility-stuff t)
20582 (org-startup-align-all-tables nil))
20583 (when (boundp 'org-table-coordinate-overlays)
20584 (mapc #'delete-overlay org-table-coordinate-overlays)
20585 (setq org-table-coordinate-overlays nil))
20586 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20587 (message "Local setup has been refreshed"))
20588 (`plain-list
20589 ;; At a plain list, with a double C-u argument, set
20590 ;; checkboxes of each item to "[-]", whereas a single one
20591 ;; will toggle their presence according to the state of the
20592 ;; first item in the list. Without an argument, repair the
20593 ;; list.
20594 (let* ((begin (org-element-property :contents-begin context))
20595 (beginm (move-marker (make-marker) begin))
20596 (struct (org-element-property :structure context))
20597 (old-struct (copy-tree struct))
20598 (first-box (save-excursion
20599 (goto-char begin)
20600 (looking-at org-list-full-item-re)
20601 (match-string-no-properties 3)))
20602 (new-box (cond ((equal arg '(16)) "[-]")
20603 ((equal arg '(4)) (unless first-box "[ ]"))
20604 ((equal first-box "[X]") "[ ]")
20605 (t "[X]"))))
20606 (cond
20607 (arg
20608 (dolist (pos
20609 (org-list-get-all-items
20610 begin struct (org-list-prevs-alist struct)))
20611 (org-list-set-checkbox pos struct new-box)))
20612 ((and first-box (eq (point) begin))
20613 ;; For convenience, when point is at bol on the first
20614 ;; item of the list and no argument is provided, simply
20615 ;; toggle checkbox of that item, if any.
20616 (org-list-set-checkbox begin struct new-box)))
20617 (org-list-write-struct
20618 struct (org-list-parents-alist struct) old-struct)
20619 (org-update-checkbox-count-maybe)
20620 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20621 ((or `property-drawer `node-property)
20622 (call-interactively #'org-property-action))
20623 (`radio-target
20624 (call-interactively #'org-update-radio-target-regexp))
20625 (`statistics-cookie
20626 (call-interactively #'org-update-statistics-cookies))
20627 ((or `table `table-cell `table-row)
20628 ;; At a table, recalculate every field and align it. Also
20629 ;; send the table if necessary. If the table has
20630 ;; a `table.el' type, just give up. At a table row or cell,
20631 ;; maybe recalculate line but always align table.
20632 (if (eq (org-element-property :type context) 'table.el)
20633 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20634 Use `\\[org-edit-special]' to edit table.el tables"))
20635 (if (or (eq type 'table)
20636 ;; Check if point is at a TBLFM line.
20637 (and (eq type 'table-row)
20638 (= (point) (org-element-property :end context))))
20639 (save-excursion
20640 (if (org-at-TBLFM-p)
20641 (progn (require 'org-table)
20642 (org-table-calc-current-TBLFM))
20643 (goto-char (org-element-property :contents-begin context))
20644 (org-call-with-arg 'org-table-recalculate (or arg t))
20645 (orgtbl-send-table 'maybe)))
20646 (org-table-maybe-eval-formula)
20647 (cond (arg (call-interactively #'org-table-recalculate))
20648 ((org-table-maybe-recalculate-line))
20649 (t (org-table-align))))))
20650 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20651 (org-timestamp-change 0 'day))
20652 ((and `nil (guard (org-at-heading-p)))
20653 ;; When point is on an unsupported object type, we can miss
20654 ;; the fact that it also is at a heading. Handle it here.
20655 (call-interactively #'org-set-tags))
20656 ((guard
20657 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20659 (user-error
20660 (substitute-command-keys
20661 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20663 (defun org-mode-restart ()
20664 (interactive)
20665 (let ((indent-status (bound-and-true-p org-indent-mode)))
20666 (funcall major-mode)
20667 (hack-local-variables)
20668 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20669 (org-indent-mode -1))
20670 (org-reset-file-cache))
20671 (message "%s restarted" major-mode))
20673 (defun org-kill-note-or-show-branches ()
20674 "Abort storing current note, or call `outline-show-branches'."
20675 (interactive)
20676 (if (not org-finish-function)
20677 (progn
20678 (outline-hide-subtree)
20679 (call-interactively 'outline-show-branches))
20680 (let ((org-note-abort t))
20681 (funcall org-finish-function))))
20683 (defun org-delete-indentation (&optional arg)
20684 "Join current line to previous and fix whitespace at join.
20686 If previous line is a headline add to headline title. Otherwise
20687 the function calls `delete-indentation'.
20689 With a non-nil optional argument, join it to the following one."
20690 (interactive "*P")
20691 (if (save-excursion
20692 (beginning-of-line (if arg 1 0))
20693 (let ((case-fold-search nil))
20694 (looking-at org-complex-heading-regexp)))
20695 ;; At headline.
20696 (let ((tags-column (when (match-beginning 5)
20697 (save-excursion (goto-char (match-beginning 5))
20698 (current-column))))
20699 (string (concat " " (progn (when arg (forward-line 1))
20700 (org-trim (delete-and-extract-region
20701 (line-beginning-position)
20702 (line-end-position)))))))
20703 (unless (bobp) (delete-region (point) (1- (point))))
20704 (goto-char (or (match-end 4)
20705 (match-beginning 5)
20706 (match-end 0)))
20707 (skip-chars-backward " \t")
20708 (save-excursion (insert string))
20709 ;; Adjust alignment of tags.
20710 (cond
20711 ((not tags-column)) ;no tags
20712 (org-auto-align-tags (org-set-tags nil t))
20713 (t (org--align-tags-here tags-column)))) ;preserve tags column
20714 (delete-indentation arg)))
20716 (defun org-open-line (n)
20717 "Insert a new row in tables, call `open-line' elsewhere.
20718 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20719 As a special case, when a document starts with a table, allow to
20720 call `open-line' on the very first character."
20721 (interactive "*p")
20722 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20723 (org-table-insert-row)
20724 (open-line n)))
20726 (defun org-return (&optional indent)
20727 "Goto next table row or insert a newline.
20729 Calls `org-table-next-row' or `newline', depending on context.
20731 When optional INDENT argument is non-nil, call
20732 `newline-and-indent' instead of `newline'.
20734 When `org-return-follows-link' is non-nil and point is on
20735 a timestamp or a link, call `org-open-at-point'. However, it
20736 will not happen if point is in a table or on a \"dead\"
20737 object (e.g., within a comment). In these case, you need to use
20738 `org-open-at-point' directly."
20739 (interactive)
20740 (let ((context (if org-return-follows-link (org-element-context)
20741 (org-element-at-point))))
20742 (cond
20743 ;; In a table, call `org-table-next-row'.
20744 ((or (and (eq (org-element-type context) 'table)
20745 (>= (point) (org-element-property :contents-begin context))
20746 (< (point) (org-element-property :contents-end context)))
20747 (org-element-lineage context '(table-row table-cell) t))
20748 (org-table-justify-field-maybe)
20749 (call-interactively #'org-table-next-row))
20750 ;; On a link or a timestamp, call `org-open-at-point' if
20751 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20752 ;; locations, e.g., in a comment, as `org-open-at-point'.
20753 ((and org-return-follows-link
20754 (or (org-in-regexp org-ts-regexp-both nil t)
20755 (org-in-regexp org-tsr-regexp-both nil t)
20756 (org-in-regexp org-any-link-re nil t)))
20757 (call-interactively #'org-open-at-point))
20758 ;; Insert newline in heading, but preserve tags.
20759 ((and (not (bolp))
20760 (save-excursion (beginning-of-line)
20761 (let ((case-fold-search nil))
20762 (looking-at org-complex-heading-regexp))))
20763 ;; At headline. Split line. However, if point is on keyword,
20764 ;; priority cookie or tags, do not break any of them: add
20765 ;; a newline after the headline instead.
20766 (let ((tags-column (and (match-beginning 5)
20767 (save-excursion (goto-char (match-beginning 5))
20768 (current-column))))
20769 (string
20770 (when (and (match-end 4) (org-point-in-group (point) 4))
20771 (delete-and-extract-region (point) (match-end 4)))))
20772 ;; Adjust tag alignment.
20773 (cond
20774 ((not (and tags-column string)))
20775 (org-auto-align-tags (org-set-tags nil t))
20776 (t (org--align-tags-here tags-column))) ;preserve tags column
20777 (end-of-line)
20778 (org-show-entry)
20779 (if indent (newline-and-indent) (newline))
20780 (when string (save-excursion (insert (org-trim string))))))
20781 ;; In a list, make sure indenting keeps trailing text within.
20782 ((and indent
20783 (not (eolp))
20784 (org-element-lineage context '(item)))
20785 (let ((trailing-data
20786 (delete-and-extract-region (point) (line-end-position))))
20787 (newline-and-indent)
20788 (save-excursion (insert trailing-data))))
20789 (t (if indent (newline-and-indent) (newline))))))
20791 (defun org-return-indent ()
20792 "Goto next table row or insert a newline and indent.
20793 Calls `org-table-next-row' or `newline-and-indent', depending on
20794 context. See the individual commands for more information."
20795 (interactive)
20796 (org-return t))
20798 (defun org-ctrl-c-tab (&optional _arg)
20799 "Toggle columns width in a table, or show children.
20800 Call `org-table-toggle-column-width' if point is in a table.
20801 Otherwise, call `org-show-children'."
20802 (interactive "p")
20803 (call-interactively
20804 (if (org-at-table-p) #'org-table-toggle-column-width
20805 #'org-show-children)))
20807 (defun org-ctrl-c-star ()
20808 "Compute table, or change heading status of lines.
20809 Calls `org-table-recalculate' or `org-toggle-heading',
20810 depending on context."
20811 (interactive)
20812 (cond
20813 ((org-at-table-p)
20814 (call-interactively 'org-table-recalculate))
20816 ;; Convert all lines in region to list items
20817 (call-interactively 'org-toggle-heading))))
20819 (defun org-ctrl-c-minus ()
20820 "Insert separator line in table or modify bullet status of line.
20821 Also turns a plain line or a region of lines into list items.
20822 Calls `org-table-insert-hline', `org-toggle-item', or
20823 `org-cycle-list-bullet', depending on context."
20824 (interactive)
20825 (cond
20826 ((org-at-table-p)
20827 (call-interactively 'org-table-insert-hline))
20828 ((org-region-active-p)
20829 (call-interactively 'org-toggle-item))
20830 ((org-in-item-p)
20831 (call-interactively 'org-cycle-list-bullet))
20833 (call-interactively 'org-toggle-item))))
20835 (defun org-toggle-heading (&optional nstars)
20836 "Convert headings to normal text, or items or text to headings.
20837 If there is no active region, only convert the current line.
20839 With a `\\[universal-argument]' prefix, convert the whole list at
20840 point into heading.
20842 In a region:
20844 - If the first non blank line is a headline, remove the stars
20845 from all headlines in the region.
20847 - If it is a normal line, turn each and every normal line (i.e.,
20848 not an heading or an item) in the region into headings. If you
20849 want to convert only the first line of this region, use one
20850 universal prefix argument.
20852 - If it is a plain list item, turn all plain list items into headings.
20854 When converting a line into a heading, the number of stars is chosen
20855 such that the lines become children of the current entry. However,
20856 when a numeric prefix argument is given, its value determines the
20857 number of stars to add."
20858 (interactive "P")
20859 (let ((skip-blanks
20860 (function
20861 ;; Return beginning of first non-blank line, starting from
20862 ;; line at POS.
20863 (lambda (pos)
20864 (save-excursion
20865 (goto-char pos)
20866 (while (org-at-comment-p) (forward-line))
20867 (skip-chars-forward " \r\t\n")
20868 (point-at-bol)))))
20869 beg end toggled)
20870 ;; Determine boundaries of changes. If a universal prefix has
20871 ;; been given, put the list in a region. If region ends at a bol,
20872 ;; do not consider the last line to be in the region.
20874 (when (and current-prefix-arg (org-at-item-p))
20875 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20876 (org-mark-element))
20878 (if (org-region-active-p)
20879 (setq beg (funcall skip-blanks (region-beginning))
20880 end (copy-marker (save-excursion
20881 (goto-char (region-end))
20882 (if (bolp) (point) (point-at-eol)))))
20883 (setq beg (funcall skip-blanks (point-at-bol))
20884 end (copy-marker (point-at-eol))))
20885 ;; Ensure inline tasks don't count as headings.
20886 (org-with-limited-levels
20887 (save-excursion
20888 (goto-char beg)
20889 (cond
20890 ;; Case 1. Started at an heading: de-star headings.
20891 ((org-at-heading-p)
20892 (while (< (point) end)
20893 (when (org-at-heading-p t)
20894 (looking-at org-outline-regexp) (replace-match "")
20895 (setq toggled t))
20896 (forward-line)))
20897 ;; Case 2. Started at an item: change items into headlines.
20898 ;; One star will be added by `org-list-to-subtree'.
20899 ((org-at-item-p)
20900 (while (< (point) end)
20901 (when (org-at-item-p)
20902 ;; Pay attention to cases when region ends before list.
20903 (let* ((struct (org-list-struct))
20904 (list-end
20905 (min (org-list-get-bottom-point struct) (1+ end))))
20906 (save-restriction
20907 (narrow-to-region (point) list-end)
20908 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20909 (setq toggled t))
20910 (forward-line)))
20911 ;; Case 3. Started at normal text: make every line an heading,
20912 ;; skipping headlines and items.
20913 (t (let* ((stars
20914 (make-string
20915 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20916 (add-stars
20917 (cond (nstars "") ; stars from prefix only
20918 ((equal stars "") "*") ; before first heading
20919 (org-odd-levels-only "**") ; inside heading, odd
20920 (t "*"))) ; inside heading, oddeven
20921 (rpl (concat stars add-stars " "))
20922 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20923 (while (< (point) (if (equal nstars '(4)) lend end))
20924 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20925 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20926 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20927 (forward-line)))))))
20928 (unless toggled (message "Cannot toggle heading from here"))))
20930 (defun org-meta-return (&optional arg)
20931 "Insert a new heading or wrap a region in a table.
20932 Calls `org-insert-heading', `org-insert-item' or
20933 `org-table-wrap-region', depending on context. When called with
20934 an argument, unconditionally call `org-insert-heading'."
20935 (interactive "P")
20936 (org-check-before-invisible-edit 'insert)
20937 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20938 (call-interactively (cond (arg #'org-insert-heading)
20939 ((org-at-table-p) #'org-table-wrap-region)
20940 ((org-in-item-p) #'org-insert-item)
20941 (t #'org-insert-heading)))))
20943 ;;; Menu entries
20945 (defsubst org-in-subtree-not-table-p ()
20946 "Are we in a subtree and not in a table?"
20947 (and (not (org-before-first-heading-p))
20948 (not (org-at-table-p))))
20950 ;; Define the Org mode menus
20951 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20952 '("Tbl"
20953 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20954 ["Next Field" org-cycle (org-at-table-p)]
20955 ["Previous Field" org-shifttab (org-at-table-p)]
20956 ["Next Row" org-return (org-at-table-p)]
20957 "--"
20958 ["Blank Field" org-table-blank-field (org-at-table-p)]
20959 ["Edit Field" org-table-edit-field (org-at-table-p)]
20960 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20961 "--"
20962 ("Column"
20963 ["Move Column Left" org-metaleft (org-at-table-p)]
20964 ["Move Column Right" org-metaright (org-at-table-p)]
20965 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20966 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20967 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20968 ("Row"
20969 ["Move Row Up" org-metaup (org-at-table-p)]
20970 ["Move Row Down" org-metadown (org-at-table-p)]
20971 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20972 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20973 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20974 "--"
20975 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20976 ("Rectangle"
20977 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20978 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20979 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20980 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20981 "--"
20982 ("Calculate"
20983 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20984 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20985 ["Edit Formulas" org-edit-special (org-at-table-p)]
20986 "--"
20987 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20988 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20989 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20990 "--"
20991 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20992 "--"
20993 ["Sum Column/Rectangle" org-table-sum
20994 (or (org-at-table-p) (org-region-active-p))]
20995 ["Which Column?" org-table-current-column (org-at-table-p)])
20996 ["Debug Formulas"
20997 org-table-toggle-formula-debugger
20998 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20999 ["Show Col/Row Numbers"
21000 org-table-toggle-coordinate-overlays
21001 :style toggle
21002 :selected (bound-and-true-p org-table-overlay-coordinates)]
21003 "--"
21004 ["Create" org-table-create (not (org-at-table-p))]
21005 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21006 ["Import from File" org-table-import (not (org-at-table-p))]
21007 ["Export to File" org-table-export (org-at-table-p)]
21008 "--"
21009 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21010 "--"
21011 ("Plot"
21012 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21013 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21015 (easy-menu-define org-org-menu org-mode-map "Org menu"
21016 '("Org"
21017 ("Show/Hide"
21018 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21019 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21020 ["Sparse Tree..." org-sparse-tree t]
21021 ["Reveal Context" org-reveal t]
21022 ["Show All" outline-show-all t]
21023 "--"
21024 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21025 "--"
21026 ["New Heading" org-insert-heading t]
21027 ("Navigate Headings"
21028 ["Up" outline-up-heading t]
21029 ["Next" outline-next-visible-heading t]
21030 ["Previous" outline-previous-visible-heading t]
21031 ["Next Same Level" outline-forward-same-level t]
21032 ["Previous Same Level" outline-backward-same-level t]
21033 "--"
21034 ["Jump" org-goto t])
21035 ("Edit Structure"
21036 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21037 "--"
21038 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21039 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21040 "--"
21041 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21042 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21043 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21044 "--"
21045 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21046 "--"
21047 ["Copy visible text" org-copy-visible t]
21048 "--"
21049 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21050 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21051 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21052 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21053 "--"
21054 ["Sort Region/Children" org-sort t]
21055 "--"
21056 ["Convert to odd levels" org-convert-to-odd-levels t]
21057 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21058 ("Editing"
21059 ["Emphasis..." org-emphasize t]
21060 ["Edit Source Example" org-edit-special t]
21061 "--"
21062 ["Footnote new/jump" org-footnote-action t]
21063 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21064 ("Archive"
21065 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21066 "--"
21067 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21068 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21069 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21071 "--"
21072 ("Hyperlinks"
21073 ["Store Link (Global)" org-store-link t]
21074 ["Find existing link to here" org-occur-link-in-agenda-files t]
21075 ["Insert Link" org-insert-link t]
21076 ["Follow Link" org-open-at-point t]
21077 "--"
21078 ["Next link" org-next-link t]
21079 ["Previous link" org-previous-link t]
21080 "--"
21081 ["Descriptive Links"
21082 org-toggle-link-display
21083 :style radio
21084 :selected org-descriptive-links
21086 ["Literal Links"
21087 org-toggle-link-display
21088 :style radio
21089 :selected (not org-descriptive-links)])
21090 "--"
21091 ("TODO Lists"
21092 ["TODO/DONE/-" org-todo t]
21093 ("Select keyword"
21094 ["Next keyword" org-shiftright (org-at-heading-p)]
21095 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21096 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21097 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21098 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21099 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21100 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21101 "--"
21102 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21103 :selected org-enforce-todo-dependencies :style toggle :active t]
21104 "Settings for tree at point"
21105 ["Do Children sequentially" org-toggle-ordered-property :style radio
21106 :selected (org-entry-get nil "ORDERED")
21107 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21108 ["Do Children parallel" org-toggle-ordered-property :style radio
21109 :selected (not (org-entry-get nil "ORDERED"))
21110 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21111 "--"
21112 ["Set Priority" org-priority t]
21113 ["Priority Up" org-shiftup t]
21114 ["Priority Down" org-shiftdown t]
21115 "--"
21116 ["Get news from all feeds" org-feed-update-all t]
21117 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21118 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21119 ("TAGS and Properties"
21120 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21121 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21122 "--"
21123 ["Set property" org-set-property (not (org-before-first-heading-p))]
21124 ["Column view of properties" org-columns t]
21125 ["Insert Column View DBlock" org-columns-insert-dblock t])
21126 ("Dates and Scheduling"
21127 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21128 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21129 ("Change Date"
21130 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21131 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21132 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21133 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21134 ["Compute Time Range" org-evaluate-time-range t]
21135 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21136 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21137 "--"
21138 ["Custom time format" org-toggle-time-stamp-overlays
21139 :style radio :selected org-display-custom-times]
21140 "--"
21141 ["Goto Calendar" org-goto-calendar t]
21142 ["Date from Calendar" org-date-from-calendar t]
21143 "--"
21144 ["Start/Restart Timer" org-timer-start t]
21145 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21146 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21147 ["Insert Timer String" org-timer t]
21148 ["Insert Timer Item" org-timer-item t])
21149 ("Logging work"
21150 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21151 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21152 ["Clock out" org-clock-out t]
21153 ["Clock cancel" org-clock-cancel t]
21154 "--"
21155 ["Mark as default task" org-clock-mark-default-task t]
21156 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21157 ["Goto running clock" org-clock-goto t]
21158 "--"
21159 ["Display times" org-clock-display t]
21160 ["Create clock table" org-clock-report t]
21161 "--"
21162 ["Record DONE time"
21163 (progn (setq org-log-done (not org-log-done))
21164 (message "Switching to %s will %s record a timestamp"
21165 (car org-done-keywords)
21166 (if org-log-done "automatically" "not")))
21167 :style toggle :selected org-log-done])
21168 "--"
21169 ["Agenda Command..." org-agenda t]
21170 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21171 ("File List for Agenda")
21172 ("Special views current file"
21173 ["TODO Tree" org-show-todo-tree t]
21174 ["Check Deadlines" org-check-deadlines t]
21175 ["Tags/Property tree" org-match-sparse-tree t])
21176 "--"
21177 ["Export/Publish..." org-export-dispatch t]
21178 ("LaTeX"
21179 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21180 :selected org-cdlatex-mode]
21181 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21182 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21183 ["Modify math symbol" org-cdlatex-math-modify
21184 (org-inside-LaTeX-fragment-p)]
21185 ["Insert citation" org-reftex-citation t])
21186 "--"
21187 ("MobileOrg"
21188 ["Push Files and Views" org-mobile-push t]
21189 ["Get Captured and Flagged" org-mobile-pull t]
21190 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21191 "--"
21192 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21193 "--"
21194 ("Documentation"
21195 ["Show Version" org-version t]
21196 ["Info Documentation" org-info t])
21197 ("Customize"
21198 ["Browse Org Group" org-customize t]
21199 "--"
21200 ["Expand This Menu" org-create-customize-menu
21201 (fboundp 'customize-menu-create)])
21202 ["Send bug report" org-submit-bug-report t]
21203 "--"
21204 ("Refresh/Reload"
21205 ["Refresh setup current buffer" org-mode-restart t]
21206 ["Reload Org (after update)" org-reload t]
21207 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21210 (defun org-info (&optional node)
21211 "Read documentation for Org in the info system.
21212 With optional NODE, go directly to that node."
21213 (interactive)
21214 (info (format "(org)%s" (or node ""))))
21216 ;;;###autoload
21217 (defun org-submit-bug-report ()
21218 "Submit a bug report on Org via mail.
21220 Don't hesitate to report any problems or inaccurate documentation.
21222 If you don't have setup sending mail from (X)Emacs, please copy the
21223 output buffer into your mail program, as it gives us important
21224 information about your Org version and configuration."
21225 (interactive)
21226 (require 'reporter)
21227 (defvar reporter-prompt-for-summary-p)
21228 (org-load-modules-maybe)
21229 (org-require-autoloaded-modules)
21230 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21231 (reporter-submit-bug-report
21232 "emacs-orgmode@gnu.org"
21233 (org-version nil 'full)
21234 (let (list)
21235 (save-window-excursion
21236 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21237 (delete-other-windows)
21238 (erase-buffer)
21239 (insert "You are about to submit a bug report to the Org mailing list.
21241 We would like to add your full Org and Outline configuration to the
21242 bug report. This greatly simplifies the work of the maintainer and
21243 other experts on the mailing list.
21245 HOWEVER, some variables you have customized may contain private
21246 information. The names of customers, colleagues, or friends, might
21247 appear in the form of file names, tags, todo states, or search strings.
21248 If you answer yes to the prompt, you might want to check and remove
21249 such private information before sending the email.")
21250 (add-text-properties (point-min) (point-max) '(face org-warning))
21251 (when (yes-or-no-p "Include your Org configuration ")
21252 (mapatoms
21253 (lambda (v)
21254 (and (boundp v)
21255 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21256 (or (and (symbol-value v)
21257 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21258 (and
21259 (get v 'custom-type) (get v 'standard-value)
21260 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21261 (push v list)))))
21262 (kill-buffer (get-buffer "*Warn about privacy*"))
21263 list))
21264 nil nil
21265 "Remember to cover the basics, that is, what you expected to happen and
21266 what in fact did happen. You don't know how to make a good report? See
21268 http://orgmode.org/manual/Feedback.html#Feedback
21270 Your bug report will be posted to the Org mailing list.
21271 ------------------------------------------------------------------------")
21272 (save-excursion
21273 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21274 (replace-match "\\1Bug: \\3 [\\2]")))))
21277 (defun org-install-agenda-files-menu ()
21278 (let ((bl (buffer-list)))
21279 (save-excursion
21280 (while bl
21281 (set-buffer (pop bl))
21282 (when (derived-mode-p 'org-mode) (setq bl nil)))
21283 (when (derived-mode-p 'org-mode)
21284 (easy-menu-change
21285 '("Org") "File List for Agenda"
21286 (append
21287 (list
21288 ["Edit File List" (org-edit-agenda-file-list) t]
21289 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21290 ["Remove Current File from List" org-remove-file t]
21291 ["Cycle through agenda files" org-cycle-agenda-files t]
21292 ["Occur in all agenda files" org-occur-in-agenda-files t]
21293 "--")
21294 (mapcar 'org-file-menu-entry
21295 ;; Prevent initialization from failing.
21296 (ignore-errors (org-agenda-files t)))))))))
21298 ;;;; Documentation
21300 (defun org-require-autoloaded-modules ()
21301 (interactive)
21302 (mapc #'require
21303 '(org-agenda org-archive org-attach org-clock org-colview org-id
21304 org-table org-timer)))
21306 ;;;###autoload
21307 (defun org-reload (&optional uncompiled)
21308 "Reload all org lisp files.
21309 With prefix arg UNCOMPILED, load the uncompiled versions."
21310 (interactive "P")
21311 (require 'loadhist)
21312 (let* ((org-dir (org-find-library-dir "org"))
21313 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21314 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21315 (remove-re (format "\\`%s\\'"
21316 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21317 (feats (delete-dups
21318 (mapcar 'file-name-sans-extension
21319 (mapcar 'file-name-nondirectory
21320 (delq nil
21321 (mapcar 'feature-file
21322 features))))))
21323 (lfeat (append
21324 (sort
21325 (setq feats
21326 (delq nil (mapcar
21327 (lambda (f)
21328 (if (and (string-match feature-re f)
21329 (not (string-match remove-re f)))
21330 f nil))
21331 feats)))
21332 'string-lessp)
21333 (list "org-version" "org")))
21334 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21335 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21336 load-uncore load-misses)
21337 (setq load-misses
21338 (delq 't
21339 (mapcar (lambda (f)
21340 (or (org-load-noerror-mustsuffix (concat org-dir f))
21341 (and (string= org-dir contrib-dir)
21342 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21343 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21344 (add-to-list 'load-uncore f 'append)
21347 lfeat)))
21348 (when load-uncore
21349 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21350 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21351 (if load-misses
21352 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21353 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21354 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21356 ;;;###autoload
21357 (defun org-customize ()
21358 "Call the customize function with org as argument."
21359 (interactive)
21360 (org-load-modules-maybe)
21361 (org-require-autoloaded-modules)
21362 (customize-browse 'org))
21364 (defun org-create-customize-menu ()
21365 "Create a full customization menu for Org mode, insert it into the menu."
21366 (interactive)
21367 (org-load-modules-maybe)
21368 (org-require-autoloaded-modules)
21369 (if (fboundp 'customize-menu-create)
21370 (progn
21371 (easy-menu-change
21372 '("Org") "Customize"
21373 `(["Browse Org group" org-customize t]
21374 "--"
21375 ,(customize-menu-create 'org)
21376 ["Set" Custom-set t]
21377 ["Save" Custom-save t]
21378 ["Reset to Current" Custom-reset-current t]
21379 ["Reset to Saved" Custom-reset-saved t]
21380 ["Reset to Standard Settings" Custom-reset-standard t]))
21381 (message "\"Org\"-menu now contains full customization menu"))
21382 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21384 ;;;; Miscellaneous stuff
21386 ;;; Generally useful functions
21388 (defun org-link-display-format (s)
21389 "Replace links in string S with their description.
21390 If there is no description, use the link target."
21391 (save-match-data
21392 (replace-regexp-in-string
21393 org-bracket-link-analytic-regexp
21394 (lambda (m)
21395 (if (match-end 5) (match-string 5 m)
21396 (concat (match-string 1 m) (match-string 3 m))))
21397 s nil t)))
21399 (defun org-toggle-link-display ()
21400 "Toggle the literal or descriptive display of links."
21401 (interactive)
21402 (if org-descriptive-links
21403 (progn (org-remove-from-invisibility-spec '(org-link))
21404 (org-restart-font-lock)
21405 (setq org-descriptive-links nil))
21406 (progn (add-to-invisibility-spec '(org-link))
21407 (org-restart-font-lock)
21408 (setq org-descriptive-links t))))
21410 (defun org-in-clocktable-p ()
21411 "Check if the cursor is in a clocktable."
21412 (let ((pos (point)) start)
21413 (save-excursion
21414 (end-of-line 1)
21415 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21416 (setq start (match-beginning 0))
21417 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21418 (>= (match-end 0) pos)
21419 start))))
21421 (defun org-in-verbatim-emphasis ()
21422 (save-match-data
21423 (and (org-in-regexp org-verbatim-re 2)
21424 (>= (point) (match-beginning 3))
21425 (<= (point) (match-end 4)))))
21427 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21428 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21429 (if (and marker (marker-buffer marker)
21430 (buffer-live-p (marker-buffer marker)))
21431 (progn
21432 (pop-to-buffer-same-window (marker-buffer marker))
21433 (when (or (> marker (point-max)) (< marker (point-min)))
21434 (widen))
21435 (goto-char marker)
21436 (org-show-context 'org-goto))
21437 (if bookmark
21438 (bookmark-jump bookmark)
21439 (error "Cannot find location"))))
21441 (defun org-quote-csv-field (s)
21442 "Quote field for inclusion in CSV material."
21443 (if (string-match "[\",]" s)
21444 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21447 (defun org-force-self-insert (N)
21448 "Needed to enforce self-insert under remapping."
21449 (interactive "p")
21450 (self-insert-command N))
21452 (defun org-get-indentation (&optional line)
21453 "Get the indentation of the current line, interpreting tabs.
21454 When LINE is given, assume it represents a line and compute its indentation."
21455 (if line
21456 (when (string-match "^ *" (org-remove-tabs line))
21457 (match-end 0))
21458 (save-excursion
21459 (beginning-of-line 1)
21460 (skip-chars-forward " \t")
21461 (current-column))))
21463 (defun org-get-string-indentation (s)
21464 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21465 (let ((n -1) (i 0) (w tab-width) c)
21466 (catch 'exit
21467 (while (< (setq n (1+ n)) (length s))
21468 (setq c (aref s n))
21469 (cond ((= c ?\ ) (setq i (1+ i)))
21470 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21471 (t (throw 'exit t)))))
21474 (defun org-fix-indentation (line ind)
21475 "Fix indentation in LINE.
21476 IND is a cons cell with target and minimum indentation.
21477 If the current indentation in LINE is smaller than the minimum,
21478 leave it alone. If it is larger than ind, set it to the target."
21479 (let* ((l (org-remove-tabs line))
21480 (i (org-get-indentation l))
21481 (i1 (car ind)) (i2 (cdr ind)))
21482 (when (>= i i2) (setq l (substring line i2)))
21483 (if (> i1 0)
21484 (concat (make-string i1 ?\ ) l)
21485 l)))
21487 (defun org-fill-template (template alist)
21488 "Find each %key of ALIST in TEMPLATE and replace it."
21489 (let ((case-fold-search nil))
21490 (dolist (entry (sort (copy-sequence alist)
21491 (lambda (a b) (< (length (car a)) (length (car b))))))
21492 (setq template
21493 (replace-regexp-in-string
21494 (concat "%" (regexp-quote (car entry)))
21495 (or (cdr entry) "") template t t)))
21496 template))
21498 (defun org-quote-vert (s)
21499 "Replace \"|\" with \"\\vert\"."
21500 (while (string-match "|" s)
21501 (setq s (replace-match "\\vert" t t s)))
21504 (defun org-uuidgen-p (s)
21505 "Is S an ID created by UUIDGEN?"
21506 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21508 (defun org-in-src-block-p (&optional inside)
21509 "Whether point is in a code source block.
21510 When INSIDE is non-nil, don't consider we are within a src block
21511 when point is at #+BEGIN_SRC or #+END_SRC."
21512 (let ((case-fold-search t))
21513 (or (and (eq (get-char-property (point) 'src-block) t))
21514 (and (not inside)
21515 (save-match-data
21516 (save-excursion
21517 (beginning-of-line)
21518 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21520 (defun org-context ()
21521 "Return a list of contexts of the current cursor position.
21522 If several contexts apply, all are returned.
21523 Each context entry is a list with a symbol naming the context, and
21524 two positions indicating start and end of the context. Possible
21525 contexts are:
21527 :headline anywhere in a headline
21528 :headline-stars on the leading stars in a headline
21529 :todo-keyword on a TODO keyword (including DONE) in a headline
21530 :tags on the TAGS in a headline
21531 :priority on the priority cookie in a headline
21532 :item on the first line of a plain list item
21533 :item-bullet on the bullet/number of a plain list item
21534 :checkbox on the checkbox in a plain list item
21535 :table in an Org table
21536 :table-special on a special filed in a table
21537 :table-table in a table.el table
21538 :clocktable in a clocktable
21539 :src-block in a source block
21540 :link on a hyperlink
21541 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21542 :target on a <<target>>
21543 :radio-target on a <<<radio-target>>>
21544 :latex-fragment on a LaTeX fragment
21545 :latex-preview on a LaTeX fragment with overlaid preview image
21547 This function expects the position to be visible because it uses font-lock
21548 faces as a help to recognize the following contexts: :table-special, :link,
21549 and :keyword."
21550 (let* ((f (get-text-property (point) 'face))
21551 (faces (if (listp f) f (list f)))
21552 (case-fold-search t)
21553 (p (point)) clist o)
21554 ;; First the large context
21555 (cond
21556 ((org-at-heading-p t)
21557 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21558 (when (progn
21559 (beginning-of-line 1)
21560 (looking-at org-todo-line-tags-regexp))
21561 (push (org-point-in-group p 1 :headline-stars) clist)
21562 (push (org-point-in-group p 2 :todo-keyword) clist)
21563 (push (org-point-in-group p 4 :tags) clist))
21564 (goto-char p)
21565 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21566 (when (looking-at "\\[#[A-Z0-9]\\]")
21567 (push (org-point-in-group p 0 :priority) clist)))
21569 ((org-at-item-p)
21570 (push (org-point-in-group p 2 :item-bullet) clist)
21571 (push (list :item (point-at-bol)
21572 (save-excursion (org-end-of-item) (point)))
21573 clist)
21574 (and (org-at-item-checkbox-p)
21575 (push (org-point-in-group p 0 :checkbox) clist)))
21577 ((org-at-table-p)
21578 (push (list :table (org-table-begin) (org-table-end)) clist)
21579 (when (memq 'org-formula faces)
21580 (push (list :table-special
21581 (previous-single-property-change p 'face)
21582 (next-single-property-change p 'face)) clist)))
21583 ((org-at-table-p 'any)
21584 (push (list :table-table) clist)))
21585 (goto-char p)
21587 (let ((case-fold-search t))
21588 ;; New the "medium" contexts: clocktables, source blocks
21589 (cond ((org-in-clocktable-p)
21590 (push (list :clocktable
21591 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21592 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21593 (match-beginning 1))
21594 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21595 (match-end 0))) clist))
21596 ((org-in-src-block-p)
21597 (push (list :src-block
21598 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21599 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21600 (match-beginning 1))
21601 (and (search-forward "#+END_SRC" nil t)
21602 (match-beginning 0))) clist))))
21603 (goto-char p)
21605 ;; Now the small context
21606 (cond
21607 ((org-at-timestamp-p)
21608 (push (org-point-in-group p 0 :timestamp) clist))
21609 ((memq 'org-link faces)
21610 (push (list :link
21611 (previous-single-property-change p 'face)
21612 (next-single-property-change p 'face)) clist))
21613 ((memq 'org-special-keyword faces)
21614 (push (list :keyword
21615 (previous-single-property-change p 'face)
21616 (next-single-property-change p 'face)) clist))
21617 ((org-at-target-p)
21618 (push (org-point-in-group p 0 :target) clist)
21619 (goto-char (1- (match-beginning 0)))
21620 (when (looking-at org-radio-target-regexp)
21621 (push (org-point-in-group p 0 :radio-target) clist))
21622 (goto-char p))
21623 ((setq o (cl-some
21624 (lambda (o)
21625 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21627 (overlays-at (point))))
21628 (push (list :latex-fragment
21629 (overlay-start o) (overlay-end o)) clist)
21630 (push (list :latex-preview
21631 (overlay-start o) (overlay-end o)) clist))
21632 ((org-inside-LaTeX-fragment-p)
21633 ;; FIXME: positions wrong.
21634 (push (list :latex-fragment (point) (point)) clist)))
21636 (setq clist (nreverse (delq nil clist)))
21637 clist))
21639 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21640 "Non-nil when point is between matches of START-RE and END-RE.
21642 Also return a non-nil value when point is on one of the matches.
21644 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21645 buffer positions. Default values are the positions of headlines
21646 surrounding the point.
21648 The functions returns a cons cell whose car (resp. cdr) is the
21649 position before START-RE (resp. after END-RE)."
21650 (save-match-data
21651 (let ((pos (point))
21652 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21653 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21654 beg end)
21655 (save-excursion
21656 ;; Point is on a block when on START-RE or if START-RE can be
21657 ;; found before it...
21658 (and (or (org-in-regexp start-re)
21659 (re-search-backward start-re limit-up t))
21660 (setq beg (match-beginning 0))
21661 ;; ... and END-RE after it...
21662 (goto-char (match-end 0))
21663 (re-search-forward end-re limit-down t)
21664 (> (setq end (match-end 0)) pos)
21665 ;; ... without another START-RE in-between.
21666 (goto-char (match-beginning 0))
21667 (not (re-search-backward start-re (1+ beg) t))
21668 ;; Return value.
21669 (cons beg end))))))
21671 (defun org-in-block-p (names)
21672 "Non-nil when point belongs to a block whose name belongs to NAMES.
21674 NAMES is a list of strings containing names of blocks.
21676 Return first block name matched, or nil. Beware that in case of
21677 nested blocks, the returned name may not belong to the closest
21678 block from point."
21679 (save-match-data
21680 (catch 'exit
21681 (let ((case-fold-search t)
21682 (lim-up (save-excursion (outline-previous-heading)))
21683 (lim-down (save-excursion (outline-next-heading))))
21684 (dolist (name names)
21685 (let ((n (regexp-quote name)))
21686 (when (org-between-regexps-p
21687 (concat "^[ \t]*#\\+begin_" n)
21688 (concat "^[ \t]*#\\+end_" n)
21689 lim-up lim-down)
21690 (throw 'exit n)))))
21691 nil)))
21693 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21694 "Call `multi-occur' with buffers for all agenda files."
21695 (interactive "sOrg-files matching: ")
21696 (let* ((files (org-agenda-files))
21697 (tnames (mapcar #'file-truename files))
21698 (extra org-agenda-text-search-extra-files))
21699 (when (eq (car extra) 'agenda-archives)
21700 (setq extra (cdr extra))
21701 (setq files (org-add-archive-files files)))
21702 (dolist (f extra)
21703 (unless (member (file-truename f) tnames)
21704 (unless (member f files) (setq files (append files (list f))))
21705 (setq tnames (append tnames (list (file-truename f))))))
21706 (multi-occur
21707 (mapcar (lambda (x)
21708 (with-current-buffer
21709 ;; FIXME: Why not just (find-file-noselect x)?
21710 ;; Is it to avoid the "revert buffer" prompt?
21711 (or (get-file-buffer x) (find-file-noselect x))
21712 (widen)
21713 (current-buffer)))
21714 files)
21715 regexp)))
21717 (add-hook 'occur-mode-find-occurrence-hook
21718 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21720 (defun org-occur-link-in-agenda-files ()
21721 "Create a link and search for it in the agendas.
21722 The link is not stored in `org-stored-links', it is just created
21723 for the search purpose."
21724 (interactive)
21725 (let ((link (condition-case nil
21726 (org-store-link nil)
21727 (error "Unable to create a link to here"))))
21728 (org-occur-in-agenda-files (regexp-quote link))))
21730 (defun org-back-over-empty-lines ()
21731 "Move backwards over whitespace, to the beginning of the first empty line.
21732 Returns the number of empty lines passed."
21733 (let ((pos (point)))
21734 (if (cdr (assq 'heading org-blank-before-new-entry))
21735 (skip-chars-backward " \t\n\r")
21736 (unless (eobp)
21737 (forward-line -1)))
21738 (beginning-of-line 2)
21739 (goto-char (min (point) pos))
21740 (count-lines (point) pos)))
21742 (defun org-switch-to-buffer-other-window (&rest args)
21743 "Switch to buffer in a second window on the current frame.
21744 In particular, do not allow pop-up frames.
21745 Returns the newly created buffer."
21746 (org-no-popups
21747 (apply 'switch-to-buffer-other-window args)))
21749 (defun org-replace-escapes (string table)
21750 "Replace %-escapes in STRING with values in TABLE.
21751 TABLE is an association list with keys like \"%a\" and string values.
21752 The sequences in STRING may contain normal field width and padding information,
21753 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21754 so values can contain further %-escapes if they are define later in TABLE."
21755 (let ((tbl (copy-alist table))
21756 (case-fold-search nil)
21757 (pchg 0)
21758 re rpl)
21759 (dolist (e tbl)
21760 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21761 (when (and (cdr e) (string-match re (cdr e)))
21762 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21763 (safe "SREF"))
21764 (add-text-properties 0 3 (list 'sref sref) safe)
21765 (setcdr e (replace-match safe t t (cdr e)))))
21766 (while (string-match re string)
21767 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21768 (cdr e)))
21769 (setq string (replace-match rpl t t string))))
21770 (while (setq pchg (next-property-change pchg string))
21771 (let ((sref (get-text-property pchg 'sref string)))
21772 (when (and sref (string-match "SREF" string pchg))
21773 (setq string (replace-match sref t t string)))))
21774 string))
21776 ;;; TODO: Only called once, from ox-odt which should probably use
21777 ;;; org-export-inline-image-p or something.
21778 (defun org-file-image-p (file)
21779 "Return non-nil if FILE is an image."
21780 (save-match-data
21781 (string-match (image-file-name-regexp) file)))
21783 (defun org-get-cursor-date (&optional with-time)
21784 "Return the date at cursor in as a time.
21785 This works in the calendar and in the agenda, anywhere else it just
21786 returns the current time.
21787 If WITH-TIME is non-nil, returns the time of the event at point (in
21788 the agenda) or the current time of the day."
21789 (let (date day defd tp hod mod)
21790 (when with-time
21791 (setq tp (get-text-property (point) 'time))
21792 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21793 (setq hod (string-to-number (match-string 1 tp))
21794 mod (string-to-number (match-string 2 tp))))
21795 (or tp (let ((now (decode-time)))
21796 (setq hod (nth 2 now)
21797 mod (nth 1 now)))))
21798 (cond
21799 ((eq major-mode 'calendar-mode)
21800 (setq date (calendar-cursor-to-date)
21801 defd (encode-time 0 (or mod 0) (or hod 0)
21802 (nth 1 date) (nth 0 date) (nth 2 date))))
21803 ((eq major-mode 'org-agenda-mode)
21804 (setq day (get-text-property (point) 'day))
21805 (when day
21806 (setq date (calendar-gregorian-from-absolute day)
21807 defd (encode-time 0 (or mod 0) (or hod 0)
21808 (nth 1 date) (nth 0 date) (nth 2 date))))))
21809 (or defd (current-time))))
21811 (defun org-mark-subtree (&optional up)
21812 "Mark the current subtree.
21813 This puts point at the start of the current subtree, and mark at
21814 the end. If a numeric prefix UP is given, move up into the
21815 hierarchy of headlines by UP levels before marking the subtree."
21816 (interactive "P")
21817 (org-with-limited-levels
21818 (cond ((org-at-heading-p) (beginning-of-line))
21819 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21820 (t (outline-previous-visible-heading 1))))
21821 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21822 (if (called-interactively-p 'any)
21823 (call-interactively 'org-mark-element)
21824 (org-mark-element)))
21826 (defun org-file-newer-than-p (file time)
21827 "Non-nil if FILE is newer than TIME.
21828 FILE is a filename, as a string, TIME is a list of integers, as
21829 returned by, e.g., `current-time'."
21830 (and (file-exists-p file)
21831 ;; Only compare times up to whole seconds as some file-systems
21832 ;; (e.g. HFS+) do not retain any finer granularity. As
21833 ;; a consequence, make sure we return non-nil when the two
21834 ;; times are equal.
21835 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
21836 (cl-subseq time 0 2)))))
21838 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
21839 "Compile a SOURCE file using PROCESS.
21841 PROCESS is either a function or a list of shell commands, as
21842 strings. EXT is a file extension, without the leading dot, as
21843 a string. It is used to check if the process actually succeeded.
21845 PROCESS must create a file with the same base name and directory
21846 as SOURCE, but ending with EXT. The function then returns its
21847 filename. Otherwise, it raises an error. The error message can
21848 then be refined by providing string ERR-MSG, which is appended to
21849 the standard message.
21851 If PROCESS is a function, it is called with a single argument:
21852 the SOURCE file.
21854 If it is a list of commands, each of them is called using
21855 `shell-command'. By default, in each command, %b, %f, %F, %o and
21856 %O are replaced with, respectively, SOURCE base name, name, full
21857 name, directory and absolute output file name. It is possible,
21858 however, to use more place-holders by specifying them in optional
21859 argument SPEC, as an alist following the pattern
21861 (CHARACTER . REPLACEMENT-STRING).
21863 When PROCESS is a list of commands, optional argument LOG-BUF can
21864 be set to a buffer or a buffer name. `shell-command' then uses
21865 it for output."
21866 (let* ((base-name (file-name-base source))
21867 (full-name (file-truename source))
21868 (out-dir (or (file-name-directory source) "./"))
21869 (output (expand-file-name (concat base-name "." ext) out-dir))
21870 (time (current-time))
21871 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
21872 (save-window-excursion
21873 (pcase process
21874 ((pred functionp) (funcall process (shell-quote-argument source)))
21875 ((pred consp)
21876 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
21877 (spec (append spec
21878 `((?b . ,(shell-quote-argument base-name))
21879 (?f . ,(shell-quote-argument source))
21880 (?F . ,(shell-quote-argument full-name))
21881 (?o . ,(shell-quote-argument out-dir))
21882 (?O . ,(shell-quote-argument output))))))
21883 (dolist (command process)
21884 (shell-command (format-spec command spec) log-buf))
21885 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
21886 (_ (error "No valid command to process %S%s" source err-msg))))
21887 ;; Check for process failure. Output file is expected to be
21888 ;; located in the same directory as SOURCE.
21889 (unless (org-file-newer-than-p output time)
21890 (error (format "File %S wasn't produced%s" output err-msg)))
21891 output))
21893 ;;; Indentation
21895 (defvar org-element-greater-elements)
21896 (defun org--get-expected-indentation (element contentsp)
21897 "Expected indentation column for current line, according to ELEMENT.
21898 ELEMENT is an element containing point. CONTENTSP is non-nil
21899 when indentation is to be computed according to contents of
21900 ELEMENT."
21901 (let ((type (org-element-type element))
21902 (start (org-element-property :begin element))
21903 (post-affiliated (org-element-property :post-affiliated element)))
21904 (org-with-wide-buffer
21905 (cond
21906 (contentsp
21907 (cl-case type
21908 ((diary-sexp footnote-definition) 0)
21909 ((headline inlinetask nil)
21910 (if (not org-adapt-indentation) 0
21911 (let ((level (org-current-level)))
21912 (if level (1+ level) 0))))
21913 ((item plain-list) (org-list-item-body-column post-affiliated))
21915 (goto-char start)
21916 (org-get-indentation))))
21917 ((memq type '(headline inlinetask nil))
21918 (if (org-match-line "[ \t]*$")
21919 (org--get-expected-indentation element t)
21921 ((memq type '(diary-sexp footnote-definition)) 0)
21922 ;; First paragraph of a footnote definition or an item.
21923 ;; Indent like parent.
21924 ((< (line-beginning-position) start)
21925 (org--get-expected-indentation
21926 (org-element-property :parent element) t))
21927 ;; At first line: indent according to previous sibling, if any,
21928 ;; ignoring footnote definitions and inline tasks, or parent's
21929 ;; contents.
21930 ((= (line-beginning-position) start)
21931 (catch 'exit
21932 (while t
21933 (if (= (point-min) start) (throw 'exit 0)
21934 (goto-char (1- start))
21935 (let* ((previous (org-element-at-point))
21936 (parent previous))
21937 (while (and parent (<= (org-element-property :end parent) start))
21938 (setq previous parent
21939 parent (org-element-property :parent parent)))
21940 (cond
21941 ((not previous) (throw 'exit 0))
21942 ((> (org-element-property :end previous) start)
21943 (throw 'exit (org--get-expected-indentation previous t)))
21944 ((memq (org-element-type previous)
21945 '(footnote-definition inlinetask))
21946 (setq start (org-element-property :begin previous)))
21947 (t (goto-char (org-element-property :begin previous))
21948 (throw 'exit
21949 (if (bolp) (org-get-indentation)
21950 ;; At first paragraph in an item or
21951 ;; a footnote definition.
21952 (org--get-expected-indentation
21953 (org-element-property :parent previous) t))))))))))
21954 ;; Otherwise, move to the first non-blank line above.
21956 (beginning-of-line)
21957 (let ((pos (point)))
21958 (skip-chars-backward " \r\t\n")
21959 (cond
21960 ;; Two blank lines end a footnote definition or a plain
21961 ;; list. When we indent an empty line after them, the
21962 ;; containing list or footnote definition is over, so it
21963 ;; qualifies as a previous sibling. Therefore, we indent
21964 ;; like its first line.
21965 ((and (memq type '(footnote-definition plain-list))
21966 (> (count-lines (point) pos) 2))
21967 (goto-char start)
21968 (org-get-indentation))
21969 ;; Line above is the first one of a paragraph at the
21970 ;; beginning of an item or a footnote definition. Indent
21971 ;; like parent.
21972 ((< (line-beginning-position) start)
21973 (org--get-expected-indentation
21974 (org-element-property :parent element) t))
21975 ;; Line above is the beginning of an element, i.e., point
21976 ;; was originally on the blank lines between element's start
21977 ;; and contents.
21978 ((= (line-beginning-position) post-affiliated)
21979 (org--get-expected-indentation element t))
21980 ;; POS is after contents in a greater element. Indent like
21981 ;; the beginning of the element.
21982 ((and (memq type org-element-greater-elements)
21983 (let ((cend (org-element-property :contents-end element)))
21984 (and cend (<= cend pos))))
21985 ;; As a special case, if point is at the end of a footnote
21986 ;; definition or an item, indent like the very last element
21987 ;; within. If that last element is an item, indent like
21988 ;; its contents.
21989 (if (memq type '(footnote-definition item plain-list))
21990 (let ((last (org-element-at-point)))
21991 (goto-char pos)
21992 (org--get-expected-indentation
21993 last (eq (org-element-type last) 'item)))
21994 (goto-char start)
21995 (org-get-indentation)))
21996 ;; In any other case, indent like the current line.
21997 (t (org-get-indentation)))))))))
21999 (defun org--align-node-property ()
22000 "Align node property at point.
22001 Alignment is done according to `org-property-format', which see."
22002 (when (save-excursion
22003 (beginning-of-line)
22004 (looking-at org-property-re))
22005 (replace-match
22006 (concat (match-string 4)
22007 (org-trim
22008 (format org-property-format (match-string 1) (match-string 3))))
22009 t t)))
22011 (defun org-indent-line ()
22012 "Indent line depending on context.
22014 Indentation is done according to the following rules:
22016 - Footnote definitions, diary sexps, headlines and inline tasks
22017 have to start at column 0.
22019 - On the very first line of an element, consider, in order, the
22020 next rules until one matches:
22022 1. If there's a sibling element before, ignoring footnote
22023 definitions and inline tasks, indent like its first line.
22025 2. If element has a parent, indent like its contents. More
22026 precisely, if parent is an item, indent after the
22027 description part, if any, or the bullet (see
22028 `org-list-description-max-indent'). Else, indent like
22029 parent's first line.
22031 3. Otherwise, indent relatively to current level, if
22032 `org-adapt-indentation' is non-nil, or to left margin.
22034 - On a blank line at the end of an element, indent according to
22035 the type of the element. More precisely
22037 1. If element is a plain list, an item, or a footnote
22038 definition, indent like the very last element within.
22040 2. If element is a paragraph, indent like its last non blank
22041 line.
22043 3. Otherwise, indent like its very first line.
22045 - In the code part of a source block, use language major mode
22046 to indent current line if `org-src-tab-acts-natively' is
22047 non-nil. If it is nil, do nothing.
22049 - Otherwise, indent like the first non-blank line above.
22051 The function doesn't indent an item as it could break the whole
22052 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22053 `\\[org-shiftmetaright]'.
22055 Also align node properties according to `org-property-format'."
22056 (interactive)
22057 (cond
22058 (orgstruct-is-++
22059 (let ((indent-line-function
22060 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22061 (indent-according-to-mode)))
22062 ((org-at-heading-p) 'noindent)
22064 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22065 (type (org-element-type element)))
22066 (cond ((and (memq type '(plain-list item))
22067 (= (line-beginning-position)
22068 (org-element-property :post-affiliated element)))
22069 'noindent)
22070 ((and (eq type 'latex-environment)
22071 (>= (point) (org-element-property :post-affiliated element))
22072 (< (point) (org-with-wide-buffer
22073 (goto-char (org-element-property :end element))
22074 (skip-chars-backward " \r\t\n")
22075 (line-beginning-position 2))))
22076 'noindent)
22077 ((and (eq type 'src-block)
22078 org-src-tab-acts-natively
22079 (> (line-beginning-position)
22080 (org-element-property :post-affiliated element))
22081 (< (line-beginning-position)
22082 (org-with-wide-buffer
22083 (goto-char (org-element-property :end element))
22084 (skip-chars-backward " \r\t\n")
22085 (line-beginning-position))))
22086 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22088 (let ((column (org--get-expected-indentation element nil)))
22089 ;; Preserve current column.
22090 (if (<= (current-column) (current-indentation))
22091 (indent-line-to column)
22092 (save-excursion (indent-line-to column))))
22093 ;; Align node property. Also preserve current column.
22094 (when (eq type 'node-property)
22095 (let ((column (current-column)))
22096 (org--align-node-property)
22097 (org-move-to-column column)))))))))
22099 (defun org-indent-region (start end)
22100 "Indent each non-blank line in the region.
22101 Called from a program, START and END specify the region to
22102 indent. The function will not indent contents of example blocks,
22103 verse blocks and export blocks as leading white spaces are
22104 assumed to be significant there."
22105 (interactive "r")
22106 (save-excursion
22107 (goto-char start)
22108 (skip-chars-forward " \r\t\n")
22109 (unless (eobp) (beginning-of-line))
22110 (let ((indent-to
22111 (lambda (ind pos)
22112 ;; Set IND as indentation for all lines between point and
22113 ;; POS. Blank lines are ignored. Leave point after POS
22114 ;; once done.
22115 (let ((limit (copy-marker pos)))
22116 (while (< (point) limit)
22117 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22118 (forward-line))
22119 (set-marker limit nil))))
22120 (end (copy-marker end)))
22121 (while (< (point) end)
22122 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22123 (let* ((element (org-element-at-point))
22124 (type (org-element-type element))
22125 (element-end (copy-marker (org-element-property :end element)))
22126 (ind (org--get-expected-indentation element nil)))
22127 (cond
22128 ;; Element indented as a single block. Example blocks
22129 ;; preserving indentation are a special case since the
22130 ;; "contents" must not be indented whereas the block
22131 ;; boundaries can.
22132 ((or (memq type '(export-block latex-environment))
22133 (and (eq type 'example-block)
22134 (not
22135 (or org-src-preserve-indentation
22136 (org-element-property :preserve-indent element)))))
22137 (let ((offset (- ind (org-get-indentation))))
22138 (unless (zerop offset)
22139 (indent-rigidly (org-element-property :begin element)
22140 (org-element-property :end element)
22141 offset)))
22142 (goto-char element-end))
22143 ;; Elements indented line wise. Be sure to exclude
22144 ;; example blocks (preserving indentation) and source
22145 ;; blocks from this category as they are treated
22146 ;; specially later.
22147 ((or (memq type '(paragraph table table-row))
22148 (not (or (org-element-property :contents-begin element)
22149 (memq type '(example-block src-block)))))
22150 (when (eq type 'node-property)
22151 (org--align-node-property)
22152 (beginning-of-line))
22153 (funcall indent-to ind (min element-end end)))
22154 ;; Elements consisting of three parts: before the
22155 ;; contents, the contents, and after the contents. The
22156 ;; contents are treated specially, according to the
22157 ;; element type, or not indented at all. Other parts are
22158 ;; indented as a single block.
22160 (let* ((post (copy-marker
22161 (org-element-property :post-affiliated element)))
22162 (cbeg
22163 (copy-marker
22164 (cond
22165 ((not (org-element-property :contents-begin element))
22166 ;; Fake contents for source blocks.
22167 (org-with-wide-buffer
22168 (goto-char post)
22169 (line-beginning-position 2)))
22170 ((memq type '(footnote-definition item plain-list))
22171 ;; Contents in these elements could start on
22172 ;; the same line as the beginning of the
22173 ;; element. Make sure we start indenting
22174 ;; from the second line.
22175 (org-with-wide-buffer
22176 (goto-char post)
22177 (end-of-line)
22178 (skip-chars-forward " \r\t\n")
22179 (if (eobp) (point) (line-beginning-position))))
22180 (t (org-element-property :contents-begin element)))))
22181 (cend (copy-marker
22182 (or (org-element-property :contents-end element)
22183 ;; Fake contents for source blocks.
22184 (org-with-wide-buffer
22185 (goto-char element-end)
22186 (skip-chars-backward " \r\t\n")
22187 (line-beginning-position)))
22188 t)))
22189 ;; Do not change items indentation individually as it
22190 ;; might break the list as a whole. On the other
22191 ;; hand, when at a plain list, indent it as a whole.
22192 (cond ((eq type 'plain-list)
22193 (let ((offset (- ind (org-get-indentation))))
22194 (unless (zerop offset)
22195 (indent-rigidly (org-element-property :begin element)
22196 (org-element-property :end element)
22197 offset))
22198 (goto-char cbeg)))
22199 ((eq type 'item) (goto-char cbeg))
22200 (t (funcall indent-to ind (min cbeg end))))
22201 (when (< (point) end)
22202 (cl-case type
22203 ((example-block verse-block))
22204 (src-block
22205 ;; In a source block, indent source code
22206 ;; according to language major mode, but only if
22207 ;; `org-src-tab-acts-natively' is non-nil.
22208 (when (and (< (point) end) org-src-tab-acts-natively)
22209 (ignore-errors
22210 (org-babel-do-in-edit-buffer
22211 (indent-region (point-min) (point-max))))))
22212 (t (org-indent-region (point) (min cend end))))
22213 (goto-char (min cend end))
22214 (when (< (point) end)
22215 (funcall indent-to ind (min element-end end))))
22216 (set-marker post nil)
22217 (set-marker cbeg nil)
22218 (set-marker cend nil))))
22219 (set-marker element-end nil))))
22220 (set-marker end nil))))
22222 (defun org-indent-drawer ()
22223 "Indent the drawer at point."
22224 (interactive)
22225 (unless (save-excursion
22226 (beginning-of-line)
22227 (looking-at-p org-drawer-regexp))
22228 (user-error "Not at a drawer"))
22229 (let ((element (org-element-at-point)))
22230 (unless (memq (org-element-type element) '(drawer property-drawer))
22231 (user-error "Not at a drawer"))
22232 (org-with-wide-buffer
22233 (org-indent-region (org-element-property :begin element)
22234 (org-element-property :end element))))
22235 (message "Drawer at point indented"))
22237 (defun org-indent-block ()
22238 "Indent the block at point."
22239 (interactive)
22240 (unless (save-excursion
22241 (beginning-of-line)
22242 (let ((case-fold-search t))
22243 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22244 (user-error "Not at a block"))
22245 (let ((element (org-element-at-point)))
22246 (unless (memq (org-element-type element)
22247 '(comment-block center-block dynamic-block example-block
22248 export-block quote-block special-block
22249 src-block verse-block))
22250 (user-error "Not at a block"))
22251 (org-with-wide-buffer
22252 (org-indent-region (org-element-property :begin element)
22253 (org-element-property :end element))))
22254 (message "Block at point indented"))
22257 ;;; Filling
22259 ;; We use our own fill-paragraph and auto-fill functions.
22261 ;; `org-fill-paragraph' relies on adaptive filling and context
22262 ;; checking. Appropriate `fill-prefix' is computed with
22263 ;; `org-adaptive-fill-function'.
22265 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22266 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22267 ;; `org-adaptive-fill-function' value. Internally,
22268 ;; `org-comment-line-break-function' breaks the line.
22270 ;; `org-setup-filling' installs filling and auto-filling related
22271 ;; variables during `org-mode' initialization.
22273 (defvar org-element-paragraph-separate) ; org-element.el
22274 (defun org-setup-filling ()
22275 (require 'org-element)
22276 ;; Prevent auto-fill from inserting unwanted new items.
22277 (when (boundp 'fill-nobreak-predicate)
22278 (setq-local
22279 fill-nobreak-predicate
22280 (org-uniquify
22281 (append fill-nobreak-predicate
22282 '(org-fill-line-break-nobreak-p
22283 org-fill-n-macro-as-item-nobreak-p
22284 org-fill-paragraph-with-timestamp-nobreak-p)))))
22285 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22286 (setq-local paragraph-start paragraph-ending)
22287 (setq-local paragraph-separate paragraph-ending))
22288 (setq-local fill-paragraph-function 'org-fill-paragraph)
22289 (setq-local auto-fill-inhibit-regexp nil)
22290 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22291 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22292 (setq-local comment-line-break-function 'org-comment-line-break-function))
22294 (defun org-fill-line-break-nobreak-p ()
22295 "Non-nil when a new line at point would create an Org line break."
22296 (save-excursion
22297 (skip-chars-backward "[ \t]")
22298 (skip-chars-backward "\\\\")
22299 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22301 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22302 "Non-nil when a new line at point would split a timestamp."
22303 (and (org-at-timestamp-p 'lax)
22304 (not (looking-at org-ts-regexp-both))))
22306 (defun org-fill-n-macro-as-item-nobreak-p ()
22307 "Non-nil when a new line at point would create a new list."
22308 ;; During export, a "n" macro followed by a dot or a closing
22309 ;; parenthesis can end up being parsed as a new list item.
22310 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22312 (declare-function message-in-body-p "message" ())
22313 (defvar orgtbl-line-start-regexp) ; From org-table.el
22314 (defun org-adaptive-fill-function ()
22315 "Compute a fill prefix for the current line.
22316 Return fill prefix, as a string, or nil if current line isn't
22317 meant to be filled. For convenience, if `adaptive-fill-regexp'
22318 matches in paragraphs or comments, use it."
22319 (catch 'exit
22320 (when (derived-mode-p 'message-mode)
22321 (save-excursion
22322 (beginning-of-line)
22323 (cond ((not (message-in-body-p)) (throw 'exit nil))
22324 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22325 ((looking-at message-cite-prefix-regexp)
22326 (throw 'exit (match-string-no-properties 0)))
22327 ((looking-at org-outline-regexp)
22328 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22329 (org-with-wide-buffer
22330 (unless (org-at-heading-p)
22331 (let* ((p (line-beginning-position))
22332 (element (save-excursion
22333 (beginning-of-line)
22334 (org-element-at-point)))
22335 (type (org-element-type element))
22336 (post-affiliated (org-element-property :post-affiliated element)))
22337 (unless (< p post-affiliated)
22338 (cl-case type
22339 (comment
22340 (save-excursion
22341 (beginning-of-line)
22342 (looking-at "[ \t]*")
22343 (concat (match-string 0) "# ")))
22344 (footnote-definition "")
22345 ((item plain-list)
22346 (make-string (org-list-item-body-column post-affiliated) ?\s))
22347 (paragraph
22348 ;; Fill prefix is usually the same as the current line,
22349 ;; unless the paragraph is at the beginning of an item.
22350 (let ((parent (org-element-property :parent element)))
22351 (save-excursion
22352 (beginning-of-line)
22353 (cond ((eq (org-element-type parent) 'item)
22354 (make-string (org-list-item-body-column
22355 (org-element-property :begin parent))
22356 ?\s))
22357 ((and adaptive-fill-regexp
22358 ;; Locally disable
22359 ;; `adaptive-fill-function' to let
22360 ;; `fill-context-prefix' handle
22361 ;; `adaptive-fill-regexp' variable.
22362 (let (adaptive-fill-function)
22363 (fill-context-prefix
22364 post-affiliated
22365 (org-element-property :end element)))))
22366 ((looking-at "[ \t]+") (match-string 0))
22367 (t "")))))
22368 (comment-block
22369 ;; Only fill contents if P is within block boundaries.
22370 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22371 (forward-line)
22372 (point)))
22373 (cend (save-excursion
22374 (goto-char (org-element-property :end element))
22375 (skip-chars-backward " \r\t\n")
22376 (line-beginning-position))))
22377 (when (and (>= p cbeg) (< p cend))
22378 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22379 (match-string 0)
22380 "")))))))))))
22382 (declare-function message-goto-body "message" ())
22383 (defvar message-cite-prefix-regexp) ; From message.el
22385 (defun org-fill-element (&optional justify)
22386 "Fill element at point, when applicable.
22388 This function only applies to comment blocks, comments, example
22389 blocks and paragraphs. Also, as a special case, re-align table
22390 when point is at one.
22392 If JUSTIFY is non-nil (interactively, with prefix argument),
22393 justify as well. If `sentence-end-double-space' is non-nil, then
22394 period followed by one space does not end a sentence, so don't
22395 break a line there. The variable `fill-column' controls the
22396 width for filling.
22398 For convenience, when point is at a plain list, an item or
22399 a footnote definition, try to fill the first paragraph within."
22400 (with-syntax-table org-mode-transpose-word-syntax-table
22401 ;; Move to end of line in order to get the first paragraph within
22402 ;; a plain list or a footnote definition.
22403 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22404 ;; First check if point is in a blank line at the beginning of
22405 ;; the buffer. In that case, ignore filling.
22406 (cl-case (org-element-type element)
22407 ;; Use major mode filling function is src blocks.
22408 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22409 ;; Align Org tables, leave table.el tables as-is.
22410 (table-row (org-table-align) t)
22411 (table
22412 (when (eq (org-element-property :type element) 'org)
22413 (save-excursion
22414 (goto-char (org-element-property :post-affiliated element))
22415 (org-table-align)))
22417 (paragraph
22418 ;; Paragraphs may contain `line-break' type objects.
22419 (let ((beg (max (point-min)
22420 (org-element-property :contents-begin element)))
22421 (end (min (point-max)
22422 (org-element-property :contents-end element))))
22423 ;; Do nothing if point is at an affiliated keyword.
22424 (if (< (line-end-position) beg) t
22425 (when (derived-mode-p 'message-mode)
22426 ;; In `message-mode', do not fill following citation
22427 ;; in current paragraph nor text before message body.
22428 (let ((body-start (save-excursion (message-goto-body))))
22429 (when body-start (setq beg (max body-start beg))))
22430 (when (save-excursion
22431 (re-search-forward
22432 (concat "^" message-cite-prefix-regexp) end t))
22433 (setq end (match-beginning 0))))
22434 ;; Fill paragraph, taking line breaks into account.
22435 (save-excursion
22436 (goto-char beg)
22437 (let ((cuts (list beg)))
22438 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22439 (when (eq 'line-break
22440 (org-element-type
22441 (save-excursion (backward-char)
22442 (org-element-context))))
22443 (push (point) cuts)))
22444 (dolist (c (delq end cuts))
22445 (fill-region-as-paragraph c end justify)
22446 (setq end c))))
22447 t)))
22448 ;; Contents of `comment-block' type elements should be
22449 ;; filled as plain text, but only if point is within block
22450 ;; markers.
22451 (comment-block
22452 (let* ((case-fold-search t)
22453 (beg (save-excursion
22454 (goto-char (org-element-property :begin element))
22455 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22456 (forward-line)
22457 (point)))
22458 (end (save-excursion
22459 (goto-char (org-element-property :end element))
22460 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22461 (line-beginning-position))))
22462 (if (or (< (point) beg) (> (point) end)) t
22463 (fill-region-as-paragraph
22464 (save-excursion (end-of-line)
22465 (re-search-backward "^[ \t]*$" beg 'move)
22466 (line-beginning-position))
22467 (save-excursion (beginning-of-line)
22468 (re-search-forward "^[ \t]*$" end 'move)
22469 (line-beginning-position))
22470 justify))))
22471 ;; Fill comments.
22472 (comment
22473 (let ((begin (org-element-property :post-affiliated element))
22474 (end (org-element-property :end element)))
22475 (when (and (>= (point) begin) (<= (point) end))
22476 (let ((begin (save-excursion
22477 (end-of-line)
22478 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22479 (progn (forward-line) (point))
22480 begin)))
22481 (end (save-excursion
22482 (end-of-line)
22483 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22484 (1- (line-beginning-position))
22485 (skip-chars-backward " \r\t\n")
22486 (line-end-position)))))
22487 ;; Do not fill comments when at a blank line.
22488 (when (> end begin)
22489 (let ((fill-prefix
22490 (save-excursion
22491 (beginning-of-line)
22492 (looking-at "[ \t]*#")
22493 (let ((comment-prefix (match-string 0)))
22494 (goto-char (match-end 0))
22495 (if (looking-at adaptive-fill-regexp)
22496 (concat comment-prefix (match-string 0))
22497 (concat comment-prefix " "))))))
22498 (save-excursion
22499 (fill-region-as-paragraph begin end justify))))))
22501 ;; Ignore every other element.
22502 (otherwise t)))))
22504 (defun org-fill-paragraph (&optional justify region)
22505 "Fill element at point, when applicable.
22507 This function only applies to comment blocks, comments, example
22508 blocks and paragraphs. Also, as a special case, re-align table
22509 when point is at one.
22511 For convenience, when point is at a plain list, an item or
22512 a footnote definition, try to fill the first paragraph within.
22514 If JUSTIFY is non-nil (interactively, with prefix argument),
22515 justify as well. If `sentence-end-double-space' is non-nil, then
22516 period followed by one space does not end a sentence, so don't
22517 break a line there. The variable `fill-column' controls the
22518 width for filling.
22520 The REGION argument is non-nil if called interactively; in that
22521 case, if Transient Mark mode is enabled and the mark is active,
22522 fill each of the elements in the active region, instead of just
22523 filling the current element."
22524 (interactive (progn
22525 (barf-if-buffer-read-only)
22526 (list (if current-prefix-arg 'full) t)))
22527 (cond
22528 ((and (derived-mode-p 'message-mode)
22529 (or (not (message-in-body-p))
22530 (save-excursion (move-beginning-of-line 1)
22531 (looking-at message-cite-prefix-regexp))))
22532 ;; First ensure filling is correct in message-mode.
22533 (let ((fill-paragraph-function
22534 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
22535 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
22536 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
22537 (paragraph-separate
22538 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
22539 (fill-paragraph nil)))
22540 ((and region transient-mark-mode mark-active
22541 (not (eq (region-beginning) (region-end))))
22542 (let ((origin (point-marker))
22543 (start (region-beginning)))
22544 (unwind-protect
22545 (progn
22546 (goto-char (region-end))
22547 (while (> (point) start)
22548 (org-backward-paragraph)
22549 (org-fill-element justify)))
22550 (goto-char origin)
22551 (set-marker origin nil))))
22552 (t (org-fill-element justify))))
22553 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
22555 (defun org-auto-fill-function ()
22556 "Auto-fill function."
22557 ;; Check if auto-filling is meaningful.
22558 (let ((fc (current-fill-column)))
22559 (when (and fc (> (current-column) fc))
22560 (let* ((fill-prefix (org-adaptive-fill-function))
22561 ;; Enforce empty fill prefix, if required. Otherwise, it
22562 ;; will be computed again.
22563 (adaptive-fill-mode (not (equal fill-prefix ""))))
22564 (when fill-prefix (do-auto-fill))))))
22566 (defun org-comment-line-break-function (&optional soft)
22567 "Break line at point and indent, continuing comment if within one.
22568 The inserted newline is marked hard if variable
22569 `use-hard-newlines' is true, unless optional argument SOFT is
22570 non-nil."
22571 (if soft (insert-and-inherit ?\n) (newline 1))
22572 (save-excursion (forward-char -1) (delete-horizontal-space))
22573 (delete-horizontal-space)
22574 (indent-to-left-margin)
22575 (insert-before-markers-and-inherit fill-prefix))
22578 ;;; Fixed Width Areas
22580 (defun org-toggle-fixed-width ()
22581 "Toggle fixed-width markup.
22583 Add or remove fixed-width markup on current line, whenever it
22584 makes sense. Return an error otherwise.
22586 If a region is active and if it contains only fixed-width areas
22587 or blank lines, remove all fixed-width markup in it. If the
22588 region contains anything else, convert all non-fixed-width lines
22589 to fixed-width ones.
22591 Blank lines at the end of the region are ignored unless the
22592 region only contains such lines."
22593 (interactive)
22594 (if (not (org-region-active-p))
22595 ;; No region:
22597 ;; Remove fixed width marker only in a fixed-with element.
22599 ;; Add fixed width maker in paragraphs, in blank lines after
22600 ;; elements or at the beginning of a headline or an inlinetask,
22601 ;; and before any one-line elements (e.g., a clock).
22602 (progn
22603 (beginning-of-line)
22604 (let* ((element (org-element-at-point))
22605 (type (org-element-type element)))
22606 (cond
22607 ((and (eq type 'fixed-width)
22608 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22609 (replace-match
22610 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22611 ((and (memq type '(babel-call clock comment diary-sexp headline
22612 horizontal-rule keyword paragraph
22613 planning))
22614 (<= (org-element-property :post-affiliated element) (point)))
22615 (skip-chars-forward " \t")
22616 (insert ": "))
22617 ((and (looking-at-p "[ \t]*$")
22618 (or (eq type 'inlinetask)
22619 (save-excursion
22620 (skip-chars-forward " \r\t\n")
22621 (<= (org-element-property :end element) (point)))))
22622 (delete-region (point) (line-end-position))
22623 (org-indent-line)
22624 (insert ": "))
22625 (t (user-error "Cannot insert a fixed-width line here")))))
22626 ;; Region active.
22627 (let* ((begin (save-excursion
22628 (goto-char (region-beginning))
22629 (line-beginning-position)))
22630 (end (copy-marker
22631 (save-excursion
22632 (goto-char (region-end))
22633 (unless (eolp) (beginning-of-line))
22634 (if (save-excursion (re-search-backward "\\S-" begin t))
22635 (progn (skip-chars-backward " \r\t\n") (point))
22636 (point)))))
22637 (all-fixed-width-p
22638 (catch 'not-all-p
22639 (save-excursion
22640 (goto-char begin)
22641 (skip-chars-forward " \r\t\n")
22642 (when (eobp) (throw 'not-all-p nil))
22643 (while (< (point) end)
22644 (let ((element (org-element-at-point)))
22645 (if (eq (org-element-type element) 'fixed-width)
22646 (goto-char (org-element-property :end element))
22647 (throw 'not-all-p nil))))
22648 t))))
22649 (if all-fixed-width-p
22650 (save-excursion
22651 (goto-char begin)
22652 (while (< (point) end)
22653 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22654 (replace-match
22655 "" nil nil nil
22656 (if (= (line-end-position) (match-end 0)) 0 1)))
22657 (forward-line)))
22658 (let ((min-ind (point-max)))
22659 ;; Find minimum indentation across all lines.
22660 (save-excursion
22661 (goto-char begin)
22662 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22663 (setq min-ind 0)
22664 (catch 'zerop
22665 (while (< (point) end)
22666 (unless (looking-at-p "[ \t]*$")
22667 (let ((ind (org-get-indentation)))
22668 (setq min-ind (min min-ind ind))
22669 (when (zerop ind) (throw 'zerop t))))
22670 (forward-line)))))
22671 ;; Loop over all lines and add fixed-width markup everywhere
22672 ;; but in fixed-width lines.
22673 (save-excursion
22674 (goto-char begin)
22675 (while (< (point) end)
22676 (cond
22677 ((org-at-heading-p)
22678 (insert ": ")
22679 (forward-line)
22680 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22681 (insert ":")
22682 (forward-line)))
22683 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22684 (let* ((element (org-element-at-point))
22685 (element-end (org-element-property :end element)))
22686 (if (eq (org-element-type element) 'fixed-width)
22687 (progn (goto-char element-end)
22688 (skip-chars-backward " \r\t\n")
22689 (forward-line))
22690 (let ((limit (min end element-end)))
22691 (while (< (point) limit)
22692 (org-move-to-column min-ind t)
22693 (insert ": ")
22694 (forward-line))))))
22696 (org-move-to-column min-ind t)
22697 (insert ": ")
22698 (forward-line)))))))
22699 (set-marker end nil))))
22702 ;;; Comments
22704 ;; Org comments syntax is quite complex. It requires the entire line
22705 ;; to be just a comment. Also, even with the right syntax at the
22706 ;; beginning of line, some elements (e.g., verse-block or
22707 ;; example-block) don't accept comments. Usual Emacs comment commands
22708 ;; cannot cope with those requirements. Therefore, Org replaces them.
22710 ;; Org still relies on `comment-dwim', but cannot trust
22711 ;; `comment-only-p'. So, `comment-region-function' and
22712 ;; `uncomment-region-function' both point
22713 ;; to`org-comment-or-uncomment-region'. Eventually,
22714 ;; `org-insert-comment' takes care of insertion of comments at the
22715 ;; beginning of line.
22717 ;; `org-setup-comments-handling' install comments related variables
22718 ;; during `org-mode' initialization.
22720 (defun org-setup-comments-handling ()
22721 (interactive)
22722 (setq-local comment-use-syntax nil)
22723 (setq-local comment-start "# ")
22724 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22725 (setq-local comment-insert-comment-function 'org-insert-comment)
22726 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22727 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22729 (defun org-insert-comment ()
22730 "Insert an empty comment above current line.
22731 If the line is empty, insert comment at its beginning. When
22732 point is within a source block, comment according to the related
22733 major mode."
22734 (if (let ((element (org-element-at-point)))
22735 (and (eq (org-element-type element) 'src-block)
22736 (< (save-excursion
22737 (goto-char (org-element-property :post-affiliated element))
22738 (line-end-position))
22739 (point))
22740 (> (save-excursion
22741 (goto-char (org-element-property :end element))
22742 (skip-chars-backward " \r\t\n")
22743 (line-beginning-position))
22744 (point))))
22745 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22746 (beginning-of-line)
22747 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22748 (open-line 1))
22749 (org-indent-line)
22750 (insert "# ")))
22752 (defvar comment-empty-lines) ; From newcomment.el.
22753 (defun org-comment-or-uncomment-region (beg end &rest _)
22754 "Comment or uncomment each non-blank line in the region.
22755 Uncomment each non-blank line between BEG and END if it only
22756 contains commented lines. Otherwise, comment them. If region is
22757 strictly within a source block, use appropriate comment syntax."
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 beg)
22764 (>= (save-excursion
22765 (goto-char (org-element-property :end element))
22766 (skip-chars-backward " \r\t\n")
22767 (line-beginning-position))
22768 end)))
22769 ;; Translate region boundaries for the Org buffer to the source
22770 ;; buffer.
22771 (let ((offset (- end beg)))
22772 (save-excursion
22773 (goto-char beg)
22774 (org-babel-do-in-edit-buffer
22775 (comment-or-uncomment-region (point) (+ offset (point))))))
22776 (save-restriction
22777 ;; Restrict region
22778 (narrow-to-region (save-excursion (goto-char beg)
22779 (skip-chars-forward " \r\t\n" end)
22780 (line-beginning-position))
22781 (save-excursion (goto-char end)
22782 (skip-chars-backward " \r\t\n" beg)
22783 (line-end-position)))
22784 (let ((uncommentp
22785 ;; UNCOMMENTP is non-nil when every non blank line between
22786 ;; BEG and END is a comment.
22787 (save-excursion
22788 (goto-char (point-min))
22789 (while (and (not (eobp))
22790 (let ((element (org-element-at-point)))
22791 (and (eq (org-element-type element) 'comment)
22792 (goto-char (min (point-max)
22793 (org-element-property
22794 :end element)))))))
22795 (eobp))))
22796 (if uncommentp
22797 ;; Only blank lines and comments in region: uncomment it.
22798 (save-excursion
22799 (goto-char (point-min))
22800 (while (not (eobp))
22801 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22802 (replace-match "" nil nil nil 1))
22803 (forward-line)))
22804 ;; Comment each line in region.
22805 (let ((min-indent (point-max)))
22806 ;; First find the minimum indentation across all lines.
22807 (save-excursion
22808 (goto-char (point-min))
22809 (while (and (not (eobp)) (not (zerop min-indent)))
22810 (unless (looking-at "[ \t]*$")
22811 (setq min-indent (min min-indent (current-indentation))))
22812 (forward-line)))
22813 ;; Then loop over all lines.
22814 (save-excursion
22815 (goto-char (point-min))
22816 (while (not (eobp))
22817 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22818 ;; Don't get fooled by invisible text (e.g. link path)
22819 ;; when moving to column MIN-INDENT.
22820 (let ((buffer-invisibility-spec nil))
22821 (org-move-to-column min-indent t))
22822 (insert comment-start))
22823 (forward-line)))))))))
22825 (defun org-comment-dwim (_arg)
22826 "Call `comment-dwim' within a source edit buffer if needed."
22827 (interactive "*P")
22828 (if (org-in-src-block-p)
22829 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22830 (call-interactively 'comment-dwim)))
22833 ;;; Timestamps API
22835 ;; This section contains tools to operate on timestamp objects, as
22836 ;; returned by, e.g. `org-element-context'.
22838 (defun org-timestamp--to-internal-time (timestamp &optional end)
22839 "Encode TIMESTAMP object into Emacs internal time.
22840 Use end of date range or time range when END is non-nil."
22841 (apply #'encode-time
22842 (cons 0
22843 (mapcar
22844 (lambda (prop) (or (org-element-property prop timestamp) 0))
22845 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22846 '(:minute-start :hour-start :day-start :month-start
22847 :year-start))))))
22849 (defun org-timestamp-has-time-p (timestamp)
22850 "Non-nil when TIMESTAMP has a time specified."
22851 (org-element-property :hour-start timestamp))
22853 (defun org-timestamp-format (timestamp format &optional end utc)
22854 "Format a TIMESTAMP object into a string.
22856 FORMAT is a format specifier to be passed to
22857 `format-time-string'.
22859 When optional argument END is non-nil, use end of date-range or
22860 time-range, if possible.
22862 When optional argument UTC is non-nil, time will be expressed as
22863 Universal Time."
22864 (format-time-string
22865 format (org-timestamp--to-internal-time timestamp end)
22866 (and utc t)))
22868 (defun org-timestamp-split-range (timestamp &optional end)
22869 "Extract a TIMESTAMP object from a date or time range.
22871 END, when non-nil, means extract the end of the range.
22872 Otherwise, extract its start.
22874 Return a new timestamp object."
22875 (let ((type (org-element-property :type timestamp)))
22876 (if (memq type '(active inactive diary)) timestamp
22877 (let ((split-ts (org-element-copy timestamp)))
22878 ;; Set new type.
22879 (org-element-put-property
22880 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22881 ;; Copy start properties over end properties if END is
22882 ;; non-nil. Otherwise, copy end properties over `start' ones.
22883 (let ((p-alist '((:minute-start . :minute-end)
22884 (:hour-start . :hour-end)
22885 (:day-start . :day-end)
22886 (:month-start . :month-end)
22887 (:year-start . :year-end))))
22888 (dolist (p-cell p-alist)
22889 (org-element-put-property
22890 split-ts
22891 (funcall (if end #'car #'cdr) p-cell)
22892 (org-element-property
22893 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22894 ;; Eventually refresh `:raw-value'.
22895 (org-element-put-property split-ts :raw-value nil)
22896 (org-element-put-property
22897 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22899 (defun org-timestamp-translate (timestamp &optional boundary)
22900 "Translate TIMESTAMP object to custom format.
22902 Format string is defined in `org-time-stamp-custom-formats',
22903 which see.
22905 When optional argument BOUNDARY is non-nil, it is either the
22906 symbol `start' or `end'. In this case, only translate the
22907 starting or ending part of TIMESTAMP if it is a date or time
22908 range. Otherwise, translate both parts.
22910 Return timestamp as-is if `org-display-custom-times' is nil or if
22911 it has a `diary' type."
22912 (let ((type (org-element-property :type timestamp)))
22913 (if (or (not org-display-custom-times) (eq type 'diary))
22914 (org-element-interpret-data timestamp)
22915 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22916 org-time-stamp-custom-formats)))
22917 (if (and (not boundary) (memq type '(active-range inactive-range)))
22918 (concat (org-timestamp-format timestamp fmt)
22919 "--"
22920 (org-timestamp-format timestamp fmt t))
22921 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22925 ;;; Other stuff.
22927 (defvar reftex-docstruct-symbol)
22928 (defvar org--rds)
22930 (defun org-reftex-citation ()
22931 "Use reftex-citation to insert a citation into the buffer.
22932 This looks for a line like
22934 #+BIBLIOGRAPHY: foo plain option:-d
22936 and derives from it that foo.bib is the bibliography file relevant
22937 for this document. It then installs the necessary environment for RefTeX
22938 to work in this buffer and calls `reftex-citation' to insert a citation
22939 into the buffer.
22941 Export of such citations to both LaTeX and HTML is handled by the contributed
22942 package ox-bibtex by Taru Karttunen."
22943 (interactive)
22944 (let ((reftex-docstruct-symbol 'org--rds)
22945 org--rds bib)
22946 (org-with-wide-buffer
22947 (let ((case-fold-search t)
22948 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22949 (if (not (save-excursion
22950 (or (re-search-forward re nil t)
22951 (re-search-backward re nil t))))
22952 (user-error "No bibliography defined in file")
22953 (setq bib (concat (match-string 1) ".bib")
22954 org--rds (list (list 'bib bib))))))
22955 (call-interactively 'reftex-citation)))
22957 ;;;; Functions extending outline functionality
22959 (defun org-beginning-of-line (&optional n)
22960 "Go to the beginning of the current visible line.
22962 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22963 tags on the first attempt, and only move to after the tags when
22964 the cursor is already beyond the end of the headline.
22966 With argument N not nil or 1, move forward N - 1 lines first."
22967 (interactive "^p")
22968 (let ((origin (point))
22969 (special (pcase org-special-ctrl-a/e
22970 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22971 deactivate-mark)
22972 ;; First move to a visible line.
22973 (if (bound-and-true-p visual-line-mode)
22974 (beginning-of-visual-line n)
22975 (move-beginning-of-line n)
22976 ;; `move-beginning-of-line' may leave point after invisible
22977 ;; characters if line starts with such of these (e.g., with
22978 ;; a link at column 0). Really move to the beginning of the
22979 ;; current visible line.
22980 (beginning-of-line))
22981 (cond
22982 ;; No special behavior. Point is already at the beginning of
22983 ;; a line, logical or visual.
22984 ((not special))
22985 ;; `beginning-of-visual-line' left point before logical beginning
22986 ;; of line: point is at the beginning of a visual line. Bail
22987 ;; out.
22988 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22989 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22990 ;; At a headline, special position is before the title, but
22991 ;; after any TODO keyword or priority cookie.
22992 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22993 (line-end-position)))
22994 (bol (point)))
22995 (if (eq special 'reversed)
22996 (when (and (= origin bol) (eq last-command this-command))
22997 (goto-char refpos))
22998 (when (or (> origin refpos) (= origin bol))
22999 (goto-char refpos)))))
23000 ((and (looking-at org-list-full-item-re)
23001 (memq (org-element-type (save-match-data (org-element-at-point)))
23002 '(item plain-list)))
23003 ;; Set special position at first white space character after
23004 ;; bullet, and check-box, if any.
23005 (let ((after-bullet
23006 (let ((box (match-end 3)))
23007 (cond ((not box) (match-end 1))
23008 ((eq (char-after box) ?\s) (1+ box))
23009 (t box)))))
23010 (if (eq special 'reversed)
23011 (when (and (= (point) origin) (eq last-command this-command))
23012 (goto-char after-bullet))
23013 (when (or (> origin after-bullet) (= (point) origin))
23014 (goto-char after-bullet)))))
23015 ;; No special context. Point is already at beginning of line.
23016 (t nil))))
23018 (defun org-end-of-line (&optional n)
23019 "Go to the end of the line, but before ellipsis, if any.
23021 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23022 tags on the first attempt, and only move to after the tags when
23023 the cursor is already beyond the end of the headline.
23025 With argument N not nil or 1, move forward N - 1 lines first."
23026 (interactive "^p")
23027 (let ((origin (point))
23028 (special (pcase org-special-ctrl-a/e
23029 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23030 deactivate-mark)
23031 ;; First move to a visible line.
23032 (if (bound-and-true-p visual-line-mode)
23033 (beginning-of-visual-line n)
23034 (move-beginning-of-line n))
23035 (cond
23036 ;; At a headline, with tags.
23037 ((and special
23038 (save-excursion
23039 (beginning-of-line)
23040 (let ((case-fold-search nil))
23041 (looking-at org-complex-heading-regexp)))
23042 (match-end 5))
23043 (let ((tags (save-excursion
23044 (goto-char (match-beginning 5))
23045 (skip-chars-backward " \t")
23046 (point)))
23047 (visual-end (and (bound-and-true-p visual-line-mode)
23048 (save-excursion
23049 (end-of-visual-line)
23050 (point)))))
23051 ;; If `end-of-visual-line' brings us before end of line or
23052 ;; even tags, i.e., the headline spans over multiple visual
23053 ;; lines, move there.
23054 (cond ((and visual-end
23055 (< visual-end tags)
23056 (<= origin visual-end))
23057 (goto-char visual-end))
23058 ((eq special 'reversed)
23059 (if (and (= origin (line-end-position))
23060 (eq this-command last-command))
23061 (goto-char tags)
23062 (end-of-line)))
23064 (if (or (< origin tags) (= origin (line-end-position)))
23065 (goto-char tags)
23066 (end-of-line))))))
23067 ((bound-and-true-p visual-line-mode)
23068 (let ((bol (line-beginning-position)))
23069 (end-of-visual-line)
23070 ;; If `end-of-visual-line' gets us past the ellipsis at the
23071 ;; end of a line, backtrack and use `end-of-line' instead.
23072 (when (/= bol (line-beginning-position))
23073 (goto-char bol)
23074 (end-of-line))))
23075 (t (end-of-line)))))
23077 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23078 (define-key org-mode-map "\C-e" 'org-end-of-line)
23080 (defun org-backward-sentence (&optional _arg)
23081 "Go to beginning of sentence, or beginning of table field.
23082 This will call `backward-sentence' or `org-table-beginning-of-field',
23083 depending on context."
23084 (interactive)
23085 (let* ((element (org-element-at-point))
23086 (contents-begin (org-element-property :contents-begin element))
23087 (table (org-element-lineage element '(table) t)))
23088 (if (and table
23089 (> (point) contents-begin)
23090 (<= (point) (org-element-property :contents-end table)))
23091 (call-interactively #'org-table-beginning-of-field)
23092 (save-restriction
23093 (when (and contents-begin
23094 (< (point-min) contents-begin)
23095 (> (point) contents-begin))
23096 (narrow-to-region contents-begin
23097 (org-element-property :contents-end element)))
23098 (call-interactively #'backward-sentence)))))
23100 (defun org-forward-sentence (&optional _arg)
23101 "Go to end of sentence, or end of table field.
23102 This will call `forward-sentence' or `org-table-end-of-field',
23103 depending on context."
23104 (interactive)
23105 (if (and (org-at-heading-p)
23106 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23107 (save-restriction
23108 (narrow-to-region (line-beginning-position) (line-end-position))
23109 (call-interactively #'forward-sentence))
23110 (let* ((element (org-element-at-point))
23111 (contents-end (org-element-property :contents-end element))
23112 (table (org-element-lineage element '(table) t)))
23113 (if (and table
23114 (>= (point) (org-element-property :contents-begin table))
23115 (< (point) contents-end))
23116 (call-interactively #'org-table-end-of-field)
23117 (save-restriction
23118 (when (and contents-end
23119 (> (point-max) contents-end)
23120 ;; Skip blank lines between elements.
23121 (< (org-element-property :end element)
23122 (save-excursion (goto-char contents-end)
23123 (skip-chars-forward " \r\t\n"))))
23124 (narrow-to-region (org-element-property :contents-begin element)
23125 contents-end))
23126 ;; End of heading is considered as the end of a sentence.
23127 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
23128 (call-interactively #'forward-sentence)))))))
23130 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23131 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23133 (defun org-kill-line (&optional _arg)
23134 "Kill line, to tags or end of line."
23135 (interactive)
23136 (cond
23137 ((or (not org-special-ctrl-k)
23138 (bolp)
23139 (not (org-at-heading-p)))
23140 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23141 org-ctrl-k-protect-subtree
23142 (or (eq org-ctrl-k-protect-subtree 'error)
23143 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23144 (user-error "C-k aborted as it would kill a hidden subtree"))
23145 (call-interactively
23146 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23147 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23148 (kill-region (point) (match-beginning 1))
23149 (org-set-tags nil t))
23150 (t (kill-region (point) (point-at-eol)))))
23152 (define-key org-mode-map "\C-k" 'org-kill-line)
23154 (defun org-yank (&optional arg)
23155 "Yank. If the kill is a subtree, treat it specially.
23156 This command will look at the current kill and check if is a single
23157 subtree, or a series of subtrees[1]. If it passes the test, and if the
23158 cursor is at the beginning of a line or after the stars of a currently
23159 empty headline, then the yank is handled specially. How exactly depends
23160 on the value of the following variables.
23162 `org-yank-folded-subtrees'
23163 By default, this variable is non-nil, which results in
23164 subtree(s) being folded after insertion, except if doing so
23165 would swallow text after the yanked text.
23167 `org-yank-adjusted-subtrees'
23168 When non-nil (the default value is nil), the subtree will be
23169 promoted or demoted in order to fit into the local outline tree
23170 structure, which means that the level will be adjusted so that it
23171 becomes the smaller one of the two *visible* surrounding headings.
23173 Any prefix to this command will cause `yank' to be called directly with
23174 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23175 will just
23176 plainly yank the text as it is.
23178 \[1] The test checks if the first non-white line is a heading
23179 and if there are no other headings with fewer stars."
23180 (interactive "P")
23181 (org-yank-generic 'yank arg))
23183 (defun org-yank-generic (command arg)
23184 "Perform some yank-like command.
23186 This function implements the behavior described in the `org-yank'
23187 documentation. However, it has been generalized to work for any
23188 interactive command with similar behavior."
23190 ;; pretend to be command COMMAND
23191 (setq this-command command)
23193 (if arg
23194 (call-interactively command)
23196 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23197 (and (org-kill-is-subtree-p)
23198 (or (bolp)
23199 (and (looking-at "[ \t]*$")
23200 (string-match
23201 "\\`\\*+\\'"
23202 (buffer-substring (point-at-bol) (point)))))))
23203 swallowp)
23204 (cond
23205 ((and subtreep org-yank-folded-subtrees)
23206 (let ((beg (point))
23207 end)
23208 (if (and subtreep org-yank-adjusted-subtrees)
23209 (org-paste-subtree nil nil 'for-yank)
23210 (call-interactively command))
23212 (setq end (point))
23213 (goto-char beg)
23214 (when (and (bolp) subtreep
23215 (not (setq swallowp
23216 (org-yank-folding-would-swallow-text beg end))))
23217 (org-with-limited-levels
23218 (or (looking-at org-outline-regexp)
23219 (re-search-forward org-outline-regexp-bol end t))
23220 (while (and (< (point) end) (looking-at org-outline-regexp))
23221 (outline-hide-subtree)
23222 (org-cycle-show-empty-lines 'folded)
23223 (condition-case nil
23224 (outline-forward-same-level 1)
23225 (error (goto-char end))))))
23226 (when swallowp
23227 (message
23228 "Inserted text not folded because that would swallow text"))
23230 (goto-char end)
23231 (skip-chars-forward " \t\n\r")
23232 (beginning-of-line 1)
23233 (push-mark beg 'nomsg)))
23234 ((and subtreep org-yank-adjusted-subtrees)
23235 (let ((beg (point-at-bol)))
23236 (org-paste-subtree nil nil 'for-yank)
23237 (push-mark beg 'nomsg)))
23239 (call-interactively command))))))
23241 (defun org-yank-folding-would-swallow-text (beg end)
23242 "Would hide-subtree at BEG swallow any text after END?"
23243 (let (level)
23244 (org-with-limited-levels
23245 (save-excursion
23246 (goto-char beg)
23247 (when (or (looking-at org-outline-regexp)
23248 (re-search-forward org-outline-regexp-bol end t))
23249 (setq level (org-outline-level)))
23250 (goto-char end)
23251 (skip-chars-forward " \t\r\n\v\f")
23252 (not (or (eobp)
23253 (and (bolp) (looking-at-p org-outline-regexp)
23254 (<= (org-outline-level) level))))))))
23256 (define-key org-mode-map "\C-y" 'org-yank)
23258 (defun org-back-to-heading (&optional invisible-ok)
23259 "Call `outline-back-to-heading', but provide a better error message."
23260 (condition-case nil
23261 (outline-back-to-heading invisible-ok)
23262 (error (error "Before first headline at position %d in buffer %s"
23263 (point) (current-buffer)))))
23265 (defun org-before-first-heading-p ()
23266 "Before first heading?"
23267 (save-excursion
23268 (end-of-line)
23269 (null (re-search-backward org-outline-regexp-bol nil t))))
23271 (defun org-at-heading-p (&optional ignored)
23272 (outline-on-heading-p t))
23274 (defun org-in-commented-heading-p (&optional no-inheritance)
23275 "Non-nil if point is under a commented heading.
23276 This function also checks ancestors of the current headline,
23277 unless optional argument NO-INHERITANCE is non-nil."
23278 (cond
23279 ((org-before-first-heading-p) nil)
23280 ((let ((headline (nth 4 (org-heading-components))))
23281 (and headline
23282 (let ((case-fold-search nil))
23283 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23284 headline)))))
23285 (no-inheritance nil)
23287 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23289 (defun org-at-comment-p nil
23290 "Is cursor in a commented line?"
23291 (save-excursion
23292 (save-match-data
23293 (beginning-of-line)
23294 (looking-at "^[ \t]*# "))))
23296 (defun org-at-drawer-p nil
23297 "Is cursor at a drawer keyword?"
23298 (save-excursion
23299 (move-beginning-of-line 1)
23300 (looking-at org-drawer-regexp)))
23302 (defun org-at-block-p nil
23303 "Is cursor at a block keyword?"
23304 (save-excursion
23305 (move-beginning-of-line 1)
23306 (looking-at org-block-regexp)))
23308 (defun org-point-at-end-of-empty-headline ()
23309 "If point is at the end of an empty headline, return t, else nil.
23310 If the heading only contains a TODO keyword, it is still still considered
23311 empty."
23312 (let ((case-fold-search nil))
23313 (and (looking-at "[ \t]*$")
23314 org-todo-line-regexp
23315 (save-excursion
23316 (beginning-of-line)
23317 (looking-at org-todo-line-regexp)
23318 (string= (match-string 3) "")))))
23320 (defun org-at-heading-or-item-p ()
23321 (or (org-at-heading-p) (org-at-item-p)))
23323 (defun org-at-target-p ()
23324 (or (org-in-regexp org-radio-target-regexp)
23325 (org-in-regexp org-target-regexp)))
23326 ;; Compatibility alias with Org versions < 7.8.03
23327 (defalias 'org-on-target-p 'org-at-target-p)
23329 (defun org-up-heading-all (arg)
23330 "Move to the heading line of which the present line is a subheading.
23331 This function considers both visible and invisible heading lines.
23332 With argument, move up ARG levels."
23333 (outline-up-heading arg t))
23335 (defun org-up-heading-safe ()
23336 "Move to the heading line of which the present line is a subheading.
23337 This version will not throw an error. It will return the level of the
23338 headline found, or nil if no higher level is found.
23340 Also, this function will be a lot faster than `outline-up-heading',
23341 because it relies on stars being the outline starters. This can really
23342 make a significant difference in outlines with very many siblings."
23343 (when (ignore-errors (org-back-to-heading t))
23344 (let ((level-up (1- (funcall outline-level))))
23345 (and (> level-up 0)
23346 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23347 (funcall outline-level)))))
23349 (defun org-first-sibling-p ()
23350 "Is this heading the first child of its parents?"
23351 (interactive)
23352 (let ((re org-outline-regexp-bol)
23353 level l)
23354 (unless (org-at-heading-p t)
23355 (user-error "Not at a heading"))
23356 (setq level (funcall outline-level))
23357 (save-excursion
23358 (if (not (re-search-backward re nil t))
23360 (setq l (funcall outline-level))
23361 (< l level)))))
23363 (defun org-goto-sibling (&optional previous)
23364 "Goto the next sibling, even if it is invisible.
23365 When PREVIOUS is set, go to the previous sibling instead. Returns t
23366 when a sibling was found. When none is found, return nil and don't
23367 move point."
23368 (let ((fun (if previous 're-search-backward 're-search-forward))
23369 (pos (point))
23370 (re org-outline-regexp-bol)
23371 level l)
23372 (when (ignore-errors (org-back-to-heading t))
23373 (setq level (funcall outline-level))
23374 (catch 'exit
23375 (or previous (forward-char 1))
23376 (while (funcall fun re nil t)
23377 (setq l (funcall outline-level))
23378 (when (< l level) (goto-char pos) (throw 'exit nil))
23379 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23380 (goto-char pos)
23381 nil))))
23383 (defun org-show-siblings ()
23384 "Show all siblings of the current headline."
23385 (save-excursion
23386 (while (org-goto-sibling) (org-flag-heading nil)))
23387 (save-excursion
23388 (while (org-goto-sibling 'previous)
23389 (org-flag-heading nil))))
23391 (defun org-goto-first-child ()
23392 "Goto the first child, even if it is invisible.
23393 Return t when a child was found. Otherwise don't move point and
23394 return nil."
23395 (let (level (pos (point)) (re org-outline-regexp-bol))
23396 (when (ignore-errors (org-back-to-heading t))
23397 (setq level (outline-level))
23398 (forward-char 1)
23399 (if (and (re-search-forward re nil t) (> (outline-level) level))
23400 (progn (goto-char (match-beginning 0)) t)
23401 (goto-char pos) nil))))
23403 (defun org-show-hidden-entry ()
23404 "Show an entry where even the heading is hidden."
23405 (save-excursion
23406 (org-show-entry)))
23408 (defun org-flag-heading (flag &optional entry)
23409 "Flag the current heading. FLAG non-nil means make invisible.
23410 When ENTRY is non-nil, show the entire entry."
23411 (save-excursion
23412 (org-back-to-heading t)
23413 ;; Check if we should show the entire entry
23414 (if entry
23415 (progn
23416 (org-show-entry)
23417 (save-excursion
23418 (and (outline-next-heading)
23419 (org-flag-heading nil))))
23420 (outline-flag-region (max (point-min) (1- (point)))
23421 (save-excursion (outline-end-of-heading) (point))
23422 flag))))
23424 (defun org-get-next-sibling ()
23425 "Move to next heading of the same level, and return point.
23426 If there is no such heading, return nil.
23427 This is like outline-next-sibling, but invisible headings are ok."
23428 (let ((level (funcall outline-level)))
23429 (outline-next-heading)
23430 (while (and (not (eobp)) (> (funcall outline-level) level))
23431 (outline-next-heading))
23432 (unless (or (eobp) (< (funcall outline-level) level))
23433 (point))))
23435 (defun org-get-last-sibling ()
23436 "Move to previous heading of the same level, and return point.
23437 If there is no such heading, return nil."
23438 (let ((opoint (point))
23439 (level (funcall outline-level)))
23440 (outline-previous-heading)
23441 (when (and (/= (point) opoint) (outline-on-heading-p t))
23442 (while (and (> (funcall outline-level) level)
23443 (not (bobp)))
23444 (outline-previous-heading))
23445 (unless (< (funcall outline-level) level)
23446 (point)))))
23448 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23449 "Goto to the end of a subtree."
23450 ;; This contains an exact copy of the original function, but it uses
23451 ;; `org-back-to-heading', to make it work also in invisible
23452 ;; trees. And is uses an invisible-ok argument.
23453 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23454 ;; Furthermore, when used inside Org, finding the end of a large subtree
23455 ;; with many children and grandchildren etc, this can be much faster
23456 ;; than the outline version.
23457 (org-back-to-heading invisible-ok)
23458 (let ((first t)
23459 (level (funcall outline-level)))
23460 (if (and (derived-mode-p 'org-mode) (< level 1000))
23461 ;; A true heading (not a plain list item), in Org
23462 ;; This means we can easily find the end by looking
23463 ;; only for the right number of stars. Using a regexp to do
23464 ;; this is so much faster than using a Lisp loop.
23465 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23466 (forward-char 1)
23467 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23468 ;; something else, do it the slow way
23469 (while (and (not (eobp))
23470 (or first (> (funcall outline-level) level)))
23471 (setq first nil)
23472 (outline-next-heading)))
23473 (unless to-heading
23474 (when (memq (preceding-char) '(?\n ?\^M))
23475 ;; Go to end of line before heading
23476 (forward-char -1)
23477 (when (memq (preceding-char) '(?\n ?\^M))
23478 ;; leave blank line before heading
23479 (forward-char -1)))))
23480 (point))
23482 (defun org-end-of-meta-data (&optional full)
23483 "Skip planning line and properties drawer in current entry.
23484 When optional argument FULL is non-nil, also skip empty lines,
23485 clocking lines and regular drawers at the beginning of the
23486 entry."
23487 (org-back-to-heading t)
23488 (forward-line)
23489 (when (looking-at-p org-planning-line-re) (forward-line))
23490 (when (looking-at org-property-drawer-re)
23491 (goto-char (match-end 0))
23492 (forward-line))
23493 (when (and full (not (org-at-heading-p)))
23494 (catch 'exit
23495 (let ((end (save-excursion (outline-next-heading) (point)))
23496 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23497 (while (not (eobp))
23498 (cond ((looking-at-p org-drawer-regexp)
23499 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23500 (forward-line)
23501 (throw 'exit t)))
23502 ((looking-at-p re) (forward-line))
23503 (t (throw 'exit t))))))))
23505 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23506 "Move forward to the ARG'th subheading at same level as this one.
23507 Stop at the first and last subheadings of a superior heading.
23508 Normally this only looks at visible headings, but when INVISIBLE-OK is
23509 non-nil it will also look at invisible ones."
23510 (interactive "p")
23511 (let ((backward? (and arg (< arg 0))))
23512 (if (org-before-first-heading-p)
23513 (if backward? (goto-char (point-min)) (outline-next-heading))
23514 (org-back-to-heading invisible-ok)
23515 (unless backward? (end-of-line)) ;do not match current headline
23516 (let ((level (- (match-end 0) (match-beginning 0) 1))
23517 (f (if backward? #'re-search-backward #'re-search-forward))
23518 (count (if arg (abs arg) 1))
23519 (result (point)))
23520 (while (and (> count 0)
23521 (funcall f org-outline-regexp-bol nil 'move))
23522 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23523 (cond ((< l level) (setq count 0))
23524 ((and (= l level)
23525 (or invisible-ok
23526 (not (org-invisible-p
23527 (line-beginning-position)))))
23528 (cl-decf count)
23529 (when (= l level) (setq result (point)))))))
23530 (goto-char result))
23531 (beginning-of-line))))
23533 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23534 "Move backward to the ARG'th subheading at same level as this one.
23535 Stop at the first and last subheadings of a superior heading."
23536 (interactive "p")
23537 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23539 (defun org-next-visible-heading (arg)
23540 "Move to the next visible heading.
23542 This function wraps `outline-next-visible-heading' with
23543 `org-with-limited-levels' in order to skip over inline tasks and
23544 respect customization of `org-odd-levels-only'."
23545 (interactive "p")
23546 (org-with-limited-levels
23547 (outline-next-visible-heading arg)))
23549 (defun org-previous-visible-heading (arg)
23550 "Move to the previous visible heading.
23552 This function wraps `outline-previous-visible-heading' with
23553 `org-with-limited-levels' in order to skip over inline tasks and
23554 respect customization of `org-odd-levels-only'."
23555 (interactive "p")
23556 (org-with-limited-levels
23557 (outline-previous-visible-heading arg)))
23559 (defun org-next-block (arg &optional backward block-regexp)
23560 "Jump to the next block.
23562 With a prefix argument ARG, jump forward ARG many blocks.
23564 When BACKWARD is non-nil, jump to the previous block.
23566 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
23567 Match data is set according to this regexp when the function
23568 returns.
23570 Return point at beginning of the opening line of found block.
23571 Throw an error if no block is found."
23572 (interactive "p")
23573 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
23574 (case-fold-search t)
23575 (search-fn (if backward #'re-search-backward #'re-search-forward))
23576 (count (or arg 1))
23577 (origin (point))
23578 last-element)
23579 (if backward (beginning-of-line) (end-of-line))
23580 (while (and (> count 0) (funcall search-fn re nil t))
23581 (let ((element (save-excursion
23582 (goto-char (match-beginning 0))
23583 (save-match-data (org-element-at-point)))))
23584 (when (and (memq (org-element-type element)
23585 '(center-block comment-block dynamic-block
23586 example-block export-block quote-block
23587 special-block src-block verse-block))
23588 (<= (match-beginning 0)
23589 (org-element-property :post-affiliated element)))
23590 (setq last-element element)
23591 (cl-decf count))))
23592 (if (= count 0)
23593 (prog1 (goto-char (org-element-property :post-affiliated last-element))
23594 (save-match-data (org-show-context)))
23595 (goto-char origin)
23596 (user-error "No %s code blocks" (if backward "previous" "further")))))
23598 (defun org-previous-block (arg &optional block-regexp)
23599 "Jump to the previous block.
23600 With a prefix argument ARG, jump backward ARG many source blocks.
23601 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23602 (interactive "p")
23603 (org-next-block arg t block-regexp))
23605 (defun org-forward-paragraph ()
23606 "Move forward to beginning of next paragraph or equivalent.
23608 The function moves point to the beginning of the next visible
23609 structural element, which can be a paragraph, a table, a list
23610 item, etc. It also provides some special moves for convenience:
23612 - On an affiliated keyword, jump to the beginning of the
23613 relative element.
23614 - On an item or a footnote definition, move to the second
23615 element inside, if any.
23616 - On a table or a property drawer, jump after it.
23617 - On a verse or source block, stop after blank lines."
23618 (interactive)
23619 (unless (eobp)
23620 (let* ((deactivate-mark nil)
23621 (element (org-element-at-point))
23622 (type (org-element-type element))
23623 (post-affiliated (org-element-property :post-affiliated element))
23624 (contents-begin (org-element-property :contents-begin element))
23625 (contents-end (org-element-property :contents-end element))
23626 (end (let ((end (org-element-property :end element)) (parent element))
23627 (while (and (setq parent (org-element-property :parent parent))
23628 (= (org-element-property :contents-end parent) end))
23629 (setq end (org-element-property :end parent)))
23630 end)))
23631 (cond ((not element)
23632 (skip-chars-forward " \r\t\n")
23633 (or (eobp) (beginning-of-line)))
23634 ;; On affiliated keywords, move to element's beginning.
23635 ((< (point) post-affiliated)
23636 (goto-char post-affiliated))
23637 ;; At a table row, move to the end of the table. Similarly,
23638 ;; at a node property, move to the end of the property
23639 ;; drawer.
23640 ((memq type '(node-property table-row))
23641 (goto-char (org-element-property
23642 :end (org-element-property :parent element))))
23643 ((memq type '(property-drawer table)) (goto-char end))
23644 ;; Consider blank lines as separators in verse and source
23645 ;; blocks to ease editing.
23646 ((memq type '(src-block verse-block))
23647 (when (eq type 'src-block)
23648 (setq contents-end
23649 (save-excursion (goto-char end)
23650 (skip-chars-backward " \r\t\n")
23651 (line-beginning-position))))
23652 (beginning-of-line)
23653 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23654 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23655 (goto-char end)
23656 (skip-chars-forward " \r\t\n")
23657 (if (= (point) contents-end) (goto-char end)
23658 (beginning-of-line))))
23659 ;; With no contents, just skip element.
23660 ((not contents-begin) (goto-char end))
23661 ;; If contents are invisible, skip the element altogether.
23662 ((org-invisible-p (line-end-position))
23663 (cl-case type
23664 (headline
23665 (org-with-limited-levels (outline-next-visible-heading 1)))
23666 ;; At a plain list, make sure we move to the next item
23667 ;; instead of skipping the whole list.
23668 (plain-list (forward-char)
23669 (org-forward-paragraph))
23670 (otherwise (goto-char end))))
23671 ((>= (point) contents-end) (goto-char end))
23672 ((>= (point) contents-begin)
23673 ;; This can only happen on paragraphs and plain lists.
23674 (cl-case type
23675 (paragraph (goto-char end))
23676 ;; At a plain list, try to move to second element in
23677 ;; first item, if possible.
23678 (plain-list (end-of-line)
23679 (org-forward-paragraph))))
23680 ;; When contents start on the middle of a line (e.g. in
23681 ;; items and footnote definitions), try to reach first
23682 ;; element starting after current line.
23683 ((> (line-end-position) contents-begin)
23684 (end-of-line)
23685 (org-forward-paragraph))
23686 (t (goto-char contents-begin))))))
23688 (defun org-backward-paragraph ()
23689 "Move backward to start of previous paragraph or equivalent.
23691 The function moves point to the beginning of the current
23692 structural element, which can be a paragraph, a table, a list
23693 item, etc., or to the beginning of the previous visible one if
23694 point is already there. It also provides some special moves for
23695 convenience:
23697 - On an affiliated keyword, jump to the first one.
23698 - On a table or a property drawer, move to its beginning.
23699 - On comment, example, export, src and verse blocks, stop
23700 before blank lines."
23701 (interactive)
23702 (unless (bobp)
23703 (let* ((deactivate-mark nil)
23704 (element (org-element-at-point))
23705 (type (org-element-type element))
23706 (contents-end (org-element-property :contents-end element))
23707 (post-affiliated (org-element-property :post-affiliated element))
23708 (begin (org-element-property :begin element))
23709 (special? ;blocks handled specially
23710 (memq type '(comment-block example-block export-block src-block
23711 verse-block)))
23712 (contents-begin
23713 (if special?
23714 ;; These types have no proper contents. Fake line
23715 ;; below the block opening line as contents beginning.
23716 (save-excursion (goto-char begin) (line-beginning-position 2))
23717 (org-element-property :contents-begin element))))
23718 (cond
23719 ((not element) (goto-char (point-min)))
23720 ((= (point) begin)
23721 (backward-char)
23722 (org-backward-paragraph))
23723 ((<= (point) post-affiliated) (goto-char begin))
23724 ;; Special behavior: on a table or a property drawer, move to
23725 ;; its beginning.
23726 ((memq type '(node-property table-row))
23727 (goto-char (org-element-property
23728 :post-affiliated (org-element-property :parent element))))
23729 (special?
23730 (if (<= (point) contents-begin) (goto-char post-affiliated)
23731 ;; Inside a verse block, see blank lines as paragraph
23732 ;; separators.
23733 (let ((origin (point)))
23734 (skip-chars-backward " \r\t\n" contents-begin)
23735 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23736 (skip-chars-forward " \r\t\n" origin)
23737 (if (= (point) origin) (goto-char contents-begin)
23738 (beginning-of-line))))))
23739 ((eq type 'paragraph) (goto-char contents-begin)
23740 ;; When at first paragraph in an item or a footnote definition,
23741 ;; move directly to beginning of line.
23742 (let ((parent-contents
23743 (org-element-property
23744 :contents-begin (org-element-property :parent element))))
23745 (when (and parent-contents (= parent-contents contents-begin))
23746 (beginning-of-line))))
23747 ;; At the end of a greater element, move to the beginning of
23748 ;; the last element within.
23749 ((and contents-end (>= (point) contents-end))
23750 (goto-char (1- contents-end))
23751 (org-backward-paragraph))
23752 (t (goto-char (or post-affiliated begin))))
23753 ;; Ensure we never leave point invisible.
23754 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23756 (defun org-forward-element ()
23757 "Move forward by one element.
23758 Move to the next element at the same level, when possible."
23759 (interactive)
23760 (cond ((eobp) (user-error "Cannot move further down"))
23761 ((org-with-limited-levels (org-at-heading-p))
23762 (let ((origin (point)))
23763 (goto-char (org-end-of-subtree nil t))
23764 (unless (org-with-limited-levels (org-at-heading-p))
23765 (goto-char origin)
23766 (user-error "Cannot move further down"))))
23768 (let* ((elem (org-element-at-point))
23769 (end (org-element-property :end elem))
23770 (parent (org-element-property :parent elem)))
23771 (cond ((and parent (= (org-element-property :contents-end parent) end))
23772 (goto-char (org-element-property :end parent)))
23773 ((integer-or-marker-p end) (goto-char end))
23774 (t (message "No element at point")))))))
23776 (defun org-backward-element ()
23777 "Move backward by one element.
23778 Move to the previous element at the same level, when possible."
23779 (interactive)
23780 (cond ((bobp) (user-error "Cannot move further up"))
23781 ((org-with-limited-levels (org-at-heading-p))
23782 ;; At a headline, move to the previous one, if any, or stay
23783 ;; here.
23784 (let ((origin (point)))
23785 (org-with-limited-levels (org-backward-heading-same-level 1))
23786 ;; When current headline has no sibling above, move to its
23787 ;; parent.
23788 (when (= (point) origin)
23789 (or (org-with-limited-levels (org-up-heading-safe))
23790 (progn (goto-char origin)
23791 (user-error "Cannot move further up"))))))
23793 (let* ((elem (org-element-at-point))
23794 (beg (org-element-property :begin elem)))
23795 (cond
23796 ;; Move to beginning of current element if point isn't
23797 ;; there already.
23798 ((null beg) (message "No element at point"))
23799 ((/= (point) beg) (goto-char beg))
23800 (t (goto-char beg)
23801 (skip-chars-backward " \r\t\n")
23802 (unless (bobp)
23803 (let ((prev (org-element-at-point)))
23804 (goto-char (org-element-property :begin prev))
23805 (while (and (setq prev (org-element-property :parent prev))
23806 (<= (org-element-property :end prev) beg))
23807 (goto-char (org-element-property :begin prev)))))))))))
23809 (defun org-up-element ()
23810 "Move to upper element."
23811 (interactive)
23812 (if (org-with-limited-levels (org-at-heading-p))
23813 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23814 (let* ((elem (org-element-at-point))
23815 (parent (org-element-property :parent elem)))
23816 (if parent (goto-char (org-element-property :begin parent))
23817 (if (org-with-limited-levels (org-before-first-heading-p))
23818 (user-error "No surrounding element")
23819 (org-with-limited-levels (org-back-to-heading)))))))
23821 (defun org-down-element ()
23822 "Move to inner element."
23823 (interactive)
23824 (let ((element (org-element-at-point)))
23825 (cond
23826 ((memq (org-element-type element) '(plain-list table))
23827 (goto-char (org-element-property :contents-begin element))
23828 (forward-char))
23829 ((memq (org-element-type element) org-element-greater-elements)
23830 ;; If contents are hidden, first disclose them.
23831 (when (org-invisible-p (line-end-position)) (org-cycle))
23832 (goto-char (or (org-element-property :contents-begin element)
23833 (user-error "No content for this element"))))
23834 (t (user-error "No inner element")))))
23836 (defun org-drag-element-backward ()
23837 "Move backward element at point."
23838 (interactive)
23839 (let ((elem (or (org-element-at-point)
23840 (user-error "No element at point"))))
23841 (if (eq (org-element-type elem) 'headline)
23842 ;; Preserve point when moving a whole tree, even if point was
23843 ;; on blank lines below the headline.
23844 (let ((offset (skip-chars-backward " \t\n")))
23845 (unwind-protect (org-move-subtree-up)
23846 (forward-char (- offset))))
23847 (let ((prev-elem
23848 (save-excursion
23849 (goto-char (org-element-property :begin elem))
23850 (skip-chars-backward " \r\t\n")
23851 (unless (bobp)
23852 (let* ((beg (org-element-property :begin elem))
23853 (prev (org-element-at-point))
23854 (up prev))
23855 (while (and (setq up (org-element-property :parent up))
23856 (<= (org-element-property :end up) beg))
23857 (setq prev up))
23858 prev)))))
23859 ;; Error out if no previous element or previous element is
23860 ;; a parent of the current one.
23861 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23862 (user-error "Cannot drag element backward")
23863 (let ((pos (point)))
23864 (org-element-swap-A-B prev-elem elem)
23865 (goto-char (+ (org-element-property :begin prev-elem)
23866 (- pos (org-element-property :begin elem))))))))))
23868 (defun org-drag-element-forward ()
23869 "Move forward element at point."
23870 (interactive)
23871 (let* ((pos (point))
23872 (elem (or (org-element-at-point)
23873 (user-error "No element at point"))))
23874 (when (= (point-max) (org-element-property :end elem))
23875 (user-error "Cannot drag element forward"))
23876 (goto-char (org-element-property :end elem))
23877 (let ((next-elem (org-element-at-point)))
23878 (when (or (org-element-nested-p elem next-elem)
23879 (and (eq (org-element-type next-elem) 'headline)
23880 (not (eq (org-element-type elem) 'headline))))
23881 (goto-char pos)
23882 (user-error "Cannot drag element forward"))
23883 ;; Compute new position of point: it's shifted by NEXT-ELEM
23884 ;; body's length (without final blanks) and by the length of
23885 ;; blanks between ELEM and NEXT-ELEM.
23886 (let ((size-next (- (save-excursion
23887 (goto-char (org-element-property :end next-elem))
23888 (skip-chars-backward " \r\t\n")
23889 (forward-line)
23890 ;; Small correction if buffer doesn't end
23891 ;; with a newline character.
23892 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23893 (org-element-property :begin next-elem)))
23894 (size-blank (- (org-element-property :end elem)
23895 (save-excursion
23896 (goto-char (org-element-property :end elem))
23897 (skip-chars-backward " \r\t\n")
23898 (forward-line)
23899 (point)))))
23900 (org-element-swap-A-B elem next-elem)
23901 (goto-char (+ pos size-next size-blank))))))
23903 (defun org-drag-line-forward (arg)
23904 "Drag the line at point ARG lines forward."
23905 (interactive "p")
23906 (dotimes (_ (abs arg))
23907 (let ((c (current-column)))
23908 (if (< 0 arg)
23909 (progn
23910 (beginning-of-line 2)
23911 (transpose-lines 1)
23912 (beginning-of-line 0))
23913 (transpose-lines 1)
23914 (beginning-of-line -1))
23915 (org-move-to-column c))))
23917 (defun org-drag-line-backward (arg)
23918 "Drag the line at point ARG lines backward."
23919 (interactive "p")
23920 (org-drag-line-forward (- arg)))
23922 (defun org-mark-element ()
23923 "Put point at beginning of this element, mark at end.
23925 Interactively, if this command is repeated or (in Transient Mark
23926 mode) if the mark is active, it marks the next element after the
23927 ones already marked."
23928 (interactive)
23929 (let (deactivate-mark)
23930 (if (and (called-interactively-p 'any)
23931 (or (and (eq last-command this-command) (mark t))
23932 (and transient-mark-mode mark-active)))
23933 (set-mark
23934 (save-excursion
23935 (goto-char (mark))
23936 (goto-char (org-element-property :end (org-element-at-point)))))
23937 (let ((element (org-element-at-point)))
23938 (end-of-line)
23939 (push-mark (org-element-property :end element) t t)
23940 (goto-char (org-element-property :begin element))))))
23942 (defun org-narrow-to-element ()
23943 "Narrow buffer to current element."
23944 (interactive)
23945 (let ((elem (org-element-at-point)))
23946 (cond
23947 ((eq (car elem) 'headline)
23948 (narrow-to-region
23949 (org-element-property :begin elem)
23950 (org-element-property :end elem)))
23951 ((memq (car elem) org-element-greater-elements)
23952 (narrow-to-region
23953 (org-element-property :contents-begin elem)
23954 (org-element-property :contents-end elem)))
23956 (narrow-to-region
23957 (org-element-property :begin elem)
23958 (org-element-property :end elem))))))
23960 (defun org-transpose-element ()
23961 "Transpose current and previous elements, keeping blank lines between.
23962 Point is moved after both elements."
23963 (interactive)
23964 (org-skip-whitespace)
23965 (let ((end (org-element-property :end (org-element-at-point))))
23966 (org-drag-element-backward)
23967 (goto-char end)))
23969 (defun org-unindent-buffer ()
23970 "Un-indent the visible part of the buffer.
23971 Relative indentation (between items, inside blocks, etc.) isn't
23972 modified."
23973 (interactive)
23974 (unless (eq major-mode 'org-mode)
23975 (user-error "Cannot un-indent a buffer not in Org mode"))
23976 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23977 (unindent-tree
23978 (lambda (contents)
23979 (dolist (element (reverse contents))
23980 (if (memq (org-element-type element) '(headline section))
23981 (funcall unindent-tree (org-element-contents element))
23982 (save-excursion
23983 (save-restriction
23984 (narrow-to-region
23985 (org-element-property :begin element)
23986 (org-element-property :end element))
23987 (org-do-remove-indentation))))))))
23988 (funcall unindent-tree (org-element-contents parse-tree))))
23990 (defun org-show-children (&optional level)
23991 "Show all direct subheadings of this heading.
23992 Prefix arg LEVEL is how many levels below the current level
23993 should be shown. Default is enough to cause the following
23994 heading to appear."
23995 (interactive "p")
23996 ;; If `orgstruct-mode' is active, use the slower version.
23997 (if orgstruct-mode (call-interactively #'outline-show-children)
23998 (save-excursion
23999 (org-back-to-heading t)
24000 (let* ((current-level (funcall outline-level))
24001 (max-level (org-get-valid-level
24002 current-level
24003 (if level (prefix-numeric-value level) 1)))
24004 (end (save-excursion (org-end-of-subtree t t)))
24005 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24006 (past-first-child nil)
24007 ;; Make sure to skip inlinetasks.
24008 (re (format regexp-fmt
24009 current-level
24010 (cond
24011 ((not (featurep 'org-inlinetask)) "")
24012 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24014 (t (1- org-inlinetask-min-level))))))
24015 ;; Display parent heading.
24016 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24017 (forward-line)
24018 ;; Display children. First child may be deeper than expected
24019 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24020 ;; MAX-LEVEL accordingly.
24021 (while (re-search-forward re end t)
24022 (unless past-first-child
24023 (setq re (format regexp-fmt
24024 current-level
24025 (max (funcall outline-level) max-level)))
24026 (setq past-first-child t))
24027 (outline-flag-region
24028 (line-end-position 0) (line-end-position) nil))))))
24030 (defun org-show-subtree ()
24031 "Show everything after this heading at deeper levels."
24032 (interactive)
24033 (outline-flag-region
24034 (point)
24035 (save-excursion
24036 (org-end-of-subtree t t))
24037 nil))
24039 (defun org-show-entry ()
24040 "Show the body directly following this heading.
24041 Show the heading too, if it is currently invisible."
24042 (interactive)
24043 (save-excursion
24044 (ignore-errors
24045 (org-back-to-heading t)
24046 (outline-flag-region
24047 (max (point-min) (1- (point)))
24048 (save-excursion
24049 (if (re-search-forward
24050 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24051 (match-beginning 1)
24052 (point-max)))
24053 nil)
24054 (org-cycle-hide-drawers 'children))))
24056 (defun org-make-options-regexp (kwds &optional extra)
24057 "Make a regular expression for keyword lines.
24058 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24059 when non-nil, is a regexp matching keywords names."
24060 (concat "^[ \t]*#\\+\\("
24061 (regexp-opt kwds)
24062 (and extra (concat (and kwds "\\|") extra))
24063 "\\):[ \t]*\\(.*\\)"))
24065 ;;;; Finish up
24067 (provide 'org)
24069 (run-hooks 'org-load-hook)
24071 ;;; org.el ends here