Improve docstrings
[org-mode/org-tableheadings.git] / lisp / org.el
blob8dddf02951225f9b3965619791fbb9959822519c
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-2018 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: https://orgmode.org
10 ;; Version: 9.2
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
46 ;; webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; https://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; https://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (defvar org-inlinetask-min-level)
72 ;;;; Require other packages
74 (require 'cl-lib)
76 (eval-when-compile (require 'gnus-sum))
78 (require 'calendar)
79 (require 'find-func)
80 (require 'format-spec)
82 (or (eq this-command 'eval-buffer)
83 (condition-case nil
84 (load (concat (file-name-directory load-file-name)
85 "org-loaddefs.el")
86 nil t t t)
87 (error
88 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
89 (sit-for 3)
90 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
91 (sit-for 3))))
93 (eval-and-compile (require 'org-macs))
94 (require 'org-compat)
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 (defvar org-outline-regexp "\\*+ "
99 "Regexp to match Org headlines.")
101 (defvar org-outline-regexp-bol "^\\*+ "
102 "Regexp to match Org headlines.
103 This is similar to `org-outline-regexp' but additionally makes
104 sure that we are at the beginning of the line.")
106 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
107 "Matches a headline, putting stars and text into groups.
108 Stars are put in group 1 and the trimmed body in group 2.")
110 (declare-function calendar-check-holidays "holidays" (date))
111 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
112 (declare-function cdlatex-math-symbol "ext:cdlatex")
113 (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
114 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
115 (declare-function org-add-archive-files "org-archive" (files))
116 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
117 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
118 (declare-function org-agenda-redo "org-agenda" (&optional all))
119 (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
120 (declare-function org-archive-subtree "org-archive" (&optional find-done))
121 (declare-function org-archive-subtree-default "org-archive" ())
122 (declare-function org-archive-to-archive-sibling "org-archive" ())
123 (declare-function org-attach "org-attach" ())
124 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
125 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
126 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
127 (declare-function org-clock-cancel "org-clock" ())
128 (declare-function org-clock-display "org-clock" (&optional arg))
129 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
130 (declare-function org-clock-goto "org-clock" (&optional select))
131 (declare-function org-clock-in "org-clock" (&optional select start-time))
132 (declare-function org-clock-in-last "org-clock" (&optional arg))
133 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
134 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
135 (declare-function org-clock-report "org-clock" (&optional arg))
136 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
137 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
138 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
139 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
140 (declare-function org-clock-update-time-maybe "org-clock" ())
141 (declare-function org-clocking-buffer "org-clock" ())
142 (declare-function org-clocktable-shift "org-clock" (dir n))
143 (declare-function org-columns-insert-dblock "org-colview" ())
144 (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
145 (declare-function org-element-at-point "org-element" ())
146 (declare-function org-element-cache-refresh "org-element" (pos))
147 (declare-function org-element-cache-reset "org-element" (&optional all))
148 (declare-function org-element-contents "org-element" (element))
149 (declare-function org-element-context "org-element" (&optional element))
150 (declare-function org-element-copy "org-element" (datum))
151 (declare-function org-element-create "org-element" (type &optional props &rest children))
152 (declare-function org-element-interpret-data "org-element" (data))
153 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
154 (declare-function org-element-link-parser "org-element" ())
155 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
156 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
157 (declare-function org-element-property "org-element" (property element))
158 (declare-function org-element-put-property "org-element" (element property value))
159 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
160 (declare-function org-element-timestamp-parser "org-element" ())
161 (declare-function org-element-type "org-element" (element))
162 (declare-function org-element-update-syntax "org-element" ())
163 (declare-function org-export-dispatch "ox" (&optional arg))
164 (declare-function org-export-get-backend "ox" (name))
165 (declare-function org-export-get-backend "ox" (name))
166 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
167 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
168 (declare-function org-feed-goto-inbox "org-feed" (feed))
169 (declare-function org-feed-update-all "org-feed" ())
170 (declare-function org-goto "org-goto" (&optional alternative-interface))
171 (declare-function org-goto "org-goto" (&optional alternative-interface))
172 (declare-function org-id-find-id-file "org-id" (id))
173 (declare-function org-id-get-create "org-id" (&optional force))
174 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
175 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
176 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
177 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
178 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
179 (declare-function org-plot/gnuplot "org-plot" (&optional params))
180 (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
181 (declare-function org-table-align "org-table" ())
182 (declare-function org-table-begin "org-table" (&optional table-type))
183 (declare-function org-table-beginning-of-field "org-table" (&optional n))
184 (declare-function org-table-blank-field "org-table" ())
185 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
186 (declare-function org-table-copy-down "org-table" (N))
187 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
188 (declare-function org-table-create-or-convert-from-region "org-table" (arg))
189 (declare-function org-table-create-with-table.el "org-table" ())
190 (declare-function org-table-cut-region "org-table" (beg end))
191 (declare-function org-table-edit-field "org-table" (arg))
192 (declare-function org-table-end "org-table" (&optional table-type))
193 (declare-function org-table-end-of-field "org-table" (&optional n))
194 (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
195 (declare-function org-table-field-info "org-table" (arg))
196 (declare-function org-table-insert-row "org-table" (&optional arg))
197 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
198 (declare-function org-table-maybe-eval-formula "org-table" ())
199 (declare-function org-table-maybe-recalculate-line "org-table" ())
200 (declare-function org-table-next-row "org-table" ())
201 (declare-function org-table-paste-rectangle "org-table" ())
202 (declare-function org-table-recalculate "org-table" (&optional all noalign))
203 (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
204 (declare-function org-table-shrink "org-table" (&optional begin end))
205 (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
206 (declare-function org-table-sum "org-table" (&optional beg end nlast))
207 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
208 (declare-function org-table-toggle-coordinate-overlays "org-table" ())
209 (declare-function org-table-toggle-formula-debugger "org-table" ())
210 (declare-function org-table-wrap-region "org-table" (arg))
211 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
212 (declare-function org-timer "org-timer" (&optional restart no-insert))
213 (declare-function org-timer-item "org-timer" (&optional arg))
214 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
215 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
216 (declare-function org-timer-set-timer "org-timer" (&optional opt))
217 (declare-function org-timer-start "org-timer" (&optional offset))
218 (declare-function org-timer-stop "org-timer" ())
219 (declare-function org-timer-stop "org-timer" ())
220 (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
221 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
222 (declare-function orgtbl-mode "org-table" (&optional arg))
224 (defvar ffap-url-regexp)
225 (defvar org-element-paragraph-separate)
226 (defvar org-indent-indentation-per-level)
228 ;; load languages based on value of `org-babel-load-languages'
229 (defvar org-babel-load-languages)
231 ;;;###autoload
232 (defun org-babel-do-load-languages (sym value)
233 "Load the languages defined in `org-babel-load-languages'."
234 (set-default sym value)
235 (dolist (pair org-babel-load-languages)
236 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
237 (if active
238 (require (intern (concat "ob-" lang)))
239 (fmakunbound
240 (intern (concat "org-babel-execute:" lang)))
241 (fmakunbound
242 (intern (concat "org-babel-expand-body:" lang)))))))
244 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
245 ;;;###autoload
246 (defun org-babel-load-file (file &optional compile)
247 "Load Emacs Lisp source code blocks in the Org FILE.
248 This function exports the source code using `org-babel-tangle'
249 and then loads the resulting file using `load-file'. With prefix
250 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
251 file to byte-code before it is loaded."
252 (interactive "fFile to load: \nP")
253 (let* ((age (lambda (file)
254 (float-time
255 (time-subtract (current-time)
256 (nth 5 (or (file-attributes (file-truename file))
257 (file-attributes file)))))))
258 (base-name (file-name-sans-extension file))
259 (exported-file (concat base-name ".el")))
260 ;; tangle if the Org file is newer than the elisp file
261 (unless (and (file-exists-p exported-file)
262 (> (funcall age file) (funcall age exported-file)))
263 ;; Tangle-file traversal returns reversed list of tangled files
264 ;; and we want to evaluate the first target.
265 (setq exported-file
266 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
267 (message "%s %s"
268 (if compile
269 (progn (byte-compile-file exported-file 'load)
270 "Compiled and loaded")
271 (progn (load-file exported-file) "Loaded"))
272 exported-file)))
274 (defcustom org-babel-load-languages '((emacs-lisp . t))
275 "Languages which can be evaluated in Org buffers.
276 \\<org-mode-map>
277 This list can be used to load support for any of the languages
278 below. Each language will depend on a different set of system
279 executables and/or Emacs modes.
281 When a language is \"loaded\", code blocks in that language can
282 be evaluated with `org-babel-execute-src-block', which is bound
283 by default to \\[org-ctrl-c-ctrl-c].
285 The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
286 remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
287 default, only Emacs Lisp is loaded, since it has no specific
288 requirement."
289 :group 'org-babel
290 :set 'org-babel-do-load-languages
291 :version "24.1"
292 :type '(alist :tag "Babel Languages"
293 :key-type
294 (choice
295 (const :tag "Awk" awk)
296 (const :tag "C" C)
297 (const :tag "R" R)
298 (const :tag "Asymptote" asymptote)
299 (const :tag "Calc" calc)
300 (const :tag "Clojure" clojure)
301 (const :tag "CSS" css)
302 (const :tag "Ditaa" ditaa)
303 (const :tag "Dot" dot)
304 (const :tag "Ebnf2ps" ebnf2ps)
305 (const :tag "Emacs Lisp" emacs-lisp)
306 (const :tag "Forth" forth)
307 (const :tag "Fortran" fortran)
308 (const :tag "Gnuplot" gnuplot)
309 (const :tag "Haskell" haskell)
310 (const :tag "hledger" hledger)
311 (const :tag "IO" io)
312 (const :tag "J" J)
313 (const :tag "Java" java)
314 (const :tag "Javascript" js)
315 (const :tag "LaTeX" latex)
316 (const :tag "Ledger" ledger)
317 (const :tag "Lilypond" lilypond)
318 (const :tag "Lisp" lisp)
319 (const :tag "Makefile" makefile)
320 (const :tag "Maxima" maxima)
321 (const :tag "Matlab" matlab)
322 (const :tag "Mscgen" mscgen)
323 (const :tag "Ocaml" ocaml)
324 (const :tag "Octave" octave)
325 (const :tag "Org" org)
326 (const :tag "Perl" perl)
327 (const :tag "Pico Lisp" picolisp)
328 (const :tag "PlantUML" plantuml)
329 (const :tag "Python" python)
330 (const :tag "Ruby" ruby)
331 (const :tag "Sass" sass)
332 (const :tag "Scala" scala)
333 (const :tag "Scheme" scheme)
334 (const :tag "Screen" screen)
335 (const :tag "Shell Script" shell)
336 (const :tag "Shen" shen)
337 (const :tag "Sql" sql)
338 (const :tag "Sqlite" sqlite)
339 (const :tag "Stan" stan)
340 (const :tag "Vala" vala))
341 :value-type (boolean :tag "Activate" :value t)))
343 ;;;; Customization variables
344 (defcustom org-clone-delete-id nil
345 "Remove ID property of clones of a subtree.
346 When non-nil, clones of a subtree don't inherit the ID property.
347 Otherwise they inherit the ID property with a new unique
348 identifier."
349 :type 'boolean
350 :version "24.1"
351 :group 'org-id)
353 ;;; Version
354 (org-check-version)
356 ;;;###autoload
357 (defun org-version (&optional here full message)
358 "Show the Org version.
359 Interactively, or when MESSAGE is non-nil, show it in echo area.
360 With prefix argument, or when HERE is non-nil, insert it at point.
361 In non-interactive uses, a reduced version string is output unless
362 FULL is given."
363 (interactive (list current-prefix-arg t (not current-prefix-arg)))
364 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
365 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
366 (load-suffixes (list ".el"))
367 (org-install-dir
368 (ignore-errors (org-find-library-dir "org-loaddefs"))))
369 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
370 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
371 (let* ((load-suffixes save-load-suffixes)
372 (release (org-release))
373 (git-version (org-git-version))
374 (version (format "Org mode version %s (%s @ %s)"
375 release
376 git-version
377 (if org-install-dir
378 (if (string= org-dir org-install-dir)
379 org-install-dir
380 (concat "mixed installation! "
381 org-install-dir
382 " and "
383 org-dir))
384 "org-loaddefs.el can not be found!")))
385 (version1 (if full version release)))
386 (when here (insert version1))
387 (when message (message "%s" version1))
388 version1)))
390 (defconst org-version (org-version))
393 ;;; Syntax Constants
395 ;;;; Block
397 (defconst org-block-regexp
398 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
399 "Regular expression for hiding blocks.")
401 (defconst org-dblock-start-re
402 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
403 "Matches the start line of a dynamic block, with parameters.")
405 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
406 "Matches the end of a dynamic block.")
408 ;;;; Clock and Planning
410 (defconst org-clock-string "CLOCK:"
411 "String used as prefix for timestamps clocking work hours on an item.")
413 (defvar org-closed-string "CLOSED:"
414 "String used as the prefix for timestamps logging closing a TODO entry.")
416 (defvar org-deadline-string "DEADLINE:"
417 "String to mark deadline entries.
418 \\<org-mode-map>
419 A deadline is this string, followed by a time stamp. It must be
420 a word, terminated by a colon. You can insert a schedule keyword
421 and a timestamp with `\\[org-deadline]'.")
423 (defvar org-scheduled-string "SCHEDULED:"
424 "String to mark scheduled TODO entries.
425 \\<org-mode-map>
426 A schedule is this string, followed by a time stamp. It must be
427 a word, terminated by a colon. You can insert a schedule keyword
428 and a timestamp with `\\[org-schedule]'.")
430 (defconst org-ds-keyword-length
431 (+ 2
432 (apply #'max
433 (mapcar #'length
434 (list org-deadline-string org-scheduled-string
435 org-clock-string org-closed-string))))
436 "Maximum length of the DEADLINE and SCHEDULED keywords.")
438 (defconst org-planning-line-re
439 (concat "^[ \t]*"
440 (regexp-opt
441 (list org-closed-string org-deadline-string org-scheduled-string)
443 "Matches a line with planning info.
444 Matched keyword is in group 1.")
446 (defconst org-clock-line-re
447 (concat "^[ \t]*" org-clock-string)
448 "Matches a line with clock info.")
450 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
451 "Matches the DEADLINE keyword.")
453 (defconst org-deadline-time-regexp
454 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
455 "Matches the DEADLINE keyword together with a time stamp.")
457 (defconst org-deadline-time-hour-regexp
458 (concat "\\<" org-deadline-string
459 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
460 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
462 (defconst org-deadline-line-regexp
463 (concat "\\<\\(" org-deadline-string "\\).*")
464 "Matches the DEADLINE keyword and the rest of the line.")
466 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
467 "Matches the SCHEDULED keyword.")
469 (defconst org-scheduled-time-regexp
470 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
471 "Matches the SCHEDULED keyword together with a time stamp.")
473 (defconst org-scheduled-time-hour-regexp
474 (concat "\\<" org-scheduled-string
475 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
476 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
478 (defconst org-closed-time-regexp
479 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
480 "Matches the CLOSED keyword together with a time stamp.")
482 (defconst org-keyword-time-regexp
483 (concat "\\<"
484 (regexp-opt
485 (list org-scheduled-string org-deadline-string org-closed-string
486 org-clock-string)
488 " *[[<]\\([^]>]+\\)[]>]")
489 "Matches any of the 4 keywords, together with the time stamp.")
491 (defconst org-keyword-time-not-clock-regexp
492 (concat
493 "\\<"
494 (regexp-opt
495 (list org-scheduled-string org-deadline-string org-closed-string) t)
496 " *[[<]\\([^]>]+\\)[]>]")
497 "Matches any of the 3 keywords, together with the time stamp.")
499 (defconst org-maybe-keyword-time-regexp
500 (concat "\\(\\<"
501 (regexp-opt
502 (list org-scheduled-string org-deadline-string org-closed-string
503 org-clock-string)
505 "\\)?"
506 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
507 "\\|"
508 "<%%([^\r\n>]*>\\)")
509 "Matches a timestamp, possibly preceded by a keyword.")
511 (defconst org-all-time-keywords
512 (mapcar (lambda (w) (substring w 0 -1))
513 (list org-scheduled-string org-deadline-string
514 org-clock-string org-closed-string))
515 "List of time keywords.")
517 ;;;; Drawer
519 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
520 "Matches first or last line of a hidden block.
521 Group 1 contains drawer's name or \"END\".")
523 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
524 "Regular expression matching the first line of a property drawer.")
526 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
527 "Regular expression matching the last line of a property drawer.")
529 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
530 "Regular expression matching the first line of a clock drawer.")
532 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
533 "Regular expression matching the last line of a clock drawer.")
535 (defconst org-property-drawer-re
536 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
537 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
538 "[ \t]*:END:[ \t]*$")
539 "Matches an entire property drawer.")
541 (defconst org-clock-drawer-re
542 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
543 org-clock-drawer-end-re "\\)\n?")
544 "Matches an entire clock drawer.")
546 ;;;; Headline
548 (defconst org-heading-keyword-regexp-format
549 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
550 "Printf format for a regexp matching a headline with some keyword.
551 This regexp will match the headline of any node which has the
552 exact keyword that is put into the format. The keyword isn't in
553 any group by default, but the stars and the body are.")
555 (defconst org-heading-keyword-maybe-regexp-format
556 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
557 "Printf format for a regexp matching a headline, possibly with some keyword.
558 This regexp can match any headline with the specified keyword, or
559 without a keyword. The keyword isn't in any group by default,
560 but the stars and the body are.")
562 (defconst org-archive-tag "ARCHIVE"
563 "The tag that marks a subtree as archived.
564 An archived subtree does not open during visibility cycling, and does
565 not contribute to the agenda listings.")
567 (defconst org-tag-re "[[:alnum:]_@#%]+"
568 "Regexp matching a single tag.")
570 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
571 "Regexp matching the tag group at the end of a line, with leading spaces.
572 Tags are stored in match group 1. Match group 2 stores the tags
573 without the enclosing colons.")
575 (defconst org-tag-line-re
576 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
577 "Regexp matching tags in a headline.
578 Tags are stored in match group 1. Match group 2 stores the tags
579 without the enclosing colons.")
581 (eval-and-compile
582 (defconst org-comment-string "COMMENT"
583 "Entries starting with this keyword will never be exported.
584 \\<org-mode-map>
585 An entry can be toggled between COMMENT and normal with
586 `\\[org-toggle-comment]'."))
589 ;;;; LaTeX Environments and Fragments
591 (defconst org-latex-regexps
592 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
593 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
594 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
595 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
596 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
597 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
598 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
599 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
600 "Regular expressions for matching embedded LaTeX.")
602 ;;;; Node Property
604 (defconst org-effort-property "Effort"
605 "The property that is being used to keep track of effort estimates.
606 Effort estimates given in this property need to have the format H:MM.")
608 ;;;; Table
610 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
611 "Detect an org-type or table-type table.")
613 (defconst org-table-line-regexp "^[ \t]*|"
614 "Detect an org-type table line.")
616 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
617 "Detect an org-type table line.")
619 (defconst org-table-hline-regexp "^[ \t]*|-"
620 "Detect an org-type table hline.")
622 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
623 "Detect a table-type table hline.")
625 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
626 "Detect the first line outside a table when searching from within it.
627 This works for both table types.")
629 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
630 "Detect a #+TBLFM line.")
632 ;;;; Timestamp
634 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
635 "Regular expression for fast time stamp matching.")
637 (defconst org-ts-regexp-inactive
638 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
639 "Regular expression for fast inactive time stamp matching.")
641 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
642 "Regular expression for fast time stamp matching.")
644 (defconst org-ts-regexp0
645 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
646 "Regular expression matching time strings for analysis.
647 This one does not require the space after the date, so it can be used
648 on a string that terminates immediately after the date.")
650 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
651 "Regular expression matching time strings for analysis.")
653 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
654 "Regular expression matching time stamps, with groups.")
656 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
657 "Regular expression matching time stamps (also [..]), with groups.")
659 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
660 "Regular expression matching a time stamp range.")
662 (defconst org-tr-regexp-both
663 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
664 "Regular expression matching a time stamp range.")
666 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
667 org-ts-regexp "\\)?")
668 "Regular expression matching a time stamp or time stamp range.")
670 (defconst org-tsr-regexp-both
671 (concat org-ts-regexp-both "\\(--?-?"
672 org-ts-regexp-both "\\)?")
673 "Regular expression matching a time stamp or time stamp range.
674 The time stamps may be either active or inactive.")
676 (defconst org-repeat-re
677 "[[<][0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^]>\n]*?\
678 \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
679 "Regular expression for specifying repeated events.
680 After a match, group 1 contains the repeat expression.")
682 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
683 "Formats for `format-time-string' which are used for time stamps.")
686 ;;; The custom variables
688 (defgroup org nil
689 "Outline-based notes management and organizer."
690 :tag "Org"
691 :group 'outlines
692 :group 'calendar)
694 (defcustom org-mode-hook nil
695 "Mode hook for Org mode, run after the mode was turned on."
696 :group 'org
697 :type 'hook)
699 (defcustom org-load-hook nil
700 "Hook that is run after org.el has been loaded."
701 :group 'org
702 :type 'hook)
704 (defcustom org-log-buffer-setup-hook nil
705 "Hook that is run after an Org log buffer is created."
706 :group 'org
707 :version "24.1"
708 :type 'hook)
710 (defvar org-modules) ; defined below
711 (defvar org-modules-loaded nil
712 "Have the modules been loaded already?")
714 (defun org-load-modules-maybe (&optional force)
715 "Load all extensions listed in `org-modules'."
716 (when (or force (not org-modules-loaded))
717 (dolist (ext org-modules)
718 (condition-case nil (require ext)
719 (error (message "Problems while trying to load feature `%s'" ext))))
720 (setq org-modules-loaded t)))
722 (defun org-set-modules (var value)
723 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
724 (set var value)
725 (when (featurep 'org)
726 (org-load-modules-maybe 'force)
727 (org-element-cache-reset 'all)))
729 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
730 "Modules that should always be loaded together with org.el.
732 If a description starts with <C>, the file is not part of Emacs
733 and loading it will require that you have downloaded and properly
734 installed the Org mode distribution.
736 You can also use this system to load external packages (i.e. neither Org
737 core modules, nor modules from the CONTRIB directory). Just add symbols
738 to the end of the list. If the package is called org-xyz.el, then you need
739 to add the symbol `xyz', and the package must have a call to:
741 (provide \\='org-xyz)
743 For export specific modules, see also `org-export-backends'."
744 :group 'org
745 :set 'org-set-modules
746 :version "26.1"
747 :package-version '(Org . "9.2")
748 :type
749 '(set :greedy t
750 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
751 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
752 (const :tag " crypt: Encryption of subtrees" org-crypt)
753 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
754 (const :tag " docview: Links to doc-view buffers" org-docview)
755 (const :tag " eww: Store link to url of eww" org-eww)
756 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
757 (const :tag " habit: Track your consistency with habits" org-habit)
758 (const :tag " id: Global IDs for identifying entries" org-id)
759 (const :tag " info: Links to Info nodes" org-info)
760 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
761 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
762 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
763 (const :tag " mouse: Additional mouse support" org-mouse)
764 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
765 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
766 (const :tag " tempo: Fast completion for structures" org-tempo)
767 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
768 (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
770 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
771 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
772 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
773 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
774 (const :tag "C collector: Collect properties into tables" org-collector)
775 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
776 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
777 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
778 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
779 (const :tag "C eval: Include command output as text" org-eval)
780 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
781 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
782 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
783 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
784 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
785 (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
786 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
787 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
788 (const :tag "C man: Support for links to manpages in Org mode" org-man)
789 (const :tag "C mew: Links to Mew folders/messages" org-mew)
790 (const :tag "C notify: Notifications for Org-mode" org-notify)
791 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
792 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
793 (const :tag "C registry: A registry for Org links" org-registry)
794 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
795 (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
796 (const :tag "C secretary: Team management with Org" org-secretary)
797 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
798 (const :tag "C toc: Table of contents for Org buffer" org-toc)
799 (const :tag "C track: Keep up with Org mode development" org-track)
800 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
801 (const :tag "C vm: Links to VM folders/messages" org-vm)
802 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
803 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
804 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
806 (defvar org-export-registered-backends) ; From ox.el.
807 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
808 (declare-function org-export-backend-name "ox" (backend) t)
809 (defcustom org-export-backends '(ascii html icalendar latex odt)
810 "List of export back-ends that should be always available.
812 If a description starts with <C>, the file is not part of Emacs
813 and loading it will require that you have downloaded and properly
814 installed the Org mode distribution.
816 Unlike to `org-modules', libraries in this list will not be
817 loaded along with Org, but only once the export framework is
818 needed.
820 This variable needs to be set before org.el is loaded. If you
821 need to make a change while Emacs is running, use the customize
822 interface or run the following code, where VAL stands for the new
823 value of the variable, after updating it:
825 (progn
826 (setq org-export-registered-backends
827 (cl-remove-if-not
828 (lambda (backend)
829 (let ((name (org-export-backend-name backend)))
830 (or (memq name val)
831 (catch \\='parentp
832 (dolist (b val)
833 (and (org-export-derived-backend-p b name)
834 (throw \\='parentp t)))))))
835 org-export-registered-backends))
836 (let ((new-list (mapcar #\\='org-export-backend-name
837 org-export-registered-backends)))
838 (dolist (backend val)
839 (cond
840 ((not (load (format \"ox-%s\" backend) t t))
841 (message \"Problems while trying to load export back-end \\=`%s\\='\"
842 backend))
843 ((not (memq backend new-list)) (push backend new-list))))
844 (set-default \\='org-export-backends new-list)))
846 Adding a back-end to this list will also pull the back-end it
847 depends on, if any."
848 :group 'org
849 :group 'org-export
850 :version "26.1"
851 :package-version '(Org . "9.0")
852 :initialize 'custom-initialize-set
853 :set (lambda (var val)
854 (if (not (featurep 'ox)) (set-default var val)
855 ;; Any back-end not required anymore (not present in VAL and not
856 ;; a parent of any back-end in the new value) is removed from the
857 ;; list of registered back-ends.
858 (setq org-export-registered-backends
859 (cl-remove-if-not
860 (lambda (backend)
861 (let ((name (org-export-backend-name backend)))
862 (or (memq name val)
863 (catch 'parentp
864 (dolist (b val)
865 (and (org-export-derived-backend-p b name)
866 (throw 'parentp t)))))))
867 org-export-registered-backends))
868 ;; Now build NEW-LIST of both new back-ends and required
869 ;; parents.
870 (let ((new-list (mapcar #'org-export-backend-name
871 org-export-registered-backends)))
872 (dolist (backend val)
873 (cond
874 ((not (load (format "ox-%s" backend) t t))
875 (message "Problems while trying to load export back-end `%s'"
876 backend))
877 ((not (memq backend new-list)) (push backend new-list))))
878 ;; Set VAR to that list with fixed dependencies.
879 (set-default var new-list))))
880 :type '(set :greedy t
881 (const :tag " ascii Export buffer to ASCII format" ascii)
882 (const :tag " beamer Export buffer to Beamer presentation" beamer)
883 (const :tag " html Export buffer to HTML format" html)
884 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
885 (const :tag " latex Export buffer to LaTeX format" latex)
886 (const :tag " man Export buffer to MAN format" man)
887 (const :tag " md Export buffer to Markdown format" md)
888 (const :tag " odt Export buffer to ODT format" odt)
889 (const :tag " org Export buffer to Org format" org)
890 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
891 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
892 (const :tag "C deck Export buffer to deck.js presentations" deck)
893 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
894 (const :tag "C groff Export buffer to Groff format" groff)
895 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
896 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
897 (const :tag "C s5 Export buffer to s5 presentations" s5)
898 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
900 (eval-after-load 'ox
901 '(dolist (backend org-export-backends)
902 (condition-case nil (require (intern (format "ox-%s" backend)))
903 (error (message "Problems while trying to load export back-end `%s'"
904 backend)))))
906 (defcustom org-support-shift-select nil
907 "Non-nil means make shift-cursor commands select text when possible.
908 \\<org-mode-map>\
910 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
911 start selecting a region, or enlarge regions started in this way.
912 In Org mode, in special contexts, these same keys are used for
913 other purposes, important enough to compete with shift selection.
914 Org tries to balance these needs by supporting `shift-select-mode'
915 outside these special contexts, under control of this variable.
917 The default of this variable is nil, to avoid confusing behavior. Shifted
918 cursor keys will then execute Org commands in the following contexts:
919 - on a headline, changing TODO state (left/right) and priority (up/down)
920 - on a time stamp, changing the time
921 - in a plain list item, changing the bullet type
922 - in a property definition line, switching between allowed values
923 - in the BEGIN line of a clock table (changing the time block).
924 Outside these contexts, the commands will throw an error.
926 When this variable is t and the cursor is not in a special
927 context, Org mode will support shift-selection for making and
928 enlarging regions. To make this more effective, the bullet
929 cycling will no longer happen anywhere in an item line, but only
930 if the cursor is exactly on the bullet.
932 If you set this variable to the symbol `always', then the keys
933 will not be special in headlines, property lines, and item lines,
934 to make shift selection work there as well. If this is what you
935 want, you can use the following alternative commands:
936 `\\[org-todo]' and `\\[org-priority]' \
937 to change TODO state and priority,
938 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
939 can be used to switch TODO sets,
940 `\\[org-ctrl-c-minus]' to cycle item bullet types,
941 and properties can be edited by hand or in column view.
943 However, when the cursor is on a timestamp, shift-cursor commands
944 will still edit the time stamp - this is just too good to give up."
945 :group 'org
946 :type '(choice
947 (const :tag "Never" nil)
948 (const :tag "When outside special context" t)
949 (const :tag "Everywhere except timestamps" always)))
951 (defcustom org-loop-over-headlines-in-active-region nil
952 "Shall some commands act upon headlines in the active region?
954 When set to t, some commands will be performed in all headlines
955 within the active region.
957 When set to `start-level', some commands will be performed in all
958 headlines within the active region, provided that these headlines
959 are of the same level than the first one.
961 When set to a string, those commands will be performed on the
962 matching headlines within the active region. Such string must be
963 a tags/property/todo match as it is used in the agenda tags view.
965 The list of commands is: `org-schedule', `org-deadline',
966 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
967 `org-archive-to-archive-sibling'. The archiving commands skip
968 already archived entries."
969 :type '(choice (const :tag "Don't loop" nil)
970 (const :tag "All headlines in active region" t)
971 (const :tag "In active region, headlines at the same level than the first one" start-level)
972 (string :tag "Tags/Property/Todo matcher"))
973 :version "24.1"
974 :group 'org-todo
975 :group 'org-archive)
977 (defcustom org-startup-folded t
978 "Non-nil means entering Org mode will switch to OVERVIEW.
980 This can also be configured on a per-file basis by adding one of
981 the following lines anywhere in the buffer:
983 #+STARTUP: fold (or `overview', this is equivalent)
984 #+STARTUP: nofold (or `showall', this is equivalent)
985 #+STARTUP: content
986 #+STARTUP: showeverything
988 Set `org-agenda-inhibit-startup' to a non-nil value if you want
989 to ignore this option when Org opens agenda files for the first
990 time."
991 :group 'org-startup
992 :type '(choice
993 (const :tag "nofold: show all" nil)
994 (const :tag "fold: overview" t)
995 (const :tag "content: all headlines" content)
996 (const :tag "show everything, even drawers" showeverything)))
998 (defcustom org-startup-truncated t
999 "Non-nil means entering Org mode will set `truncate-lines'.
1000 This is useful since some lines containing links can be very long and
1001 uninteresting. Also tables look terrible when wrapped.
1003 The variable `org-startup-truncated' allows to configure
1004 truncation for Org mode different to the other modes that use the
1005 variable `truncate-lines' and as a shortcut instead of putting
1006 the variable `truncate-lines' into the `org-mode-hook'. If one
1007 wants to configure truncation for Org mode not statically but
1008 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
1009 the variable `truncate-lines' has to be used because in such a
1010 case it is too late to set the variable `org-startup-truncated'."
1011 :group 'org-startup
1012 :type 'boolean)
1014 (defcustom org-startup-indented nil
1015 "Non-nil means turn on `org-indent-mode' on startup.
1016 This can also be configured on a per-file basis by adding one of
1017 the following lines anywhere in the buffer:
1019 #+STARTUP: indent
1020 #+STARTUP: noindent"
1021 :group 'org-structure
1022 :type '(choice
1023 (const :tag "Not" nil)
1024 (const :tag "Globally (slow on startup in large files)" t)))
1026 (defcustom org-use-sub-superscripts t
1027 "Non-nil means interpret \"_\" and \"^\" for display.
1029 If you want to control how Org exports those characters, see
1030 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
1031 used to be an alias for `org-export-with-sub-superscripts' in
1032 Org <8.0, it is not anymore.
1034 When this option is turned on, you can use TeX-like syntax for
1035 sub- and superscripts within the buffer. Several characters after
1036 \"_\" or \"^\" will be considered as a single item - so grouping
1037 with {} is normally not needed. For example, the following things
1038 will be parsed as single sub- or superscripts:
1040 10^24 or 10^tau several digits will be considered 1 item.
1041 10^-12 or 10^-tau a leading sign with digits or a word
1042 x^2-y^3 will be read as x^2 - y^3, because items are
1043 terminated by almost any nonword/nondigit char.
1044 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1046 Still, ambiguity is possible. So when in doubt, use {} to enclose
1047 the sub/superscript. If you set this variable to the symbol `{}',
1048 the braces are *required* in order to trigger interpretations as
1049 sub/superscript. This can be helpful in documents that need \"_\"
1050 frequently in plain text."
1051 :group 'org-startup
1052 :version "24.4"
1053 :package-version '(Org . "8.0")
1054 :type '(choice
1055 (const :tag "Always interpret" t)
1056 (const :tag "Only with braces" {})
1057 (const :tag "Never interpret" nil)))
1059 (defcustom org-startup-with-beamer-mode nil
1060 "Non-nil means turn on `org-beamer-mode' on startup.
1061 This can also be configured on a per-file basis by adding one of
1062 the following lines anywhere in the buffer:
1064 #+STARTUP: beamer"
1065 :group 'org-startup
1066 :version "24.1"
1067 :type 'boolean)
1069 (defcustom org-startup-align-all-tables nil
1070 "Non-nil means align all tables when visiting a file.
1071 This can also be configured on a per-file basis by adding one of
1072 the following lines anywhere in the buffer:
1073 #+STARTUP: align
1074 #+STARTUP: noalign"
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defcustom org-startup-shrink-all-tables nil
1079 "Non-nil means shrink all table columns with a width cookie.
1080 This can also be configured on a per-file basis by adding one of
1081 the following lines anywhere in the buffer:
1082 #+STARTUP: shrink"
1083 :group 'org-startup
1084 :type 'boolean
1085 :version "27.1"
1086 :package-version '(Org . "9.2")
1087 :safe #'booleanp)
1089 (defcustom org-startup-with-inline-images nil
1090 "Non-nil means show inline images when loading a new Org file.
1091 This can also be configured on a per-file basis by adding one of
1092 the following lines anywhere in the buffer:
1093 #+STARTUP: inlineimages
1094 #+STARTUP: noinlineimages"
1095 :group 'org-startup
1096 :version "24.1"
1097 :type 'boolean)
1099 (defcustom org-startup-with-latex-preview nil
1100 "Non-nil means preview LaTeX fragments when loading a new Org file.
1102 This can also be configured on a per-file basis by adding one of
1103 the following lines anywhere in the buffer:
1104 #+STARTUP: latexpreview
1105 #+STARTUP: nolatexpreview"
1106 :group 'org-startup
1107 :version "24.4"
1108 :package-version '(Org . "8.0")
1109 :type 'boolean)
1111 (defcustom org-insert-mode-line-in-empty-file nil
1112 "Non-nil means insert the first line setting Org mode in empty files.
1113 When the function `org-mode' is called interactively in an empty file, this
1114 normally means that the file name does not automatically trigger Org mode.
1115 To ensure that the file will always be in Org mode in the future, a
1116 line enforcing Org mode will be inserted into the buffer, if this option
1117 has been set."
1118 :group 'org-startup
1119 :type 'boolean)
1121 (defcustom org-replace-disputed-keys nil
1122 "Non-nil means use alternative key bindings for some keys.
1124 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1125 These keys are also used by other packages like Shift Select mode,
1126 CUA mode or Windmove. If you want to use Org mode together with
1127 one of these other modes, or more generally if you would like to
1128 move some Org mode commands to other keys, set this variable and
1129 configure the keys with the variable `org-disputed-keys'.
1131 This option is only relevant at load-time of Org mode, and must be set
1132 *before* org.el is loaded. Changing it requires a restart of Emacs to
1133 become effective."
1134 :group 'org-startup
1135 :type 'boolean)
1137 (defcustom org-use-extra-keys nil
1138 "Non-nil means use extra key sequence definitions for certain commands.
1139 This happens automatically if `window-system' is nil. This
1140 variable lets you do the same manually. You must set it before
1141 loading Org."
1142 :group 'org-startup
1143 :type 'boolean)
1145 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1147 (defcustom org-disputed-keys
1148 '(([(shift up)] . [(meta p)])
1149 ([(shift down)] . [(meta n)])
1150 ([(shift left)] . [(meta -)])
1151 ([(shift right)] . [(meta +)])
1152 ([(control shift right)] . [(meta shift +)])
1153 ([(control shift left)] . [(meta shift -)]))
1154 "Keys for which Org mode and other modes compete.
1155 This is an alist, cars are the default keys, second element specifies
1156 the alternative to use when `org-replace-disputed-keys' is t.
1158 Keys can be specified in any syntax supported by `define-key'.
1159 The value of this option takes effect only at Org mode startup,
1160 therefore you'll have to restart Emacs to apply it after changing."
1161 :group 'org-startup
1162 :type 'alist)
1164 (defun org-key (key)
1165 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1166 Or return the original if not disputed."
1167 (when org-replace-disputed-keys
1168 (let* ((nkey (key-description key))
1169 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1170 org-disputed-keys)))
1171 (setq key (if x (cdr x) key))))
1172 key)
1174 (defun org-defkey (keymap key def)
1175 "Define a key, possibly translated, as returned by `org-key'."
1176 (define-key keymap (org-key key) def))
1178 (defcustom org-ellipsis nil
1179 "The ellipsis to use in the Org mode outline.
1181 When nil, just use the standard three dots. When a non-empty string,
1182 use that string instead.
1184 The change affects only Org mode (which will then use its own display table).
1185 Changing this requires executing `\\[org-mode]' in a buffer to become
1186 effective."
1187 :group 'org-startup
1188 :type '(choice (const :tag "Default" nil)
1189 (string :tag "String" :value "...#"))
1190 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1192 (defvar org-display-table nil
1193 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1195 (defgroup org-keywords nil
1196 "Keywords in Org mode."
1197 :tag "Org Keywords"
1198 :group 'org)
1200 (defcustom org-closed-keep-when-no-todo nil
1201 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1202 :group 'org-todo
1203 :group 'org-keywords
1204 :version "24.4"
1205 :package-version '(Org . "8.0")
1206 :type 'boolean)
1208 (defgroup org-structure nil
1209 "Options concerning the general structure of Org files."
1210 :tag "Org Structure"
1211 :group 'org)
1213 (defgroup org-reveal-location nil
1214 "Options about how to make context of a location visible."
1215 :tag "Org Reveal Location"
1216 :group 'org-structure)
1218 (defcustom org-show-context-detail '((agenda . local)
1219 (bookmark-jump . lineage)
1220 (isearch . lineage)
1221 (default . ancestors))
1222 "Alist between context and visibility span when revealing a location.
1224 \\<org-mode-map>Some actions may move point into invisible
1225 locations. As a consequence, Org always expose a neighborhood
1226 around point. How much is shown depends on the initial action,
1227 or context. Valid contexts are
1229 agenda when exposing an entry from the agenda
1230 org-goto when using the command `org-goto' (`\\[org-goto]')
1231 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1232 tags-tree when constructing a sparse tree based on tags matches
1233 link-search when exposing search matches associated with a link
1234 mark-goto when exposing the jump goal of a mark
1235 bookmark-jump when exposing a bookmark location
1236 isearch when exiting from an incremental search
1237 default default for all contexts not set explicitly
1239 Allowed visibility spans are
1241 minimal show current headline; if point is not on headline,
1242 also show entry
1244 local show current headline, entry and next headline
1246 ancestors show current headline and its direct ancestors; if
1247 point is not on headline, also show entry
1249 lineage show current headline, its direct ancestors and all
1250 their children; if point is not on headline, also show
1251 entry and first child
1253 tree show current headline, its direct ancestors and all
1254 their children; if point is not on headline, also show
1255 entry and all children
1257 canonical show current headline, its direct ancestors along with
1258 their entries and children; if point is not located on
1259 the headline, also show current entry and all children
1261 As special cases, a nil or t value means show all contexts in
1262 `minimal' or `canonical' view, respectively.
1264 Some views can make displayed information very compact, but also
1265 make it harder to edit the location of the match. In such
1266 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1267 more context."
1268 :group 'org-reveal-location
1269 :version "26.1"
1270 :package-version '(Org . "9.0")
1271 :type '(choice
1272 (const :tag "Canonical" t)
1273 (const :tag "Minimal" nil)
1274 (repeat :greedy t :tag "Individual contexts"
1275 (cons
1276 (choice :tag "Context"
1277 (const agenda)
1278 (const org-goto)
1279 (const occur-tree)
1280 (const tags-tree)
1281 (const link-search)
1282 (const mark-goto)
1283 (const bookmark-jump)
1284 (const isearch)
1285 (const default))
1286 (choice :tag "Detail level"
1287 (const minimal)
1288 (const local)
1289 (const ancestors)
1290 (const lineage)
1291 (const tree)
1292 (const canonical))))))
1294 (defcustom org-indirect-buffer-display 'other-window
1295 "How should indirect tree buffers be displayed?
1297 This applies to indirect buffers created with the commands
1298 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1300 Valid values are:
1301 current-window Display in the current window
1302 other-window Just display in another window.
1303 dedicated-frame Create one new frame, and re-use it each time.
1304 new-frame Make a new frame each time. Note that in this case
1305 previously-made indirect buffers are kept, and you need to
1306 kill these buffers yourself."
1307 :group 'org-structure
1308 :group 'org-agenda-windows
1309 :type '(choice
1310 (const :tag "In current window" current-window)
1311 (const :tag "In current frame, other window" other-window)
1312 (const :tag "Each time a new frame" new-frame)
1313 (const :tag "One dedicated frame" dedicated-frame)))
1315 (defcustom org-use-speed-commands nil
1316 "Non-nil means activate single letter commands at beginning of a headline.
1317 This may also be a function to test for appropriate locations where speed
1318 commands should be active.
1320 For example, to activate speed commands when the point is on any
1321 star at the beginning of the headline, you can do this:
1323 (setq org-use-speed-commands
1324 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1325 :group 'org-structure
1326 :type '(choice
1327 (const :tag "Never" nil)
1328 (const :tag "At beginning of headline stars" t)
1329 (function)))
1331 (defcustom org-speed-commands-user nil
1332 "Alist of additional speed commands.
1333 This list will be checked before `org-speed-commands-default'
1334 when the variable `org-use-speed-commands' is non-nil
1335 and when the cursor is at the beginning of a headline.
1336 The car of each entry is a string with a single letter, which must
1337 be assigned to `self-insert-command' in the global map.
1338 The cdr is either a command to be called interactively, a function
1339 to be called, or a form to be evaluated.
1340 An entry that is just a list with a single string will be interpreted
1341 as a descriptive headline that will be added when listing the speed
1342 commands in the Help buffer using the `?' speed command."
1343 :group 'org-structure
1344 :type '(repeat :value ("k" . ignore)
1345 (choice :value ("k" . ignore)
1346 (list :tag "Descriptive Headline" (string :tag "Headline"))
1347 (cons :tag "Letter and Command"
1348 (string :tag "Command letter")
1349 (choice
1350 (function)
1351 (sexp))))))
1353 (defcustom org-bookmark-names-plist
1354 '(:last-capture "org-capture-last-stored"
1355 :last-refile "org-refile-last-stored"
1356 :last-capture-marker "org-capture-last-stored-marker")
1357 "Names for bookmarks automatically set by some Org commands.
1358 This can provide strings as names for a number of bookmarks Org sets
1359 automatically. The following keys are currently implemented:
1360 :last-capture
1361 :last-capture-marker
1362 :last-refile
1363 When a key does not show up in the property list, the corresponding bookmark
1364 is not set."
1365 :group 'org-structure
1366 :type 'plist)
1368 (defgroup org-cycle nil
1369 "Options concerning visibility cycling in Org mode."
1370 :tag "Org Cycle"
1371 :group 'org-structure)
1373 (defcustom org-cycle-skip-children-state-if-no-children t
1374 "Non-nil means skip CHILDREN state in entries that don't have any."
1375 :group 'org-cycle
1376 :type 'boolean)
1378 (defcustom org-cycle-max-level nil
1379 "Maximum level which should still be subject to visibility cycling.
1380 Levels higher than this will, for cycling, be treated as text, not a headline.
1381 When `org-odd-levels-only' is set, a value of N in this variable actually
1382 means 2N-1 stars as the limiting headline.
1383 When nil, cycle all levels.
1384 Note that the limiting level of cycling is also influenced by
1385 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1386 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1387 than its value."
1388 :group 'org-cycle
1389 :type '(choice
1390 (const :tag "No limit" nil)
1391 (integer :tag "Maximum level")))
1393 (defcustom org-hide-block-startup nil
1394 "Non-nil means entering Org mode will fold all blocks.
1395 This can also be set in on a per-file basis with
1397 #+STARTUP: hideblocks
1398 #+STARTUP: showblocks"
1399 :group 'org-startup
1400 :group 'org-cycle
1401 :type 'boolean)
1403 (defcustom org-cycle-global-at-bob nil
1404 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1406 This makes it possible to do global cycling without having to use `S-TAB'
1407 or `\\[universal-argument] TAB'. For this special case to work, the first \
1408 line of the buffer
1409 must not be a headline -- it may be empty or some other text.
1411 When used in this way, `org-cycle-hook' is disabled temporarily to make
1412 sure the cursor stays at the beginning of the buffer.
1414 When this option is nil, don't do anything special at the beginning of
1415 the buffer."
1416 :group 'org-cycle
1417 :type 'boolean)
1419 (defcustom org-cycle-level-after-item/entry-creation t
1420 "Non-nil means cycle entry level or item indentation in new empty entries.
1422 When the cursor is at the end of an empty headline, i.e., with only stars
1423 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1424 and then all possible ancestor states, before returning to the original state.
1425 This makes data entry extremely fast: M-RET to create a new headline,
1426 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1428 When the cursor is at the end of an empty plain list item, one TAB will
1429 make it a subitem, two or more tabs will back up to make this an item
1430 higher up in the item hierarchy."
1431 :group 'org-cycle
1432 :type 'boolean)
1434 (defcustom org-cycle-emulate-tab t
1435 "Where should `org-cycle' emulate TAB.
1436 nil Never
1437 white Only in completely white lines
1438 whitestart Only at the beginning of lines, before the first non-white char
1439 t Everywhere except in headlines
1440 exc-hl-bol Everywhere except at the start of a headline
1441 If TAB is used in a place where it does not emulate TAB, the current subtree
1442 visibility is cycled."
1443 :group 'org-cycle
1444 :type '(choice (const :tag "Never" nil)
1445 (const :tag "Only in completely white lines" white)
1446 (const :tag "Before first char in a line" whitestart)
1447 (const :tag "Everywhere except in headlines" t)
1448 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1450 (defcustom org-cycle-separator-lines 2
1451 "Number of empty lines needed to keep an empty line between collapsed trees.
1452 If you leave an empty line between the end of a subtree and the following
1453 headline, this empty line is hidden when the subtree is folded.
1454 Org mode will leave (exactly) one empty line visible if the number of
1455 empty lines is equal or larger to the number given in this variable.
1456 So the default 2 means at least 2 empty lines after the end of a subtree
1457 are needed to produce free space between a collapsed subtree and the
1458 following headline.
1460 If the number is negative, and the number of empty lines is at least -N,
1461 all empty lines are shown.
1463 Special case: when 0, never leave empty lines in collapsed view."
1464 :group 'org-cycle
1465 :type 'integer)
1466 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1468 (defcustom org-pre-cycle-hook nil
1469 "Hook that is run before visibility cycling is happening.
1470 The function(s) in this hook must accept a single argument which indicates
1471 the new state that will be set right after running this hook. The
1472 argument is a symbol. Before a global state change, it can have the values
1473 `overview', `content', or `all'. Before a local state change, it can have
1474 the values `folded', `children', or `subtree'."
1475 :group 'org-cycle
1476 :type 'hook)
1478 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1479 org-cycle-show-empty-lines
1480 org-optimize-window-after-visibility-change)
1481 "Hook that is run after `org-cycle' has changed the buffer visibility.
1482 The function(s) in this hook must accept a single argument which indicates
1483 the new state that was set by the most recent `org-cycle' command. The
1484 argument is a symbol. After a global state change, it can have the values
1485 `overview', `contents', or `all'. After a local state change, it can have
1486 the values `folded', `children', or `subtree'."
1487 :group 'org-cycle
1488 :type 'hook
1489 :version "26.1"
1490 :package-version '(Org . "8.3"))
1492 (defgroup org-edit-structure nil
1493 "Options concerning structure editing in Org mode."
1494 :tag "Org Edit Structure"
1495 :group 'org-structure)
1497 (defcustom org-odd-levels-only nil
1498 "Non-nil means skip even levels and only use odd levels for the outline.
1499 This has the effect that two stars are being added/taken away in
1500 promotion/demotion commands. It also influences how levels are
1501 handled by the exporters.
1502 Changing it requires restart of `font-lock-mode' to become effective
1503 for fontification also in regions already fontified.
1504 You may also set this on a per-file basis by adding one of the following
1505 lines to the buffer:
1507 #+STARTUP: odd
1508 #+STARTUP: oddeven"
1509 :group 'org-edit-structure
1510 :group 'org-appearance
1511 :type 'boolean)
1513 (defcustom org-adapt-indentation t
1514 "Non-nil means adapt indentation to outline node level.
1516 When this variable is set, Org assumes that you write outlines by
1517 indenting text in each node to align with the headline (after the
1518 stars). The following issues are influenced by this variable:
1520 - The indentation is increased by one space in a demotion
1521 command, and decreased by one in a promotion command. However,
1522 in the latter case, if shifting some line in the entry body
1523 would alter document structure (e.g., insert a new headline),
1524 indentation is not changed at all.
1526 - Property drawers and planning information is inserted indented
1527 when this variable is set. When nil, they will not be indented.
1529 - TAB indents a line relative to current level. The lines below
1530 a headline will be indented when this variable is set.
1532 Note that this is all about true indentation, by adding and
1533 removing space characters. See also \"org-indent.el\" which does
1534 level-dependent indentation in a virtual way, i.e. at display
1535 time in Emacs."
1536 :group 'org-edit-structure
1537 :type 'boolean
1538 :safe #'booleanp)
1540 (defcustom org-special-ctrl-a/e nil
1541 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1543 When t, `C-a' will bring back the cursor to the beginning of the
1544 headline text, i.e. after the stars and after a possible TODO
1545 keyword. In an item, this will be the position after bullet and
1546 check-box, if any. When the cursor is already at that position,
1547 another `C-a' will bring it to the beginning of the line.
1549 `C-e' will jump to the end of the headline, ignoring the presence
1550 of tags in the headline. A second `C-e' will then jump to the
1551 true end of the line, after any tags. This also means that, when
1552 this variable is non-nil, `C-e' also will never jump beyond the
1553 end of the heading of a folded section, i.e. not after the
1554 ellipses.
1556 When set to the symbol `reversed', the first `C-a' or `C-e' works
1557 normally, going to the true line boundary first. Only a directly
1558 following, identical keypress will bring the cursor to the
1559 special positions.
1561 This may also be a cons cell where the behavior for `C-a' and
1562 `C-e' is set separately."
1563 :group 'org-edit-structure
1564 :type '(choice
1565 (const :tag "off" nil)
1566 (const :tag "on: after stars/bullet and before tags first" t)
1567 (const :tag "reversed: true line boundary first" reversed)
1568 (cons :tag "Set C-a and C-e separately"
1569 (choice :tag "Special C-a"
1570 (const :tag "off" nil)
1571 (const :tag "on: after stars/bullet first" t)
1572 (const :tag "reversed: before stars/bullet first" reversed))
1573 (choice :tag "Special C-e"
1574 (const :tag "off" nil)
1575 (const :tag "on: before tags first" t)
1576 (const :tag "reversed: after tags first" reversed)))))
1577 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1579 (defcustom org-special-ctrl-k nil
1580 "Non-nil means `C-k' will behave specially in headlines.
1581 When nil, `C-k' will call the default `kill-line' command.
1582 When t, the following will happen while the cursor is in the headline:
1584 - When the cursor is at the beginning of a headline, kill the entire
1585 line and possible the folded subtree below the line.
1586 - When in the middle of the headline text, kill the headline up to the tags.
1587 - When after the headline text, kill the tags."
1588 :group 'org-edit-structure
1589 :type 'boolean)
1591 (defcustom org-ctrl-k-protect-subtree nil
1592 "Non-nil means, do not delete a hidden subtree with C-k.
1593 When set to the symbol `error', simply throw an error when C-k is
1594 used to kill (part-of) a headline that has hidden text behind it.
1595 Any other non-nil value will result in a query to the user, if it is
1596 OK to kill that hidden subtree. When nil, kill without remorse."
1597 :group 'org-edit-structure
1598 :version "24.1"
1599 :type '(choice
1600 (const :tag "Do not protect hidden subtrees" nil)
1601 (const :tag "Protect hidden subtrees with a security query" t)
1602 (const :tag "Never kill a hidden subtree with C-k" error)))
1604 (defcustom org-special-ctrl-o t
1605 "Non-nil means, make `C-o' insert a row in tables."
1606 :group 'org-edit-structure
1607 :type 'boolean)
1609 (defcustom org-catch-invisible-edits nil
1610 "Check if in invisible region before inserting or deleting a character.
1611 Valid values are:
1613 nil Do not check, so just do invisible edits.
1614 error Throw an error and do nothing.
1615 show Make point visible, and do the requested edit.
1616 show-and-error Make point visible, then throw an error and abort the edit.
1617 smart Make point visible, and do insertion/deletion if it is
1618 adjacent to visible text and the change feels predictable.
1619 Never delete a previously invisible character or add in the
1620 middle or right after an invisible region. Basically, this
1621 allows insertion and backward-delete right before ellipses.
1622 FIXME: maybe in this case we should not even show?"
1623 :group 'org-edit-structure
1624 :version "24.1"
1625 :type '(choice
1626 (const :tag "Do not check" nil)
1627 (const :tag "Throw error when trying to edit" error)
1628 (const :tag "Unhide, but do not do the edit" show-and-error)
1629 (const :tag "Show invisible part and do the edit" show)
1630 (const :tag "Be smart and do the right thing" smart)))
1632 (defcustom org-yank-folded-subtrees t
1633 "Non-nil means when yanking subtrees, fold them.
1634 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1635 it starts with a heading and all other headings in it are either children
1636 or siblings, then fold all the subtrees. However, do this only if no
1637 text after the yank would be swallowed into a folded tree by this action."
1638 :group 'org-edit-structure
1639 :type 'boolean)
1641 (defcustom org-yank-adjusted-subtrees nil
1642 "Non-nil means when yanking subtrees, adjust the level.
1643 With this setting, `org-paste-subtree' is used to insert the subtree, see
1644 this function for details."
1645 :group 'org-edit-structure
1646 :type 'boolean)
1648 (defcustom org-M-RET-may-split-line '((default . t))
1649 "Non-nil means M-RET will split the line at the cursor position.
1650 When nil, it will go to the end of the line before making a
1651 new line.
1652 You may also set this option in a different way for different
1653 contexts. Valid contexts are:
1655 headline when creating a new headline
1656 item when creating a new item
1657 table in a table field
1658 default the value to be used for all contexts not explicitly
1659 customized"
1660 :group 'org-structure
1661 :group 'org-table
1662 :type '(choice
1663 (const :tag "Always" t)
1664 (const :tag "Never" nil)
1665 (repeat :greedy t :tag "Individual contexts"
1666 (cons
1667 (choice :tag "Context"
1668 (const headline)
1669 (const item)
1670 (const table)
1671 (const default))
1672 (boolean)))))
1675 (defcustom org-insert-heading-respect-content nil
1676 "Non-nil means insert new headings after the current subtree.
1677 \\<org-mode-map>
1678 When nil, the new heading is created directly after the current line.
1679 The commands `\\[org-insert-heading-respect-content]' and \
1680 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1681 for the duration of the command."
1682 :group 'org-structure
1683 :type 'boolean)
1685 (defcustom org-blank-before-new-entry '((heading . auto)
1686 (plain-list-item . auto))
1687 "Should `org-insert-heading' leave a blank line before new heading/item?
1688 The value is an alist, with `heading' and `plain-list-item' as CAR,
1689 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1690 which case Org will look at the surrounding headings/items and try to
1691 make an intelligent decision whether to insert a blank line or not."
1692 :group 'org-edit-structure
1693 :type '(list
1694 (cons (const heading)
1695 (choice (const :tag "Never" nil)
1696 (const :tag "Always" t)
1697 (const :tag "Auto" auto)))
1698 (cons (const plain-list-item)
1699 (choice (const :tag "Never" nil)
1700 (const :tag "Always" t)
1701 (const :tag "Auto" auto)))))
1703 (defcustom org-insert-heading-hook nil
1704 "Hook being run after inserting a new heading."
1705 :group 'org-edit-structure
1706 :type 'hook)
1708 (defcustom org-enable-fixed-width-editor t
1709 "Non-nil means lines starting with \":\" are treated as fixed-width.
1710 This currently only means they are never auto-wrapped.
1711 When nil, such lines will be treated like ordinary lines."
1712 :group 'org-edit-structure
1713 :type 'boolean)
1715 (defgroup org-sparse-trees nil
1716 "Options concerning sparse trees in Org mode."
1717 :tag "Org Sparse Trees"
1718 :group 'org-structure)
1720 (defcustom org-highlight-sparse-tree-matches t
1721 "Non-nil means highlight all matches that define a sparse tree.
1722 The highlights will automatically disappear the next time the buffer is
1723 changed by an edit command."
1724 :group 'org-sparse-trees
1725 :type 'boolean)
1727 (defcustom org-remove-highlights-with-change t
1728 "Non-nil means any change to the buffer will remove temporary highlights.
1729 \\<org-mode-map>\
1730 Such highlights are created by `org-occur' and `org-clock-display'.
1731 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1732 to get rid of the highlights.
1733 The highlights created by `org-toggle-latex-fragment' always need
1734 `\\[org-toggle-latex-fragment]' to be removed."
1735 :group 'org-sparse-trees
1736 :group 'org-time
1737 :type 'boolean)
1739 (defcustom org-occur-case-fold-search t
1740 "Non-nil means `org-occur' should be case-insensitive.
1741 If set to `smart' the search will be case-insensitive only if it
1742 doesn't specify any upper case character."
1743 :group 'org-sparse-trees
1744 :version "26.1"
1745 :type '(choice
1746 (const :tag "Case-sensitive" nil)
1747 (const :tag "Case-insensitive" t)
1748 (const :tag "Case-insensitive for lower case searches only" smart)))
1750 (defcustom org-occur-hook '(org-first-headline-recenter)
1751 "Hook that is run after `org-occur' has constructed a sparse tree.
1752 This can be used to recenter the window to show as much of the structure
1753 as possible."
1754 :group 'org-sparse-trees
1755 :type 'hook)
1757 (defgroup org-table nil
1758 "Options concerning tables in Org mode."
1759 :tag "Org Table"
1760 :group 'org)
1762 (defcustom org-self-insert-cluster-for-undo nil
1763 "Non-nil means cluster self-insert commands for undo when possible.
1764 If this is set, then, like in the Emacs command loop, 20 consecutive
1765 characters will be undone together.
1766 This is configurable, because there is some impact on typing performance."
1767 :group 'org-table
1768 :type 'boolean)
1770 (defcustom org-table-tab-recognizes-table.el t
1771 "Non-nil means TAB will automatically notice a table.el table.
1772 When it sees such a table, it moves point into it and - if necessary -
1773 calls `table-recognize-table'."
1774 :group 'org-table-editing
1775 :type 'boolean)
1777 (defgroup org-link nil
1778 "Options concerning links in Org mode."
1779 :tag "Org Link"
1780 :group 'org)
1782 (defvar-local org-link-abbrev-alist-local nil
1783 "Buffer-local version of `org-link-abbrev-alist', which see.
1784 The value of this is taken from the #+LINK lines.")
1786 (defcustom org-link-parameters
1787 '(("doi" :follow org--open-doi-link)
1788 ("elisp" :follow org--open-elisp-link)
1789 ("file" :complete org-file-complete-link)
1790 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1791 ("help" :follow org--open-help-link)
1792 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1793 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1794 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1795 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1796 ("shell" :follow org--open-shell-link))
1797 "An alist of properties that defines all the links in Org mode.
1798 The key in each association is a string of the link type.
1799 Subsequent optional elements make up a p-list of link properties.
1801 :follow - A function that takes the link path as an argument.
1803 :export - A function that takes the link path, description and
1804 export-backend as arguments.
1806 :store - A function responsible for storing the link. See the
1807 function `org-store-link-functions'.
1809 :complete - A function that inserts a link with completion. The
1810 function takes one optional prefix arg.
1812 :face - A face for the link, or a function that returns a face.
1813 The function takes one argument which is the link path. The
1814 default face is `org-link'.
1816 :mouse-face - The mouse-face. The default is `highlight'.
1818 :display - `full' will not fold the link in descriptive
1819 display. Default is `org-link'.
1821 :help-echo - A string or function that takes (window object position)
1822 as arguments and returns a string.
1824 :keymap - A keymap that is active on the link. The default is
1825 `org-mouse-map'.
1827 :htmlize-link - A function for the htmlize-link. Defaults
1828 to (list :uri \"type:path\")
1830 :activate-func - A function to run at the end of font-lock
1831 activation. The function must accept (link-start link-end path bracketp)
1832 as arguments."
1833 :group 'org-link
1834 :type '(alist :tag "Link display parameters"
1835 :value-type plist)
1836 :version "26.1"
1837 :package-version '(Org . "9.1"))
1839 (defun org-link-get-parameter (type key)
1840 "Get TYPE link property for KEY.
1841 TYPE is a string and KEY is a plist keyword."
1842 (plist-get
1843 (cdr (assoc type org-link-parameters))
1844 key))
1846 (defun org-link-set-parameters (type &rest parameters)
1847 "Set link TYPE properties to PARAMETERS.
1848 PARAMETERS should be :key val pairs."
1849 (let ((data (assoc type org-link-parameters)))
1850 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1851 (push (cons type parameters) org-link-parameters)
1852 (org-make-link-regexps)
1853 (org-element-update-syntax))))
1855 (defun org-link-types ()
1856 "Return a list of known link types."
1857 (mapcar #'car org-link-parameters))
1859 (defcustom org-link-abbrev-alist nil
1860 "Alist of link abbreviations.
1861 The car of each element is a string, to be replaced at the start of a link.
1862 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1863 links in Org buffers can have an optional tag after a double colon, e.g.,
1865 [[linkkey:tag][description]]
1867 The `linkkey' must be a single word, starting with a letter, followed
1868 by letters, numbers, `-' or `_'.
1870 If REPLACE is a string, the tag will simply be appended to create the link.
1871 If the string contains \"%s\", the tag will be inserted there. If the string
1872 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1873 at that point (see the function `url-hexify-string'). If the string contains
1874 the specifier \"%(my-function)\", then the custom function `my-function' will
1875 be invoked: this function takes the tag as its only argument and must return
1876 a string.
1878 REPLACE may also be a function that will be called with the tag as the
1879 only argument to create the link, which should be returned as a string.
1881 See the manual for examples."
1882 :group 'org-link
1883 :type '(repeat
1884 (cons
1885 (string :tag "Protocol")
1886 (choice
1887 (string :tag "Format")
1888 (function)))))
1890 (defcustom org-descriptive-links t
1891 "Non-nil means Org will display descriptive links.
1892 E.g. [[https://orgmode.org][Org website]] will be displayed as
1893 \"Org Website\", hiding the link itself and just displaying its
1894 description. When set to nil, Org will display the full links
1895 literally.
1897 You can interactively set the value of this variable by calling
1898 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1899 :group 'org-link
1900 :type 'boolean)
1902 (defcustom org-link-file-path-type 'adaptive
1903 "How the path name in file links should be stored.
1904 Valid values are:
1906 relative Relative to the current directory, i.e. the directory of the file
1907 into which the link is being inserted.
1908 absolute Absolute path, if possible with ~ for home directory.
1909 noabbrev Absolute path, no abbreviation of home directory.
1910 adaptive Use relative path for files in the current directory and sub-
1911 directories of it. For other files, use an absolute path."
1912 :group 'org-link
1913 :type '(choice
1914 (const relative)
1915 (const absolute)
1916 (const noabbrev)
1917 (const adaptive)))
1919 (defvaralias 'org-activate-links 'org-highlight-links)
1920 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1921 "Types of links that should be highlighted in Org files.
1923 This is a list of symbols, each one of them leading to the
1924 highlighting of a certain link type.
1926 You can still open links that are not highlighted.
1928 In principle, it does not hurt to turn on highlighting for all
1929 link types. There may be a small gain when turning off unused
1930 link types. The types are:
1932 bracket The recommended [[link][description]] or [[link]] links with hiding.
1933 angle Links in angular brackets that may contain whitespace like
1934 <bbdb:Carsten Dominik>.
1935 plain Plain links in normal text, no whitespace, like http://google.com.
1936 radio Text that is matched by a radio target, see manual for details.
1937 tag Tag settings in a headline (link to tag search).
1938 date Time stamps (link to calendar).
1939 footnote Footnote labels.
1941 If you set this variable during an Emacs session, use `org-mode-restart'
1942 in the Org buffer so that the change takes effect."
1943 :group 'org-link
1944 :group 'org-appearance
1945 :type '(set :greedy t
1946 (const :tag "Double bracket links" bracket)
1947 (const :tag "Angular bracket links" angle)
1948 (const :tag "Plain text links" plain)
1949 (const :tag "Radio target matches" radio)
1950 (const :tag "Tags" tag)
1951 (const :tag "Timestamps" date)
1952 (const :tag "Footnotes" footnote)))
1954 (defcustom org-make-link-description-function nil
1955 "Function to use for generating link descriptions from links.
1956 This function must take two parameters: the first one is the
1957 link, the second one is the description generated by
1958 `org-insert-link'. The function should return the description to
1959 use."
1960 :group 'org-link
1961 :type '(choice (const nil) (function)))
1963 (defgroup org-link-store nil
1964 "Options concerning storing links in Org mode."
1965 :tag "Org Store Link"
1966 :group 'org-link)
1968 (defcustom org-url-hexify-p t
1969 "When non-nil, hexify URL when creating a link."
1970 :type 'boolean
1971 :version "24.3"
1972 :group 'org-link-store)
1974 (defcustom org-email-link-description-format "Email %c: %.30s"
1975 "Format of the description part of a link to an email or usenet message.
1976 The following %-escapes will be replaced by corresponding information:
1978 %F full \"From\" field
1979 %f name, taken from \"From\" field, address if no name
1980 %T full \"To\" field
1981 %t first name in \"To\" field, address if no name
1982 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1983 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1984 %s subject
1985 %d date
1986 %m message-id.
1988 You may use normal field width specification between the % and the letter.
1989 This is for example useful to limit the length of the subject.
1991 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1992 :group 'org-link-store
1993 :type 'string)
1995 (defcustom org-from-is-user-regexp
1996 (let (r1 r2)
1997 (when (and user-mail-address (not (string= user-mail-address "")))
1998 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1999 (when (and user-full-name (not (string= user-full-name "")))
2000 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
2001 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2002 "Regexp matched against the \"From:\" header of an email or usenet message.
2003 It should match if the message is from the user him/herself."
2004 :group 'org-link-store
2005 :type 'regexp)
2007 (defcustom org-context-in-file-links t
2008 "Non-nil means file links from `org-store-link' contain context.
2009 \\<org-mode-map>
2010 A search string will be added to the file name with :: as separator
2011 and used to find the context when the link is activated by the command
2012 `org-open-at-point'. When this option is t, the entire active region
2013 will be placed in the search string of the file link. If set to a
2014 positive integer, only the first n lines of context will be stored.
2016 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2017 \\[org-store-link]')
2018 negates this setting for the duration of the command."
2019 :group 'org-link-store
2020 :type '(choice boolean integer))
2022 (defcustom org-keep-stored-link-after-insertion nil
2023 "Non-nil means keep link in list for entire session.
2024 \\<org-mode-map>
2025 The command `org-store-link' adds a link pointing to the current
2026 location to an internal list. These links accumulate during a session.
2027 The command `org-insert-link' can be used to insert links into any
2028 Org file (offering completion for all stored links).
2030 When this option is nil, every link which has been inserted once using
2031 `\\[org-insert-link]' will be removed from the list, to make completing the \
2032 unused
2033 links more efficient."
2034 :group 'org-link-store
2035 :type 'boolean)
2037 (defgroup org-link-follow nil
2038 "Options concerning following links in Org mode."
2039 :tag "Org Follow Link"
2040 :group 'org-link)
2042 (defcustom org-link-translation-function nil
2043 "Function to translate links with different syntax to Org syntax.
2044 This can be used to translate links created for example by the Planner
2045 or emacs-wiki packages to Org syntax.
2046 The function must accept two parameters, a TYPE containing the link
2047 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2048 which is everything after the link protocol. It should return a cons
2049 with possibly modified values of type and path.
2050 Org contains a function for this, so if you set this variable to
2051 `org-translate-link-from-planner', you should be able follow many
2052 links created by planner."
2053 :group 'org-link-follow
2054 :type '(choice (const nil) (function)))
2056 (defcustom org-follow-link-hook nil
2057 "Hook that is run after a link has been followed."
2058 :group 'org-link-follow
2059 :type 'hook)
2061 (defcustom org-tab-follows-link nil
2062 "Non-nil means on links TAB will follow the link.
2063 Needs to be set before org.el is loaded.
2064 This really should not be used, it does not make sense, and the
2065 implementation is bad."
2066 :group 'org-link-follow
2067 :type 'boolean)
2069 (defcustom org-return-follows-link nil
2070 "Non-nil means on links RET will follow the link.
2071 In tables, the special behavior of RET has precedence."
2072 :group 'org-link-follow
2073 :type 'boolean)
2075 (defcustom org-mouse-1-follows-link
2076 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2077 "Non-nil means mouse-1 on a link will follow the link.
2078 A longer mouse click will still set point. Needs to be set
2079 before org.el is loaded."
2080 :group 'org-link-follow
2081 :version "26.1"
2082 :package-version '(Org . "8.3")
2083 :type '(choice
2084 (const :tag "A double click follows the link" double)
2085 (const :tag "Unconditionally follow the link with mouse-1" t)
2086 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2088 (defcustom org-mark-ring-length 4
2089 "Number of different positions to be recorded in the ring.
2090 Changing this requires a restart of Emacs to work correctly."
2091 :group 'org-link-follow
2092 :type 'integer)
2094 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2095 "Non-nil means internal fuzzy links can only match headlines.
2097 When nil, the a fuzzy link may point to a target or a named
2098 construct in the document. When set to the special value
2099 `query-to-create', offer to create a new headline when none
2100 matched.
2102 Spaces and statistics cookies are ignored during heading searches."
2103 :group 'org-link-follow
2104 :version "24.1"
2105 :type '(choice
2106 (const :tag "Use fuzzy text search" nil)
2107 (const :tag "Match only exact headline" t)
2108 (const :tag "Match exact headline or query to create it"
2109 query-to-create))
2110 :safe #'symbolp)
2112 (defcustom org-link-frame-setup
2113 '((vm . vm-visit-folder-other-frame)
2114 (vm-imap . vm-visit-imap-folder-other-frame)
2115 (gnus . org-gnus-no-new-news)
2116 (file . find-file-other-window)
2117 (wl . wl-other-frame))
2118 "Setup the frame configuration for following links.
2119 When following a link with Emacs, it may often be useful to display
2120 this link in another window or frame. This variable can be used to
2121 set this up for the different types of links.
2122 For VM, use any of
2123 `vm-visit-folder'
2124 `vm-visit-folder-other-window'
2125 `vm-visit-folder-other-frame'
2126 For Gnus, use any of
2127 `gnus'
2128 `gnus-other-frame'
2129 `org-gnus-no-new-news'
2130 For FILE, use any of
2131 `find-file'
2132 `find-file-other-window'
2133 `find-file-other-frame'
2134 For Wanderlust use any of
2135 `wl'
2136 `wl-other-frame'
2137 For the calendar, use the variable `calendar-setup'.
2138 For BBDB, it is currently only possible to display the matches in
2139 another window."
2140 :group 'org-link-follow
2141 :type '(list
2142 (cons (const vm)
2143 (choice
2144 (const vm-visit-folder)
2145 (const vm-visit-folder-other-window)
2146 (const vm-visit-folder-other-frame)))
2147 (cons (const vm-imap)
2148 (choice
2149 (const vm-visit-imap-folder)
2150 (const vm-visit-imap-folder-other-window)
2151 (const vm-visit-imap-folder-other-frame)))
2152 (cons (const gnus)
2153 (choice
2154 (const gnus)
2155 (const gnus-other-frame)
2156 (const org-gnus-no-new-news)))
2157 (cons (const file)
2158 (choice
2159 (const find-file)
2160 (const find-file-other-window)
2161 (const find-file-other-frame)))
2162 (cons (const wl)
2163 (choice
2164 (const wl)
2165 (const wl-other-frame)))))
2167 (defcustom org-display-internal-link-with-indirect-buffer nil
2168 "Non-nil means use indirect buffer to display infile links.
2169 Activating internal links (from one location in a file to another location
2170 in the same file) normally just jumps to the location. When the link is
2171 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2172 is displayed in
2173 another window. When this option is set, the other window actually displays
2174 an indirect buffer clone of the current buffer, to avoid any visibility
2175 changes to the current buffer."
2176 :group 'org-link-follow
2177 :type 'boolean)
2179 (defcustom org-open-non-existing-files nil
2180 "Non-nil means `org-open-file' will open non-existing files.
2181 When nil, an error will be generated.
2182 This variable applies only to external applications because they
2183 might choke on non-existing files. If the link is to a file that
2184 will be opened in Emacs, the variable is ignored."
2185 :group 'org-link-follow
2186 :type 'boolean)
2188 (defcustom org-open-directory-means-index-dot-org nil
2189 "Non-nil means a link to a directory really means to index.org.
2190 When nil, following a directory link will run dired or open a finder/explorer
2191 window on that directory."
2192 :group 'org-link-follow
2193 :type 'boolean)
2195 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2196 "Non-nil means ask for confirmation before executing shell links.
2197 Shell links can be dangerous: just think about a link
2199 [[shell:rm -rf ~/*][Google Search]]
2201 This link would show up in your Org document as \"Google Search\",
2202 but really it would remove your entire home directory.
2203 Therefore we advise against setting this variable to nil.
2204 Just change it to `y-or-n-p' if you want to confirm with a
2205 single keystroke rather than having to type \"yes\"."
2206 :group 'org-link-follow
2207 :type '(choice
2208 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2209 (const :tag "with y-or-n (faster)" y-or-n-p)
2210 (const :tag "no confirmation (dangerous)" nil)))
2211 (put 'org-confirm-shell-link-function
2212 'safe-local-variable
2213 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2215 (defcustom org-confirm-shell-link-not-regexp ""
2216 "A regexp to skip confirmation for shell links."
2217 :group 'org-link-follow
2218 :version "24.1"
2219 :type 'regexp)
2221 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2222 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2223 Elisp links can be dangerous: just think about a link
2225 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2227 This link would show up in your Org document as \"Google Search\",
2228 but really it would remove your entire home directory.
2229 Therefore we advise against setting this variable to nil.
2230 Just change it to `y-or-n-p' if you want to confirm with a
2231 single keystroke rather than having to type \"yes\"."
2232 :group 'org-link-follow
2233 :type '(choice
2234 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2235 (const :tag "with y-or-n (faster)" y-or-n-p)
2236 (const :tag "no confirmation (dangerous)" nil)))
2237 (put 'org-confirm-shell-link-function
2238 'safe-local-variable
2239 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2241 (defcustom org-confirm-elisp-link-not-regexp ""
2242 "A regexp to skip confirmation for Elisp links."
2243 :group 'org-link-follow
2244 :version "24.1"
2245 :type 'regexp)
2247 (defconst org-file-apps-defaults-gnu
2248 '((remote . emacs)
2249 (system . mailcap)
2250 (t . mailcap))
2251 "Default file applications on a UNIX or GNU/Linux system.
2252 See `org-file-apps'.")
2254 (defconst org-file-apps-defaults-macosx
2255 '((remote . emacs)
2256 (system . "open %s")
2257 ("ps.gz" . "gv %s")
2258 ("eps.gz" . "gv %s")
2259 ("dvi" . "xdvi %s")
2260 ("fig" . "xfig %s")
2261 (t . "open %s"))
2262 "Default file applications on a macOS system.
2263 The system \"open\" is known as a default, but we use X11 applications
2264 for some files for which the OS does not have a good default.
2265 See `org-file-apps'.")
2267 (defconst org-file-apps-defaults-windowsnt
2268 (list '(remote . emacs)
2269 (cons 'system (lambda (file _path)
2270 (with-no-warnings (w32-shell-execute "open" file))))
2271 (cons t (lambda (file _path)
2272 (with-no-warnings (w32-shell-execute "open" file)))))
2273 "Default file applications on a Windows NT system.
2274 The system \"open\" is used for most files.
2275 See `org-file-apps'.")
2277 (defcustom org-file-apps
2278 '((auto-mode . emacs)
2279 ("\\.mm\\'" . default)
2280 ("\\.x?html?\\'" . default)
2281 ("\\.pdf\\'" . default))
2282 "External applications for opening `file:path' items in a document.
2283 \\<org-mode-map>\
2285 Org mode uses system defaults for different file types, but
2286 you can use this variable to set the application for a given file
2287 extension. The entries in this list are cons cells where the car identifies
2288 files and the cdr the corresponding command.
2290 Possible values for the file identifier are:
2292 \"string\" A string as a file identifier can be interpreted in different
2293 ways, depending on its contents:
2295 - Alphanumeric characters only:
2296 Match links with this file extension.
2297 Example: (\"pdf\" . \"evince %s\")
2298 to open PDFs with evince.
2300 - Regular expression: Match links where the
2301 filename matches the regexp. If you want to
2302 use groups here, use shy groups.
2304 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2305 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2306 to open *.html and *.xhtml with firefox.
2308 - Regular expression which contains (non-shy) groups:
2309 Match links where the whole link, including \"::\", and
2310 anything after that, matches the regexp.
2311 In a custom command string, %1, %2, etc. are replaced with
2312 the parts of the link that were matched by the groups.
2313 For backwards compatibility, if a command string is given
2314 that does not use any of the group matches, this case is
2315 handled identically to the second one (i.e. match against
2316 file name only).
2317 In a custom function, you can access the group matches with
2318 (match-string n link).
2320 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2321 \"evince -p %1 %s\")
2322 to open [[file:document.pdf::5]] with evince at page 5.
2324 `directory' Matches a directory
2325 `remote' Matches a remote file, accessible through tramp or efs.
2326 Remote files most likely should be visited through Emacs
2327 because external applications cannot handle such paths.
2328 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2329 so all files Emacs knows how to handle. Using this with
2330 command `emacs' will open most files in Emacs. Beware that this
2331 will also open html files inside Emacs, unless you add
2332 (\"html\" . default) to the list as well.
2333 `system' The system command to open files, like `open' on Windows
2334 and macOS, and mailcap under GNU/Linux. This is the command
2335 that will be selected if you call `org-open-at-point' with a
2336 double prefix argument (`\\[universal-argument] \
2337 \\[universal-argument] \\[org-open-at-point]').
2338 t Default for files not matched by any of the other options.
2340 Possible values for the command are:
2342 `emacs' The file will be visited by the current Emacs process.
2343 `default' Use the default application for this file type, which is the
2344 association for t in the list, most likely in the system-specific
2345 part. This can be used to overrule an unwanted setting in the
2346 system-specific variable.
2347 `system' Use the system command for opening files, like \"open\".
2348 This command is specified by the entry whose car is `system'.
2349 Most likely, the system-specific version of this variable
2350 does define this command, but you can overrule/replace it
2351 here.
2352 `mailcap' Use command specified in the mailcaps.
2353 string A command to be executed by a shell; %s will be replaced
2354 by the path to the file.
2355 function A Lisp function, which will be called with two arguments:
2356 the file path and the original link string, without the
2357 \"file:\" prefix.
2359 For more examples, see the system specific constants
2360 `org-file-apps-defaults-macosx'
2361 `org-file-apps-defaults-windowsnt'
2362 `org-file-apps-defaults-gnu'."
2363 :group 'org-link-follow
2364 :type '(repeat
2365 (cons (choice :value ""
2366 (string :tag "Extension")
2367 (const :tag "System command to open files" system)
2368 (const :tag "Default for unrecognized files" t)
2369 (const :tag "Remote file" remote)
2370 (const :tag "Links to a directory" directory)
2371 (const :tag "Any files that have Emacs modes"
2372 auto-mode))
2373 (choice :value ""
2374 (const :tag "Visit with Emacs" emacs)
2375 (const :tag "Use default" default)
2376 (const :tag "Use the system command" system)
2377 (string :tag "Command")
2378 (function :tag "Function")))))
2380 (defcustom org-doi-server-url "http://dx.doi.org/"
2381 "The URL of the DOI server."
2382 :type 'string
2383 :version "24.3"
2384 :group 'org-link-follow)
2386 (defgroup org-refile nil
2387 "Options concerning refiling entries in Org mode."
2388 :tag "Org Refile"
2389 :group 'org)
2391 (defcustom org-directory "~/org"
2392 "Directory with Org files.
2393 This is just a default location to look for Org files. There is no need
2394 at all to put your files into this directory. It is used in the
2395 following situations:
2397 1. When a capture template specifies a target file that is not an
2398 absolute path. The path will then be interpreted relative to
2399 `org-directory'
2400 2. When the value of variable `org-agenda-files' is a single file, any
2401 relative paths in this file will be taken as relative to
2402 `org-directory'."
2403 :group 'org-refile
2404 :group 'org-capture
2405 :type 'directory)
2407 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2408 "Default target for storing notes.
2409 Used as a fall back file for org-capture.el, for templates that
2410 do not specify a target file."
2411 :group 'org-refile
2412 :group 'org-capture
2413 :type 'file)
2415 (defcustom org-reverse-note-order nil
2416 "Non-nil means store new notes at the beginning of a file or entry.
2417 When nil, new notes will be filed to the end of a file or entry.
2418 This can also be a list with cons cells of regular expressions that
2419 are matched against file names, and values."
2420 :group 'org-capture
2421 :group 'org-refile
2422 :type '(choice
2423 (const :tag "Reverse always" t)
2424 (const :tag "Reverse never" nil)
2425 (repeat :tag "By file name regexp"
2426 (cons regexp boolean))))
2428 (defcustom org-log-refile nil
2429 "Information to record when a task is refiled.
2431 Possible values are:
2433 nil Don't add anything
2434 time Add a time stamp to the task
2435 note Prompt for a note and add it with template `org-log-note-headings'
2437 This option can also be set with on a per-file-basis with
2439 #+STARTUP: nologrefile
2440 #+STARTUP: logrefile
2441 #+STARTUP: lognoterefile
2443 You can have local logging settings for a subtree by setting the LOGGING
2444 property to one or more of these keywords.
2446 When bulk-refiling from the agenda, the value `note' is forbidden and
2447 will temporarily be changed to `time'."
2448 :group 'org-refile
2449 :group 'org-progress
2450 :version "24.1"
2451 :type '(choice
2452 (const :tag "No logging" nil)
2453 (const :tag "Record timestamp" time)
2454 (const :tag "Record timestamp with note." note)))
2456 (defcustom org-refile-targets nil
2457 "Targets for refiling entries with `\\[org-refile]'.
2458 This is a list of cons cells. Each cell contains:
2459 - a specification of the files to be considered, either a list of files,
2460 or a symbol whose function or variable value will be used to retrieve
2461 a file name or a list of file names. If you use `org-agenda-files' for
2462 that, all agenda files will be scanned for targets. Nil means consider
2463 headings in the current buffer.
2464 - A specification of how to find candidate refile targets. This may be
2465 any of:
2466 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2467 This tag has to be present in all target headlines, inheritance will
2468 not be considered.
2469 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2470 todo keyword.
2471 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2472 headlines that are refiling targets.
2473 - a cons cell (:level . N). Any headline of level N is considered a target.
2474 Note that, when `org-odd-levels-only' is set, level corresponds to
2475 order in hierarchy, not to the number of stars.
2476 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2477 Note that, when `org-odd-levels-only' is set, level corresponds to
2478 order in hierarchy, not to the number of stars.
2480 Each element of this list generates a set of possible targets.
2481 The union of these sets is presented (with completion) to
2482 the user by `org-refile'.
2484 You can set the variable `org-refile-target-verify-function' to a function
2485 to verify each headline found by the simple criteria above.
2487 When this variable is nil, all top-level headlines in the current buffer
2488 are used, equivalent to the value `((nil . (:level . 1))'."
2489 :group 'org-refile
2490 :type '(repeat
2491 (cons
2492 (choice :value org-agenda-files
2493 (const :tag "All agenda files" org-agenda-files)
2494 (const :tag "Current buffer" nil)
2495 (function) (variable) (file))
2496 (choice :tag "Identify target headline by"
2497 (cons :tag "Specific tag" (const :value :tag) (string))
2498 (cons :tag "TODO keyword" (const :value :todo) (string))
2499 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2500 (cons :tag "Level number" (const :value :level) (integer))
2501 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2503 (defcustom org-refile-target-verify-function nil
2504 "Function to verify if the headline at point should be a refile target.
2505 The function will be called without arguments, with point at the
2506 beginning of the headline. It should return t and leave point
2507 where it is if the headline is a valid target for refiling.
2509 If the target should not be selected, the function must return nil.
2510 In addition to this, it may move point to a place from where the search
2511 should be continued. For example, the function may decide that the entire
2512 subtree of the current entry should be excluded and move point to the end
2513 of the subtree."
2514 :group 'org-refile
2515 :type '(choice
2516 (const nil)
2517 (function)))
2519 (defcustom org-refile-use-cache nil
2520 "Non-nil means cache refile targets to speed up the process.
2521 \\<org-mode-map>\
2522 The cache for a particular file will be updated automatically when
2523 the buffer has been killed, or when any of the marker used for flagging
2524 refile targets no longer points at a live buffer.
2525 If you have added new entries to a buffer that might themselves be targets,
2526 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2527 if you find that easier, \
2528 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2529 \\[org-refile]'."
2530 :group 'org-refile
2531 :version "24.1"
2532 :type 'boolean)
2534 (defcustom org-refile-use-outline-path nil
2535 "Non-nil means provide refile targets as paths.
2536 So a level 3 headline will be available as level1/level2/level3.
2538 When the value is `file', also include the file name (without directory)
2539 into the path. In this case, you can also stop the completion after
2540 the file name, to get entries inserted as top level in the file.
2542 When `full-file-path', include the full file path.
2544 When `buffer-name', use the buffer name."
2545 :group 'org-refile
2546 :type '(choice
2547 (const :tag "Not" nil)
2548 (const :tag "Yes" t)
2549 (const :tag "Start with file name" file)
2550 (const :tag "Start with full file path" full-file-path)
2551 (const :tag "Start with buffer name" buffer-name)))
2553 (defcustom org-outline-path-complete-in-steps t
2554 "Non-nil means complete the outline path in hierarchical steps.
2555 When Org uses the refile interface to select an outline path (see
2556 `org-refile-use-outline-path'), the completion of the path can be
2557 done in a single go, or it can be done in steps down the headline
2558 hierarchy. Going in steps is probably the best if you do not use
2559 a special completion package like `ido' or `icicles'. However,
2560 when using these packages, going in one step can be very fast,
2561 while still showing the whole path to the entry."
2562 :group 'org-refile
2563 :type 'boolean)
2565 (defcustom org-refile-allow-creating-parent-nodes nil
2566 "Non-nil means allow the creation of new nodes as refile targets.
2567 New nodes are then created by adding \"/new node name\" to the completion
2568 of an existing node. When the value of this variable is `confirm',
2569 new node creation must be confirmed by the user (recommended).
2570 When nil, the completion must match an existing entry.
2572 Note that, if the new heading is not seen by the criteria
2573 listed in `org-refile-targets', multiple instances of the same
2574 heading would be created by trying again to file under the new
2575 heading."
2576 :group 'org-refile
2577 :type '(choice
2578 (const :tag "Never" nil)
2579 (const :tag "Always" t)
2580 (const :tag "Prompt for confirmation" confirm)))
2582 (defcustom org-refile-active-region-within-subtree nil
2583 "Non-nil means also refile active region within a subtree.
2585 By default `org-refile' doesn't allow refiling regions if they
2586 don't contain a set of subtrees, but it might be convenient to
2587 do so sometimes: in that case, the first line of the region is
2588 converted to a headline before refiling."
2589 :group 'org-refile
2590 :version "24.1"
2591 :type 'boolean)
2593 (defgroup org-todo nil
2594 "Options concerning TODO items in Org mode."
2595 :tag "Org TODO"
2596 :group 'org)
2598 (defgroup org-progress nil
2599 "Options concerning Progress logging in Org mode."
2600 :tag "Org Progress"
2601 :group 'org-time)
2603 (defvar org-todo-interpretation-widgets
2604 '((:tag "Sequence (cycling hits every state)" sequence)
2605 (:tag "Type (cycling directly to DONE)" type))
2606 "The available interpretation symbols for customizing `org-todo-keywords'.
2607 Interested libraries should add to this list.")
2609 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2610 "List of TODO entry keyword sequences and their interpretation.
2611 \\<org-mode-map>This is a list of sequences.
2613 Each sequence starts with a symbol, either `sequence' or `type',
2614 indicating if the keywords should be interpreted as a sequence of
2615 action steps, or as different types of TODO items. The first
2616 keywords are states requiring action - these states will select a headline
2617 for inclusion into the global TODO list Org produces. If one of the
2618 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2619 signify that no further action is necessary. If \"|\" is not found,
2620 the last keyword is treated as the only DONE state of the sequence.
2622 The command `\\[org-todo]' cycles an entry through these states, and one
2623 additional state where no keyword is present. For details about this
2624 cycling, see the manual.
2626 TODO keywords and interpretation can also be set on a per-file basis with
2627 the special #+SEQ_TODO and #+TYP_TODO lines.
2629 Each keyword can optionally specify a character for fast state selection
2630 \(in combination with the variable `org-use-fast-todo-selection')
2631 and specifiers for state change logging, using the same syntax that
2632 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2633 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2634 indicates to record a time stamp each time this state is selected.
2636 Each keyword may also specify if a timestamp or a note should be
2637 recorded when entering or leaving the state, by adding additional
2638 characters in the parenthesis after the keyword. This looks like this:
2639 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2640 record only the time of the state change. With X and Y being either
2641 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2642 Y when leaving the state if and only if the *target* state does not
2643 define X. You may omit any of the fast-selection key or X or /Y,
2644 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2646 For backward compatibility, this variable may also be just a list
2647 of keywords. In this case the interpretation (sequence or type) will be
2648 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2649 :group 'org-todo
2650 :group 'org-keywords
2651 :type '(choice
2652 (repeat :tag "Old syntax, just keywords"
2653 (string :tag "Keyword"))
2654 (repeat :tag "New syntax"
2655 (cons
2656 (choice
2657 :tag "Interpretation"
2658 ;;Quick and dirty way to see
2659 ;;`org-todo-interpretations'. This takes the
2660 ;;place of item arguments
2661 :convert-widget
2662 (lambda (widget)
2663 (widget-put widget
2664 :args (mapcar
2665 (lambda (x)
2666 (widget-convert
2667 (cons 'const x)))
2668 org-todo-interpretation-widgets))
2669 widget))
2670 (repeat
2671 (string :tag "Keyword"))))))
2673 (defvar-local org-todo-keywords-1 nil
2674 "All TODO and DONE keywords active in a buffer.")
2675 (defvar org-todo-keywords-for-agenda nil)
2676 (defvar org-done-keywords-for-agenda nil)
2677 (defvar org-todo-keyword-alist-for-agenda nil)
2678 (defvar org-tag-alist-for-agenda nil
2679 "Alist of all tags from all agenda files.")
2680 (defvar org-tag-groups-alist-for-agenda nil
2681 "Alist of all groups tags from all current agenda files.")
2682 (defvar-local org-tag-groups-alist nil)
2683 (defvar org-agenda-contributing-files nil)
2684 (defvar-local org-current-tag-alist nil
2685 "Alist of all tag groups in current buffer.
2686 This variable takes into consideration `org-tag-alist',
2687 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2688 (defvar-local org-not-done-keywords nil)
2689 (defvar-local org-done-keywords nil)
2690 (defvar-local org-todo-heads nil)
2691 (defvar-local org-todo-sets nil)
2692 (defvar-local org-todo-log-states nil)
2693 (defvar-local org-todo-kwd-alist nil)
2694 (defvar-local org-todo-key-alist nil)
2695 (defvar-local org-todo-key-trigger nil)
2697 (defcustom org-todo-interpretation 'sequence
2698 "Controls how TODO keywords are interpreted.
2699 This variable is in principle obsolete and is only used for
2700 backward compatibility, if the interpretation of todo keywords is
2701 not given already in `org-todo-keywords'. See that variable for
2702 more information."
2703 :group 'org-todo
2704 :group 'org-keywords
2705 :type '(choice (const sequence)
2706 (const type)))
2708 (defcustom org-use-fast-todo-selection t
2709 "\\<org-mode-map>\
2710 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2711 This variable describes if and under what circumstances the cycling
2712 mechanism for TODO keywords will be replaced by a single-key, direct
2713 selection scheme.
2715 When nil, fast selection is never used.
2717 When the symbol `prefix', it will be used when `org-todo' is called
2718 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2719 in an Org buffer, and
2720 `\\[universal-argument] t' in an agenda buffer.
2722 When t, fast selection is used by default. In this case, the prefix
2723 argument forces cycling instead.
2725 In all cases, the special interface is only used if access keys have
2726 actually been assigned by the user, i.e. if keywords in the configuration
2727 are followed by a letter in parenthesis, like TODO(t)."
2728 :group 'org-todo
2729 :type '(choice
2730 (const :tag "Never" nil)
2731 (const :tag "By default" t)
2732 (const :tag "Only with C-u C-c C-t" prefix)))
2734 (defcustom org-provide-todo-statistics t
2735 "Non-nil means update todo statistics after insert and toggle.
2736 ALL-HEADLINES means update todo statistics by including headlines
2737 with no TODO keyword as well, counting them as not done.
2738 A list of TODO keywords means the same, but skip keywords that are
2739 not in this list.
2740 When set to a list of two lists, the first list contains keywords
2741 to consider as TODO keywords, the second list contains keywords
2742 to consider as DONE keywords.
2744 When this is set, todo statistics is updated in the parent of the
2745 current entry each time a todo state is changed."
2746 :group 'org-todo
2747 :type '(choice
2748 (const :tag "Yes, only for TODO entries" t)
2749 (const :tag "Yes, including all entries" all-headlines)
2750 (repeat :tag "Yes, for TODOs in this list"
2751 (string :tag "TODO keyword"))
2752 (list :tag "Yes, for TODOs and DONEs in these lists"
2753 (repeat (string :tag "TODO keyword"))
2754 (repeat (string :tag "DONE keyword")))
2755 (other :tag "No TODO statistics" nil)))
2757 (defcustom org-hierarchical-todo-statistics t
2758 "Non-nil means TODO statistics covers just direct children.
2759 When nil, all entries in the subtree are considered.
2760 This has only an effect if `org-provide-todo-statistics' is set.
2761 To set this to nil for only a single subtree, use a COOKIE_DATA
2762 property and include the word \"recursive\" into the value."
2763 :group 'org-todo
2764 :type 'boolean)
2766 (defcustom org-after-todo-state-change-hook nil
2767 "Hook which is run after the state of a TODO item was changed.
2768 The new state (a string with a TODO keyword, or nil) is available in the
2769 Lisp variable `org-state'."
2770 :group 'org-todo
2771 :type 'hook)
2773 (defvar org-blocker-hook nil
2774 "Hook for functions that are allowed to block a state change.
2776 Functions in this hook should not modify the buffer.
2777 Each function gets as its single argument a property list,
2778 see `org-trigger-hook' for more information about this list.
2780 If any of the functions in this hook returns nil, the state change
2781 is blocked.")
2783 (defvar org-trigger-hook nil
2784 "Hook for functions that are triggered by a state change.
2786 Each function gets as its single argument a property list with at
2787 least the following elements:
2789 (:type type-of-change :position pos-at-entry-start
2790 :from old-state :to new-state)
2792 Depending on the type, more properties may be present.
2794 This mechanism is currently implemented for:
2796 TODO state changes
2797 ------------------
2798 :type todo-state-change
2799 :from previous state (keyword as a string), or nil, or a symbol
2800 `todo' or `done', to indicate the general type of state.
2801 :to new state, like in :from")
2803 (defcustom org-enforce-todo-dependencies nil
2804 "Non-nil means undone TODO entries will block switching the parent to DONE.
2805 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2806 be blocked if any prior sibling is not yet done.
2807 Finally, if the parent is blocked because of ordered siblings of its own,
2808 the child will also be blocked."
2809 :set (lambda (var val)
2810 (set var val)
2811 (if val
2812 (add-hook 'org-blocker-hook
2813 'org-block-todo-from-children-or-siblings-or-parent)
2814 (remove-hook 'org-blocker-hook
2815 'org-block-todo-from-children-or-siblings-or-parent)))
2816 :group 'org-todo
2817 :type 'boolean)
2819 (defcustom org-enforce-todo-checkbox-dependencies nil
2820 "Non-nil means unchecked boxes will block switching the parent to DONE.
2821 When this is nil, checkboxes have no influence on switching TODO states.
2822 When non-nil, you first need to check off all check boxes before the TODO
2823 entry can be switched to DONE.
2824 This variable needs to be set before org.el is loaded, and you need to
2825 restart Emacs after a change to make the change effective. The only way
2826 to change it while Emacs is running is through the customize interface."
2827 :set (lambda (var val)
2828 (set var val)
2829 (if val
2830 (add-hook 'org-blocker-hook
2831 'org-block-todo-from-checkboxes)
2832 (remove-hook 'org-blocker-hook
2833 'org-block-todo-from-checkboxes)))
2834 :group 'org-todo
2835 :type 'boolean)
2837 (defcustom org-treat-insert-todo-heading-as-state-change nil
2838 "Non-nil means inserting a TODO heading is treated as state change.
2839 So when the command `\\[org-insert-todo-heading]' is used, state change
2840 logging will apply if appropriate. When nil, the new TODO item will
2841 be inserted directly, and no logging will take place."
2842 :group 'org-todo
2843 :type 'boolean)
2845 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2846 "Non-nil means switching TODO states with S-cursor counts as state change.
2847 This is the default behavior. However, setting this to nil allows a
2848 convenient way to select a TODO state and bypass any logging associated
2849 with that."
2850 :group 'org-todo
2851 :type 'boolean)
2853 (defcustom org-todo-state-tags-triggers nil
2854 "Tag changes that should be triggered by TODO state changes.
2855 This is a list. Each entry is
2857 (state-change (tag . flag) .......)
2859 State-change can be a string with a state, and empty string to indicate the
2860 state that has no TODO keyword, or it can be one of the symbols `todo'
2861 or `done', meaning any not-done or done state, respectively."
2862 :group 'org-todo
2863 :group 'org-tags
2864 :type '(repeat
2865 (cons (choice :tag "When changing to"
2866 (const :tag "Not-done state" todo)
2867 (const :tag "Done state" done)
2868 (string :tag "State"))
2869 (repeat
2870 (cons :tag "Tag action"
2871 (string :tag "Tag")
2872 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2874 (defcustom org-log-done nil
2875 "Information to record when a task moves to the DONE state.
2877 Possible values are:
2879 nil Don't add anything, just change the keyword
2880 time Add a time stamp to the task
2881 note Prompt for a note and add it with template `org-log-note-headings'
2883 This option can also be set with on a per-file-basis with
2885 #+STARTUP: nologdone
2886 #+STARTUP: logdone
2887 #+STARTUP: lognotedone
2889 You can have local logging settings for a subtree by setting the LOGGING
2890 property to one or more of these keywords."
2891 :group 'org-todo
2892 :group 'org-progress
2893 :type '(choice
2894 (const :tag "No logging" nil)
2895 (const :tag "Record CLOSED timestamp" time)
2896 (const :tag "Record CLOSED timestamp with note." note)))
2898 ;; Normalize old uses of org-log-done.
2899 (cond
2900 ((eq org-log-done t) (setq org-log-done 'time))
2901 ((and (listp org-log-done) (memq 'done org-log-done))
2902 (setq org-log-done 'note)))
2904 (defcustom org-log-reschedule nil
2905 "Information to record when the scheduling date of a task is modified.
2907 Possible values are:
2909 nil Don't add anything, just change the date
2910 time Add a time stamp to the task
2911 note Prompt for a note and add it with template `org-log-note-headings'
2913 This option can also be set with on a per-file-basis with
2915 #+STARTUP: nologreschedule
2916 #+STARTUP: logreschedule
2917 #+STARTUP: lognotereschedule
2919 You can have local logging settings for a subtree by setting the LOGGING
2920 property to one or more of these keywords.
2922 This variable has an effect when calling `org-schedule' or
2923 `org-agenda-schedule' only."
2924 :group 'org-todo
2925 :group 'org-progress
2926 :type '(choice
2927 (const :tag "No logging" nil)
2928 (const :tag "Record timestamp" time)
2929 (const :tag "Record timestamp with note" note)))
2931 (defcustom org-log-redeadline nil
2932 "Information to record when the deadline date of a task is modified.
2934 Possible values are:
2936 nil Don't add anything, just change the date
2937 time Add a time stamp to the task
2938 note Prompt for a note and add it with template `org-log-note-headings'
2940 This option can also be set with on a per-file-basis with
2942 #+STARTUP: nologredeadline
2943 #+STARTUP: logredeadline
2944 #+STARTUP: lognoteredeadline
2946 You can have local logging settings for a subtree by setting the LOGGING
2947 property to one or more of these keywords.
2949 This variable has an effect when calling `org-deadline' or
2950 `org-agenda-deadline' only."
2951 :group 'org-todo
2952 :group 'org-progress
2953 :type '(choice
2954 (const :tag "No logging" nil)
2955 (const :tag "Record timestamp" time)
2956 (const :tag "Record timestamp with note." note)))
2958 (defcustom org-log-note-clock-out nil
2959 "Non-nil means record a note when clocking out of an item.
2960 This can also be configured on a per-file basis by adding one of
2961 the following lines anywhere in the buffer:
2963 #+STARTUP: lognoteclock-out
2964 #+STARTUP: nolognoteclock-out"
2965 :group 'org-todo
2966 :group 'org-progress
2967 :type 'boolean)
2969 (defcustom org-log-done-with-time t
2970 "Non-nil means the CLOSED time stamp will contain date and time.
2971 When nil, only the date will be recorded."
2972 :group 'org-progress
2973 :type 'boolean)
2975 (defcustom org-log-note-headings
2976 '((done . "CLOSING NOTE %t")
2977 (state . "State %-12s from %-12S %t")
2978 (note . "Note taken on %t")
2979 (reschedule . "Rescheduled from %S on %t")
2980 (delschedule . "Not scheduled, was %S on %t")
2981 (redeadline . "New deadline from %S on %t")
2982 (deldeadline . "Removed deadline, was %S on %t")
2983 (refile . "Refiled on %t")
2984 (clock-out . ""))
2985 "Headings for notes added to entries.
2987 The value is an alist, with the car being a symbol indicating the
2988 note context, and the cdr is the heading to be used. The heading
2989 may also be the empty string. The following placeholders can be
2990 used:
2992 %t a time stamp.
2993 %T an active time stamp instead the default inactive one
2994 %d a short-format time stamp.
2995 %D an active short-format time stamp.
2996 %s the new TODO state or time stamp (inactive), in double quotes.
2997 %S the old TODO state or time stamp (inactive), in double quotes.
2998 %u the user name.
2999 %U full user name.
3001 In fact, it is not a good idea to change the `state' entry,
3002 because Agenda Log mode depends on the format of these entries."
3003 :group 'org-todo
3004 :group 'org-progress
3005 :type '(list :greedy t
3006 (cons (const :tag "Heading when closing an item" done) string)
3007 (cons (const :tag
3008 "Heading when changing todo state (todo sequence only)"
3009 state) string)
3010 (cons (const :tag "Heading when just taking a note" note) string)
3011 (cons (const :tag "Heading when rescheduling" reschedule) string)
3012 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3013 (cons (const :tag "Heading when changing deadline" redeadline) string)
3014 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3015 (cons (const :tag "Heading when refiling" refile) string)
3016 (cons (const :tag "Heading when clocking out" clock-out) string)))
3018 (unless (assq 'note org-log-note-headings)
3019 (push '(note . "%t") org-log-note-headings))
3021 (defcustom org-log-into-drawer nil
3022 "Non-nil means insert state change notes and time stamps into a drawer.
3023 When nil, state changes notes will be inserted after the headline and
3024 any scheduling and clock lines, but not inside a drawer.
3026 The value of this variable should be the name of the drawer to use.
3027 LOGBOOK is proposed as the default drawer for this purpose, you can
3028 also set this to a string to define the drawer of your choice.
3030 A value of t is also allowed, representing \"LOGBOOK\".
3032 A value of t or nil can also be set with on a per-file-basis with
3034 #+STARTUP: logdrawer
3035 #+STARTUP: nologdrawer
3037 If this variable is set, `org-log-state-notes-insert-after-drawers'
3038 will be ignored.
3040 You can set the property LOG_INTO_DRAWER to overrule this setting for
3041 a subtree.
3043 Do not check directly this variable in a Lisp program. Call
3044 function `org-log-into-drawer' instead."
3045 :group 'org-todo
3046 :group 'org-progress
3047 :type '(choice
3048 (const :tag "Not into a drawer" nil)
3049 (const :tag "LOGBOOK" t)
3050 (string :tag "Other")))
3052 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3054 (defun org-log-into-drawer ()
3055 "Name of the log drawer, as a string, or nil.
3056 This is the value of `org-log-into-drawer'. However, if the
3057 current entry has or inherits a LOG_INTO_DRAWER property, it will
3058 be used instead of the default value."
3059 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3060 (cond ((equal p "nil") nil)
3061 ((equal p "t") "LOGBOOK")
3062 ((stringp p) p)
3063 (p "LOGBOOK")
3064 ((stringp org-log-into-drawer) org-log-into-drawer)
3065 (org-log-into-drawer "LOGBOOK"))))
3067 (defcustom org-log-state-notes-insert-after-drawers nil
3068 "Non-nil means insert state change notes after any drawers in entry.
3069 Only the drawers that *immediately* follow the headline and the
3070 deadline/scheduled line are skipped.
3071 When nil, insert notes right after the heading and perhaps the line
3072 with deadline/scheduling if present.
3074 This variable will have no effect if `org-log-into-drawer' is
3075 set."
3076 :group 'org-todo
3077 :group 'org-progress
3078 :type 'boolean)
3080 (defcustom org-log-states-order-reversed t
3081 "Non-nil means the latest state note will be directly after heading.
3082 When nil, the state change notes will be ordered according to time.
3084 This option can also be set with on a per-file-basis with
3086 #+STARTUP: logstatesreversed
3087 #+STARTUP: nologstatesreversed"
3088 :group 'org-todo
3089 :group 'org-progress
3090 :type 'boolean)
3092 (defcustom org-todo-repeat-to-state nil
3093 "The TODO state to which a repeater should return the repeating task.
3094 By default this is the first task of a TODO sequence or the
3095 previous state of a TYPE_TODO set. But you can specify to use
3096 the previous state in a TODO sequence or a string.
3098 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3099 entry, which has precedence over this option."
3100 :group 'org-todo
3101 :version "24.1"
3102 :type '(choice (const :tag "Use the previous TODO state" t)
3103 (const :tag "Use the head of the TODO sequence" nil)
3104 (string :tag "Use a specific TODO state")))
3106 (defcustom org-log-repeat 'time
3107 "Non-nil means record moving through the DONE state when triggering repeat.
3108 An auto-repeating task is immediately switched back to TODO when
3109 marked DONE. If you are not logging state changes (by adding \"@\"
3110 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3111 record a closing note, there will be no record of the task moving
3112 through DONE. This variable forces taking a note anyway.
3114 nil Don't force a record
3115 time Record a time stamp
3116 note Prompt for a note and add it with template `org-log-note-headings'
3118 This option can also be set with on a per-file-basis with
3120 #+STARTUP: nologrepeat
3121 #+STARTUP: logrepeat
3122 #+STARTUP: lognoterepeat
3124 You can have local logging settings for a subtree by setting the LOGGING
3125 property to one or more of these keywords."
3126 :group 'org-todo
3127 :group 'org-progress
3128 :type '(choice
3129 (const :tag "Don't force a record" nil)
3130 (const :tag "Force recording the DONE state" time)
3131 (const :tag "Force recording a note with the DONE state" note)))
3134 (defgroup org-priorities nil
3135 "Priorities in Org mode."
3136 :tag "Org Priorities"
3137 :group 'org-todo)
3139 (defcustom org-enable-priority-commands t
3140 "Non-nil means priority commands are active.
3141 When nil, these commands will be disabled, so that you never accidentally
3142 set a priority."
3143 :group 'org-priorities
3144 :type 'boolean)
3146 (defcustom org-highest-priority ?A
3147 "The highest priority of TODO items. A character like ?A, ?B etc.
3148 Must have a smaller ASCII number than `org-lowest-priority'."
3149 :group 'org-priorities
3150 :type 'character)
3152 (defcustom org-lowest-priority ?C
3153 "The lowest priority of TODO items. A character like ?A, ?B etc.
3154 Must have a larger ASCII number than `org-highest-priority'."
3155 :group 'org-priorities
3156 :type 'character)
3158 (defcustom org-default-priority ?B
3159 "The default priority of TODO items.
3160 This is the priority an item gets if no explicit priority is given.
3161 When starting to cycle on an empty priority the first step in the cycle
3162 depends on `org-priority-start-cycle-with-default'. The resulting first
3163 step priority must not exceed the range from `org-highest-priority' to
3164 `org-lowest-priority' which means that `org-default-priority' has to be
3165 in this range exclusive or inclusive the range boundaries. Else the
3166 first step refuses to set the default and the second will fall back
3167 to (depending on the command used) the highest or lowest priority."
3168 :group 'org-priorities
3169 :type 'character)
3171 (defcustom org-priority-start-cycle-with-default t
3172 "Non-nil means start with default priority when starting to cycle.
3173 When this is nil, the first step in the cycle will be (depending on the
3174 command used) one higher or lower than the default priority.
3175 See also `org-default-priority'."
3176 :group 'org-priorities
3177 :type 'boolean)
3179 (defcustom org-get-priority-function nil
3180 "Function to extract the priority from a string.
3181 The string is normally the headline. If this is nil Org computes the
3182 priority from the priority cookie like [#A] in the headline. It returns
3183 an integer, increasing by 1000 for each priority level.
3184 The user can set a different function here, which should take a string
3185 as an argument and return the numeric priority."
3186 :group 'org-priorities
3187 :version "24.1"
3188 :type '(choice
3189 (const nil)
3190 (function)))
3192 (defgroup org-time nil
3193 "Options concerning time stamps and deadlines in Org mode."
3194 :tag "Org Time"
3195 :group 'org)
3197 (defcustom org-time-stamp-rounding-minutes '(0 5)
3198 "Number of minutes to round time stamps to.
3199 \\<org-mode-map>\
3200 These are two values, the first applies when first creating a time stamp.
3201 The second applies when changing it with the commands `S-up' and `S-down'.
3202 When changing the time stamp, this means that it will change in steps
3203 of N minutes, as given by the second value.
3205 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3206 numbers should be factors of 60, so for example 5, 10, 15.
3208 When this is larger than 1, you can still force an exact time stamp by using
3209 a double prefix argument to a time stamp command like \
3210 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3211 and by using a prefix arg to `S-up/down' to specify the exact number
3212 of minutes to shift."
3213 :group 'org-time
3214 :get (lambda (var) ; Make sure both elements are there
3215 (if (integerp (default-value var))
3216 (list (default-value var) 5)
3217 (default-value var)))
3218 :type '(list
3219 (integer :tag "when inserting times")
3220 (integer :tag "when modifying times")))
3222 ;; Normalize old customizations of this variable.
3223 (when (integerp org-time-stamp-rounding-minutes)
3224 (setq org-time-stamp-rounding-minutes
3225 (list org-time-stamp-rounding-minutes
3226 org-time-stamp-rounding-minutes)))
3228 (defcustom org-display-custom-times nil
3229 "Non-nil means overlay custom formats over all time stamps.
3230 The formats are defined through the variable `org-time-stamp-custom-formats'.
3231 To turn this on on a per-file basis, insert anywhere in the file:
3232 #+STARTUP: customtime"
3233 :group 'org-time
3234 :set 'set-default
3235 :type 'sexp)
3236 (make-variable-buffer-local 'org-display-custom-times)
3238 (defcustom org-time-stamp-custom-formats
3239 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3240 "Custom formats for time stamps. See `format-time-string' for the syntax.
3241 These are overlaid over the default ISO format if the variable
3242 `org-display-custom-times' is set. Time like %H:%M should be at the
3243 end of the second format. The custom formats are also honored by export
3244 commands, if custom time display is turned on at the time of export."
3245 :group 'org-time
3246 :type 'sexp)
3248 (defun org-time-stamp-format (&optional long inactive)
3249 "Get the right format for a time string."
3250 (let ((f (if long (cdr org-time-stamp-formats)
3251 (car org-time-stamp-formats))))
3252 (if inactive
3253 (concat "[" (substring f 1 -1) "]")
3254 f)))
3256 (defcustom org-deadline-warning-days 14
3257 "Number of days before expiration during which a deadline becomes active.
3258 This variable governs the display in sparse trees and in the agenda.
3259 When 0 or negative, it means use this number (the absolute value of it)
3260 even if a deadline has a different individual lead time specified.
3262 Custom commands can set this variable in the options section."
3263 :group 'org-time
3264 :group 'org-agenda-daily/weekly
3265 :type 'integer)
3267 (defcustom org-scheduled-delay-days 0
3268 "Number of days before a scheduled item becomes active.
3269 This variable governs the display in sparse trees and in the agenda.
3270 The default value (i.e. 0) means: don't delay scheduled item.
3271 When negative, it means use this number (the absolute value of it)
3272 even if a scheduled item has a different individual delay time
3273 specified.
3275 Custom commands can set this variable in the options section."
3276 :group 'org-time
3277 :group 'org-agenda-daily/weekly
3278 :version "24.4"
3279 :package-version '(Org . "8.0")
3280 :type 'integer)
3282 (defcustom org-read-date-prefer-future t
3283 "Non-nil means assume future for incomplete date input from user.
3284 This affects the following situations:
3285 1. The user gives a month but not a year.
3286 For example, if it is April and you enter \"feb 2\", this will be read
3287 as Feb 2, *next* year. \"May 5\", however, will be this year.
3288 2. The user gives a day, but no month.
3289 For example, if today is the 15th, and you enter \"3\", Org will read
3290 this as the third of *next* month. However, if you enter \"17\",
3291 it will be considered as *this* month.
3293 If you set this variable to the symbol `time', then also the following
3294 will work:
3296 3. If the user gives a time.
3297 If the time is before now, it will be interpreted as tomorrow.
3299 Currently none of this works for ISO week specifications.
3301 When this option is nil, the current day, month and year will always be
3302 used as defaults.
3304 See also `org-agenda-jump-prefer-future'."
3305 :group 'org-time
3306 :type '(choice
3307 (const :tag "Never" nil)
3308 (const :tag "Check month and day" t)
3309 (const :tag "Check month, day, and time" time)))
3311 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3312 "Should the agenda jump command prefer the future for incomplete dates?
3313 The default is to do the same as configured in `org-read-date-prefer-future'.
3314 But you can also set a deviating value here.
3315 This may t or nil, or the symbol `org-read-date-prefer-future'."
3316 :group 'org-agenda
3317 :group 'org-time
3318 :version "24.1"
3319 :type '(choice
3320 (const :tag "Use org-read-date-prefer-future"
3321 org-read-date-prefer-future)
3322 (const :tag "Never" nil)
3323 (const :tag "Always" t)))
3325 (defcustom org-read-date-force-compatible-dates t
3326 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3328 Depending on the system Emacs is running on, certain dates cannot
3329 be represented with the type used internally to represent time.
3330 Dates between 1970-1-1 and 2038-1-1 can always be represented
3331 correctly. Some systems allow for earlier dates, some for later,
3332 some for both. One way to find out it to insert any date into an
3333 Org buffer, putting the cursor on the year and hitting S-up and
3334 S-down to test the range.
3336 When this variable is set to t, the date/time prompt will not let
3337 you specify dates outside the 1970-2037 range, so it is certain that
3338 these dates will work in whatever version of Emacs you are
3339 running, and also that you can move a file from one Emacs implementation
3340 to another. WHenever Org is forcing the year for you, it will display
3341 a message and beep.
3343 When this variable is nil, Org will check if the date is
3344 representable in the specific Emacs implementation you are using.
3345 If not, it will force a year, usually the current year, and beep
3346 to remind you. Currently this setting is not recommended because
3347 the likelihood that you will open your Org files in an Emacs that
3348 has limited date range is not negligible.
3350 A workaround for this problem is to use diary sexp dates for time
3351 stamps outside of this range."
3352 :group 'org-time
3353 :version "24.1"
3354 :type 'boolean)
3356 (defcustom org-read-date-display-live t
3357 "Non-nil means display current interpretation of date prompt live.
3358 This display will be in an overlay, in the minibuffer."
3359 :group 'org-time
3360 :type 'boolean)
3362 (defcustom org-read-date-popup-calendar t
3363 "Non-nil means pop up a calendar when prompting for a date.
3364 In the calendar, the date can be selected with mouse-1. However, the
3365 minibuffer will also be active, and you can simply enter the date as well.
3366 When nil, only the minibuffer will be available."
3367 :group 'org-time
3368 :type 'boolean)
3369 (defvaralias 'org-popup-calendar-for-date-prompt
3370 'org-read-date-popup-calendar)
3372 (defcustom org-extend-today-until 0
3373 "The hour when your day really ends. Must be an integer.
3374 This has influence for the following applications:
3375 - When switching the agenda to \"today\". It it is still earlier than
3376 the time given here, the day recognized as TODAY is actually yesterday.
3377 - When a date is read from the user and it is still before the time given
3378 here, the current date and time will be assumed to be yesterday, 23:59.
3379 Also, timestamps inserted in capture templates follow this rule.
3381 IMPORTANT: This is a feature whose implementation is and likely will
3382 remain incomplete. Really, it is only here because past midnight seems to
3383 be the favorite working time of John Wiegley :-)"
3384 :group 'org-time
3385 :type 'integer)
3387 (defcustom org-use-effective-time nil
3388 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3389 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3390 \"effective time\" of any timestamps between midnight and 8am will be
3391 23:59 of the previous day."
3392 :group 'org-time
3393 :version "24.1"
3394 :type 'boolean)
3396 (defcustom org-use-last-clock-out-time-as-effective-time nil
3397 "When non-nil, use the last clock out time for `org-todo'.
3398 Note that this option has precedence over the combined use of
3399 `org-use-effective-time' and `org-extend-today-until'."
3400 :group 'org-time
3401 :version "24.4"
3402 :package-version '(Org . "8.0")
3403 :type 'boolean)
3405 (defcustom org-edit-timestamp-down-means-later nil
3406 "Non-nil means S-down will increase the time in a time stamp.
3407 When nil, S-up will increase."
3408 :group 'org-time
3409 :type 'boolean)
3411 (defcustom org-calendar-follow-timestamp-change t
3412 "Non-nil means make the calendar window follow timestamp changes.
3413 When a timestamp is modified and the calendar window is visible, it will be
3414 moved to the new date."
3415 :group 'org-time
3416 :type 'boolean)
3418 (defgroup org-tags nil
3419 "Options concerning tags in Org mode."
3420 :tag "Org Tags"
3421 :group 'org)
3423 (defcustom org-tag-alist nil
3424 "Default tags available in Org files.
3426 The value of this variable is an alist. Associations either:
3428 (TAG)
3429 (TAG . SELECT)
3430 (SPECIAL)
3432 where TAG is a tag as a string, SELECT is character, used to
3433 select that tag through the fast tag selection interface, and
3434 SPECIAL is one of the following keywords: `:startgroup',
3435 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
3436 `:newline'. These keywords are used to define a hierarchy of
3437 tags. See manual for details.
3439 When this variable is nil, Org mode bases tag input on what is
3440 already in the buffer. The value can be overridden locally by
3441 using a TAGS keyword, e.g.,
3443 #+TAGS: tag1 tag2
3445 See also `org-tag-persistent-alist' to sidestep this behavior."
3446 :group 'org-tags
3447 :type '(repeat
3448 (choice
3449 (cons :tag "Tag with key"
3450 (string :tag "Tag name")
3451 (character :tag "Access char"))
3452 (list :tag "Tag" (string :tag "Tag name"))
3453 (const :tag "Start radio group" (:startgroup))
3454 (const :tag "Start tag group, non distinct" (:startgrouptag))
3455 (const :tag "Group tags delimiter" (:grouptags))
3456 (const :tag "End radio group" (:endgroup))
3457 (const :tag "End tag group, non distinct" (:endgrouptag))
3458 (const :tag "New line" (:newline)))))
3460 (defcustom org-tag-persistent-alist nil
3461 "Tags always available in Org files.
3463 The value of this variable is an alist. Associations either:
3465 (TAG)
3466 (TAG . SELECT)
3467 (SPECIAL)
3469 where TAG is a tag as a string, SELECT is a character, used to
3470 select that tag through the fast tag selection interface, and
3471 SPECIAL is one of the following keywords: `:startgroup',
3472 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
3473 `:newline'. These keywords are used to define a hierarchy of
3474 tags. See manual for details.
3476 Unlike to `org-tag-alist', tags defined in this variable do not
3477 depend on a local TAGS keyword. Instead, to disable these tags
3478 on a per-file basis, insert anywhere in the file:
3480 #+STARTUP: noptag"
3481 :group 'org-tags
3482 :type '(repeat
3483 (choice
3484 (cons :tag "Tag with key"
3485 (string :tag "Tag name")
3486 (character :tag "Access char"))
3487 (list :tag "Tag" (string :tag "Tag name"))
3488 (const :tag "Start radio group" (:startgroup))
3489 (const :tag "Start tag group, non distinct" (:startgrouptag))
3490 (const :tag "Group tags delimiter" (:grouptags))
3491 (const :tag "End radio group" (:endgroup))
3492 (const :tag "End tag group, non distinct" (:endgrouptag))
3493 (const :tag "New line" (:newline)))))
3495 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3496 "If non-nil, always offer completion for all tags of all agenda files.
3498 Setting this variable locally allows for dynamic generation of tag
3499 completions in capture buffers.
3501 (add-hook \\='org-capture-mode-hook
3502 (lambda ()
3503 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3504 :group 'org-tags
3505 :version "24.1"
3506 :type 'boolean)
3508 (defvar org-file-tags nil
3509 "List of tags that can be inherited by all entries in the file.
3510 The tags will be inherited if the variable `org-use-tag-inheritance'
3511 says they should be.
3512 This variable is populated from #+FILETAGS lines.")
3514 (defcustom org-use-fast-tag-selection 'auto
3515 "Non-nil means use fast tag selection scheme.
3516 This is a special interface to select and deselect tags with single keys.
3517 When nil, fast selection is never used.
3518 When the symbol `auto', fast selection is used if and only if selection
3519 characters for tags have been configured, either through the variable
3520 `org-tag-alist' or through a #+TAGS line in the buffer.
3521 When t, fast selection is always used and selection keys are assigned
3522 automatically if necessary."
3523 :group 'org-tags
3524 :type '(choice
3525 (const :tag "Always" t)
3526 (const :tag "Never" nil)
3527 (const :tag "When selection characters are configured" auto)))
3529 (defcustom org-fast-tag-selection-single-key nil
3530 "Non-nil means fast tag selection exits after first change.
3531 When nil, you have to press RET to exit it.
3532 During fast tag selection, you can toggle this flag with `C-c'.
3533 This variable can also have the value `expert'. In this case, the window
3534 displaying the tags menu is not even shown, until you press C-c again."
3535 :group 'org-tags
3536 :type '(choice
3537 (const :tag "No" nil)
3538 (const :tag "Yes" t)
3539 (const :tag "Expert" expert)))
3541 (defvar org-fast-tag-selection-include-todo nil
3542 "Non-nil means fast tags selection interface will also offer TODO states.
3543 This is an undocumented feature, you should not rely on it.")
3545 (defcustom org-tags-column -77
3546 "The column to which tags should be indented in a headline.
3547 If this number is positive, it specifies the column. If it is negative,
3548 it means that the tags should be flushright to that column. For example,
3549 -80 works well for a normal 80 character screen.
3550 When 0, place tags directly after headline text, with only one space in
3551 between."
3552 :group 'org-tags
3553 :type 'integer)
3555 (defcustom org-auto-align-tags t
3556 "Non-nil keeps tags aligned when modifying headlines.
3557 Some operations (i.e. demoting) change the length of a headline and
3558 therefore shift the tags around. With this option turned on, after
3559 each such operation the tags are again aligned to `org-tags-column'."
3560 :group 'org-tags
3561 :type 'boolean)
3563 (defcustom org-use-tag-inheritance t
3564 "Non-nil means tags in levels apply also for sublevels.
3565 When nil, only the tags directly given in a specific line apply there.
3566 This may also be a list of tags that should be inherited, or a regexp that
3567 matches tags that should be inherited. Additional control is possible
3568 with the variable `org-tags-exclude-from-inheritance' which gives an
3569 explicit list of tags to be excluded from inheritance, even if the value of
3570 `org-use-tag-inheritance' would select it for inheritance.
3572 If this option is t, a match early-on in a tree can lead to a large
3573 number of matches in the subtree when constructing the agenda or creating
3574 a sparse tree. If you only want to see the first match in a tree during
3575 a search, check out the variable `org-tags-match-list-sublevels'."
3576 :group 'org-tags
3577 :type '(choice
3578 (const :tag "Not" nil)
3579 (const :tag "Always" t)
3580 (repeat :tag "Specific tags" (string :tag "Tag"))
3581 (regexp :tag "Tags matched by regexp")))
3583 (defcustom org-tags-exclude-from-inheritance nil
3584 "List of tags that should never be inherited.
3585 This is a way to exclude a few tags from inheritance. For way to do
3586 the opposite, to actively allow inheritance for selected tags,
3587 see the variable `org-use-tag-inheritance'."
3588 :group 'org-tags
3589 :type '(repeat (string :tag "Tag")))
3591 (defun org-tag-inherit-p (tag)
3592 "Check if TAG is one that should be inherited."
3593 (cond
3594 ((member tag org-tags-exclude-from-inheritance) nil)
3595 ((eq org-use-tag-inheritance t) t)
3596 ((not org-use-tag-inheritance) nil)
3597 ((stringp org-use-tag-inheritance)
3598 (string-match org-use-tag-inheritance tag))
3599 ((listp org-use-tag-inheritance)
3600 (member tag org-use-tag-inheritance))
3601 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3603 (defcustom org-tags-match-list-sublevels t
3604 "Non-nil means list also sublevels of headlines matching a search.
3605 This variable applies to tags/property searches, and also to stuck
3606 projects because this search is based on a tags match as well.
3608 When set to the symbol `indented', sublevels are indented with
3609 leading dots.
3611 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3612 the sublevels of a headline matching a tag search often also match
3613 the same search. Listing all of them can create very long lists.
3614 Setting this variable to nil causes subtrees of a match to be skipped.
3616 This variable is semi-obsolete and probably should always be true. It
3617 is better to limit inheritance to certain tags using the variables
3618 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3619 :group 'org-tags
3620 :type '(choice
3621 (const :tag "No, don't list them" nil)
3622 (const :tag "Yes, do list them" t)
3623 (const :tag "List them, indented with leading dots" indented)))
3625 (defcustom org-tags-sort-function nil
3626 "When set, tags are sorted using this function as a comparator."
3627 :group 'org-tags
3628 :type '(choice
3629 (const :tag "No sorting" nil)
3630 (const :tag "Alphabetical" org-string-collate-lessp)
3631 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3632 (function :tag "Custom function" nil)))
3634 (defvar org-tags-history nil
3635 "History of minibuffer reads for tags.")
3636 (defvar org-last-tags-completion-table nil
3637 "The last used completion table for tags.")
3638 (defvar org-after-tags-change-hook nil
3639 "Hook that is run after the tags in a line have changed.")
3641 (defgroup org-properties nil
3642 "Options concerning properties in Org mode."
3643 :tag "Org Properties"
3644 :group 'org)
3646 (defcustom org-property-format "%-10s %s"
3647 "How property key/value pairs should be formatted by `indent-line'.
3648 When `indent-line' hits a property definition, it will format the line
3649 according to this format, mainly to make sure that the values are
3650 lined-up with respect to each other."
3651 :group 'org-properties
3652 :type 'string)
3654 (defcustom org-properties-postprocess-alist nil
3655 "Alist of properties and functions to adjust inserted values.
3656 Elements of this alist must be of the form
3658 ([string] [function])
3660 where [string] must be a property name and [function] must be a
3661 lambda expression: this lambda expression must take one argument,
3662 the value to adjust, and return the new value as a string.
3664 For example, this element will allow the property \"Remaining\"
3665 to be updated wrt the relation between the \"Effort\" property
3666 and the clock summary:
3668 ((\"Remaining\" (lambda(value)
3669 (let ((clocksum (org-clock-sum-current-item))
3670 (effort (org-duration-to-minutes
3671 (org-entry-get (point) \"Effort\"))))
3672 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3673 :group 'org-properties
3674 :version "24.1"
3675 :type '(alist :key-type (string :tag "Property")
3676 :value-type (function :tag "Function")))
3678 (defcustom org-use-property-inheritance nil
3679 "Non-nil means properties apply also for sublevels.
3681 This setting is chiefly used during property searches. Turning it on can
3682 cause significant overhead when doing a search, which is why it is not
3683 on by default.
3685 When nil, only the properties directly given in the current entry count.
3686 When t, every property is inherited. The value may also be a list of
3687 properties that should have inheritance, or a regular expression matching
3688 properties that should be inherited.
3690 However, note that some special properties use inheritance under special
3691 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3692 and the properties ending in \"_ALL\" when they are used as descriptor
3693 for valid values of a property.
3695 Note for programmers:
3696 When querying an entry with `org-entry-get', you can control if inheritance
3697 should be used. By default, `org-entry-get' looks only at the local
3698 properties. You can request inheritance by setting the inherit argument
3699 to t (to force inheritance) or to `selective' (to respect the setting
3700 in this variable)."
3701 :group 'org-properties
3702 :type '(choice
3703 (const :tag "Not" nil)
3704 (const :tag "Always" t)
3705 (repeat :tag "Specific properties" (string :tag "Property"))
3706 (regexp :tag "Properties matched by regexp")))
3708 (defun org-property-inherit-p (property)
3709 "Return a non-nil value if PROPERTY should be inherited."
3710 (cond
3711 ((eq org-use-property-inheritance t) t)
3712 ((not org-use-property-inheritance) nil)
3713 ((stringp org-use-property-inheritance)
3714 (string-match org-use-property-inheritance property))
3715 ((listp org-use-property-inheritance)
3716 (member-ignore-case property org-use-property-inheritance))
3717 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3719 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3720 "The default column format, if no other format has been defined.
3721 This variable can be set on the per-file basis by inserting a line
3723 #+COLUMNS: %25ITEM ....."
3724 :group 'org-properties
3725 :type 'string)
3727 (defcustom org-columns-ellipses ".."
3728 "The ellipses to be used when a field in column view is truncated.
3729 When this is the empty string, as many characters as possible are shown,
3730 but then there will be no visual indication that the field has been truncated.
3731 When this is a string of length N, the last N characters of a truncated
3732 field are replaced by this string. If the column is narrower than the
3733 ellipses string, only part of the ellipses string will be shown."
3734 :group 'org-properties
3735 :type 'string)
3737 (defconst org-global-properties-fixed
3738 '(("VISIBILITY_ALL" . "folded children content all")
3739 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3740 "List of property/value pairs that can be inherited by any entry.
3742 These are fixed values, for the preset properties. The user variable
3743 that can be used to add to this list is `org-global-properties'.
3745 The entries in this list are cons cells where the car is a property
3746 name and cdr is a string with the value. If the value represents
3747 multiple items like an \"_ALL\" property, separate the items by
3748 spaces.")
3750 (defcustom org-global-properties nil
3751 "List of property/value pairs that can be inherited by any entry.
3753 This list will be combined with the constant `org-global-properties-fixed'.
3755 The entries in this list are cons cells where the car is a property
3756 name and cdr is a string with the value.
3758 You can set buffer-local values for the same purpose in the variable
3759 `org-file-properties' this by adding lines like
3761 #+PROPERTY: NAME VALUE"
3762 :group 'org-properties
3763 :type '(repeat
3764 (cons (string :tag "Property")
3765 (string :tag "Value"))))
3767 (defvar-local org-file-properties nil
3768 "List of property/value pairs that can be inherited by any entry.
3769 Valid for the current buffer.
3770 This variable is populated from #+PROPERTY lines.")
3772 (defgroup org-agenda nil
3773 "Options concerning agenda views in Org mode."
3774 :tag "Org Agenda"
3775 :group 'org)
3777 (defvar-local org-category nil
3778 "Variable used by Org files to set a category for agenda display.
3779 Such files should use a file variable to set it, for example
3781 # -*- mode: org; org-category: \"ELisp\"
3783 or contain a special line
3785 #+CATEGORY: ELisp
3787 If the file does not specify a category, then file's base name
3788 is used instead.")
3789 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3791 (defcustom org-agenda-files nil
3792 "The files to be used for agenda display.
3794 If an entry is a directory, all files in that directory that are matched
3795 by `org-agenda-file-regexp' will be part of the file list.
3797 If the value of the variable is not a list but a single file name, then
3798 the list of agenda files is actually stored and maintained in that file,
3799 one agenda file per line. In this file paths can be given relative to
3800 `org-directory'. Tilde expansion and environment variable substitution
3801 are also made.
3803 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3804 and removed with `\\[org-remove-file]'."
3805 :group 'org-agenda
3806 :type '(choice
3807 (repeat :tag "List of files and directories" file)
3808 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3810 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3811 "Regular expression to match files for `org-agenda-files'.
3812 If any element in the list in that variable contains a directory instead
3813 of a normal file, all files in that directory that are matched by this
3814 regular expression will be included."
3815 :group 'org-agenda
3816 :type 'regexp)
3818 (defcustom org-agenda-text-search-extra-files nil
3819 "List of extra files to be searched by text search commands.
3820 These files will be searched in addition to the agenda files by the
3821 commands `org-search-view' (`\\[org-agenda] s') \
3822 and `org-occur-in-agenda-files'.
3823 Note that these files will only be searched for text search commands,
3824 not for the other agenda views like todo lists, tag searches or the weekly
3825 agenda. This variable is intended to list notes and possibly archive files
3826 that should also be searched by these two commands.
3827 In fact, if the first element in the list is the symbol `agenda-archives',
3828 then all archive files of all agenda files will be added to the search
3829 scope."
3830 :group 'org-agenda
3831 :type '(set :greedy t
3832 (const :tag "Agenda Archives" agenda-archives)
3833 (repeat :inline t (file))))
3835 (defvaralias 'org-agenda-multi-occur-extra-files
3836 'org-agenda-text-search-extra-files)
3838 (defcustom org-agenda-skip-unavailable-files nil
3839 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3840 A nil value means to remove them, after a query, from the list."
3841 :group 'org-agenda
3842 :type 'boolean)
3844 (defcustom org-agenda-diary-file 'diary-file
3845 "File to which to add new entries with the `i' key in agenda and calendar.
3846 When this is the symbol `diary-file', the functionality in the Emacs
3847 calendar will be used to add entries to the `diary-file'. But when this
3848 points to a file, `org-agenda-diary-entry' will be used instead."
3849 :group 'org-agenda
3850 :type '(choice
3851 (const :tag "The standard Emacs diary file" diary-file)
3852 (file :tag "Special Org file diary entries")))
3854 (defgroup org-latex nil
3855 "Options for embedding LaTeX code into Org mode."
3856 :tag "Org LaTeX"
3857 :group 'org)
3859 (defcustom org-format-latex-options
3860 '(:foreground default :background default :scale 1.0
3861 :html-foreground "Black" :html-background "Transparent"
3862 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3863 "Options for creating images from LaTeX fragments.
3864 This is a property list with the following properties:
3865 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3866 `default' means use the foreground of the default face.
3867 `auto' means use the foreground from the text face.
3868 :background the background color, or \"Transparent\".
3869 `default' means use the background of the default face.
3870 `auto' means use the background from the text face.
3871 :scale a scaling factor for the size of the images, to get more pixels
3872 :html-foreground, :html-background, :html-scale
3873 the same numbers for HTML export.
3874 :matchers a list indicating which matchers should be used to
3875 find LaTeX fragments. Valid members of this list are:
3876 \"begin\" find environments
3877 \"$1\" find single characters surrounded by $.$
3878 \"$\" find math expressions surrounded by $...$
3879 \"$$\" find math expressions surrounded by $$....$$
3880 \"\\(\" find math expressions surrounded by \\(...\\)
3881 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3882 :group 'org-latex
3883 :type 'plist)
3885 (defcustom org-format-latex-signal-error t
3886 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3887 When nil, just push out a message."
3888 :group 'org-latex
3889 :version "24.1"
3890 :type 'boolean)
3892 (defcustom org-latex-to-mathml-jar-file nil
3893 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3894 Use this to specify additional executable file say a jar file.
3896 When using MathToWeb as the converter, specify the full-path to
3897 your mathtoweb.jar file."
3898 :group 'org-latex
3899 :version "24.1"
3900 :type '(choice
3901 (const :tag "None" nil)
3902 (file :tag "JAR file" :must-match t)))
3904 (defcustom org-latex-to-mathml-convert-command nil
3905 "Command to convert LaTeX fragments to MathML.
3906 Replace format-specifiers in the command as noted below and use
3907 `shell-command' to convert LaTeX to MathML.
3908 %j: Executable file in fully expanded form as specified by
3909 `org-latex-to-mathml-jar-file'.
3910 %I: Input LaTeX file in fully expanded form.
3911 %i: The latex fragment to be converted.
3912 %o: Output MathML file.
3914 This command is used by `org-create-math-formula'.
3916 When using MathToWeb as the converter, set this option to
3917 \"java -jar %j -unicode -force -df %o %I\".
3919 When using LaTeXML set this option to
3920 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3921 :group 'org-latex
3922 :version "24.1"
3923 :type '(choice
3924 (const :tag "None" nil)
3925 (string :tag "\nShell command")))
3927 (defcustom org-preview-latex-default-process 'dvipng
3928 "The default process to convert LaTeX fragments to image files.
3929 All available processes and theirs documents can be found in
3930 `org-preview-latex-process-alist', which see."
3931 :group 'org-latex
3932 :version "26.1"
3933 :package-version '(Org . "9.0")
3934 :type 'symbol)
3936 (defcustom org-preview-latex-process-alist
3937 '((dvipng
3938 :programs ("latex" "dvipng")
3939 :description "dvi > png"
3940 :message "you need to install the programs: latex and dvipng."
3941 :image-input-type "dvi"
3942 :image-output-type "png"
3943 :image-size-adjust (1.0 . 1.0)
3944 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3945 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3946 (dvisvgm
3947 :programs ("latex" "dvisvgm")
3948 :description "dvi > svg"
3949 :message "you need to install the programs: latex and dvisvgm."
3950 :use-xcolor t
3951 :image-input-type "dvi"
3952 :image-output-type "svg"
3953 :image-size-adjust (1.7 . 1.5)
3954 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3955 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3956 (imagemagick
3957 :programs ("latex" "convert")
3958 :description "pdf > png"
3959 :message "you need to install the programs: latex and imagemagick."
3960 :use-xcolor t
3961 :image-input-type "pdf"
3962 :image-output-type "png"
3963 :image-size-adjust (1.0 . 1.0)
3964 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3965 :image-converter
3966 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3967 "Definitions of external processes for LaTeX previewing.
3968 Org mode can use some external commands to generate TeX snippet's images for
3969 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3970 `org-create-formula-image' how to call them.
3972 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3973 PROPERTIES accepts the following attributes:
3975 :programs list of strings, required programs.
3976 :description string, describe the process.
3977 :message string, message it when required programs cannot be found.
3978 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3979 :image-output-type string, output file type of image converter (e.g., \"png\").
3980 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3981 deal with background and foreground color of image.
3982 Otherwise, dvipng style background and foreground color
3983 format are generated. You may then refer to them in
3984 command options with \"%F\" and \"%B\".
3985 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3986 image size showed in buffer and the cdr element is for
3987 HTML file. This option is only useful for process
3988 developers, users should use variable
3989 `org-format-latex-options' instead.
3990 :post-clean list of strings, files matched are to be cleaned up once
3991 the image is generated. When nil, the files with \".dvi\",
3992 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3993 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3994 be cleaned up.
3995 :latex-header list of strings, the LaTeX header of the snippet file.
3996 When nil, the fallback value is used instead, which is
3997 controlled by `org-format-latex-header',
3998 `org-latex-default-packages-alist' and
3999 `org-latex-packages-alist', which see.
4000 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4001 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4002 replaced with values defined below.
4003 :image-converter list of image converter commands strings. Each of them is
4004 given to the shell and supports any of the following
4005 place-holders defined below.
4007 Place-holders used by `:image-converter' and `:latex-compiler':
4009 %f input file name
4010 %b base name of input file
4011 %o base directory of input file
4012 %O absolute output file name
4014 Place-holders only used by `:image-converter':
4016 %F foreground of image
4017 %B background of image
4018 %D dpi, which is used to adjust image size by some processing commands.
4019 %S the image size scale ratio, which is used to adjust image size by some
4020 processing commands."
4021 :group 'org-latex
4022 :version "26.1"
4023 :package-version '(Org . "9.0")
4024 :type '(alist :tag "LaTeX to image backends"
4025 :value-type (plist)))
4027 (defcustom org-preview-latex-image-directory "ltximg/"
4028 "Path to store latex preview images.
4029 A relative path here creates many directories relative to the
4030 processed Org files paths. An absolute path puts all preview
4031 images at the same place."
4032 :group 'org-latex
4033 :version "26.1"
4034 :package-version '(Org . "9.0")
4035 :type 'string)
4037 (defun org-format-latex-mathml-available-p ()
4038 "Return t if `org-latex-to-mathml-convert-command' is usable."
4039 (save-match-data
4040 (when (and (boundp 'org-latex-to-mathml-convert-command)
4041 org-latex-to-mathml-convert-command)
4042 (let ((executable (car (split-string
4043 org-latex-to-mathml-convert-command))))
4044 (when (executable-find executable)
4045 (if (string-match
4046 "%j" org-latex-to-mathml-convert-command)
4047 (file-readable-p org-latex-to-mathml-jar-file)
4048 t))))))
4050 (defcustom org-format-latex-header "\\documentclass{article}
4051 \\usepackage[usenames]{color}
4052 \[PACKAGES]
4053 \[DEFAULT-PACKAGES]
4054 \\pagestyle{empty} % do not remove
4055 % The settings below are copied from fullpage.sty
4056 \\setlength{\\textwidth}{\\paperwidth}
4057 \\addtolength{\\textwidth}{-3cm}
4058 \\setlength{\\oddsidemargin}{1.5cm}
4059 \\addtolength{\\oddsidemargin}{-2.54cm}
4060 \\setlength{\\evensidemargin}{\\oddsidemargin}
4061 \\setlength{\\textheight}{\\paperheight}
4062 \\addtolength{\\textheight}{-\\headheight}
4063 \\addtolength{\\textheight}{-\\headsep}
4064 \\addtolength{\\textheight}{-\\footskip}
4065 \\addtolength{\\textheight}{-3cm}
4066 \\setlength{\\topmargin}{1.5cm}
4067 \\addtolength{\\topmargin}{-2.54cm}"
4068 "The document header used for processing LaTeX fragments.
4069 It is imperative that this header make sure that no page number
4070 appears on the page. The package defined in the variables
4071 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4072 will either replace the placeholder \"[PACKAGES]\" in this
4073 header, or they will be appended."
4074 :group 'org-latex
4075 :type 'string)
4077 (defun org-set-packages-alist (var val)
4078 "Set the packages alist and make sure it has 3 elements per entry."
4079 (set var (mapcar (lambda (x)
4080 (if (and (consp x) (= (length x) 2))
4081 (list (car x) (nth 1 x) t)
4083 val)))
4085 (defun org-get-packages-alist (var)
4086 "Get the packages alist and make sure it has 3 elements per entry."
4087 (mapcar (lambda (x)
4088 (if (and (consp x) (= (length x) 2))
4089 (list (car x) (nth 1 x) t)
4091 (default-value var)))
4093 (defcustom org-latex-default-packages-alist
4094 '(("AUTO" "inputenc" t ("pdflatex"))
4095 ("T1" "fontenc" t ("pdflatex"))
4096 ("" "graphicx" t)
4097 ("" "grffile" t)
4098 ("" "longtable" nil)
4099 ("" "wrapfig" nil)
4100 ("" "rotating" nil)
4101 ("normalem" "ulem" t)
4102 ("" "amsmath" t)
4103 ("" "textcomp" t)
4104 ("" "amssymb" t)
4105 ("" "capt-of" nil)
4106 ("" "hyperref" nil))
4107 "Alist of default packages to be inserted in the header.
4109 Change this only if one of the packages here causes an
4110 incompatibility with another package you are using.
4112 The packages in this list are needed by one part or another of
4113 Org mode to function properly:
4115 - inputenc, fontenc: for basic font and character selection
4116 - graphicx: for including images
4117 - grffile: allow periods and spaces in graphics file names
4118 - longtable: For multipage tables
4119 - wrapfig: for figure placement
4120 - rotating: for sideways figures and tables
4121 - ulem: for underline and strike-through
4122 - amsmath: for subscript and superscript and math environments
4123 - textcomp, amssymb: for various symbols used
4124 for interpreting the entities in `org-entities'. You can skip
4125 some of these packages if you don't use any of their symbols.
4126 - capt-of: for captions outside of floats
4127 - hyperref: for cross references
4129 Therefore you should not modify this variable unless you know
4130 what you are doing. The one reason to change it anyway is that
4131 you might be loading some other package that conflicts with one
4132 of the default packages. Each element is either a cell or
4133 a string.
4135 A cell is of the format
4137 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4139 If SNIPPET-FLAG is non-nil, the package also needs to be included
4140 when compiling LaTeX snippets into images for inclusion into
4141 non-LaTeX output.
4143 COMPILERS is a list of compilers that should include the package,
4144 see `org-latex-compiler'. If the document compiler is not in the
4145 list, and the list is non-nil, the package will not be inserted
4146 in the final document.
4148 A string will be inserted as-is in the header of the document."
4149 :group 'org-latex
4150 :group 'org-export-latex
4151 :set 'org-set-packages-alist
4152 :get 'org-get-packages-alist
4153 :version "26.1"
4154 :package-version '(Org . "8.3")
4155 :type '(repeat
4156 (choice
4157 (list :tag "options/package pair"
4158 (string :tag "options")
4159 (string :tag "package")
4160 (boolean :tag "Snippet")
4161 (choice
4162 (const :tag "For all compilers" nil)
4163 (repeat :tag "Allowed compiler" string)))
4164 (string :tag "A line of LaTeX"))))
4166 (defcustom org-latex-packages-alist nil
4167 "Alist of packages to be inserted in every LaTeX header.
4169 These will be inserted after `org-latex-default-packages-alist'.
4170 Each element is either a cell or a string.
4172 A cell is of the format:
4174 (\"options\" \"package\" SNIPPET-FLAG)
4176 SNIPPET-FLAG, when non-nil, indicates that this package is also
4177 needed when turning LaTeX snippets into images for inclusion into
4178 non-LaTeX output.
4180 COMPILERS is a list of compilers that should include the package,
4181 see `org-latex-compiler'. If the document compiler is not in the
4182 list, and the list is non-nil, the package will not be inserted
4183 in the final document.
4185 A string will be inserted as-is in the header of the document.
4187 Make sure that you only list packages here which:
4189 - you want in every file;
4190 - do not conflict with the setup in `org-format-latex-header';
4191 - do not conflict with the default packages in
4192 `org-latex-default-packages-alist'."
4193 :group 'org-latex
4194 :group 'org-export-latex
4195 :set 'org-set-packages-alist
4196 :get 'org-get-packages-alist
4197 :type '(repeat
4198 (choice
4199 (list :tag "options/package pair"
4200 (string :tag "options")
4201 (string :tag "package")
4202 (boolean :tag "Snippet"))
4203 (string :tag "A line of LaTeX"))))
4205 (defgroup org-appearance nil
4206 "Settings for Org mode appearance."
4207 :tag "Org Appearance"
4208 :group 'org)
4210 (defcustom org-level-color-stars-only nil
4211 "Non-nil means fontify only the stars in each headline.
4212 When nil, the entire headline is fontified.
4213 Changing it requires restart of `font-lock-mode' to become effective
4214 also in regions already fontified."
4215 :group 'org-appearance
4216 :type 'boolean)
4218 (defcustom org-hide-leading-stars nil
4219 "Non-nil means hide the first N-1 stars in a headline.
4220 This works by using the face `org-hide' for these stars. This
4221 face is white for a light background, and black for a dark
4222 background. You may have to customize the face `org-hide' to
4223 make this work.
4224 Changing it requires restart of `font-lock-mode' to become effective
4225 also in regions already fontified.
4226 You may also set this on a per-file basis by adding one of the following
4227 lines to the buffer:
4229 #+STARTUP: hidestars
4230 #+STARTUP: showstars"
4231 :group 'org-appearance
4232 :type 'boolean)
4234 (defcustom org-hidden-keywords nil
4235 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4236 For example, a value \\='(title) for this list makes the document's title
4237 appear in the buffer without the initial \"#+TITLE:\" part."
4238 :group 'org-appearance
4239 :version "24.1"
4240 :type '(set (const :tag "#+AUTHOR" author)
4241 (const :tag "#+DATE" date)
4242 (const :tag "#+EMAIL" email)
4243 (const :tag "#+TITLE" title)))
4245 (defcustom org-custom-properties nil
4246 "List of properties (as strings) with a special meaning.
4247 The default use of these custom properties is to let the user
4248 hide them with `org-toggle-custom-properties-visibility'."
4249 :group 'org-properties
4250 :group 'org-appearance
4251 :version "24.3"
4252 :type '(repeat (string :tag "Property Name")))
4254 (defcustom org-fontify-done-headline nil
4255 "Non-nil means change the face of a headline if it is marked DONE.
4256 Normally, only the TODO/DONE keyword indicates the state of a headline.
4257 When this is non-nil, the headline after the keyword is set to the
4258 `org-headline-done' as an additional indication."
4259 :group 'org-appearance
4260 :type 'boolean)
4262 (defcustom org-fontify-emphasized-text t
4263 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4264 Changing this variable requires a restart of Emacs to take effect."
4265 :group 'org-appearance
4266 :type 'boolean)
4268 (defcustom org-fontify-whole-heading-line nil
4269 "Non-nil means fontify the whole line for headings.
4270 This is useful when setting a background color for the
4271 org-level-* faces."
4272 :group 'org-appearance
4273 :type 'boolean)
4275 (defcustom org-highlight-latex-and-related nil
4276 "Non-nil means highlight LaTeX related syntax in the buffer.
4277 When non nil, the value should be a list containing any of the
4278 following symbols:
4279 `latex' Highlight LaTeX snippets and environments.
4280 `script' Highlight subscript and superscript.
4281 `entities' Highlight entities."
4282 :group 'org-appearance
4283 :version "24.4"
4284 :package-version '(Org . "8.0")
4285 :type '(choice
4286 (const :tag "No highlighting" nil)
4287 (set :greedy t :tag "Highlight"
4288 (const :tag "LaTeX snippets and environments" latex)
4289 (const :tag "Subscript and superscript" script)
4290 (const :tag "Entities" entities))))
4292 (defcustom org-hide-emphasis-markers nil
4293 "Non-nil mean font-lock should hide the emphasis marker characters."
4294 :group 'org-appearance
4295 :type 'boolean
4296 :safe #'booleanp)
4298 (defcustom org-hide-macro-markers nil
4299 "Non-nil mean font-lock should hide the brackets marking macro calls."
4300 :group 'org-appearance
4301 :type 'boolean)
4303 (defcustom org-pretty-entities nil
4304 "Non-nil means show entities as UTF8 characters.
4305 When nil, the \\name form remains in the buffer."
4306 :group 'org-appearance
4307 :version "24.1"
4308 :type 'boolean)
4310 (defcustom org-pretty-entities-include-sub-superscripts t
4311 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4312 :group 'org-appearance
4313 :version "24.1"
4314 :type 'boolean)
4316 (defvar org-emph-re nil
4317 "Regular expression for matching emphasis.
4318 After a match, the match groups contain these elements:
4319 0 The match of the full regular expression, including the characters
4320 before and after the proper match
4321 1 The character before the proper match, or empty at beginning of line
4322 2 The proper match, including the leading and trailing markers
4323 3 The leading marker like * or /, indicating the type of highlighting
4324 4 The text between the emphasis markers, not including the markers
4325 5 The character after the match, empty at the end of a line")
4327 (defvar org-verbatim-re nil
4328 "Regular expression for matching verbatim text.")
4330 (defvar org-emphasis-regexp-components) ; defined just below
4331 (defvar org-emphasis-alist) ; defined just below
4332 (defun org-set-emph-re (var val)
4333 "Set variable and compute the emphasis regular expression."
4334 (set var val)
4335 (when (and (boundp 'org-emphasis-alist)
4336 (boundp 'org-emphasis-regexp-components)
4337 org-emphasis-alist org-emphasis-regexp-components)
4338 (pcase-let*
4339 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4340 (body (if (<= nl 0) body
4341 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4342 (template
4343 (format (concat "\\([%s]\\|^\\)" ;before markers
4344 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4345 "\\([%s]\\|$\\)") ;after markers
4346 pre border border body border post)))
4347 (setq org-emph-re (format template "*/_+"))
4348 (setq org-verbatim-re (format template "=~")))))
4350 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4351 ;; set this option proved cumbersome. See this message/thread:
4352 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4353 (defvar org-emphasis-regexp-components
4354 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4355 "Components used to build the regular expression for emphasis.
4356 This is a list with five entries. Terminology: In an emphasis string
4357 like \" *strong word* \", we call the initial space PREMATCH, the final
4358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4359 and \"trong wor\" is the body. The different components in this variable
4360 specify what is allowed/forbidden in each part:
4362 pre Chars allowed as prematch. Beginning of line will be allowed too.
4363 post Chars allowed as postmatch. End of line will be allowed too.
4364 border The chars *forbidden* as border characters.
4365 body-regexp A regexp like \".\" to match a body character. Don't use
4366 non-shy groups here, and don't allow newline here.
4367 newline The maximum number of newlines allowed in an emphasis exp.
4369 You need to reload Org or to restart Emacs after setting this.")
4371 (defcustom org-emphasis-alist
4372 '(("*" bold)
4373 ("/" italic)
4374 ("_" underline)
4375 ("=" org-verbatim verbatim)
4376 ("~" org-code verbatim)
4377 ("+" (:strike-through t)))
4378 "Alist of characters and faces to emphasize text.
4379 Text starting and ending with a special character will be emphasized,
4380 for example *bold*, _underlined_ and /italic/. This variable sets the
4381 marker characters and the face to be used by font-lock for highlighting
4382 in Org buffers.
4384 You need to reload Org or to restart Emacs after customizing this."
4385 :group 'org-appearance
4386 :set 'org-set-emph-re
4387 :version "24.4"
4388 :package-version '(Org . "8.0")
4389 :type '(repeat
4390 (list
4391 (string :tag "Marker character")
4392 (choice
4393 (face :tag "Font-lock-face")
4394 (plist :tag "Face property list"))
4395 (option (const verbatim)))))
4397 (defvar org-protecting-blocks '("src" "example" "export")
4398 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4399 This is needed for font-lock setup.")
4401 ;;; Functions and variables from their packages
4402 ;; Declared here to avoid compiler warnings
4403 (defvar mark-active)
4405 ;; Various packages
4406 (declare-function calc-eval "calc" (str &optional separator &rest args))
4407 (declare-function calendar-forward-day "cal-move" (arg))
4408 (declare-function calendar-goto-date "cal-move" (date))
4409 (declare-function calendar-goto-today "cal-move" ())
4410 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4411 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4412 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4413 (declare-function cdlatex-tab "ext:cdlatex" ())
4414 (declare-function dired-get-filename
4415 "dired"
4416 (&optional localp no-error-if-not-filep))
4417 (declare-function iswitchb-read-buffer
4418 "iswitchb"
4419 (prompt &optional
4420 default require-match _predicate start matches-set))
4421 (declare-function org-agenda-change-all-lines
4422 "org-agenda"
4423 (newhead hdmarker &optional fixface just-this))
4424 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4425 "org-agenda"
4426 (&optional end))
4427 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4428 (declare-function org-agenda-format-item
4429 "org-agenda"
4430 (extra txt &optional level category tags dotime
4431 remove-re habitp))
4432 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4433 (declare-function org-agenda-save-markers-for-cut-and-paste
4434 "org-agenda"
4435 (beg end))
4436 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4437 (declare-function org-agenda-skip "org-agenda" ())
4438 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4439 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4440 (declare-function org-indent-mode "org-indent" (&optional arg))
4441 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4442 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4443 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4444 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4445 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4446 (declare-function parse-time-string "parse-time" (string))
4448 (defvar align-mode-rules-list)
4449 (defvar calc-embedded-close-formula)
4450 (defvar calc-embedded-open-formula)
4451 (defvar calc-embedded-open-mode)
4452 (defvar font-lock-unfontify-region-function)
4453 (defvar iswitchb-temp-buflist)
4454 (defvar org-agenda-tags-todo-honor-ignore-options)
4455 (defvar remember-data-file)
4456 (defvar texmathp-why)
4458 ;;;###autoload
4459 (defun turn-on-orgtbl ()
4460 "Unconditionally turn on `orgtbl-mode'."
4461 (require 'org-table)
4462 (orgtbl-mode 1))
4464 (defun org-at-table-p (&optional table-type)
4465 "Non-nil if the cursor is inside an Org table.
4466 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4467 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4468 (or (not (derived-mode-p 'org-mode))
4469 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4470 (and e (or table-type
4471 (eq 'org (org-element-property :type e))))))))
4473 (defun org-at-table.el-p ()
4474 "Non-nil when point is at a table.el table."
4475 (and (org-match-line "[ \t]*[|+]")
4476 (let ((element (org-element-at-point)))
4477 (and (eq (org-element-type element) 'table)
4478 (eq (org-element-property :type element) 'table.el)))))
4480 (defun org-at-table-hline-p ()
4481 "Non-nil when point is inside a hline in a table.
4482 Assume point is already in a table."
4483 (org-match-line org-table-hline-regexp))
4485 (defun org-table-map-tables (function &optional quietly)
4486 "Apply FUNCTION to the start of all tables in the buffer."
4487 (org-with-wide-buffer
4488 (goto-char (point-min))
4489 (while (re-search-forward org-table-any-line-regexp nil t)
4490 (unless quietly
4491 (message "Mapping tables: %d%%"
4492 (floor (* 100.0 (point)) (buffer-size))))
4493 (beginning-of-line 1)
4494 (when (and (looking-at org-table-line-regexp)
4495 ;; Exclude tables in src/example/verbatim/clocktable blocks
4496 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4497 (save-excursion (funcall function))
4498 (or (looking-at org-table-line-regexp)
4499 (forward-char 1)))
4500 (re-search-forward org-table-any-border-regexp nil 1)))
4501 (unless quietly (message "Mapping tables: done")))
4503 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4504 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
4505 (declare-function org-resolve-clocks "org-clock"
4506 (&optional also-non-dangling-p prompt last-valid))
4508 (defun org-at-TBLFM-p (&optional pos)
4509 "Non-nil when point (or POS) is in #+TBLFM line."
4510 (save-excursion
4511 (goto-char (or pos (point)))
4512 (beginning-of-line)
4513 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4514 (eq (org-element-type (org-element-at-point)) 'table))))
4516 (defvar org-clock-start-time)
4517 (defvar org-clock-marker (make-marker)
4518 "Marker recording the last clock-in.")
4519 (defvar org-clock-hd-marker (make-marker)
4520 "Marker recording the last clock-in, but the headline position.")
4521 (defvar org-clock-heading ""
4522 "The heading of the current clock entry.")
4523 (defun org-clock-is-active ()
4524 "Return the buffer where the clock is currently running.
4525 Return nil if no clock is running."
4526 (marker-buffer org-clock-marker))
4528 (defun org-check-running-clock ()
4529 "Check if the current buffer contains the running clock.
4530 If yes, offer to stop it and to save the buffer with the changes."
4531 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4532 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4533 (buffer-name))))
4534 (org-clock-out)
4535 (when (y-or-n-p "Save changed buffer?")
4536 (save-buffer))))
4538 (defun org-clocktable-try-shift (dir n)
4539 "Check if this line starts a clock table, if yes, shift the time block."
4540 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4541 (org-clocktable-shift dir n)))
4543 ;;;###autoload
4544 (defun org-clock-persistence-insinuate ()
4545 "Set up hooks for clock persistence."
4546 (require 'org-clock)
4547 (add-hook 'org-mode-hook 'org-clock-load)
4548 (add-hook 'kill-emacs-hook 'org-clock-save))
4550 (defgroup org-archive nil
4551 "Options concerning archiving in Org mode."
4552 :tag "Org Archive"
4553 :group 'org-structure)
4555 (defcustom org-archive-location "%s_archive::"
4556 "The location where subtrees should be archived.
4558 The value of this variable is a string, consisting of two parts,
4559 separated by a double-colon. The first part is a filename and
4560 the second part is a headline.
4562 When the filename is omitted, archiving happens in the same file.
4563 %s in the filename will be replaced by the current file
4564 name (without the directory part). Archiving to a different file
4565 is useful to keep archived entries from contributing to the
4566 Org Agenda.
4568 The archived entries will be filed as subtrees of the specified
4569 headline. When the headline is omitted, the subtrees are simply
4570 filed away at the end of the file, as top-level entries. Also in
4571 the heading you can use %s to represent the file name, this can be
4572 useful when using the same archive for a number of different files.
4574 Here are a few examples:
4575 \"%s_archive::\"
4576 If the current file is Projects.org, archive in file
4577 Projects.org_archive, as top-level trees. This is the default.
4579 \"::* Archived Tasks\"
4580 Archive in the current file, under the top-level headline
4581 \"* Archived Tasks\".
4583 \"~/org/archive.org::\"
4584 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4586 \"~/org/archive.org::* From %s\"
4587 Archive in file ~/org/archive.org (absolute path), under headlines
4588 \"From FILENAME\" where file name is the current file name.
4590 \"~/org/datetree.org::datetree/* Finished Tasks\"
4591 The \"datetree/\" string is special, signifying to archive
4592 items to the datetree. Items are placed in either the CLOSED
4593 date of the item, or the current date if there is no CLOSED date.
4594 The heading will be a subentry to the current date. There doesn't
4595 need to be a heading, but there always needs to be a slash after
4596 datetree. For example, to store archived items directly in the
4597 datetree, use \"~/org/datetree.org::datetree/\".
4599 \"basement::** Finished Tasks\"
4600 Archive in file ./basement (relative path), as level 3 trees
4601 below the level 2 heading \"** Finished Tasks\".
4603 You may set this option on a per-file basis by adding to the buffer a
4604 line like
4606 #+ARCHIVE: basement::** Finished Tasks
4608 You may also define it locally for a subtree by setting an ARCHIVE property
4609 in the entry. If such a property is found in an entry, or anywhere up
4610 the hierarchy, it will be used."
4611 :group 'org-archive
4612 :type 'string)
4614 (defcustom org-agenda-skip-archived-trees t
4615 "Non-nil means the agenda will skip any items located in archived trees.
4616 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4617 variable is no longer recommended, you should leave it at the value t.
4618 Instead, use the key `v' to cycle the archives-mode in the agenda."
4619 :group 'org-archive
4620 :group 'org-agenda-skip
4621 :type 'boolean)
4623 (defcustom org-columns-skip-archived-trees t
4624 "Non-nil means ignore archived trees when creating column view."
4625 :group 'org-archive
4626 :group 'org-properties
4627 :type 'boolean)
4629 (defcustom org-cycle-open-archived-trees nil
4630 "Non-nil means `org-cycle' will open archived trees.
4631 An archived tree is a tree marked with the tag ARCHIVE.
4632 When nil, archived trees will stay folded. You can still open them with
4633 normal outline commands like `show-all', but not with the cycling commands."
4634 :group 'org-archive
4635 :group 'org-cycle
4636 :type 'boolean)
4638 (defcustom org-sparse-tree-open-archived-trees nil
4639 "Non-nil means sparse tree construction shows matches in archived trees.
4640 When nil, matches in these trees are highlighted, but the trees are kept in
4641 collapsed state."
4642 :group 'org-archive
4643 :group 'org-sparse-trees
4644 :type 'boolean)
4646 (defcustom org-sparse-tree-default-date-type nil
4647 "The default date type when building a sparse tree.
4648 When this is nil, a date is a scheduled or a deadline timestamp.
4649 Otherwise, these types are allowed:
4651 all: all timestamps
4652 active: only active timestamps (<...>)
4653 inactive: only inactive timestamps ([...])
4654 scheduled: only scheduled timestamps
4655 deadline: only deadline timestamps"
4656 :type '(choice (const :tag "Scheduled or deadline" nil)
4657 (const :tag "All timestamps" all)
4658 (const :tag "Only active timestamps" active)
4659 (const :tag "Only inactive timestamps" inactive)
4660 (const :tag "Only scheduled timestamps" scheduled)
4661 (const :tag "Only deadline timestamps" deadline)
4662 (const :tag "Only closed timestamps" closed))
4663 :version "26.1"
4664 :package-version '(Org . "8.3")
4665 :group 'org-sparse-trees)
4667 (defun org-cycle-hide-archived-subtrees (state)
4668 "Re-hide all archived subtrees after a visibility state change.
4669 STATE should be one of the symbols listed in the docstring of
4670 `org-cycle-hook'."
4671 (when (and (not org-cycle-open-archived-trees)
4672 (not (memq state '(overview folded))))
4673 (save-excursion
4674 (let* ((globalp (memq state '(contents all)))
4675 (beg (if globalp (point-min) (point)))
4676 (end (if globalp (point-max) (org-end-of-subtree t))))
4677 (org-hide-archived-subtrees beg end)
4678 (goto-char beg)
4679 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4680 (message "%s" (substitute-command-keys
4681 "Subtree is archived and stays closed. Use \
4682 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4684 (defun org-force-cycle-archived ()
4685 "Cycle subtree even if it is archived."
4686 (interactive)
4687 (setq this-command 'org-cycle)
4688 (let ((org-cycle-open-archived-trees t))
4689 (call-interactively 'org-cycle)))
4691 (defun org-hide-archived-subtrees (beg end)
4692 "Re-hide all archived subtrees after a visibility state change."
4693 (org-with-wide-buffer
4694 (let ((case-fold-search nil)
4695 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4696 (goto-char beg)
4697 ;; Include headline point is currently on.
4698 (beginning-of-line)
4699 (while (and (< (point) end) (re-search-forward re end t))
4700 (when (member org-archive-tag (org-get-tags nil t))
4701 (org-flag-subtree t)
4702 (org-end-of-subtree t))))))
4704 (defun org-flag-subtree (flag)
4705 (save-excursion
4706 (org-back-to-heading t)
4707 (org-flag-region (line-end-position)
4708 (progn (org-end-of-subtree t) (point))
4709 flag
4710 'outline)))
4712 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4714 ;; Declare Column View Code
4716 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4717 (declare-function org-columns-compute "org-colview" (property))
4719 ;; Declare ID code
4721 (declare-function org-id-store-link "org-id")
4722 (declare-function org-id-locations-load "org-id")
4723 (declare-function org-id-locations-save "org-id")
4724 (defvar org-id-track-globally)
4726 ;;; Variables for pre-computed regular expressions, all buffer local
4728 (defvar-local org-todo-regexp nil
4729 "Matches any of the TODO state keywords.
4730 Since TODO keywords are case-sensitive, `case-fold-search' is
4731 expected to be bound to nil when matching against this regexp.")
4733 (defvar-local org-not-done-regexp nil
4734 "Matches any of the TODO state keywords except the last one.
4735 Since TODO keywords are case-sensitive, `case-fold-search' is
4736 expected to be bound to nil when matching against this regexp.")
4738 (defvar-local org-not-done-heading-regexp nil
4739 "Matches a TODO headline that is not done.
4740 Since TODO keywords are case-sensitive, `case-fold-search' is
4741 expected to be bound to nil when matching against this regexp.")
4743 (defvar-local org-todo-line-regexp nil
4744 "Matches a headline and puts TODO state into group 2 if present.
4745 Since TODO keywords are case-sensitive, `case-fold-search' is
4746 expected to be bound to nil when matching against this regexp.")
4748 (defvar-local org-complex-heading-regexp nil
4749 "Matches a headline and puts everything into groups:
4751 group 1: Stars
4752 group 2: The TODO keyword, maybe
4753 group 3: Priority cookie
4754 group 4: True headline
4755 group 5: Tags
4757 Since TODO keywords are case-sensitive, `case-fold-search' is
4758 expected to be bound to nil when matching against this regexp.")
4760 (defvar-local org-complex-heading-regexp-format nil
4761 "Printf format to make regexp to match an exact headline.
4762 This regexp will match the headline of any node which has the
4763 exact headline text that is put into the format, but may have any
4764 TODO state, priority and tags.")
4766 (defvar-local org-todo-line-tags-regexp nil
4767 "Matches a headline and puts TODO state into group 2 if present.
4768 Also put tags into group 4 if tags are present.")
4770 (defconst org-plain-time-of-day-regexp
4771 (concat
4772 "\\(\\<[012]?[0-9]"
4773 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4774 "\\(--?"
4775 "\\(\\<[012]?[0-9]"
4776 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4777 "\\)?")
4778 "Regular expression to match a plain time or time range.
4779 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4780 groups carry important information:
4781 0 the full match
4782 1 the first time, range or not
4783 8 the second time, if it is a range.")
4785 (defconst org-plain-time-extension-regexp
4786 (concat
4787 "\\(\\<[012]?[0-9]"
4788 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4789 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4790 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4791 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4792 groups carry important information:
4793 0 the full match
4794 7 hours of duration
4795 9 minutes of duration")
4797 (defconst org-stamp-time-of-day-regexp
4798 (concat
4799 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4800 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4801 "\\(--?"
4802 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4803 "Regular expression to match a timestamp time or time range.
4804 After a match, the following groups carry important information:
4805 0 the full match
4806 1 date plus weekday, for back referencing to make sure both times are on the same day
4807 2 the first time, range or not
4808 4 the second time, if it is a range.")
4810 (defconst org-startup-options
4811 '(("fold" org-startup-folded t)
4812 ("overview" org-startup-folded t)
4813 ("nofold" org-startup-folded nil)
4814 ("showall" org-startup-folded nil)
4815 ("showeverything" org-startup-folded showeverything)
4816 ("content" org-startup-folded content)
4817 ("indent" org-startup-indented t)
4818 ("noindent" org-startup-indented nil)
4819 ("hidestars" org-hide-leading-stars t)
4820 ("showstars" org-hide-leading-stars nil)
4821 ("odd" org-odd-levels-only t)
4822 ("oddeven" org-odd-levels-only nil)
4823 ("align" org-startup-align-all-tables t)
4824 ("noalign" org-startup-align-all-tables nil)
4825 ("shrink" org-startup-shrink-all-tables t)
4826 ("inlineimages" org-startup-with-inline-images t)
4827 ("noinlineimages" org-startup-with-inline-images nil)
4828 ("latexpreview" org-startup-with-latex-preview t)
4829 ("nolatexpreview" org-startup-with-latex-preview nil)
4830 ("customtime" org-display-custom-times t)
4831 ("logdone" org-log-done time)
4832 ("lognotedone" org-log-done note)
4833 ("nologdone" org-log-done nil)
4834 ("lognoteclock-out" org-log-note-clock-out t)
4835 ("nolognoteclock-out" org-log-note-clock-out nil)
4836 ("logrepeat" org-log-repeat state)
4837 ("lognoterepeat" org-log-repeat note)
4838 ("logdrawer" org-log-into-drawer t)
4839 ("nologdrawer" org-log-into-drawer nil)
4840 ("logstatesreversed" org-log-states-order-reversed t)
4841 ("nologstatesreversed" org-log-states-order-reversed nil)
4842 ("nologrepeat" org-log-repeat nil)
4843 ("logreschedule" org-log-reschedule time)
4844 ("lognotereschedule" org-log-reschedule note)
4845 ("nologreschedule" org-log-reschedule nil)
4846 ("logredeadline" org-log-redeadline time)
4847 ("lognoteredeadline" org-log-redeadline note)
4848 ("nologredeadline" org-log-redeadline nil)
4849 ("logrefile" org-log-refile time)
4850 ("lognoterefile" org-log-refile note)
4851 ("nologrefile" org-log-refile nil)
4852 ("fninline" org-footnote-define-inline t)
4853 ("nofninline" org-footnote-define-inline nil)
4854 ("fnlocal" org-footnote-section nil)
4855 ("fnauto" org-footnote-auto-label t)
4856 ("fnprompt" org-footnote-auto-label nil)
4857 ("fnconfirm" org-footnote-auto-label confirm)
4858 ("fnplain" org-footnote-auto-label plain)
4859 ("fnadjust" org-footnote-auto-adjust t)
4860 ("nofnadjust" org-footnote-auto-adjust nil)
4861 ("constcgs" constants-unit-system cgs)
4862 ("constSI" constants-unit-system SI)
4863 ("noptag" org-tag-persistent-alist nil)
4864 ("hideblocks" org-hide-block-startup t)
4865 ("nohideblocks" org-hide-block-startup nil)
4866 ("beamer" org-startup-with-beamer-mode t)
4867 ("entitiespretty" org-pretty-entities t)
4868 ("entitiesplain" org-pretty-entities nil))
4869 "Variable associated with STARTUP options for Org.
4870 Each element is a list of three items: the startup options (as written
4871 in the #+STARTUP line), the corresponding variable, and the value to set
4872 this variable to if the option is found. An optional forth element PUSH
4873 means to push this value onto the list in the variable.")
4875 (defcustom org-group-tags t
4876 "When non-nil (the default), use group tags.
4877 This can be turned on/off through `org-toggle-tags-groups'."
4878 :group 'org-tags
4879 :group 'org-startup
4880 :type 'boolean)
4882 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4884 (defun org-toggle-tags-groups ()
4885 "Toggle support for group tags.
4886 Support for group tags is controlled by the option
4887 `org-group-tags', which is non-nil by default."
4888 (interactive)
4889 (setq org-group-tags (not org-group-tags))
4890 (cond ((and (derived-mode-p 'org-agenda-mode)
4891 org-group-tags)
4892 (org-agenda-redo))
4893 ((derived-mode-p 'org-mode)
4894 (let ((org-inhibit-startup t)) (org-mode))))
4895 (message "Groups tags support has been turned %s"
4896 (if org-group-tags "on" "off")))
4898 (defun org--tag-add-to-alist (alist1 alist2)
4899 "Merge tags from ALIST1 into ALIST2.
4901 Duplicates tags outside a group are removed. Keywords and order
4902 are preserved.
4904 The function assumes ALIST1 and ALIST2 are proper tag alists.
4905 See `org-tag-alist' for their structure."
4906 (cond
4907 ((null alist2) alist1)
4908 ((null alist1) alist2)
4910 (let ((to-add nil)
4911 (group-flag nil))
4912 (dolist (tag-pair alist1)
4913 (pcase tag-pair
4914 (`(,(or :startgrouptag :startgroup))
4915 (setq group-flag t)
4916 (push tag-pair to-add))
4917 (`(,(or :endgrouptag :endgroup))
4918 (setq group-flag nil)
4919 (push tag-pair to-add))
4920 (`(,(or :grouptags :newline))
4921 (push tag-pair to-add))
4922 (`(,tag . ,_)
4923 ;; Remove duplicates from ALIST1, unless they are in
4924 ;; a group. Indeed, it makes sense to have a tag appear in
4925 ;; multiple groups.
4926 (when (or group-flag (not (assoc tag alist2)))
4927 (push tag-pair to-add)))
4928 (_ (error "Invalid association in tag alist: %S" tag-pair))))
4929 ;; Preserve order of ALIST1.
4930 (append (nreverse to-add) alist2)))))
4932 (defun org-set-regexps-and-options (&optional tags-only)
4933 "Precompute regular expressions used in the current buffer.
4934 When optional argument TAGS-ONLY is non-nil, only compute tags
4935 related expressions."
4936 (when (derived-mode-p 'org-mode)
4937 (let ((alist (org--setup-collect-keywords
4938 (org-make-options-regexp
4939 (append '("FILETAGS" "TAGS" "SETUPFILE")
4940 (and (not tags-only)
4941 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4942 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4943 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4944 ;; Startup options. Get this early since it does change
4945 ;; behavior for other options (e.g., tags).
4946 (let ((startup (cdr (assq 'startup alist))))
4947 (dolist (option startup)
4948 (let ((entry (assoc-string option org-startup-options t)))
4949 (when entry
4950 (let ((var (nth 1 entry))
4951 (val (nth 2 entry)))
4952 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4953 (unless (listp (symbol-value var))
4954 (set (make-local-variable var) nil))
4955 (add-to-list var val)))))))
4956 (setq-local org-file-tags
4957 (mapcar #'org-add-prop-inherited
4958 (cdr (assq 'filetags alist))))
4959 (setq org-current-tag-alist
4960 (org--tag-add-to-alist
4961 org-tag-persistent-alist
4962 (let ((tags (cdr (assq 'tags alist))))
4963 (if tags (org-tag-string-to-alist tags)
4964 org-tag-alist))))
4965 (setq org-tag-groups-alist
4966 (org-tag-alist-to-groups org-current-tag-alist))
4967 (unless tags-only
4968 ;; File properties.
4969 (setq-local org-file-properties (cdr (assq 'property alist)))
4970 ;; Archive location.
4971 (let ((archive (cdr (assq 'archive alist))))
4972 (when archive (setq-local org-archive-location archive)))
4973 ;; Category.
4974 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4975 (when cat
4976 (setq-local org-category (intern cat))
4977 (setq-local org-file-properties
4978 (org--update-property-plist
4979 "CATEGORY" cat org-file-properties))))
4980 ;; Columns.
4981 (let ((column (cdr (assq 'columns alist))))
4982 (when column (setq-local org-columns-default-format column)))
4983 ;; Constants.
4984 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4985 ;; Link abbreviations.
4986 (let ((links (cdr (assq 'link alist))))
4987 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4988 ;; Priorities.
4989 (let ((priorities (cdr (assq 'priorities alist))))
4990 (when priorities
4991 (setq-local org-highest-priority (nth 0 priorities))
4992 (setq-local org-lowest-priority (nth 1 priorities))
4993 (setq-local org-default-priority (nth 2 priorities))))
4994 ;; Scripts.
4995 (let ((scripts (assq 'scripts alist)))
4996 (when scripts
4997 (setq-local org-use-sub-superscripts (cdr scripts))))
4998 ;; TODO keywords.
4999 (setq-local org-todo-kwd-alist nil)
5000 (setq-local org-todo-key-alist nil)
5001 (setq-local org-todo-key-trigger nil)
5002 (setq-local org-todo-keywords-1 nil)
5003 (setq-local org-done-keywords nil)
5004 (setq-local org-todo-heads nil)
5005 (setq-local org-todo-sets nil)
5006 (setq-local org-todo-log-states nil)
5007 (let ((todo-sequences
5008 (or (nreverse (cdr (assq 'todo alist)))
5009 (let ((d (default-value 'org-todo-keywords)))
5010 (if (not (stringp (car d))) d
5011 ;; XXX: Backward compatibility code.
5012 (list (cons org-todo-interpretation d)))))))
5013 (dolist (sequence todo-sequences)
5014 (let* ((sequence (or (run-hook-with-args-until-success
5015 'org-todo-setup-filter-hook sequence)
5016 sequence))
5017 (sequence-type (car sequence))
5018 (keywords (cdr sequence))
5019 (sep (member "|" keywords))
5020 names alist)
5021 (dolist (k (remove "|" keywords))
5022 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5024 (error "Invalid TODO keyword %s" k))
5025 (let ((name (match-string 1 k))
5026 (key (match-string 2 k))
5027 (log (org-extract-log-state-settings k)))
5028 (push name names)
5029 (push (cons name (and key (string-to-char key))) alist)
5030 (when log (push log org-todo-log-states))))
5031 (let* ((names (nreverse names))
5032 (done (if sep (org-remove-keyword-keys (cdr sep))
5033 (last names)))
5034 (head (car names))
5035 (tail (list sequence-type head (car done) (org-last done))))
5036 (add-to-list 'org-todo-heads head 'append)
5037 (push names org-todo-sets)
5038 (setq org-done-keywords (append org-done-keywords done nil))
5039 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5040 (setq org-todo-key-alist
5041 (append org-todo-key-alist
5042 (and alist
5043 (append '((:startgroup))
5044 (nreverse alist)
5045 '((:endgroup))))))
5046 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5047 (setq org-todo-sets (nreverse org-todo-sets)
5048 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5049 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5050 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5051 ;; Compute the regular expressions and other local variables.
5052 ;; Using `org-outline-regexp-bol' would complicate them much,
5053 ;; because of the fixed white space at the end of that string.
5054 (unless org-done-keywords
5055 (setq org-done-keywords
5056 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5057 (setq org-not-done-keywords
5058 (org-delete-all org-done-keywords
5059 (copy-sequence org-todo-keywords-1))
5060 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5061 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5062 org-not-done-heading-regexp
5063 (format org-heading-keyword-regexp-format org-not-done-regexp)
5064 org-todo-line-regexp
5065 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5066 org-complex-heading-regexp
5067 (concat "^\\(\\*+\\)"
5068 "\\(?: +" org-todo-regexp "\\)?"
5069 "\\(?: +\\(\\[#.\\]\\)\\)?"
5070 "\\(?: +\\(.*?\\)\\)??"
5071 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5072 "[ \t]*$")
5073 org-complex-heading-regexp-format
5074 (concat "^\\(\\*+\\)"
5075 "\\(?: +" org-todo-regexp "\\)?"
5076 "\\(?: +\\(\\[#.\\]\\)\\)?"
5077 "\\(?: +"
5078 ;; Stats cookies can be stuck to body.
5079 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5080 "\\(%s\\)"
5081 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5082 "\\)"
5083 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5084 "[ \t]*$")
5085 org-todo-line-tags-regexp
5086 (concat "^\\(\\*+\\)"
5087 "\\(?: +" org-todo-regexp "\\)?"
5088 "\\(?: +\\(.*?\\)\\)??"
5089 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5090 "[ \t]*$"))
5091 (org-compute-latex-and-related-regexp)))))
5093 (defun org--setup-collect-keywords (regexp &optional files alist)
5094 "Return setup keywords values as an alist.
5096 REGEXP matches a subset of setup keywords. FILES is a list of
5097 file names already visited. It is used to avoid circular setup
5098 files. ALIST, when non-nil, is the alist computed so far.
5100 Return value contains the following keys: `archive', `category',
5101 `columns', `constants', `filetags', `link', `priorities',
5102 `property', `scripts', `startup', `tags' and `todo'."
5103 (org-with-wide-buffer
5104 (goto-char (point-min))
5105 (let ((case-fold-search t))
5106 (while (re-search-forward regexp nil t)
5107 (let ((element (org-element-at-point)))
5108 (when (eq (org-element-type element) 'keyword)
5109 (let ((key (org-element-property :key element))
5110 (value (org-element-property :value element)))
5111 (cond
5112 ((equal key "ARCHIVE")
5113 (when (org-string-nw-p value)
5114 (push (cons 'archive value) alist)))
5115 ((equal key "CATEGORY") (push (cons 'category value) alist))
5116 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5117 ((equal key "CONSTANTS")
5118 (let* ((constants (assq 'constants alist))
5119 (store (cdr constants)))
5120 (dolist (pair (split-string value))
5121 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5122 pair)
5123 (let* ((name (match-string 1 pair))
5124 (value (match-string 2 pair))
5125 (old (assoc name store)))
5126 (if old (setcdr old value)
5127 (push (cons name value) store)))))
5128 (if constants (setcdr constants store)
5129 (push (cons 'constants store) alist))))
5130 ((equal key "FILETAGS")
5131 (when (org-string-nw-p value)
5132 (let ((old (assq 'filetags alist))
5133 (new (apply #'nconc
5134 (mapcar (lambda (x) (org-split-string x ":"))
5135 (split-string value)))))
5136 (if old (setcdr old (append new (cdr old)))
5137 (push (cons 'filetags new) alist)))))
5138 ((equal key "LINK")
5139 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5140 (let ((links (assq 'link alist))
5141 (pair (cons (match-string-no-properties 1 value)
5142 (match-string-no-properties 2 value))))
5143 (if links (push pair (cdr links))
5144 (push (list 'link pair) alist)))))
5145 ((equal key "OPTIONS")
5146 (when (and (org-string-nw-p value)
5147 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5148 (push (cons 'scripts (read (match-string 1 value))) alist)))
5149 ((equal key "PRIORITIES")
5150 (push (cons 'priorities
5151 (let ((prio (split-string value)))
5152 (if (< (length prio) 3) '(?A ?C ?B)
5153 (mapcar #'string-to-char prio))))
5154 alist))
5155 ((equal key "PROPERTY")
5156 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5157 (let* ((property (assq 'property alist))
5158 (value (org--update-property-plist
5159 (match-string-no-properties 1 value)
5160 (match-string-no-properties 2 value)
5161 (cdr property))))
5162 (if property (setcdr property value)
5163 (push (cons 'property value) alist)))))
5164 ((equal key "STARTUP")
5165 (let ((startup (assq 'startup alist)))
5166 (if startup
5167 (setcdr startup
5168 (append (cdr startup) (split-string value)))
5169 (push (cons 'startup (split-string value)) alist))))
5170 ((equal key "TAGS")
5171 (let ((tag-cell (assq 'tags alist)))
5172 (if tag-cell
5173 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5174 (push (cons 'tags value) alist))))
5175 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5176 (let ((todo (assq 'todo alist))
5177 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5178 (split-string value))))
5179 (if todo (push value (cdr todo))
5180 (push (list 'todo value) alist))))
5181 ((equal key "SETUPFILE")
5182 (unless buffer-read-only ; Do not check in Gnus messages.
5183 (let ((f (and (org-string-nw-p value)
5184 (expand-file-name (org-strip-quotes value)))))
5185 (when (and f (file-readable-p f) (not (member f files)))
5186 (with-temp-buffer
5187 (setq default-directory (file-name-directory f))
5188 (insert-file-contents f)
5189 (setq alist
5190 ;; Fake Org mode to benefit from cache
5191 ;; without recurring needlessly.
5192 (let ((major-mode 'org-mode))
5193 (org--setup-collect-keywords
5194 regexp (cons f files) alist)))))))))))))))
5195 alist)
5197 (defun org-tag-string-to-alist (s)
5198 "Return tag alist associated to string S.
5199 S is a value for TAGS keyword or produced with
5200 `org-tag-alist-to-string'. Return value is an alist suitable for
5201 `org-tag-alist' or `org-tag-persistent-alist'."
5202 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5203 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5204 "\\(?:(\\(.\\))\\)?\\'"))
5205 alist group-flag)
5206 (dolist (tokens lines (cdr (nreverse alist)))
5207 (push '(:newline) alist)
5208 (while tokens
5209 (let ((token (pop tokens)))
5210 (pcase token
5211 ("{"
5212 (push '(:startgroup) alist)
5213 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5214 ("}"
5215 (push '(:endgroup) alist)
5216 (setq group-flag nil))
5217 ("["
5218 (push '(:startgrouptag) alist)
5219 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5220 ("]"
5221 (push '(:endgrouptag) alist)
5222 (setq group-flag nil))
5223 (":"
5224 (push '(:grouptags) alist))
5225 ((guard (string-match tag-re token))
5226 (let ((tag (match-string 1 token))
5227 (key (and (match-beginning 2)
5228 (string-to-char (match-string 2 token)))))
5229 ;; Push all tags in groups, no matter if they already
5230 ;; appear somewhere else in the list.
5231 (when (or group-flag (not (assoc tag alist)))
5232 (push (cons tag key) alist))))))))))
5234 (defun org-tag-alist-to-string (alist &optional skip-key)
5235 "Return tag string associated to ALIST.
5237 ALIST is an alist, as defined in `org-tag-alist' or
5238 `org-tag-persistent-alist', or produced with
5239 `org-tag-string-to-alist'.
5241 Return value is a string suitable as a value for \"TAGS\"
5242 keyword.
5244 When optional argument SKIP-KEY is non-nil, skip selection keys
5245 next to tags."
5246 (mapconcat (lambda (token)
5247 (pcase token
5248 (`(:startgroup) "{")
5249 (`(:endgroup) "}")
5250 (`(:startgrouptag) "[")
5251 (`(:endgrouptag) "]")
5252 (`(:grouptags) ":")
5253 (`(:newline) "\\n")
5254 ((and
5255 (guard (not skip-key))
5256 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5257 (format "%s(%c)" tag key))
5258 (`(,(and tag (pred stringp)) . ,_) tag)
5259 (_ (user-error "Invalid tag token: %S" token))))
5260 alist
5261 " "))
5263 (defun org-tag-alist-to-groups (alist)
5264 "Return group alist from tag ALIST.
5265 ALIST is an alist, as defined in `org-tag-alist' or
5266 `org-tag-persistent-alist', or produced with
5267 `org-tag-string-to-alist'. Return value is an alist following
5268 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5269 a string, summarizing TAGS, as a list of strings."
5270 (let (groups group-status current-group)
5271 (dolist (token alist (nreverse groups))
5272 (pcase token
5273 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5274 (`(,(or :endgroup :endgrouptag))
5275 (when (eq group-status 'append)
5276 (push (nreverse current-group) groups))
5277 (setq group-status nil current-group nil))
5278 (`(:grouptags) (setq group-status 'append))
5279 ((and `(,tag . ,_) (guard group-status))
5280 (if (eq group-status 'append) (push tag current-group)
5281 (setq current-group (list tag))))
5282 (_ nil)))))
5284 (defvar org--file-cache (make-hash-table :test #'equal)
5285 "Hash table to store contents of files referenced via a URL.
5286 This is the cache of file URLs read using `org-file-contents'.")
5288 (defun org-reset-file-cache ()
5289 "Reset the cache of files downloaded by `org-file-contents'."
5290 (clrhash org--file-cache))
5292 (defun org-file-url-p (file)
5293 "Non-nil if FILE is a URL."
5294 (require 'ffap)
5295 (string-match-p ffap-url-regexp file))
5297 (defun org-file-contents (file &optional noerror nocache)
5298 "Return the contents of FILE, as a string.
5300 FILE can be a file name or URL.
5302 If FILE is a URL, download the contents. If the URL contents are
5303 already cached in the `org--file-cache' hash table, the download step
5304 is skipped.
5306 If NOERROR is non-nil, ignore the error when unable to read the FILE
5307 from file or URL.
5309 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5310 is available. This option applies only if FILE is a URL."
5311 (let* ((is-url (org-file-url-p file))
5312 (cache (and is-url
5313 (not nocache)
5314 (gethash file org--file-cache))))
5315 (cond
5316 (cache)
5317 (is-url
5318 (with-current-buffer (url-retrieve-synchronously file)
5319 (goto-char (point-min))
5320 ;; Move point to after the url-retrieve header.
5321 (search-forward "\n\n" nil :move)
5322 ;; Search for the success code only in the url-retrieve header.
5323 (if (save-excursion
5324 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5325 ;; Update the cache `org--file-cache' and return contents.
5326 (puthash file
5327 (buffer-substring-no-properties (point) (point-max))
5328 org--file-cache)
5329 (funcall (if noerror #'message #'user-error)
5330 "Unable to fetch file from %S"
5331 file))))
5333 (with-temp-buffer
5334 (condition-case nil
5335 (progn
5336 (insert-file-contents file)
5337 (buffer-string))
5338 (file-error
5339 (funcall (if noerror #'message #'user-error)
5340 "Unable to read file %S"
5341 file))))))))
5343 (defun org-extract-log-state-settings (x)
5344 "Extract the log state setting from a TODO keyword string.
5345 This will extract info from a string like \"WAIT(w@/!)\"."
5346 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5347 (let ((kw (match-string 1 x))
5348 (log1 (and (match-end 3) (match-string 3 x)))
5349 (log2 (and (match-end 4) (match-string 4 x))))
5350 (and (or log1 log2)
5351 (list kw
5352 (and log1 (if (equal log1 "!") 'time 'note))
5353 (and log2 (if (equal log2 "!") 'time 'note)))))))
5355 (defun org-remove-keyword-keys (list)
5356 "Remove a pair of parenthesis at the end of each string in LIST."
5357 (mapcar (lambda (x)
5358 (if (string-match "(.*)$" x)
5359 (substring x 0 (match-beginning 0))
5361 list))
5363 (defun org-assign-fast-keys (alist)
5364 "Assign fast keys to a keyword-key alist.
5365 Respect keys that are already there."
5366 (let (new e (alt ?0))
5367 (while (setq e (pop alist))
5368 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5369 (cdr e)) ;; Key already assigned.
5370 (push e new)
5371 (let ((clist (string-to-list (downcase (car e))))
5372 (used (append new alist)))
5373 (when (= (car clist) ?@)
5374 (pop clist))
5375 (while (and clist (rassoc (car clist) used))
5376 (pop clist))
5377 (unless clist
5378 (while (rassoc alt used)
5379 (cl-incf alt)))
5380 (push (cons (car e) (or (car clist) alt)) new))))
5381 (nreverse new)))
5383 ;;; Some variables used in various places
5385 (defvar org-window-configuration nil
5386 "Used in various places to store a window configuration.")
5387 (defvar org-selected-window nil
5388 "Used in various places to store a window configuration.")
5389 (defvar org-finish-function nil
5390 "Function to be called when `C-c C-c' is used.
5391 This is for getting out of special buffers like capture.")
5392 (defvar org-last-state)
5394 ;; Defined somewhere in this file, but used before definition.
5395 (defvar org-entities) ;; defined in org-entities.el
5396 (defvar org-struct-menu)
5397 (defvar org-org-menu)
5398 (defvar org-tbl-menu)
5400 ;;;; Define the Org mode
5402 ;; We use a before-change function to check if a table might need
5403 ;; an update.
5404 (defvar org-table-may-need-update t
5405 "Indicates that a table might need an update.
5406 This variable is set by `org-before-change-function'.
5407 `org-table-align' sets it back to nil.")
5408 (defun org-before-change-function (_beg _end)
5409 "Every change indicates that a table might need an update."
5410 (setq org-table-may-need-update t))
5411 (defvar org-mode-map)
5412 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5413 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5414 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5415 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5416 (defvar org-table-buffer-is-an nil)
5418 (defvar bidi-paragraph-direction)
5419 (defvar buffer-face-mode-face)
5421 (require 'outline)
5423 ;; Other stuff we need.
5424 (require 'time-date)
5425 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5426 (require 'easymenu)
5427 (autoload 'easy-menu-add "easymenu")
5428 (require 'overlay)
5430 ;; (require 'org-macs) moved higher up in the file before it is first used
5431 (require 'org-entities)
5432 ;; (require 'org-compat) moved higher up in the file before it is first used
5433 (require 'org-faces)
5434 (require 'org-list)
5435 (require 'org-pcomplete)
5436 (require 'org-src)
5437 (require 'org-footnote)
5438 (require 'org-macro)
5440 ;; babel
5441 (require 'ob)
5443 ;;;###autoload
5444 (define-derived-mode org-mode outline-mode "Org"
5445 "Outline-based notes management and organizer, alias
5446 \"Carsten's outline-mode for keeping track of everything.\"
5448 Org mode develops organizational tasks around a NOTES file which
5449 contains information about projects as plain text. Org mode is
5450 implemented on top of Outline mode, which is ideal to keep the content
5451 of large files well structured. It supports ToDo items, deadlines and
5452 time stamps, which magically appear in the diary listing of the Emacs
5453 calendar. Tables are easily created with a built-in table editor.
5454 Plain text URL-like links connect to websites, emails (VM), Usenet
5455 messages (Gnus), BBDB entries, and any files related to the project.
5456 For printing and sharing of notes, an Org file (or a part of it)
5457 can be exported as a structured ASCII or HTML file.
5459 The following commands are available:
5461 \\{org-mode-map}"
5463 ;; Get rid of Outline menus, they are not needed
5464 ;; Need to do this here because define-derived-mode sets up
5465 ;; the keymap so late. Still, it is a waste to call this each time
5466 ;; we switch another buffer into Org mode.
5467 (define-key org-mode-map [menu-bar headings] 'undefined)
5468 (define-key org-mode-map [menu-bar hide] 'undefined)
5469 (define-key org-mode-map [menu-bar show] 'undefined)
5471 (org-load-modules-maybe)
5472 (org-install-agenda-files-menu)
5473 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5474 (add-to-invisibility-spec '(org-hide-block . t))
5475 (add-to-invisibility-spec '(org-hide-drawer . t))
5476 (setq-local outline-regexp org-outline-regexp)
5477 (setq-local outline-level 'org-outline-level)
5478 (setq bidi-paragraph-direction 'left-to-right)
5479 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5480 (unless org-display-table
5481 (setq org-display-table (make-display-table)))
5482 (set-display-table-slot
5483 org-display-table 4
5484 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5485 org-ellipsis)))
5486 (setq buffer-display-table org-display-table))
5487 (org-set-regexps-and-options)
5488 (org-set-font-lock-defaults)
5489 (when (and org-tag-faces (not org-tags-special-faces-re))
5490 ;; tag faces set outside customize.... force initialization.
5491 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5492 ;; Calc embedded
5493 (setq-local calc-embedded-open-mode "# ")
5494 ;; Modify a few syntax entries
5495 (modify-syntax-entry ?\" "\"")
5496 (modify-syntax-entry ?\\ "_")
5497 (modify-syntax-entry ?~ "_")
5498 (modify-syntax-entry ?< "(>")
5499 (modify-syntax-entry ?> ")<")
5500 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5501 ;; Activate before-change-function
5502 (setq-local org-table-may-need-update t)
5503 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5504 ;; Check for running clock before killing a buffer
5505 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5506 ;; Initialize macros templates.
5507 (org-macro-initialize-templates)
5508 ;; Initialize radio targets.
5509 (org-update-radio-target-regexp)
5510 ;; Indentation.
5511 (setq-local indent-line-function 'org-indent-line)
5512 (setq-local indent-region-function 'org-indent-region)
5513 ;; Filling and auto-filling.
5514 (org-setup-filling)
5515 ;; Comments.
5516 (org-setup-comments-handling)
5517 ;; Initialize cache.
5518 (org-element-cache-reset)
5519 ;; Beginning/end of defun
5520 (setq-local beginning-of-defun-function 'org-backward-element)
5521 (setq-local end-of-defun-function
5522 (lambda ()
5523 (if (not (org-at-heading-p))
5524 (org-forward-element)
5525 (org-forward-element)
5526 (forward-char -1))))
5527 ;; Next error for sparse trees
5528 (setq-local next-error-function 'org-occur-next-match)
5529 ;; Make commit log messages from Org documents easier.
5530 (setq-local add-log-current-defun-function #'org-add-log-current-headline)
5531 ;; Make sure dependence stuff works reliably, even for users who set it
5532 ;; too late :-(
5533 (if org-enforce-todo-dependencies
5534 (add-hook 'org-blocker-hook
5535 'org-block-todo-from-children-or-siblings-or-parent)
5536 (remove-hook 'org-blocker-hook
5537 'org-block-todo-from-children-or-siblings-or-parent))
5538 (if org-enforce-todo-checkbox-dependencies
5539 (add-hook 'org-blocker-hook
5540 'org-block-todo-from-checkboxes)
5541 (remove-hook 'org-blocker-hook
5542 'org-block-todo-from-checkboxes))
5544 ;; Align options lines
5545 (setq-local
5546 align-mode-rules-list
5547 '((org-in-buffer-settings
5548 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5549 (modes . '(org-mode)))))
5551 ;; Make isearch reveal context
5552 (setq-local outline-isearch-open-invisible-function
5553 (lambda (&rest _) (org-show-context 'isearch)))
5555 ;; Setup the pcomplete hooks
5556 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5557 (setq-local pcomplete-command-name-function 'org-command-at-point)
5558 (setq-local pcomplete-default-completion-function 'ignore)
5559 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5560 (setq-local pcomplete-termination-string "")
5561 (setq-local buffer-face-mode-face 'org-default)
5563 ;; If empty file that did not turn on Org mode automatically, make
5564 ;; it to.
5565 (when (and org-insert-mode-line-in-empty-file
5566 (called-interactively-p 'any)
5567 (= (point-min) (point-max)))
5568 (insert "# -*- mode: org -*-\n\n"))
5569 (unless org-inhibit-startup
5570 (org-unmodified
5571 (when org-startup-with-beamer-mode (org-beamer-mode))
5572 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5573 (org-table-map-tables
5574 (cond ((and org-startup-align-all-tables
5575 org-startup-shrink-all-tables)
5576 (lambda () (org-table-align) (org-table-shrink)))
5577 (org-startup-align-all-tables #'org-table-align)
5578 (t #'org-table-shrink))
5580 (when org-startup-with-inline-images (org-display-inline-images))
5581 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5582 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5583 (when org-startup-truncated (setq truncate-lines t))
5584 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5585 (org-refresh-effort-properties)))
5586 ;; Try to set `org-hide' face correctly.
5587 (let ((foreground (org-find-invisible-foreground)))
5588 (when foreground
5589 (set-face-foreground 'org-hide foreground))))
5591 ;; Update `customize-package-emacs-version-alist'
5592 (add-to-list 'customize-package-emacs-version-alist
5593 '(Org ("8.0" . "24.4")
5594 ("8.1" . "24.4")
5595 ("8.2" . "24.4")
5596 ("8.2.7" . "24.4")
5597 ("8.3" . "26.1")
5598 ("9.0" . "26.1")
5599 ("9.1" . "26.1")
5600 ("9.2" . "27.1")))
5602 (defvar org-mode-transpose-word-syntax-table
5603 (let ((st (make-syntax-table text-mode-syntax-table)))
5604 (dolist (c org-emphasis-alist st)
5605 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5607 (when (fboundp 'abbrev-table-put)
5608 (abbrev-table-put org-mode-abbrev-table
5609 :parents (list text-mode-abbrev-table)))
5611 (defun org-find-invisible-foreground ()
5612 (let ((candidates (remove
5613 "unspecified-bg"
5614 (nconc
5615 (list (face-background 'default)
5616 (face-background 'org-default))
5617 (mapcar
5618 (lambda (alist)
5619 (when (boundp alist)
5620 (cdr (assq 'background-color (symbol-value alist)))))
5621 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5622 (list (face-foreground 'org-hide))))))
5623 (car (remove nil candidates))))
5625 (defun org-current-time (&optional rounding-minutes past)
5626 "Current time, possibly rounded to ROUNDING-MINUTES.
5627 When ROUNDING-MINUTES is not an integer, fall back on the car of
5628 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5629 the rounding returns a past time."
5630 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5631 (car org-time-stamp-rounding-minutes)))
5632 (time (decode-time)) res)
5633 (if (< r 1)
5634 (current-time)
5635 (setq res
5636 (apply 'encode-time
5637 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5638 (nthcdr 2 time))))
5639 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5640 (seconds-to-time (- (float-time res) (* r 60)))
5641 res))))
5643 (defun org-today ()
5644 "Return today date, considering `org-extend-today-until'."
5645 (time-to-days
5646 (time-subtract (current-time)
5647 (list 0 (* 3600 org-extend-today-until) 0))))
5649 ;;;; Font-Lock stuff, including the activators
5651 (defvar org-mouse-map (make-sparse-keymap))
5652 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5653 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5654 (when org-mouse-1-follows-link
5655 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5656 (when org-tab-follows-link
5657 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5658 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5660 (require 'font-lock)
5662 (defconst org-non-link-chars "]\t\n\r<>")
5663 (defvar org-link-types-re nil
5664 "Matches a link that has a url-like prefix like \"http:\"")
5665 (defvar org-link-re-with-space nil
5666 "Matches a link with spaces, optional angular brackets around it.")
5667 (defvar org-link-re-with-space2 nil
5668 "Matches a link with spaces, optional angular brackets around it.")
5669 (defvar org-link-re-with-space3 nil
5670 "Matches a link with spaces, only for internal part in bracket links.")
5671 (defvar org-angle-link-re nil
5672 "Matches link with angular brackets, spaces are allowed.")
5673 (defvar org-plain-link-re nil
5674 "Matches plain link, without spaces.")
5675 (defvar org-bracket-link-regexp nil
5676 "Matches a link in double brackets.")
5677 (defvar org-bracket-link-analytic-regexp nil
5678 "Regular expression used to analyze links.
5679 Here is what the match groups contain after a match:
5680 1: http:
5681 2: http
5682 3: path
5683 4: [desc]
5684 5: desc")
5685 (defvar org-bracket-link-analytic-regexp++ nil
5686 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5687 (defvar org-any-link-re nil
5688 "Regular expression matching any link.")
5690 (defconst org-match-sexp-depth 3
5691 "Number of stacked braces for sub/superscript matching.")
5693 (defun org-create-multibrace-regexp (left right n)
5694 "Create a regular expression which will match a balanced sexp.
5695 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5696 as single character strings.
5697 The regexp returned will match the entire expression including the
5698 delimiters. It will also define a single group which contains the
5699 match except for the outermost delimiters. The maximum depth of
5700 stacked delimiters is N. Escaping delimiters is not possible."
5701 (let* ((nothing (concat "[^" left right "]*?"))
5702 (or "\\|")
5703 (re nothing)
5704 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5705 (while (> n 1)
5706 (setq n (1- n)
5707 re (concat re or next)
5708 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5709 (concat left "\\(" re "\\)" right)))
5711 (defconst org-match-substring-regexp
5712 (concat
5713 "\\(\\S-\\)\\([_^]\\)\\("
5714 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5715 "\\|"
5716 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5717 "\\|"
5718 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5719 "The regular expression matching a sub- or superscript.")
5721 (defconst org-match-substring-with-braces-regexp
5722 (concat
5723 "\\(\\S-\\)\\([_^]\\)"
5724 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5725 "The regular expression matching a sub- or superscript, forcing braces.")
5727 (defun org-make-link-regexps ()
5728 "Update the link regular expressions.
5729 This should be called after the variable `org-link-parameters' has changed."
5730 (let ((types-re (regexp-opt (org-link-types) t)))
5731 (setq org-link-types-re
5732 (concat "\\`" types-re ":")
5733 org-link-re-with-space
5734 (concat "<?" types-re ":"
5735 "\\([^" org-non-link-chars " ]"
5736 "[^" org-non-link-chars "]*"
5737 "[^" org-non-link-chars " ]\\)>?")
5738 org-link-re-with-space2
5739 (concat "<?" types-re ":"
5740 "\\([^" org-non-link-chars " ]"
5741 "[^\t\n\r]*"
5742 "[^" org-non-link-chars " ]\\)>?")
5743 org-link-re-with-space3
5744 (concat "<?" types-re ":"
5745 "\\([^" org-non-link-chars " ]"
5746 "[^\t\n\r]*\\)")
5747 org-angle-link-re
5748 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5749 types-re)
5750 org-plain-link-re
5751 (concat
5752 "\\<" types-re ":"
5753 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5754 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5755 org-bracket-link-regexp
5756 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5757 org-bracket-link-analytic-regexp
5758 (concat
5759 "\\[\\["
5760 "\\(" types-re ":\\)?"
5761 "\\([^]]+\\)"
5762 "\\]"
5763 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5764 "\\]")
5765 org-bracket-link-analytic-regexp++
5766 (concat
5767 "\\[\\["
5768 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5769 "\\([^]]+\\)"
5770 "\\]"
5771 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5772 "\\]")
5773 org-any-link-re
5774 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5775 org-angle-link-re "\\)\\|\\("
5776 org-plain-link-re "\\)"))))
5778 (org-make-link-regexps)
5780 (defvar org-emph-face nil)
5782 (defun org-do-emphasis-faces (limit)
5783 "Run through the buffer and emphasize strings."
5784 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5785 (car org-emphasis-regexp-components))))
5786 (catch :exit
5787 (while (re-search-forward quick-re limit t)
5788 (let* ((marker (match-string 2))
5789 (verbatim? (member marker '("~" "="))))
5790 (when (save-excursion
5791 (goto-char (match-beginning 0))
5792 (and
5793 ;; Do not match table hlines.
5794 (not (and (equal marker "+")
5795 (org-match-line
5796 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5797 ;; Do not match headline stars. Do not consider
5798 ;; stars of a headline as closing marker for bold
5799 ;; markup either.
5800 (not (and (equal marker "*")
5801 (save-excursion
5802 (forward-char)
5803 (skip-chars-backward "*")
5804 (looking-at-p org-outline-regexp-bol))))
5805 ;; Match full emphasis markup regexp.
5806 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5807 ;; Do not span over paragraph boundaries.
5808 (not (string-match-p org-element-paragraph-separate
5809 (match-string 2)))
5810 ;; Do not span over cells in table rows.
5811 (not (and (save-match-data (org-match-line "[ \t]*|"))
5812 (string-match-p "|" (match-string 4))))))
5813 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5814 (font-lock-prepend-text-property
5815 (match-beginning 2) (match-end 2) 'face face)
5816 (when verbatim?
5817 (org-remove-flyspell-overlays-in
5818 (match-beginning 0) (match-end 0))
5819 (remove-text-properties (match-beginning 2) (match-end 2)
5820 '(display t invisible t intangible t)))
5821 (add-text-properties (match-beginning 2) (match-end 2)
5822 '(font-lock-multiline t org-emphasis t))
5823 (when org-hide-emphasis-markers
5824 (add-text-properties (match-end 4) (match-beginning 5)
5825 '(invisible org-link))
5826 (add-text-properties (match-beginning 3) (match-end 3)
5827 '(invisible org-link)))
5828 (throw :exit t))))))))
5830 (defun org-emphasize (&optional char)
5831 "Insert or change an emphasis, i.e. a font like bold or italic.
5832 If there is an active region, change that region to a new emphasis.
5833 If there is no region, just insert the marker characters and position
5834 the cursor between them.
5835 CHAR should be the marker character. If it is a space, it means to
5836 remove the emphasis of the selected region.
5837 If CHAR is not given (for example in an interactive call) it will be
5838 prompted for."
5839 (interactive)
5840 (let ((erc org-emphasis-regexp-components)
5841 (string "") beg end move s)
5842 (if (org-region-active-p)
5843 (setq beg (region-beginning)
5844 end (region-end)
5845 string (buffer-substring beg end))
5846 (setq move t))
5848 (unless char
5849 (message "Emphasis marker or tag: [%s]"
5850 (mapconcat #'car org-emphasis-alist ""))
5851 (setq char (read-char-exclusive)))
5852 (if (equal char ?\s)
5853 (setq s ""
5854 move nil)
5855 (unless (assoc (char-to-string char) org-emphasis-alist)
5856 (user-error "No such emphasis marker: \"%c\"" char))
5857 (setq s (char-to-string char)))
5858 (while (and (> (length string) 1)
5859 (equal (substring string 0 1) (substring string -1))
5860 (assoc (substring string 0 1) org-emphasis-alist))
5861 (setq string (substring string 1 -1)))
5862 (setq string (concat s string s))
5863 (when beg (delete-region beg end))
5864 (unless (or (bolp)
5865 (string-match (concat "[" (nth 0 erc) "\n]")
5866 (char-to-string (char-before (point)))))
5867 (insert " "))
5868 (unless (or (eobp)
5869 (string-match (concat "[" (nth 1 erc) "\n]")
5870 (char-to-string (char-after (point)))))
5871 (insert " ") (backward-char 1))
5872 (insert string)
5873 (and move (backward-char 1))))
5875 (defconst org-nonsticky-props
5876 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5878 (defsubst org-rear-nonsticky-at (pos)
5879 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5881 (defun org-activate-links (limit)
5882 "Add link properties to links.
5883 This includes angle, plain, and bracket links."
5884 (catch :exit
5885 (while (re-search-forward org-any-link-re limit t)
5886 (let* ((start (match-beginning 0))
5887 (end (match-end 0))
5888 (style (cond ((eq ?< (char-after start)) 'angle)
5889 ((eq ?\[ (char-after (1+ start))) 'bracket)
5890 (t 'plain))))
5891 (when (and (memq style org-highlight-links)
5892 ;; Do not confuse plain links with tags.
5893 (not (and (eq style 'plain)
5894 (let ((face (get-text-property
5895 (max (1- start) (point-min)) 'face)))
5896 (if (consp face) (memq 'org-tag face)
5897 (eq 'org-tag face))))))
5898 (let* ((link-object (save-excursion
5899 (goto-char start)
5900 (save-match-data (org-element-link-parser))))
5901 (link (org-element-property :raw-link link-object))
5902 (type (org-element-property :type link-object))
5903 (path (org-element-property :path link-object))
5904 (properties ;for link's visible part
5905 (list
5906 'face (pcase (org-link-get-parameter type :face)
5907 ((and (pred functionp) face) (funcall face path))
5908 ((and (pred facep) face) face)
5909 ((and (pred consp) face) face) ;anonymous
5910 (_ 'org-link))
5911 'mouse-face (or (org-link-get-parameter type :mouse-face)
5912 'highlight)
5913 'keymap (or (org-link-get-parameter type :keymap)
5914 org-mouse-map)
5915 'help-echo (pcase (org-link-get-parameter type :help-echo)
5916 ((and (pred stringp) echo) echo)
5917 ((and (pred functionp) echo) echo)
5918 (_ (concat "LINK: " link)))
5919 'htmlize-link (pcase (org-link-get-parameter type
5920 :htmlize-link)
5921 ((and (pred functionp) f) (funcall f))
5922 (_ `(:uri ,link)))
5923 'font-lock-multiline t)))
5924 (org-remove-flyspell-overlays-in start end)
5925 (org-rear-nonsticky-at end)
5926 (if (not (eq 'bracket style))
5927 (add-text-properties start end properties)
5928 ;; Handle invisible parts in bracket links.
5929 (remove-text-properties start end '(invisible nil))
5930 (let ((hidden
5931 (append `(invisible
5932 ,(or (org-link-get-parameter type :display)
5933 'org-link))
5934 properties))
5935 (visible-start (or (match-beginning 4) (match-beginning 2)))
5936 (visible-end (or (match-end 4) (match-end 2))))
5937 (add-text-properties start visible-start hidden)
5938 (add-text-properties visible-start visible-end properties)
5939 (add-text-properties visible-end end hidden)
5940 (org-rear-nonsticky-at visible-start)
5941 (org-rear-nonsticky-at visible-end)))
5942 (let ((f (org-link-get-parameter type :activate-func)))
5943 (when (functionp f)
5944 (funcall f start end path (eq style 'bracket))))
5945 (throw :exit t))))) ;signal success
5946 nil))
5948 (defun org-activate-code (limit)
5949 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5950 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5951 (remove-text-properties (match-beginning 0) (match-end 0)
5952 '(display t invisible t intangible t))
5955 (defcustom org-src-fontify-natively t
5956 "When non-nil, fontify code in code blocks.
5957 See also the `org-block' face."
5958 :type 'boolean
5959 :version "26.1"
5960 :package-version '(Org . "8.3")
5961 :group 'org-appearance
5962 :group 'org-babel)
5964 (defcustom org-allow-promoting-top-level-subtree nil
5965 "When non-nil, allow promoting a top level subtree.
5966 The leading star of the top level headline will be replaced
5967 by a #."
5968 :type 'boolean
5969 :version "24.1"
5970 :group 'org-appearance)
5972 (defun org-fontify-meta-lines-and-blocks (limit)
5973 (condition-case nil
5974 (org-fontify-meta-lines-and-blocks-1 limit)
5975 (error (message "Org mode fontification error in %S at %d"
5976 (current-buffer)
5977 (line-number-at-pos)))))
5979 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5980 "Fontify #+ lines and blocks."
5981 (let ((case-fold-search t))
5982 (when (re-search-forward
5983 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5984 limit t)
5985 (let ((beg (match-beginning 0))
5986 (block-start (match-end 0))
5987 (block-end nil)
5988 (lang (match-string 7))
5989 (beg1 (line-beginning-position 2))
5990 (dc1 (downcase (match-string 2)))
5991 (dc3 (downcase (match-string 3)))
5992 end end1 quoting block-type)
5993 (cond
5994 ((and (match-end 4) (equal dc3 "+begin"))
5995 ;; Truly a block
5996 (setq block-type (downcase (match-string 5))
5997 quoting (member block-type org-protecting-blocks))
5998 (when (re-search-forward
5999 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6000 nil t) ;; on purpose, we look further than LIMIT
6001 (setq end (min (point-max) (match-end 0))
6002 end1 (min (point-max) (1- (match-beginning 0))))
6003 (setq block-end (match-beginning 0))
6004 (when quoting
6005 (org-remove-flyspell-overlays-in beg1 end1)
6006 (remove-text-properties beg end
6007 '(display t invisible t intangible t)))
6008 (add-text-properties
6009 beg end '(font-lock-fontified t font-lock-multiline t))
6010 (add-text-properties beg beg1 '(face org-meta-line))
6011 (org-remove-flyspell-overlays-in beg beg1)
6012 (add-text-properties ; For end_src
6013 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6014 (org-remove-flyspell-overlays-in end1 end)
6015 (cond
6016 ((and lang (not (string= lang "")) org-src-fontify-natively)
6017 (org-src-font-lock-fontify-block lang block-start block-end)
6018 (add-text-properties beg1 block-end '(src-block t)))
6019 (quoting
6020 (add-text-properties beg1 (min (point-max) (1+ end1))
6021 (list 'face
6022 (list :inherit
6023 (let ((face-name
6024 (intern (format "org-block-%s" lang))))
6025 (append (and (facep face-name) (list face-name))
6026 '(org-block))))))) ; end of source block
6027 ((not org-fontify-quote-and-verse-blocks))
6028 ((string= block-type "quote")
6029 (add-face-text-property
6030 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6031 ((string= block-type "verse")
6032 (add-face-text-property
6033 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6034 (add-text-properties beg beg1 '(face org-block-begin-line))
6035 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6036 '(face org-block-end-line))
6038 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6039 (org-remove-flyspell-overlays-in
6040 (match-beginning 0)
6041 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6042 (add-text-properties
6043 beg (match-end 3)
6044 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6045 '(font-lock-fontified t invisible t)
6046 '(font-lock-fontified t face org-document-info-keyword)))
6047 (add-text-properties
6048 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6049 (if (string-equal dc1 "+title:")
6050 '(font-lock-fontified t face org-document-title)
6051 '(font-lock-fontified t face org-document-info))))
6052 ((string-prefix-p "+caption" dc1)
6053 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6054 (remove-text-properties (match-beginning 0) (match-end 0)
6055 '(display t invisible t intangible t))
6056 ;; Handle short captions.
6057 (save-excursion
6058 (beginning-of-line)
6059 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6060 (add-text-properties (line-beginning-position) (match-end 1)
6061 '(font-lock-fontified t face org-meta-line))
6062 (add-text-properties (match-end 0) (line-end-position)
6063 '(font-lock-fontified t face org-block))
6065 ((member dc3 '(" " ""))
6066 (org-remove-flyspell-overlays-in beg (match-end 0))
6067 (add-text-properties
6068 beg (match-end 0)
6069 '(font-lock-fontified t face font-lock-comment-face)))
6070 (t ;; just any other in-buffer setting, but not indented
6071 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6072 (remove-text-properties (match-beginning 0) (match-end 0)
6073 '(display t invisible t intangible t))
6074 (add-text-properties beg (match-end 0)
6075 '(font-lock-fontified t face org-meta-line))
6076 t))))))
6078 (defun org-fontify-drawers (limit)
6079 "Fontify drawers."
6080 (when (re-search-forward org-drawer-regexp limit t)
6081 (add-text-properties
6082 (match-beginning 0) (match-end 0)
6083 '(font-lock-fontified t face org-special-keyword))
6084 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6087 (defun org-fontify-macros (limit)
6088 "Fontify macros."
6089 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6090 (let ((begin (match-beginning 0))
6091 (opening-end (match-beginning 1)))
6092 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6093 (match-string 1))
6094 (let ((end (match-end 1))
6095 (closing-start (match-beginning 1)))
6096 (add-text-properties
6097 begin end
6098 '(font-lock-multiline t font-lock-fontified t face org-macro))
6099 (org-remove-flyspell-overlays-in begin end)
6100 (when org-hide-macro-markers
6101 (add-text-properties begin opening-end '(invisible t))
6102 (add-text-properties closing-start end '(invisible t)))
6103 t)))))
6105 (defun org-activate-footnote-links (limit)
6106 "Add text properties for footnotes."
6107 (let ((fn (org-footnote-next-reference-or-definition limit)))
6108 (when fn
6109 (let* ((beg (nth 1 fn))
6110 (end (nth 2 fn))
6111 (label (car fn))
6112 (referencep (/= (line-beginning-position) beg)))
6113 (when (and referencep (nth 3 fn))
6114 (save-excursion
6115 (goto-char beg)
6116 (search-forward (or label "fn:"))
6117 (org-remove-flyspell-overlays-in beg (match-end 0))))
6118 (add-text-properties beg end
6119 (list 'mouse-face 'highlight
6120 'keymap org-mouse-map
6121 'help-echo
6122 (if referencep "Footnote reference"
6123 "Footnote definition")
6124 'font-lock-fontified t
6125 'font-lock-multiline t
6126 'face 'org-footnote))))))
6128 (defun org-activate-dates (limit)
6129 "Add text properties for dates."
6130 (when (and (re-search-forward org-tsr-regexp-both limit t)
6131 (not (equal (char-before (match-beginning 0)) 91)))
6132 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6133 (add-text-properties (match-beginning 0) (match-end 0)
6134 (list 'mouse-face 'highlight
6135 'keymap org-mouse-map))
6136 (org-rear-nonsticky-at (match-end 0))
6137 (when org-display-custom-times
6138 ;; If it's a date range, activate custom time for second date.
6139 (when (match-end 3)
6140 (org-display-custom-time (match-beginning 3) (match-end 3)))
6141 (org-display-custom-time (match-beginning 1) (match-end 1)))
6144 (defvar-local org-target-link-regexp nil
6145 "Regular expression matching radio targets in plain text.")
6147 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6148 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6149 border border border))
6150 "Regular expression matching a link target.")
6152 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6153 "Regular expression matching a radio target.")
6155 (defconst org-any-target-regexp
6156 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6157 "Regular expression matching any target.")
6159 (defun org-activate-target-links (limit)
6160 "Add text properties for target matches."
6161 (when org-target-link-regexp
6162 (let ((case-fold-search t))
6163 (when (re-search-forward org-target-link-regexp limit t)
6164 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6165 (add-text-properties (match-beginning 1) (match-end 1)
6166 (list 'mouse-face 'highlight
6167 'keymap org-mouse-map
6168 'help-echo "Radio target link"
6169 'org-linked-text t))
6170 (org-rear-nonsticky-at (match-end 1))
6171 t))))
6173 (defun org-update-radio-target-regexp ()
6174 "Find all radio targets in this file and update the regular expression.
6175 Also refresh fontification if needed."
6176 (interactive)
6177 (let ((old-regexp org-target-link-regexp)
6178 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6179 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6180 (targets
6181 (org-with-wide-buffer
6182 (goto-char (point-min))
6183 (let (rtn)
6184 (while (re-search-forward org-radio-target-regexp nil t)
6185 ;; Make sure point is really within the object.
6186 (backward-char)
6187 (let ((obj (org-element-context)))
6188 (when (eq (org-element-type obj) 'radio-target)
6189 (cl-pushnew (org-element-property :value obj) rtn
6190 :test #'equal))))
6191 rtn))))
6192 (setq org-target-link-regexp
6193 (and targets
6194 (concat before-re
6195 (mapconcat
6196 (lambda (x)
6197 (replace-regexp-in-string
6198 " +" "\\s-+" (regexp-quote x) t t))
6199 targets
6200 "\\|")
6201 after-re)))
6202 (unless (equal old-regexp org-target-link-regexp)
6203 ;; Clean-up cache.
6204 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6205 ((not org-target-link-regexp) old-regexp)
6207 (concat before-re
6208 (mapconcat
6209 (lambda (re)
6210 (substring re (length before-re)
6211 (- (length after-re))))
6212 (list old-regexp org-target-link-regexp)
6213 "\\|")
6214 after-re)))))
6215 (org-with-wide-buffer
6216 (goto-char (point-min))
6217 (while (re-search-forward regexp nil t)
6218 (org-element-cache-refresh (match-beginning 1)))))
6219 ;; Re fontify buffer.
6220 (when (memq 'radio org-highlight-links)
6221 (org-restart-font-lock)))))
6223 (defvar org-latex-and-related-regexp nil
6224 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6226 (defun org-compute-latex-and-related-regexp ()
6227 "Compute regular expression for LaTeX, entities and sub/superscript.
6228 Result depends on variable `org-highlight-latex-and-related'."
6229 (setq-local
6230 org-latex-and-related-regexp
6231 (let* ((re-sub
6232 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6233 ((eq org-use-sub-superscripts '{})
6234 (list org-match-substring-with-braces-regexp))
6235 (org-use-sub-superscripts (list org-match-substring-regexp))))
6236 (re-latex
6237 (when (memq 'latex org-highlight-latex-and-related)
6238 (let ((matchers (plist-get org-format-latex-options :matchers)))
6239 (delq nil
6240 (mapcar (lambda (x)
6241 (and (member (car x) matchers) (nth 1 x)))
6242 org-latex-regexps)))))
6243 (re-entities
6244 (when (memq 'entities org-highlight-latex-and-related)
6245 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6246 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6248 (defun org-do-latex-and-related (limit)
6249 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6250 LIMIT bounds the search for syntax to highlight. Stop at first
6251 highlighted object, if any. Return t if some highlighting was
6252 done, nil otherwise."
6253 (when (org-string-nw-p org-latex-and-related-regexp)
6254 (catch 'found
6255 (while (re-search-forward org-latex-and-related-regexp limit t)
6256 (unless
6257 (cl-some
6258 (lambda (f)
6259 (memq f '(org-code org-verbatim underline org-special-keyword)))
6260 (save-excursion
6261 (goto-char (1+ (match-beginning 0)))
6262 (face-at-point nil t)))
6263 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6264 '(?_ ?^))
6266 0)))
6267 (font-lock-prepend-text-property
6268 (+ offset (match-beginning 0)) (match-end 0)
6269 'face 'org-latex-and-related)
6270 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6271 '(font-lock-multiline t)))
6272 (throw 'found t)))
6273 nil)))
6275 (defun org-restart-font-lock ()
6276 "Restart `font-lock-mode', to force refontification."
6277 (when (and (boundp 'font-lock-mode) font-lock-mode)
6278 (font-lock-mode -1)
6279 (font-lock-mode 1)))
6281 (defun org-activate-tags (limit)
6282 (when (re-search-forward org-tag-line-re limit t)
6283 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6284 (add-text-properties (match-beginning 1) (match-end 1)
6285 (list 'mouse-face 'highlight
6286 'keymap org-mouse-map))
6287 (org-rear-nonsticky-at (match-end 1))
6290 (defun org-outline-level ()
6291 "Compute the outline level of the heading at point.
6293 If this is called at a normal headline, the level is the number
6294 of stars. Use `org-reduced-level' to remove the effect of
6295 `org-odd-levels'. Unlike to `org-current-level', this function
6296 takes into consideration inlinetasks."
6297 (org-with-wide-buffer
6298 (end-of-line)
6299 (if (re-search-backward org-outline-regexp-bol nil t)
6300 (1- (- (match-end 0) (match-beginning 0)))
6301 0)))
6303 (defvar org-font-lock-keywords nil)
6305 (defsubst org-re-property (property &optional literal allow-null value)
6306 "Return a regexp matching a PROPERTY line.
6308 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6309 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6310 non-nil, match properties even without a value.
6312 Match group 3 is set to the value when it exists. If there is no
6313 value and ALLOW-NULL is non-nil, it is set to the empty string.
6315 With optional argument VALUE, match only property lines with
6316 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6317 unless LITERAL is non-nil."
6318 (concat
6319 "^\\(?4:[ \t]*\\)"
6320 (format "\\(?1::\\(?2:%s\\):\\)"
6321 (if literal property (regexp-quote property)))
6322 (cond (value
6323 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6324 (if literal value (regexp-quote value))))
6325 (allow-null
6326 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6328 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6330 (defconst org-property-re
6331 (org-re-property "\\S-+" 'literal t)
6332 "Regular expression matching a property line.
6333 There are four matching groups:
6334 1: :PROPKEY: including the leading and trailing colon,
6335 2: PROPKEY without the leading and trailing colon,
6336 3: PROPVAL without leading or trailing spaces,
6337 4: the indentation of the current line,
6338 5: trailing whitespace.")
6340 (defvar org-font-lock-hook nil
6341 "Functions to be called for special font lock stuff.")
6343 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6345 (defvar org-font-lock-set-keywords-hook nil
6346 "Functions that can manipulate `org-font-lock-extra-keywords'.
6347 This is called after `org-font-lock-extra-keywords' is defined, but before
6348 it is installed to be used by font lock. This can be useful if something
6349 needs to be inserted at a specific position in the font-lock sequence.")
6351 (defun org-font-lock-hook (limit)
6352 "Run `org-font-lock-hook' within LIMIT."
6353 (run-hook-with-args 'org-font-lock-hook limit))
6355 (defun org-set-font-lock-defaults ()
6356 "Set font lock defaults for the current buffer."
6357 (let* ((em org-fontify-emphasized-text)
6358 (lk org-highlight-links)
6359 (org-font-lock-extra-keywords
6360 (list
6361 ;; Call the hook
6362 '(org-font-lock-hook)
6363 ;; Headlines
6364 `(,(if org-fontify-whole-heading-line
6365 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6366 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6367 (1 (org-get-level-face 1))
6368 (2 (org-get-level-face 2))
6369 (3 (org-get-level-face 3)))
6370 ;; Table lines
6371 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6372 (1 'org-table t))
6373 ;; Table internals
6374 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6375 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6376 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6377 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6378 ;; Drawers
6379 '(org-fontify-drawers)
6380 ;; Properties
6381 (list org-property-re
6382 '(1 'org-special-keyword t)
6383 '(3 'org-property-value t))
6384 ;; Link related fontification.
6385 '(org-activate-links)
6386 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6387 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6388 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6389 (when (memq 'footnote lk) '(org-activate-footnote-links))
6390 ;; Targets.
6391 (list org-any-target-regexp '(0 'org-target t))
6392 ;; Diary sexps.
6393 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6394 ;; Macro
6395 '(org-fontify-macros)
6396 ;; TODO keyword
6397 (list (format org-heading-keyword-regexp-format
6398 org-todo-regexp)
6399 '(2 (org-get-todo-face 2) t))
6400 ;; DONE
6401 (if org-fontify-done-headline
6402 (list (format org-heading-keyword-regexp-format
6403 (concat
6404 "\\(?:"
6405 (mapconcat 'regexp-quote org-done-keywords "\\|")
6406 "\\)"))
6407 '(2 'org-headline-done t))
6408 nil)
6409 ;; Priorities
6410 '(org-font-lock-add-priority-faces)
6411 ;; Tags
6412 '(org-font-lock-add-tag-faces)
6413 ;; Tags groups
6414 (when (and org-group-tags org-tag-groups-alist)
6415 (list (concat org-outline-regexp-bol ".+\\(:"
6416 (regexp-opt (mapcar 'car org-tag-groups-alist))
6417 ":\\).*$")
6418 '(1 'org-tag-group prepend)))
6419 ;; Special keywords
6420 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6421 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6422 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6423 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6424 ;; Emphasis
6425 (when em '(org-do-emphasis-faces))
6426 ;; Checkboxes
6427 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6428 1 'org-checkbox prepend)
6429 (when (cdr (assq 'checkbox org-list-automatic-rules))
6430 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6431 (0 (org-get-checkbox-statistics-face) t)))
6432 ;; Description list items
6433 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6434 1 'org-list-dt prepend)
6435 ;; ARCHIVEd headings
6436 (list (concat
6437 org-outline-regexp-bol
6438 "\\(.*:" org-archive-tag ":.*\\)")
6439 '(1 'org-archived prepend))
6440 ;; Specials
6441 '(org-do-latex-and-related)
6442 '(org-fontify-entities)
6443 '(org-raise-scripts)
6444 ;; Code
6445 '(org-activate-code (1 'org-code t))
6446 ;; COMMENT
6447 (list (format
6448 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6449 org-todo-regexp
6450 org-comment-string)
6451 '(9 'org-special-keyword t))
6452 ;; Blocks and meta lines
6453 '(org-fontify-meta-lines-and-blocks))))
6454 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6455 (run-hooks 'org-font-lock-set-keywords-hook)
6456 ;; Now set the full font-lock-keywords
6457 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6458 (setq-local font-lock-defaults
6459 '(org-font-lock-keywords t nil nil backward-paragraph))
6460 (kill-local-variable 'font-lock-keywords)
6461 nil))
6463 (defun org-toggle-pretty-entities ()
6464 "Toggle the composition display of entities as UTF8 characters."
6465 (interactive)
6466 (setq-local org-pretty-entities (not org-pretty-entities))
6467 (org-restart-font-lock)
6468 (if org-pretty-entities
6469 (message "Entities are now displayed as UTF8 characters")
6470 (save-restriction
6471 (widen)
6472 (decompose-region (point-min) (point-max))
6473 (message "Entities are now displayed as plain text"))))
6475 (defvar-local org-custom-properties-overlays nil
6476 "List of overlays used for custom properties.")
6478 (defun org-toggle-custom-properties-visibility ()
6479 "Display or hide properties in `org-custom-properties'."
6480 (interactive)
6481 (if org-custom-properties-overlays
6482 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6483 (setq org-custom-properties-overlays nil))
6484 (when org-custom-properties
6485 (org-with-wide-buffer
6486 (goto-char (point-min))
6487 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6488 (while (re-search-forward regexp nil t)
6489 (let ((end (cdr (save-match-data (org-get-property-block)))))
6490 (when (and end (< (point) end))
6491 ;; Hide first custom property in current drawer.
6492 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6493 (overlay-put o 'invisible t)
6494 (overlay-put o 'org-custom-property t)
6495 (push o org-custom-properties-overlays))
6496 ;; Hide additional custom properties in the same drawer.
6497 (while (re-search-forward regexp end t)
6498 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6499 (overlay-put o 'invisible t)
6500 (overlay-put o 'org-custom-property t)
6501 (push o org-custom-properties-overlays)))))
6502 ;; Each entry is limited to a single property drawer.
6503 (outline-next-heading)))))))
6505 (defun org-fontify-entities (limit)
6506 "Find an entity to fontify."
6507 (let (ee)
6508 (when org-pretty-entities
6509 (catch 'match
6510 ;; "\_ "-family is left out on purpose. Only the first one,
6511 ;; i.e., "\_ ", could be fontified anyway, and it would be
6512 ;; confusing when adding a second white space character.
6513 (while (re-search-forward
6514 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6515 limit t)
6516 (when (and (not (org-at-comment-p))
6517 (setq ee (org-entity-get (match-string 1)))
6518 (= (length (nth 6 ee)) 1))
6519 (let* ((end (if (equal (match-string 2) "{}")
6520 (match-end 2)
6521 (match-end 1))))
6522 (add-text-properties
6523 (match-beginning 0) end
6524 (list 'font-lock-fontified t))
6525 (compose-region (match-beginning 0) end
6526 (nth 6 ee) nil)
6527 (backward-char 1)
6528 (throw 'match t))))
6529 nil))))
6531 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6532 "Fontify string S like in Org mode."
6533 (with-temp-buffer
6534 (insert s)
6535 (let ((org-odd-levels-only odd-levels))
6536 (org-mode)
6537 (org-font-lock-ensure)
6538 (buffer-string))))
6540 (defvar org-m nil)
6541 (defvar org-l nil)
6542 (defvar org-f nil)
6543 (defun org-get-level-face (n)
6544 "Get the right face for match N in font-lock matching of headlines."
6545 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6546 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6547 (if org-cycle-level-faces
6548 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6549 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6550 (cond
6551 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6552 ((eq n 2) org-f)
6553 (t (unless org-level-color-stars-only org-f))))
6555 (defun org-face-from-face-or-color (context inherit face-or-color)
6556 "Create a face list that inherits INHERIT, but sets the foreground color.
6557 When FACE-OR-COLOR is not a string, just return it."
6558 (if (stringp face-or-color)
6559 (list :inherit inherit
6560 (cdr (assoc context org-faces-easy-properties))
6561 face-or-color)
6562 face-or-color))
6564 (defun org-get-todo-face (kwd)
6565 "Get the right face for a TODO keyword KWD.
6566 If KWD is a number, get the corresponding match group."
6567 (when (numberp kwd) (setq kwd (match-string kwd)))
6568 (or (org-face-from-face-or-color
6569 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6570 (and (member kwd org-done-keywords) 'org-done)
6571 'org-todo))
6573 (defun org-get-priority-face (priority)
6574 "Get the right face for PRIORITY.
6575 PRIORITY is a character."
6576 (or (org-face-from-face-or-color
6577 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6578 'org-priority))
6580 (defun org-get-tag-face (tag)
6581 "Get the right face for TAG.
6582 If TAG is a number, get the corresponding match group."
6583 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6584 (or (org-face-from-face-or-color
6585 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6586 'org-tag)))
6588 (defun org-font-lock-add-priority-faces (limit)
6589 "Add the special priority faces."
6590 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6591 (add-text-properties
6592 (match-beginning 1) (match-end 1)
6593 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6594 'font-lock-fontified t))))
6596 (defun org-font-lock-add-tag-faces (limit)
6597 "Add the special tag faces."
6598 (when (and org-tag-faces org-tags-special-faces-re)
6599 (while (re-search-forward org-tags-special-faces-re limit t)
6600 (add-text-properties (match-beginning 1) (match-end 1)
6601 (list 'face (org-get-tag-face 1)
6602 'font-lock-fontified t))
6603 (backward-char 1))))
6605 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6606 "Remove fontification and activation overlays from links."
6607 (font-lock-default-unfontify-region beg end)
6608 (let* ((buffer-undo-list t)
6609 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6610 (inhibit-modification-hooks t)
6611 deactivate-mark buffer-file-name buffer-file-truename)
6612 (decompose-region beg end)
6613 (remove-text-properties beg end
6614 '(mouse-face t keymap t org-linked-text t
6615 invisible t intangible t
6616 org-emphasis t))
6617 (org-remove-font-lock-display-properties beg end)))
6619 (defconst org-script-display '(((raise -0.3) (height 0.7))
6620 ((raise 0.3) (height 0.7))
6621 ((raise -0.5))
6622 ((raise 0.5)))
6623 "Display properties for showing superscripts and subscripts.")
6625 (defun org-remove-font-lock-display-properties (beg end)
6626 "Remove specific display properties that have been added by font lock.
6627 The will remove the raise properties that are used to show superscripts
6628 and subscripts."
6629 (let (next prop)
6630 (while (< beg end)
6631 (setq next (next-single-property-change beg 'display nil end)
6632 prop (get-text-property beg 'display))
6633 (when (member prop org-script-display)
6634 (put-text-property beg next 'display nil))
6635 (setq beg next))))
6637 (defun org-raise-scripts (limit)
6638 "Add raise properties to sub/superscripts."
6639 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6640 (re-search-forward
6641 (if (eq org-use-sub-superscripts t)
6642 org-match-substring-regexp
6643 org-match-substring-with-braces-regexp)
6644 limit t))
6645 (let* ((pos (point)) table-p comment-p
6646 (mpos (match-beginning 3))
6647 (emph-p (get-text-property mpos 'org-emphasis))
6648 (link-p (get-text-property mpos 'mouse-face))
6649 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6650 (goto-char (point-at-bol))
6651 (setq table-p (looking-at-p org-table-dataline-regexp)
6652 comment-p (looking-at-p "^[ \t]*#[ +]"))
6653 (goto-char pos)
6654 ;; Handle a_b^c
6655 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6656 (unless (or comment-p emph-p link-p keyw-p)
6657 (put-text-property (match-beginning 3) (match-end 0)
6658 'display
6659 (if (equal (char-after (match-beginning 2)) ?^)
6660 (nth (if table-p 3 1) org-script-display)
6661 (nth (if table-p 2 0) org-script-display)))
6662 (add-text-properties (match-beginning 2) (match-end 2)
6663 (list 'invisible t))
6664 (when (and (eq (char-after (match-beginning 3)) ?{)
6665 (eq (char-before (match-end 3)) ?}))
6666 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6667 (list 'invisible t))
6668 (add-text-properties (1- (match-end 3)) (match-end 3)
6669 (list 'invisible t))))
6670 t)))
6672 (defun org-remove-empty-overlays-at (pos)
6673 "Remove outline overlays that do not contain non-white stuff."
6674 (dolist (o (overlays-at pos))
6675 (and (eq 'outline (overlay-get o 'invisible))
6676 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6677 (overlay-end o))))
6678 (delete-overlay o))))
6680 (defun org-show-empty-lines-in-parent ()
6681 "Move to the parent and re-show empty lines before visible headlines."
6682 (save-excursion
6683 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6684 (org-cycle-show-empty-lines context))))
6686 (defun org-files-list ()
6687 "Return `org-agenda-files' list, plus all open Org files.
6688 This is useful for operations that need to scan all of a user's
6689 open and agenda-wise Org files."
6690 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6691 (dolist (buf (buffer-list))
6692 (with-current-buffer buf
6693 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6694 (cl-pushnew (expand-file-name (buffer-file-name)) files
6695 :test #'equal))))
6696 files))
6698 (defsubst org-entry-beginning-position ()
6699 "Return the beginning position of the current entry."
6700 (save-excursion (org-back-to-heading t) (point)))
6702 (defsubst org-entry-end-position ()
6703 "Return the end position of the current entry."
6704 (save-excursion (outline-next-heading) (point)))
6706 (defun org-subtree-end-visible-p ()
6707 "Is the end of the current subtree visible?"
6708 (pos-visible-in-window-p
6709 (save-excursion (org-end-of-subtree t) (point))))
6711 (defun org-first-headline-recenter ()
6712 "Move cursor to the first headline and recenter the headline."
6713 (let ((window (get-buffer-window)))
6714 (when window
6715 (goto-char (point-min))
6716 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6717 (set-window-start window (line-beginning-position))))))
6720 ;;; Visibility (headlines, blocks, drawers)
6722 ;;;; Headlines visibility
6724 (defun org-show-entry ()
6725 "Show the body directly following this heading.
6726 Show the heading too, if it is currently invisible."
6727 (interactive)
6728 (save-excursion
6729 (ignore-errors
6730 (org-back-to-heading t)
6731 (org-flag-region
6732 (line-end-position 0)
6733 (save-excursion
6734 (if (re-search-forward
6735 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6736 (match-beginning 1)
6737 (point-max)))
6739 'outline))))
6741 (defun org-show-children (&optional level)
6742 "Show all direct subheadings of this heading.
6743 Prefix arg LEVEL is how many levels below the current level
6744 should be shown. Default is enough to cause the following
6745 heading to appear."
6746 (interactive "p")
6747 (save-excursion
6748 (org-back-to-heading t)
6749 (let* ((current-level (funcall outline-level))
6750 (max-level (org-get-valid-level
6751 current-level
6752 (if level (prefix-numeric-value level) 1)))
6753 (end (save-excursion (org-end-of-subtree t t)))
6754 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6755 (past-first-child nil)
6756 ;; Make sure to skip inlinetasks.
6757 (re (format regexp-fmt
6758 current-level
6759 (cond
6760 ((not (featurep 'org-inlinetask)) "")
6761 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6763 (t (1- org-inlinetask-min-level))))))
6764 ;; Display parent heading.
6765 (org-flag-heading nil)
6766 (forward-line)
6767 ;; Display children. First child may be deeper than expected
6768 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6769 ;; MAX-LEVEL accordingly.
6770 (while (re-search-forward re end t)
6771 (unless past-first-child
6772 (setq re (format regexp-fmt
6773 current-level
6774 (max (funcall outline-level) max-level)))
6775 (setq past-first-child t))
6776 (org-flag-heading nil)))))
6778 (defun org-show-subtree ()
6779 "Show everything after this heading at deeper levels."
6780 (interactive)
6781 (org-flag-region
6782 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6784 ;;;; Blocks visibility
6786 (defun org-hide-block-toggle-maybe ()
6787 "Toggle visibility of block at point.
6788 Unlike to `org-hide-block-toggle', this function does not throw
6789 an error. Return a non-nil value when toggling is successful."
6790 (interactive)
6791 (ignore-errors (org-hide-block-toggle)))
6793 (defun org-hide-block-toggle (&optional force)
6794 "Toggle the visibility of the current block.
6795 When optional argument FORCE is `off', make block visible. If it
6796 is non-nil, hide it unconditionally. Throw an error when not at
6797 a block. Return a non-nil value when toggling is successful."
6798 (interactive)
6799 (let ((element (org-element-at-point)))
6800 (unless (memq (org-element-type element)
6801 '(center-block comment-block dynamic-block example-block
6802 export-block quote-block special-block
6803 src-block verse-block))
6804 (user-error "Not at a block"))
6805 (let* ((post (org-element-property :post-affiliated element))
6806 (start (save-excursion
6807 (goto-char post)
6808 (line-end-position)))
6809 (end (save-excursion
6810 (goto-char (org-element-property :end element))
6811 (skip-chars-backward " \t\n")
6812 (line-end-position))))
6813 ;; Do nothing when not before or at the block opening line or at
6814 ;; the block closing line.
6815 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6816 (cond ((eq force 'off)
6817 (org-flag-region start end nil 'org-hide-block))
6818 (force
6819 (org-flag-region start end t 'org-hide-block))
6820 ((eq (get-char-property start 'invisible) 'org-hide-block)
6821 (org-flag-region start end nil 'org-hide-block))
6823 (org-flag-region start end t 'org-hide-block)))
6824 ;; When the block is hidden away, make sure point is left in
6825 ;; a visible part of the buffer.
6826 (when (invisible-p (max (1- (point)) (point-min)))
6827 (goto-char post))
6828 ;; Signal success.
6829 t))))
6831 (defun org-hide-block-toggle-all ()
6832 "Toggle the visibility of all blocks in the current buffer."
6833 (org-block-map 'org-hide-block-toggle))
6835 (defun org-hide-block-all ()
6836 "Fold all blocks in the current buffer."
6837 (interactive)
6838 (org-show-all '(blocks))
6839 (org-block-map 'org-hide-block-toggle-maybe))
6841 ;;;; Drawers visibility
6843 (defun org-cycle-hide-drawers (state &optional exceptions)
6844 "Re-hide all drawers after a visibility state change.
6845 STATE should be one of the symbols listed in the docstring of
6846 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6847 a list of strings specifying which drawers should not be hidden."
6848 (when (and (derived-mode-p 'org-mode)
6849 (not (memq state '(overview folded contents))))
6850 (save-excursion
6851 (let* ((globalp (eq state 'all))
6852 (beg (if globalp (point-min) (point)))
6853 (end (if globalp (point-max)
6854 (if (eq state 'children)
6855 (save-excursion (outline-next-heading) (point))
6856 (org-end-of-subtree t)))))
6857 (goto-char beg)
6858 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6859 (unless (member-ignore-case (match-string 1) exceptions)
6860 (let ((drawer (org-element-at-point)))
6861 (when (memq (org-element-type drawer) '(drawer property-drawer))
6862 (org-flag-drawer t drawer)
6863 ;; Make sure to skip drawer entirely or we might flag
6864 ;; it another time when matching its ending line with
6865 ;; `org-drawer-regexp'.
6866 (goto-char (org-element-property :end drawer))))))))))
6868 (defun org-flag-drawer (flag &optional element)
6869 "When FLAG is non-nil, hide the drawer we are at.
6870 Otherwise make it visible. When optional argument ELEMENT is
6871 a parsed drawer, as returned by `org-element-at-point', hide or
6872 show that drawer instead."
6873 (let ((drawer (or element
6874 (and (save-excursion
6875 (beginning-of-line)
6876 (looking-at-p org-drawer-regexp))
6877 (org-element-at-point)))))
6878 (when (memq (org-element-type drawer) '(drawer property-drawer))
6879 (let ((post (org-element-property :post-affiliated drawer)))
6880 (org-flag-region
6881 (save-excursion (goto-char post) (line-end-position))
6882 (save-excursion (goto-char (org-element-property :end drawer))
6883 (skip-chars-backward " \t\n")
6884 (line-end-position))
6885 flag 'org-hide-drawer)
6886 ;; When the drawer is hidden away, make sure point lies in
6887 ;; a visible part of the buffer.
6888 (when (invisible-p (max (1- (point)) (point-min)))
6889 (goto-char post))))))
6891 ;;;; Visibility cycling
6893 (defvar-local org-cycle-global-status nil)
6894 (put 'org-cycle-global-status 'org-state t)
6895 (defvar-local org-cycle-subtree-status nil)
6896 (put 'org-cycle-subtree-status 'org-state t)
6898 (defun org-show-all (&optional types)
6899 "Show all contents in the visible part of the buffer.
6900 By default, the function expands headings, blocks and drawers.
6901 When optional argument TYPE is a list of symbols among `blocks',
6902 `drawers' and `headings', to only expand one specific type."
6903 (dolist (type (or types '(blocks drawers headings)))
6904 (org-flag-region (point-min) (point-max) nil
6905 (pcase type
6906 (`blocks 'org-hide-block)
6907 (`drawers 'org-hide-drawer)
6908 (`headings 'outline)
6909 (_ (error "Invalid type: %S" type))))))
6911 ;;;###autoload
6912 (defun org-cycle (&optional arg)
6913 "TAB-action and visibility cycling for Org mode.
6915 This is the command invoked in Org mode by the `TAB' key. Its main
6916 purpose is outline visibility cycling, but it also invokes other actions
6917 in special contexts.
6919 When this function is called with a `\\[universal-argument]' prefix, rotate \
6920 the entire
6921 buffer through 3 states (global cycling)
6922 1. OVERVIEW: Show only top-level headlines.
6923 2. CONTENTS: Show all headlines of all levels, but no body text.
6924 3. SHOW ALL: Show everything.
6926 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6927 switch to the startup visibility,
6928 determined by the variable `org-startup-folded', and by any VISIBILITY
6929 properties in the buffer.
6931 With a `\\[universal-argument] \\[universal-argument] \
6932 \\[universal-argument]' prefix argument, show the entire buffer, including
6933 any drawers.
6935 When inside a table, re-align the table and move to the next field.
6937 When point is at the beginning of a headline, rotate the subtree started
6938 by this line through 3 different states (local cycling)
6939 1. FOLDED: Only the main headline is shown.
6940 2. CHILDREN: The main headline and the direct children are shown.
6941 From this state, you can move to one of the children
6942 and zoom in further.
6943 3. SUBTREE: Show the entire subtree, including body text.
6944 If there is no subtree, switch directly from CHILDREN to FOLDED.
6946 When point is at the beginning of an empty headline and the variable
6947 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6948 of the headline by demoting and promoting it to likely levels. This
6949 speeds up creation document structure by pressing `TAB' once or several
6950 times right after creating a new headline.
6952 When there is a numeric prefix, go up to a heading with level ARG, do
6953 a `show-subtree' and return to the previous cursor position. If ARG
6954 is negative, go up that many levels.
6956 When point is not at the beginning of a headline, execute the global
6957 binding for `TAB', which is re-indenting the line. See the option
6958 `org-cycle-emulate-tab' for details.
6960 As a special case, if point is at the beginning of the buffer and there is
6961 no headline in line 1, this function will act as if called with prefix arg
6962 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6963 prefix arg, but only
6964 if the variable `org-cycle-global-at-bob' is t."
6965 (interactive "P")
6966 (org-load-modules-maybe)
6967 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6968 (and org-cycle-level-after-item/entry-creation
6969 (or (org-cycle-level)
6970 (org-cycle-item-indentation))))
6971 (let* ((limit-level
6972 (or org-cycle-max-level
6973 (and (boundp 'org-inlinetask-min-level)
6974 org-inlinetask-min-level
6975 (1- org-inlinetask-min-level))))
6976 (nstars (and limit-level
6977 (if org-odd-levels-only
6978 (and limit-level (1- (* limit-level 2)))
6979 limit-level)))
6980 (org-outline-regexp
6981 (if (not (derived-mode-p 'org-mode))
6982 outline-regexp
6983 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6984 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6985 (not (looking-at org-outline-regexp))))
6986 (org-cycle-hook
6987 (if bob-special
6988 (delq 'org-optimize-window-after-visibility-change
6989 (copy-sequence org-cycle-hook))
6990 org-cycle-hook))
6991 (pos (point)))
6993 (cond
6995 ((equal arg '(16))
6996 (setq last-command 'dummy)
6997 (org-set-startup-visibility)
6998 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
7000 ((equal arg '(64))
7001 (org-show-all)
7002 (org-unlogged-message "Entire buffer visible, including drawers"))
7004 ((equal arg '(4)) (org-cycle-internal-global))
7006 ;; Try hiding block at point.
7007 ((org-hide-block-toggle-maybe))
7009 ;; Try cdlatex TAB completion
7010 ((org-try-cdlatex-tab))
7012 ;; Table: enter it or move to the next field.
7013 ((org-at-table-p 'any)
7014 (if (org-at-table.el-p)
7015 (message "%s" (substitute-command-keys "\\<org-mode-map>\
7016 Use `\\[org-edit-special]' to edit table.el tables"))
7017 (if arg (org-table-edit-field t)
7018 (org-table-justify-field-maybe)
7019 (call-interactively 'org-table-next-field))))
7021 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
7023 ;; Global cycling: delegate to `org-cycle-internal-global'.
7024 (bob-special (org-cycle-internal-global))
7026 ;; Drawers: delegate to `org-flag-drawer'.
7027 ((save-excursion
7028 (beginning-of-line 1)
7029 (looking-at org-drawer-regexp))
7030 (org-flag-drawer ; toggle block visibility
7031 (not (get-char-property (match-end 0) 'invisible))))
7033 ;; Show-subtree, ARG levels up from here.
7034 ((integerp arg)
7035 (save-excursion
7036 (org-back-to-heading)
7037 (outline-up-heading (if (< arg 0) (- arg)
7038 (- (funcall outline-level) arg)))
7039 (org-show-subtree)))
7041 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
7042 ((and (featurep 'org-inlinetask)
7043 (org-inlinetask-at-task-p)
7044 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7045 (org-inlinetask-toggle-visibility))
7047 ;; At an item/headline: delegate to `org-cycle-internal-local'.
7048 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
7049 (save-excursion (move-beginning-of-line 1)
7050 (looking-at org-outline-regexp)))
7051 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7052 (org-cycle-internal-local))
7054 ;; From there: TAB emulation and template completion.
7055 (buffer-read-only (org-back-to-heading))
7057 ((run-hook-with-args-until-success
7058 'org-tab-after-check-for-cycling-hook))
7060 ((run-hook-with-args-until-success
7061 'org-tab-before-tab-emulation-hook))
7063 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7064 (or (not (bolp))
7065 (not (looking-at org-outline-regexp))))
7066 (call-interactively (global-key-binding "\t")))
7068 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7069 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7070 (or (and (eq org-cycle-emulate-tab 'white)
7071 (= (match-end 0) (point-at-eol)))
7072 (and (eq org-cycle-emulate-tab 'whitestart)
7073 (>= (match-end 0) pos))))
7075 (eq org-cycle-emulate-tab t))
7076 (call-interactively (global-key-binding "\t")))
7078 (t (save-excursion
7079 (org-back-to-heading)
7080 (org-cycle)))))))
7082 (defun org-cycle-internal-global ()
7083 "Do the global cycling action."
7084 ;; Hack to avoid display of messages for .org attachments in Gnus
7085 (let ((ga (string-match "\\*fontification" (buffer-name))))
7086 (cond
7087 ((and (eq last-command this-command)
7088 (eq org-cycle-global-status 'overview))
7089 ;; We just created the overview - now do table of contents
7090 ;; This can be slow in very large buffers, so indicate action
7091 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7092 (unless ga (org-unlogged-message "CONTENTS..."))
7093 (org-content)
7094 (unless ga (org-unlogged-message "CONTENTS...done"))
7095 (setq org-cycle-global-status 'contents)
7096 (run-hook-with-args 'org-cycle-hook 'contents))
7098 ((and (eq last-command this-command)
7099 (eq org-cycle-global-status 'contents))
7100 ;; We just showed the table of contents - now show everything
7101 (run-hook-with-args 'org-pre-cycle-hook 'all)
7102 (org-show-all '(headings blocks))
7103 (unless ga (org-unlogged-message "SHOW ALL"))
7104 (setq org-cycle-global-status 'all)
7105 (run-hook-with-args 'org-cycle-hook 'all))
7108 ;; Default action: go to overview
7109 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7110 (org-overview)
7111 (unless ga (org-unlogged-message "OVERVIEW"))
7112 (setq org-cycle-global-status 'overview)
7113 (run-hook-with-args 'org-cycle-hook 'overview)))))
7115 (defvar org-called-with-limited-levels nil
7116 "Non-nil when `org-with-limited-levels' is currently active.")
7118 (defun org-cycle-internal-local ()
7119 "Do the local cycling action."
7120 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7121 ;; First, determine end of headline (EOH), end of subtree or item
7122 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7123 (save-excursion
7124 (if (org-at-item-p)
7125 (progn
7126 (beginning-of-line)
7127 (setq struct (org-list-struct))
7128 (setq eoh (point-at-eol))
7129 (setq eos (org-list-get-item-end-before-blank (point) struct))
7130 (setq has-children (org-list-has-child-p (point) struct)))
7131 (org-back-to-heading)
7132 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7133 (setq eos (save-excursion (org-end-of-subtree t t)
7134 (when (bolp) (backward-char)) (point)))
7135 (setq has-children
7136 (or (save-excursion
7137 (let ((level (funcall outline-level)))
7138 (outline-next-heading)
7139 (and (org-at-heading-p t)
7140 (> (funcall outline-level) level))))
7141 (save-excursion
7142 (org-list-search-forward (org-item-beginning-re) eos t)))))
7143 ;; Determine end invisible part of buffer (EOL)
7144 (beginning-of-line 2)
7145 (while (and (not (eobp)) ;This is like `next-line'.
7146 (get-char-property (1- (point)) 'invisible))
7147 (goto-char (next-single-char-property-change (point) 'invisible))
7148 (and (eolp) (beginning-of-line 2)))
7149 (setq eol (point)))
7150 ;; Find out what to do next and set `this-command'
7151 (cond
7152 ((= eos eoh)
7153 ;; Nothing is hidden behind this heading
7154 (unless (org-before-first-heading-p)
7155 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7156 (org-unlogged-message "EMPTY ENTRY")
7157 (setq org-cycle-subtree-status nil)
7158 (save-excursion
7159 (goto-char eos)
7160 (outline-next-heading)
7161 (when (org-invisible-p) (org-flag-heading nil))))
7162 ((and (or (>= eol eos)
7163 (not (string-match "\\S-" (buffer-substring eol eos))))
7164 (or has-children
7165 (not (setq children-skipped
7166 org-cycle-skip-children-state-if-no-children))))
7167 ;; Entire subtree is hidden in one line: children view
7168 (unless (org-before-first-heading-p)
7169 (run-hook-with-args 'org-pre-cycle-hook 'children))
7170 (if (org-at-item-p)
7171 (org-list-set-item-visibility (point-at-bol) struct 'children)
7172 (org-show-entry)
7173 (org-with-limited-levels (org-show-children))
7174 (org-show-set-visibility 'canonical)
7175 ;; Fold every list in subtree to top-level items.
7176 (when (eq org-cycle-include-plain-lists 'integrate)
7177 (save-excursion
7178 (org-back-to-heading)
7179 (while (org-list-search-forward (org-item-beginning-re) eos t)
7180 (beginning-of-line 1)
7181 (let* ((struct (org-list-struct))
7182 (prevs (org-list-prevs-alist struct))
7183 (end (org-list-get-bottom-point struct)))
7184 (dolist (e (org-list-get-all-items (point) struct prevs))
7185 (org-list-set-item-visibility e struct 'folded))
7186 (goto-char (if (< end eos) end eos)))))))
7187 (org-unlogged-message "CHILDREN")
7188 (save-excursion
7189 (goto-char eos)
7190 (outline-next-heading)
7191 (when (org-invisible-p) (org-flag-heading nil)))
7192 (setq org-cycle-subtree-status 'children)
7193 (unless (org-before-first-heading-p)
7194 (run-hook-with-args 'org-cycle-hook 'children)))
7195 ((or children-skipped
7196 (and (eq last-command this-command)
7197 (eq org-cycle-subtree-status 'children)))
7198 ;; We just showed the children, or no children are there,
7199 ;; now show everything.
7200 (unless (org-before-first-heading-p)
7201 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7202 (org-flag-region eoh eos nil 'outline)
7203 (org-unlogged-message
7204 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7205 (setq org-cycle-subtree-status 'subtree)
7206 (unless (org-before-first-heading-p)
7207 (run-hook-with-args 'org-cycle-hook 'subtree)))
7209 ;; Default action: hide the subtree.
7210 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7211 (org-flag-region eoh eos t 'outline)
7212 (org-unlogged-message "FOLDED")
7213 (setq org-cycle-subtree-status 'folded)
7214 (unless (org-before-first-heading-p)
7215 (run-hook-with-args 'org-cycle-hook 'folded))))))
7217 ;;;###autoload
7218 (defun org-global-cycle (&optional arg)
7219 "Cycle the global visibility. For details see `org-cycle'.
7220 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7221 With a numeric prefix, show all headlines up to that level."
7222 (interactive "P")
7223 (let ((org-cycle-include-plain-lists
7224 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7225 (cond
7226 ((integerp arg)
7227 (org-show-all '(headings blocks))
7228 (outline-hide-sublevels arg)
7229 (setq org-cycle-global-status 'contents))
7230 ((equal arg '(4))
7231 (org-set-startup-visibility)
7232 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7234 (org-cycle '(4))))))
7236 (defun org-set-startup-visibility ()
7237 "Set the visibility required by startup options and properties."
7238 (cond
7239 ((eq org-startup-folded t)
7240 (org-overview))
7241 ((eq org-startup-folded 'content)
7242 (org-content))
7243 ((or (eq org-startup-folded 'showeverything)
7244 (eq org-startup-folded nil))
7245 (org-show-all)))
7246 (unless (eq org-startup-folded 'showeverything)
7247 (when org-hide-block-startup (org-hide-block-all))
7248 (org-set-visibility-according-to-property)
7249 (org-cycle-hide-archived-subtrees 'all)
7250 (org-cycle-hide-drawers 'all)
7251 (org-cycle-show-empty-lines t)))
7253 (defun org-set-visibility-according-to-property ()
7254 "Switch subtree visibilities according to :VISIBILITY: property."
7255 (interactive)
7256 (org-with-wide-buffer
7257 (goto-char (point-min))
7258 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7259 (if (not (org-at-property-p)) (outline-next-heading)
7260 (let ((state (match-string 3)))
7261 (save-excursion
7262 (org-back-to-heading t)
7263 (outline-hide-subtree)
7264 (org-reveal)
7265 (cond
7266 ((equal state "folded")
7267 (outline-hide-subtree))
7268 ((equal state "children")
7269 (org-show-hidden-entry)
7270 (org-show-children))
7271 ((equal state "content")
7272 (save-excursion
7273 (save-restriction
7274 (org-narrow-to-subtree)
7275 (org-content))))
7276 ((member state '("all" "showall"))
7277 (outline-show-subtree)))))))))
7279 (defun org-overview ()
7280 "Switch to overview mode, showing only top-level headlines.
7281 This shows all headlines with a level equal or greater than the level
7282 of the first headline in the buffer. This is important, because if the
7283 first headline is not level one, then (hide-sublevels 1) gives confusing
7284 results."
7285 (interactive)
7286 (save-excursion
7287 (let ((level
7288 (save-excursion
7289 (goto-char (point-min))
7290 (when (re-search-forward org-outline-regexp-bol nil t)
7291 (goto-char (match-beginning 0))
7292 (funcall outline-level)))))
7293 (and level (outline-hide-sublevels level)))))
7295 (defun org-content (&optional arg)
7296 "Show all headlines in the buffer, like a table of contents.
7297 With numerical argument N, show content up to level N."
7298 (interactive "P")
7299 (org-overview)
7300 (save-excursion
7301 ;; Visit all headings and show their offspring
7302 (and (integerp arg) (org-overview))
7303 (goto-char (point-max))
7304 (catch 'exit
7305 (while (and (progn (condition-case nil
7306 (outline-previous-visible-heading 1)
7307 (error (goto-char (point-min))))
7309 (looking-at org-outline-regexp))
7310 (if (integerp arg)
7311 (org-show-children (1- arg))
7312 (outline-show-branches))
7313 (when (bobp) (throw 'exit nil))))))
7315 (defun org-optimize-window-after-visibility-change (state)
7316 "Adjust the window after a change in outline visibility.
7317 This function is the default value of the hook `org-cycle-hook'."
7318 (when (get-buffer-window (current-buffer))
7319 (cond
7320 ((eq state 'content) nil)
7321 ((eq state 'all) nil)
7322 ((eq state 'folded) nil)
7323 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7324 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7326 (defun org-clean-visibility-after-subtree-move ()
7327 "Fix visibility issues after moving a subtree."
7328 ;; First, find a reasonable region to look at:
7329 ;; Start two siblings above, end three below
7330 (let* ((beg (save-excursion
7331 (and (org-get-last-sibling)
7332 (org-get-last-sibling))
7333 (point)))
7334 (end (save-excursion
7335 (and (org-get-next-sibling)
7336 (org-get-next-sibling)
7337 (org-get-next-sibling))
7338 (if (org-at-heading-p)
7339 (point-at-eol)
7340 (point))))
7341 (level (looking-at "\\*+"))
7342 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7343 (save-excursion
7344 (save-restriction
7345 (narrow-to-region beg end)
7346 (when re
7347 ;; Properly fold already folded siblings
7348 (goto-char (point-min))
7349 (while (re-search-forward re nil t)
7350 (when (and (not (org-invisible-p))
7351 (org-invisible-p (line-end-position)))
7352 (outline-hide-entry))))
7353 (org-cycle-hide-drawers 'all)
7354 (org-cycle-show-empty-lines 'overview)))))
7356 (defun org-cycle-show-empty-lines (state)
7357 "Show empty lines above all visible headlines.
7358 The region to be covered depends on STATE when called through
7359 `org-cycle-hook'. Lisp program can use t for STATE to get the
7360 entire buffer covered. Note that an empty line is only shown if there
7361 are at least `org-cycle-separator-lines' empty lines before the headline."
7362 (when (/= org-cycle-separator-lines 0)
7363 (save-excursion
7364 (let* ((n (abs org-cycle-separator-lines))
7365 (re (cond
7366 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7367 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7368 (t (let ((ns (number-to-string (- n 2))))
7369 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7370 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7371 beg end)
7372 (cond
7373 ((memq state '(overview contents t))
7374 (setq beg (point-min) end (point-max)))
7375 ((memq state '(children folded))
7376 (setq beg (point)
7377 end (progn (org-end-of-subtree t t)
7378 (line-beginning-position 2)))))
7379 (when beg
7380 (goto-char beg)
7381 (while (re-search-forward re end t)
7382 (unless (get-char-property (match-end 1) 'invisible)
7383 (let ((e (match-end 1))
7384 (b (if (>= org-cycle-separator-lines 0)
7385 (match-beginning 1)
7386 (save-excursion
7387 (goto-char (match-beginning 0))
7388 (skip-chars-backward " \t\n")
7389 (line-end-position)))))
7390 (org-flag-region b e nil 'outline))))))))
7391 ;; Never hide empty lines at the end of the file.
7392 (save-excursion
7393 (goto-char (point-max))
7394 (outline-previous-heading)
7395 (outline-end-of-heading)
7396 (when (and (looking-at "[ \t\n]+")
7397 (= (match-end 0) (point-max)))
7398 (org-flag-region (point) (match-end 0) nil 'outline))))
7400 ;;;; Reveal point location
7402 (defun org-show-context (&optional key)
7403 "Make sure point and context are visible.
7404 Optional argument KEY, when non-nil, is a symbol. See
7405 `org-show-context-detail' for allowed values and how much is to
7406 be shown."
7407 (org-show-set-visibility
7408 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7409 ((cdr (assq key org-show-context-detail)))
7410 (t (cdr (assq 'default org-show-context-detail))))))
7412 (defun org-show-set-visibility (detail)
7413 "Set visibility around point according to DETAIL.
7414 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7415 `tree', `canonical' or t. See `org-show-context-detail' for more
7416 information."
7417 ;; Show current heading and possibly its entry, following headline
7418 ;; or all children.
7419 (if (and (org-at-heading-p) (not (eq detail 'local)))
7420 (org-flag-heading nil)
7421 (org-show-entry)
7422 ;; If point is hidden within a drawer or a block, make sure to
7423 ;; expose it.
7424 (dolist (o (overlays-at (point)))
7425 (when (memq (overlay-get o 'invisible)
7426 '(org-hide-block org-hide-drawer outline))
7427 (delete-overlay o)))
7428 (unless (org-before-first-heading-p)
7429 (org-with-limited-levels
7430 (cl-case detail
7431 ((tree canonical t) (org-show-children))
7432 ((nil minimal ancestors))
7433 (t (save-excursion
7434 (outline-next-heading)
7435 (org-flag-heading nil)))))))
7436 ;; Show all siblings.
7437 (when (eq detail 'lineage) (org-show-siblings))
7438 ;; Show ancestors, possibly with their children.
7439 (when (memq detail '(ancestors lineage tree canonical t))
7440 (save-excursion
7441 (while (org-up-heading-safe)
7442 (org-flag-heading nil)
7443 (when (memq detail '(canonical t)) (org-show-entry))
7444 (when (memq detail '(tree canonical t)) (org-show-children))))))
7446 (defvar org-reveal-start-hook nil
7447 "Hook run before revealing a location.")
7449 (defun org-reveal (&optional siblings)
7450 "Show current entry, hierarchy above it, and the following headline.
7452 This can be used to show a consistent set of context around
7453 locations exposed with `org-show-context'.
7455 With optional argument SIBLINGS, on each level of the hierarchy all
7456 siblings are shown. This repairs the tree structure to what it would
7457 look like when opened with hierarchical calls to `org-cycle'.
7459 With a \\[universal-argument] \\[universal-argument] prefix, \
7460 go to the parent and show the entire tree."
7461 (interactive "P")
7462 (run-hooks 'org-reveal-start-hook)
7463 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7464 ((equal siblings '(16))
7465 (save-excursion
7466 (when (org-up-heading-safe)
7467 (org-show-subtree)
7468 (run-hook-with-args 'org-cycle-hook 'subtree))))
7469 (t (org-show-set-visibility 'lineage))))
7472 ;;; Indirect buffer display of subtrees
7474 (defvar org-indirect-dedicated-frame nil
7475 "This is the frame being used for indirect tree display.")
7476 (defvar org-last-indirect-buffer nil)
7478 (defun org-tree-to-indirect-buffer (&optional arg)
7479 "Create indirect buffer and narrow it to current subtree.
7481 With a numerical prefix ARG, go up to this level and then take that tree.
7482 If ARG is negative, go up that many levels.
7484 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7485 indirect buffer previously made with this command, to avoid proliferation of
7486 indirect buffers. However, when you call the command with a \
7487 `\\[universal-argument]' prefix, or
7488 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7489 so that you can work with several indirect buffers at the same time. If
7490 `org-indirect-buffer-display' is `dedicated-frame', the \
7491 `\\[universal-argument]' prefix also
7492 requests that a new frame be made for the new buffer, so that the dedicated
7493 frame is not changed."
7494 (interactive "P")
7495 (let ((cbuf (current-buffer))
7496 (cwin (selected-window))
7497 (pos (point))
7498 beg end level heading ibuf)
7499 (save-excursion
7500 (org-back-to-heading t)
7501 (when (numberp arg)
7502 (setq level (org-outline-level))
7503 (when (< arg 0) (setq arg (+ level arg)))
7504 (while (> (setq level (org-outline-level)) arg)
7505 (org-up-heading-safe)))
7506 (setq beg (point)
7507 heading (org-get-heading 'no-tags))
7508 (org-end-of-subtree t t)
7509 (when (org-at-heading-p) (backward-char 1))
7510 (setq end (point)))
7511 (when (and (buffer-live-p org-last-indirect-buffer)
7512 (not (eq org-indirect-buffer-display 'new-frame))
7513 (not arg))
7514 (kill-buffer org-last-indirect-buffer))
7515 (setq ibuf (org-get-indirect-buffer cbuf heading)
7516 org-last-indirect-buffer ibuf)
7517 (cond
7518 ((or (eq org-indirect-buffer-display 'new-frame)
7519 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7520 (select-frame (make-frame))
7521 (delete-other-windows)
7522 (pop-to-buffer-same-window ibuf)
7523 (org-set-frame-title heading))
7524 ((eq org-indirect-buffer-display 'dedicated-frame)
7525 (raise-frame
7526 (select-frame (or (and org-indirect-dedicated-frame
7527 (frame-live-p org-indirect-dedicated-frame)
7528 org-indirect-dedicated-frame)
7529 (setq org-indirect-dedicated-frame (make-frame)))))
7530 (delete-other-windows)
7531 (pop-to-buffer-same-window ibuf)
7532 (org-set-frame-title (concat "Indirect: " heading)))
7533 ((eq org-indirect-buffer-display 'current-window)
7534 (pop-to-buffer-same-window ibuf))
7535 ((eq org-indirect-buffer-display 'other-window)
7536 (pop-to-buffer ibuf))
7537 (t (error "Invalid value")))
7538 (narrow-to-region beg end)
7539 (org-show-all '(headings blocks))
7540 (goto-char pos)
7541 (run-hook-with-args 'org-cycle-hook 'all)
7542 (and (window-live-p cwin) (select-window cwin))))
7544 (defun org-get-indirect-buffer (&optional buffer heading)
7545 (setq buffer (or buffer (current-buffer)))
7546 (let ((n 1) (base (buffer-name buffer)) bname)
7547 (while (buffer-live-p
7548 (get-buffer
7549 (setq bname
7550 (concat base "-"
7551 (if heading (concat heading "-" (number-to-string n))
7552 (number-to-string n))))))
7553 (setq n (1+ n)))
7554 (condition-case nil
7555 (make-indirect-buffer buffer bname 'clone)
7556 (error (make-indirect-buffer buffer bname)))))
7558 (defun org-set-frame-title (title)
7559 "Set the title of the current frame to the string TITLE."
7560 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7562 ;;;; Structure editing
7564 ;;; Inserting headlines
7566 (defun org--line-empty-p (n)
7567 "Is the Nth next line empty?
7569 Counts the current line as N = 1 and the previous line as N = 0;
7570 see `beginning-of-line'."
7571 (save-excursion
7572 (and (not (bobp))
7573 (or (beginning-of-line n) t)
7574 (save-match-data
7575 (looking-at "[ \t]*$")))))
7577 (defun org-previous-line-empty-p ()
7578 "Is the previous line a blank line?
7579 When NEXT is non-nil, check the next line instead."
7580 (org--line-empty-p 0))
7582 (defun org-next-line-empty-p ()
7583 "Is the previous line a blank line?
7584 When NEXT is non-nil, check the next line instead."
7585 (org--line-empty-p 2))
7587 (defun org--blank-before-heading-p (&optional parent)
7588 "Non-nil when an empty line should precede a new heading here.
7589 When optional argument PARENT is non-nil, consider parent
7590 headline instead of current one."
7591 (pcase (assq 'heading org-blank-before-new-entry)
7592 (`(heading . auto)
7593 (save-excursion
7594 (org-with-limited-levels
7595 (unless (and (org-before-first-heading-p)
7596 (not (outline-next-heading)))
7597 (org-back-to-heading t)
7598 (when parent (org-up-heading-safe))
7599 (cond ((not (bobp))
7600 (org-previous-line-empty-p))
7601 ((outline-next-heading)
7602 (org-previous-line-empty-p))
7603 ;; Ignore trailing spaces on last buffer line.
7604 ((progn (skip-chars-backward " \t") (bolp))
7605 (org-previous-line-empty-p))
7606 (t nil))))))
7607 (`(heading . ,value) value)
7608 (_ nil)))
7610 (defun org-insert-heading (&optional arg invisible-ok top)
7611 "Insert a new heading or an item with the same depth at point.
7613 If point is at the beginning of a heading, insert a new heading
7614 or a new headline above the current one. When at the beginning
7615 of a regular line of text, turn it into a heading.
7617 If point is in the middle of a line, split it and create a new
7618 headline with the text in the current line after point (see
7619 `org-M-RET-may-split-line' on how to modify this behavior). As
7620 a special case, on a headline, splitting can only happen on the
7621 title itself. E.g., this excludes breaking stars or tags.
7623 With a `\\[universal-argument]' prefix, set \
7624 `org-insert-heading-respect-content' to
7625 a non-nil value for the duration of the command. This forces the
7626 insertion of a heading after the current subtree, independently
7627 on the location of point.
7629 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7630 insert the heading at the end of the tree
7631 above the current heading. For example, if point is within a
7632 2nd-level heading, then it will insert a 2nd-level heading at
7633 the end of the 1st-level parent subtree.
7635 When INVISIBLE-OK is set, stop at invisible headlines when going
7636 back. This is important for non-interactive uses of the
7637 command.
7639 When optional argument TOP is non-nil, insert a level 1 heading,
7640 unconditionally."
7641 (interactive "P")
7642 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7643 (level (org-current-level))
7644 (stars (make-string (if (and level (not top)) level 1) ?*)))
7645 (cond
7646 ((or org-insert-heading-respect-content
7647 (member arg '((4) (16)))
7648 (and (not invisible-ok)
7649 (invisible-p (max (1- (point)) (point-min)))))
7650 ;; Position point at the location of insertion. Make sure we
7651 ;; end up on a visible headline if INVISIBLE-OK is nil.
7652 (org-with-limited-levels
7653 (if (not level) (outline-next-heading) ;before first headline
7654 (org-back-to-heading invisible-ok)
7655 (when (equal arg '(16)) (org-up-heading-safe))
7656 (org-end-of-subtree)))
7657 (unless (bolp) (insert "\n"))
7658 (unless (and blank? (org-previous-line-empty-p))
7659 (org-N-empty-lines-before-current (if blank? 1 0)))
7660 (insert stars " ")
7661 (when (eobp) (save-excursion (insert "\n")))
7662 ;; When INVISIBLE-OK is non-nil, ensure newly created headline
7663 ;; is visible.
7664 (unless invisible-ok
7665 (pcase (get-char-property-and-overlay (point) 'invisible)
7666 (`(outline . ,o)
7667 (move-overlay o (overlay-start o) (line-end-position 0)))
7668 (_ nil))))
7669 ;; At a headline...
7670 ((org-at-heading-p)
7671 (cond ((bolp)
7672 (when blank? (save-excursion (insert "\n")))
7673 (save-excursion (insert stars " \n"))
7674 (unless (and blank? (org-previous-line-empty-p))
7675 (org-N-empty-lines-before-current (if blank? 1 0)))
7676 (end-of-line))
7677 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7678 (org-match-line org-complex-heading-regexp)
7679 (org-pos-in-match-range (point) 4))
7680 ;; Grab the text that should moved to the new headline.
7681 ;; Preserve tags.
7682 (let ((split (delete-and-extract-region (point) (match-end 4))))
7683 (if (looking-at "[ \t]*$") (replace-match "")
7684 (org-align-tags))
7685 (end-of-line)
7686 (when blank? (insert "\n"))
7687 (insert "\n" stars " ")
7688 (when (org-string-nw-p split) (insert split))
7689 (when (eobp) (save-excursion (insert "\n")))))
7691 (end-of-line)
7692 (when blank? (insert "\n"))
7693 (insert "\n" stars " ")
7694 (when (eobp) (save-excursion (insert "\n"))))))
7695 ;; On regular text, turn line into a headline or split, if
7696 ;; appropriate.
7697 ((bolp)
7698 (insert stars " ")
7699 (unless (and blank? (org-previous-line-empty-p))
7700 (org-N-empty-lines-before-current (if blank? 1 0))))
7702 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7703 (end-of-line))
7704 (insert "\n" stars " ")
7705 (unless (and blank? (org-previous-line-empty-p))
7706 (org-N-empty-lines-before-current (if blank? 1 0))))))
7707 (run-hooks 'org-insert-heading-hook))
7709 (defun org-N-empty-lines-before-current (n)
7710 "Make the number of empty lines before current exactly N.
7711 So this will delete or add empty lines."
7712 (let ((column (current-column)))
7713 (beginning-of-line)
7714 (unless (bobp)
7715 (let ((start (save-excursion
7716 (skip-chars-backward " \r\t\n")
7717 (line-end-position))))
7718 (delete-region start (line-end-position 0))))
7719 (insert (make-string n ?\n))
7720 (move-to-column column)))
7722 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7723 "Return the heading of the current entry, without the stars.
7724 When NO-TAGS is non-nil, don't include tags.
7725 When NO-TODO is non-nil, don't include TODO keywords.
7726 When NO-PRIORITY is non-nil, don't include priority cookie.
7727 When NO-COMMENT is non-nil, don't include COMMENT string.
7728 Return nil before first heading."
7729 (unless (org-before-first-heading-p)
7730 (save-excursion
7731 (org-back-to-heading t)
7732 (let ((case-fold-search nil))
7733 (looking-at org-complex-heading-regexp)
7734 (let ((todo (and (not no-todo) (match-string 2)))
7735 (priority (and (not no-priority) (match-string 3)))
7736 (headline (pcase (match-string 4)
7737 (`nil "")
7738 ((and (guard no-comment) h)
7739 (replace-regexp-in-string
7740 (eval-when-compile
7741 (format "\\`%s[ \t]+" org-comment-string))
7742 "" h))
7743 (h h)))
7744 (tags (and (not no-tags) (match-string 5))))
7745 (mapconcat #'identity
7746 (delq nil (list todo priority headline tags))
7747 " "))))))
7749 (defun org-heading-components ()
7750 "Return the components of the current heading.
7751 This is a list with the following elements:
7752 - the level as an integer
7753 - the reduced level, different if `org-odd-levels-only' is set.
7754 - the TODO keyword, or nil
7755 - the priority character, like ?A, or nil if no priority is given
7756 - the headline text itself, or the tags string if no headline text
7757 - the tags string, or nil."
7758 (save-excursion
7759 (org-back-to-heading t)
7760 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7761 (list (length (match-string 1))
7762 (org-reduced-level (length (match-string 1)))
7763 (match-string-no-properties 2)
7764 (and (match-end 3) (aref (match-string 3) 2))
7765 (match-string-no-properties 4)
7766 (match-string-no-properties 5)))))
7768 (defun org-get-entry ()
7769 "Get the entry text, after heading, entire subtree."
7770 (save-excursion
7771 (org-back-to-heading t)
7772 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7774 (defun org-edit-headline (&optional heading)
7775 "Edit the current headline.
7776 Set it to HEADING when provided."
7777 (interactive)
7778 (org-with-wide-buffer
7779 (org-back-to-heading t)
7780 (let ((case-fold-search nil))
7781 (when (looking-at org-complex-heading-regexp)
7782 (let* ((old (match-string-no-properties 4))
7783 (new (save-match-data
7784 (org-trim (or heading (read-string "Edit: " old))))))
7785 (unless (equal old new)
7786 (if old (replace-match new t t nil 4)
7787 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7788 (insert " " new))
7789 (org-align-tags)
7790 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7792 (defun org-insert-heading-after-current ()
7793 "Insert a new heading with same level as current, after current subtree."
7794 (interactive)
7795 (org-back-to-heading)
7796 (org-insert-heading)
7797 (org-move-subtree-down)
7798 (end-of-line 1))
7800 (defun org-insert-heading-respect-content (&optional invisible-ok)
7801 "Insert heading with `org-insert-heading-respect-content' set to t."
7802 (interactive)
7803 (org-insert-heading '(4) invisible-ok))
7805 (defun org-insert-todo-heading-respect-content (&optional force-state)
7806 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7807 (interactive)
7808 (org-insert-todo-heading force-state '(4)))
7810 (defun org-insert-todo-heading (arg &optional force-heading)
7811 "Insert a new heading with the same level and TODO state as current heading.
7813 If the heading has no TODO state, or if the state is DONE, use
7814 the first state (TODO by default). Also with one prefix arg,
7815 force first state. With two prefix args, force inserting at the
7816 end of the parent subtree.
7818 When called at a plain list item, insert a new item with an
7819 unchecked check box."
7820 (interactive "P")
7821 (when (or force-heading (not (org-insert-item 'checkbox)))
7822 (org-insert-heading (or (and (equal arg '(16)) '(16))
7823 force-heading))
7824 (save-excursion
7825 (org-forward-heading-same-level -1)
7826 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7827 (let* ((new-mark-x
7828 (if (or (equal arg '(4))
7829 (not (match-beginning 2))
7830 (member (match-string 2) org-done-keywords))
7831 (car org-todo-keywords-1)
7832 (match-string 2)))
7833 (new-mark
7835 (run-hook-with-args-until-success
7836 'org-todo-get-default-hook new-mark-x nil)
7837 new-mark-x)))
7838 (beginning-of-line 1)
7839 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7840 (if org-treat-insert-todo-heading-as-state-change
7841 (org-todo new-mark)
7842 (insert new-mark " "))))
7843 (when org-provide-todo-statistics
7844 (org-update-parent-todo-statistics))))
7846 (defun org-insert-subheading (arg)
7847 "Insert a new subheading and demote it.
7848 Works for outline headings and for plain lists alike."
7849 (interactive "P")
7850 (org-insert-heading arg)
7851 (cond
7852 ((org-at-heading-p) (org-do-demote))
7853 ((org-at-item-p) (org-indent-item))))
7855 (defun org-insert-todo-subheading (arg)
7856 "Insert a new subheading with TODO keyword or checkbox and demote it.
7857 Works for outline headings and for plain lists alike."
7858 (interactive "P")
7859 (org-insert-todo-heading arg)
7860 (cond
7861 ((org-at-heading-p) (org-do-demote))
7862 ((org-at-item-p) (org-indent-item))))
7864 ;;; Promotion and Demotion
7866 (defvar org-after-demote-entry-hook nil
7867 "Hook run after an entry has been demoted.
7868 The cursor will be at the beginning of the entry.
7869 When a subtree is being demoted, the hook will be called for each node.")
7871 (defvar org-after-promote-entry-hook nil
7872 "Hook run after an entry has been promoted.
7873 The cursor will be at the beginning of the entry.
7874 When a subtree is being promoted, the hook will be called for each node.")
7876 (defun org-promote-subtree ()
7877 "Promote the entire subtree.
7878 See also `org-promote'."
7879 (interactive)
7880 (save-excursion
7881 (org-with-limited-levels (org-map-tree 'org-promote)))
7882 (org-fix-position-after-promote))
7884 (defun org-demote-subtree ()
7885 "Demote the entire subtree.
7886 See `org-demote' and `org-promote'."
7887 (interactive)
7888 (save-excursion
7889 (org-with-limited-levels (org-map-tree 'org-demote)))
7890 (org-fix-position-after-promote))
7892 (defun org-do-promote ()
7893 "Promote the current heading higher up the tree.
7894 If the region is active in `transient-mark-mode', promote all
7895 headings in the region."
7896 (interactive)
7897 (save-excursion
7898 (if (org-region-active-p)
7899 (org-map-region 'org-promote (region-beginning) (region-end))
7900 (org-promote)))
7901 (org-fix-position-after-promote))
7903 (defun org-do-demote ()
7904 "Demote the current heading lower down the tree.
7905 If the region is active in `transient-mark-mode', demote all
7906 headings in the region."
7907 (interactive)
7908 (save-excursion
7909 (if (org-region-active-p)
7910 (org-map-region 'org-demote (region-beginning) (region-end))
7911 (org-demote)))
7912 (org-fix-position-after-promote))
7914 (defun org-fix-position-after-promote ()
7915 "Fix cursor position and indentation after demoting/promoting."
7916 (let ((pos (point)))
7917 (when (save-excursion
7918 (beginning-of-line)
7919 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7920 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7921 (cond ((eobp) (insert " "))
7922 ((eolp) (insert " "))
7923 ((equal (char-after) ?\s) (forward-char 1))))))
7925 (defun org-current-level ()
7926 "Return the level of the current entry, or nil if before the first headline.
7927 The level is the number of stars at the beginning of the
7928 headline. Use `org-reduced-level' to remove the effect of
7929 `org-odd-levels'. Unlike to `org-outline-level', this function
7930 ignores inlinetasks."
7931 (let ((level (org-with-limited-levels (org-outline-level))))
7932 (and (> level 0) level)))
7934 (defun org-get-previous-line-level ()
7935 "Return the outline depth of the last headline before the current line.
7936 Returns 0 for the first headline in the buffer, and nil if before the
7937 first headline."
7938 (and (org-current-level)
7939 (or (and (/= (line-beginning-position) (point-min))
7940 (save-excursion (beginning-of-line 0) (org-current-level)))
7941 0)))
7943 (defun org-reduced-level (l)
7944 "Compute the effective level of a heading.
7945 This takes into account the setting of `org-odd-levels-only'."
7946 (cond
7947 ((zerop l) 0)
7948 (org-odd-levels-only (1+ (floor (/ l 2))))
7949 (t l)))
7951 (defun org-level-increment ()
7952 "Return the number of stars that will be added or removed at a
7953 time to headlines when structure editing, based on the value of
7954 `org-odd-levels-only'."
7955 (if org-odd-levels-only 2 1))
7957 (defun org-get-valid-level (level &optional change)
7958 "Rectify a level change under the influence of `org-odd-levels-only'.
7959 LEVEL is a current level, CHANGE is by how much the level should
7960 be modified. Even if CHANGE is nil, LEVEL may be returned
7961 modified because even level numbers will become the next higher
7962 odd number. Returns values greater than 0."
7963 (if org-odd-levels-only
7964 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7965 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7966 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7967 (max 1 (+ level (or change 0)))))
7969 (defun org-promote ()
7970 "Promote the current heading higher up the tree."
7971 (org-with-wide-buffer
7972 (org-back-to-heading t)
7973 (let* ((after-change-functions (remq 'flyspell-after-change-function
7974 after-change-functions))
7975 (level (save-match-data (funcall outline-level)))
7976 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7977 (diff (abs (- level (length up-head) -1))))
7978 (cond
7979 ((and (= level 1) org-allow-promoting-top-level-subtree)
7980 (replace-match "# " nil t))
7981 ((= level 1)
7982 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7983 (t (replace-match up-head nil t)))
7984 (unless (= level 1)
7985 (when org-auto-align-tags (org-align-tags))
7986 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7987 (run-hooks 'org-after-promote-entry-hook))))
7989 (defun org-demote ()
7990 "Demote the current heading lower down the tree."
7991 (org-with-wide-buffer
7992 (org-back-to-heading t)
7993 (let* ((after-change-functions (remq 'flyspell-after-change-function
7994 after-change-functions))
7995 (level (save-match-data (funcall outline-level)))
7996 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7997 (diff (abs (- level (length down-head) -1))))
7998 (replace-match down-head nil t)
7999 (when org-auto-align-tags (org-align-tags))
8000 (when org-adapt-indentation (org-fixup-indentation diff))
8001 (run-hooks 'org-after-demote-entry-hook))))
8003 (defun org-cycle-level ()
8004 "Cycle the level of an empty headline through possible states.
8005 This goes first to child, then to parent, level, then up the hierarchy.
8006 After top level, it switches back to sibling level."
8007 (interactive)
8008 (let ((org-adapt-indentation nil))
8009 (when (org-point-at-end-of-empty-headline)
8010 (setq this-command 'org-cycle-level) ; Only needed for caching
8011 (let ((cur-level (org-current-level))
8012 (prev-level (org-get-previous-line-level)))
8013 (cond
8014 ;; If first headline in file, promote to top-level.
8015 ((= prev-level 0)
8016 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8017 do (org-do-promote)))
8018 ;; If same level as prev, demote one.
8019 ((= prev-level cur-level)
8020 (org-do-demote))
8021 ;; If parent is top-level, promote to top level if not already.
8022 ((= prev-level 1)
8023 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8024 do (org-do-promote)))
8025 ;; If top-level, return to prev-level.
8026 ((= cur-level 1)
8027 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8028 do (org-do-demote)))
8029 ;; If less than prev-level, promote one.
8030 ((< cur-level prev-level)
8031 (org-do-promote))
8032 ;; If deeper than prev-level, promote until higher than
8033 ;; prev-level.
8034 ((> cur-level prev-level)
8035 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8036 do (org-do-promote))))
8037 t))))
8039 (defun org-map-tree (fun)
8040 "Call FUN for every heading underneath the current one."
8041 (org-back-to-heading t)
8042 (let ((level (funcall outline-level)))
8043 (save-excursion
8044 (funcall fun)
8045 (while (and (progn
8046 (outline-next-heading)
8047 (> (funcall outline-level) level))
8048 (not (eobp)))
8049 (funcall fun)))))
8051 (defun org-map-region (fun beg end)
8052 "Call FUN for every heading between BEG and END."
8053 (let ((org-ignore-region t))
8054 (save-excursion
8055 (setq end (copy-marker end))
8056 (goto-char beg)
8057 (when (and (re-search-forward org-outline-regexp-bol nil t)
8058 (< (point) end))
8059 (funcall fun))
8060 (while (and (progn
8061 (outline-next-heading)
8062 (< (point) end))
8063 (not (eobp)))
8064 (funcall fun)))))
8066 (defun org-fixup-indentation (diff)
8067 "Change the indentation in the current entry by DIFF.
8069 DIFF is an integer. Indentation is done according to the
8070 following rules:
8072 - Planning information and property drawers are always indented
8073 according to the new level of the headline;
8075 - Footnote definitions and their contents are ignored;
8077 - Inlinetasks' boundaries are not shifted;
8079 - Empty lines are ignored;
8081 - Other lines' indentation are shifted by DIFF columns, unless
8082 it would introduce a structural change in the document, in
8083 which case no shifting is done at all.
8085 Assume point is at a heading or an inlinetask beginning."
8086 (org-with-wide-buffer
8087 (narrow-to-region (line-beginning-position)
8088 (save-excursion
8089 (if (org-with-limited-levels (org-at-heading-p))
8090 (org-with-limited-levels (outline-next-heading))
8091 (org-inlinetask-goto-end))
8092 (point)))
8093 (forward-line)
8094 ;; Indent properly planning info and property drawer.
8095 (when (looking-at-p org-planning-line-re)
8096 (org-indent-line)
8097 (forward-line))
8098 (when (looking-at org-property-drawer-re)
8099 (goto-char (match-end 0))
8100 (forward-line)
8101 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8102 (catch 'no-shift
8103 (when (zerop diff) (throw 'no-shift nil))
8104 ;; If DIFF is negative, first check if a shift is possible at all
8105 ;; (e.g., it doesn't break structure). This can only happen if
8106 ;; some contents are not properly indented.
8107 (let ((case-fold-search t))
8108 (when (< diff 0)
8109 (let ((diff (- diff))
8110 (forbidden-re (concat org-outline-regexp
8111 "\\|"
8112 (substring org-footnote-definition-re 1))))
8113 (save-excursion
8114 (while (not (eobp))
8115 (cond
8116 ((looking-at-p "[ \t]*$") (forward-line))
8117 ((and (looking-at-p org-footnote-definition-re)
8118 (let ((e (org-element-at-point)))
8119 (and (eq (org-element-type e) 'footnote-definition)
8120 (goto-char (org-element-property :end e))))))
8121 ((looking-at-p org-outline-regexp) (forward-line))
8122 ;; Give up if shifting would move before column 0 or
8123 ;; if it would introduce a headline or a footnote
8124 ;; definition.
8126 (skip-chars-forward " \t")
8127 (let ((ind (current-column)))
8128 (when (or (< ind diff)
8129 (and (= ind diff) (looking-at-p forbidden-re)))
8130 (throw 'no-shift nil)))
8131 ;; Ignore contents of example blocks and source
8132 ;; blocks if their indentation is meant to be
8133 ;; preserved. Jump to block's closing line.
8134 (beginning-of-line)
8135 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8136 (let ((e (org-element-at-point)))
8137 (and (memq (org-element-type e)
8138 '(example-block src-block))
8139 (or org-src-preserve-indentation
8140 (org-element-property :preserve-indent e))
8141 (goto-char (org-element-property :end e))
8142 (progn (skip-chars-backward " \r\t\n")
8143 (beginning-of-line)
8144 t))))
8145 (forward-line))))))))
8146 ;; Shift lines but footnote definitions, inlinetasks boundaries
8147 ;; by DIFF. Also skip contents of source or example blocks
8148 ;; when indentation is meant to be preserved.
8149 (while (not (eobp))
8150 (cond
8151 ((and (looking-at-p org-footnote-definition-re)
8152 (let ((e (org-element-at-point)))
8153 (and (eq (org-element-type e) 'footnote-definition)
8154 (goto-char (org-element-property :end e))))))
8155 ((looking-at-p org-outline-regexp) (forward-line))
8156 ((looking-at-p "[ \t]*$") (forward-line))
8158 (indent-line-to (+ (current-indentation) diff))
8159 (beginning-of-line)
8160 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8161 (let ((e (org-element-at-point)))
8162 (and (memq (org-element-type e)
8163 '(example-block src-block))
8164 (or org-src-preserve-indentation
8165 (org-element-property :preserve-indent e))
8166 (goto-char (org-element-property :end e))
8167 (progn (skip-chars-backward " \r\t\n")
8168 (beginning-of-line)
8169 t))))
8170 (forward-line)))))))))
8172 (defun org-convert-to-odd-levels ()
8173 "Convert an Org file with all levels allowed to one with odd levels.
8174 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8175 level 5 etc."
8176 (interactive)
8177 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8178 (let ((outline-level 'org-outline-level)
8179 (org-odd-levels-only nil) n)
8180 (save-excursion
8181 (goto-char (point-min))
8182 (while (re-search-forward "^\\*\\*+ " nil t)
8183 (setq n (- (length (match-string 0)) 2))
8184 (while (>= (setq n (1- n)) 0)
8185 (org-demote))
8186 (end-of-line 1))))))
8188 (defun org-convert-to-oddeven-levels ()
8189 "Convert an Org file with only odd levels to one with odd/even levels.
8190 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8191 file contains a section with an even level, conversion would
8192 destroy the structure of the file. An error is signaled in this
8193 case."
8194 (interactive)
8195 (goto-char (point-min))
8196 ;; First check if there are no even levels
8197 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8198 (org-show-set-visibility 'canonical)
8199 (error "Not all levels are odd in this file. Conversion not possible"))
8200 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8201 (let ((outline-regexp org-outline-regexp)
8202 (outline-level 'org-outline-level)
8203 (org-odd-levels-only nil) n)
8204 (save-excursion
8205 (goto-char (point-min))
8206 (while (re-search-forward "^\\*\\*+ " nil t)
8207 (setq n (/ (1- (length (match-string 0))) 2))
8208 (while (>= (setq n (1- n)) 0)
8209 (org-promote))
8210 (end-of-line 1))))))
8212 (defun org-tr-level (n)
8213 "Make N odd if required."
8214 (if org-odd-levels-only (1+ (/ n 2)) n))
8216 ;;; Vertical tree motion, cutting and pasting of subtrees
8218 (defun org-move-subtree-up (&optional arg)
8219 "Move the current subtree up past ARG headlines of the same level."
8220 (interactive "p")
8221 (org-move-subtree-down (- (prefix-numeric-value arg))))
8223 (defun org-move-subtree-down (&optional arg)
8224 "Move the current subtree down past ARG headlines of the same level."
8225 (interactive "p")
8226 (setq arg (prefix-numeric-value arg))
8227 (org-preserve-local-variables
8228 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8229 'org-get-last-sibling))
8230 (ins-point (make-marker))
8231 (cnt (abs arg))
8232 (col (current-column))
8233 beg end txt folded)
8234 ;; Select the tree
8235 (org-back-to-heading)
8236 (setq beg (point))
8237 (save-match-data
8238 (save-excursion (outline-end-of-heading)
8239 (setq folded (org-invisible-p)))
8240 (progn (org-end-of-subtree nil t)
8241 (unless (eobp) (backward-char))))
8242 (outline-next-heading)
8243 (setq end (point))
8244 (goto-char beg)
8245 ;; Find insertion point, with error handling
8246 (while (> cnt 0)
8247 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8248 (goto-char beg)
8249 (user-error "Cannot move past superior level or buffer limit"))
8250 (setq cnt (1- cnt)))
8251 (when (> arg 0)
8252 ;; Moving forward - still need to move over subtree
8253 (org-end-of-subtree t t)
8254 (save-excursion
8255 (org-back-over-empty-lines)
8256 (or (bolp) (newline))))
8257 (move-marker ins-point (point))
8258 (setq txt (buffer-substring beg end))
8259 (org-save-markers-in-region beg end)
8260 (delete-region beg end)
8261 (org-remove-empty-overlays-at beg)
8262 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8263 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8264 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8265 (let ((bbb (point)))
8266 (insert-before-markers txt)
8267 (org-reinstall-markers-in-region bbb)
8268 (move-marker ins-point bbb))
8269 (or (bolp) (insert "\n"))
8270 (goto-char ins-point)
8271 (org-skip-whitespace)
8272 (move-marker ins-point nil)
8273 (if folded
8274 (outline-hide-subtree)
8275 (org-show-entry)
8276 (org-show-children))
8277 (org-clean-visibility-after-subtree-move)
8278 ;; move back to the initial column we were at
8279 (move-to-column col))))
8281 (defvar org-subtree-clip ""
8282 "Clipboard for cut and paste of subtrees.
8283 This is actually only a copy of the kill, because we use the normal kill
8284 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8286 (defvar org-subtree-clip-folded nil
8287 "Was the last copied subtree folded?
8288 This is used to fold the tree back after pasting.")
8290 (defun org-cut-subtree (&optional n)
8291 "Cut the current subtree into the clipboard.
8292 With prefix arg N, cut this many sequential subtrees.
8293 This is a short-hand for marking the subtree and then cutting it."
8294 (interactive "p")
8295 (org-copy-subtree n 'cut))
8297 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8298 "Copy the current subtree into the clipboard.
8299 With prefix arg N, copy this many sequential subtrees.
8300 This is a short-hand for marking the subtree and then copying it.
8301 If CUT is non-nil, actually cut the subtree.
8302 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8303 of some markers in the region, even if CUT is non-nil. This is
8304 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8305 (interactive "p")
8306 (org-preserve-local-variables
8307 (let (beg end folded (beg0 (point)))
8308 (if (called-interactively-p 'any)
8309 (org-back-to-heading nil) ; take what looks like a subtree
8310 (org-back-to-heading t)) ; take what is really there
8311 (setq beg (point))
8312 (skip-chars-forward " \t\r\n")
8313 (save-match-data
8314 (if nosubtrees
8315 (outline-next-heading)
8316 (save-excursion (outline-end-of-heading)
8317 (setq folded (org-invisible-p)))
8318 (ignore-errors (org-forward-heading-same-level (1- n) t))
8319 (org-end-of-subtree t t)))
8320 ;; Include the end of an inlinetask
8321 (when (and (featurep 'org-inlinetask)
8322 (looking-at-p (concat (org-inlinetask-outline-regexp)
8323 "END[ \t]*$")))
8324 (end-of-line))
8325 (setq end (point))
8326 (goto-char beg0)
8327 (when (> end beg)
8328 (setq org-subtree-clip-folded folded)
8329 (when (or cut force-store-markers)
8330 (org-save-markers-in-region beg end))
8331 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8332 (setq org-subtree-clip (current-kill 0))
8333 (message "%s: Subtree(s) with %d characters"
8334 (if cut "Cut" "Copied")
8335 (length org-subtree-clip))))))
8337 (defun org-paste-subtree (&optional level tree for-yank remove)
8338 "Paste the clipboard as a subtree, with modification of headline level.
8340 The entire subtree is promoted or demoted in order to match a new headline
8341 level.
8343 If the cursor is at the beginning of a headline, the same level as
8344 that headline is used to paste the tree.
8346 If not, the new level is derived from the *visible* headings
8347 before and after the insertion point, and taken to be the inferior headline
8348 level of the two. So if the previous visible heading is level 3 and the
8349 next is level 4 (or vice versa), level 4 will be used for insertion.
8350 This makes sure that the subtree remains an independent subtree and does
8351 not swallow low level entries.
8353 You can also force a different level, either by using a numeric prefix
8354 argument, or by inserting the heading marker by hand. For example, if the
8355 cursor is after \"*****\", then the tree will be shifted to level 5.
8357 If optional TREE is given, use this text instead of the kill ring.
8359 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8360 move back over whitespace before inserting, and move point to the end of
8361 the inserted text when done.
8363 When REMOVE is non-nil, remove the subtree from the clipboard."
8364 (interactive "P")
8365 (setq tree (or tree (and kill-ring (current-kill 0))))
8366 (unless (org-kill-is-subtree-p tree)
8367 (user-error
8368 (substitute-command-keys
8369 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8370 (org-with-limited-levels
8371 (let* ((visp (not (org-invisible-p)))
8372 (txt tree)
8373 (old-level (if (string-match org-outline-regexp-bol txt)
8374 (- (match-end 0) (match-beginning 0) 1)
8375 -1))
8376 (force-level
8377 (cond
8378 (level (prefix-numeric-value level))
8379 ;; When point is after the stars in an otherwise empty
8380 ;; headline, use the number of stars as the forced level.
8381 ((and (org-match-line "^\\*+[ \t]*$")
8382 (not (eq ?* (char-after))))
8383 (org-outline-level))
8384 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8385 (previous-level
8386 (save-excursion
8387 (org-previous-visible-heading 1)
8388 (if (org-at-heading-p) (org-outline-level) 1)))
8389 (next-level
8390 (save-excursion
8391 (if (org-at-heading-p) (org-outline-level)
8392 (org-next-visible-heading 1)
8393 (if (org-at-heading-p) (org-outline-level) 1))))
8394 (new-level (or force-level (max previous-level next-level)))
8395 (shift (if (or (= old-level -1)
8396 (= new-level -1)
8397 (= old-level new-level))
8399 (- new-level old-level)))
8400 (delta (if (> shift 0) -1 1))
8401 (func (if (> shift 0) #'org-demote #'org-promote))
8402 (org-odd-levels-only nil)
8403 beg end newend)
8404 ;; Remove the forced level indicator.
8405 (when (and force-level (not level))
8406 (delete-region (line-beginning-position) (point)))
8407 ;; Paste before the next visible heading or at end of buffer,
8408 ;; unless point is at the beginning of a headline.
8409 (unless (and (bolp) (org-at-heading-p))
8410 (org-next-visible-heading 1)
8411 (unless (bolp) (insert "\n")))
8412 (setq beg (point))
8413 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8414 (insert-before-markers txt)
8415 (unless (string-suffix-p "\n" txt) (insert "\n"))
8416 (setq newend (point))
8417 (org-reinstall-markers-in-region beg)
8418 (setq end (point))
8419 (goto-char beg)
8420 (skip-chars-forward " \t\n\r")
8421 (setq beg (point))
8422 (when (and (org-invisible-p) visp)
8423 (save-excursion (outline-show-heading)))
8424 ;; Shift if necessary.
8425 (unless (= shift 0)
8426 (save-restriction
8427 (narrow-to-region beg end)
8428 (while (not (= shift 0))
8429 (org-map-region func (point-min) (point-max))
8430 (setq shift (+ delta shift)))
8431 (goto-char (point-min))
8432 (setq newend (point-max))))
8433 (when (or for-yank (called-interactively-p 'interactive))
8434 (message "Clipboard pasted as level %d subtree" new-level))
8435 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8436 kill-ring
8437 (equal org-subtree-clip (current-kill 0))
8438 org-subtree-clip-folded)
8439 ;; The tree was folded before it was killed/copied
8440 (outline-hide-subtree))
8441 (when for-yank (goto-char newend))
8442 (when remove (pop kill-ring)))))
8444 (defun org-kill-is-subtree-p (&optional txt)
8445 "Check if the current kill is an outline subtree, or a set of trees.
8446 Returns nil if kill does not start with a headline, or if the first
8447 headline level is not the largest headline level in the tree.
8448 So this will actually accept several entries of equal levels as well,
8449 which is OK for `org-paste-subtree'.
8450 If optional TXT is given, check this string instead of the current kill."
8451 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8452 (re (org-get-limited-outline-regexp))
8453 (^re (concat "^" re))
8454 (start-level (and kill
8455 (string-match
8456 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8457 kill)
8458 (- (match-end 2) (match-beginning 2) 1)))
8459 (start (1+ (or (match-beginning 2) -1))))
8460 (if (not start-level)
8461 (progn
8462 nil) ;; does not even start with a heading
8463 (catch 'exit
8464 (while (setq start (string-match ^re kill (1+ start)))
8465 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8466 (throw 'exit nil)))
8467 t))))
8469 (defvar org-markers-to-move nil
8470 "Markers that should be moved with a cut-and-paste operation.
8471 Those markers are stored together with their positions relative to
8472 the start of the region.")
8474 (defun org-save-markers-in-region (beg end)
8475 "Check markers in region.
8476 If these markers are between BEG and END, record their position relative
8477 to BEG, so that after moving the block of text, we can put the markers back
8478 into place.
8479 This function gets called just before an entry or tree gets cut from the
8480 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8481 called immediately, to move the markers with the entries."
8482 (setq org-markers-to-move nil)
8483 (when (featurep 'org-clock)
8484 (org-clock-save-markers-for-cut-and-paste beg end))
8485 (when (featurep 'org-agenda)
8486 (org-agenda-save-markers-for-cut-and-paste beg end)))
8488 (defun org-check-and-save-marker (marker beg end)
8489 "Check if MARKER is between BEG and END.
8490 If yes, remember the marker and the distance to BEG."
8491 (when (and (marker-buffer marker)
8492 (equal (marker-buffer marker) (current-buffer))
8493 (>= marker beg) (< marker end))
8494 (push (cons marker (- marker beg)) org-markers-to-move)))
8496 (defun org-reinstall-markers-in-region (beg)
8497 "Move all remembered markers to their position relative to BEG."
8498 (dolist (x org-markers-to-move)
8499 (move-marker (car x) (+ beg (cdr x))))
8500 (setq org-markers-to-move nil))
8502 (defun org-narrow-to-subtree ()
8503 "Narrow buffer to the current subtree."
8504 (interactive)
8505 (save-excursion
8506 (save-match-data
8507 (org-with-limited-levels
8508 (narrow-to-region
8509 (progn (org-back-to-heading t) (point))
8510 (progn (org-end-of-subtree t t)
8511 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8512 (point)))))))
8514 (defun org-toggle-narrow-to-subtree ()
8515 "Narrow to the subtree at point or widen a narrowed buffer."
8516 (interactive)
8517 (if (buffer-narrowed-p)
8518 (widen)
8519 (org-narrow-to-subtree)))
8521 (defun org-narrow-to-block ()
8522 "Narrow buffer to the current block."
8523 (interactive)
8524 (let* ((case-fold-search t)
8525 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8526 "^[ \t]*#\\+end_.*")))
8527 (if blockp
8528 (narrow-to-region (car blockp) (cdr blockp))
8529 (user-error "Not in a block"))))
8531 (defun org-clone-subtree-with-time-shift (n &optional shift)
8532 "Clone the task (subtree) at point N times.
8533 The clones will be inserted as siblings.
8535 In interactive use, the user will be prompted for the number of
8536 clones to be produced. If the entry has a timestamp, the user
8537 will also be prompted for a time shift, which may be a repeater
8538 as used in time stamps, for example `+3d'. To disable this,
8539 you can call the function with a universal prefix argument.
8541 When a valid repeater is given and the entry contains any time
8542 stamps, the clones will become a sequence in time, with time
8543 stamps in the subtree shifted for each clone produced. If SHIFT
8544 is nil or the empty string, time stamps will be left alone. The
8545 ID property of the original subtree is removed.
8547 In each clone, all the CLOCK entries will be removed. This
8548 prevents Org from considering that the clocked times overlap.
8550 If the original subtree did contain time stamps with a repeater,
8551 the following will happen:
8552 - the repeater will be removed in each clone
8553 - an additional clone will be produced, with the current, unshifted
8554 date(s) in the entry.
8555 - the original entry will be placed *after* all the clones, with
8556 repeater intact.
8557 - the start days in the repeater in the original entry will be shifted
8558 to past the last clone.
8559 In this way you can spell out a number of instances of a repeating task,
8560 and still retain the repeater to cover future instances of the task.
8562 As described above, N+1 clones are produced when the original
8563 subtree has a repeater. Setting N to 0, then, can be used to
8564 remove the repeater from a subtree and create a shifted clone
8565 with the original repeater."
8566 (interactive "nNumber of clones to produce: ")
8567 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8568 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8569 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8570 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8571 (shift
8572 (or shift
8573 (if (and (not (equal current-prefix-arg '(4)))
8574 (save-excursion
8575 (goto-char beg)
8576 (re-search-forward org-ts-regexp-both end-of-tree t)))
8577 (read-from-minibuffer
8578 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8579 ""))) ;No time shift
8580 (doshift
8581 (and (org-string-nw-p shift)
8582 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8583 shift)
8584 (user-error "Invalid shift specification %s" shift)))))
8585 (goto-char end-of-tree)
8586 (unless (bolp) (insert "\n"))
8587 (let* ((end (point))
8588 (template (buffer-substring beg end))
8589 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8590 (shift-what (pcase (and doshift (match-string 2 shift))
8591 (`nil nil)
8592 ("d" 'day)
8593 ("w" (setq shift-n (* 7 shift-n)) 'day)
8594 ("m" 'month)
8595 ("y" 'year)
8596 (_ (error "Unsupported time unit"))))
8597 (nmin 1)
8598 (nmax n)
8599 (n-no-remove -1)
8600 (idprop (org-entry-get nil "ID")))
8601 (when (and doshift
8602 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8603 template))
8604 (delete-region beg end)
8605 (setq end beg)
8606 (setq nmin 0)
8607 (setq nmax (1+ nmax))
8608 (setq n-no-remove nmax))
8609 (goto-char end)
8610 (cl-loop for n from nmin to nmax do
8611 (insert
8612 ;; Prepare clone.
8613 (with-temp-buffer
8614 (insert template)
8615 (org-mode)
8616 (goto-char (point-min))
8617 (org-show-subtree)
8618 (and idprop (if org-clone-delete-id
8619 (org-entry-delete nil "ID")
8620 (org-id-get-create t)))
8621 (unless (= n 0)
8622 (while (re-search-forward org-clock-line-re nil t)
8623 (delete-region (line-beginning-position)
8624 (line-beginning-position 2)))
8625 (goto-char (point-min))
8626 (while (re-search-forward org-drawer-regexp nil t)
8627 (org-remove-empty-drawer-at (point))))
8628 (goto-char (point-min))
8629 (when doshift
8630 (while (re-search-forward org-ts-regexp-both nil t)
8631 (org-timestamp-change (* n shift-n) shift-what))
8632 (unless (= n n-no-remove)
8633 (goto-char (point-min))
8634 (while (re-search-forward org-ts-regexp nil t)
8635 (save-excursion
8636 (goto-char (match-beginning 0))
8637 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8638 (delete-region (match-beginning 1) (match-end 1)))))))
8639 (buffer-string)))))
8640 (goto-char beg)))
8642 ;;; Outline Sorting
8644 (defun org-sort (&optional with-case)
8645 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8646 Optional argument WITH-CASE means sort case-sensitively."
8647 (interactive "P")
8648 (org-call-with-arg
8649 (cond ((org-at-table-p) #'org-table-sort-lines)
8650 ((org-at-item-p) #'org-sort-list)
8651 (t #'org-sort-entries))
8652 with-case))
8654 (defun org-sort-remove-invisible (s)
8655 "Remove invisible part of links and emphasis markers from string S."
8656 (remove-text-properties 0 (length s) org-rm-props s)
8657 (replace-regexp-in-string
8658 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8659 (replace-regexp-in-string
8660 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8661 (org-link-display-format s)
8662 t t) t t))
8664 (defvar org-priority-regexp) ; defined later in the file
8666 (defvar org-after-sorting-entries-or-items-hook nil
8667 "Hook that is run after a bunch of entries or items have been sorted.
8668 When children are sorted, the cursor is in the parent line when this
8669 hook gets called. When a region or a plain list is sorted, the cursor
8670 will be in the first entry of the sorted region/list.")
8672 (defun org-sort-entries
8673 (&optional with-case sorting-type getkey-func compare-func property
8674 interactive?)
8675 "Sort entries on a certain level of an outline tree.
8676 If there is an active region, the entries in the region are sorted.
8677 Else, if the cursor is before the first entry, sort the top-level items.
8678 Else, the children of the entry at point are sorted.
8680 Sorting can be alphabetically, numerically, by date/time as given by
8681 a time stamp, by a property, by priority order, or by a custom function.
8683 The command prompts for the sorting type unless it has been given to the
8684 function through the SORTING-TYPE argument, which needs to be a character,
8685 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8686 the precise meaning of each character:
8688 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8689 c By creation time, which is assumed to be the first inactive time stamp
8690 at the beginning of a line.
8691 d By deadline date/time.
8692 k By clocking time.
8693 n Numerically, by converting the beginning of the entry/item to a number.
8694 o By order of TODO keywords.
8695 p By priority according to the cookie.
8696 r By the value of a property.
8697 s By scheduled date/time.
8698 t By date/time, either the first active time stamp in the entry, or, if
8699 none exist, by the first inactive one.
8701 Capital letters will reverse the sort order.
8703 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8704 called with point at the beginning of the record. It must return a
8705 value that is compatible with COMPARE-FUNC, the function used to
8706 compare entries.
8708 Comparing entries ignores case by default. However, with an optional argument
8709 WITH-CASE, the sorting considers case as well.
8711 Sorting is done against the visible part of the headlines, it ignores hidden
8712 links.
8714 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8716 A non-nil value for INTERACTIVE? is used to signal that this
8717 function is being called interactively."
8718 (interactive (list current-prefix-arg nil nil nil nil t))
8719 (let ((case-func (if with-case 'identity 'downcase))
8720 start beg end stars re re2
8721 txt what tmp)
8722 ;; Find beginning and end of region to sort
8723 (cond
8724 ((org-region-active-p)
8725 ;; we will sort the region
8726 (setq end (region-end)
8727 what "region")
8728 (goto-char (region-beginning))
8729 (unless (org-at-heading-p) (outline-next-heading))
8730 (setq start (point)))
8731 ((or (org-at-heading-p)
8732 (ignore-errors (progn (org-back-to-heading) t)))
8733 ;; we will sort the children of the current headline
8734 (org-back-to-heading)
8735 (setq start (point)
8736 end (progn (org-end-of-subtree t t)
8737 (or (bolp) (insert "\n"))
8738 (when (>= (org-back-over-empty-lines) 1)
8739 (forward-line 1))
8740 (point))
8741 what "children")
8742 (goto-char start)
8743 (outline-show-subtree)
8744 (outline-next-heading))
8746 ;; we will sort the top-level entries in this file
8747 (goto-char (point-min))
8748 (or (org-at-heading-p) (outline-next-heading))
8749 (setq start (point))
8750 (goto-char (point-max))
8751 (beginning-of-line 1)
8752 (when (looking-at ".*?\\S-")
8753 ;; File ends in a non-white line
8754 (end-of-line 1)
8755 (insert "\n"))
8756 (setq end (point-max))
8757 (setq what "top-level")
8758 (goto-char start)
8759 (org-show-all '(headings blocks))))
8761 (setq beg (point))
8762 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8764 (looking-at "\\(\\*+\\)")
8765 (setq stars (match-string 1)
8766 re (concat "^" (regexp-quote stars) " +")
8767 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8768 txt (buffer-substring beg end))
8769 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8770 (when (and (not (equal stars "*")) (string-match re2 txt))
8771 (user-error "Region to sort contains a level above the first entry"))
8773 (unless sorting-type
8774 (message
8775 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8776 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8777 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8778 what)
8779 (setq sorting-type (read-char-exclusive)))
8781 (unless getkey-func
8782 (and (= (downcase sorting-type) ?f)
8783 (setq getkey-func
8784 (or (and interactive?
8785 (org-read-function
8786 "Function for extracting keys: "))
8787 (error "Missing key extractor")))))
8789 (and (= (downcase sorting-type) ?r)
8790 (not property)
8791 (setq property
8792 (completing-read "Property: "
8793 (mapcar #'list (org-buffer-property-keys t))
8794 nil t)))
8796 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8797 (message "Sorting entries...")
8799 (save-restriction
8800 (narrow-to-region start end)
8801 (let ((restore-clock?
8802 ;; The clock marker is lost when using `sort-subr'; mark
8803 ;; the clock with temporary `:org-clock-marker-backup'
8804 ;; text property.
8805 (when (and (eq (org-clock-is-active) (current-buffer))
8806 (<= start (marker-position org-clock-marker))
8807 (>= end (marker-position org-clock-marker)))
8808 (with-silent-modifications
8809 (put-text-property (1- org-clock-marker) org-clock-marker
8810 :org-clock-marker-backup t))
8812 (dcst (downcase sorting-type))
8813 (case-fold-search nil)
8814 (now (current-time)))
8815 (org-preserve-local-variables
8816 (sort-subr
8817 (/= dcst sorting-type)
8818 ;; This function moves to the beginning character of the
8819 ;; "record" to be sorted.
8820 (lambda nil
8821 (if (re-search-forward re nil t)
8822 (goto-char (match-beginning 0))
8823 (goto-char (point-max))))
8824 ;; This function moves to the last character of the "record" being
8825 ;; sorted.
8826 (lambda nil
8827 (save-match-data
8828 (condition-case nil
8829 (outline-forward-same-level 1)
8830 (error
8831 (goto-char (point-max))))))
8832 ;; This function returns the value that gets sorted against.
8833 (lambda ()
8834 (cond
8835 ((= dcst ?n)
8836 (string-to-number
8837 (org-sort-remove-invisible (org-get-heading t t t t))))
8838 ((= dcst ?a)
8839 (funcall case-func
8840 (org-sort-remove-invisible (org-get-heading t t t t))))
8841 ((= dcst ?k)
8842 (or (get-text-property (point) :org-clock-minutes) 0))
8843 ((= dcst ?t)
8844 (let ((end (save-excursion (outline-next-heading) (point))))
8845 (if (or (re-search-forward org-ts-regexp end t)
8846 (re-search-forward org-ts-regexp-both end t))
8847 (org-time-string-to-seconds (match-string 0))
8848 (float-time now))))
8849 ((= dcst ?c)
8850 (let ((end (save-excursion (outline-next-heading) (point))))
8851 (if (re-search-forward
8852 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8853 end t)
8854 (org-time-string-to-seconds (match-string 0))
8855 (float-time now))))
8856 ((= dcst ?s)
8857 (let ((end (save-excursion (outline-next-heading) (point))))
8858 (if (re-search-forward org-scheduled-time-regexp end t)
8859 (org-time-string-to-seconds (match-string 1))
8860 (float-time now))))
8861 ((= dcst ?d)
8862 (let ((end (save-excursion (outline-next-heading) (point))))
8863 (if (re-search-forward org-deadline-time-regexp end t)
8864 (org-time-string-to-seconds (match-string 1))
8865 (float-time now))))
8866 ((= dcst ?p)
8867 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8868 (string-to-char (match-string 2))
8869 org-default-priority))
8870 ((= dcst ?r)
8871 (or (org-entry-get nil property) ""))
8872 ((= dcst ?o)
8873 (when (looking-at org-complex-heading-regexp)
8874 (let* ((m (match-string 2))
8875 (s (if (member m org-done-keywords) '- '+)))
8876 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8877 ((= dcst ?f)
8878 (if getkey-func
8879 (progn
8880 (setq tmp (funcall getkey-func))
8881 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8882 tmp)
8883 (error "Invalid key function `%s'" getkey-func)))
8884 (t (error "Invalid sorting type `%c'" sorting-type))))
8886 (cond
8887 ((= dcst ?a) 'org-string-collate-lessp)
8888 ((= dcst ?f)
8889 (or compare-func
8890 (and interactive?
8891 (org-read-function
8892 (concat "Function for comparing keys "
8893 "(empty for default `sort-subr' predicate): ")
8894 'allow-empty))))
8895 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8896 (when restore-clock?
8897 (move-marker org-clock-marker
8898 (1+ (next-single-property-change
8899 start :org-clock-marker-backup)))
8900 (remove-text-properties (1- org-clock-marker) org-clock-marker
8901 '(:org-clock-marker-backup t)))))
8902 (run-hooks 'org-after-sorting-entries-or-items-hook)
8903 (message "Sorting entries...done")))
8905 (defun org-contextualize-keys (alist contexts)
8906 "Return valid elements in ALIST depending on CONTEXTS.
8908 `org-agenda-custom-commands' or `org-capture-templates' are the
8909 values used for ALIST, and `org-agenda-custom-commands-contexts'
8910 or `org-capture-templates-contexts' are the associated contexts
8911 definitions."
8912 (let ((contexts
8913 ;; normalize contexts
8914 (mapcar
8915 (lambda(c) (cond ((listp (cadr c))
8916 (list (car c) (car c) (nth 1 c)))
8917 ((string= "" (cadr c))
8918 (list (car c) (car c) (nth 2 c)))
8919 (t c)))
8920 contexts))
8921 (a alist) r s)
8922 ;; loop over all commands or templates
8923 (dolist (c a)
8924 (let (vrules repl)
8925 (cond
8926 ((not (assoc (car c) contexts))
8927 (push c r))
8928 ((and (assoc (car c) contexts)
8929 (setq vrules (org-contextualize-validate-key
8930 (car c) contexts)))
8931 (mapc (lambda (vr)
8932 (unless (equal (car vr) (cadr vr))
8933 (setq repl vr)))
8934 vrules)
8935 (if (not repl) (push c r)
8936 (push (cadr repl) s)
8937 (push
8938 (cons (car c)
8939 (cdr (or (assoc (cadr repl) alist)
8940 (error "Undefined key `%s' as contextual replacement for `%s'"
8941 (cadr repl) (car c)))))
8942 r))))))
8943 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8944 (delq
8946 (delete-dups
8947 (mapcar (lambda (x)
8948 (let ((tpl (car x)))
8949 (unless (delq
8951 (mapcar (lambda (y)
8952 (equal y tpl))
8954 x)))
8955 (reverse r))))))
8957 (defun org-contextualize-validate-key (key contexts)
8958 "Check CONTEXTS for agenda or capture KEY."
8959 (let (res)
8960 (dolist (r contexts)
8961 (dolist (rr (car (last r)))
8962 (when
8963 (and (equal key (car r))
8964 (if (functionp rr) (funcall rr)
8965 (or (and (eq (car rr) 'in-file)
8966 (buffer-file-name)
8967 (string-match (cdr rr) (buffer-file-name)))
8968 (and (eq (car rr) 'in-mode)
8969 (string-match (cdr rr) (symbol-name major-mode)))
8970 (and (eq (car rr) 'in-buffer)
8971 (string-match (cdr rr) (buffer-name)))
8972 (when (and (eq (car rr) 'not-in-file)
8973 (buffer-file-name))
8974 (not (string-match (cdr rr) (buffer-file-name))))
8975 (when (eq (car rr) 'not-in-mode)
8976 (not (string-match (cdr rr) (symbol-name major-mode))))
8977 (when (eq (car rr) 'not-in-buffer)
8978 (not (string-match (cdr rr) (buffer-name)))))))
8979 (push r res))))
8980 (delete-dups (delq nil res))))
8982 ;; Defined to provide a value for defcustom, since there is no
8983 ;; string-collate-greaterp in Emacs.
8984 (defun org-string-collate-greaterp (s1 s2)
8985 "Return non-nil if S1 is greater than S2 in collation order."
8986 (not (org-string-collate-lessp s1 s2)))
8988 ;;;###autoload
8989 (defun org-run-like-in-org-mode (cmd)
8990 "Run a command, pretending that the current buffer is in Org mode.
8991 This will temporarily bind local variables that are typically bound in
8992 Org mode to the values they have in Org mode, and then interactively
8993 call CMD."
8994 (org-load-modules-maybe)
8995 (let (binds)
8996 (dolist (var (org-get-local-variables))
8997 (when (or (not (boundp (car var)))
8998 (eq (symbol-value (car var))
8999 (default-value (car var))))
9000 (push (list (car var) `(quote ,(cadr var))) binds)))
9001 (eval `(let ,binds
9002 (call-interactively (quote ,cmd))))))
9004 (defun org-get-category (&optional pos force-refresh)
9005 "Get the category applying to position POS."
9006 (save-match-data
9007 (when force-refresh (org-refresh-category-properties))
9008 (let ((pos (or pos (point))))
9009 (or (get-text-property pos 'org-category)
9010 (progn (org-refresh-category-properties)
9011 (get-text-property pos 'org-category))))))
9013 ;;; Refresh properties
9015 (defun org-refresh-properties (dprop tprop)
9016 "Refresh buffer text properties.
9017 DPROP is the drawer property and TPROP is either the
9018 corresponding text property to set, or an alist with each element
9019 being a text property (as a symbol) and a function to apply to
9020 the value of the drawer property."
9021 (let* ((case-fold-search t)
9022 (inhibit-read-only t)
9023 (inherit? (org-property-inherit-p dprop))
9024 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9025 (global (and inherit? (org--property-global-value dprop nil))))
9026 (with-silent-modifications
9027 (org-with-point-at 1
9028 ;; Set global values (e.g., values defined through
9029 ;; "#+PROPERTY:" keywords) to the whole buffer.
9030 (when global (put-text-property (point-min) (point-max) tprop global))
9031 ;; Set local values.
9032 (while (re-search-forward property-re nil t)
9033 (when (org-at-property-p)
9034 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9035 (outline-next-heading))))))
9037 (defun org-refresh-property (tprop p &optional inherit)
9038 "Refresh the buffer text property TPROP from the drawer property P.
9039 The refresh happens only for the current headline, or the whole
9040 sub-tree if optional argument INHERIT is non-nil."
9041 (unless (org-before-first-heading-p)
9042 (save-excursion
9043 (org-back-to-heading t)
9044 (let ((start (point))
9045 (end (save-excursion
9046 (if inherit (org-end-of-subtree t t)
9047 (or (outline-next-heading) (point-max))))))
9048 (if (symbolp tprop)
9049 ;; TPROP is a text property symbol.
9050 (put-text-property start end tprop p)
9051 ;; TPROP is an alist with (property . function) elements.
9052 (pcase-dolist (`(,prop . ,f) tprop)
9053 (put-text-property start end prop (funcall f p))))))))
9055 (defun org-refresh-category-properties ()
9056 "Refresh category text properties in the buffer."
9057 (let ((case-fold-search t)
9058 (inhibit-read-only t)
9059 (default-category
9060 (cond ((null org-category)
9061 (if buffer-file-name
9062 (file-name-sans-extension
9063 (file-name-nondirectory buffer-file-name))
9064 "???"))
9065 ((symbolp org-category) (symbol-name org-category))
9066 (t org-category))))
9067 (with-silent-modifications
9068 (org-with-wide-buffer
9069 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9070 ;; This is the default category for the buffer. If none is
9071 ;; found, fall-back to `org-category' or buffer file name.
9072 (put-text-property
9073 (point-min) (point-max)
9074 'org-category
9075 (catch 'buffer-category
9076 (goto-char (point-max))
9077 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9078 (let ((element (org-element-at-point)))
9079 (when (eq (org-element-type element) 'keyword)
9080 (throw 'buffer-category
9081 (org-element-property :value element)))))
9082 default-category))
9083 ;; Set sub-tree specific categories.
9084 (goto-char (point-min))
9085 (let ((regexp (org-re-property "CATEGORY")))
9086 (while (re-search-forward regexp nil t)
9087 (let ((value (match-string-no-properties 3)))
9088 (when (org-at-property-p)
9089 (put-text-property
9090 (save-excursion (org-back-to-heading t) (point))
9091 (save-excursion (org-end-of-subtree t t) (point))
9092 'org-category
9093 value)))))))))
9095 (defun org-refresh-stats-properties ()
9096 "Refresh stats text properties in the buffer."
9097 (with-silent-modifications
9098 (org-with-point-at 1
9099 (let ((regexp (concat org-outline-regexp-bol
9100 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9101 (while (re-search-forward regexp nil t)
9102 (let* ((numerator (string-to-number (match-string 1)))
9103 (denominator (and (match-end 2)
9104 (string-to-number (match-string 2))))
9105 (stats (cond ((not denominator) numerator) ;percent
9106 ((= denominator 0) 0)
9107 (t (/ (* numerator 100) denominator)))))
9108 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9109 'org-stats stats)))))))
9111 (defun org-refresh-effort-properties ()
9112 "Refresh effort properties"
9113 (org-refresh-properties
9114 org-effort-property
9115 '((effort . identity)
9116 (effort-minutes . org-duration-to-minutes))))
9118 ;;;; Link Stuff
9120 ;;; Link abbreviations
9122 (defun org-link-expand-abbrev (link)
9123 "Apply replacements as defined in `org-link-abbrev-alist'."
9124 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9125 (let* ((key (match-string 1 link))
9126 (as (or (assoc key org-link-abbrev-alist-local)
9127 (assoc key org-link-abbrev-alist)))
9128 (tag (and (match-end 2) (match-string 3 link)))
9129 rpl)
9130 (if (not as)
9131 link
9132 (setq rpl (cdr as))
9133 (cond
9134 ((symbolp rpl) (funcall rpl tag))
9135 ((string-match "%(\\([^)]+\\))" rpl)
9136 (replace-match
9137 (save-match-data
9138 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9139 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9140 ((string-match "%h" rpl)
9141 (replace-match (url-hexify-string (or tag "")) t t rpl))
9142 (t (concat rpl tag)))))
9143 link))
9145 ;;; Storing and inserting links
9147 (defvar org-insert-link-history nil
9148 "Minibuffer history for links inserted with `org-insert-link'.")
9150 (defvar org-stored-links nil
9151 "Contains the links stored with `org-store-link'.")
9153 (defvar org-store-link-plist nil
9154 "Plist with info about the most recently link created with `org-store-link'.")
9156 (defun org-store-link-functions ()
9157 "Return a list of functions that are called to create and store a link.
9158 The functions defined in the :store property of
9159 `org-link-parameters'.
9161 Each function will be called in turn until one returns a non-nil
9162 value. Each function should check if it is responsible for
9163 creating this link (for example by looking at the major mode).
9164 If not, it must exit and return nil. If yes, it should return
9165 a non-nil value after calling `org-store-link-props' with a list
9166 of properties and values. Special properties are:
9168 :type The link prefix, like \"http\". This must be given.
9169 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9170 This is obligatory as well.
9171 :description Optional default description for the second pair
9172 of brackets in an Org mode link. The user can still change
9173 this when inserting this link into an Org mode buffer.
9175 In addition to these, any additional properties can be specified
9176 and then used in capture templates."
9177 (cl-loop for link in org-link-parameters
9178 with store-func
9179 do (setq store-func (org-link-get-parameter (car link) :store))
9180 if store-func
9181 collect store-func))
9183 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9184 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9186 ;;;###autoload
9187 (defun org-store-link (arg &optional interactive?)
9188 "Store a link to the current location.
9189 \\<org-mode-map>
9190 This link is added to `org-stored-links' and can later be inserted
9191 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9193 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9194 A single
9195 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9196 `org-gnus-prefer-web-links' for links to Usenet articles.
9198 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9199 skipping storing functions that are not
9200 part of Org core.
9202 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9203 prefix ARG forces storing a link for each line in the
9204 active region.
9206 Assume the function is called interactively if INTERACTIVE? is
9207 non-nil."
9208 (interactive "P\np")
9209 (org-load-modules-maybe)
9210 (if (and (equal arg '(64)) (org-region-active-p))
9211 (save-excursion
9212 (let ((end (region-end)))
9213 (goto-char (region-beginning))
9214 (set-mark (point))
9215 (while (< (point-at-eol) end)
9216 (move-end-of-line 1) (activate-mark)
9217 (let (current-prefix-arg)
9218 (call-interactively 'org-store-link))
9219 (move-beginning-of-line 2)
9220 (set-mark (point)))))
9221 (setq org-store-link-plist nil)
9222 (let (link cpltxt desc description search txt custom-id agenda-link)
9223 (cond
9224 ;; Store a link using an external link type, if any function is
9225 ;; available. If more than one can generate a link from current
9226 ;; location, ask which one to use.
9227 ((and (not (equal arg '(16)))
9228 (let ((results-alist nil))
9229 (dolist (f (org-store-link-functions))
9230 (when (funcall f)
9231 ;; XXX: return value is not link's plist, so we
9232 ;; store the new value before it is modified. It
9233 ;; would be cleaner to ask store link functions to
9234 ;; return the plist instead.
9235 (push (cons f (copy-sequence org-store-link-plist))
9236 results-alist)))
9237 (pcase results-alist
9238 (`nil nil)
9239 (`((,_ . ,_)) t) ;single choice: nothing to do
9240 (`((,name . ,_) . ,_)
9241 ;; Reinstate link plist associated to the chosen
9242 ;; function.
9243 (apply #'org-store-link-props
9244 (cdr (assoc-string
9245 (completing-read
9246 "Which function for creating the link? "
9247 (mapcar #'car results-alist)
9248 nil t (symbol-name name))
9249 results-alist)))
9250 t))))
9251 (setq link (plist-get org-store-link-plist :link))
9252 (setq desc (or (plist-get org-store-link-plist :description)
9253 link)))
9255 ;; Store a link from a remote editing buffer.
9256 ((org-src-edit-buffer-p)
9257 (let ((coderef-format (org-src-coderef-format))
9258 (format-link
9259 (lambda (label)
9260 (if org-src-source-file-name
9261 (format "file:%s::(%s)" org-src-source-file-name label)
9262 (format "(%s)" label)))))
9263 (cond
9264 ;; Code references do not exist in this type of buffer.
9265 ;; Pretend we're linking from the source buffer directly.
9266 ((not (memq (org-src-source-type) '(example-block src-block)))
9267 (with-current-buffer (org-src-source-buffer)
9268 (org-store-link arg interactive?))
9269 (setq link nil))
9270 ;; A code reference exists. Use it.
9271 ((save-excursion
9272 (beginning-of-line)
9273 (re-search-forward (org-src-coderef-regexp coderef-format)
9274 (line-end-position)
9276 (setq link (funcall format-link (match-string-no-properties 3))))
9277 ;; No code reference. Create a new one then store the link
9278 ;; to it, but only in the function is called interactively.
9279 (interactive?
9280 (end-of-line)
9281 (let* ((label (read-string "Code line label: "))
9282 (reference (format coderef-format label))
9283 (gc (- 79 (length reference))))
9284 (if (< (current-column) gc)
9285 (org-move-to-column gc t)
9286 (insert " "))
9287 (insert reference)
9288 (setq link (funcall format-link label))))
9289 ;; No code reference, and non-interactive call. Don't know
9290 ;; what to do. Give up.
9291 (t (setq link nil)))))
9293 ;; We are in the agenda, link to referenced location
9294 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9295 (let ((m (or (get-text-property (point) 'org-hd-marker)
9296 (get-text-property (point) 'org-marker))))
9297 (when m
9298 (org-with-point-at m
9299 (setq agenda-link (org-store-link nil interactive?))))))
9301 ((eq major-mode 'calendar-mode)
9302 (let ((cd (calendar-cursor-to-date)))
9303 (setq link
9304 (format-time-string
9305 (car org-time-stamp-formats)
9306 (apply 'encode-time
9307 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9308 nil nil nil))))
9309 (org-store-link-props :type "calendar" :date cd)))
9311 ((eq major-mode 'help-mode)
9312 (setq link (concat "help:" (save-excursion
9313 (goto-char (point-min))
9314 (looking-at "^[^ ]+")
9315 (match-string 0))))
9316 (org-store-link-props :type "help"))
9318 ((eq major-mode 'w3-mode)
9319 (setq cpltxt (if (and (buffer-name)
9320 (not (string-match "Untitled" (buffer-name))))
9321 (buffer-name)
9322 (url-view-url t))
9323 link (url-view-url t))
9324 (org-store-link-props :type "w3" :url (url-view-url t)))
9326 ((eq major-mode 'image-mode)
9327 (setq cpltxt (concat "file:"
9328 (abbreviate-file-name buffer-file-name))
9329 link cpltxt)
9330 (org-store-link-props :type "image" :file buffer-file-name))
9332 ;; In dired, store a link to the file of the current line
9333 ((derived-mode-p 'dired-mode)
9334 (let ((file (dired-get-filename nil t)))
9335 (setq file (if file
9336 (abbreviate-file-name
9337 (expand-file-name (dired-get-filename nil t)))
9338 ;; otherwise, no file so use current directory.
9339 default-directory))
9340 (setq cpltxt (concat "file:" file)
9341 link cpltxt)))
9343 ((setq search (run-hook-with-args-until-success
9344 'org-create-file-search-functions))
9345 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9346 "::" search))
9347 (setq cpltxt (or description link)))
9349 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9350 (org-with-limited-levels
9351 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9352 (cond
9353 ;; Store a link using the target at point
9354 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9355 (setq cpltxt
9356 (concat "file:"
9357 (abbreviate-file-name
9358 (buffer-file-name (buffer-base-buffer)))
9359 "::" (match-string 1))
9360 link cpltxt))
9361 ((and (featurep 'org-id)
9362 (or (eq org-id-link-to-org-use-id t)
9363 (and interactive?
9364 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9365 (and (eq org-id-link-to-org-use-id
9366 'create-if-interactive-and-no-custom-id)
9367 (not custom-id))))
9368 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9369 ;; Store a link using the ID at point
9370 (setq link (condition-case nil
9371 (prog1 (org-id-store-link)
9372 (setq desc (or (plist-get org-store-link-plist
9373 :description)
9374 "")))
9375 (error
9376 ;; Probably before first headline, link only to file
9377 (concat "file:"
9378 (abbreviate-file-name
9379 (buffer-file-name (buffer-base-buffer))))))))
9381 ;; Just link to current headline
9382 (setq cpltxt (concat "file:"
9383 (abbreviate-file-name
9384 (buffer-file-name (buffer-base-buffer)))))
9385 ;; Add a context search string
9386 (when (org-xor org-context-in-file-links
9387 (equal arg '(4)))
9388 (let* ((element (org-element-at-point))
9389 (name (org-element-property :name element)))
9390 (setq txt (cond
9391 ((org-at-heading-p) nil)
9392 (name)
9393 ((org-region-active-p)
9394 (buffer-substring (region-beginning) (region-end)))))
9395 (when (or (null txt) (string-match "\\S-" txt))
9396 (setq cpltxt
9397 (concat cpltxt "::"
9398 (condition-case nil
9399 (org-make-org-heading-search-string txt)
9400 (error "")))
9401 desc (or name
9402 (nth 4 (ignore-errors (org-heading-components)))
9403 "NONE")))))
9404 (when (string-match "::\\'" cpltxt)
9405 (setq cpltxt (substring cpltxt 0 -2)))
9406 (setq link cpltxt)))))
9408 ((buffer-file-name (buffer-base-buffer))
9409 ;; Just link to this file here.
9410 (setq cpltxt (concat "file:"
9411 (abbreviate-file-name
9412 (buffer-file-name (buffer-base-buffer)))))
9413 ;; Add a context string.
9414 (when (org-xor org-context-in-file-links
9415 (equal arg '(4)))
9416 (setq txt (if (org-region-active-p)
9417 (buffer-substring (region-beginning) (region-end))
9418 (buffer-substring (point-at-bol) (point-at-eol))))
9419 ;; Only use search option if there is some text.
9420 (when (string-match "\\S-" txt)
9421 (setq cpltxt
9422 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9423 desc "NONE")))
9424 (setq link cpltxt))
9426 (interactive?
9427 (user-error "No method for storing a link from this buffer"))
9429 (t (setq link nil)))
9431 ;; We're done setting link and desc, clean up
9432 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9433 (setq link (or link cpltxt)
9434 desc (or desc cpltxt))
9435 (cond ((not desc))
9436 ((equal desc "NONE") (setq desc nil))
9437 (t (setq desc
9438 (replace-regexp-in-string
9439 org-bracket-link-analytic-regexp
9440 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9441 desc))))
9442 ;; Return the link
9443 (if (not (and interactive? link))
9444 (or agenda-link (and link (org-make-link-string link desc)))
9445 (push (list link desc) org-stored-links)
9446 (message "Stored: %s" (or desc link))
9447 (when custom-id
9448 (setq link (concat "file:" (abbreviate-file-name
9449 (buffer-file-name)) "::#" custom-id))
9450 (push (list link desc) org-stored-links))
9451 (car org-stored-links)))))
9453 (defun org-store-link-props (&rest plist)
9454 "Store link properties.
9455 The properties are pre-processed by extracting names, addresses
9456 and dates."
9457 (let ((x (plist-get plist :from)))
9458 (when x
9459 (let ((adr (mail-extract-address-components x)))
9460 (setq plist (plist-put plist :fromname (car adr)))
9461 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9462 (let ((x (plist-get plist :to)))
9463 (when x
9464 (let ((adr (mail-extract-address-components x)))
9465 (setq plist (plist-put plist :toname (car adr)))
9466 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9467 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9468 (when x
9469 (setq plist (plist-put plist :date-timestamp
9470 (format-time-string
9471 (org-time-stamp-format t) x)))
9472 (setq plist (plist-put plist :date-timestamp-inactive
9473 (format-time-string
9474 (org-time-stamp-format t t) x)))))
9475 (let ((from (plist-get plist :from))
9476 (to (plist-get plist :to)))
9477 (when (and from to org-from-is-user-regexp)
9478 (setq plist
9479 (plist-put plist :fromto
9480 (if (string-match org-from-is-user-regexp from)
9481 (concat "to %t")
9482 (concat "from %f"))))))
9483 (setq org-store-link-plist plist))
9485 (defun org-add-link-props (&rest plist)
9486 "Add these properties to the link property list."
9487 (let (key value)
9488 (while plist
9489 (setq key (pop plist) value (pop plist))
9490 (setq org-store-link-plist
9491 (plist-put org-store-link-plist key value)))))
9493 (defun org-email-link-description (&optional fmt)
9494 "Return the description part of an email link.
9495 This takes information from `org-store-link-plist' and formats it
9496 according to FMT (default from `org-email-link-description-format')."
9497 (setq fmt (or fmt org-email-link-description-format))
9498 (let* ((p org-store-link-plist)
9499 (to (plist-get p :toaddress))
9500 (from (plist-get p :fromaddress))
9501 (table
9502 (list
9503 (cons "%c" (plist-get p :fromto))
9504 (cons "%F" (plist-get p :from))
9505 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9506 (cons "%T" (plist-get p :to))
9507 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9508 (cons "%s" (plist-get p :subject))
9509 (cons "%d" (plist-get p :date))
9510 (cons "%m" (plist-get p :message-id)))))
9511 (when (string-match "%c" fmt)
9512 ;; Check if the user wrote this message
9513 (if (and org-from-is-user-regexp from to
9514 (save-match-data (string-match org-from-is-user-regexp from)))
9515 (setq fmt (replace-match "to %t" t t fmt))
9516 (setq fmt (replace-match "from %f" t t fmt))))
9517 (org-replace-escapes fmt table)))
9519 (defun org-make-org-heading-search-string (&optional string)
9520 "Make search string for the current headline or STRING."
9521 (let ((s (or string
9522 (and (derived-mode-p 'org-mode)
9523 (save-excursion
9524 (org-back-to-heading t)
9525 (org-element-property :raw-value (org-element-at-point))))))
9526 (lines org-context-in-file-links))
9527 (unless string (setq s (concat "*" s))) ;Add * for headlines
9528 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9529 (when (and string (integerp lines) (> lines 0))
9530 (let ((slines (org-split-string s "\n")))
9531 (when (< lines (length slines))
9532 (setq s (mapconcat
9533 'identity
9534 (reverse (nthcdr (- (length slines) lines)
9535 (reverse slines))) "\n")))))
9536 (mapconcat #'identity (split-string s) " ")))
9538 (defconst org-link-escape-chars
9539 ;;%20 %5B %5D %25
9540 '(?\s ?\[ ?\] ?%)
9541 "List of characters that should be escaped in a link when stored to Org.
9542 This is the list that is used for internal purposes.")
9544 (defun org-make-link-string (link &optional description)
9545 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9546 (unless (org-string-nw-p link) (error "Empty link"))
9547 (let ((uri (cond ((string-match org-link-types-re link)
9548 (concat (match-string 1 link)
9549 (org-link-escape (substring link (match-end 1)))))
9550 ((or (file-name-absolute-p link)
9551 (string-match-p "\\`\\.\\.?/" link))
9552 (org-link-escape link))
9553 ;; For readability, do not encode space characters
9554 ;; in fuzzy links.
9555 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9556 (description
9557 (and (org-string-nw-p description)
9558 ;; Remove brackets from description, as they are fatal.
9559 (replace-regexp-in-string
9560 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9561 (org-trim description)))))
9562 (format "[[%s]%s]"
9564 (if description (format "[%s]" description) ""))))
9566 (defun org-link-escape (text &optional table merge)
9567 "Return percent escaped representation of TEXT.
9568 TEXT is a string with the text to escape.
9569 Optional argument TABLE is a list with characters that should be
9570 escaped. When nil, `org-link-escape-chars' is used.
9571 If optional argument MERGE is set, merge TABLE into
9572 `org-link-escape-chars'."
9573 (let ((characters-to-encode
9574 (cond ((null table) org-link-escape-chars)
9575 (merge (append org-link-escape-chars table))
9576 (t table))))
9577 (mapconcat
9578 (lambda (c)
9579 (if (or (memq c characters-to-encode)
9580 (and org-url-hexify-p (or (< c 32) (> c 126))))
9581 (mapconcat (lambda (e) (format "%%%.2X" e))
9582 (or (encode-coding-char c 'utf-8)
9583 (error "Unable to percent escape character: %c" c))
9585 (char-to-string c)))
9586 text "")))
9588 (defun org-link-unescape (str)
9589 "Unhex hexified Unicode parts in string STR.
9590 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9591 reciprocal of `org-link-escape', which see."
9592 (if (org-string-nw-p str)
9593 (replace-regexp-in-string
9594 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9595 str))
9597 (defun org-link-unescape-compound (hex)
9598 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9599 Note: this function also decodes single byte encodings like
9600 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9601 (save-match-data
9602 (let* ((bytes (cdr (split-string hex "%")))
9603 (ret "")
9604 (eat 0)
9605 (sum 0))
9606 (while bytes
9607 (let* ((val (string-to-number (pop bytes) 16))
9608 (shift-xor
9609 (if (= 0 eat)
9610 (cond
9611 ((>= val 252) (cons 6 252))
9612 ((>= val 248) (cons 5 248))
9613 ((>= val 240) (cons 4 240))
9614 ((>= val 224) (cons 3 224))
9615 ((>= val 192) (cons 2 192))
9616 (t (cons 0 0)))
9617 (cons 6 128))))
9618 (when (>= val 192) (setq eat (car shift-xor)))
9619 (setq val (logxor val (cdr shift-xor)))
9620 (setq sum (+ (lsh sum (car shift-xor)) val))
9621 (when (> eat 0) (setq eat (- eat 1)))
9622 (cond
9623 ((= 0 eat) ;multi byte
9624 (setq ret (concat ret (char-to-string sum)))
9625 (setq sum 0))
9626 ((not bytes) ; single byte(s)
9627 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9628 ret)))
9630 (defun org-link-unescape-single-byte-sequence (hex)
9631 "Unhexify hex-encoded single byte character sequences."
9632 (mapconcat (lambda (byte)
9633 (char-to-string (string-to-number byte 16)))
9634 (cdr (split-string hex "%")) ""))
9636 (defun org-fixup-message-id-for-http (s)
9637 "Replace special characters in a message id, so it can be used in an http query."
9638 (when (string-match "%" s)
9639 (setq s (mapconcat (lambda (c)
9640 (if (eq c ?%)
9641 "%25"
9642 (char-to-string c)))
9643 s "")))
9644 (while (string-match "<" s)
9645 (setq s (replace-match "%3C" t t s)))
9646 (while (string-match ">" s)
9647 (setq s (replace-match "%3E" t t s)))
9648 (while (string-match "@" s)
9649 (setq s (replace-match "%40" t t s)))
9652 (defun org-link-prettify (link)
9653 "Return a human-readable representation of LINK.
9654 The car of LINK must be a raw link.
9655 The cdr of LINK must be either a link description or nil."
9656 (let ((desc (or (cadr link) "<no description>")))
9657 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9658 "<" (car link) ">")))
9660 ;;;###autoload
9661 (defun org-insert-link-global ()
9662 "Insert a link like Org mode does.
9663 This command can be called in any mode to insert a link in Org syntax."
9664 (interactive)
9665 (org-load-modules-maybe)
9666 (org-run-like-in-org-mode 'org-insert-link))
9668 (defun org-insert-all-links (arg &optional pre post)
9669 "Insert all links in `org-stored-links'.
9670 When a universal prefix, do not delete the links from `org-stored-links'.
9671 When `ARG' is a number, insert the last N link(s).
9672 `PRE' and `POST' are optional arguments to define a string to
9673 prepend or to append."
9674 (interactive "P")
9675 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9676 (links (copy-sequence org-stored-links))
9677 (pr (or pre "- "))
9678 (po (or post "\n"))
9679 (cnt 1) l)
9680 (if (null org-stored-links)
9681 (message "No link to insert")
9682 (while (and (or (listp arg) (>= arg cnt))
9683 (setq l (if (listp arg)
9684 (pop links)
9685 (pop org-stored-links))))
9686 (setq cnt (1+ cnt))
9687 (insert pr)
9688 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9689 (insert po)))))
9691 (defun org-insert-last-stored-link (arg)
9692 "Insert the last link stored in `org-stored-links'."
9693 (interactive "p")
9694 (org-insert-all-links arg "" "\n"))
9696 (defun org-link-fontify-links-to-this-file ()
9697 "Fontify links to the current file in `org-stored-links'."
9698 (let ((f (buffer-file-name)) a b)
9699 (setq a (mapcar (lambda(l)
9700 (let ((ll (car l)))
9701 (when (and (string-match "^file:\\(.+\\)::" ll)
9702 (equal f (expand-file-name (match-string 1 ll))))
9703 ll)))
9704 org-stored-links))
9705 (when (featurep 'org-id)
9706 (setq b (mapcar (lambda(l)
9707 (let ((ll (car l)))
9708 (when (and (string-match "^id:\\(.+\\)$" ll)
9709 (equal f (expand-file-name
9710 (or (org-id-find-id-file
9711 (match-string 1 ll)) ""))))
9712 ll)))
9713 org-stored-links)))
9714 (mapcar (lambda(l)
9715 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9716 (delq nil (append a b)))))
9718 (defvar org--links-history nil)
9719 (defun org-insert-link (&optional complete-file link-location default-description)
9720 "Insert a link. At the prompt, enter the link.
9722 Completion can be used to insert any of the link protocol prefixes in use.
9724 The history can be used to select a link previously stored with
9725 `org-store-link'. When the empty string is entered (i.e. if you just
9726 press `RET' at the prompt), the link defaults to the most recently
9727 stored link. As `SPC' triggers completion in the minibuffer, you need to
9728 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9730 You will also be prompted for a description, and if one is given, it will
9731 be displayed in the buffer instead of the link.
9733 If there is already a link at point, this command will allow you to edit
9734 link and description parts.
9736 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9737 file name can be
9738 selected using completion. The path to the file will be relative to the
9739 current directory if the file is in the current directory or a subdirectory.
9740 Otherwise, the link will be the absolute path as completed in the minibuffer
9741 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9742 option `org-link-file-path-type'.
9744 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9745 absolute path even if the file is in
9746 the current directory or below.
9748 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9749 prefix negates `org-keep-stored-link-after-insertion'.
9751 If the LINK-LOCATION parameter is non-nil, this value will be used as
9752 the link location instead of reading one interactively.
9754 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9755 be used as the default description. Otherwise, if
9756 `org-make-link-description-function' is non-nil, this function
9757 will be called with the link target, and the result will be the
9758 default link description. When called non-interactivily, don't
9759 allow to edit the default description."
9760 (interactive "P")
9761 (let* ((wcf (current-window-configuration))
9762 (origbuf (current-buffer))
9763 (region (when (org-region-active-p)
9764 (buffer-substring (region-beginning) (region-end))))
9765 (remove (and region (list (region-beginning) (region-end))))
9766 (desc region)
9767 (link link-location)
9768 (abbrevs org-link-abbrev-alist-local)
9769 entry all-prefixes auto-desc)
9770 (cond
9771 (link-location) ; specified by arg, just use it.
9772 ((org-in-regexp org-bracket-link-regexp 1)
9773 ;; We do have a link at point, and we are going to edit it.
9774 (setq remove (list (match-beginning 0) (match-end 0)))
9775 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9776 (setq link (read-string "Link: "
9777 (org-link-unescape
9778 (match-string-no-properties 1)))))
9779 ((or (org-in-regexp org-angle-link-re)
9780 (org-in-regexp org-plain-link-re))
9781 ;; Convert to bracket link
9782 (setq remove (list (match-beginning 0) (match-end 0))
9783 link (read-string "Link: "
9784 (org-unbracket-string "<" ">" (match-string 0)))))
9785 ((member complete-file '((4) (16)))
9786 ;; Completing read for file names.
9787 (setq link (org-file-complete-link complete-file)))
9789 ;; Read link, with completion for stored links.
9790 (org-link-fontify-links-to-this-file)
9791 (org-switch-to-buffer-other-window "*Org Links*")
9792 (with-current-buffer "*Org Links*"
9793 (erase-buffer)
9794 (insert "Insert a link.
9795 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9796 (when org-stored-links
9797 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9798 (insert (mapconcat 'org-link-prettify
9799 (reverse org-stored-links) "\n")))
9800 (goto-char (point-min)))
9801 (let ((cw (selected-window)))
9802 (select-window (get-buffer-window "*Org Links*" 'visible))
9803 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9804 (unless (pos-visible-in-window-p (point-max))
9805 (org-fit-window-to-buffer))
9806 (and (window-live-p cw) (select-window cw)))
9807 (setq all-prefixes (append (mapcar 'car abbrevs)
9808 (mapcar 'car org-link-abbrev-alist)
9809 (org-link-types)))
9810 (unwind-protect
9811 ;; Fake a link history, containing the stored links.
9812 (let ((org--links-history
9813 (append (mapcar #'car org-stored-links)
9814 org-insert-link-history)))
9815 (setq link
9816 (org-completing-read
9817 "Link: "
9818 (append
9819 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9820 (mapcar #'car org-stored-links))
9821 nil nil nil
9822 'org--links-history
9823 (caar org-stored-links)))
9824 (unless (org-string-nw-p link) (user-error "No link selected"))
9825 (dolist (l org-stored-links)
9826 (when (equal link (cadr l))
9827 (setq link (car l))
9828 (setq auto-desc t)))
9829 (when (or (member link all-prefixes)
9830 (and (equal ":" (substring link -1))
9831 (member (substring link 0 -1) all-prefixes)
9832 (setq link (substring link 0 -1))))
9833 (setq link (with-current-buffer origbuf
9834 (org-link-try-special-completion link)))))
9835 (set-window-configuration wcf)
9836 (kill-buffer "*Org Links*"))
9837 (setq entry (assoc link org-stored-links))
9838 (or entry (push link org-insert-link-history))
9839 (setq desc (or desc (nth 1 entry)))))
9841 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9842 (not org-keep-stored-link-after-insertion))
9843 (setq org-stored-links (delq (assoc link org-stored-links)
9844 org-stored-links)))
9846 (when (and (string-match org-plain-link-re link)
9847 (not (string-match org-ts-regexp link)))
9848 ;; URL-like link, normalize the use of angular brackets.
9849 (setq link (org-unbracket-string "<" ">" link)))
9851 ;; Check if we are linking to the current file with a search
9852 ;; option If yes, simplify the link by using only the search
9853 ;; option.
9854 (when (and buffer-file-name
9855 (let ((case-fold-search nil))
9856 (string-match "\\`file:\\(.+?\\)::" link)))
9857 (let ((path (match-string-no-properties 1 link))
9858 (search (substring-no-properties link (match-end 0))))
9859 (save-match-data
9860 (when (equal (file-truename buffer-file-name) (file-truename path))
9861 ;; We are linking to this same file, with a search option
9862 (setq link search)))))
9864 ;; Check if we can/should use a relative path. If yes, simplify
9865 ;; the link.
9866 (let ((case-fold-search nil))
9867 (when (string-match "\\`\\(file\\|docview\\):" link)
9868 (let* ((type (match-string-no-properties 0 link))
9869 (path-start (match-end 0))
9870 (search (and (string-match "::\\(.*\\)\\'" link)
9871 (match-string 1 link)))
9872 (path
9873 (if search
9874 (substring-no-properties
9875 link path-start (match-beginning 0))
9876 (substring-no-properties link (match-end 0))))
9877 (origpath path))
9878 (cond
9879 ((or (eq org-link-file-path-type 'absolute)
9880 (equal complete-file '(16)))
9881 (setq path (abbreviate-file-name (expand-file-name path))))
9882 ((eq org-link-file-path-type 'noabbrev)
9883 (setq path (expand-file-name path)))
9884 ((eq org-link-file-path-type 'relative)
9885 (setq path (file-relative-name path)))
9887 (save-match-data
9888 (if (string-match (concat "^" (regexp-quote
9889 (expand-file-name
9890 (file-name-as-directory
9891 default-directory))))
9892 (expand-file-name path))
9893 ;; We are linking a file with relative path name.
9894 (setq path (substring (expand-file-name path)
9895 (match-end 0)))
9896 (setq path (abbreviate-file-name (expand-file-name path)))))))
9897 (setq link (concat type path (and search (concat "::" search))))
9898 (when (equal desc origpath)
9899 (setq desc path)))))
9901 (unless auto-desc
9902 (let ((initial-input
9903 (cond
9904 (default-description)
9905 ((not org-make-link-description-function) desc)
9906 (t (condition-case nil
9907 (funcall org-make-link-description-function link desc)
9908 (error
9909 (message "Can't get link description from `%s'"
9910 (symbol-name org-make-link-description-function))
9911 (sit-for 2)
9912 nil))))))
9913 (setq desc (if (called-interactively-p 'any)
9914 (read-string "Description: " initial-input)
9915 initial-input))))
9917 (unless (string-match "\\S-" desc) (setq desc nil))
9918 (when remove (apply 'delete-region remove))
9919 (insert (org-make-link-string link desc))
9920 ;; Redisplay so as the new link has proper invisible characters.
9921 (sit-for 0)))
9923 (defun org-link-try-special-completion (type)
9924 "If there is completion support for link type TYPE, offer it."
9925 (let ((fun (org-link-get-parameter type :complete)))
9926 (if (functionp fun)
9927 (funcall fun)
9928 (read-string "Link (no completion support): " (concat type ":")))))
9930 (defun org-file-complete-link (&optional arg)
9931 "Create a file link using completion."
9932 (let ((file (read-file-name "File: "))
9933 (pwd (file-name-as-directory (expand-file-name ".")))
9934 (pwd1 (file-name-as-directory (abbreviate-file-name
9935 (expand-file-name ".")))))
9936 (cond ((equal arg '(16))
9937 (concat "file:"
9938 (abbreviate-file-name (expand-file-name file))))
9939 ((string-match
9940 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9941 (concat "file:" (match-string 1 file)))
9942 ((string-match
9943 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9944 (expand-file-name file))
9945 (concat "file:"
9946 (match-string 1 (expand-file-name file))))
9947 (t (concat "file:" file)))))
9950 ;;; Opening/following a link
9952 (defvar org-link-search-failed nil)
9954 (defvar org-open-link-functions nil
9955 "Hook for functions finding a plain text link.
9956 These functions must take a single argument, the link content.
9957 They will be called for links that look like [[link text][description]]
9958 when LINK TEXT does not have a protocol like \"http:\" and does not look
9959 like a filename (e.g. \"./blue.png\").
9961 These functions will be called *before* Org attempts to resolve the
9962 link by doing text searches in the current buffer - so if you want a
9963 link \"[[target]]\" to still find \"<<target>>\", your function should
9964 handle this as a special case.
9966 When the function does handle the link, it must return a non-nil value.
9967 If it decides that it is not responsible for this link, it must return
9968 nil to indicate that that Org can continue with other options like
9969 exact and fuzzy text search.")
9971 (defun org-next-link (&optional search-backward)
9972 "Move forward to the next link.
9973 If the link is in hidden text, expose it."
9974 (interactive "P")
9975 (when (and org-link-search-failed (eq this-command last-command))
9976 (goto-char (point-min))
9977 (message "Link search wrapped back to beginning of buffer"))
9978 (setq org-link-search-failed nil)
9979 (let* ((pos (point))
9980 (ct (org-context))
9981 (a (assq :link ct))
9982 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9983 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9984 ((looking-at org-any-link-re)
9985 ;; Don't stay stuck at link without an org-link face
9986 (forward-char (if search-backward -1 1))))
9987 (if (funcall srch-fun org-any-link-re nil t)
9988 (progn
9989 (goto-char (match-beginning 0))
9990 (when (org-invisible-p) (org-show-context)))
9991 (goto-char pos)
9992 (setq org-link-search-failed t)
9993 (message "No further link found"))))
9995 (defun org-previous-link ()
9996 "Move backward to the previous link.
9997 If the link is in hidden text, expose it."
9998 (interactive)
9999 (org-next-link t))
10001 (defun org-translate-link (s)
10002 "Translate a link string if a translation function has been defined."
10003 (with-temp-buffer
10004 (insert (org-trim s))
10005 (org-trim (org-element-interpret-data (org-element-context)))))
10007 (defun org-translate-link-from-planner (type path)
10008 "Translate a link from Emacs Planner syntax so that Org can follow it.
10009 This is still an experimental function, your mileage may vary."
10010 (cond
10011 ((member type '("http" "https" "news" "ftp"))
10012 ;; standard Internet links are the same.
10013 nil)
10014 ((and (equal type "irc") (string-match "^//" path))
10015 ;; Planner has two / at the beginning of an irc link, we have 1.
10016 ;; We should have zero, actually....
10017 (setq path (substring path 1)))
10018 ((and (equal type "lisp") (string-match "^/" path))
10019 ;; Planner has a slash, we do not.
10020 (setq type "elisp" path (substring path 1)))
10021 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10022 ;; A typical message link. Planner has the id after the final slash,
10023 ;; we separate it with a hash mark
10024 (setq path (concat (match-string 1 path) "#"
10025 (org-unbracket-string "<" ">" (match-string 2 path))))))
10026 (cons type path))
10028 (defun org-find-file-at-mouse (ev)
10029 "Open file link or URL at mouse."
10030 (interactive "e")
10031 (mouse-set-point ev)
10032 (org-open-at-point 'in-emacs))
10034 (defun org-open-at-mouse (ev)
10035 "Open file link or URL at mouse.
10036 See the docstring of `org-open-file' for details."
10037 (interactive "e")
10038 (mouse-set-point ev)
10039 (when (eq major-mode 'org-agenda-mode)
10040 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10041 (org-open-at-point))
10043 (defvar org-window-config-before-follow-link nil
10044 "The window configuration before following a link.
10045 This is saved in case the need arises to restore it.")
10047 ;;;###autoload
10048 (defun org-open-at-point-global ()
10049 "Follow a link or a time-stamp like Org mode does.
10050 Also follow links and emails as seen by `thing-at-point'.
10051 This command can be called in any mode to follow an external
10052 link or a time-stamp that has Org mode syntax. Its behavior
10053 is undefined when called on internal links like fuzzy links.
10054 Raise a user error when there is nothing to follow."
10055 (interactive)
10056 (let ((tap-url (thing-at-point 'url))
10057 (tap-email (thing-at-point 'email)))
10058 (cond ((org-in-regexp org-any-link-re)
10059 (org-open-link-from-string (match-string-no-properties 0)))
10060 ((or (org-in-regexp org-ts-regexp-both nil t)
10061 (org-in-regexp org-tsr-regexp-both nil t))
10062 (org-follow-timestamp-link))
10063 (tap-url (org-open-link-from-string tap-url))
10064 (tap-email (org-open-link-from-string
10065 (concat "mailto:" tap-email)))
10066 (t (user-error "No link found")))))
10068 ;;;###autoload
10069 (defun org-open-link-from-string (s &optional arg reference-buffer)
10070 "Open a link in the string S, as if it was in Org mode."
10071 (interactive "sLink: \nP")
10072 (let ((reference-buffer (or reference-buffer (current-buffer))))
10073 (with-temp-buffer
10074 (let ((org-inhibit-startup (not reference-buffer)))
10075 (org-mode)
10076 (insert s)
10077 (goto-char (point-min))
10078 (when reference-buffer
10079 (setq org-link-abbrev-alist-local
10080 (with-current-buffer reference-buffer
10081 org-link-abbrev-alist-local)))
10082 (org-open-at-point arg reference-buffer)))))
10084 (defvar org-open-at-point-functions nil
10085 "Hook that is run when following a link at point.
10087 Functions in this hook must return t if they identify and follow
10088 a link at point. If they don't find anything interesting at point,
10089 they must return nil.")
10091 (defvar org-link-search-inhibit-query nil)
10092 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10093 (defun org--open-doi-link (path)
10094 "Open a \"doi\" type link.
10095 PATH is a the path to search for, as a string."
10096 (browse-url (url-encode-url (concat org-doi-server-url path))))
10098 (defun org--open-elisp-link (path)
10099 "Open a \"elisp\" type link.
10100 PATH is the sexp to evaluate, as a string."
10101 (let ((cmd path))
10102 (if (or (and (org-string-nw-p
10103 org-confirm-elisp-link-not-regexp)
10104 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10105 (not org-confirm-elisp-link-function)
10106 (funcall org-confirm-elisp-link-function
10107 (format "Execute \"%s\" as elisp? "
10108 (org-add-props cmd nil 'face 'org-warning))))
10109 (message "%s => %s" cmd
10110 (if (eq (string-to-char cmd) ?\()
10111 (eval (read cmd))
10112 (call-interactively (read cmd))))
10113 (user-error "Abort"))))
10115 (defun org--open-help-link (path)
10116 "Open a \"help\" type link.
10117 PATH is a symbol name, as a string."
10118 (pcase (intern path)
10119 ((and (pred fboundp) variable) (describe-function variable))
10120 ((and (pred boundp) function) (describe-variable function))
10121 (name (user-error "Unknown function or variable: %s" name))))
10123 (defun org--open-shell-link (path)
10124 "Open a \"shell\" type link.
10125 PATH is the command to execute, as a string."
10126 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10127 (cmd path))
10128 (if (or (and (org-string-nw-p
10129 org-confirm-shell-link-not-regexp)
10130 (string-match
10131 org-confirm-shell-link-not-regexp cmd))
10132 (not org-confirm-shell-link-function)
10133 (funcall org-confirm-shell-link-function
10134 (format "Execute \"%s\" in shell? "
10135 (org-add-props cmd nil
10136 'face 'org-warning))))
10137 (progn
10138 (message "Executing %s" cmd)
10139 (shell-command cmd buf)
10140 (when (featurep 'midnight)
10141 (setq clean-buffer-list-kill-buffer-names
10142 (cons (buffer-name buf)
10143 clean-buffer-list-kill-buffer-names))))
10144 (user-error "Abort"))))
10146 (defun org-open-at-point (&optional arg reference-buffer)
10147 "Open link, timestamp, footnote or tags at point.
10149 When point is on a link, follow it. Normally, files will be
10150 opened by an appropriate application. If the optional prefix
10151 argument ARG is non-nil, Emacs will visit the file. With
10152 a double prefix argument, try to open outside of Emacs, in the
10153 application the system uses for this file type.
10155 When point is on a timestamp, open the agenda at the day
10156 specified.
10158 When point is a footnote definition, move to the first reference
10159 found. If it is on a reference, move to the associated
10160 definition.
10162 When point is on a headline, display a list of every link in the
10163 entry, so it is possible to pick one, or all, of them. If point
10164 is on a tag, call `org-tags-view' instead.
10166 When optional argument REFERENCE-BUFFER is non-nil, it should
10167 specify a buffer from where the link search should happen. This
10168 is used internally by `org-open-link-from-string'.
10170 On top of syntactically correct links, this function also tries
10171 to open links and time-stamps in comments, node properties, and
10172 keywords if point is on something looking like a timestamp or
10173 a link."
10174 (interactive "P")
10175 (org-load-modules-maybe)
10176 (setq org-window-config-before-follow-link (current-window-configuration))
10177 (org-remove-occur-highlights nil nil t)
10178 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10179 (let* ((context
10180 ;; Only consider supported types, even if they are not the
10181 ;; closest one.
10182 (org-element-lineage
10183 (org-element-context)
10184 '(clock comment comment-block footnote-definition
10185 footnote-reference headline inline-src-block inlinetask
10186 keyword link node-property src-block timestamp)
10188 (type (org-element-type context))
10189 (value (org-element-property :value context)))
10190 (cond
10191 ((not type) (user-error "No link found"))
10192 ;; No valid link at point. For convenience, look if something
10193 ;; looks like a link under point in some specific places.
10194 ((memq type '(comment comment-block node-property keyword))
10195 (call-interactively #'org-open-at-point-global))
10196 ;; On a headline or an inlinetask, but not on a timestamp,
10197 ;; a link, a footnote reference.
10198 ((memq type '(headline inlinetask))
10199 (org-match-line org-complex-heading-regexp)
10200 (if (and (match-beginning 5)
10201 (>= (point) (match-beginning 5))
10202 (< (point) (match-end 5)))
10203 ;; On tags.
10204 (org-tags-view arg (substring (match-string 5) 0 -1))
10205 ;; Not on tags.
10206 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10207 (`(nil . ,_)
10208 (require 'org-attach)
10209 (org-attach-reveal 'if-exists))
10210 (`(,links . ,links-end)
10211 (dolist (link (if (stringp links) (list links) links))
10212 (search-forward link nil links-end)
10213 (goto-char (match-beginning 0))
10214 (org-open-at-point))))))
10215 ;; On a footnote reference or at definition's label.
10216 ((or (eq type 'footnote-reference)
10217 (and (eq type 'footnote-definition)
10218 (save-excursion
10219 ;; Do not validate action when point is on the
10220 ;; spaces right after the footnote label, in order
10221 ;; to be on par with behavior on links.
10222 (skip-chars-forward " \t")
10223 (let ((begin
10224 (org-element-property :contents-begin context)))
10225 (if begin (< (point) begin)
10226 (= (org-element-property :post-affiliated context)
10227 (line-beginning-position)))))))
10228 (org-footnote-action))
10229 ;; On a clock line, make sure point is on the timestamp
10230 ;; before opening it.
10231 ((and (eq type 'clock)
10232 value
10233 (>= (point) (org-element-property :begin value))
10234 (<= (point) (org-element-property :end value)))
10235 (org-follow-timestamp-link))
10236 ((eq type 'src-block) (org-babel-open-src-block-result))
10237 ;; Do nothing on white spaces after an object.
10238 ((>= (point)
10239 (save-excursion
10240 (goto-char (org-element-property :end context))
10241 (skip-chars-backward " \t")
10242 (point)))
10243 (user-error "No link found"))
10244 ((eq type 'inline-src-block) (org-babel-open-src-block-result))
10245 ((eq type 'timestamp) (org-follow-timestamp-link))
10246 ((eq type 'link)
10247 (let ((type (org-element-property :type context))
10248 (path (org-link-unescape (org-element-property :path context))))
10249 ;; Switch back to REFERENCE-BUFFER needed when called in
10250 ;; a temporary buffer through `org-open-link-from-string'.
10251 (with-current-buffer (or reference-buffer (current-buffer))
10252 (cond
10253 ((equal type "file")
10254 (if (string-match "[*?{]" (file-name-nondirectory path))
10255 (dired path)
10256 ;; Look into `org-link-parameters' in order to find
10257 ;; a DEDICATED-FUNCTION to open file. The function
10258 ;; will be applied on raw link instead of parsed link
10259 ;; due to the limitation in `org-add-link-type'
10260 ;; ("open" function called with a single argument).
10261 ;; If no such function is found, fallback to
10262 ;; `org-open-file'.
10263 (let* ((option (org-element-property :search-option context))
10264 (app (org-element-property :application context))
10265 (dedicated-function
10266 (org-link-get-parameter
10267 (if app (concat type "+" app) type)
10268 :follow)))
10269 (if dedicated-function
10270 (funcall dedicated-function
10271 (concat path
10272 (and option (concat "::" option))))
10273 (apply #'org-open-file
10274 path
10275 (cond (arg)
10276 ((equal app "emacs") 'emacs)
10277 ((equal app "sys") 'system))
10278 (cond ((not option) nil)
10279 ((string-match-p "\\`[0-9]+\\'" option)
10280 (list (string-to-number option)))
10281 (t (list nil
10282 (org-link-unescape option)))))))))
10283 ((functionp (org-link-get-parameter type :follow))
10284 (funcall (org-link-get-parameter type :follow) path))
10285 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10286 (unless (run-hook-with-args-until-success
10287 'org-open-link-functions path)
10288 (if (not arg) (org-mark-ring-push)
10289 (switch-to-buffer-other-window
10290 (org-get-buffer-for-internal-link (current-buffer))))
10291 (let ((destination
10292 (org-with-wide-buffer
10293 (if (equal type "radio")
10294 (org-search-radio-target
10295 (org-element-property :path context))
10296 (org-link-search
10297 (pcase type
10298 ("custom-id" (concat "#" path))
10299 ("coderef" (format "(%s)" path))
10300 (_ path))
10301 ;; Prevent fuzzy links from matching
10302 ;; themselves.
10303 (and (equal type "fuzzy")
10304 (+ 2 (org-element-property :begin context)))))
10305 (point))))
10306 (unless (and (<= (point-min) destination)
10307 (>= (point-max) destination))
10308 (widen))
10309 (goto-char destination))))
10310 (t (browse-url-at-point))))))
10311 (t (user-error "No link found")))))
10312 (run-hook-with-args 'org-follow-link-hook))
10314 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10315 "Offer links in the current entry and return the selected link.
10316 If there is only one link, return it.
10317 If NTH is an integer, return the NTH link found.
10318 If ZERO is a string, check also this string for a link, and if
10319 there is one, return it."
10320 (with-current-buffer buffer
10321 (org-with-wide-buffer
10322 (goto-char marker)
10323 (let ((cnt ?0)
10324 have-zero end links link c)
10325 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10326 (push (match-string 0 zero) links)
10327 (setq cnt (1- cnt) have-zero t))
10328 (save-excursion
10329 (org-back-to-heading t)
10330 (setq end (save-excursion (outline-next-heading) (point)))
10331 (while (re-search-forward org-any-link-re end t)
10332 (push (match-string 0) links))
10333 (setq links (org-uniquify (reverse links))))
10334 (cond
10335 ((null links)
10336 (message "No links"))
10337 ((equal (length links) 1)
10338 (setq link (car links)))
10339 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10340 (setq link (nth (if have-zero nth (1- nth)) links)))
10341 (t ; we have to select a link
10342 (save-excursion
10343 (save-window-excursion
10344 (delete-other-windows)
10345 (with-output-to-temp-buffer "*Select Link*"
10346 (dolist (l links)
10347 (cond
10348 ((not (string-match org-bracket-link-regexp l))
10349 (princ (format "[%c] %s\n" (cl-incf cnt)
10350 (org-unbracket-string "<" ">" l))))
10351 ((match-end 3)
10352 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10353 (match-string 3 l) (match-string 1 l))))
10354 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10355 (match-string 1 l)))))))
10356 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10357 (message "Select link to open, RET to open all:")
10358 (setq c (read-char-exclusive))
10359 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10360 (when (equal c ?q) (user-error "Abort"))
10361 (if (equal c ?\C-m)
10362 (setq link links)
10363 (setq nth (- c ?0))
10364 (when have-zero (setq nth (1+ nth)))
10365 (unless (and (integerp nth) (>= (length links) nth))
10366 (user-error "Invalid link selection"))
10367 (setq link (nth (1- nth) links)))))
10368 (cons link end)))))
10370 ;; TODO: These functions are deprecated since `org-open-at-point'
10371 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10372 (defun org-open-file-with-system (path)
10373 "Open file at PATH using the system way of opening it."
10374 (org-open-file path 'system))
10375 (defun org-open-file-with-emacs (path)
10376 "Open file at PATH in Emacs."
10377 (org-open-file path 'emacs))
10380 ;;; File search
10382 (defvar org-create-file-search-functions nil
10383 "List of functions to construct the right search string for a file link.
10384 These functions are called in turn with point at the location to
10385 which the link should point.
10387 A function in the hook should first test if it would like to
10388 handle this file type, for example by checking the `major-mode'
10389 or the file extension. If it decides not to handle this file, it
10390 should just return nil to give other functions a chance. If it
10391 does handle the file, it must return the search string to be used
10392 when following the link. The search string will be part of the
10393 file link, given after a double colon, and `org-open-at-point'
10394 will automatically search for it. If special measures must be
10395 taken to make the search successful, another function should be
10396 added to the companion hook `org-execute-file-search-functions',
10397 which see.
10399 A function in this hook may also use `setq' to set the variable
10400 `description' to provide a suggestion for the descriptive text to
10401 be used for this link when it gets inserted into an Org buffer
10402 with \\[org-insert-link].")
10404 (defvar org-execute-file-search-functions nil
10405 "List of functions to execute a file search triggered by a link.
10407 Functions added to this hook must accept a single argument, the
10408 search string that was part of the file link, the part after the
10409 double colon. The function must first check if it would like to
10410 handle this search, for example by checking the `major-mode' or
10411 the file extension. If it decides not to handle this search, it
10412 should just return nil to give other functions a chance. If it
10413 does handle the search, it must return a non-nil value to keep
10414 other functions from trying.
10416 Each function can access the current prefix argument through the
10417 variable `current-prefix-arg'. Note that a single prefix is used
10418 to force opening a link in Emacs, so it may be good to only use a
10419 numeric or double prefix to guide the search function.
10421 In case this is needed, a function in this hook can also restore
10422 the window configuration before `org-open-at-point' was called using:
10424 (set-window-configuration org-window-config-before-follow-link)")
10426 (defun org-search-radio-target (target)
10427 "Search a radio target matching TARGET in current buffer.
10428 White spaces are not significant."
10429 (let ((re (format "<<<%s>>>"
10430 (mapconcat #'regexp-quote
10431 (split-string target)
10432 "[ \t]+\\(?:\n[ \t]*\\)?")))
10433 (origin (point)))
10434 (goto-char (point-min))
10435 (catch :radio-match
10436 (while (re-search-forward re nil t)
10437 (backward-char)
10438 (let ((object (org-element-context)))
10439 (when (eq (org-element-type object) 'radio-target)
10440 (goto-char (org-element-property :begin object))
10441 (org-show-context 'link-search)
10442 (throw :radio-match nil))))
10443 (goto-char origin)
10444 (user-error "No match for radio target: %s" target))))
10446 (defun org-link-search (s &optional avoid-pos stealth)
10447 "Search for a search string S.
10449 If S starts with \"#\", it triggers a custom ID search.
10451 If S is enclosed within parenthesis, it initiates a coderef
10452 search.
10454 If S is surrounded by forward slashes, it is interpreted as
10455 a regular expression. In Org mode files, this will create an
10456 `org-occur' sparse tree. In ordinary files, `occur' will be used
10457 to list matches. If the current buffer is in `dired-mode', grep
10458 will be used to search in all files.
10460 When AVOID-POS is given, ignore matches near that position.
10462 When optional argument STEALTH is non-nil, do not modify
10463 visibility around point, thus ignoring `org-show-context-detail'
10464 variable.
10466 Search is case-insensitive and ignores white spaces. Return type
10467 of matched result, which is either `dedicated' or `fuzzy'."
10468 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10469 (let* ((case-fold-search t)
10470 (origin (point))
10471 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10472 (starred (eq (string-to-char normalized) ?*))
10473 (words (split-string (if starred (substring s 1) s)))
10474 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10475 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10476 type)
10477 (cond
10478 ;; Check if there are any special search functions.
10479 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10480 ((eq (string-to-char s) ?#)
10481 ;; Look for a custom ID S if S starts with "#".
10482 (let* ((id (substring normalized 1))
10483 (match (org-find-property "CUSTOM_ID" id)))
10484 (if match (progn (goto-char match) (setf type 'dedicated))
10485 (error "No match for custom ID: %s" id))))
10486 ((string-match "\\`(\\(.*\\))\\'" normalized)
10487 ;; Look for coderef targets if S is enclosed within parenthesis.
10488 (let ((coderef (match-string-no-properties 1 normalized))
10489 (re (substring s-single-re 1 -1)))
10490 (goto-char (point-min))
10491 (catch :coderef-match
10492 (while (re-search-forward re nil t)
10493 (let ((element (org-element-at-point)))
10494 (when (and (memq (org-element-type element)
10495 '(example-block src-block))
10496 (org-match-line
10497 (concat ".*?" (org-src-coderef-regexp
10498 (org-src-coderef-format element)
10499 coderef))))
10500 (setq type 'dedicated)
10501 (goto-char (match-beginning 2))
10502 (throw :coderef-match nil))))
10503 (goto-char origin)
10504 (error "No match for coderef: %s" coderef))))
10505 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10506 ;; Look for a regular expression.
10507 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10508 (match-string 1 s)))
10509 ;; From here, we handle fuzzy links.
10511 ;; Look for targets, only if not in a headline search.
10512 ((and (not starred)
10513 (let ((target (format "<<%s>>" s-multi-re)))
10514 (catch :target-match
10515 (goto-char (point-min))
10516 (while (re-search-forward target nil t)
10517 (backward-char)
10518 (let ((context (org-element-context)))
10519 (when (eq (org-element-type context) 'target)
10520 (setq type 'dedicated)
10521 (goto-char (org-element-property :begin context))
10522 (throw :target-match t))))
10523 nil))))
10524 ;; Look for elements named after S, only if not in a headline
10525 ;; search.
10526 ((and (not starred)
10527 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10528 (catch :name-match
10529 (goto-char (point-min))
10530 (while (re-search-forward name nil t)
10531 (let ((element (org-element-at-point)))
10532 (when (equal words
10533 (split-string
10534 (org-element-property :name element)))
10535 (setq type 'dedicated)
10536 (beginning-of-line)
10537 (throw :name-match t))))
10538 nil))))
10539 ;; Regular text search. Prefer headlines in Org mode buffers.
10540 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10541 ;; statistics cookies and tags.
10542 ((and (derived-mode-p 'org-mode)
10543 (let ((title-re
10544 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10545 org-outline-regexp-bol
10546 org-comment-string
10547 (mapconcat #'regexp-quote words ".+")))
10548 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10549 (comment-re (eval-when-compile
10550 (format "\\`%s[ \t]+" org-comment-string))))
10551 (goto-char (point-min))
10552 (catch :found
10553 (while (re-search-forward title-re nil t)
10554 (when (equal words
10555 (split-string
10556 (replace-regexp-in-string
10557 cookie-re ""
10558 (replace-regexp-in-string
10559 comment-re "" (org-get-heading t t t)))))
10560 (throw :found t)))
10561 nil)))
10562 (beginning-of-line)
10563 (setq type 'dedicated))
10564 ;; Offer to create non-existent headline depending on
10565 ;; `org-link-search-must-match-exact-headline'.
10566 ((and (derived-mode-p 'org-mode)
10567 (not org-link-search-inhibit-query)
10568 (eq org-link-search-must-match-exact-headline 'query-to-create)
10569 (yes-or-no-p "No match - create this as a new heading? "))
10570 (goto-char (point-max))
10571 (unless (bolp) (newline))
10572 (org-insert-heading nil t t)
10573 (insert s "\n")
10574 (beginning-of-line 0))
10575 ;; Only headlines are looked after. No need to process
10576 ;; further: throw an error.
10577 ((and (derived-mode-p 'org-mode)
10578 (or starred org-link-search-must-match-exact-headline))
10579 (goto-char origin)
10580 (error "No match for fuzzy expression: %s" normalized))
10581 ;; Regular text search.
10582 ((catch :fuzzy-match
10583 (goto-char (point-min))
10584 (while (re-search-forward s-multi-re nil t)
10585 ;; Skip match if it contains AVOID-POS or it is included in
10586 ;; a link with a description but outside the description.
10587 (unless (or (and avoid-pos
10588 (<= (match-beginning 0) avoid-pos)
10589 (> (match-end 0) avoid-pos))
10590 (and (save-match-data
10591 (org-in-regexp org-bracket-link-regexp))
10592 (match-beginning 3)
10593 (or (> (match-beginning 3) (point))
10594 (<= (match-end 3) (point)))
10595 (org-element-lineage
10596 (save-match-data (org-element-context))
10597 '(link) t)))
10598 (goto-char (match-beginning 0))
10599 (setq type 'fuzzy)
10600 (throw :fuzzy-match t)))
10601 nil))
10602 ;; All failed. Throw an error.
10603 (t (goto-char origin)
10604 (error "No match for fuzzy expression: %s" normalized)))
10605 ;; Disclose surroundings of match, if appropriate.
10606 (when (and (derived-mode-p 'org-mode) (not stealth))
10607 (org-show-context 'link-search))
10608 type))
10610 (defun org-get-buffer-for-internal-link (buffer)
10611 "Return a buffer to be used for displaying the link target of internal links."
10612 (cond
10613 ((not org-display-internal-link-with-indirect-buffer)
10614 buffer)
10615 ((string-suffix-p "(Clone)" (buffer-name buffer))
10616 (message "Buffer is already a clone, not making another one")
10617 ;; we also do not modify visibility in this case
10618 buffer)
10619 (t ; make a new indirect buffer for displaying the link
10620 (let* ((bn (buffer-name buffer))
10621 (ibn (concat bn "(Clone)"))
10622 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10623 (with-current-buffer ib (org-overview))
10624 ib))))
10626 (defun org-do-occur (regexp &optional cleanup)
10627 "Call the Emacs command `occur'.
10628 If CLEANUP is non-nil, remove the printout of the regular expression
10629 in the *Occur* buffer. This is useful if the regex is long and not useful
10630 to read."
10631 (occur regexp)
10632 (when cleanup
10633 (let ((cwin (selected-window)) win beg end)
10634 (when (setq win (get-buffer-window "*Occur*"))
10635 (select-window win))
10636 (goto-char (point-min))
10637 (when (re-search-forward "match[a-z]+" nil t)
10638 (setq beg (match-end 0))
10639 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10640 (setq end (1- (match-beginning 0)))))
10641 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10642 (goto-char (point-min))
10643 (select-window cwin))))
10646 ;;; The Mark Ring
10648 (defvar org-mark-ring nil
10649 "Mark ring for positions before jumps in Org mode.")
10651 (defvar org-mark-ring-last-goto nil
10652 "Last position in the mark ring used to go back.")
10654 ;; Fill and close the ring
10655 (setq org-mark-ring nil)
10656 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10658 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10659 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10660 org-mark-ring)
10662 (defun org-mark-ring-push (&optional pos buffer)
10663 "Put the current position into the mark ring and rotate it.
10664 Also push position into the Emacs mark ring. If optional
10665 argument POS and BUFFER are not nil, mark this location instead."
10666 (interactive)
10667 (let ((pos (or pos (point)))
10668 (buffer (or buffer (current-buffer))))
10669 (with-current-buffer buffer
10670 (org-with-point-at pos (push-mark nil t)))
10671 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10672 (move-marker (car org-mark-ring) pos buffer))
10673 (message
10674 (substitute-command-keys
10675 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10677 (defun org-mark-ring-goto (&optional n)
10678 "Jump to the previous position in the mark ring.
10679 With prefix arg N, jump back that many stored positions. When
10680 called several times in succession, walk through the entire ring.
10681 Org mode commands jumping to a different position in the current file,
10682 or to another Org file, automatically push the old position onto the ring."
10683 (interactive "p")
10684 (let (p m)
10685 (if (eq last-command this-command)
10686 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10687 (setq p org-mark-ring))
10688 (setq org-mark-ring-last-goto p)
10689 (setq m (car p))
10690 (pop-to-buffer-same-window (marker-buffer m))
10691 (goto-char m)
10692 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10694 (defun org-add-angle-brackets (s)
10695 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10696 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10699 ;;; Following specific links
10701 (defvar org-agenda-buffer-tmp-name)
10702 (defvar org-agenda-start-on-weekday)
10703 (defun org-follow-timestamp-link ()
10704 "Open an agenda view for the time-stamp date/range at point."
10705 (cond
10706 ((org-at-date-range-p t)
10707 (let ((org-agenda-start-on-weekday)
10708 (t1 (match-string 1))
10709 (t2 (match-string 2)) tt1 tt2)
10710 (setq tt1 (time-to-days (org-time-string-to-time t1))
10711 tt2 (time-to-days (org-time-string-to-time t2)))
10712 (let ((org-agenda-buffer-tmp-name
10713 (format "*Org Agenda(a:%s)"
10714 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10715 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10716 ((org-at-timestamp-p 'lax)
10717 (let ((org-agenda-buffer-tmp-name
10718 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10719 (org-agenda-list nil (time-to-days (org-time-string-to-time
10720 (substring (match-string 1) 0 10)))
10721 1)))
10722 (t (error "This should not happen"))))
10725 ;;; Following file links
10726 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10727 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10728 (declare-function mailcap-mime-info
10729 "mailcap" (string &optional request no-decode))
10730 (defvar org-wait nil)
10731 (defun org-open-file (path &optional in-emacs line search)
10732 "Open the file at PATH.
10733 First, this expands any special file name abbreviations. Then the
10734 configuration variable `org-file-apps' is checked if it contains an
10735 entry for this file type, and if yes, the corresponding command is launched.
10737 If no application is found, Emacs simply visits the file.
10739 With optional prefix argument IN-EMACS, Emacs will visit the file.
10740 With a double \\[universal-argument] \\[universal-argument] \
10741 prefix arg, Org tries to avoid opening in Emacs
10742 and to use an external application to visit the file.
10744 Optional LINE specifies a line to go to, optional SEARCH a string
10745 to search for. If LINE or SEARCH is given, the file will be
10746 opened in Emacs, unless an entry from org-file-apps that makes
10747 use of groups in a regexp matches.
10749 If you want to change the way frames are used when following a
10750 link, please customize `org-link-frame-setup'.
10752 If the file does not exist, an error is thrown."
10753 (let* ((file (if (equal path "")
10754 buffer-file-name
10755 (substitute-in-file-name (expand-file-name path))))
10756 (file-apps (append org-file-apps (org-default-apps)))
10757 (apps (cl-remove-if
10758 'org-file-apps-entry-match-against-dlink-p file-apps))
10759 (apps-dlink (cl-remove-if-not
10760 'org-file-apps-entry-match-against-dlink-p file-apps))
10761 (remp (and (assq 'remote apps) (file-remote-p file)))
10762 (dirp (unless remp (file-directory-p file)))
10763 (file (if (and dirp org-open-directory-means-index-dot-org)
10764 (concat (file-name-as-directory file) "index.org")
10765 file))
10766 (a-m-a-p (assq 'auto-mode apps))
10767 (dfile (downcase file))
10768 ;; Reconstruct the original link from the PATH, LINE and
10769 ;; SEARCH args.
10770 (link (cond (line (concat file "::" (number-to-string line)))
10771 (search (concat file "::" search))
10772 (t file)))
10773 (dlink (downcase link))
10774 (ext
10775 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10776 (match-string 1 dfile)))
10777 (save-position-maybe
10778 (let ((old-buffer (current-buffer))
10779 (old-pos (point))
10780 (old-mode major-mode))
10781 (lambda ()
10782 (and (derived-mode-p 'org-mode)
10783 (eq old-mode 'org-mode)
10784 (or (not (eq old-buffer (current-buffer)))
10785 (not (eq old-pos (point))))
10786 (org-mark-ring-push old-pos old-buffer)))))
10787 cmd link-match-data)
10788 (cond
10789 ((member in-emacs '((16) system))
10790 (setq cmd (cdr (assq 'system apps))))
10791 (in-emacs (setq cmd 'emacs))
10793 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10794 (and dirp (cdr (assq 'directory apps)))
10795 ;; First, try matching against apps-dlink if we
10796 ;; get a match here, store the match data for
10797 ;; later.
10798 (let ((match (assoc-default dlink apps-dlink
10799 'string-match)))
10800 (if match
10801 (progn (setq link-match-data (match-data))
10802 match)
10803 (progn (setq in-emacs (or in-emacs line search))
10804 nil))) ; if we have no match in apps-dlink,
10805 ; always open the file in emacs if line or search
10806 ; is given (for backwards compatibility)
10807 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10808 'string-match)
10809 (cdr (assoc ext apps))
10810 (cdr (assq t apps))))))
10811 (when (eq cmd 'system)
10812 (setq cmd (cdr (assq 'system apps))))
10813 (when (eq cmd 'default)
10814 (setq cmd (cdr (assoc t apps))))
10815 (when (eq cmd 'mailcap)
10816 (require 'mailcap)
10817 (mailcap-parse-mailcaps)
10818 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10819 (command (mailcap-mime-info mime-type)))
10820 (if (stringp command)
10821 (setq cmd command)
10822 (setq cmd 'emacs))))
10823 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10824 (not (file-exists-p file))
10825 (not org-open-non-existing-files))
10826 (user-error "No such file: %s" file))
10827 (cond
10828 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10829 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10830 (while (string-match "['\"]%s['\"]" cmd)
10831 (setq cmd (replace-match "%s" t t cmd)))
10832 (setq cmd (replace-regexp-in-string
10833 "%s"
10834 (shell-quote-argument (convert-standard-filename file))
10836 nil t))
10838 ;; Replace "%1", "%2" etc. in command with group matches from regex
10839 (save-match-data
10840 (let ((match-index 1)
10841 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10842 (set-match-data link-match-data)
10843 (while (<= match-index number-of-groups)
10844 (let ((regex (concat "%" (number-to-string match-index)))
10845 (replace-with (match-string match-index dlink)))
10846 (while (string-match regex cmd)
10847 (setq cmd (replace-match replace-with t t cmd))))
10848 (setq match-index (+ match-index 1)))))
10850 (save-window-excursion
10851 (message "Running %s...done" cmd)
10852 (start-process-shell-command cmd nil cmd)
10853 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10854 ((or (stringp cmd)
10855 (eq cmd 'emacs))
10856 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10857 (widen)
10858 (cond (line (org-goto-line line)
10859 (when (derived-mode-p 'org-mode) (org-reveal)))
10860 (search (condition-case err
10861 (org-link-search search)
10862 ;; Save position before error-ing out so user
10863 ;; can easily move back to the original buffer.
10864 (error (funcall save-position-maybe)
10865 (error (nth 1 err)))))))
10866 ((functionp cmd)
10867 (save-match-data
10868 (set-match-data link-match-data)
10869 (condition-case nil
10870 (funcall cmd file link)
10871 ;; FIXME: Remove this check when most default installations
10872 ;; of Emacs have at least Org 9.0.
10873 ((debug wrong-number-of-arguments wrong-type-argument
10874 invalid-function)
10875 (user-error "Please see Org News for version 9.0 about \
10876 `org-file-apps'--Lisp error: %S" cmd)))))
10877 ((consp cmd)
10878 ;; FIXME: Remove this check when most default installations of
10879 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10880 ;; fall back to `org-link-frame-setup' for an old usage of
10881 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10882 (user-error "Please see Org News for version 9.0 about \
10883 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10884 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10885 (funcall save-position-maybe)))
10887 (defun org-file-apps-entry-match-against-dlink-p (entry)
10888 "This function returns non-nil if `entry' uses a regular
10889 expression which should be matched against the whole link by
10890 org-open-file.
10892 It assumes that is the case when the entry uses a regular
10893 expression which has at least one grouping construct and the
10894 action is either a lisp form or a command string containing
10895 `%1', i.e. using at least one subexpression match as a
10896 parameter."
10897 (let ((selector (car entry))
10898 (action (cdr entry)))
10899 (if (stringp selector)
10900 (and (> (regexp-opt-depth selector) 0)
10901 (or (and (stringp action)
10902 (string-match "%[0-9]" action))
10903 (consp action)))
10904 nil)))
10906 (defun org-default-apps ()
10907 "Return the default applications for this operating system."
10908 (cond
10909 ((eq system-type 'darwin)
10910 org-file-apps-defaults-macosx)
10911 ((eq system-type 'windows-nt)
10912 org-file-apps-defaults-windowsnt)
10913 (t org-file-apps-defaults-gnu)))
10915 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10916 "Convert extensions to regular expressions in the cars of LIST.
10917 Also, weed out any non-string entries, because the return value is used
10918 only for regexp matching.
10919 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10920 point to the symbol `emacs', indicating that the file should
10921 be opened in Emacs."
10922 (append
10923 (delq nil
10924 (mapcar (lambda (x)
10925 (unless (not (stringp (car x)))
10926 (if (string-match "\\W" (car x))
10928 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10929 list))
10930 (when add-auto-mode
10931 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10934 ;;;; Refiling
10936 (defun org-get-org-file ()
10937 "Read a filename, with default directory `org-directory'."
10938 (let ((default (or org-default-notes-file remember-data-file)))
10939 (read-file-name (format "File name [%s]: " default)
10940 (file-name-as-directory org-directory)
10941 default)))
10943 (defun org-notes-order-reversed-p ()
10944 "Check if the current file should receive notes in reversed order."
10945 (cond
10946 ((not org-reverse-note-order) nil)
10947 ((eq t org-reverse-note-order) t)
10948 ((not (listp org-reverse-note-order)) nil)
10949 (t (catch 'exit
10950 (dolist (entry org-reverse-note-order)
10951 (when (string-match (car entry) buffer-file-name)
10952 (throw 'exit (cdr entry))))))))
10954 (defvar org-refile-target-table nil
10955 "The list of refile targets, created by `org-refile'.")
10957 (defvar org-agenda-new-buffers nil
10958 "Buffers created to visit agenda files.")
10960 (defvar org-refile-cache nil
10961 "Cache for refile targets.")
10963 (defvar org-refile-markers nil
10964 "All the markers used for caching refile locations.")
10966 (defun org-refile-marker (pos)
10967 "Get a new refile marker, but only if caching is in use."
10968 (if (not org-refile-use-cache)
10970 (let ((m (make-marker)))
10971 (move-marker m pos)
10972 (push m org-refile-markers)
10973 m)))
10975 (defun org-refile-cache-clear ()
10976 "Clear the refile cache and disable all the markers."
10977 (dolist (m org-refile-markers) (move-marker m nil))
10978 (setq org-refile-markers nil)
10979 (setq org-refile-cache nil)
10980 (message "Refile cache has been cleared"))
10982 (defun org-refile-cache-check-set (set)
10983 "Check if all the markers in the cache still have live buffers."
10984 (let (marker)
10985 (catch 'exit
10986 (while (and set (setq marker (nth 3 (pop set))))
10987 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10988 (when (and marker (null (marker-buffer marker)))
10989 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10990 (sit-for 3)
10991 (throw 'exit nil)))
10992 t)))
10994 (defun org-refile-cache-put (set &rest identifiers)
10995 "Push the refile targets SET into the cache, under IDENTIFIERS."
10996 (let* ((key (sha1 (prin1-to-string identifiers)))
10997 (entry (assoc key org-refile-cache)))
10998 (if entry
10999 (setcdr entry set)
11000 (push (cons key set) org-refile-cache))))
11002 (defun org-refile-cache-get (&rest identifiers)
11003 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11004 (cond
11005 ((not org-refile-cache) nil)
11006 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11008 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11009 org-refile-cache))))
11010 (and set (org-refile-cache-check-set set) set)))))
11012 (defvar org-outline-path-cache nil
11013 "Alist between buffer positions and outline paths.
11014 It value is an alist (POSITION . PATH) where POSITION is the
11015 buffer position at the beginning of an entry and PATH is a list
11016 of strings describing the outline path for that entry, in reverse
11017 order.")
11019 (defun org-refile-get-targets (&optional default-buffer)
11020 "Produce a table with refile targets."
11021 (let ((case-fold-search nil)
11022 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11023 (entries (or org-refile-targets '((nil . (:level . 1)))))
11024 targets tgs files desc descre)
11025 (message "Getting targets...")
11026 (with-current-buffer (or default-buffer (current-buffer))
11027 (dolist (entry entries)
11028 (setq files (car entry) desc (cdr entry))
11029 (cond
11030 ((null files) (setq files (list (current-buffer))))
11031 ((eq files 'org-agenda-files)
11032 (setq files (org-agenda-files 'unrestricted)))
11033 ((and (symbolp files) (fboundp files))
11034 (setq files (funcall files)))
11035 ((and (symbolp files) (boundp files))
11036 (setq files (symbol-value files))))
11037 (when (stringp files) (setq files (list files)))
11038 (cond
11039 ((eq (car desc) :tag)
11040 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11041 ((eq (car desc) :todo)
11042 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11043 ((eq (car desc) :regexp)
11044 (setq descre (cdr desc)))
11045 ((eq (car desc) :level)
11046 (setq descre (concat "^\\*\\{" (number-to-string
11047 (if org-odd-levels-only
11048 (1- (* 2 (cdr desc)))
11049 (cdr desc)))
11050 "\\}[ \t]")))
11051 ((eq (car desc) :maxlevel)
11052 (setq descre (concat "^\\*\\{1," (number-to-string
11053 (if org-odd-levels-only
11054 (1- (* 2 (cdr desc)))
11055 (cdr desc)))
11056 "\\}[ \t]")))
11057 (t (error "Bad refiling target description %s" desc)))
11058 (dolist (f files)
11059 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11061 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11062 (progn
11063 (when (bufferp f)
11064 (setq f (buffer-file-name (buffer-base-buffer f))))
11065 (setq f (and f (expand-file-name f)))
11066 (when (eq org-refile-use-outline-path 'file)
11067 (push (list (file-name-nondirectory f) f nil nil) tgs))
11068 (when (eq org-refile-use-outline-path 'buffer-name)
11069 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11070 (when (eq org-refile-use-outline-path 'full-file-path)
11071 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11072 (org-with-wide-buffer
11073 (goto-char (point-min))
11074 (setq org-outline-path-cache nil)
11075 (while (re-search-forward descre nil t)
11076 (beginning-of-line)
11077 (let ((case-fold-search nil))
11078 (looking-at org-complex-heading-regexp))
11079 (let ((begin (point))
11080 (heading (match-string-no-properties 4)))
11081 (unless (or (and
11082 org-refile-target-verify-function
11083 (not
11084 (funcall org-refile-target-verify-function)))
11085 (not heading))
11086 (let ((re (format org-complex-heading-regexp-format
11087 (regexp-quote heading)))
11088 (target
11089 (if (not org-refile-use-outline-path) heading
11090 (mapconcat
11091 #'identity
11092 (append
11093 (pcase org-refile-use-outline-path
11094 (`file (list (file-name-nondirectory
11095 (buffer-file-name
11096 (buffer-base-buffer)))))
11097 (`full-file-path
11098 (list (buffer-file-name
11099 (buffer-base-buffer))))
11100 (`buffer-name
11101 (list (buffer-name
11102 (buffer-base-buffer))))
11103 (_ nil))
11104 (mapcar (lambda (s) (replace-regexp-in-string
11105 "/" "\\/" s nil t))
11106 (org-get-outline-path t t)))
11107 "/"))))
11108 (push (list target f re (org-refile-marker (point)))
11109 tgs)))
11110 (when (= (point) begin)
11111 ;; Verification function has not moved point.
11112 (end-of-line)))))))
11113 (when org-refile-use-cache
11114 (org-refile-cache-put tgs (buffer-file-name) descre))
11115 (setq targets (append tgs targets))))))
11116 (message "Getting targets...done")
11117 (delete-dups (nreverse targets))))
11119 (defun org--get-outline-path-1 (&optional use-cache)
11120 "Return outline path to current headline.
11122 Outline path is a list of strings, in reverse order. When
11123 optional argument USE-CACHE is non-nil, make use of a cache. See
11124 `org-get-outline-path' for details.
11126 Assume buffer is widened and point is on a headline."
11127 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11128 (let ((p (point))
11129 (heading (let ((case-fold-search nil))
11130 (looking-at org-complex-heading-regexp)
11131 (if (not (match-end 4)) ""
11132 ;; Remove statistics cookies.
11133 (org-trim
11134 (org-link-display-format
11135 (replace-regexp-in-string
11136 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11137 (match-string-no-properties 4))))))))
11138 (if (org-up-heading-safe)
11139 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11140 (when use-cache
11141 (push (cons p path) org-outline-path-cache))
11142 path)
11143 ;; This is a new root node. Since we assume we are moving
11144 ;; forward, we can drop previous cache so as to limit number
11145 ;; of associations there.
11146 (let ((path (list heading)))
11147 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11148 path)))))
11150 (defun org-get-outline-path (&optional with-self use-cache)
11151 "Return the outline path to the current entry.
11153 An outline path is a list of ancestors for current headline, as
11154 a list of strings. Statistics cookies are removed and links are
11155 replaced with their description, if any, or their path otherwise.
11157 When optional argument WITH-SELF is non-nil, the path also
11158 includes the current headline.
11160 When optional argument USE-CACHE is non-nil, cache outline paths
11161 between calls to this function so as to avoid backtracking. This
11162 argument is useful when planning to find more than one outline
11163 path in the same document. In that case, there are two
11164 conditions to satisfy:
11165 - `org-outline-path-cache' is set to nil before starting the
11166 process;
11167 - outline paths are computed by increasing buffer positions."
11168 (org-with-wide-buffer
11169 (and (or (and with-self (org-back-to-heading t))
11170 (org-up-heading-safe))
11171 (reverse (org--get-outline-path-1 use-cache)))))
11173 (defun org-format-outline-path (path &optional width prefix separator)
11174 "Format the outline path PATH for display.
11175 WIDTH is the maximum number of characters that is available.
11176 PREFIX is a prefix to be included in the returned string,
11177 such as the file name.
11178 SEPARATOR is inserted between the different parts of the path,
11179 the default is \"/\"."
11180 (setq width (or width 79))
11181 (setq path (delq nil path))
11182 (unless (> width 0)
11183 (user-error "Argument `width' must be positive"))
11184 (setq separator (or separator "/"))
11185 (let* ((org-odd-levels-only nil)
11186 (fpath (concat
11187 prefix (and prefix path separator)
11188 (mapconcat
11189 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11190 (cl-loop for head in path
11191 for n from 0
11192 collect (org-add-props
11193 head nil 'face
11194 (nth (% n org-n-level-faces) org-level-faces)))
11195 separator))))
11196 (when (> (length fpath) width)
11197 (if (< width 7)
11198 ;; It's unlikely that `width' will be this small, but don't
11199 ;; waste characters by adding ".." if it is.
11200 (setq fpath (substring fpath 0 width))
11201 (setf (substring fpath (- width 2)) "..")))
11202 fpath))
11204 (defun org-display-outline-path (&optional file current separator just-return-string)
11205 "Display the current outline path in the echo area.
11207 If FILE is non-nil, prepend the output with the file name.
11208 If CURRENT is non-nil, append the current heading to the output.
11209 SEPARATOR is passed through to `org-format-outline-path'. It separates
11210 the different parts of the path and defaults to \"/\".
11211 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11212 (interactive "P")
11213 (let* (case-fold-search
11214 (bfn (buffer-file-name (buffer-base-buffer)))
11215 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11216 res)
11217 (when current (setq path (append path
11218 (save-excursion
11219 (org-back-to-heading t)
11220 (when (looking-at org-complex-heading-regexp)
11221 (list (match-string 4)))))))
11222 (setq res
11223 (org-format-outline-path
11224 path
11225 (1- (frame-width))
11226 (and file bfn (concat (file-name-nondirectory bfn) separator))
11227 separator))
11228 (if just-return-string
11229 (org-no-properties res)
11230 (org-unlogged-message "%s" res))))
11232 (defvar org-refile-history nil
11233 "History for refiling operations.")
11235 (defvar org-after-refile-insert-hook nil
11236 "Hook run after `org-refile' has inserted its stuff at the new location.
11237 Note that this is still *before* the stuff will be removed from
11238 the *old* location.")
11240 (defvar org-capture-last-stored-marker)
11241 (defvar org-refile-keep nil
11242 "Non-nil means `org-refile' will copy instead of refile.")
11244 (defun org-copy ()
11245 "Like `org-refile', but copy."
11246 (interactive)
11247 (let ((org-refile-keep t))
11248 (org-refile nil nil nil "Copy")))
11250 (defun org-refile (&optional arg default-buffer rfloc msg)
11251 "Move the entry or entries at point to another heading.
11253 The list of target headings is compiled using the information in
11254 `org-refile-targets', which see.
11256 At the target location, the entry is filed as a subitem of the
11257 target heading. Depending on `org-reverse-note-order', the new
11258 subitem will either be the first or the last subitem.
11260 If there is an active region, all entries in that region will be
11261 refiled. However, the region must fulfill the requirement that
11262 the first heading sets the top-level of the moved text.
11264 With a `\\[universal-argument]' ARG, the command will only visit the target \
11265 location
11266 and not actually move anything.
11268 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11269 location where the last
11270 refiling operation has put the subtree.
11272 With a numeric prefix argument of `2', refile to the running clock.
11274 With a numeric prefix argument of `3', emulate `org-refile-keep'
11275 being set to t and copy to the target location, don't move it.
11276 Beware that keeping refiled entries may result in duplicated ID
11277 properties.
11279 RFLOC can be a refile location obtained in a different way.
11281 MSG is a string to replace \"Refile\" in the default prompt with
11282 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11284 See also `org-refile-use-outline-path'.
11286 If you are using target caching (see `org-refile-use-cache'), you
11287 have to clear the target cache in order to find new targets.
11288 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11289 prefix argument (`C-u C-u C-u C-c C-w')."
11290 (interactive "P")
11291 (if (member arg '(0 (64)))
11292 (org-refile-cache-clear)
11293 (let* ((actionmsg (cond (msg msg)
11294 ((equal arg 3) "Refile (and keep)")
11295 (t "Refile")))
11296 (regionp (org-region-active-p))
11297 (region-start (and regionp (region-beginning)))
11298 (region-end (and regionp (region-end)))
11299 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11300 pos it nbuf file level reversed)
11301 (setq last-command nil)
11302 (when regionp
11303 (goto-char region-start)
11304 (or (bolp) (goto-char (point-at-bol)))
11305 (setq region-start (point))
11306 (unless (or (org-kill-is-subtree-p
11307 (buffer-substring region-start region-end))
11308 (prog1 org-refile-active-region-within-subtree
11309 (let ((s (point-at-eol)))
11310 (org-toggle-heading)
11311 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11312 (user-error "The region is not a (sequence of) subtree(s)")))
11313 (if (equal arg '(16))
11314 (org-refile-goto-last-stored)
11315 (when (or
11316 (and (equal arg 2)
11317 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11318 (prog1
11319 (setq it (list (or org-clock-heading "running clock")
11320 (buffer-file-name
11321 (marker-buffer org-clock-hd-marker))
11323 (marker-position org-clock-hd-marker)))
11324 (setq arg nil)))
11325 (setq it
11326 (or rfloc
11327 (let (heading-text)
11328 (save-excursion
11329 (unless (and arg (listp arg))
11330 (org-back-to-heading t)
11331 (setq heading-text
11332 (replace-regexp-in-string
11333 org-bracket-link-regexp
11334 "\\3"
11335 (or (nth 4 (org-heading-components))
11336 ""))))
11337 (org-refile-get-location
11338 (cond ((and arg (listp arg)) "Goto")
11339 (regionp (concat actionmsg " region to"))
11340 (t (concat actionmsg " subtree \""
11341 heading-text "\" to")))
11342 default-buffer
11343 (and (not (equal '(4) arg))
11344 org-refile-allow-creating-parent-nodes)))))))
11345 (setq file (nth 1 it)
11346 pos (nth 3 it))
11347 (when (and (not arg)
11349 (equal (buffer-file-name) file)
11350 (if regionp
11351 (and (>= pos region-start)
11352 (<= pos region-end))
11353 (and (>= pos (point))
11354 (< pos (save-excursion
11355 (org-end-of-subtree t t))))))
11356 (error "Cannot refile to position inside the tree or region"))
11357 (setq nbuf (or (find-buffer-visiting file)
11358 (find-file-noselect file)))
11359 (if (and arg (not (equal arg 3)))
11360 (progn
11361 (pop-to-buffer-same-window nbuf)
11362 (goto-char (cond (pos)
11363 ((org-notes-order-reversed-p) (point-min))
11364 (t (point-max))))
11365 (org-show-context 'org-goto))
11366 (if regionp
11367 (progn
11368 (org-kill-new (buffer-substring region-start region-end))
11369 (org-save-markers-in-region region-start region-end))
11370 (org-copy-subtree 1 nil t))
11371 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11372 (find-file-noselect file)))
11373 (setq reversed (org-notes-order-reversed-p))
11374 (org-with-wide-buffer
11375 (if pos
11376 (progn
11377 (goto-char pos)
11378 (setq level (org-get-valid-level (funcall outline-level) 1))
11379 (goto-char
11380 (if reversed
11381 (or (outline-next-heading) (point-max))
11382 (or (save-excursion (org-get-next-sibling))
11383 (org-end-of-subtree t t)
11384 (point-max)))))
11385 (setq level 1)
11386 (if (not reversed)
11387 (goto-char (point-max))
11388 (goto-char (point-min))
11389 (or (outline-next-heading) (goto-char (point-max)))))
11390 (unless (bolp) (newline))
11391 (org-paste-subtree level nil nil t)
11392 (when org-log-refile
11393 (org-add-log-setup 'refile nil nil org-log-refile)
11394 (unless (eq org-log-refile 'note)
11395 (save-excursion (org-add-log-note))))
11396 (and org-auto-align-tags
11397 (let ((org-loop-over-headlines-in-active-region nil))
11398 (org-align-tags)))
11399 (let ((bookmark-name (plist-get org-bookmark-names-plist
11400 :last-refile)))
11401 (when bookmark-name
11402 (with-demoted-errors
11403 (bookmark-set bookmark-name))))
11404 ;; If we are refiling for capture, make sure that the
11405 ;; last-capture pointers point here
11406 (when (bound-and-true-p org-capture-is-refiling)
11407 (let ((bookmark-name (plist-get org-bookmark-names-plist
11408 :last-capture-marker)))
11409 (when bookmark-name
11410 (with-demoted-errors
11411 (bookmark-set bookmark-name))))
11412 (move-marker org-capture-last-stored-marker (point)))
11413 (when (fboundp 'deactivate-mark) (deactivate-mark))
11414 (run-hooks 'org-after-refile-insert-hook)))
11415 (unless org-refile-keep
11416 (if regionp
11417 (delete-region (point) (+ (point) (- region-end region-start)))
11418 (org-preserve-local-variables
11419 (delete-region
11420 (and (org-back-to-heading t) (point))
11421 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11422 (when (featurep 'org-inlinetask)
11423 (org-inlinetask-remove-END-maybe))
11424 (setq org-markers-to-move nil)
11425 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11427 (defun org-refile-goto-last-stored ()
11428 "Go to the location where the last refile was stored."
11429 (interactive)
11430 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11431 (message "This is the location of the last refile"))
11433 (defun org-refile--get-location (refloc tbl)
11434 "When user refile to REFLOC, find the associated target in TBL.
11435 Also check `org-refile-target-table'."
11436 (car (delq
11438 (mapcar
11439 (lambda (r) (or (assoc r tbl)
11440 (assoc r org-refile-target-table)))
11441 (list (replace-regexp-in-string "/$" "" refloc)
11442 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11444 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11445 "Prompt the user for a refile location, using PROMPT.
11446 PROMPT should not be suffixed with a colon and a space, because
11447 this function appends the default value from
11448 `org-refile-history' automatically, if that is not empty."
11449 (let ((org-refile-targets org-refile-targets)
11450 (org-refile-use-outline-path org-refile-use-outline-path))
11451 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11452 (unless org-refile-target-table
11453 (user-error "No refile targets"))
11454 (let* ((cbuf (current-buffer))
11455 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11456 (cfunc (if (and org-refile-use-outline-path
11457 org-outline-path-complete-in-steps)
11458 #'org-olpath-completing-read
11459 #'completing-read))
11460 (extra (if org-refile-use-outline-path "/" ""))
11461 (cbnex (concat (buffer-name) extra))
11462 (filename (and cfn (expand-file-name cfn)))
11463 (tbl (mapcar
11464 (lambda (x)
11465 (if (and (not (member org-refile-use-outline-path
11466 '(file full-file-path)))
11467 (not (equal filename (nth 1 x))))
11468 (cons (concat (car x) extra " ("
11469 (file-name-nondirectory (nth 1 x)) ")")
11470 (cdr x))
11471 (cons (concat (car x) extra) (cdr x))))
11472 org-refile-target-table))
11473 (completion-ignore-case t)
11474 cdef
11475 (prompt (concat prompt
11476 (or (and (car org-refile-history)
11477 (concat " (default " (car org-refile-history) ")"))
11478 (and (assoc cbnex tbl) (setq cdef cbnex)
11479 (concat " (default " cbnex ")"))) ": "))
11480 pa answ parent-target child parent old-hist)
11481 (setq old-hist org-refile-history)
11482 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11483 nil 'org-refile-history (or cdef (car org-refile-history))))
11484 (if (setq pa (org-refile--get-location answ tbl))
11485 (progn
11486 (org-refile-check-position pa)
11487 (when (or (not org-refile-history)
11488 (not (eq old-hist org-refile-history))
11489 (not (equal (car pa) (car org-refile-history))))
11490 (setq org-refile-history
11491 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11492 org-refile-history
11493 (cdr org-refile-history))))
11494 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11495 (pop org-refile-history)))
11497 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11498 (progn
11499 (setq parent (match-string 1 answ)
11500 child (match-string 2 answ))
11501 (setq parent-target (org-refile--get-location parent tbl))
11502 (when (and parent-target
11503 (or (eq new-nodes t)
11504 (and (eq new-nodes 'confirm)
11505 (y-or-n-p (format "Create new node \"%s\"? "
11506 child)))))
11507 (org-refile-new-child parent-target child)))
11508 (user-error "Invalid target location")))))
11510 (declare-function org-string-nw-p "org-macs" (s))
11511 (defun org-refile-check-position (refile-pointer)
11512 "Check if the refile pointer matches the headline to which it points."
11513 (let* ((file (nth 1 refile-pointer))
11514 (re (nth 2 refile-pointer))
11515 (pos (nth 3 refile-pointer))
11516 buffer)
11517 (if (and (not (markerp pos)) (not file))
11518 (user-error "Please indicate a target file in the refile path")
11519 (when (org-string-nw-p re)
11520 (setq buffer (if (markerp pos)
11521 (marker-buffer pos)
11522 (or (find-buffer-visiting file)
11523 (find-file-noselect file))))
11524 (with-current-buffer buffer
11525 (org-with-wide-buffer
11526 (goto-char pos)
11527 (beginning-of-line 1)
11528 (unless (looking-at-p re)
11529 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11531 (defun org-refile-new-child (parent-target child)
11532 "Use refile target PARENT-TARGET to add new CHILD below it."
11533 (unless parent-target
11534 (error "Cannot find parent for new node"))
11535 (let ((file (nth 1 parent-target))
11536 (pos (nth 3 parent-target))
11537 level)
11538 (with-current-buffer (or (find-buffer-visiting file)
11539 (find-file-noselect file))
11540 (org-with-wide-buffer
11541 (if pos
11542 (goto-char pos)
11543 (goto-char (point-max))
11544 (unless (bolp) (newline)))
11545 (when (looking-at org-outline-regexp)
11546 (setq level (funcall outline-level))
11547 (org-end-of-subtree t t))
11548 (org-back-over-empty-lines)
11549 (insert "\n" (make-string
11550 (if pos (org-get-valid-level level 1) 1) ?*)
11551 " " child "\n")
11552 (beginning-of-line 0)
11553 (list (concat (car parent-target) "/" child) file "" (point))))))
11555 (defun org-olpath-completing-read (prompt collection &rest args)
11556 "Read an outline path like a file name."
11557 (let ((thetable collection))
11558 (apply #'completing-read
11559 prompt
11560 (lambda (string predicate &optional flag)
11561 (cond
11562 ((eq flag nil) (try-completion string thetable))
11563 ((eq flag t)
11564 (let ((l (length string)))
11565 (mapcar (lambda (x)
11566 (let ((r (substring x l))
11567 (f (if (string-match " ([^)]*)$" x)
11568 (match-string 0 x)
11569 "")))
11570 (if (string-match "/" r)
11571 (concat string (substring r 0 (match-end 0)) f)
11572 x)))
11573 (all-completions string thetable predicate))))
11574 ;; Exact match?
11575 ((eq flag 'lambda) (assoc string thetable))))
11576 args)))
11578 ;;;; Dynamic blocks
11580 (defun org-find-dblock (name)
11581 "Find the first dynamic block with name NAME in the buffer.
11582 If not found, stay at current position and return nil."
11583 (let ((case-fold-search t) pos)
11584 (save-excursion
11585 (goto-char (point-min))
11586 (setq pos (and (re-search-forward
11587 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11588 (match-beginning 0))))
11589 (when pos (goto-char pos))
11590 pos))
11592 (defun org-create-dblock (plist)
11593 "Create a dynamic block section, with parameters taken from PLIST.
11594 PLIST must contain a :name entry which is used as the name of the block."
11595 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11596 (end-of-line 1)
11597 (newline))
11598 (let ((col (current-column))
11599 (name (plist-get plist :name)))
11600 (insert "#+BEGIN: " name)
11601 (while plist
11602 (if (eq (car plist) :name)
11603 (setq plist (cddr plist))
11604 (insert " " (prin1-to-string (pop plist)))))
11605 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11606 (beginning-of-line -2)))
11608 (defun org-prepare-dblock ()
11609 "Prepare dynamic block for refresh.
11610 This empties the block, puts the cursor at the insert position and returns
11611 the property list including an extra property :name with the block name."
11612 (unless (looking-at org-dblock-start-re)
11613 (user-error "Not at a dynamic block"))
11614 (let* ((begdel (1+ (match-end 0)))
11615 (name (org-no-properties (match-string 1)))
11616 (params (append (list :name name)
11617 (read (concat "(" (match-string 3) ")")))))
11618 (save-excursion
11619 (beginning-of-line 1)
11620 (skip-chars-forward " \t")
11621 (setq params (plist-put params :indentation-column (current-column))))
11622 (unless (re-search-forward org-dblock-end-re nil t)
11623 (error "Dynamic block not terminated"))
11624 (setq params
11625 (append params
11626 (list :content (buffer-substring
11627 begdel (match-beginning 0)))))
11628 (delete-region begdel (match-beginning 0))
11629 (goto-char begdel)
11630 (open-line 1)
11631 params))
11633 (defun org-map-dblocks (&optional command)
11634 "Apply COMMAND to all dynamic blocks in the current buffer.
11635 If COMMAND is not given, use `org-update-dblock'."
11636 (let ((cmd (or command 'org-update-dblock)))
11637 (save-excursion
11638 (goto-char (point-min))
11639 (while (re-search-forward org-dblock-start-re nil t)
11640 (goto-char (match-beginning 0))
11641 (save-excursion
11642 (condition-case nil
11643 (funcall cmd)
11644 (error (message "Error during update of dynamic block"))))
11645 (unless (re-search-forward org-dblock-end-re nil t)
11646 (error "Dynamic block not terminated"))))))
11648 (defun org-dblock-update (&optional arg)
11649 "User command for updating dynamic blocks.
11650 Update the dynamic block at point. With prefix ARG, update all dynamic
11651 blocks in the buffer."
11652 (interactive "P")
11653 (if arg
11654 (org-update-all-dblocks)
11655 (or (looking-at org-dblock-start-re)
11656 (org-beginning-of-dblock))
11657 (org-update-dblock)))
11659 (defun org-update-dblock ()
11660 "Update the dynamic block at point.
11661 This means to empty the block, parse for parameters and then call
11662 the correct writing function."
11663 (interactive)
11664 (save-excursion
11665 (let* ((win (selected-window))
11666 (pos (point))
11667 (line (org-current-line))
11668 (params (org-prepare-dblock))
11669 (name (plist-get params :name))
11670 (indent (plist-get params :indentation-column))
11671 (cmd (intern (concat "org-dblock-write:" name))))
11672 (message "Updating dynamic block `%s' at line %d..." name line)
11673 (funcall cmd params)
11674 (message "Updating dynamic block `%s' at line %d...done" name line)
11675 (goto-char pos)
11676 (when (and indent (> indent 0))
11677 (setq indent (make-string indent ?\ ))
11678 (save-excursion
11679 (select-window win)
11680 (org-beginning-of-dblock)
11681 (forward-line 1)
11682 (while (not (looking-at org-dblock-end-re))
11683 (insert indent)
11684 (beginning-of-line 2))
11685 (when (looking-at org-dblock-end-re)
11686 (and (looking-at "[ \t]+")
11687 (replace-match ""))
11688 (insert indent)))))))
11690 (defun org-beginning-of-dblock ()
11691 "Find the beginning of the dynamic block at point.
11692 Error if there is no such block at point."
11693 (let ((pos (point))
11694 beg)
11695 (end-of-line 1)
11696 (if (and (re-search-backward org-dblock-start-re nil t)
11697 (setq beg (match-beginning 0))
11698 (re-search-forward org-dblock-end-re nil t)
11699 (> (match-end 0) pos))
11700 (goto-char beg)
11701 (goto-char pos)
11702 (error "Not in a dynamic block"))))
11704 (defun org-update-all-dblocks ()
11705 "Update all dynamic blocks in the buffer.
11706 This function can be used in a hook."
11707 (interactive)
11708 (when (derived-mode-p 'org-mode)
11709 (org-map-dblocks 'org-update-dblock)))
11712 ;;;; Completion
11714 (declare-function org-export-backend-options "ox" (cl-x) t)
11715 (defun org-get-export-keywords ()
11716 "Return a list of all currently understood export keywords.
11717 Export keywords include options, block names, attributes and
11718 keywords relative to each registered export back-end."
11719 (let (keywords)
11720 (dolist (backend
11721 (bound-and-true-p org-export-registered-backends)
11722 (delq nil keywords))
11723 ;; Back-end name (for keywords, like #+LATEX:)
11724 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11725 (dolist (option-entry (org-export-backend-options backend))
11726 ;; Back-end options.
11727 (push (nth 1 option-entry) keywords)))))
11729 (defconst org-options-keywords
11730 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11731 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11732 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11733 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11734 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11736 (defcustom org-structure-template-alist
11737 '(("a" . "export ascii")
11738 ("c" . "center")
11739 ("C" . "comment")
11740 ("e" . "example")
11741 ("E" . "export")
11742 ("h" . "export html")
11743 ("l" . "export latex")
11744 ("q" . "quote")
11745 ("s" . "src")
11746 ("v" . "verse"))
11747 "An alist of keys and block types.
11748 `org-insert-structure-template' will display a menu with this
11749 list of templates to choose from. The block type is inserted,
11750 with \"#+BEGIN_\" and \"#+END_\" added automatically.
11752 The menu keys are defined by the car of each entry in this alist.
11753 If two entries have the keys \"a\" and \"aa\" respectively, the
11754 former will be inserted by typing \"a TAB/RET/SPC\" and the
11755 latter will be inserted by typing \"aa\". If an entry with the
11756 key \"aab\" is later added, it can be inserted by typing \"ab\".
11758 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11759 block can be inserted by pressing TAB after the string \"<KEY\"."
11760 :group 'org-edit-structure
11761 :type '(repeat
11762 (cons (string :tag "Key")
11763 (string :tag "Template")))
11764 :package-version '(Org . "9.2"))
11766 (defun org--check-org-structure-template-alist (&optional checklist)
11767 "Check whether `org-structure-template-alist' is set up correctly.
11768 In particular, check if the Org 9.2 format is used as opposed to
11769 previous format.
11771 (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
11772 (or (eval checklist)
11773 org-structure-template-alist))))
11774 (when elm
11775 (org-display-warning
11776 (format "
11777 Please update the entries of `%s'.
11779 In Org 9.2 the format was changed from something like
11781 (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
11783 to something like
11785 (\"s\" . \"src\")
11787 Please refer to the documentation of `org-structure-template-alist'.
11789 The following entries must be updated:
11792 (or checklist 'org-structure-template-alist)
11793 (pp-to-string elm))))))
11795 (defun org--insert-structure-template-mks ()
11796 "Present `org-structure-template-alist' with `org-mks'.
11798 Menus are added if keys require more than one keystroke. Tabs
11799 are added to single key entries when more than one stroke is
11800 needed. Keys longer than two characters are reduced to two
11801 characters."
11802 (org--check-org-structure-template-alist)
11803 (let* (case-fold-search
11804 (templates (append org-structure-template-alist
11805 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11806 (keys (mapcar #'car templates))
11807 (start-letters
11808 (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11809 ;; Sort each element of `org-structure-template-alist' into
11810 ;; sublists according to the first letter.
11811 (superlist
11812 (mapcar (lambda (letter)
11813 (list letter
11814 (cl-remove-if-not
11815 (apply-partially #'string-match-p (concat "^" letter))
11816 templates :key #'car)))
11817 start-letters)))
11818 (org-mks
11819 (apply #'append
11820 ;; Make an `org-mks' table. If only one element is
11821 ;; present in a sublist, make it part of the top-menu,
11822 ;; otherwise make a submenu according to the starting
11823 ;; letter and populate it.
11824 (mapcar (lambda (sublist)
11825 (if (eq 1 (length (cadr sublist)))
11826 (mapcar (lambda (elm)
11827 (list (substring (car elm) 0 1)
11828 (cdr elm) ""))
11829 (cadr sublist))
11830 ;; Create submenu.
11831 (let* ((topkey (car sublist))
11832 (elms (cadr sublist))
11833 (keys (mapcar #'car elms))
11834 (long (> (length elms) 3)))
11835 (append
11836 (list
11837 ;; Make a description of the submenu.
11838 (list topkey
11839 (concat
11840 (mapconcat #'cdr
11841 (cl-subseq elms 0 (if long 3 (length elms)))
11842 ", ")
11843 (when long ", ..."))))
11844 ;; List of entries in submenu.
11845 (cl-mapcar #'list
11846 (org--insert-structure-template-unique-keys keys)
11847 (mapcar #'cdr elms)
11848 (make-list (length elms) ""))))))
11849 superlist))
11850 "Select a key\n============"
11851 "Key: ")))
11853 (defun org--insert-structure-template-unique-keys (keys)
11854 "Make a list of unique, two characters long elements from KEYS.
11856 Elements of length one have a tab appended. Elements of length
11857 two are kept as is. Longer elements are truncated to length two.
11859 If an element cannot be made unique, an error is raised."
11860 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11861 menu-keys)
11862 (dolist (key orderd-keys)
11863 (let ((potential-key
11864 (cl-case (length key)
11865 (1 (concat key "\t"))
11866 (2 key)
11867 (otherwise
11868 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11869 (mapcar (apply-partially #'concat (substring key 0 1))
11870 (split-string (substring key 1) "" t)))))))
11871 (if (or (not potential-key) (assoc potential-key menu-keys))
11872 (user-error "Could not make unique key for %s." key)
11873 (push (cons potential-key key) menu-keys))))
11874 (mapcar #'car
11875 (cl-sort menu-keys #'<
11876 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11878 (defun org-insert-structure-template (type)
11879 "Insert a block structure of the type #+begin_foo/#+end_foo.
11880 Select a block from `org-structure-template-alist' then type
11881 either RET, TAB or SPC to write the block type. With an active
11882 region, wrap the region in the block. Otherwise, insert an empty
11883 block."
11884 (interactive
11885 (list (pcase (org--insert-structure-template-mks)
11886 (`("\t" . ,_) (read-string "Structure type: "))
11887 (`(,_ ,choice . ,_) choice))))
11888 (let* ((region? (use-region-p))
11889 (region-start (and region? (region-beginning)))
11890 (region-end (and region? (copy-marker (region-end))))
11891 (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
11892 (verbatim? (string-match-p
11893 (concat "\\`" (regexp-opt '("example" "export" "src")))
11894 type)))
11895 (when region? (goto-char region-start))
11896 (let ((column (current-indentation)))
11897 (if (save-excursion (skip-chars-backward " \t") (bolp))
11898 (beginning-of-line)
11899 (insert "\n"))
11900 (save-excursion
11901 (indent-to column)
11902 (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
11903 (when region?
11904 (when verbatim? (org-escape-code-in-region (point) region-end))
11905 (goto-char region-end)
11906 ;; Ignore empty lines at the end of the region.
11907 (skip-chars-backward " \r\t\n")
11908 (end-of-line))
11909 (unless (bolp) (insert "\n"))
11910 (indent-to column)
11911 (insert (format "#+end_%s" (car (split-string type))))
11912 (if (looking-at "[ \t]*$") (replace-match "")
11913 (insert "\n"))
11914 (when (and (eobp) (not (bolp))) (insert "\n")))
11915 (if extended? (end-of-line)
11916 (forward-line)
11917 (skip-chars-forward " \t")))))
11920 ;;;; TODO, DEADLINE, Comments
11922 (defun org-toggle-comment ()
11923 "Change the COMMENT state of an entry."
11924 (interactive)
11925 (save-excursion
11926 (org-back-to-heading)
11927 (let ((case-fold-search nil))
11928 (looking-at org-complex-heading-regexp))
11929 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11930 (skip-chars-forward " \t")
11931 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11932 (if (org-in-commented-heading-p t)
11933 (delete-region (point)
11934 (progn (search-forward " " (line-end-position) 'move)
11935 (skip-chars-forward " \t")
11936 (point)))
11937 (insert org-comment-string)
11938 (unless (eolp) (insert " ")))))
11940 (defvar org-last-todo-state-is-todo nil
11941 "This is non-nil when the last TODO state change led to a TODO state.
11942 If the last change removed the TODO tag or switched to DONE, then
11943 this is nil.")
11945 (defvar org-todo-setup-filter-hook nil
11946 "Hook for functions that pre-filter todo specs.
11947 Each function takes a todo spec and returns either nil or the spec
11948 transformed into canonical form." )
11950 (defvar org-todo-get-default-hook nil
11951 "Hook for functions that get a default item for todo.
11952 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11953 nil or a string to be used for the todo mark." )
11955 (defvar org-agenda-headline-snapshot-before-repeat)
11957 (defun org-current-effective-time ()
11958 "Return current time adjusted for `org-extend-today-until' variable."
11959 (let* ((ct (org-current-time))
11960 (dct (decode-time ct))
11961 (ct1
11962 (cond
11963 (org-use-last-clock-out-time-as-effective-time
11964 (or (org-clock-get-last-clock-out-time) ct))
11965 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11966 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11967 (t ct))))
11968 ct1))
11970 (defun org-todo-yesterday (&optional arg)
11971 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11972 (interactive "P")
11973 (if (eq major-mode 'org-agenda-mode)
11974 (apply 'org-agenda-todo-yesterday arg)
11975 (let* ((org-use-effective-time t)
11976 (hour (nth 2 (decode-time (org-current-time))))
11977 (org-extend-today-until (1+ hour)))
11978 (org-todo arg))))
11980 (defvar org-block-entry-blocking ""
11981 "First entry preventing the TODO state change.")
11983 (defun org-cancel-repeater ()
11984 "Cancel a repeater by setting its numeric value to zero."
11985 (interactive)
11986 (save-excursion
11987 (org-back-to-heading t)
11988 (let ((bound1 (point))
11989 (bound0 (save-excursion (outline-next-heading) (point))))
11990 (when (and (re-search-forward
11991 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11992 org-deadline-time-regexp "\\)\\|\\("
11993 org-ts-regexp "\\)")
11994 bound0 t)
11995 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11996 bound1 t))
11997 (replace-match "0" t nil nil 1)))))
11999 (defvar org-state)
12000 (defvar org-blocked-by-checkboxes)
12001 (defun org-todo (&optional arg)
12002 "Change the TODO state of an item.
12004 The state of an item is given by a keyword at the start of the heading,
12005 like
12006 *** TODO Write paper
12007 *** DONE Call mom
12009 The different keywords are specified in the variable `org-todo-keywords'.
12010 By default the available states are \"TODO\" and \"DONE\". So, for this
12011 example: when the item starts with TODO, it is changed to DONE.
12012 When it starts with DONE, the DONE is removed. And when neither TODO nor
12013 DONE are present, add TODO at the beginning of the heading.
12015 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12016 state.
12017 With numeric prefix ARG, switch to that state.
12018 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12019 next set of TODO \
12020 keywords (nextset).
12021 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12022 prefix, circumvent any state blocking.
12023 With a numeric prefix arg of 0, inhibit note taking for the change.
12024 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12026 When called through ELisp, arg is also interpreted in the following way:
12027 `none' -> empty state
12028 \"\" -> switch to empty state
12029 `done' -> switch to DONE
12030 `nextset' -> switch to the next set of keywords
12031 `previousset' -> switch to the previous set of keywords
12032 \"WAITING\" -> switch to the specified keyword, but only if it
12033 really is a member of `org-todo-keywords'."
12034 (interactive "P")
12035 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12036 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12037 'region-start-level 'region))
12038 org-loop-over-headlines-in-active-region)
12039 (org-map-entries
12040 `(org-todo ,arg)
12041 org-loop-over-headlines-in-active-region
12042 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12043 (when (equal arg '(16)) (setq arg 'nextset))
12044 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12045 (let ((org-blocker-hook org-blocker-hook)
12046 commentp
12047 case-fold-search)
12048 (when (equal arg '(64))
12049 (setq arg nil org-blocker-hook nil))
12050 (when (and org-blocker-hook
12051 (or org-inhibit-blocking
12052 (org-entry-get nil "NOBLOCKING")))
12053 (setq org-blocker-hook nil))
12054 (save-excursion
12055 (catch 'exit
12056 (org-back-to-heading t)
12057 (when (org-in-commented-heading-p t)
12058 (org-toggle-comment)
12059 (setq commentp t))
12060 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12061 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12062 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12063 (let* ((match-data (match-data))
12064 (startpos (copy-marker (line-beginning-position)))
12065 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12066 (org-log-done org-log-done)
12067 (org-log-repeat org-log-repeat)
12068 (org-todo-log-states org-todo-log-states)
12069 (org-inhibit-logging
12070 (if (equal arg 0)
12071 (progn (setq arg nil) 'note) org-inhibit-logging))
12072 (this (match-string 1))
12073 (hl-pos (match-beginning 0))
12074 (head (org-get-todo-sequence-head this))
12075 (ass (assoc head org-todo-kwd-alist))
12076 (interpret (nth 1 ass))
12077 (done-word (nth 3 ass))
12078 (final-done-word (nth 4 ass))
12079 (org-last-state (or this ""))
12080 (completion-ignore-case t)
12081 (member (member this org-todo-keywords-1))
12082 (tail (cdr member))
12083 (org-state (cond
12084 ((and org-todo-key-trigger
12085 (or (and (equal arg '(4))
12086 (eq org-use-fast-todo-selection 'prefix))
12087 (and (not arg) org-use-fast-todo-selection
12088 (not (eq org-use-fast-todo-selection
12089 'prefix)))))
12090 ;; Use fast selection.
12091 (org-fast-todo-selection))
12092 ((and (equal arg '(4))
12093 (or (not org-use-fast-todo-selection)
12094 (not org-todo-key-trigger)))
12095 ;; Read a state with completion.
12096 (completing-read
12097 "State: " (mapcar #'list org-todo-keywords-1)
12098 nil t))
12099 ((eq arg 'right)
12100 (if this
12101 (if tail (car tail) nil)
12102 (car org-todo-keywords-1)))
12103 ((eq arg 'left)
12104 (unless (equal member org-todo-keywords-1)
12105 (if this
12106 (nth (- (length org-todo-keywords-1)
12107 (length tail) 2)
12108 org-todo-keywords-1)
12109 (org-last org-todo-keywords-1))))
12110 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12111 (setq arg nil))) ;hack to fall back to cycling
12112 (arg
12113 ;; User or caller requests a specific state.
12114 (cond
12115 ((equal arg "") nil)
12116 ((eq arg 'none) nil)
12117 ((eq arg 'done) (or done-word (car org-done-keywords)))
12118 ((eq arg 'nextset)
12119 (or (car (cdr (member head org-todo-heads)))
12120 (car org-todo-heads)))
12121 ((eq arg 'previousset)
12122 (let ((org-todo-heads (reverse org-todo-heads)))
12123 (or (car (cdr (member head org-todo-heads)))
12124 (car org-todo-heads))))
12125 ((car (member arg org-todo-keywords-1)))
12126 ((stringp arg)
12127 (user-error "State `%s' not valid in this file" arg))
12128 ((nth (1- (prefix-numeric-value arg))
12129 org-todo-keywords-1))))
12130 ((null member) (or head (car org-todo-keywords-1)))
12131 ((equal this final-done-word) nil) ;-> make empty
12132 ((null tail) nil) ;-> first entry
12133 ((memq interpret '(type priority))
12134 (if (eq this-command last-command)
12135 (car tail)
12136 (if (> (length tail) 0)
12137 (or done-word (car org-done-keywords))
12138 nil)))
12140 (car tail))))
12141 (org-state (or
12142 (run-hook-with-args-until-success
12143 'org-todo-get-default-hook org-state org-last-state)
12144 org-state))
12145 (next (if org-state (concat " " org-state " ") " "))
12146 (change-plist (list :type 'todo-state-change :from this :to org-state
12147 :position startpos))
12148 dolog now-done-p)
12149 (when org-blocker-hook
12150 (let (org-blocked-by-checkboxes block-reason)
12151 (setq org-last-todo-state-is-todo
12152 (not (member this org-done-keywords)))
12153 (unless (save-excursion
12154 (save-match-data
12155 (org-with-wide-buffer
12156 (run-hook-with-args-until-failure
12157 'org-blocker-hook change-plist))))
12158 (setq block-reason (if org-blocked-by-checkboxes
12159 "contained checkboxes"
12160 (format "\"%s\"" org-block-entry-blocking)))
12161 (if (called-interactively-p 'interactive)
12162 (user-error "TODO state change from %s to %s blocked (by %s)"
12163 this org-state block-reason)
12164 ;; Fail silently.
12165 (message "TODO state change from %s to %s blocked (by %s)"
12166 this org-state block-reason)
12167 (throw 'exit nil)))))
12168 (store-match-data match-data)
12169 (replace-match next t t)
12170 (cond ((equal this org-state)
12171 (message "TODO state was already %s" (org-trim next)))
12172 ((not (pos-visible-in-window-p hl-pos))
12173 (message "TODO state changed to %s" (org-trim next))))
12174 (unless head
12175 (setq head (org-get-todo-sequence-head org-state)
12176 ass (assoc head org-todo-kwd-alist)
12177 interpret (nth 1 ass)
12178 done-word (nth 3 ass)
12179 final-done-word (nth 4 ass)))
12180 (when (memq arg '(nextset previousset))
12181 (message "Keyword-Set %d/%d: %s"
12182 (- (length org-todo-sets) -1
12183 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12184 (length org-todo-sets)
12185 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12186 (setq org-last-todo-state-is-todo
12187 (not (member org-state org-done-keywords)))
12188 (setq now-done-p (and (member org-state org-done-keywords)
12189 (not (member this org-done-keywords))))
12190 (and logging (org-local-logging logging))
12191 (when (and (or org-todo-log-states org-log-done)
12192 (not (eq org-inhibit-logging t))
12193 (not (memq arg '(nextset previousset))))
12194 ;; We need to look at recording a time and note.
12195 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12196 (nth 2 (assoc this org-todo-log-states))))
12197 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12198 (setq dolog 'time))
12199 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12200 (and org-state
12201 (member org-state org-not-done-keywords)
12202 (not (member this org-not-done-keywords))))
12203 ;; This is now a todo state and was not one before
12204 ;; If there was a CLOSED time stamp, get rid of it.
12205 (org-add-planning-info nil nil 'closed))
12206 (when (and now-done-p org-log-done)
12207 ;; It is now done, and it was not done before.
12208 (org-add-planning-info 'closed (org-current-effective-time))
12209 (when (and (not dolog) (eq 'note org-log-done))
12210 (org-add-log-setup 'done org-state this 'note)))
12211 (when (and org-state dolog)
12212 ;; This is a non-nil state, and we need to log it.
12213 (org-add-log-setup 'state org-state this dolog)))
12214 ;; Fixup tag positioning.
12215 (org-todo-trigger-tag-changes org-state)
12216 (when org-auto-align-tags (org-align-tags))
12217 (when org-provide-todo-statistics
12218 (org-update-parent-todo-statistics))
12219 (run-hooks 'org-after-todo-state-change-hook)
12220 (when (and arg (not (member org-state org-done-keywords)))
12221 (setq head (org-get-todo-sequence-head org-state)))
12222 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12223 ;; Do we need to trigger a repeat?
12224 (when now-done-p
12225 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12226 ;; This is for the agenda, take a snapshot of the headline.
12227 (save-match-data
12228 (setq org-agenda-headline-snapshot-before-repeat
12229 (org-get-heading))))
12230 (org-auto-repeat-maybe org-state))
12231 ;; Fixup cursor location if close to the keyword.
12232 (when (and (outline-on-heading-p)
12233 (not (bolp))
12234 (save-excursion (beginning-of-line 1)
12235 (looking-at org-todo-line-regexp))
12236 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12237 (goto-char (or (match-end 2) (match-end 1)))
12238 (and (looking-at " ") (just-one-space)))
12239 (when org-trigger-hook
12240 (save-excursion
12241 (run-hook-with-args 'org-trigger-hook change-plist)))
12242 (when commentp (org-toggle-comment))))))))
12244 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12245 "Block turning an entry into a TODO, using the hierarchy.
12246 This checks whether the current task should be blocked from state
12247 changes. Such blocking occurs when:
12249 1. The task has children which are not all in a completed state.
12251 2. A task has a parent with the property :ORDERED:, and there
12252 are siblings prior to the current task with incomplete
12253 status.
12255 3. The parent of the task is blocked because it has siblings that should
12256 be done first, or is child of a block grandparent TODO entry."
12258 (if (not org-enforce-todo-dependencies)
12259 t ; if locally turned off don't block
12260 (catch 'dont-block
12261 ;; If this is not a todo state change, or if this entry is already DONE,
12262 ;; do not block
12263 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12264 (member (plist-get change-plist :from)
12265 (cons 'done org-done-keywords))
12266 (member (plist-get change-plist :to)
12267 (cons 'todo org-not-done-keywords))
12268 (not (plist-get change-plist :to)))
12269 (throw 'dont-block t))
12270 ;; If this task has children, and any are undone, it's blocked
12271 (save-excursion
12272 (org-back-to-heading t)
12273 (let ((this-level (funcall outline-level)))
12274 (outline-next-heading)
12275 (let ((child-level (funcall outline-level)))
12276 (while (and (not (eobp))
12277 (> child-level this-level))
12278 ;; this todo has children, check whether they are all
12279 ;; completed
12280 (when (and (not (org-entry-is-done-p))
12281 (org-entry-is-todo-p))
12282 (setq org-block-entry-blocking (org-get-heading))
12283 (throw 'dont-block nil))
12284 (outline-next-heading)
12285 (setq child-level (funcall outline-level))))))
12286 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12287 ;; any previous siblings are undone, it's blocked
12288 (save-excursion
12289 (org-back-to-heading t)
12290 (let* ((pos (point))
12291 (parent-pos (and (org-up-heading-safe) (point)))
12292 (case-fold-search nil))
12293 (unless parent-pos (throw 'dont-block t)) ; no parent
12294 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12295 (forward-line 1)
12296 (re-search-forward org-not-done-heading-regexp pos t))
12297 (setq org-block-entry-blocking (match-string 0))
12298 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12299 ;; Search further up the hierarchy, to see if an ancestor is blocked
12300 (while t
12301 (goto-char parent-pos)
12302 (unless (looking-at org-not-done-heading-regexp)
12303 (throw 'dont-block t)) ; do not block, parent is not a TODO
12304 (setq pos (point))
12305 (setq parent-pos (and (org-up-heading-safe) (point)))
12306 (unless parent-pos (throw 'dont-block t)) ; no parent
12307 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12308 (forward-line 1)
12309 (re-search-forward org-not-done-heading-regexp pos t)
12310 (setq org-block-entry-blocking (org-get-heading)))
12311 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12313 (defcustom org-track-ordered-property-with-tag nil
12314 "Should the ORDERED property also be shown as a tag?
12315 The ORDERED property decides if an entry should require subtasks to be
12316 completed in sequence. Since a property is not very visible, setting
12317 this option means that toggling the ORDERED property with the command
12318 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12319 not relevant for the behavior, but it makes things more visible.
12321 Note that toggling the tag with tags commands will not change the property
12322 and therefore not influence behavior!
12324 This can be t, meaning the tag ORDERED should be used, It can also be a
12325 string to select a different tag for this task."
12326 :group 'org-todo
12327 :type '(choice
12328 (const :tag "No tracking" nil)
12329 (const :tag "Track with ORDERED tag" t)
12330 (string :tag "Use other tag")))
12332 (defun org-toggle-ordered-property ()
12333 "Toggle the ORDERED property of the current entry.
12334 For better visibility, you can track the value of this property with a tag.
12335 See variable `org-track-ordered-property-with-tag'."
12336 (interactive)
12337 (let* ((t1 org-track-ordered-property-with-tag)
12338 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12339 (save-excursion
12340 (org-back-to-heading)
12341 (if (org-entry-get nil "ORDERED")
12342 (progn
12343 (org-delete-property "ORDERED")
12344 (and tag (org-toggle-tag tag 'off))
12345 (message "Subtasks can be completed in arbitrary order"))
12346 (org-entry-put nil "ORDERED" "t")
12347 (and tag (org-toggle-tag tag 'on))
12348 (message "Subtasks must be completed in sequence")))))
12350 (defun org-block-todo-from-checkboxes (change-plist)
12351 "Block turning an entry into a TODO, using checkboxes.
12352 This checks whether the current task should be blocked from state
12353 changes because there are unchecked boxes in this entry."
12354 (if (not org-enforce-todo-checkbox-dependencies)
12355 t ; if locally turned off don't block
12356 (catch 'dont-block
12357 ;; If this is not a todo state change, or if this entry is already DONE,
12358 ;; do not block
12359 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12360 (member (plist-get change-plist :from)
12361 (cons 'done org-done-keywords))
12362 (member (plist-get change-plist :to)
12363 (cons 'todo org-not-done-keywords))
12364 (not (plist-get change-plist :to)))
12365 (throw 'dont-block t))
12366 ;; If this task has checkboxes that are not checked, it's blocked
12367 (save-excursion
12368 (org-back-to-heading t)
12369 (let ((beg (point)) end)
12370 (outline-next-heading)
12371 (setq end (point))
12372 (goto-char beg)
12373 (when (org-list-search-forward
12374 (concat (org-item-beginning-re)
12375 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12376 "\\[[- ]\\]")
12377 end t)
12378 (when (boundp 'org-blocked-by-checkboxes)
12379 (setq org-blocked-by-checkboxes t))
12380 (throw 'dont-block nil))))
12381 t))) ; do not block
12383 (defun org-entry-blocked-p ()
12384 "Non-nil if entry at point is blocked."
12385 (and (not (org-entry-get nil "NOBLOCKING"))
12386 (member (org-entry-get nil "TODO") org-not-done-keywords)
12387 (not (run-hook-with-args-until-failure
12388 'org-blocker-hook
12389 (list :type 'todo-state-change
12390 :position (point)
12391 :from 'todo
12392 :to 'done)))))
12394 (defun org-update-statistics-cookies (all)
12395 "Update the statistics cookie, either from TODO or from checkboxes.
12396 This should be called with the cursor in a line with a statistics
12397 cookie. When called with a \\[universal-argument] prefix, update
12398 all statistics cookies in the buffer."
12399 (interactive "P")
12400 (if all
12401 (progn
12402 (org-update-checkbox-count 'all)
12403 (org-map-entries 'org-update-parent-todo-statistics))
12404 (if (not (org-at-heading-p))
12405 (org-update-checkbox-count)
12406 (let ((pos (point-marker))
12407 end l1 l2)
12408 (ignore-errors (org-back-to-heading t))
12409 (if (not (org-at-heading-p))
12410 (org-update-checkbox-count)
12411 (setq l1 (org-outline-level))
12412 (setq end (save-excursion
12413 (outline-next-heading)
12414 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12415 (point)))
12416 (if (and (save-excursion
12417 (re-search-forward
12418 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12419 (not (save-excursion (re-search-forward
12420 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12421 (org-update-checkbox-count)
12422 (if (and l2 (> l2 l1))
12423 (progn
12424 (goto-char end)
12425 (org-update-parent-todo-statistics))
12426 (goto-char pos)
12427 (beginning-of-line 1)
12428 (while (re-search-forward
12429 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12430 (point-at-eol) t)
12431 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12432 (goto-char pos)
12433 (move-marker pos nil)))))
12435 (defvar org-entry-property-inherited-from) ;; defined below
12436 (defun org-update-parent-todo-statistics ()
12437 "Update any statistics cookie in the parent of the current headline.
12438 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12439 the entire subtree and this will travel up the hierarchy and update
12440 statistics everywhere."
12441 (let* ((prop (save-excursion (org-up-heading-safe)
12442 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12443 (recursive (or (not org-hierarchical-todo-statistics)
12444 (and prop (string-match "\\<recursive\\>" prop))))
12445 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12447 (first t)
12448 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12449 level ltoggle l1 new ndel
12450 (cnt-all 0) (cnt-done 0) is-percent kwd
12451 checkbox-beg cookie-present)
12452 (catch 'exit
12453 (save-excursion
12454 (beginning-of-line 1)
12455 (setq ltoggle (funcall outline-level))
12456 ;; Three situations are to consider:
12458 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12459 ;; to the top-level ancestor on the headline;
12461 ;; 2. If parent has "recursive" property, repeat up to the
12462 ;; headline setting that property, taking inheritance into
12463 ;; account;
12465 ;; 3. Else, move up to direct parent and proceed only once.
12466 (while (and (setq level (org-up-heading-safe))
12467 (or recursive first)
12468 (>= (point) lim))
12469 (setq first nil cookie-present nil)
12470 (unless (and level
12471 (not (string-match
12472 "\\<checkbox\\>"
12473 (downcase (or (org-entry-get nil "COOKIE_DATA")
12474 "")))))
12475 (throw 'exit nil))
12476 (while (re-search-forward box-re (point-at-eol) t)
12477 (setq cnt-all 0 cnt-done 0 cookie-present t)
12478 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12479 (save-match-data
12480 (unless (outline-next-heading) (throw 'exit nil))
12481 (while (and (looking-at org-complex-heading-regexp)
12482 (> (setq l1 (length (match-string 1))) level))
12483 (setq kwd (and (or recursive (= l1 ltoggle))
12484 (match-string 2)))
12485 (if (or (eq org-provide-todo-statistics 'all-headlines)
12486 (and (eq org-provide-todo-statistics t)
12487 (or (member kwd org-done-keywords)))
12488 (and (listp org-provide-todo-statistics)
12489 (stringp (car org-provide-todo-statistics))
12490 (or (member kwd org-provide-todo-statistics)
12491 (member kwd org-done-keywords)))
12492 (and (listp org-provide-todo-statistics)
12493 (listp (car org-provide-todo-statistics))
12494 (or (member kwd (car org-provide-todo-statistics))
12495 (and (member kwd org-done-keywords)
12496 (member kwd (cadr org-provide-todo-statistics))))))
12497 (setq cnt-all (1+ cnt-all))
12498 (and (eq org-provide-todo-statistics t)
12500 (setq cnt-all (1+ cnt-all))))
12501 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12502 (member kwd org-done-keywords))
12503 (and (listp org-provide-todo-statistics)
12504 (listp (car org-provide-todo-statistics))
12505 (member kwd org-done-keywords)
12506 (member kwd (cadr org-provide-todo-statistics)))
12507 (and (listp org-provide-todo-statistics)
12508 (stringp (car org-provide-todo-statistics))
12509 (member kwd org-done-keywords)))
12510 (setq cnt-done (1+ cnt-done)))
12511 (outline-next-heading)))
12512 (setq new
12513 (if is-percent
12514 (format "[%d%%]" (floor (* 100.0 cnt-done)
12515 (max 1 cnt-all)))
12516 (format "[%d/%d]" cnt-done cnt-all))
12517 ndel (- (match-end 0) checkbox-beg))
12518 (goto-char checkbox-beg)
12519 (insert new)
12520 (delete-region (point) (+ (point) ndel))
12521 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12522 (when cookie-present
12523 (run-hook-with-args 'org-after-todo-statistics-hook
12524 cnt-done (- cnt-all cnt-done))))))
12525 (run-hooks 'org-todo-statistics-hook)))
12527 (defvar org-after-todo-statistics-hook nil
12528 "Hook that is called after a TODO statistics cookie has been updated.
12529 Each function is called with two arguments: the number of not-done entries
12530 and the number of done entries.
12532 For example, the following function, when added to this hook, will switch
12533 an entry to DONE when all children are done, and back to TODO when new
12534 entries are set to a TODO status. Note that this hook is only called
12535 when there is a statistics cookie in the headline!
12537 (defun org-summary-todo (n-done n-not-done)
12538 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12539 (let (org-log-done org-log-states) ; turn off logging
12540 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12543 (defvar org-todo-statistics-hook nil
12544 "Hook that is run whenever Org thinks TODO statistics should be updated.
12545 This hook runs even if there is no statistics cookie present, in which case
12546 `org-after-todo-statistics-hook' would not run.")
12548 (defun org-todo-trigger-tag-changes (state)
12549 "Apply the changes defined in `org-todo-state-tags-triggers'."
12550 (let ((l org-todo-state-tags-triggers)
12551 changes)
12552 (when (or (not state) (equal state ""))
12553 (setq changes (append changes (cdr (assoc "" l)))))
12554 (when (and (stringp state) (> (length state) 0))
12555 (setq changes (append changes (cdr (assoc state l)))))
12556 (when (member state org-not-done-keywords)
12557 (setq changes (append changes (cdr (assq 'todo l)))))
12558 (when (member state org-done-keywords)
12559 (setq changes (append changes (cdr (assq 'done l)))))
12560 (dolist (c changes)
12561 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12563 (defun org-local-logging (value)
12564 "Get logging settings from a property VALUE."
12565 ;; Directly set the variables, they are already local.
12566 (setq org-log-done nil
12567 org-log-repeat nil
12568 org-todo-log-states nil)
12569 (dolist (w (split-string value))
12570 (let (a)
12571 (cond
12572 ((setq a (assoc w org-startup-options))
12573 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12574 (set (nth 1 a) (nth 2 a))))
12575 ((setq a (org-extract-log-state-settings w))
12576 (and (member (car a) org-todo-keywords-1)
12577 (push a org-todo-log-states)))))))
12579 (defun org-get-todo-sequence-head (kwd)
12580 "Return the head of the TODO sequence to which KWD belongs.
12581 If KWD is not set, check if there is a text property remembering the
12582 right sequence."
12583 (let (p)
12584 (cond
12585 ((not kwd)
12586 (or (get-text-property (point-at-bol) 'org-todo-head)
12587 (progn
12588 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12589 nil (point-at-eol)))
12590 (get-text-property p 'org-todo-head))))
12591 ((not (member kwd org-todo-keywords-1))
12592 (car org-todo-keywords-1))
12593 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12595 (defun org-fast-todo-selection ()
12596 "Fast TODO keyword selection with single keys.
12597 Returns the new TODO keyword, or nil if no state change should occur."
12598 (let* ((fulltable org-todo-key-alist)
12599 (done-keywords org-done-keywords) ;; needed for the faces.
12600 (maxlen (apply 'max (mapcar
12601 (lambda (x)
12602 (if (stringp (car x)) (string-width (car x)) 0))
12603 fulltable)))
12604 (expert nil)
12605 (fwidth (+ maxlen 3 1 3))
12606 (ncol (/ (- (window-width) 4) fwidth))
12607 tg cnt e c tbl
12608 groups ingroup)
12609 (save-excursion
12610 (save-window-excursion
12611 (if expert
12612 (set-buffer (get-buffer-create " *Org todo*"))
12613 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12614 (erase-buffer)
12615 (setq-local org-done-keywords done-keywords)
12616 (setq tbl fulltable cnt 0)
12617 (while (setq e (pop tbl))
12618 (cond
12619 ((equal e '(:startgroup))
12620 (push '() groups) (setq ingroup t)
12621 (unless (= cnt 0)
12622 (setq cnt 0)
12623 (insert "\n"))
12624 (insert "{ "))
12625 ((equal e '(:endgroup))
12626 (setq ingroup nil cnt 0)
12627 (insert "}\n"))
12628 ((equal e '(:newline))
12629 (unless (= cnt 0)
12630 (setq cnt 0)
12631 (insert "\n")
12632 (setq e (car tbl))
12633 (while (equal (car tbl) '(:newline))
12634 (insert "\n")
12635 (setq tbl (cdr tbl)))))
12637 (setq tg (car e) c (cdr e))
12638 (when ingroup (push tg (car groups)))
12639 (setq tg (org-add-props tg nil 'face
12640 (org-get-todo-face tg)))
12641 (when (and (= cnt 0) (not ingroup)) (insert " "))
12642 (insert "[" c "] " tg (make-string
12643 (- fwidth 4 (length tg)) ?\ ))
12644 (when (= (setq cnt (1+ cnt)) ncol)
12645 (insert "\n")
12646 (when ingroup (insert " "))
12647 (setq cnt 0)))))
12648 (insert "\n")
12649 (goto-char (point-min))
12650 (unless expert (org-fit-window-to-buffer))
12651 (message "[a-z..]:Set [SPC]:clear")
12652 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12653 (cond
12654 ((or (= c ?\C-g)
12655 (and (= c ?q) (not (rassoc c fulltable))))
12656 (setq quit-flag t))
12657 ((= c ?\ ) nil)
12658 ((setq e (rassoc c fulltable) tg (car e))
12660 (t (setq quit-flag t)))))))
12662 (defun org-entry-is-todo-p ()
12663 (member (org-get-todo-state) org-not-done-keywords))
12665 (defun org-entry-is-done-p ()
12666 (member (org-get-todo-state) org-done-keywords))
12668 (defun org-get-todo-state ()
12669 "Return the TODO keyword of the current subtree."
12670 (save-excursion
12671 (org-back-to-heading t)
12672 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12673 (match-end 2)
12674 (match-string 2))))
12676 (defun org-at-date-range-p (&optional inactive-ok)
12677 "Non-nil if point is inside a date range.
12679 When optional argument INACTIVE-OK is non-nil, also consider
12680 inactive time ranges.
12682 When this function returns a non-nil value, match data is set
12683 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12684 on INACTIVE-OK."
12685 (interactive)
12686 (save-excursion
12687 (catch 'exit
12688 (let ((pos (point)))
12689 (skip-chars-backward "^[<\r\n")
12690 (skip-chars-backward "<[")
12691 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12692 (>= (match-end 0) pos)
12693 (throw 'exit t))
12694 (skip-chars-backward "^<[\r\n")
12695 (skip-chars-backward "<[")
12696 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12697 (>= (match-end 0) pos)
12698 (throw 'exit t)))
12699 nil)))
12701 (defun org-get-repeat (&optional timestamp)
12702 "Check if there is a time-stamp with repeater in this entry.
12704 Return the repeater, as a string, or nil. Also return nil when
12705 this function is called before first heading.
12707 When optional argument TIMESTAMP is a string, extract the
12708 repeater from there instead."
12709 (save-match-data
12710 (cond (timestamp
12711 (and (string-match org-repeat-re timestamp)
12712 (match-string-no-properties 1 timestamp)))
12713 ((org-before-first-heading-p) nil)
12715 (save-excursion
12716 (org-back-to-heading t)
12717 (let ((end (org-entry-end-position)))
12718 (catch :repeat
12719 (while (re-search-forward org-repeat-re end t)
12720 (when (save-match-data (org-at-timestamp-p 'agenda))
12721 (throw :repeat (match-string-no-properties 1)))))))))))
12723 (defvar org-last-changed-timestamp)
12724 (defvar org-last-inserted-timestamp)
12725 (defvar org-log-post-message)
12726 (defvar org-log-note-purpose)
12727 (defvar org-log-note-how nil)
12728 (defvar org-log-note-extra)
12729 (defun org-auto-repeat-maybe (done-word)
12730 "Check if the current headline contains a repeated time-stamp.
12732 If yes, set TODO state back to what it was and change the base date
12733 of repeating deadline/scheduled time stamps to new date.
12735 This function is run automatically after each state change to a DONE state."
12736 (let* ((repeat (org-get-repeat))
12737 (aa (assoc org-last-state org-todo-kwd-alist))
12738 (interpret (nth 1 aa))
12739 (head (nth 2 aa))
12740 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12741 (msg "Entry repeats: ")
12742 (org-log-done nil)
12743 (org-todo-log-states nil)
12744 (end (copy-marker (org-entry-end-position))))
12745 (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
12746 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12747 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12748 (and (stringp org-todo-repeat-to-state)
12749 org-todo-repeat-to-state)
12750 (and org-todo-repeat-to-state org-last-state))))
12751 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
12752 to-state)
12753 ((eq interpret 'type) org-last-state)
12754 (head)
12755 (t 'none))))
12756 (org-back-to-heading t)
12757 (org-add-planning-info nil nil 'closed)
12758 ;; When `org-log-repeat' is non-nil or entry contains
12759 ;; a clock, set LAST_REPEAT property.
12760 (when (or org-log-repeat
12761 (catch :clock
12762 (save-excursion
12763 (while (re-search-forward org-clock-line-re end t)
12764 (when (org-at-clock-log-p) (throw :clock t))))))
12765 (org-entry-put nil "LAST_REPEAT" (format-time-string
12766 (org-time-stamp-format t t)
12767 (current-time))))
12768 (when org-log-repeat
12769 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12770 (memq 'org-add-log-note post-command-hook))
12771 ;; We are already setup for some record.
12772 (when (eq org-log-repeat 'note)
12773 ;; Make sure we take a note, not only a time stamp.
12774 (setq org-log-note-how 'note))
12775 ;; Set up for taking a record.
12776 (org-add-log-setup 'state
12777 (or done-word (car org-done-keywords))
12778 org-last-state
12779 org-log-repeat)))
12780 ;; Time-stamps without a repeater are usually skipped. However,
12781 ;; a SCHEDULED time-stamp without one is removed, as they are no
12782 ;; longer relevant.
12783 (save-excursion
12784 (let ((scheduled (org-entry-get (point) "SCHEDULED")))
12785 (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
12786 (org-remove-timestamp-with-keyword org-scheduled-string))))
12787 ;; Update every time-stamp with a repeater in the entry.
12788 (let ((planning-re (regexp-opt
12789 (list org-scheduled-string org-deadline-string))))
12790 (while (re-search-forward org-repeat-re end t)
12791 (let* ((ts (match-string 0))
12792 (type (if (not (org-at-planning-p)) "Plain:"
12793 (save-excursion
12794 (re-search-backward
12795 planning-re (line-beginning-position) t)
12796 (match-string 0)))))
12797 (when (and (org-at-timestamp-p 'agenda)
12798 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
12799 (let ((n (string-to-number (match-string 2 ts)))
12800 (what (match-string 3 ts)))
12801 (when (equal what "w") (setq n (* n 7) what "d"))
12802 (when (and (equal what "h")
12803 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12804 ts)))
12805 (user-error
12806 "Cannot repeat in %d hour(s) because no hour has been set"
12808 ;; Preparation, see if we need to modify the start
12809 ;; date for the change.
12810 (when (match-end 1)
12811 (let ((time (save-match-data (org-time-string-to-time ts)))
12812 (repeater-type (match-string 1 ts)))
12813 (cond
12814 ((equal "." repeater-type)
12815 ;; Shift starting date to today.
12816 (org-timestamp-change (- (org-today) (time-to-days time))
12817 'day))
12818 ((equal "+" repeater-type)
12819 (let ((nshiftmax 10)
12820 (nshift 0))
12821 (while (or (= nshift 0)
12822 (not (time-less-p (current-time) time)))
12823 (when (= nshiftmax (cl-incf nshift))
12824 (or (y-or-n-p
12825 (format "%d repeater intervals were not \
12826 enough to shift date past today. Continue? "
12827 nshift))
12828 (user-error "Abort")))
12829 (org-timestamp-change n (cdr (assoc what whata)))
12830 (org-in-regexp org-ts-regexp3)
12831 (setq ts (match-string 1))
12832 (setq time
12833 (save-match-data
12834 (org-time-string-to-time ts)))))
12835 (org-timestamp-change (- n) (cdr (assoc what whata)))
12836 ;; Rematch, so that we have everything in place
12837 ;; for the real shift.
12838 (org-in-regexp org-ts-regexp3)
12839 (setq ts (match-string 1))
12840 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12841 ts)))))
12842 (save-excursion
12843 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12844 (setq msg
12845 (concat msg type " " org-last-changed-timestamp " ")))))))
12846 (setq org-log-post-message msg)
12847 (message msg))))
12849 (defun org-show-todo-tree (arg)
12850 "Make a compact tree which shows all headlines marked with TODO.
12851 The tree will show the lines where the regexp matches, and all higher
12852 headlines above the match.
12853 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12854 With a numeric prefix N, construct a sparse tree for the Nth element
12855 of `org-todo-keywords-1'."
12856 (interactive "P")
12857 (let ((case-fold-search nil)
12858 (kwd-re
12859 (cond ((null arg) org-not-done-regexp)
12860 ((equal arg '(4))
12861 (let ((kwd
12862 (completing-read "Keyword (or KWD1|KWD2|...): "
12863 (mapcar #'list org-todo-keywords-1))))
12864 (concat "\\("
12865 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12866 "\\)\\>")))
12867 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12868 (regexp-quote (nth (1- (prefix-numeric-value arg))
12869 org-todo-keywords-1)))
12870 (t (user-error "Invalid prefix argument: %s" arg)))))
12871 (message "%d TODO entries found"
12872 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12874 (defun org--deadline-or-schedule (arg type time)
12875 "Insert DEADLINE or SCHEDULE information in current entry.
12876 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12877 `org-schedule' for information about ARG and TIME arguments."
12878 (let* ((deadline? (eq type 'deadline))
12879 (keyword (if deadline? org-deadline-string org-scheduled-string))
12880 (log (if deadline? org-log-redeadline org-log-reschedule))
12881 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12882 (old-date-time (and old-date (org-time-string-to-time old-date)))
12883 ;; Save repeater cookie from either TIME or current scheduled
12884 ;; time stamp. We are going to insert it back at the end of
12885 ;; the process.
12886 (repeater (or (and (org-string-nw-p time)
12887 ;; We use `org-repeat-re' because we need
12888 ;; to tell the difference between a real
12889 ;; repeater and a time delta, e.g. "+2d".
12890 (string-match org-repeat-re time)
12891 (match-string 1 time))
12892 (and (org-string-nw-p old-date)
12893 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12894 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12895 old-date)
12896 (match-string 1 old-date)))))
12897 (pcase arg
12898 (`(4)
12899 (if (not old-date)
12900 (message (if deadline? "Entry had no deadline to remove"
12901 "Entry was not scheduled"))
12902 (when (and old-date log)
12903 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12904 nil old-date log))
12905 (org-remove-timestamp-with-keyword keyword)
12906 (message (if deadline? "Entry no longer has a deadline."
12907 "Entry is no longer scheduled."))))
12908 (`(16)
12909 (save-excursion
12910 (org-back-to-heading t)
12911 (let ((regexp (if deadline? org-deadline-time-regexp
12912 org-scheduled-time-regexp)))
12913 (if (not (re-search-forward regexp (line-end-position 2) t))
12914 (user-error (if deadline? "No deadline information to update"
12915 "No scheduled information to update"))
12916 (let* ((rpl0 (match-string 1))
12917 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12918 (msg (if deadline? "Warn starting from" "Delay until")))
12919 (replace-match
12920 (concat keyword
12921 " <" rpl
12922 (format " -%dd"
12923 (abs (- (time-to-days
12924 (save-match-data
12925 (org-read-date
12926 nil t nil msg old-date-time)))
12927 (time-to-days old-date-time))))
12928 ">") t t))))))
12930 (org-add-planning-info type time 'closed)
12931 (when (and old-date
12933 (not (equal old-date org-last-inserted-timestamp)))
12934 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12935 org-last-inserted-timestamp
12936 old-date
12937 log))
12938 (when repeater
12939 (save-excursion
12940 (org-back-to-heading t)
12941 (when (re-search-forward
12942 (concat keyword " " org-last-inserted-timestamp)
12943 (line-end-position 2)
12945 (goto-char (1- (match-end 0)))
12946 (insert " " repeater)
12947 (setq org-last-inserted-timestamp
12948 (concat (substring org-last-inserted-timestamp 0 -1)
12949 " " repeater
12950 (substring org-last-inserted-timestamp -1))))))
12951 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12952 org-last-inserted-timestamp)))))
12954 (defun org-deadline (arg &optional time)
12955 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12956 With one universal prefix argument, remove any deadline from the item.
12957 With two universal prefix arguments, prompt for a warning delay.
12958 With argument TIME, set the deadline at the corresponding date. TIME
12959 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12960 (interactive "P")
12961 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12962 (org-map-entries
12963 (lambda () (org--deadline-or-schedule arg 'deadline time))
12965 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12966 'region-start-level
12967 'region)
12968 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12969 (org--deadline-or-schedule arg 'deadline time)))
12971 (defun org-schedule (arg &optional time)
12972 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12973 With one universal prefix argument, remove any scheduling date from the item.
12974 With two universal prefix arguments, prompt for a delay cookie.
12975 With argument TIME, scheduled at the corresponding date. TIME can
12976 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12977 (interactive "P")
12978 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12979 (org-map-entries
12980 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12982 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12983 'region-start-level
12984 'region)
12985 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12986 (org--deadline-or-schedule arg 'scheduled time)))
12988 (defun org-get-scheduled-time (pom &optional inherit)
12989 "Get the scheduled time as a time tuple, of a format suitable
12990 for calling org-schedule with, or if there is no scheduling,
12991 returns nil."
12992 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12993 (when time
12994 (apply 'encode-time (org-parse-time-string time)))))
12996 (defun org-get-deadline-time (pom &optional inherit)
12997 "Get the deadline as a time tuple, of a format suitable for
12998 calling org-deadline with, or if there is no scheduling, returns
12999 nil."
13000 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13001 (when time
13002 (apply 'encode-time (org-parse-time-string time)))))
13004 (defun org-remove-timestamp-with-keyword (keyword)
13005 "Remove all time stamps with KEYWORD in the current entry."
13006 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13007 beg)
13008 (save-excursion
13009 (org-back-to-heading t)
13010 (setq beg (point))
13011 (outline-next-heading)
13012 (while (re-search-backward re beg t)
13013 (replace-match "")
13014 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13015 (equal (char-before) ?\ ))
13016 (backward-delete-char 1)
13017 (when (string-match "^[ \t]*$" (buffer-substring
13018 (point-at-bol) (point-at-eol)))
13019 (delete-region (point-at-bol)
13020 (min (point-max) (1+ (point-at-eol))))))))))
13022 (defvar org-time-was-given) ; dynamically scoped parameter
13023 (defvar org-end-time-was-given) ; dynamically scoped parameter
13025 (defun org-at-planning-p ()
13026 "Non-nil when point is on a planning info line."
13027 ;; This is as accurate and faster than `org-element-at-point' since
13028 ;; planning info location is fixed in the section.
13029 (org-with-wide-buffer
13030 (beginning-of-line)
13031 (and (looking-at-p org-planning-line-re)
13032 (eq (point)
13033 (ignore-errors
13034 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13035 (org-back-to-heading t)
13036 (org-with-limited-levels (org-back-to-heading t)))
13037 (line-beginning-position 2))))))
13039 (defun org-add-planning-info (what &optional time &rest remove)
13040 "Insert new timestamp with keyword in the planning line.
13041 WHAT indicates what kind of time stamp to add. It is a symbol
13042 among `closed', `deadline', `scheduled' and nil. TIME indicates
13043 the time to use. If none is given, the user is prompted for
13044 a date. REMOVE indicates what kind of entries to remove. An old
13045 WHAT entry will also be removed."
13046 (let (org-time-was-given org-end-time-was-given default-time default-input)
13047 (catch 'exit
13048 (when (and (memq what '(scheduled deadline))
13049 (or (not time)
13050 (and (stringp time)
13051 (string-match "^[-+]+[0-9]" time))))
13052 ;; Try to get a default date/time from existing timestamp
13053 (save-excursion
13054 (org-back-to-heading t)
13055 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13056 (when (re-search-forward (if (eq what 'scheduled)
13057 org-scheduled-time-regexp
13058 org-deadline-time-regexp)
13059 end t)
13060 (setq ts (match-string 1)
13061 default-time (apply 'encode-time (org-parse-time-string ts))
13062 default-input (and ts (org-get-compact-tod ts)))))))
13063 (when what
13064 (setq time
13065 (if (stringp time)
13066 ;; This is a string (relative or absolute), set
13067 ;; proper date.
13068 (apply #'encode-time
13069 (org-read-date-analyze
13070 time default-time (decode-time default-time)))
13071 ;; If necessary, get the time from the user
13072 (or time (org-read-date nil 'to-time nil
13073 (cl-case what
13074 (deadline "DEADLINE")
13075 (scheduled "SCHEDULED")
13076 (otherwise nil))
13077 default-time default-input)))))
13078 (org-with-wide-buffer
13079 (org-back-to-heading t)
13080 (forward-line)
13081 (unless (bolp) (insert "\n"))
13082 (cond ((looking-at-p org-planning-line-re)
13083 ;; Move to current indentation.
13084 (skip-chars-forward " \t")
13085 ;; Check if we have to remove something.
13086 (dolist (type (if what (cons what remove) remove))
13087 (save-excursion
13088 (when (re-search-forward
13089 (cl-case type
13090 (closed org-closed-time-regexp)
13091 (deadline org-deadline-time-regexp)
13092 (scheduled org-scheduled-time-regexp)
13093 (otherwise
13094 (error "Invalid planning type: %s" type)))
13095 (line-end-position) t)
13096 ;; Delete until next keyword or end of line.
13097 (delete-region
13098 (match-beginning 0)
13099 (if (re-search-forward org-keyword-time-not-clock-regexp
13100 (line-end-position)
13102 (match-beginning 0)
13103 (line-end-position))))))
13104 ;; If there is nothing more to add and no more keyword
13105 ;; is left, remove the line completely.
13106 (if (and (looking-at-p "[ \t]*$") (not what))
13107 (delete-region (line-beginning-position)
13108 (line-beginning-position 2))
13109 ;; If we removed last keyword, do not leave trailing
13110 ;; white space at the end of line.
13111 (let ((p (point)))
13112 (save-excursion
13113 (end-of-line)
13114 (unless (= (skip-chars-backward " \t" p) 0)
13115 (delete-region (point) (line-end-position)))))))
13116 ((not what) (throw 'exit nil)) ; Nothing to do.
13117 (t (insert-before-markers "\n")
13118 (backward-char 1)
13119 (when org-adapt-indentation
13120 (indent-to-column (1+ (org-outline-level))))))
13121 (when what
13122 ;; Insert planning keyword.
13123 (insert (cl-case what
13124 (closed org-closed-string)
13125 (deadline org-deadline-string)
13126 (scheduled org-scheduled-string)
13127 (otherwise (error "Invalid planning type: %s" what)))
13128 " ")
13129 ;; Insert associated timestamp.
13130 (let ((ts (org-insert-time-stamp
13131 time
13132 (or org-time-was-given
13133 (and (eq what 'closed) org-log-done-with-time))
13134 (eq what 'closed)
13135 nil nil (list org-end-time-was-given))))
13136 (unless (eolp) (insert " "))
13137 ts))))))
13139 (defvar org-log-note-marker (make-marker)
13140 "Marker pointing at the entry where the note is to be inserted.")
13141 (defvar org-log-note-purpose nil)
13142 (defvar org-log-note-state nil)
13143 (defvar org-log-note-previous-state nil)
13144 (defvar org-log-note-extra nil)
13145 (defvar org-log-note-window-configuration nil)
13146 (defvar org-log-note-return-to (make-marker))
13147 (defvar org-log-note-effective-time nil
13148 "Remembered current time so that dynamically scoped
13149 `org-extend-today-until' affects timestamps in state change log")
13151 (defvar org-log-post-message nil
13152 "Message to be displayed after a log note has been stored.
13153 The auto-repeater uses this.")
13155 (defun org-add-note ()
13156 "Add a note to the current entry.
13157 This is done in the same way as adding a state change note."
13158 (interactive)
13159 (org-add-log-setup 'note))
13161 (defun org-log-beginning (&optional create)
13162 "Return expected start of log notes in current entry.
13163 When optional argument CREATE is non-nil, the function creates
13164 a drawer to store notes, if necessary. Returned position ignores
13165 narrowing."
13166 (org-with-wide-buffer
13167 (let ((drawer (org-log-into-drawer)))
13168 (cond
13169 (drawer
13170 (org-end-of-meta-data)
13171 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13172 (end (if (org-at-heading-p) (point)
13173 (save-excursion (outline-next-heading) (point))))
13174 (case-fold-search t))
13175 (catch 'exit
13176 ;; Try to find existing drawer.
13177 (while (re-search-forward regexp end t)
13178 (let ((element (org-element-at-point)))
13179 (when (eq (org-element-type element) 'drawer)
13180 (let ((cend (org-element-property :contents-end element)))
13181 (when (and (not org-log-states-order-reversed) cend)
13182 (goto-char cend)))
13183 (throw 'exit nil))))
13184 ;; No drawer found. Create one, if permitted.
13185 (when create
13186 (unless (bolp) (insert "\n"))
13187 (let ((beg (point)))
13188 (insert ":" drawer ":\n:END:\n")
13189 (org-indent-region beg (point))
13190 (org-flag-region
13191 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13192 (end-of-line -1)))))
13194 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13195 (skip-chars-forward " \t\n")
13196 (beginning-of-line)
13197 (unless org-log-states-order-reversed
13198 (org-skip-over-state-notes)
13199 (skip-chars-backward " \t\n")
13200 (forward-line)))))
13201 (if (bolp) (point) (line-beginning-position 2))))
13203 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13204 "Set up the post command hook to take a note.
13205 If this is about to TODO state change, the new state is expected in STATE.
13206 HOW is an indicator what kind of note should be created.
13207 EXTRA is additional text that will be inserted into the notes buffer."
13208 (move-marker org-log-note-marker (point))
13209 (setq org-log-note-purpose purpose
13210 org-log-note-state state
13211 org-log-note-previous-state prev-state
13212 org-log-note-how how
13213 org-log-note-extra extra
13214 org-log-note-effective-time (org-current-effective-time))
13215 (add-hook 'post-command-hook 'org-add-log-note 'append))
13217 (defun org-skip-over-state-notes ()
13218 "Skip past the list of State notes in an entry."
13219 (when (ignore-errors (goto-char (org-in-item-p)))
13220 (let* ((struct (org-list-struct))
13221 (prevs (org-list-prevs-alist struct))
13222 (regexp
13223 (concat "[ \t]*- +"
13224 (replace-regexp-in-string
13225 " +" " +"
13226 (org-replace-escapes
13227 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13228 `(("%d" . ,org-ts-regexp-inactive)
13229 ("%D" . ,org-ts-regexp)
13230 ("%s" . "\\(?:\"\\S-+\"\\)?")
13231 ("%S" . "\\(?:\"\\S-+\"\\)?")
13232 ("%t" . ,org-ts-regexp-inactive)
13233 ("%T" . ,org-ts-regexp)
13234 ("%u" . ".*?")
13235 ("%U" . ".*?")))))))
13236 (while (looking-at-p regexp)
13237 (goto-char (or (org-list-get-next-item (point) struct prevs)
13238 (org-list-get-item-end (point) struct)))))))
13240 (defun org-add-log-note (&optional _purpose)
13241 "Pop up a window for taking a note, and add this note later."
13242 (remove-hook 'post-command-hook 'org-add-log-note)
13243 (setq org-log-note-window-configuration (current-window-configuration))
13244 (delete-other-windows)
13245 (move-marker org-log-note-return-to (point))
13246 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13247 (goto-char org-log-note-marker)
13248 (org-switch-to-buffer-other-window "*Org Note*")
13249 (erase-buffer)
13250 (if (memq org-log-note-how '(time state))
13251 (org-store-log-note)
13252 (let ((org-inhibit-startup t)) (org-mode))
13253 (insert (format "# Insert note for %s.
13254 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13255 (cl-case org-log-note-purpose
13256 (clock-out "stopped clock")
13257 (done "closed todo item")
13258 (reschedule "rescheduling")
13259 (delschedule "no longer scheduled")
13260 (redeadline "changing deadline")
13261 (deldeadline "removing deadline")
13262 (refile "refiling")
13263 (note "this entry")
13264 (state
13265 (format "state change from \"%s\" to \"%s\""
13266 (or org-log-note-previous-state "")
13267 (or org-log-note-state "")))
13268 (t (error "This should not happen")))))
13269 (when org-log-note-extra (insert org-log-note-extra))
13270 (setq-local org-finish-function 'org-store-log-note)
13271 (run-hooks 'org-log-buffer-setup-hook)))
13273 (defvar org-note-abort nil) ; dynamically scoped
13274 (defun org-store-log-note ()
13275 "Finish taking a log note, and insert it to where it belongs."
13276 (let ((txt (prog1 (buffer-string)
13277 (kill-buffer)))
13278 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13279 lines)
13280 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13281 (setq txt (replace-match "" t t txt)))
13282 (when (string-match "\\s-+\\'" txt)
13283 (setq txt (replace-match "" t t txt)))
13284 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13285 (when (org-string-nw-p note)
13286 (setq note
13287 (org-replace-escapes
13288 note
13289 (list (cons "%u" (user-login-name))
13290 (cons "%U" user-full-name)
13291 (cons "%t" (format-time-string
13292 (org-time-stamp-format 'long 'inactive)
13293 org-log-note-effective-time))
13294 (cons "%T" (format-time-string
13295 (org-time-stamp-format 'long nil)
13296 org-log-note-effective-time))
13297 (cons "%d" (format-time-string
13298 (org-time-stamp-format nil 'inactive)
13299 org-log-note-effective-time))
13300 (cons "%D" (format-time-string
13301 (org-time-stamp-format nil nil)
13302 org-log-note-effective-time))
13303 (cons "%s" (cond
13304 ((not org-log-note-state) "")
13305 ((string-match-p org-ts-regexp
13306 org-log-note-state)
13307 (format "\"[%s]\""
13308 (substring org-log-note-state 1 -1)))
13309 (t (format "\"%s\"" org-log-note-state))))
13310 (cons "%S"
13311 (cond
13312 ((not org-log-note-previous-state) "")
13313 ((string-match-p org-ts-regexp
13314 org-log-note-previous-state)
13315 (format "\"[%s]\""
13316 (substring
13317 org-log-note-previous-state 1 -1)))
13318 (t (format "\"%s\""
13319 org-log-note-previous-state)))))))
13320 (when lines (setq note (concat note " \\\\")))
13321 (push note lines))
13322 (when (and lines (not org-note-abort))
13323 (with-current-buffer (marker-buffer org-log-note-marker)
13324 (org-with-wide-buffer
13325 ;; Find location for the new note.
13326 (goto-char org-log-note-marker)
13327 (set-marker org-log-note-marker nil)
13328 ;; Note associated to a clock is to be located right after
13329 ;; the clock. Do not move point.
13330 (unless (eq org-log-note-purpose 'clock-out)
13331 (goto-char (org-log-beginning t)))
13332 ;; Make sure point is at the beginning of an empty line.
13333 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13334 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13335 ;; In an existing list, add a new item at the top level.
13336 ;; Otherwise, indent line like a regular one.
13337 (let ((itemp (org-in-item-p)))
13338 (if itemp
13339 (indent-line-to
13340 (let ((struct (save-excursion
13341 (goto-char itemp) (org-list-struct))))
13342 (org-list-get-ind (org-list-get-top-point struct) struct)))
13343 (org-indent-line)))
13344 (insert (org-list-bullet-string "-") (pop lines))
13345 (let ((ind (org-list-item-body-column (line-beginning-position))))
13346 (dolist (line lines)
13347 (insert "\n")
13348 (indent-line-to ind)
13349 (insert line)))
13350 (message "Note stored")
13351 (org-back-to-heading t))
13352 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13353 ;; from within `org-add-log-note' because `buffer-undo-list'
13354 ;; is then modified outside of `org-with-remote-undo'.
13355 (when (eq this-command 'org-agenda-todo)
13356 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13357 ;; Don't add undo information when called from `org-agenda-todo'.
13358 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13359 (set-window-configuration org-log-note-window-configuration)
13360 (with-current-buffer (marker-buffer org-log-note-return-to)
13361 (goto-char org-log-note-return-to))
13362 (move-marker org-log-note-return-to nil)
13363 (when org-log-post-message (message "%s" org-log-post-message))))
13365 (defun org-remove-empty-drawer-at (pos)
13366 "Remove an empty drawer at position POS.
13367 POS may also be a marker."
13368 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13369 (org-with-wide-buffer
13370 (goto-char pos)
13371 (let ((drawer (org-element-at-point)))
13372 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13373 (not (org-element-property :contents-begin drawer)))
13374 (delete-region (org-element-property :begin drawer)
13375 (progn (goto-char (org-element-property :end drawer))
13376 (skip-chars-backward " \r\t\n")
13377 (forward-line)
13378 (point))))))))
13380 (defvar org-ts-type nil)
13381 (defun org-sparse-tree (&optional arg type)
13382 "Create a sparse tree, prompt for the details.
13383 This command can create sparse trees. You first need to select the type
13384 of match used to create the tree:
13386 t Show all TODO entries.
13387 T Show entries with a specific TODO keyword.
13388 m Show entries selected by a tags/property match.
13389 p Enter a property name and its value (both with completion on existing
13390 names/values) and show entries with that property.
13391 r Show entries matching a regular expression (`/' can be used as well).
13392 b Show deadlines and scheduled items before a date.
13393 a Show deadlines and scheduled items after a date.
13394 d Show deadlines due within `org-deadline-warning-days'.
13395 D Show deadlines and scheduled items between a date range."
13396 (interactive "P")
13397 (setq type (or type org-sparse-tree-default-date-type))
13398 (setq org-ts-type type)
13399 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13400 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13401 \[c]ycle through date types: %s"
13402 (cl-case type
13403 (all "all timestamps")
13404 (scheduled "only scheduled")
13405 (deadline "only deadline")
13406 (active "only active timestamps")
13407 (inactive "only inactive timestamps")
13408 (closed "with a closed time-stamp")
13409 (otherwise "scheduled/deadline")))
13410 (let ((answer (read-char-exclusive)))
13411 (cl-case answer
13413 (org-sparse-tree
13415 (cadr
13416 (memq type '(nil all scheduled deadline active inactive closed)))))
13417 (?d (call-interactively 'org-check-deadlines))
13418 (?b (call-interactively 'org-check-before-date))
13419 (?a (call-interactively 'org-check-after-date))
13420 (?D (call-interactively 'org-check-dates-range))
13421 (?t (call-interactively 'org-show-todo-tree))
13422 (?T (org-show-todo-tree '(4)))
13423 (?m (call-interactively 'org-match-sparse-tree))
13424 ((?p ?P)
13425 (let* ((kwd (completing-read
13426 "Property: " (mapcar #'list (org-buffer-property-keys))))
13427 (value (completing-read
13428 "Value: " (mapcar #'list (org-property-values kwd)))))
13429 (unless (string-match "\\`{.*}\\'" value)
13430 (setq value (concat "\"" value "\"")))
13431 (org-match-sparse-tree arg (concat kwd "=" value))))
13432 ((?r ?R ?/) (call-interactively 'org-occur))
13433 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13435 (defvar-local org-occur-highlights nil
13436 "List of overlays used for occur matches.")
13437 (defvar-local org-occur-parameters nil
13438 "Parameters of the active org-occur calls.
13439 This is a list, each call to org-occur pushes as cons cell,
13440 containing the regular expression and the callback, onto the list.
13441 The list can contain several entries if `org-occur' has been called
13442 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13443 will only contain one set of parameters. When the highlights are
13444 removed (for example with `C-c C-c', or with the next edit (depending
13445 on `org-remove-highlights-with-change'), this variable is emptied
13446 as well.")
13448 (defun org-occur (regexp &optional keep-previous callback)
13449 "Make a compact tree which shows all matches of REGEXP.
13451 The tree will show the lines where the regexp matches, and any other context
13452 defined in `org-show-context-detail', which see.
13454 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13455 done by a previous call to `org-occur' will be kept, to allow stacking of
13456 calls to this command.
13458 Optional argument CALLBACK can be a function of no argument. In this case,
13459 it is called with point at the end of the match, match data being set
13460 accordingly. Current match is shown only if the return value is non-nil.
13461 The function must neither move point nor alter narrowing."
13462 (interactive "sRegexp: \nP")
13463 (when (equal regexp "")
13464 (user-error "Regexp cannot be empty"))
13465 (unless keep-previous
13466 (org-remove-occur-highlights nil nil t))
13467 (push (cons regexp callback) org-occur-parameters)
13468 (let ((cnt 0))
13469 (save-excursion
13470 (goto-char (point-min))
13471 (when (or (not keep-previous) ; do not want to keep
13472 (not org-occur-highlights)) ; no previous matches
13473 ;; hide everything
13474 (org-overview))
13475 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13476 (isearch-no-upper-case-p regexp t)
13477 org-occur-case-fold-search)))
13478 (while (re-search-forward regexp nil t)
13479 (when (or (not callback)
13480 (save-match-data (funcall callback)))
13481 (setq cnt (1+ cnt))
13482 (when org-highlight-sparse-tree-matches
13483 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13484 (org-show-context 'occur-tree)))))
13485 (when org-remove-highlights-with-change
13486 (add-hook 'before-change-functions 'org-remove-occur-highlights
13487 nil 'local))
13488 (unless org-sparse-tree-open-archived-trees
13489 (org-hide-archived-subtrees (point-min) (point-max)))
13490 (run-hooks 'org-occur-hook)
13491 (when (called-interactively-p 'interactive)
13492 (message "%d match(es) for regexp %s" cnt regexp))
13493 cnt))
13495 (defun org-occur-next-match (&optional n _reset)
13496 "Function for `next-error-function' to find sparse tree matches.
13497 N is the number of matches to move, when negative move backwards.
13498 This function always goes back to the starting point when no
13499 match is found."
13500 (let* ((limit (if (< n 0) (point-min) (point-max)))
13501 (search-func (if (< n 0)
13502 'previous-single-char-property-change
13503 'next-single-char-property-change))
13504 (n (abs n))
13505 (pos (point))
13507 (catch 'exit
13508 (while (setq p1 (funcall search-func (point) 'org-type))
13509 (when (equal p1 limit)
13510 (goto-char pos)
13511 (user-error "No more matches"))
13512 (when (equal (get-char-property p1 'org-type) 'org-occur)
13513 (setq n (1- n))
13514 (when (= n 0)
13515 (goto-char p1)
13516 (throw 'exit (point))))
13517 (goto-char p1))
13518 (goto-char p1)
13519 (user-error "No more matches"))))
13521 (defun org-highlight-new-match (beg end)
13522 "Highlight from BEG to END and mark the highlight is an occur headline."
13523 (let ((ov (make-overlay beg end)))
13524 (overlay-put ov 'face 'secondary-selection)
13525 (overlay-put ov 'org-type 'org-occur)
13526 (push ov org-occur-highlights)))
13528 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13529 "Remove the occur highlights from the buffer.
13530 BEG and END are ignored. If NOREMOVE is nil, remove this function
13531 from the `before-change-functions' in the current buffer."
13532 (interactive)
13533 (unless org-inhibit-highlight-removal
13534 (mapc #'delete-overlay org-occur-highlights)
13535 (setq org-occur-highlights nil)
13536 (setq org-occur-parameters nil)
13537 (unless noremove
13538 (remove-hook 'before-change-functions
13539 'org-remove-occur-highlights 'local))))
13541 ;;;; Priorities
13543 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13544 "Regular expression matching the priority indicator.")
13546 (defvar org-remove-priority-next-time nil)
13548 (defun org-priority-up ()
13549 "Increase the priority of the current item."
13550 (interactive)
13551 (org-priority 'up))
13553 (defun org-priority-down ()
13554 "Decrease the priority of the current item."
13555 (interactive)
13556 (org-priority 'down))
13558 (defun org-priority (&optional action show)
13559 "Change the priority of an item.
13561 When called interactively with a `\\[universal-argument]' prefix,
13562 show the priority in the minibuffer instead of changing it.
13564 When called programatically, ACTION can be `set', `up', `down',
13565 or a character."
13566 (interactive "P")
13567 (when show
13568 ;; Deprecation warning inserted for Org 9.2; once enough time has
13569 ;; passed the SHOW argument should be removed.
13570 (warn "`org-priority' called with deprecated SHOW argument"))
13571 (if (equal action '(4))
13572 (org-show-priority)
13573 (unless org-enable-priority-commands
13574 (user-error "Priority commands are disabled"))
13575 (setq action (or action 'set))
13576 (let (current new news have remove)
13577 (save-excursion
13578 (org-back-to-heading t)
13579 (when (looking-at org-priority-regexp)
13580 (setq current (string-to-char (match-string 2))
13581 have t))
13582 (cond
13583 ((eq action 'remove)
13584 (setq remove t new ?\ ))
13585 ((or (eq action 'set)
13586 (integerp action))
13587 (if (not (eq action 'set))
13588 (setq new action)
13589 (message "Priority %c-%c, SPC to remove: "
13590 org-highest-priority org-lowest-priority)
13591 (save-match-data
13592 (setq new (read-char-exclusive))))
13593 (when (and (= (upcase org-highest-priority) org-highest-priority)
13594 (= (upcase org-lowest-priority) org-lowest-priority))
13595 (setq new (upcase new)))
13596 (cond ((equal new ?\s) (setq remove t))
13597 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13598 (user-error "Priority must be between `%c' and `%c'"
13599 org-highest-priority org-lowest-priority))))
13600 ((eq action 'up)
13601 (setq new (if have
13602 (1- current) ; normal cycling
13603 ;; last priority was empty
13604 (if (eq last-command this-command)
13605 org-lowest-priority ; wrap around empty to lowest
13606 ;; default
13607 (if org-priority-start-cycle-with-default
13608 org-default-priority
13609 (1- org-default-priority))))))
13610 ((eq action 'down)
13611 (setq new (if have
13612 (1+ current) ; normal cycling
13613 ;; last priority was empty
13614 (if (eq last-command this-command)
13615 org-highest-priority ; wrap around empty to highest
13616 ;; default
13617 (if org-priority-start-cycle-with-default
13618 org-default-priority
13619 (1+ org-default-priority))))))
13620 (t (user-error "Invalid action")))
13621 (when (or (< (upcase new) org-highest-priority)
13622 (> (upcase new) org-lowest-priority))
13623 (if (and (memq action '(up down))
13624 (not have) (not (eq last-command this-command)))
13625 ;; `new' is from default priority
13626 (error
13627 "The default can not be set, see `org-default-priority' why")
13628 ;; normal cycling: `new' is beyond highest/lowest priority
13629 ;; and is wrapped around to the empty priority
13630 (setq remove t)))
13631 (setq news (format "%c" new))
13632 (if have
13633 (if remove
13634 (replace-match "" t t nil 1)
13635 (replace-match news t t nil 2))
13636 (if remove
13637 (user-error "No priority cookie found in line")
13638 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13639 (if (match-end 2)
13640 (progn
13641 (goto-char (match-end 2))
13642 (insert " [#" news "]"))
13643 (goto-char (match-beginning 3))
13644 (insert "[#" news "] "))))
13645 (org-align-tags))
13646 (if remove
13647 (message "Priority removed")
13648 (message "Priority of current item set to %s" news)))))
13650 (defun org-show-priority ()
13651 "Show the priority of the current item.
13652 This priority is composed of the main priority given with the [#A] cookies,
13653 and by additional input from the age of a schedules or deadline entry."
13654 (interactive)
13655 (let ((pri (if (eq major-mode 'org-agenda-mode)
13656 (org-get-at-bol 'priority)
13657 (save-excursion
13658 (save-match-data
13659 (beginning-of-line)
13660 (and (looking-at org-heading-regexp)
13661 (org-get-priority (match-string 0))))))))
13662 (message "Priority is %d" (if pri pri -1000))))
13664 (defun org-get-priority (s)
13665 "Find priority cookie and return priority."
13666 (save-match-data
13667 (if (functionp org-get-priority-function)
13668 (funcall org-get-priority-function)
13669 (if (not (string-match org-priority-regexp s))
13670 (* 1000 (- org-lowest-priority org-default-priority))
13671 (* 1000 (- org-lowest-priority
13672 (string-to-char (match-string 2 s))))))))
13674 ;;;; Tags
13676 (defvar org-agenda-archives-mode)
13677 (defvar org-map-continue-from nil
13678 "Position from where mapping should continue.
13679 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13681 (defvar org-scanner-tags nil
13682 "The current tag list while the tags scanner is running.")
13684 (defvar org-trust-scanner-tags nil
13685 "Should `org-get-tags' use the tags for the scanner.
13686 This is for internal dynamical scoping only.
13687 When this is non-nil, the function `org-get-tags' will return the value
13688 of `org-scanner-tags' instead of building the list by itself. This
13689 can lead to large speed-ups when the tags scanner is used in a file with
13690 many entries, and when the list of tags is retrieved, for example to
13691 obtain a list of properties. Building the tags list for each entry in such
13692 a file becomes an N^2 operation - but with this variable set, it scales
13693 as N.")
13695 (defvar org--matcher-tags-todo-only nil)
13697 (defun org-scan-tags (action matcher todo-only &optional start-level)
13698 "Scan headline tags with inheritance and produce output ACTION.
13700 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13701 or `agenda' to produce an entry list for an agenda view. It can also be
13702 a Lisp form or a function that should be called at each matched headline, in
13703 this case the return value is a list of all return values from these calls.
13705 MATCHER is a function accepting three arguments, returning
13706 a non-nil value whenever a given set of tags qualifies a headline
13707 for inclusion. See `org-make-tags-matcher' for more information.
13708 As a special case, it can also be set to t (respectively nil) in
13709 order to match all (respectively none) headline.
13711 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13712 included in the output.
13714 START-LEVEL can be a string with asterisks, reducing the scope to
13715 headlines matching this string."
13716 (require 'org-agenda)
13717 (let* ((re (concat "^"
13718 (if start-level
13719 ;; Get the correct level to match
13720 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13721 org-outline-regexp)
13722 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13723 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13724 (props (list 'face 'default
13725 'done-face 'org-agenda-done
13726 'undone-face 'default
13727 'mouse-face 'highlight
13728 'org-not-done-regexp org-not-done-regexp
13729 'org-todo-regexp org-todo-regexp
13730 'org-complex-heading-regexp org-complex-heading-regexp
13731 'help-echo
13732 (format "mouse-2 or RET jump to Org file %S"
13733 (abbreviate-file-name
13734 (or (buffer-file-name (buffer-base-buffer))
13735 (buffer-name (buffer-base-buffer)))))))
13736 (org-map-continue-from nil)
13737 lspos tags tags-list
13738 (tags-alist (list (cons 0 org-file-tags)))
13739 (llast 0) rtn rtn1 level category i txt
13740 todo marker entry priority
13741 ts-date ts-date-type ts-date-pair)
13742 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13743 (setq action (list 'lambda nil action)))
13744 (save-excursion
13745 (goto-char (point-min))
13746 (when (eq action 'sparse-tree)
13747 (org-overview)
13748 (org-remove-occur-highlights))
13749 (while (let (case-fold-search)
13750 (re-search-forward re nil t))
13751 (setq org-map-continue-from nil)
13752 (catch :skip
13753 ;; Ignore closing parts of inline tasks.
13754 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13755 (throw :skip t))
13756 (setq todo (and (match-end 1) (match-string-no-properties 1)))
13757 (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
13758 (goto-char (setq lspos (match-beginning 0)))
13759 (setq level (org-reduced-level (org-outline-level))
13760 category (org-get-category))
13761 (when (eq action 'agenda)
13762 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13763 ts-date (car ts-date-pair)
13764 ts-date-type (cdr ts-date-pair)))
13765 (setq i llast llast level)
13766 ;; remove tag lists from same and sublevels
13767 (while (>= i level)
13768 (when (setq entry (assoc i tags-alist))
13769 (setq tags-alist (delete entry tags-alist)))
13770 (setq i (1- i)))
13771 ;; add the next tags
13772 (when tags
13773 (setq tags (org-split-string tags ":")
13774 tags-alist
13775 (cons (cons level tags) tags-alist)))
13776 ;; compile tags for current headline
13777 (setq tags-list
13778 (if org-use-tag-inheritance
13779 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13780 tags)
13781 org-scanner-tags tags-list)
13782 (when org-use-tag-inheritance
13783 (setcdr (car tags-alist)
13784 (mapcar (lambda (x)
13785 (setq x (copy-sequence x))
13786 (org-add-prop-inherited x))
13787 (cdar tags-alist))))
13788 (when (and tags org-use-tag-inheritance
13789 (or (not (eq t org-use-tag-inheritance))
13790 org-tags-exclude-from-inheritance))
13791 ;; Selective inheritance, remove uninherited ones.
13792 (setcdr (car tags-alist)
13793 (org-remove-uninherited-tags (cdar tags-alist))))
13794 (when (and
13796 ;; eval matcher only when the todo condition is OK
13797 (and (or (not todo-only) (member todo org-todo-keywords-1))
13798 (if (functionp matcher)
13799 (let ((case-fold-search t) (org-trust-scanner-tags t))
13800 (funcall matcher todo tags-list level))
13801 matcher))
13803 ;; Call the skipper, but return t if it does not
13804 ;; skip, so that the `and' form continues evaluating.
13805 (progn
13806 (unless (eq action 'sparse-tree) (org-agenda-skip))
13809 ;; Check if timestamps are deselecting this entry
13810 (or (not todo-only)
13811 (and (member todo org-todo-keywords-1)
13812 (or (not org-agenda-tags-todo-honor-ignore-options)
13813 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13815 ;; select this headline
13816 (cond
13817 ((eq action 'sparse-tree)
13818 (and org-highlight-sparse-tree-matches
13819 (org-get-heading) (match-end 0)
13820 (org-highlight-new-match
13821 (match-beginning 1) (match-end 1)))
13822 (org-show-context 'tags-tree))
13823 ((eq action 'agenda)
13824 (setq txt (org-agenda-format-item
13826 (concat
13827 (if (eq org-tags-match-list-sublevels 'indented)
13828 (make-string (1- level) ?.) "")
13829 (org-get-heading))
13830 (make-string level ?\s)
13831 category
13832 tags-list)
13833 priority (org-get-priority txt))
13834 (goto-char lspos)
13835 (setq marker (org-agenda-new-marker))
13836 (org-add-props txt props
13837 'org-marker marker 'org-hd-marker marker 'org-category category
13838 'todo-state todo
13839 'ts-date ts-date
13840 'priority priority
13841 'type (concat "tagsmatch" ts-date-type))
13842 (push txt rtn))
13843 ((functionp action)
13844 (setq org-map-continue-from nil)
13845 (save-excursion
13846 (setq rtn1 (funcall action))
13847 (push rtn1 rtn)))
13848 (t (user-error "Invalid action")))
13850 ;; if we are to skip sublevels, jump to end of subtree
13851 (unless org-tags-match-list-sublevels
13852 (org-end-of-subtree t)
13853 (backward-char 1))))
13854 ;; Get the correct position from where to continue
13855 (if org-map-continue-from
13856 (goto-char org-map-continue-from)
13857 (and (= (point) lspos) (end-of-line 1)))))
13858 (when (and (eq action 'sparse-tree)
13859 (not org-sparse-tree-open-archived-trees))
13860 (org-hide-archived-subtrees (point-min) (point-max)))
13861 (nreverse rtn)))
13863 (defun org-remove-uninherited-tags (tags)
13864 "Remove all tags that are not inherited from the list TAGS."
13865 (cond
13866 ((eq org-use-tag-inheritance t)
13867 (if org-tags-exclude-from-inheritance
13868 (org-delete-all org-tags-exclude-from-inheritance tags)
13869 tags))
13870 ((not org-use-tag-inheritance) nil)
13871 ((stringp org-use-tag-inheritance)
13872 (delq nil (mapcar
13873 (lambda (x)
13874 (if (and (string-match org-use-tag-inheritance x)
13875 (not (member x org-tags-exclude-from-inheritance)))
13876 x nil))
13877 tags)))
13878 ((listp org-use-tag-inheritance)
13879 (delq nil (mapcar
13880 (lambda (x)
13881 (if (member x org-use-tag-inheritance) x nil))
13882 tags)))))
13884 (defun org-match-sparse-tree (&optional todo-only match)
13885 "Create a sparse tree according to tags string MATCH.
13887 MATCH is a string with match syntax. It can contain a selection
13888 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13889 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13890 those. See the manual for details.
13892 If optional argument TODO-ONLY is non-nil, only select lines that
13893 are also TODO tasks."
13894 (interactive "P")
13895 (org-agenda-prepare-buffers (list (current-buffer)))
13896 (let ((org--matcher-tags-todo-only todo-only))
13897 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13898 org--matcher-tags-todo-only)))
13900 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13902 (defvar org-cached-props nil)
13903 (defun org-cached-entry-get (pom property)
13904 (if (or (eq t org-use-property-inheritance)
13905 (and (stringp org-use-property-inheritance)
13906 (let ((case-fold-search t))
13907 (string-match-p org-use-property-inheritance property)))
13908 (and (listp org-use-property-inheritance)
13909 (member-ignore-case property org-use-property-inheritance)))
13910 ;; Caching is not possible, check it directly.
13911 (org-entry-get pom property 'inherit)
13912 ;; Get all properties, so we can do complicated checks easily.
13913 (cdr (assoc-string property
13914 (or org-cached-props
13915 (setq org-cached-props (org-entry-properties pom)))
13916 t))))
13918 (defun org-global-tags-completion-table (&optional files)
13919 "Return the list of all tags in all agenda buffer/files.
13920 Optional FILES argument is a list of files which can be used
13921 instead of the agenda files."
13922 (save-excursion
13923 (org-uniquify
13924 (delq nil
13925 (apply #'append
13926 (mapcar
13927 (lambda (file)
13928 (set-buffer (find-file-noselect file))
13929 (org--tag-add-to-alist
13930 (org-get-buffer-tags)
13931 (mapcar (lambda (x)
13932 (and (stringp (car-safe x))
13933 (list (car-safe x))))
13934 org-current-tag-alist)))
13935 (if (car-safe files) files
13936 (org-agenda-files))))))))
13938 (defun org-make-tags-matcher (match)
13939 "Create the TAGS/TODO matcher form for the selection string MATCH.
13941 Returns a cons of the selection string MATCH and a function
13942 implementing the matcher.
13944 The matcher is to be called at an Org entry, with point on the
13945 headline, and returns non-nil if the entry matches the selection
13946 string MATCH. It must be called with three arguments: the TODO
13947 keyword at the entry (or nil if none), the list of all tags at
13948 the entry including inherited ones and the reduced level of the
13949 headline. Additionally, the category of the entry, if any, must
13950 be specified as the text property `org-category' on the headline.
13952 This function sets the variable `org--matcher-tags-todo-only' to
13953 a non-nil value if the matcher restricts matching to TODO
13954 entries, otherwise it is not touched.
13956 See also `org-scan-tags'."
13957 (unless match
13958 ;; Get a new match request, with completion against the global
13959 ;; tags table and the local tags in current buffer.
13960 (let ((org-last-tags-completion-table
13961 (org--tag-add-to-alist
13962 (org-get-buffer-tags)
13963 (org-global-tags-completion-table))))
13964 (setq match
13965 (completing-read
13966 "Match: "
13967 'org-tags-completion-function nil nil nil 'org-tags-history))))
13969 (let ((match0 match)
13970 (re (concat
13971 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13972 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13973 "\\([<>=]\\{1,2\\}\\)"
13974 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13975 "\\|" org-tag-re "\\)"))
13976 (start 0)
13977 tagsmatch todomatch tagsmatcher todomatcher)
13979 ;; Expand group tags.
13980 (setq match (org-tags-expand match))
13982 ;; Check if there is a TODO part of this match, which would be the
13983 ;; part after a "/". To make sure that this slash is not part of
13984 ;; a property value to be matched against, we also check that
13985 ;; there is no / after that slash. First, find the last slash.
13986 (let ((s 0))
13987 (while (string-match "/+" match s)
13988 (setq start (match-beginning 0))
13989 (setq s (match-end 0))))
13990 (if (and (string-match "/+" match start)
13991 (not (string-match-p "\"" match start)))
13992 ;; Match contains also a TODO-matching request.
13993 (progn
13994 (setq tagsmatch (substring match 0 (match-beginning 0)))
13995 (setq todomatch (substring match (match-end 0)))
13996 (when (string-prefix-p "!" todomatch)
13997 (setq org--matcher-tags-todo-only t)
13998 (setq todomatch (substring todomatch 1)))
13999 (when (string-match "\\`\\s-*\\'" todomatch)
14000 (setq todomatch nil)))
14001 ;; Only matching tags.
14002 (setq tagsmatch match)
14003 (setq todomatch nil))
14005 ;; Make the tags matcher.
14006 (when (org-string-nw-p tagsmatch)
14007 (let ((orlist nil)
14008 (orterms (org-split-string tagsmatch "|"))
14009 term)
14010 (while (setq term (pop orterms))
14011 (while (and (equal (substring term -1) "\\") orterms)
14012 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14013 (while (string-match re term)
14014 (let* ((rest (substring term (match-end 0)))
14015 (minus (and (match-end 1)
14016 (equal (match-string 1 term) "-")))
14017 (tag (save-match-data
14018 (replace-regexp-in-string
14019 "\\\\-" "-" (match-string 2 term))))
14020 (regexp (eq (string-to-char tag) ?{))
14021 (levelp (match-end 4))
14022 (propp (match-end 5))
14024 (cond
14025 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14026 (levelp
14027 `(,(org-op-to-function (match-string 3 term))
14028 level
14029 ,(string-to-number (match-string 4 term))))
14030 (propp
14031 (let* ((gv (pcase (upcase (match-string 5 term))
14032 ("CATEGORY"
14033 '(get-text-property (point) 'org-category))
14034 ("TODO" 'todo)
14035 (p `(org-cached-entry-get nil ,p))))
14036 (pv (match-string 7 term))
14037 (regexp (eq (string-to-char pv) ?{))
14038 (strp (eq (string-to-char pv) ?\"))
14039 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14040 (po (org-op-to-function (match-string 6 term)
14041 (if timep 'time strp))))
14042 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14043 (when timep (setq pv (org-matcher-time pv)))
14044 (cond ((and regexp (eq po '/=))
14045 `(not (string-match ,pv (or ,gv ""))))
14046 (regexp `(string-match ,pv (or ,gv "")))
14047 (strp `(,po (or ,gv "") ,pv))
14049 `(,po
14050 (string-to-number (or ,gv ""))
14051 ,(string-to-number pv))))))
14052 (t `(member ,tag tags-list)))))
14053 (push (if minus `(not ,mm) mm) tagsmatcher)
14054 (setq term rest)))
14055 (push `(and ,@tagsmatcher) orlist)
14056 (setq tagsmatcher nil))
14057 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14059 ;; Make the TODO matcher.
14060 (when (org-string-nw-p todomatch)
14061 (let ((orlist nil))
14062 (dolist (term (org-split-string todomatch "|"))
14063 (while (string-match re term)
14064 (let* ((minus (and (match-end 1)
14065 (equal (match-string 1 term) "-")))
14066 (kwd (match-string 2 term))
14067 (regexp (eq (string-to-char kwd) ?{))
14068 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14069 `(equal todo ,kwd))))
14070 (push (if minus `(not ,mm) mm) todomatcher))
14071 (setq term (substring term (match-end 0))))
14072 (push (if (> (length todomatcher) 1)
14073 (cons 'and todomatcher)
14074 (car todomatcher))
14075 orlist)
14076 (setq todomatcher nil))
14077 (setq todomatcher (cons 'or orlist))))
14079 ;; Return the string and function of the matcher. If no
14080 ;; tags-specific or todo-specific matcher exists, match
14081 ;; everything.
14082 (let ((matcher (if (and tagsmatcher todomatcher)
14083 `(and ,tagsmatcher ,todomatcher)
14084 (or tagsmatcher todomatcher t))))
14085 (when org--matcher-tags-todo-only
14086 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14087 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14089 (defun org--tags-expand-group (group tag-groups expanded)
14090 "Recursively Expand all tags in GROUP, according to TAG-GROUPS.
14091 TAG-GROUPS is the list of groups used for expansion. EXPANDED is
14092 an accumulator used in recursive calls."
14093 (dolist (tag group)
14094 (unless (member tag expanded)
14095 (let ((group (assoc tag tag-groups)))
14096 (push tag expanded)
14097 (when group
14098 (setq expanded
14099 (org--tags-expand-group (cdr group) tag-groups expanded))))))
14100 expanded)
14102 (defun org-tags-expand (match &optional single-as-list downcased)
14103 "Expand group tags in MATCH.
14105 This replaces every group tag in MATCH with a regexp tag search.
14106 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14107 will be replaced like this:
14109 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14110 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14111 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14113 Replacing by a regexp preserves the structure of the match.
14114 E.g., this expansion
14116 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14118 will match anything tagged with \"Lab\" and \"Home\", or tagged
14119 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
14121 A group tag in MATCH can contain regular expressions of its own.
14122 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14123 will be replaced like this:
14125 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14127 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14128 assumed to be a single group tag, and the function will return
14129 the list of tags in this group.
14131 When DOWNCASED is non-nil, expand downcased TAGS."
14132 (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
14133 (let ((tag-groups
14134 (let ((g (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
14135 (if (not downcased) g
14136 (mapcar (lambda (s) (mapcar #'downcase s)) g)))))
14137 (cond
14138 (single-as-list (org--tags-expand-group (list match) tag-groups nil))
14139 (org-group-tags
14140 (let* ((case-fold-search t)
14141 (tag-syntax org-mode-syntax-table)
14142 (group-keys (mapcar #'car tag-groups))
14143 (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
14144 (return-match (if downcased (downcase match) match)))
14145 ;; Mark regexp-expressions in the match-expression so that we
14146 ;; do not replace them later on.
14147 (let ((s 0))
14148 (while (string-match "{.+?}" return-match s)
14149 (setq s (match-end 0))
14150 (add-text-properties
14151 (match-beginning 0) (match-end 0) '(regexp t) return-match)))
14152 ;; @ and _ are allowed as word-components in tags.
14153 (modify-syntax-entry ?@ "w" tag-syntax)
14154 (modify-syntax-entry ?_ "w" tag-syntax)
14155 ;; For each tag token found in MATCH, compute a regexp and it
14156 (with-syntax-table tag-syntax
14157 (replace-regexp-in-string
14158 key-regexp
14159 (lambda (m)
14160 (if (get-text-property (match-beginning 2) 'regexp m)
14161 m ;regexp tag: ignore
14162 (let* ((operator (match-string 1 m))
14163 (tag-token (let ((tag (match-string 2 m)))
14164 (list (if downcased (downcase tag) tag))))
14165 regexp-tags regular-tags)
14166 ;; Partition tags between regexp and regular tags.
14167 ;; Remove curly bracket syntax from regexp tags.
14168 (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
14169 (save-match-data
14170 (if (string-match "{\\(.+?\\)}" tag)
14171 (push (match-string 1 tag) regexp-tags)
14172 (push tag regular-tags))))
14173 ;; Replace tag token by the appropriate regexp.
14174 ;; Regular tags need to be regexp-quoted, whereas
14175 ;; regexp-tags are inserted as-is.
14176 (let ((regular (regexp-opt regular-tags))
14177 (regexp (mapconcat #'identity regexp-tags "\\|")))
14178 (concat operator
14179 (cond
14180 ((null regular-tags) (format "{%s}" regexp))
14181 ((null regexp-tags) (format "{\\<%s\\>}" regular))
14182 (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
14183 return-match
14184 t t))))
14185 (t match))))
14187 (defun org-op-to-function (op &optional stringp)
14188 "Turn an operator into the appropriate function."
14189 (setq op
14190 (cond
14191 ((equal op "<" ) '(< org-string< org-time<))
14192 ((equal op ">" ) '(> org-string> org-time>))
14193 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14194 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14195 ((member op '("=" "==")) '(= string= org-time=))
14196 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14197 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14199 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14200 (defvar org-tags-overlay (make-overlay 1 1))
14201 (delete-overlay org-tags-overlay)
14203 (defun org-add-prop-inherited (s)
14204 (add-text-properties 0 (length s) '(inherited t) s)
14207 (defun org-toggle-tag (tag &optional onoff)
14208 "Toggle the tag TAG for the current line.
14209 If ONOFF is `on' or `off', don't toggle but set to this state."
14210 (save-excursion
14211 (org-back-to-heading t)
14212 (let ((current
14213 ;; Reverse the tags list so any new tag is appended to the
14214 ;; current list of tags.
14215 (nreverse (org-get-tags nil t)))
14216 res)
14217 (pcase onoff
14218 (`off (setq current (delete tag current)))
14219 ((or `on (guard (not (member tag current))))
14220 (setq res t)
14221 (cl-pushnew tag current :test #'equal))
14222 (_ (setq current (delete tag current))))
14223 (org-set-tags (nreverse current))
14224 res)))
14226 (defun org--align-tags-here (to-col)
14227 "Align tags on the current headline to TO-COL.
14228 Assume point is on a headline. Preserve point when aligning
14229 tags."
14230 (when (org-match-line org-tag-line-re)
14231 (let* ((tags-start (match-beginning 1))
14232 (blank-start (save-excursion
14233 (goto-char tags-start)
14234 (skip-chars-backward " \t")
14235 (point)))
14236 (new (max (if (>= to-col 0) to-col
14237 (- (abs to-col) (string-width (match-string 1))))
14238 ;; Introduce at least one space after the heading
14239 ;; or the stars.
14240 (save-excursion
14241 (goto-char blank-start)
14242 (1+ (current-column)))))
14243 (current
14244 (save-excursion (goto-char tags-start) (current-column)))
14245 (origin (point-marker))
14246 (column (current-column))
14247 (in-blank? (and (> origin blank-start) (<= origin tags-start))))
14248 (when (/= new current)
14249 (delete-region blank-start tags-start)
14250 (goto-char blank-start)
14251 (let ((indent-tabs-mode nil)) (indent-to new))
14252 ;; Try to move back to original position. If point was in the
14253 ;; blanks before the tags, ORIGIN marker is of no use because
14254 ;; it now points to BLANK-START. Use COLUMN instead.
14255 (if in-blank? (org-move-to-column column) (goto-char origin))))))
14257 (defun org-set-tags-command (&optional arg)
14258 "Set the tags for the current visible entry.
14260 When called with `\\[universal-argument]' prefix argument ARG, \
14261 realign all tags
14262 in the current buffer. If a region is active, set tags for
14263 all headlines in the region.
14265 This function is for interactive use only;
14266 in Lisp code use `org-set-tags' instead."
14267 (interactive "P")
14268 (cond
14269 (arg (org-align-tags t))
14270 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14271 ;; Disable `org-loop-over-headlines-in-active-region' for
14272 ;; successive calls.
14273 (let (org-loop-over-headlines-in-active-region)
14274 (org-map-entries
14275 #'org-set-tags-command
14277 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14278 'region-start-level
14279 'region)
14280 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14282 (save-excursion
14283 (org-back-to-heading)
14284 (let* ((all-tags (org-get-tags))
14285 (table (setq org-last-tags-completion-table
14286 (org--tag-add-to-alist
14287 (and org-complete-tags-always-offer-all-agenda-tags
14288 (org-global-tags-completion-table
14289 (org-agenda-files)))
14290 (or org-current-tag-alist (org-get-buffer-tags)))))
14291 (current-tags
14292 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14293 all-tags))
14294 (inherited-tags
14295 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14296 all-tags))
14297 (tags
14298 (replace-regexp-in-string
14299 ;; Ignore all forbidden characters in tags.
14300 "[^[:alnum:]_@#%]+" ":"
14301 (if (or (eq t org-use-fast-tag-selection)
14302 (and org-use-fast-tag-selection
14303 (delq nil (mapcar #'cdr table))))
14304 (org-fast-tag-selection
14305 current-tags
14306 inherited-tags
14307 table
14308 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14309 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14310 (org-trim (completing-read
14311 "Tags: "
14312 #'org-tags-completion-function
14313 nil nil (org-make-tag-string current-tags)
14314 'org-tags-history)))))))
14315 (org-set-tags tags))))))
14317 (defun org-align-tags (&optional all)
14318 "Align tags in current entry.
14319 When optional argument ALL is non-nil, align all tags in the
14320 visible part of the buffer."
14321 (let ((get-indent-column
14322 (lambda ()
14323 (let ((offset (if (bound-and-true-p org-indent-mode)
14324 (* (1- org-indent-indentation-per-level)
14325 (1- (org-current-level)))
14326 0)))
14327 (+ org-tags-column
14328 (if (> org-tags-column 0) (- offset) offset))))))
14329 (if (and (not all) (org-at-heading-p))
14330 (org--align-tags-here (funcall get-indent-column))
14331 (save-excursion
14332 (if all
14333 (while (re-search-forward org-tag-line-re nil t)
14334 (org--align-tags-here (funcall get-indent-column)))
14335 (org-back-to-heading t)
14336 (org--align-tags-here (funcall get-indent-column)))))))
14338 (defun org-set-tags (tags)
14339 "Set the tags of the current entry to TAGS, replacing current tags.
14341 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14342 If TAGS is nil or the empty string, all tags are removed.
14344 This function assumes point is on a headline."
14345 (org-with-wide-buffer
14346 (let ((tags (pcase tags
14347 ((pred listp) tags)
14348 ((pred stringp) (split-string (org-trim tags) ":" t))
14349 (_ (error "Invalid tag specification: %S" tags))))
14350 (old-tags (org-get-tags nil t))
14351 (tags-change? nil))
14352 (when (functionp org-tags-sort-function)
14353 (setq tags (sort tags org-tags-sort-function)))
14354 (setq tags-change? (not (equal tags old-tags)))
14355 (when tags-change?
14356 ;; Delete previous tags and any trailing white space.
14357 (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
14358 (line-end-position)))
14359 (skip-chars-backward " \t")
14360 (delete-region (point) (line-end-position))
14361 ;; Deleting white spaces may break an otherwise empty headline.
14362 ;; Re-introduce one space in this case.
14363 (unless (org-at-heading-p) (insert " "))
14364 (when tags
14365 (save-excursion (insert " " (org-make-tag-string tags)))
14366 ;; When text is being inserted on an invisible region
14367 ;; boundary, it can be inadvertently sucked into
14368 ;; invisibility.
14369 (unless (org-invisible-p (line-beginning-position))
14370 (org-flag-region (point) (line-end-position) nil 'outline))))
14371 ;; Align tags, if any.
14372 (when tags (org-align-tags))
14373 (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
14375 (defun org-change-tag-in-region (beg end tag off)
14376 "Add or remove TAG for each entry in the region.
14377 This works in the agenda, and also in an Org buffer."
14378 (interactive
14379 (list (region-beginning) (region-end)
14380 (let ((org-last-tags-completion-table
14381 (if (derived-mode-p 'org-mode)
14382 (org--tag-add-to-alist
14383 (org-get-buffer-tags)
14384 (org-global-tags-completion-table))
14385 (org-global-tags-completion-table))))
14386 (completing-read
14387 "Tag: " 'org-tags-completion-function nil nil nil
14388 'org-tags-history))
14389 (progn
14390 (message "[s]et or [r]emove? ")
14391 (equal (read-char-exclusive) ?r))))
14392 (when (fboundp 'deactivate-mark) (deactivate-mark))
14393 (let ((agendap (equal major-mode 'org-agenda-mode))
14394 l1 l2 m buf pos newhead (cnt 0))
14395 (goto-char end)
14396 (setq l2 (1- (org-current-line)))
14397 (goto-char beg)
14398 (setq l1 (org-current-line))
14399 (cl-loop for l from l1 to l2 do
14400 (org-goto-line l)
14401 (setq m (get-text-property (point) 'org-hd-marker))
14402 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14403 (and agendap m))
14404 (setq buf (if agendap (marker-buffer m) (current-buffer))
14405 pos (if agendap m (point)))
14406 (with-current-buffer buf
14407 (save-excursion
14408 (save-restriction
14409 (goto-char pos)
14410 (setq cnt (1+ cnt))
14411 (org-toggle-tag tag (if off 'off 'on))
14412 (setq newhead (org-get-heading)))))
14413 (and agendap (org-agenda-change-all-lines newhead m))))
14414 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14416 (defun org-tags-completion-function (string _predicate &optional flag)
14417 "Complete tag STRING.
14418 FLAG specifies the type of completion operation to perform. This
14419 function is passed as a collection function to `completing-read',
14420 which see."
14421 (let ((completion-ignore-case nil) ;tags are case-sensitive
14422 (confirm (lambda (x) (stringp (car x))))
14423 (prefix ""))
14424 (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14425 (setq prefix (match-string 1 string))
14426 (setq string (match-string 2 string)))
14427 (pcase flag
14428 (`t (all-completions string org-last-tags-completion-table confirm))
14429 (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
14430 (`nil
14431 (pcase (try-completion string org-last-tags-completion-table confirm)
14432 ((and completion (pred stringp))
14433 (concat prefix
14434 completion
14435 (if (and org-add-colon-after-tag-completion
14436 (assoc completion org-last-tags-completion-table))
14438 "")))
14439 (completion completion)))
14440 (_ nil))))
14442 (defun org-fast-tag-insert (kwd tags face &optional end)
14443 "Insert KWD, and the TAGS, the latter with face FACE.
14444 Also insert END."
14445 (insert (format "%-12s" (concat kwd ":"))
14446 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14447 (or end "")))
14449 (defun org-fast-tag-show-exit (flag)
14450 (save-excursion
14451 (org-goto-line 3)
14452 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14453 (replace-match ""))
14454 (when flag
14455 (end-of-line 1)
14456 (org-move-to-column (- (window-width) 19) t)
14457 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14459 (defun org-set-current-tags-overlay (current prefix)
14460 "Add an overlay to CURRENT tag with PREFIX."
14461 (let ((s (org-make-tag-string current)))
14462 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14463 (org-overlay-display org-tags-overlay (concat prefix s))))
14465 (defvar org-last-tag-selection-key nil)
14466 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14467 "Fast tag selection with single keys.
14468 CURRENT is the current list of tags in the headline, INHERITED is the
14469 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14470 possibly with grouping information. TODO-TABLE is a similar table with
14471 TODO keywords, should these have keys assigned to them.
14472 If the keys are nil, a-z are automatically assigned.
14473 Returns the new tags string, or nil to not change the current settings."
14474 (let* ((fulltable (append table todo-table))
14475 (maxlen (if (null fulltable) 0
14476 (apply #'max
14477 (mapcar (lambda (x)
14478 (if (stringp (car x)) (string-width (car x))
14480 fulltable))))
14481 (buf (current-buffer))
14482 (expert (eq org-fast-tag-selection-single-key 'expert))
14483 (buffer-tags nil)
14484 (fwidth (+ maxlen 3 1 3))
14485 (ncol (/ (- (window-width) 4) fwidth))
14486 (i-face 'org-done)
14487 (c-face 'org-todo)
14488 tg cnt e c char c1 c2 ntable tbl rtn
14489 ov-start ov-end ov-prefix
14490 (exit-after-next org-fast-tag-selection-single-key)
14491 (done-keywords org-done-keywords)
14492 groups ingroup intaggroup)
14493 (save-excursion
14494 (beginning-of-line)
14495 (if (looking-at org-tag-line-re)
14496 (setq ov-start (match-beginning 1)
14497 ov-end (match-end 1)
14498 ov-prefix "")
14499 (setq ov-start (1- (point-at-eol))
14500 ov-end (1+ ov-start))
14501 (skip-chars-forward "^\n\r")
14502 (setq ov-prefix
14503 (concat
14504 (buffer-substring (1- (point)) (point))
14505 (if (> (current-column) org-tags-column)
14507 (make-string (- org-tags-column (current-column)) ?\ ))))))
14508 (move-overlay org-tags-overlay ov-start ov-end)
14509 (save-window-excursion
14510 (if expert
14511 (set-buffer (get-buffer-create " *Org tags*"))
14512 (delete-other-windows)
14513 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14514 (org-switch-to-buffer-other-window " *Org tags*"))
14515 (erase-buffer)
14516 (setq-local org-done-keywords done-keywords)
14517 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14518 (org-fast-tag-insert "Current" current c-face "\n\n")
14519 (org-fast-tag-show-exit exit-after-next)
14520 (org-set-current-tags-overlay current ov-prefix)
14521 (setq tbl fulltable char ?a cnt 0)
14522 (while (setq e (pop tbl))
14523 (cond
14524 ((eq (car e) :startgroup)
14525 (push '() groups) (setq ingroup t)
14526 (unless (zerop cnt)
14527 (setq cnt 0)
14528 (insert "\n"))
14529 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14530 ((eq (car e) :endgroup)
14531 (setq ingroup nil cnt 0)
14532 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14533 ((eq (car e) :startgrouptag)
14534 (setq intaggroup t)
14535 (unless (zerop cnt)
14536 (setq cnt 0)
14537 (insert "\n"))
14538 (insert "[ "))
14539 ((eq (car e) :endgrouptag)
14540 (setq intaggroup nil cnt 0)
14541 (insert "]\n"))
14542 ((equal e '(:newline))
14543 (unless (zerop cnt)
14544 (setq cnt 0)
14545 (insert "\n")
14546 (setq e (car tbl))
14547 (while (equal (car tbl) '(:newline))
14548 (insert "\n")
14549 (setq tbl (cdr tbl)))))
14550 ((equal e '(:grouptags)) (insert " : "))
14552 (setq tg (copy-sequence (car e)) c2 nil)
14553 (if (cdr e)
14554 (setq c (cdr e))
14555 ;; automatically assign a character.
14556 (setq c1 (string-to-char
14557 (downcase (substring
14558 tg (if (= (string-to-char tg) ?@) 1 0)))))
14559 (if (or (rassoc c1 ntable) (rassoc c1 table))
14560 (while (or (rassoc char ntable) (rassoc char table))
14561 (setq char (1+ char)))
14562 (setq c2 c1))
14563 (setq c (or c2 char)))
14564 (when ingroup (push tg (car groups)))
14565 (setq tg (org-add-props tg nil 'face
14566 (cond
14567 ((not (assoc tg table))
14568 (org-get-todo-face tg))
14569 ((member tg current) c-face)
14570 ((member tg inherited) i-face))))
14571 (when (equal (caar tbl) :grouptags)
14572 (org-add-props tg nil 'face 'org-tag-group))
14573 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14574 (insert "[" c "] " tg (make-string
14575 (- fwidth 4 (length tg)) ?\ ))
14576 (push (cons tg c) ntable)
14577 (when (= (cl-incf cnt) ncol)
14578 (insert "\n")
14579 (when (or ingroup intaggroup) (insert " "))
14580 (setq cnt 0)))))
14581 (setq ntable (nreverse ntable))
14582 (insert "\n")
14583 (goto-char (point-min))
14584 (unless expert (org-fit-window-to-buffer))
14585 (setq rtn
14586 (catch 'exit
14587 (while t
14588 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14589 (if (not groups) "no " "")
14590 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14591 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14592 (setq org-last-tag-selection-key c)
14593 (cond
14594 ((= c ?\r) (throw 'exit t))
14595 ((= c ?!)
14596 (setq groups (not groups))
14597 (goto-char (point-min))
14598 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14599 ((= c ?\C-c)
14600 (if (not expert)
14601 (org-fast-tag-show-exit
14602 (setq exit-after-next (not exit-after-next)))
14603 (setq expert nil)
14604 (delete-other-windows)
14605 (set-window-buffer (split-window-vertically) " *Org tags*")
14606 (org-switch-to-buffer-other-window " *Org tags*")
14607 (org-fit-window-to-buffer)))
14608 ((or (= c ?\C-g)
14609 (and (= c ?q) (not (rassoc c ntable))))
14610 (delete-overlay org-tags-overlay)
14611 (setq quit-flag t))
14612 ((= c ?\ )
14613 (setq current nil)
14614 (when exit-after-next (setq exit-after-next 'now)))
14615 ((= c ?\t)
14616 (condition-case nil
14617 (setq tg (completing-read
14618 "Tag: "
14619 (or buffer-tags
14620 (with-current-buffer buf
14621 (setq buffer-tags
14622 (org-get-buffer-tags))))))
14623 (quit (setq tg "")))
14624 (when (string-match "\\S-" tg)
14625 (cl-pushnew (list tg) buffer-tags :test #'equal)
14626 (if (member tg current)
14627 (setq current (delete tg current))
14628 (push tg current)))
14629 (when exit-after-next (setq exit-after-next 'now)))
14630 ((setq e (rassoc c todo-table) tg (car e))
14631 (with-current-buffer buf
14632 (save-excursion (org-todo tg)))
14633 (when exit-after-next (setq exit-after-next 'now)))
14634 ((setq e (rassoc c ntable) tg (car e))
14635 (if (member tg current)
14636 (setq current (delete tg current))
14637 (cl-loop for g in groups do
14638 (when (member tg g)
14639 (dolist (x g) (setq current (delete x current)))))
14640 (push tg current))
14641 (when exit-after-next (setq exit-after-next 'now))))
14643 ;; Create a sorted list
14644 (setq current
14645 (sort current
14646 (lambda (a b)
14647 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14648 (when (eq exit-after-next 'now) (throw 'exit t))
14649 (goto-char (point-min))
14650 (beginning-of-line 2)
14651 (delete-region (point) (point-at-eol))
14652 (org-fast-tag-insert "Current" current c-face)
14653 (org-set-current-tags-overlay current ov-prefix)
14654 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14655 (while (re-search-forward tag-re nil t)
14656 (let ((tag (match-string 1)))
14657 (add-text-properties
14658 (match-beginning 1) (match-end 1)
14659 (list 'face
14660 (cond
14661 ((member tag current) c-face)
14662 ((member tag inherited) i-face)
14663 (t (get-text-property (match-beginning 1) '
14664 face))))))))
14665 (goto-char (point-min)))))
14666 (delete-overlay org-tags-overlay)
14667 (if rtn
14668 (mapconcat 'identity current ":")
14669 nil))))
14671 (defun org-make-tag-string (tags)
14672 "Return string associated to TAGS.
14673 TAGS is a list of strings."
14674 (if (null tags) ""
14675 (format ":%s:" (mapconcat #'identity tags ":"))))
14677 (defun org--get-local-tags ()
14678 "Return list of tags for the current headline.
14679 Assume point is at the beginning of the headline."
14680 (and (looking-at org-tag-line-re)
14681 (split-string (match-string-no-properties 2) ":" t)))
14683 (defun org-get-tags (&optional pos local)
14684 "Get the list of tags specified in the current headline.
14686 When argument POS is non-nil, retrieve tags for headline at POS.
14688 According to `org-use-tags-inheritance', tags may be inherited
14689 from parent headlines, and from the whole document, through
14690 `org-file-tags'. However, when optional argument LOCAL is
14691 non-nil, only return tags specified at the headline.
14693 Inherited tags have the `inherited' text property."
14694 (if (and org-trust-scanner-tags
14695 (or (not pos) (eq pos (point)))
14696 (not local))
14697 org-scanner-tags
14698 (org-with-point-at (or pos (point))
14699 (unless (org-before-first-heading-p)
14700 (org-back-to-heading t)
14701 (let ((ltags (org--get-local-tags)) itags)
14702 (if (or local (not org-use-tag-inheritance)) ltags
14703 (setq itags org-file-tags)
14704 (while (org-up-heading-safe)
14705 (setq itags (append (mapcar #'org-add-prop-inherited
14706 (org--get-local-tags))
14707 itags)))
14708 (delete-dups
14709 (append (org-remove-uninherited-tags itags) ltags))))))))
14711 (defun org-get-buffer-tags ()
14712 "Get a table of all tags used in the buffer, for completion."
14713 (org-with-point-at 1
14714 (let (tags)
14715 (while (re-search-forward org-tag-line-re nil t)
14716 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14717 tags)))
14718 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14720 ;;;; The mapping API
14722 (defvar org-agenda-skip-comment-trees)
14723 (defvar org-agenda-skip-function)
14724 (defun org-map-entries (func &optional match scope &rest skip)
14725 "Call FUNC at each headline selected by MATCH in SCOPE.
14727 FUNC is a function or a lisp form. The function will be called without
14728 arguments, with the cursor positioned at the beginning of the headline.
14729 The return values of all calls to the function will be collected and
14730 returned as a list.
14732 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14733 does not need to preserve point. After evaluation, the cursor will be
14734 moved to the end of the line (presumably of the headline of the
14735 processed entry) and search continues from there. Under some
14736 circumstances, this may not produce the wanted results. For example,
14737 if you have removed (e.g. archived) the current (sub)tree it could
14738 mean that the next entry will be skipped entirely. In such cases, you
14739 can specify the position from where search should continue by making
14740 FUNC set the variable `org-map-continue-from' to the desired buffer
14741 position.
14743 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14744 Only headlines that are matched by this query will be considered during
14745 the iteration. When MATCH is nil or t, all headlines will be
14746 visited by the iteration.
14748 SCOPE determines the scope of this command. It can be any of:
14750 nil The current buffer, respecting the restriction if any
14751 tree The subtree started with the entry at point
14752 region The entries within the active region, if any
14753 region-start-level
14754 The entries within the active region, but only those at
14755 the same level than the first one.
14756 file The current buffer, without restriction
14757 file-with-archives
14758 The current buffer, and any archives associated with it
14759 agenda All agenda files
14760 agenda-with-archives
14761 All agenda files with any archive files associated with them
14762 \(file1 file2 ...)
14763 If this is a list, all files in the list will be scanned
14765 The remaining args are treated as settings for the skipping facilities of
14766 the scanner. The following items can be given here:
14768 archive skip trees with the archive tag
14769 comment skip trees with the COMMENT keyword
14770 function or Emacs Lisp form:
14771 will be used as value for `org-agenda-skip-function', so
14772 whenever the function returns a position, FUNC will not be
14773 called for that entry and search will continue from the
14774 position returned
14776 If your function needs to retrieve the tags including inherited tags
14777 at the *current* entry, you can use the value of the variable
14778 `org-scanner-tags' which will be much faster than getting the value
14779 with `org-get-tags'. If your function gets properties with
14780 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14781 to t around the call to `org-entry-properties' to get the same speedup.
14782 Note that if your function moves around to retrieve tags and properties at
14783 a *different* entry, you cannot use these techniques."
14784 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14785 (not (org-region-active-p)))
14786 (let* ((org-agenda-archives-mode nil) ; just to make sure
14787 (org-agenda-skip-archived-trees (memq 'archive skip))
14788 (org-agenda-skip-comment-trees (memq 'comment skip))
14789 (org-agenda-skip-function
14790 (car (org-delete-all '(comment archive) skip)))
14791 (org-tags-match-list-sublevels t)
14792 (start-level (eq scope 'region-start-level))
14793 matcher res
14794 org-todo-keywords-for-agenda
14795 org-done-keywords-for-agenda
14796 org-todo-keyword-alist-for-agenda
14797 org-tag-alist-for-agenda
14798 org--matcher-tags-todo-only)
14800 (cond
14801 ((eq match t) (setq matcher t))
14802 ((eq match nil) (setq matcher t))
14803 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14805 (save-excursion
14806 (save-restriction
14807 (cond ((eq scope 'tree)
14808 (org-back-to-heading t)
14809 (org-narrow-to-subtree)
14810 (setq scope nil))
14811 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14812 (org-region-active-p))
14813 ;; If needed, set start-level to a string like "2"
14814 (when start-level
14815 (save-excursion
14816 (goto-char (region-beginning))
14817 (unless (org-at-heading-p) (outline-next-heading))
14818 (setq start-level (org-current-level))))
14819 (narrow-to-region (region-beginning)
14820 (save-excursion
14821 (goto-char (region-end))
14822 (unless (and (bolp) (org-at-heading-p))
14823 (outline-next-heading))
14824 (point)))
14825 (setq scope nil)))
14827 (if (not scope)
14828 (progn
14829 (org-agenda-prepare-buffers
14830 (and buffer-file-name (list buffer-file-name)))
14831 (setq res
14832 (org-scan-tags
14833 func matcher org--matcher-tags-todo-only start-level)))
14834 ;; Get the right scope
14835 (cond
14836 ((and scope (listp scope) (symbolp (car scope)))
14837 (setq scope (eval scope)))
14838 ((eq scope 'agenda)
14839 (setq scope (org-agenda-files t)))
14840 ((eq scope 'agenda-with-archives)
14841 (setq scope (org-agenda-files t))
14842 (setq scope (org-add-archive-files scope)))
14843 ((eq scope 'file)
14844 (setq scope (and buffer-file-name (list buffer-file-name))))
14845 ((eq scope 'file-with-archives)
14846 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14847 (org-agenda-prepare-buffers scope)
14848 (dolist (file scope)
14849 (with-current-buffer (org-find-base-buffer-visiting file)
14850 (org-with-wide-buffer
14851 (goto-char (point-min))
14852 (setq res
14853 (append
14855 (org-scan-tags
14856 func matcher org--matcher-tags-todo-only)))))))))
14857 res)))
14859 ;;; Properties API
14861 (defconst org-special-properties
14862 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14863 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14864 "The special properties valid in Org mode.
14865 These are properties that are not defined in the property drawer,
14866 but in some other way.")
14868 (defconst org-default-properties
14869 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14870 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14871 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14872 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14873 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14874 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14875 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14876 "Some properties that are used by Org mode for various purposes.
14877 Being in this list makes sure that they are offered for completion.")
14879 (defun org--valid-property-p (property)
14880 "Non nil when string PROPERTY is a valid property name."
14881 (not
14882 (or (equal property "")
14883 (string-match-p "\\s-" property))))
14885 (defun org--update-property-plist (key val props)
14886 "Associate KEY to VAL in alist PROPS.
14887 Modifications are made by side-effect. Return new alist."
14888 (let* ((appending (string= (substring key -1) "+"))
14889 (key (if appending (substring key 0 -1) key))
14890 (old (assoc-string key props t)))
14891 (if (not old) (cons (cons key val) props)
14892 (setcdr old (if appending (concat (cdr old) " " val) val))
14893 props)))
14895 (defun org-get-property-block (&optional beg force)
14896 "Return the (beg . end) range of the body of the property drawer.
14897 BEG is the beginning of the current subtree, or of the part
14898 before the first headline. If it is not given, it will be found.
14899 If the drawer does not exist, create it if FORCE is non-nil, or
14900 return nil."
14901 (org-with-wide-buffer
14902 (when beg (goto-char beg))
14903 (unless (org-before-first-heading-p)
14904 (let ((beg (cond (beg)
14905 ((or (not (featurep 'org-inlinetask))
14906 (org-inlinetask-in-task-p))
14907 (org-back-to-heading t))
14908 (t (org-with-limited-levels (org-back-to-heading t))))))
14909 (forward-line)
14910 (when (looking-at-p org-planning-line-re) (forward-line))
14911 (cond ((looking-at org-property-drawer-re)
14912 (forward-line)
14913 (cons (point) (progn (goto-char (match-end 0))
14914 (line-beginning-position))))
14915 (force
14916 (goto-char beg)
14917 (org-insert-property-drawer)
14918 (let ((pos (save-excursion (search-forward ":END:")
14919 (line-beginning-position))))
14920 (cons pos pos))))))))
14922 (defun org-at-property-p ()
14923 "Non-nil when point is inside a property drawer.
14924 See `org-property-re' for match data, if applicable."
14925 (save-excursion
14926 (beginning-of-line)
14927 (and (looking-at org-property-re)
14928 (let ((property-drawer (save-match-data (org-get-property-block))))
14929 (and property-drawer
14930 (>= (point) (car property-drawer))
14931 (< (point) (cdr property-drawer)))))))
14933 (defun org-property-action ()
14934 "Do an action on properties."
14935 (interactive)
14936 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14937 (let ((c (read-char-exclusive)))
14938 (cl-case c
14939 (?s (call-interactively #'org-set-property))
14940 (?d (call-interactively #'org-delete-property))
14941 (?D (call-interactively #'org-delete-property-globally))
14942 (?c (call-interactively #'org-compute-property-at-point))
14943 (otherwise (user-error "No such property action %c" c)))))
14945 (defun org-inc-effort ()
14946 "Increment the value of the effort property in the current entry."
14947 (interactive)
14948 (org-set-effort t))
14950 (defvar org-clock-effort) ; Defined in org-clock.el.
14951 (defvar org-clock-current-task) ; Defined in org-clock.el.
14952 (defun org-set-effort (&optional increment value)
14953 "Set the effort property of the current entry.
14954 If INCREMENT is non-nil, set the property to the next allowed
14955 value. Otherwise, if optional argument VALUE is provided, use
14956 it. Eventually, prompt for the new value if none of the previous
14957 variables is set."
14958 (interactive "P")
14959 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14960 (current (org-entry-get nil org-effort-property))
14961 (value
14962 (cond
14963 (increment
14964 (unless allowed (user-error "Allowed effort values are not set"))
14965 (or (cl-caadr (member (list current) allowed))
14966 (user-error "Unknown value %S among allowed values" current)))
14967 (value
14968 (if (stringp value) value
14969 (error "Invalid effort value: %S" value)))
14971 (let ((must-match
14972 (and allowed
14973 (not (get-text-property 0 'org-unrestricted
14974 (caar allowed))))))
14975 (completing-read "Effort: " allowed nil must-match))))))
14976 (unless (equal current value)
14977 (org-entry-put nil org-effort-property value))
14978 (org-refresh-property '((effort . identity)
14979 (effort-minutes . org-duration-to-minutes))
14980 value)
14981 (when (equal (org-get-heading t t t t)
14982 (bound-and-true-p org-clock-current-task))
14983 (setq org-clock-effort (org-get-at-bol 'effort))
14984 (org-clock-update-mode-line))
14985 (message "%s is now %s" org-effort-property value)))
14987 (defun org-entry-properties (&optional pom which)
14988 "Get all properties of the current entry.
14990 When POM is a buffer position, get all properties from the entry
14991 there instead.
14993 This includes the TODO keyword, the tags, time strings for
14994 deadline, scheduled, and clocking, and any additional properties
14995 defined in the entry.
14997 If WHICH is nil or `all', get all properties. If WHICH is
14998 `special' or `standard', only get that subclass. If WHICH is
14999 a string, only get that property.
15001 Return value is an alist. Keys are properties, as upcased
15002 strings."
15003 (org-with-point-at pom
15004 (when (and (derived-mode-p 'org-mode)
15005 (ignore-errors (org-back-to-heading t)))
15006 (catch 'exit
15007 (let* ((beg (point))
15008 (specific (and (stringp which) (upcase which)))
15009 (which (cond ((not specific) which)
15010 ((member specific org-special-properties) 'special)
15011 (t 'standard)))
15012 props)
15013 ;; Get the special properties, like TODO and TAGS.
15014 (when (memq which '(nil all special))
15015 (when (or (not specific) (string= specific "CLOCKSUM"))
15016 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15017 (when clocksum
15018 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15019 props)))
15020 (when specific (throw 'exit props)))
15021 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15022 (let ((clocksumt (get-text-property (point)
15023 :org-clock-minutes-today)))
15024 (when clocksumt
15025 (push (cons "CLOCKSUM_T"
15026 (org-duration-from-minutes clocksumt))
15027 props)))
15028 (when specific (throw 'exit props)))
15029 (when (or (not specific) (string= specific "ITEM"))
15030 (let ((case-fold-search nil))
15031 (when (looking-at org-complex-heading-regexp)
15032 (push (cons "ITEM"
15033 (let ((title (match-string-no-properties 4)))
15034 (if (org-string-nw-p title)
15035 (org-remove-tabs title)
15036 "")))
15037 props)))
15038 (when specific (throw 'exit props)))
15039 (when (or (not specific) (string= specific "TODO"))
15040 (let ((case-fold-search nil))
15041 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15042 (push (cons "TODO" (match-string-no-properties 2)) props)))
15043 (when specific (throw 'exit props)))
15044 (when (or (not specific) (string= specific "PRIORITY"))
15045 (push (cons "PRIORITY"
15046 (if (looking-at org-priority-regexp)
15047 (match-string-no-properties 2)
15048 (char-to-string org-default-priority)))
15049 props)
15050 (when specific (throw 'exit props)))
15051 (when (or (not specific) (string= specific "FILE"))
15052 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15053 props)
15054 (when specific (throw 'exit props)))
15055 (when (or (not specific) (string= specific "TAGS"))
15056 (let ((tags (org-get-tags nil t)))
15057 (when tags
15058 (push (cons "TAGS" (org-make-tag-string tags))
15059 props)))
15060 (when specific (throw 'exit props)))
15061 (when (or (not specific) (string= specific "ALLTAGS"))
15062 (let ((tags (org-get-tags)))
15063 (when tags
15064 (push (cons "ALLTAGS" (org-make-tag-string tags))
15065 props)))
15066 (when specific (throw 'exit props)))
15067 (when (or (not specific) (string= specific "BLOCKED"))
15068 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15069 (when specific (throw 'exit props)))
15070 (when (or (not specific)
15071 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15072 (forward-line)
15073 (when (looking-at-p org-planning-line-re)
15074 (end-of-line)
15075 (let ((bol (line-beginning-position))
15076 ;; Backward compatibility: time keywords used to
15077 ;; be configurable (before 8.3). Make sure we
15078 ;; get the correct keyword.
15079 (key-assoc `(("CLOSED" . ,org-closed-string)
15080 ("DEADLINE" . ,org-deadline-string)
15081 ("SCHEDULED" . ,org-scheduled-string))))
15082 (dolist (pair (if specific (list (assoc specific key-assoc))
15083 key-assoc))
15084 (save-excursion
15085 (when (search-backward (cdr pair) bol t)
15086 (goto-char (match-end 0))
15087 (skip-chars-forward " \t")
15088 (and (looking-at org-ts-regexp-both)
15089 (push (cons (car pair)
15090 (match-string-no-properties 0))
15091 props)))))))
15092 (when specific (throw 'exit props)))
15093 (when (or (not specific)
15094 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15095 (let ((find-ts
15096 (lambda (end ts)
15097 ;; Fix next time-stamp before END. TS is the
15098 ;; list of time-stamps found so far.
15099 (let ((ts ts)
15100 (regexp (cond
15101 ((string= specific "TIMESTAMP")
15102 org-ts-regexp)
15103 ((string= specific "TIMESTAMP_IA")
15104 org-ts-regexp-inactive)
15105 ((assoc "TIMESTAMP_IA" ts)
15106 org-ts-regexp)
15107 ((assoc "TIMESTAMP" ts)
15108 org-ts-regexp-inactive)
15109 (t org-ts-regexp-both))))
15110 (catch 'next
15111 (while (re-search-forward regexp end t)
15112 (backward-char)
15113 (let ((object (org-element-context)))
15114 ;; Accept to match timestamps in node
15115 ;; properties, too.
15116 (when (memq (org-element-type object)
15117 '(node-property timestamp))
15118 (let ((type
15119 (org-element-property :type object)))
15120 (cond
15121 ((and (memq type '(active active-range))
15122 (not (equal specific "TIMESTAMP_IA")))
15123 (unless (assoc "TIMESTAMP" ts)
15124 (push (cons "TIMESTAMP"
15125 (org-element-property
15126 :raw-value object))
15128 (when specific (throw 'exit ts))))
15129 ((and (memq type '(inactive inactive-range))
15130 (not (string= specific "TIMESTAMP")))
15131 (unless (assoc "TIMESTAMP_IA" ts)
15132 (push (cons "TIMESTAMP_IA"
15133 (org-element-property
15134 :raw-value object))
15136 (when specific (throw 'exit ts))))))
15137 ;; Both timestamp types are found,
15138 ;; move to next part.
15139 (when (= (length ts) 2) (throw 'next ts)))))
15140 ts)))))
15141 (goto-char beg)
15142 ;; First look for timestamps within headline.
15143 (let ((ts (funcall find-ts (line-end-position) nil)))
15144 (if (= (length ts) 2) (setq props (nconc ts props))
15145 ;; Then find timestamps in the section, skipping
15146 ;; planning line.
15147 (let ((end (save-excursion (outline-next-heading))))
15148 (forward-line)
15149 (when (looking-at-p org-planning-line-re) (forward-line))
15150 (setq props (nconc (funcall find-ts end ts) props))))))))
15151 ;; Get the standard properties, like :PROP:.
15152 (when (memq which '(nil all standard))
15153 ;; If we are looking after a specific property, delegate
15154 ;; to `org-entry-get', which is faster. However, make an
15155 ;; exception for "CATEGORY", since it can be also set
15156 ;; through keywords (i.e. #+CATEGORY).
15157 (if (and specific (not (equal specific "CATEGORY")))
15158 (let ((value (org-entry-get beg specific nil t)))
15159 (throw 'exit (and value (list (cons specific value)))))
15160 (let ((range (org-get-property-block beg)))
15161 (when range
15162 (let ((end (cdr range)) seen-base)
15163 (goto-char (car range))
15164 ;; Unlike to `org--update-property-plist', we
15165 ;; handle the case where base values is found
15166 ;; after its extension. We also forbid standard
15167 ;; properties to be named as special properties.
15168 (while (re-search-forward org-property-re end t)
15169 (let* ((key (upcase (match-string-no-properties 2)))
15170 (extendp (string-match-p "\\+\\'" key))
15171 (key-base (if extendp (substring key 0 -1) key))
15172 (value (match-string-no-properties 3)))
15173 (cond
15174 ((member-ignore-case key-base org-special-properties))
15175 (extendp
15176 (setq props
15177 (org--update-property-plist key value props)))
15178 ((member key seen-base))
15179 (t (push key seen-base)
15180 (let ((p (assoc-string key props t)))
15181 (if p (setcdr p (concat value " " (cdr p)))
15182 (push (cons key value) props))))))))))))
15183 (unless (assoc "CATEGORY" props)
15184 (push (cons "CATEGORY" (org-get-category beg)) props)
15185 (when (string= specific "CATEGORY") (throw 'exit props)))
15186 ;; Return value.
15187 props)))))
15189 (defun org--property-local-values (property literal-nil)
15190 "Return value for PROPERTY in current entry.
15191 Value is a list whose car is the base value for PROPERTY and cdr
15192 a list of accumulated values. Return nil if neither is found in
15193 the entry. Also return nil when PROPERTY is set to \"nil\",
15194 unless LITERAL-NIL is non-nil."
15195 (let ((range (org-get-property-block)))
15196 (when range
15197 (goto-char (car range))
15198 (let* ((case-fold-search t)
15199 (end (cdr range))
15200 (value
15201 ;; Base value.
15202 (save-excursion
15203 (let ((v (and (re-search-forward
15204 (org-re-property property nil t) end t)
15205 (match-string-no-properties 3))))
15206 (list (if literal-nil v (org-not-nil v)))))))
15207 ;; Find additional values.
15208 (let* ((property+ (org-re-property (concat property "+") nil t)))
15209 (while (re-search-forward property+ end t)
15210 (push (match-string-no-properties 3) value)))
15211 ;; Return final values.
15212 (and (not (equal value '(nil))) (nreverse value))))))
15214 (defun org--property-global-value (property literal-nil)
15215 "Return value for PROPERTY in current buffer.
15216 Return value is a string. Return nil if property is not set
15217 globally. Also return nil when PROPERTY is set to \"nil\",
15218 unless LITERAL-NIL is non-nil."
15219 (let ((global
15220 (cdr (or (assoc-string property org-file-properties t)
15221 (assoc-string property org-global-properties t)
15222 (assoc-string property org-global-properties-fixed t)))))
15223 (if literal-nil global (org-not-nil global))))
15225 (defun org-entry-get (pom property &optional inherit literal-nil)
15226 "Get value of PROPERTY for entry or content at point-or-marker POM.
15228 If INHERIT is non-nil and the entry does not have the property,
15229 then also check higher levels of the hierarchy. If INHERIT is
15230 the symbol `selective', use inheritance only if the setting in
15231 `org-use-property-inheritance' selects PROPERTY for inheritance.
15233 If the property is present but empty, the return value is the
15234 empty string. If the property is not present at all, nil is
15235 returned. In any other case, return the value as a string.
15236 Search is case-insensitive.
15238 If LITERAL-NIL is set, return the string value \"nil\" as
15239 a string, do not interpret it as the list atom nil. This is used
15240 for inheritance when a \"nil\" value can supersede a non-nil
15241 value higher up the hierarchy."
15242 (org-with-point-at pom
15243 (cond
15244 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15245 ;; We need a special property. Use `org-entry-properties' to
15246 ;; retrieve it, but specify the wanted property.
15247 (cdr (assoc-string property (org-entry-properties nil property))))
15248 ((and inherit
15249 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15250 (org-entry-get-with-inheritance property literal-nil))
15252 (let* ((local (org--property-local-values property literal-nil))
15253 (value (and local (mapconcat #'identity (delq nil local) " "))))
15254 (if literal-nil value (org-not-nil value)))))))
15256 (defun org-property-or-variable-value (var &optional inherit)
15257 "Check if there is a property fixing the value of VAR.
15258 If yes, return this value. If not, return the current value of the variable."
15259 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15260 (if (and prop (stringp prop) (string-match "\\S-" prop))
15261 (read prop)
15262 (symbol-value var))))
15264 (defun org-entry-delete (pom property)
15265 "Delete PROPERTY from entry at point-or-marker POM.
15266 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15267 non-nil when a property was removed."
15268 (org-with-point-at pom
15269 (pcase (org-get-property-block)
15270 (`(,begin . ,origin)
15271 (let* ((end (copy-marker origin))
15272 (re (org-re-property
15273 (concat (regexp-quote property) "\\+?") t t)))
15274 (goto-char begin)
15275 (while (re-search-forward re end t)
15276 (delete-region (match-beginning 0) (line-beginning-position 2)))
15277 ;; If drawer is empty, remove it altogether.
15278 (when (= begin end)
15279 (delete-region (line-beginning-position 0)
15280 (line-beginning-position 2)))
15281 ;; Return non-nil if some property was removed.
15282 (prog1 (/= end origin) (set-marker end nil))))
15283 (_ nil))))
15285 ;; Multi-values properties are properties that contain multiple values
15286 ;; These values are assumed to be single words, separated by whitespace.
15287 (defun org-entry-add-to-multivalued-property (pom property value)
15288 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15289 (let* ((old (org-entry-get pom property))
15290 (values (and old (split-string old))))
15291 (setq value (org-entry-protect-space value))
15292 (unless (member value values)
15293 (setq values (append values (list value)))
15294 (org-entry-put pom property (mapconcat #'identity values " ")))))
15296 (defun org-entry-remove-from-multivalued-property (pom property value)
15297 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15298 (let* ((old (org-entry-get pom property))
15299 (values (and old (split-string old))))
15300 (setq value (org-entry-protect-space value))
15301 (when (member value values)
15302 (setq values (delete value values))
15303 (org-entry-put pom property (mapconcat #'identity values " ")))))
15305 (defun org-entry-member-in-multivalued-property (pom property value)
15306 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15307 (let* ((old (org-entry-get pom property))
15308 (values (and old (split-string old))))
15309 (setq value (org-entry-protect-space value))
15310 (member value values)))
15312 (defun org-entry-get-multivalued-property (pom property)
15313 "Return a list of values in a multivalued property."
15314 (let* ((value (org-entry-get pom property))
15315 (values (and value (split-string value))))
15316 (mapcar #'org-entry-restore-space values)))
15318 (defun org-entry-put-multivalued-property (pom property &rest values)
15319 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15320 VALUES should be a list of strings. Spaces will be protected."
15321 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15322 (let* ((value (org-entry-get pom property))
15323 (values (and value (split-string value))))
15324 (mapcar #'org-entry-restore-space values)))
15326 (defun org-entry-protect-space (s)
15327 "Protect spaces and newline in string S."
15328 (while (string-match " " s)
15329 (setq s (replace-match "%20" t t s)))
15330 (while (string-match "\n" s)
15331 (setq s (replace-match "%0A" t t s)))
15334 (defun org-entry-restore-space (s)
15335 "Restore spaces and newline in string S."
15336 (while (string-match "%20" s)
15337 (setq s (replace-match " " t t s)))
15338 (while (string-match "%0A" s)
15339 (setq s (replace-match "\n" t t s)))
15342 (defvar org-entry-property-inherited-from (make-marker)
15343 "Marker pointing to the entry from where a property was inherited.
15344 Each call to `org-entry-get-with-inheritance' will set this marker to the
15345 location of the entry where the inheritance search matched. If there was
15346 no match, the marker will point nowhere.
15347 Note that also `org-entry-get' calls this function, if the INHERIT flag
15348 is set.")
15350 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15351 "Get PROPERTY of entry or content at point, search higher levels if needed.
15352 The search will stop at the first ancestor which has the property defined.
15353 If the value found is \"nil\", return nil to show that the property
15354 should be considered as undefined (this is the meaning of nil here).
15355 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15356 (move-marker org-entry-property-inherited-from nil)
15357 (org-with-wide-buffer
15358 (let (value)
15359 (catch 'exit
15360 (while t
15361 (let ((v (org--property-local-values property literal-nil)))
15362 (when v
15363 (setq value
15364 (concat (mapconcat #'identity (delq nil v) " ")
15365 (and value " ")
15366 value)))
15367 (cond
15368 ((car v)
15369 (org-back-to-heading t)
15370 (move-marker org-entry-property-inherited-from (point))
15371 (throw 'exit nil))
15372 ((org-up-heading-safe))
15374 (let ((global (org--property-global-value property literal-nil)))
15375 (cond ((not global))
15376 (value (setq value (concat global " " value)))
15377 (t (setq value global))))
15378 (throw 'exit nil))))))
15379 (if literal-nil value (org-not-nil value)))))
15381 (defvar org-property-changed-functions nil
15382 "Hook called when the value of a property has changed.
15383 Each hook function should accept two arguments, the name of the property
15384 and the new value.")
15386 (defun org-entry-put (pom property value)
15387 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15389 If the value is nil, it is converted to the empty string. If it
15390 is not a string, an error is raised. Also raise an error on
15391 invalid property names.
15393 PROPERTY can be any regular property (see
15394 `org-special-properties'). It can also be \"TODO\",
15395 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15397 For the last two properties, VALUE may have any of the special
15398 values \"earlier\" and \"later\". The function then increases or
15399 decreases scheduled or deadline date by one day."
15400 (cond ((null value) (setq value ""))
15401 ((not (stringp value)) (error "Properties values should be strings"))
15402 ((not (org--valid-property-p property))
15403 (user-error "Invalid property name: \"%s\"" property)))
15404 (org-with-point-at pom
15405 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15406 (org-back-to-heading t)
15407 (org-with-limited-levels (org-back-to-heading t)))
15408 (let ((beg (point)))
15409 (cond
15410 ((equal property "TODO")
15411 (cond ((not (org-string-nw-p value)) (setq value 'none))
15412 ((not (member value org-todo-keywords-1))
15413 (user-error "\"%s\" is not a valid TODO state" value)))
15414 (org-todo value)
15415 (org-align-tags))
15416 ((equal property "PRIORITY")
15417 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15418 (org-align-tags))
15419 ((equal property "SCHEDULED")
15420 (forward-line)
15421 (if (and (looking-at-p org-planning-line-re)
15422 (re-search-forward
15423 org-scheduled-time-regexp (line-end-position) t))
15424 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15425 ((string= value "later") (org-timestamp-change 1 'day))
15426 ((string= value "") (org-schedule '(4)))
15427 (t (org-schedule nil value)))
15428 (if (member value '("earlier" "later" ""))
15429 (call-interactively #'org-schedule)
15430 (org-schedule nil value))))
15431 ((equal property "DEADLINE")
15432 (forward-line)
15433 (if (and (looking-at-p org-planning-line-re)
15434 (re-search-forward
15435 org-deadline-time-regexp (line-end-position) t))
15436 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15437 ((string= value "later") (org-timestamp-change 1 'day))
15438 ((string= value "") (org-deadline '(4)))
15439 (t (org-deadline nil value)))
15440 (if (member value '("earlier" "later" ""))
15441 (call-interactively #'org-deadline)
15442 (org-deadline nil value))))
15443 ((member property org-special-properties)
15444 (error "The %s property cannot be set with `org-entry-put'" property))
15446 (let* ((range (org-get-property-block beg 'force))
15447 (end (cdr range))
15448 (case-fold-search t))
15449 (goto-char (car range))
15450 (if (re-search-forward (org-re-property property nil t) end t)
15451 (progn (delete-region (match-beginning 0) (match-end 0))
15452 (goto-char (match-beginning 0)))
15453 (goto-char end)
15454 (insert "\n")
15455 (backward-char))
15456 (insert ":" property ":")
15457 (when value (insert " " value))
15458 (org-indent-line)))))
15459 (run-hook-with-args 'org-property-changed-functions property value)))
15461 (defun org-buffer-property-keys (&optional specials defaults columns)
15462 "Get all property keys in the current buffer.
15464 When SPECIALS is non-nil, also list the special properties that
15465 reflect things like tags and TODO state.
15467 When DEFAULTS is non-nil, also include properties that has
15468 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15469 DESCRIPTION, LOCATION, and LOGGING and others.
15471 When COLUMNS in non-nil, also include property names given in
15472 COLUMN formats in the current buffer."
15473 (let ((case-fold-search t)
15474 (props (append
15475 (and specials org-special-properties)
15476 (and defaults (cons org-effort-property org-default-properties))
15477 nil)))
15478 (org-with-wide-buffer
15479 (goto-char (point-min))
15480 (while (re-search-forward org-property-start-re nil t)
15481 (catch :skip
15482 (let ((range (org-get-property-block)))
15483 (unless range (throw :skip nil))
15484 (goto-char (car range))
15485 (let ((begin (car range))
15486 (end (cdr range)))
15487 ;; Make sure that found property block is not located
15488 ;; before current point, as it would generate an infloop.
15489 ;; It can happen, for example, in the following
15490 ;; situation:
15492 ;; * Headline
15493 ;; :PROPERTIES:
15494 ;; ...
15495 ;; :END:
15496 ;; *************** Inlinetask
15497 ;; #+BEGIN_EXAMPLE
15498 ;; :PROPERTIES:
15499 ;; #+END_EXAMPLE
15501 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15502 (while (< (point) end)
15503 (let ((p (progn (looking-at org-property-re)
15504 (match-string-no-properties 2))))
15505 ;; Only add true property name, not extension symbol.
15506 (push (if (not (string-match-p "\\+\\'" p)) p
15507 (substring p 0 -1))
15508 props))
15509 (forward-line))))
15510 (outline-next-heading)))
15511 (when columns
15512 (goto-char (point-min))
15513 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15514 (let ((element (org-element-at-point)))
15515 (when (memq (org-element-type element) '(keyword node-property))
15516 (let ((value (org-element-property :value element))
15517 (start 0))
15518 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15519 \\(?:{[^}]+}\\)?"
15520 value start)
15521 (setq start (match-end 0))
15522 (let ((p (match-string-no-properties 1 value)))
15523 (unless (member-ignore-case p org-special-properties)
15524 (push p props))))))))))
15525 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15527 (defun org-property-values (key)
15528 "List all non-nil values of property KEY in current buffer."
15529 (org-with-wide-buffer
15530 (goto-char (point-min))
15531 (let ((case-fold-search t)
15532 (re (org-re-property key))
15533 values)
15534 (while (re-search-forward re nil t)
15535 (push (org-entry-get (point) key) values))
15536 (delete-dups values))))
15538 (defun org-insert-property-drawer ()
15539 "Insert a property drawer into the current entry."
15540 (org-with-wide-buffer
15541 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15542 (org-back-to-heading t)
15543 (org-with-limited-levels (org-back-to-heading t)))
15544 (forward-line)
15545 (when (looking-at-p org-planning-line-re) (forward-line))
15546 (unless (looking-at-p org-property-drawer-re)
15547 ;; Make sure we start editing a line from current entry, not from
15548 ;; next one. It prevents extending text properties or overlays
15549 ;; belonging to the latter.
15550 (when (bolp) (backward-char))
15551 (let ((begin (1+ (point)))
15552 (inhibit-read-only t))
15553 (insert "\n:PROPERTIES:\n:END:")
15554 (when (eobp) (insert "\n"))
15555 (org-indent-region begin (point))))))
15557 (defun org-insert-drawer (&optional arg drawer)
15558 "Insert a drawer at point.
15560 When optional argument ARG is non-nil, insert a property drawer.
15562 Optional argument DRAWER, when non-nil, is a string representing
15563 drawer's name. Otherwise, the user is prompted for a name.
15565 If a region is active, insert the drawer around that region
15566 instead.
15568 Point is left between drawer's boundaries."
15569 (interactive "P")
15570 (let* ((drawer (if arg "PROPERTIES"
15571 (or drawer (read-from-minibuffer "Drawer: ")))))
15572 (cond
15573 ;; With C-u, fall back on `org-insert-property-drawer'
15574 (arg (org-insert-property-drawer))
15575 ;; Check validity of suggested drawer's name.
15576 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15577 (user-error "Invalid drawer name"))
15578 ;; With an active region, insert a drawer at point.
15579 ((not (org-region-active-p))
15580 (progn
15581 (unless (bolp) (insert "\n"))
15582 (insert (format ":%s:\n\n:END:\n" drawer))
15583 (forward-line -2)))
15584 ;; Otherwise, insert the drawer at point
15586 (let ((rbeg (region-beginning))
15587 (rend (copy-marker (region-end))))
15588 (unwind-protect
15589 (progn
15590 (goto-char rbeg)
15591 (beginning-of-line)
15592 (when (save-excursion
15593 (re-search-forward org-outline-regexp-bol rend t))
15594 (user-error "Drawers cannot contain headlines"))
15595 ;; Position point at the beginning of the first
15596 ;; non-blank line in region. Insert drawer's opening
15597 ;; there, then indent it.
15598 (org-skip-whitespace)
15599 (beginning-of-line)
15600 (insert ":" drawer ":\n")
15601 (forward-line -1)
15602 (indent-for-tab-command)
15603 ;; Move point to the beginning of the first blank line
15604 ;; after the last non-blank line in region. Insert
15605 ;; drawer's closing, then indent it.
15606 (goto-char rend)
15607 (skip-chars-backward " \r\t\n")
15608 (insert "\n:END:")
15609 (deactivate-mark t)
15610 (indent-for-tab-command)
15611 (unless (eolp) (insert "\n")))
15612 ;; Clear marker, whatever the outcome of insertion is.
15613 (set-marker rend nil)))))))
15615 (defvar org-property-set-functions-alist nil
15616 "Property set function alist.
15617 Each entry should have the following format:
15619 (PROPERTY . READ-FUNCTION)
15621 The read function will be called with the same argument as
15622 `org-completing-read'.")
15624 (defun org-set-property-function (property)
15625 "Get the function that should be used to set PROPERTY.
15626 This is computed according to `org-property-set-functions-alist'."
15627 (or (cdr (assoc property org-property-set-functions-alist))
15628 'org-completing-read))
15630 (defun org-read-property-value (property &optional pom)
15631 "Read value for PROPERTY, as a string.
15632 When optional argument POM is non-nil, completion uses additional
15633 information, i.e., allowed or existing values at point or marker
15634 POM."
15635 (let* ((completion-ignore-case t)
15636 (allowed
15637 (or (org-property-get-allowed-values nil property 'table)
15638 (and pom (org-property-get-allowed-values pom property 'table))))
15639 (current (org-entry-get nil property))
15640 (prompt (format "%s value%s: "
15641 property
15642 (if (org-string-nw-p current)
15643 (format " [%s]" current)
15644 "")))
15645 (set-function (org-set-property-function property)))
15646 (org-trim
15647 (if allowed
15648 (funcall set-function
15649 prompt allowed nil
15650 (not (get-text-property 0 'org-unrestricted (caar allowed))))
15651 (let ((all (mapcar #'list
15652 (append (org-property-values property)
15653 (and pom
15654 (org-with-point-at pom
15655 (org-property-values property)))))))
15656 (funcall set-function prompt all nil nil "" nil current))))))
15658 (defvar org-last-set-property nil)
15659 (defvar org-last-set-property-value nil)
15660 (defun org-read-property-name ()
15661 "Read a property name."
15662 (let ((completion-ignore-case t)
15663 (default-prop (or (and (org-at-property-p)
15664 (match-string-no-properties 2))
15665 org-last-set-property)))
15666 (org-completing-read
15667 (concat "Property"
15668 (if default-prop (concat " [" default-prop "]") "")
15669 ": ")
15670 (mapcar #'list (org-buffer-property-keys nil t t))
15671 nil nil nil nil default-prop)))
15673 (defun org-set-property-and-value (use-last)
15674 "Allow to set [PROPERTY]: [value] direction from prompt.
15675 When use-default, don't even ask, just use the last
15676 \"[PROPERTY]: [value]\" string from the history."
15677 (interactive "P")
15678 (let* ((completion-ignore-case t)
15679 (pv (or (and use-last org-last-set-property-value)
15680 (org-completing-read
15681 "Enter a \"[Property]: [value]\" pair: "
15682 nil nil nil nil nil
15683 org-last-set-property-value)))
15684 prop val)
15685 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15686 (setq prop (match-string 1 pv)
15687 val (match-string 2 pv))
15688 (org-set-property prop val))))
15690 (defun org-set-property (property value)
15691 "In the current entry, set PROPERTY to VALUE.
15693 When called interactively, this will prompt for a property name, offering
15694 completion on existing and default properties. And then it will prompt
15695 for a value, offering completion either on allowed values (via an inherited
15696 xxx_ALL property) or on existing values in other instances of this property
15697 in the current file.
15699 Throw an error when trying to set a property with an invalid name."
15700 (interactive (list nil nil))
15701 (let ((property (or property (org-read-property-name))))
15702 ;; `org-entry-put' also makes the following check, but this one
15703 ;; avoids polluting `org-last-set-property' and
15704 ;; `org-last-set-property-value' needlessly.
15705 (unless (org--valid-property-p property)
15706 (user-error "Invalid property name: \"%s\"" property))
15707 (let ((value (or value (org-read-property-value property)))
15708 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15709 (setq org-last-set-property property)
15710 (setq org-last-set-property-value (concat property ": " value))
15711 ;; Possibly postprocess the inserted value:
15712 (when fn (setq value (funcall fn value)))
15713 (unless (equal (org-entry-get nil property) value)
15714 (org-entry-put nil property value)))))
15716 (defun org-find-property (property &optional value)
15717 "Find first entry in buffer that sets PROPERTY.
15719 When optional argument VALUE is non-nil, only consider an entry
15720 if it contains PROPERTY set to this value. If PROPERTY should be
15721 explicitly set to nil, use string \"nil\" for VALUE.
15723 Return position where the entry begins, or nil if there is no
15724 such entry. If narrowing is in effect, only search the visible
15725 part of the buffer."
15726 (save-excursion
15727 (goto-char (point-min))
15728 (let ((case-fold-search t)
15729 (re (org-re-property property nil (not value) value)))
15730 (catch 'exit
15731 (while (re-search-forward re nil t)
15732 (when (if value (org-at-property-p)
15733 (org-entry-get (point) property nil t))
15734 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15736 (defun org-delete-property (property)
15737 "In the current entry, delete PROPERTY."
15738 (interactive
15739 (let* ((completion-ignore-case t)
15740 (cat (org-entry-get (point) "CATEGORY"))
15741 (props0 (org-entry-properties nil 'standard))
15742 (props (if cat props0
15743 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15744 (prop (if (< 1 (length props))
15745 (completing-read "Property: " props nil t)
15746 (caar props))))
15747 (list prop)))
15748 (if (not property)
15749 (message "No property to delete in this entry")
15750 (org-entry-delete nil property)
15751 (message "Property \"%s\" deleted" property)))
15753 (defun org-delete-property-globally (property)
15754 "Remove PROPERTY globally, from all entries.
15755 This function ignores narrowing, if any."
15756 (interactive
15757 (let* ((completion-ignore-case t)
15758 (prop (completing-read
15759 "Globally remove property: "
15760 (mapcar #'list (org-buffer-property-keys)))))
15761 (list prop)))
15762 (org-with-wide-buffer
15763 (goto-char (point-min))
15764 (let ((count 0)
15765 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15766 (while (re-search-forward re nil t)
15767 (when (org-entry-delete (point) property) (cl-incf count)))
15768 (message "Property \"%s\" removed from %d entries" property count))))
15770 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15772 (defun org-compute-property-at-point ()
15773 "Compute the property at point.
15774 This looks for an enclosing column format, extracts the operator and
15775 then applies it to the property in the column format's scope."
15776 (interactive)
15777 (unless (org-at-property-p)
15778 (user-error "Not at a property"))
15779 (let ((prop (match-string-no-properties 2)))
15780 (org-columns-get-format-and-top-level)
15781 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15782 (user-error "No operator defined for property %s" prop))
15783 (org-columns-compute prop)))
15785 (defvar org-property-allowed-value-functions nil
15786 "Hook for functions supplying allowed values for a specific property.
15787 The functions must take a single argument, the name of the property, and
15788 return a flat list of allowed values. If \":ETC\" is one of
15789 the values, this means that these values are intended as defaults for
15790 completion, but that other values should be allowed too.
15791 The functions must return nil if they are not responsible for this
15792 property.")
15794 (defun org-property-get-allowed-values (pom property &optional table)
15795 "Get allowed values for the property PROPERTY.
15796 When TABLE is non-nil, return an alist that can directly be used for
15797 completion."
15798 (let (vals)
15799 (cond
15800 ((equal property "TODO")
15801 (setq vals (org-with-point-at pom
15802 (append org-todo-keywords-1 '("")))))
15803 ((equal property "PRIORITY")
15804 (let ((n org-lowest-priority))
15805 (while (>= n org-highest-priority)
15806 (push (char-to-string n) vals)
15807 (setq n (1- n)))))
15808 ((equal property "CATEGORY"))
15809 ((member property org-special-properties))
15810 ((setq vals (run-hook-with-args-until-success
15811 'org-property-allowed-value-functions property)))
15813 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15814 (when (and vals (string-match "\\S-" vals))
15815 (setq vals (car (read-from-string (concat "(" vals ")"))))
15816 (setq vals (mapcar (lambda (x)
15817 (cond ((stringp x) x)
15818 ((numberp x) (number-to-string x))
15819 ((symbolp x) (symbol-name x))
15820 (t "???")))
15821 vals)))))
15822 (when (member ":ETC" vals)
15823 (setq vals (remove ":ETC" vals))
15824 (org-add-props (car vals) '(org-unrestricted t)))
15825 (if table (mapcar 'list vals) vals)))
15827 (defun org-property-previous-allowed-value (&optional _previous)
15828 "Switch to the next allowed value for this property."
15829 (interactive)
15830 (org-property-next-allowed-value t))
15832 (defun org-property-next-allowed-value (&optional previous)
15833 "Switch to the next allowed value for this property."
15834 (interactive)
15835 (unless (org-at-property-p)
15836 (user-error "Not at a property"))
15837 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15838 (key (match-string 2))
15839 (value (match-string 3))
15840 (allowed (or (org-property-get-allowed-values (point) key)
15841 (and (member value '("[ ]" "[-]" "[X]"))
15842 '("[ ]" "[X]"))))
15843 (heading (save-match-data (nth 4 (org-heading-components))))
15844 nval)
15845 (unless allowed
15846 (user-error "Allowed values for this property have not been defined"))
15847 (when previous (setq allowed (reverse allowed)))
15848 (when (member value allowed)
15849 (setq nval (car (cdr (member value allowed)))))
15850 (setq nval (or nval (car allowed)))
15851 (when (equal nval value)
15852 (user-error "Only one allowed value for this property"))
15853 (org-at-property-p)
15854 (replace-match (concat " :" key ": " nval) t t)
15855 (org-indent-line)
15856 (beginning-of-line 1)
15857 (skip-chars-forward " \t")
15858 (when (equal prop org-effort-property)
15859 (org-refresh-property
15860 '((effort . identity)
15861 (effort-minutes . org-duration-to-minutes))
15862 nval)
15863 (when (string= org-clock-current-task heading)
15864 (setq org-clock-effort nval)
15865 (org-clock-update-mode-line)))
15866 (run-hook-with-args 'org-property-changed-functions key nval)))
15868 (defun org-find-olp (path &optional this-buffer)
15869 "Return a marker pointing to the entry at outline path OLP.
15870 If anything goes wrong, throw an error.
15871 You can wrap this call to catch the error like this:
15873 (condition-case msg
15874 (org-mobile-locate-entry (match-string 4))
15875 (error (nth 1 msg)))
15877 The return value will then be either a string with the error message,
15878 or a marker if everything is OK.
15880 If THIS-BUFFER is set, the outline path does not contain a file,
15881 only headings."
15882 (let* ((file (if this-buffer buffer-file-name (pop path)))
15883 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15884 (level 1)
15885 (lmin 1)
15886 (lmax 1)
15887 end found flevel)
15888 (unless buffer (error "File not found :%s" file))
15889 (with-current-buffer buffer
15890 (unless (derived-mode-p 'org-mode)
15891 (error "Buffer %s needs to be in Org mode" buffer))
15892 (org-with-wide-buffer
15893 (goto-char (point-min))
15894 (dolist (heading path)
15895 (let ((re (format org-complex-heading-regexp-format
15896 (regexp-quote heading)))
15897 (cnt 0))
15898 (while (re-search-forward re end t)
15899 (setq level (- (match-end 1) (match-beginning 1)))
15900 (when (and (>= level lmin) (<= level lmax))
15901 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15902 (when (= cnt 0)
15903 (error "Heading not found on level %d: %s" lmax heading))
15904 (when (> cnt 1)
15905 (error "Heading not unique on level %d: %s" lmax heading))
15906 (goto-char found)
15907 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15908 (setq end (save-excursion (org-end-of-subtree t t)))))
15909 (when (org-at-heading-p)
15910 (point-marker))))))
15912 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15913 "Find node HEADING in BUFFER.
15914 Return a marker to the heading if it was found, or nil if not.
15915 If POS-ONLY is set, return just the position instead of a marker.
15917 The heading text must match exact, but it may have a TODO keyword,
15918 a priority cookie and tags in the standard locations."
15919 (with-current-buffer (or buffer (current-buffer))
15920 (org-with-wide-buffer
15921 (goto-char (point-min))
15922 (let (case-fold-search)
15923 (when (re-search-forward
15924 (format org-complex-heading-regexp-format
15925 (regexp-quote heading)) nil t)
15926 (if pos-only
15927 (match-beginning 0)
15928 (move-marker (make-marker) (match-beginning 0))))))))
15930 (defun org-find-exact-heading-in-directory (heading &optional dir)
15931 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15932 When the target headline is found, return a marker to this location."
15933 (let ((files (directory-files (or dir default-directory)
15934 t "\\`[^.#].*\\.org\\'"))
15935 visiting m buffer)
15936 (catch 'found
15937 (dolist (file files)
15938 (message "trying %s" file)
15939 (setq visiting (org-find-base-buffer-visiting file))
15940 (setq buffer (or visiting (find-file-noselect file)))
15941 (setq m (org-find-exact-headline-in-buffer
15942 heading buffer))
15943 (when (and (not m) (not visiting)) (kill-buffer buffer))
15944 (and m (throw 'found m))))))
15946 (defun org-find-entry-with-id (ident)
15947 "Locate the entry that contains the ID property with exact value IDENT.
15948 IDENT can be a string, a symbol or a number, this function will search for
15949 the string representation of it.
15950 Return the position where this entry starts, or nil if there is no such entry."
15951 (interactive "sID: ")
15952 (let ((id (cond
15953 ((stringp ident) ident)
15954 ((symbolp ident) (symbol-name ident))
15955 ((numberp ident) (number-to-string ident))
15956 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15957 (org-with-wide-buffer (org-find-property "ID" id))))
15959 ;;;; Timestamps
15961 (defvar org-last-changed-timestamp nil)
15962 (defvar org-last-inserted-timestamp nil
15963 "The last time stamp inserted with `org-insert-time-stamp'.")
15965 (defun org-time-stamp (arg &optional inactive)
15966 "Prompt for a date/time and insert a time stamp.
15968 If the user specifies a time like HH:MM or if this command is
15969 called with at least one prefix argument, the time stamp contains
15970 the date and the time. Otherwise, only the date is included.
15972 All parts of a date not specified by the user are filled in from
15973 the timestamp at point, if any, or the current date/time
15974 otherwise.
15976 If there is already a timestamp at the cursor, it is replaced.
15978 With two universal prefix arguments, insert an active timestamp
15979 with the current time without prompting the user.
15981 When called from lisp, the timestamp is inactive if INACTIVE is
15982 non-nil."
15983 (interactive "P")
15984 (let* ((ts (cond
15985 ((org-at-date-range-p t)
15986 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15987 ((org-at-timestamp-p 'lax) (match-string 0))))
15988 ;; Default time is either the timestamp at point or today.
15989 ;; When entering a range, only the range start is considered.
15990 (default-time (if (not ts) (current-time)
15991 (apply #'encode-time (org-parse-time-string ts))))
15992 (default-input (and ts (org-get-compact-tod ts)))
15993 (repeater (and ts
15994 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15995 (match-string 0 ts)))
15996 org-time-was-given
15997 org-end-time-was-given
15998 (time
15999 (and (if (equal arg '(16)) (current-time)
16000 ;; Preserve `this-command' and `last-command'.
16001 (let ((this-command this-command)
16002 (last-command last-command))
16003 (org-read-date
16004 arg 'totime nil nil default-time default-input
16005 inactive))))))
16006 (cond
16007 ((and ts
16008 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16009 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16010 (insert "--")
16011 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16013 ;; Make sure we're on a timestamp. When in the middle of a date
16014 ;; range, move arbitrarily to range end.
16015 (unless (org-at-timestamp-p 'lax)
16016 (skip-chars-forward "-")
16017 (org-at-timestamp-p 'lax))
16018 (replace-match "")
16019 (setq org-last-changed-timestamp
16020 (org-insert-time-stamp
16021 time (or org-time-was-given arg)
16022 inactive nil nil (list org-end-time-was-given)))
16023 (when repeater
16024 (backward-char)
16025 (insert " " repeater)
16026 (setq org-last-changed-timestamp
16027 (concat (substring org-last-inserted-timestamp 0 -1)
16028 " " repeater ">")))
16029 (message "Timestamp updated"))
16030 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16031 (t (org-insert-time-stamp
16032 time (or org-time-was-given arg) inactive nil nil
16033 (list org-end-time-was-given))))))
16035 ;; FIXME: can we use this for something else, like computing time differences?
16036 (defun org-get-compact-tod (s)
16037 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16038 (let* ((t1 (match-string 1 s))
16039 (h1 (string-to-number (match-string 2 s)))
16040 (m1 (string-to-number (match-string 3 s)))
16041 (t2 (and (match-end 4) (match-string 5 s)))
16042 (h2 (and t2 (string-to-number (match-string 6 s))))
16043 (m2 (and t2 (string-to-number (match-string 7 s))))
16044 dh dm)
16045 (if (not t2)
16047 (setq dh (- h2 h1) dm (- m2 m1))
16048 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16049 (concat t1 "+" (number-to-string dh)
16050 (and (/= 0 dm) (format ":%02d" dm)))))))
16052 (defun org-time-stamp-inactive (&optional arg)
16053 "Insert an inactive time stamp.
16055 An inactive time stamp is enclosed in square brackets instead of angle
16056 brackets. It is inactive in the sense that it does not trigger agenda entries,
16057 does not link to the calendar and cannot be changed with the S-cursor keys.
16058 So these are more for recording a certain time/date.
16060 If the user specifies a time like HH:MM or if this command is called with
16061 at least one prefix argument, the time stamp contains the date and the time.
16062 Otherwise, only the date is included.
16064 When called with two universal prefix arguments, insert an active time stamp
16065 with the current time without prompting the user."
16066 (interactive "P")
16067 (org-time-stamp arg 'inactive))
16069 (defvar org-date-ovl (make-overlay 1 1))
16070 (overlay-put org-date-ovl 'face 'org-date-selected)
16071 (delete-overlay org-date-ovl)
16073 (defvar org-ans1) ; dynamically scoped parameter
16074 (defvar org-ans2) ; dynamically scoped parameter
16076 (defvar org-plain-time-of-day-regexp) ; defined below
16078 (defvar org-overriding-default-time nil) ; dynamically scoped
16079 (defvar org-read-date-overlay nil)
16080 (defvar org-dcst nil) ; dynamically scoped
16081 (defvar org-read-date-history nil)
16082 (defvar org-read-date-final-answer nil)
16083 (defvar org-read-date-analyze-futurep nil)
16084 (defvar org-read-date-analyze-forced-year nil)
16085 (defvar org-read-date-inactive)
16087 (defvar org-read-date-minibuffer-local-map
16088 (let* ((map (make-sparse-keymap)))
16089 (set-keymap-parent map minibuffer-local-map)
16090 (org-defkey map (kbd ".")
16091 (lambda () (interactive)
16092 ;; Are we at the beginning of the prompt?
16093 (if (looking-back "^[^:]+: "
16094 (let ((inhibit-field-text-motion t))
16095 (line-beginning-position)))
16096 (org-eval-in-calendar '(calendar-goto-today))
16097 (insert "."))))
16098 (org-defkey map (kbd "C-.")
16099 (lambda () (interactive)
16100 (org-eval-in-calendar '(calendar-goto-today))))
16101 (org-defkey map (kbd "M-S-<left>")
16102 (lambda () (interactive)
16103 (org-eval-in-calendar '(calendar-backward-month 1))))
16104 (org-defkey map (kbd "ESC S-<left>")
16105 (lambda () (interactive)
16106 (org-eval-in-calendar '(calendar-backward-month 1))))
16107 (org-defkey map (kbd "M-S-<right>")
16108 (lambda () (interactive)
16109 (org-eval-in-calendar '(calendar-forward-month 1))))
16110 (org-defkey map (kbd "ESC S-<right>")
16111 (lambda () (interactive)
16112 (org-eval-in-calendar '(calendar-forward-month 1))))
16113 (org-defkey map (kbd "M-S-<up>")
16114 (lambda () (interactive)
16115 (org-eval-in-calendar '(calendar-backward-year 1))))
16116 (org-defkey map (kbd "ESC S-<up>")
16117 (lambda () (interactive)
16118 (org-eval-in-calendar '(calendar-backward-year 1))))
16119 (org-defkey map (kbd "M-S-<down>")
16120 (lambda () (interactive)
16121 (org-eval-in-calendar '(calendar-forward-year 1))))
16122 (org-defkey map (kbd "ESC S-<down>")
16123 (lambda () (interactive)
16124 (org-eval-in-calendar '(calendar-forward-year 1))))
16125 (org-defkey map (kbd "S-<up>")
16126 (lambda () (interactive)
16127 (org-eval-in-calendar '(calendar-backward-week 1))))
16128 (org-defkey map (kbd "S-<down>")
16129 (lambda () (interactive)
16130 (org-eval-in-calendar '(calendar-forward-week 1))))
16131 (org-defkey map (kbd "S-<left>")
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(calendar-backward-day 1))))
16134 (org-defkey map (kbd "S-<right>")
16135 (lambda () (interactive)
16136 (org-eval-in-calendar '(calendar-forward-day 1))))
16137 (org-defkey map (kbd "!")
16138 (lambda () (interactive)
16139 (org-eval-in-calendar '(diary-view-entries))
16140 (message "")))
16141 (org-defkey map (kbd ">")
16142 (lambda () (interactive)
16143 (org-eval-in-calendar '(calendar-scroll-left 1))))
16144 (org-defkey map (kbd "<")
16145 (lambda () (interactive)
16146 (org-eval-in-calendar '(calendar-scroll-right 1))))
16147 (org-defkey map (kbd "C-v")
16148 (lambda () (interactive)
16149 (org-eval-in-calendar
16150 '(calendar-scroll-left-three-months 1))))
16151 (org-defkey map (kbd "M-v")
16152 (lambda () (interactive)
16153 (org-eval-in-calendar
16154 '(calendar-scroll-right-three-months 1))))
16155 map)
16156 "Keymap for minibuffer commands when using `org-read-date'.")
16158 (defvar org-def)
16159 (defvar org-defdecode)
16160 (defvar org-with-time)
16162 (defvar calendar-setup) ; Dynamically scoped.
16163 (defun org-read-date (&optional with-time to-time from-string prompt
16164 default-time default-input inactive)
16165 "Read a date, possibly a time, and make things smooth for the user.
16166 The prompt will suggest to enter an ISO date, but you can also enter anything
16167 which will at least partially be understood by `parse-time-string'.
16168 Unrecognized parts of the date will default to the current day, month, year,
16169 hour and minute. If this command is called to replace a timestamp at point,
16170 or to enter the second timestamp of a range, the default time is taken
16171 from the existing stamp. Furthermore, the command prefers the future,
16172 so if you are giving a date where the year is not given, and the day-month
16173 combination is already past in the current year, it will assume you
16174 mean next year. For details, see the manual. A few examples:
16176 3-2-5 --> 2003-02-05
16177 feb 15 --> currentyear-02-15
16178 2/15 --> currentyear-02-15
16179 sep 12 9 --> 2009-09-12
16180 12:45 --> today 12:45
16181 22 sept 0:34 --> currentyear-09-22 0:34
16182 12 --> currentyear-currentmonth-12
16183 Fri --> nearest Friday after today
16184 -Tue --> last Tuesday
16185 etc.
16187 Furthermore you can specify a relative date by giving, as the *first* thing
16188 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16189 change in days weeks, months, years.
16190 With a single plus or minus, the date is relative to today. With a double
16191 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16192 +4d --> four days from today
16193 +4 --> same as above
16194 +2w --> two weeks from today
16195 ++5 --> five days from default date
16197 The function understands only English month and weekday abbreviations.
16199 While prompting, a calendar is popped up - you can also select the
16200 date with the mouse (button 1). The calendar shows a period of three
16201 months. To scroll it to other months, use the keys `>' and `<'.
16202 If you don't like the calendar, turn it off with
16203 (setq org-read-date-popup-calendar nil)
16205 With optional argument TO-TIME, the date will immediately be converted
16206 to an internal time.
16207 With an optional argument WITH-TIME, the prompt will suggest to
16208 also insert a time. Note that when WITH-TIME is not set, you can
16209 still enter a time, and this function will inform the calling routine
16210 about this change. The calling routine may then choose to change the
16211 format used to insert the time stamp into the buffer to include the time.
16212 With optional argument FROM-STRING, read from this string instead from
16213 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16214 the time/date that is used for everything that is not specified by the
16215 user."
16216 (require 'parse-time)
16217 (let* ((org-with-time with-time)
16218 (org-time-stamp-rounding-minutes
16219 (if (equal org-with-time '(16))
16220 '(0 0)
16221 org-time-stamp-rounding-minutes))
16222 (org-dcst org-display-custom-times)
16223 (ct (org-current-time))
16224 (org-def (or org-overriding-default-time default-time ct))
16225 (org-defdecode (decode-time org-def))
16226 (cur-frame (selected-frame))
16227 (mouse-autoselect-window nil) ; Don't let the mouse jump
16228 (calendar-setup
16229 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16230 (calendar-move-hook nil)
16231 (calendar-view-diary-initially-flag nil)
16232 (calendar-view-holidays-initially-flag nil)
16233 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16234 ;; Rationalize `org-def' and `org-defdecode', if required.
16235 (when (< (nth 2 org-defdecode) org-extend-today-until)
16236 (setf (nth 2 org-defdecode) -1)
16237 (setf (nth 1 org-defdecode) 59)
16238 (setq org-def (apply #'encode-time org-defdecode))
16239 (setq org-defdecode (decode-time org-def)))
16240 (let* ((timestr (format-time-string
16241 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16242 org-def))
16243 (prompt (concat (if prompt (concat prompt " ") "")
16244 (format "Date+time [%s]: " timestr))))
16245 (cond
16246 (from-string (setq ans from-string))
16247 (org-read-date-popup-calendar
16248 (save-excursion
16249 (save-window-excursion
16250 (calendar)
16251 (when (eq calendar-setup 'calendar-only)
16252 (setq cal-frame
16253 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16254 (select-frame cal-frame))
16255 (org-eval-in-calendar '(setq cursor-type nil) t)
16256 (unwind-protect
16257 (progn
16258 (calendar-forward-day (- (time-to-days org-def)
16259 (calendar-absolute-from-gregorian
16260 (calendar-current-date))))
16261 (org-eval-in-calendar nil t)
16262 (let* ((old-map (current-local-map))
16263 (map (copy-keymap calendar-mode-map))
16264 (minibuffer-local-map
16265 (copy-keymap org-read-date-minibuffer-local-map)))
16266 (org-defkey map (kbd "RET") 'org-calendar-select)
16267 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16268 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16269 (unwind-protect
16270 (progn
16271 (use-local-map map)
16272 (setq org-read-date-inactive inactive)
16273 (add-hook 'post-command-hook 'org-read-date-display)
16274 (setq org-ans0
16275 (read-string prompt
16276 default-input
16277 'org-read-date-history
16278 nil))
16279 ;; org-ans0: from prompt
16280 ;; org-ans1: from mouse click
16281 ;; org-ans2: from calendar motion
16282 (setq ans
16283 (concat org-ans0 " " (or org-ans1 org-ans2))))
16284 (remove-hook 'post-command-hook 'org-read-date-display)
16285 (use-local-map old-map)
16286 (when org-read-date-overlay
16287 (delete-overlay org-read-date-overlay)
16288 (setq org-read-date-overlay nil)))))
16289 (bury-buffer "*Calendar*")
16290 (when cal-frame
16291 (delete-frame cal-frame)
16292 (select-frame-set-input-focus cur-frame))))))
16294 (t ; Naked prompt only
16295 (unwind-protect
16296 (setq ans (read-string prompt default-input
16297 'org-read-date-history timestr))
16298 (when org-read-date-overlay
16299 (delete-overlay org-read-date-overlay)
16300 (setq org-read-date-overlay nil))))))
16302 (setq final (org-read-date-analyze ans org-def org-defdecode))
16304 (when org-read-date-analyze-forced-year
16305 (message "Year was forced into %s"
16306 (if org-read-date-force-compatible-dates
16307 "compatible range (1970-2037)"
16308 "range representable on this machine"))
16309 (ding))
16311 ;; One round trip to get rid of 34th of August and stuff like that....
16312 (setq final (decode-time (apply 'encode-time final)))
16314 (setq org-read-date-final-answer ans)
16316 (if to-time
16317 (apply 'encode-time final)
16318 (if (and (boundp 'org-time-was-given) org-time-was-given)
16319 (format "%04d-%02d-%02d %02d:%02d"
16320 (nth 5 final) (nth 4 final) (nth 3 final)
16321 (nth 2 final) (nth 1 final))
16322 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16324 (defun org-read-date-display ()
16325 "Display the current date prompt interpretation in the minibuffer."
16326 (when org-read-date-display-live
16327 (when org-read-date-overlay
16328 (delete-overlay org-read-date-overlay))
16329 (when (minibufferp (current-buffer))
16330 (save-excursion
16331 (end-of-line 1)
16332 (while (not (equal (buffer-substring
16333 (max (point-min) (- (point) 4)) (point))
16334 " "))
16335 (insert " ")))
16336 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16337 " " (or org-ans1 org-ans2)))
16338 (org-end-time-was-given nil)
16339 (f (org-read-date-analyze ans org-def org-defdecode))
16340 (fmts (if org-dcst
16341 org-time-stamp-custom-formats
16342 org-time-stamp-formats))
16343 (fmt (if (or org-with-time
16344 (and (boundp 'org-time-was-given) org-time-was-given))
16345 (cdr fmts)
16346 (car fmts)))
16347 (txt (format-time-string fmt (apply 'encode-time f)))
16348 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16349 (txt (concat "=> " txt)))
16350 (when (and org-end-time-was-given
16351 (string-match org-plain-time-of-day-regexp txt))
16352 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16353 org-end-time-was-given
16354 (substring txt (match-end 0)))))
16355 (when org-read-date-analyze-futurep
16356 (setq txt (concat txt " (=>F)")))
16357 (setq org-read-date-overlay
16358 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16359 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16361 (defun org-read-date-analyze (ans def defdecode)
16362 "Analyze the combined answer of the date prompt."
16363 ;; FIXME: cleanup and comment
16364 ;; Pass `current-time' result to `decode-time' (instead of calling
16365 ;; without arguments) so that only `current-time' has to be
16366 ;; overridden in tests.
16367 (let ((org-def def)
16368 (org-defdecode defdecode)
16369 (nowdecode (decode-time (current-time)))
16370 delta deltan deltaw deltadef year month day
16371 hour minute second wday pm h2 m2 tl wday1
16372 iso-year iso-weekday iso-week iso-date futurep kill-year)
16373 (setq org-read-date-analyze-futurep nil
16374 org-read-date-analyze-forced-year nil)
16375 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16376 (setq ans "+0"))
16378 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16379 (setq ans (replace-match "" t t ans)
16380 deltan (car delta)
16381 deltaw (nth 1 delta)
16382 deltadef (nth 2 delta)))
16384 ;; Check if there is an iso week date in there. If yes, store the
16385 ;; info and postpone interpreting it until the rest of the parsing
16386 ;; is done.
16387 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16388 (setq iso-year (when (match-end 1)
16389 (org-small-year-to-year
16390 (string-to-number (match-string 1 ans))))
16391 iso-weekday (when (match-end 3)
16392 (string-to-number (match-string 3 ans)))
16393 iso-week (string-to-number (match-string 2 ans)))
16394 (setq ans (replace-match "" t t ans)))
16396 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16397 (when (string-match
16398 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16399 (setq year (if (match-end 2)
16400 (string-to-number (match-string 2 ans))
16401 (progn (setq kill-year t)
16402 (string-to-number (format-time-string "%Y"))))
16403 month (string-to-number (match-string 3 ans))
16404 day (string-to-number (match-string 4 ans)))
16405 (setq year (org-small-year-to-year year))
16406 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16407 t nil ans)))
16409 ;; Help matching dotted european dates
16410 (when (string-match
16411 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16412 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16413 (setq kill-year t)
16414 (string-to-number (format-time-string "%Y")))
16415 day (string-to-number (match-string 1 ans))
16416 month (string-to-number (match-string 2 ans))
16417 ans (replace-match (format "%04d-%02d-%02d" year month day)
16418 t nil ans)))
16420 ;; Help matching american dates, like 5/30 or 5/30/7
16421 (when (string-match
16422 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16423 (setq year (if (match-end 4)
16424 (string-to-number (match-string 4 ans))
16425 (progn (setq kill-year t)
16426 (string-to-number (format-time-string "%Y"))))
16427 month (string-to-number (match-string 1 ans))
16428 day (string-to-number (match-string 2 ans)))
16429 (setq year (org-small-year-to-year year))
16430 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16431 t nil ans)))
16432 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16433 ;; If there is a time with am/pm, and *no* time without it, we convert
16434 ;; so that matching will be successful.
16435 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16436 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16437 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16438 (setq hour (string-to-number (match-string 1 ans))
16439 minute (if (match-end 3)
16440 (string-to-number (match-string 3 ans))
16442 pm (equal ?p
16443 (string-to-char (downcase (match-string 4 ans)))))
16444 (if (and (= hour 12) (not pm))
16445 (setq hour 0)
16446 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16447 (setq ans (replace-match (format "%02d:%02d" hour minute)
16448 t t ans))))
16450 ;; Check if a time range is given as a duration
16451 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16452 (setq hour (string-to-number (match-string 1 ans))
16453 h2 (+ hour (string-to-number (match-string 3 ans)))
16454 minute (string-to-number (match-string 2 ans))
16455 m2 (+ minute (if (match-end 5) (string-to-number
16456 (match-string 5 ans))0)))
16457 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16458 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16459 t t ans)))
16461 ;; Check if there is a time range
16462 (when (boundp 'org-end-time-was-given)
16463 (setq org-time-was-given nil)
16464 (when (and (string-match org-plain-time-of-day-regexp ans)
16465 (match-end 8))
16466 (setq org-end-time-was-given (match-string 8 ans))
16467 (setq ans (concat (substring ans 0 (match-beginning 7))
16468 (substring ans (match-end 7))))))
16470 (setq tl (parse-time-string ans)
16471 day (or (nth 3 tl) (nth 3 org-defdecode))
16472 month
16473 (cond ((nth 4 tl))
16474 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16475 ;; Day was specified. Make sure DAY+MONTH
16476 ;; combination happens in the future.
16477 ((nth 3 tl)
16478 (setq futurep t)
16479 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16480 (nth 4 nowdecode)))
16481 (t (nth 4 org-defdecode)))
16482 year
16483 (cond ((and (not kill-year) (nth 5 tl)))
16484 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16485 ;; Month was guessed in the future and is at least
16486 ;; equal to NOWDECODE's. Fix year accordingly.
16487 (futurep
16488 (if (or (> month (nth 4 nowdecode))
16489 (>= day (nth 3 nowdecode)))
16490 (nth 5 nowdecode)
16491 (1+ (nth 5 nowdecode))))
16492 ;; Month was specified. Make sure MONTH+YEAR
16493 ;; combination happens in the future.
16494 ((nth 4 tl)
16495 (setq futurep t)
16496 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16497 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16498 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16499 (t (nth 5 nowdecode))))
16500 (t (nth 5 org-defdecode)))
16501 hour (or (nth 2 tl) (nth 2 org-defdecode))
16502 minute (or (nth 1 tl) (nth 1 org-defdecode))
16503 second (or (nth 0 tl) 0)
16504 wday (nth 6 tl))
16506 (when (and (eq org-read-date-prefer-future 'time)
16507 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16508 (equal day (nth 3 nowdecode))
16509 (equal month (nth 4 nowdecode))
16510 (equal year (nth 5 nowdecode))
16511 (nth 2 tl)
16512 (or (< (nth 2 tl) (nth 2 nowdecode))
16513 (and (= (nth 2 tl) (nth 2 nowdecode))
16514 (nth 1 tl)
16515 (< (nth 1 tl) (nth 1 nowdecode)))))
16516 (setq day (1+ day)
16517 futurep t))
16519 ;; Special date definitions below
16520 (cond
16521 (iso-week
16522 ;; There was an iso week
16523 (require 'cal-iso)
16524 (setq futurep nil)
16525 (setq year (or iso-year year)
16526 day (or iso-weekday wday 1)
16527 wday nil ; to make sure that the trigger below does not match
16528 iso-date (calendar-gregorian-from-absolute
16529 (calendar-iso-to-absolute
16530 (list iso-week day year))))
16531 ; FIXME: Should we also push ISO weeks into the future?
16532 ; (when (and org-read-date-prefer-future
16533 ; (not iso-year)
16534 ; (< (calendar-absolute-from-gregorian iso-date)
16535 ; (time-to-days (current-time))))
16536 ; (setq year (1+ year)
16537 ; iso-date (calendar-gregorian-from-absolute
16538 ; (calendar-iso-to-absolute
16539 ; (list iso-week day year)))))
16540 (setq month (car iso-date)
16541 year (nth 2 iso-date)
16542 day (nth 1 iso-date)))
16543 (deltan
16544 (setq futurep nil)
16545 (unless deltadef
16546 ;; Pass `current-time' result to `decode-time' (instead of
16547 ;; calling without arguments) so that only `current-time' has
16548 ;; to be overridden in tests.
16549 (let ((now (decode-time (current-time))))
16550 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16551 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16552 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16553 ((equal deltaw "m") (setq month (+ month deltan)))
16554 ((equal deltaw "y") (setq year (+ year deltan)))))
16555 ((and wday (not (nth 3 tl)))
16556 ;; Weekday was given, but no day, so pick that day in the week
16557 ;; on or after the derived date.
16558 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16559 (unless (equal wday wday1)
16560 (setq day (+ day (% (- wday wday1 -7) 7))))))
16561 (when (and (boundp 'org-time-was-given)
16562 (nth 2 tl))
16563 (setq org-time-was-given t))
16564 (when (< year 100) (setq year (+ 2000 year)))
16565 ;; Check of the date is representable
16566 (if org-read-date-force-compatible-dates
16567 (progn
16568 (when (< year 1970)
16569 (setq year 1970 org-read-date-analyze-forced-year t))
16570 (when (> year 2037)
16571 (setq year 2037 org-read-date-analyze-forced-year t)))
16572 (condition-case nil
16573 (ignore (encode-time second minute hour day month year))
16574 (error
16575 (setq year (nth 5 org-defdecode))
16576 (setq org-read-date-analyze-forced-year t))))
16577 (setq org-read-date-analyze-futurep futurep)
16578 (list second minute hour day month year)))
16580 (defvar parse-time-weekdays)
16581 (defun org-read-date-get-relative (s today default)
16582 "Check string S for special relative date string.
16583 TODAY and DEFAULT are internal times, for today and for a default.
16584 Return shift list (N what def-flag)
16585 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16586 N is the number of WHATs to shift.
16587 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16588 the DEFAULT date rather than TODAY."
16589 (require 'parse-time)
16590 (when (and
16591 (string-match
16592 (concat
16593 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16594 "\\([0-9]+\\)?"
16595 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16596 "\\([ \t]\\|$\\)") s)
16597 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16598 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16599 (string-to-char (substring (match-string 1 s) -1))
16600 ?+))
16601 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16602 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16603 (what (if (match-end 3) (match-string 3 s) "d"))
16604 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16605 (date (if rel default today))
16606 (wday (nth 6 (decode-time date)))
16607 delta)
16608 (if wday1
16609 (progn
16610 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16611 (when (= delta 0) (setq delta 7))
16612 (when (= dir ?-)
16613 (setq delta (- delta 7))
16614 (when (= delta 0) (setq delta -7)))
16615 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16616 (list delta "d" rel))
16617 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16619 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16620 "Turn a user-specified date into the internal representation.
16621 The internal representation needed by the calendar is (month day year).
16622 This is a wrapper to handle the brain-dead convention in calendar that
16623 user function argument order change dependent on argument order."
16624 (pcase calendar-date-style
16625 (`american (list arg1 arg2 arg3))
16626 (`european (list arg2 arg1 arg3))
16627 (`iso (list arg2 arg3 arg1))))
16629 (defun org-eval-in-calendar (form &optional keepdate)
16630 "Eval FORM in the calendar window and return to current window.
16631 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16632 (let ((sf (selected-frame))
16633 (sw (selected-window)))
16634 (select-window (get-buffer-window "*Calendar*" t))
16635 (eval form)
16636 (when (and (not keepdate) (calendar-cursor-to-date))
16637 (let* ((date (calendar-cursor-to-date))
16638 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16639 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16640 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16641 (select-window sw)
16642 (select-frame-set-input-focus sf)))
16644 (defun org-calendar-select ()
16645 "Return to `org-read-date' with the date currently selected.
16646 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16647 (interactive)
16648 (when (calendar-cursor-to-date)
16649 (let* ((date (calendar-cursor-to-date))
16650 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16651 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16652 (when (active-minibuffer-window) (exit-minibuffer))))
16654 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16655 "Insert a date stamp for the date given by the internal TIME.
16656 See `format-time-string' for the format of TIME.
16657 WITH-HM means use the stamp format that includes the time of the day.
16658 INACTIVE means use square brackets instead of angular ones, so that the
16659 stamp will not contribute to the agenda.
16660 PRE and POST are optional strings to be inserted before and after the
16661 stamp.
16662 The command returns the inserted time stamp."
16663 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16664 stamp)
16665 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16666 (insert-before-markers (or pre ""))
16667 (when (listp extra)
16668 (setq extra (car extra))
16669 (if (and (stringp extra)
16670 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16671 (setq extra (format "-%02d:%02d"
16672 (string-to-number (match-string 1 extra))
16673 (string-to-number (match-string 2 extra))))
16674 (setq extra nil)))
16675 (when extra
16676 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16677 (insert-before-markers (setq stamp (format-time-string fmt time)))
16678 (insert-before-markers (or post ""))
16679 (setq org-last-inserted-timestamp stamp)))
16681 (defun org-toggle-time-stamp-overlays ()
16682 "Toggle the use of custom time stamp formats."
16683 (interactive)
16684 (setq org-display-custom-times (not org-display-custom-times))
16685 (unless org-display-custom-times
16686 (let ((p (point-min)) (bmp (buffer-modified-p)))
16687 (while (setq p (next-single-property-change p 'display))
16688 (when (and (get-text-property p 'display)
16689 (eq (get-text-property p 'face) 'org-date))
16690 (remove-text-properties
16691 p (setq p (next-single-property-change p 'display))
16692 '(display t))))
16693 (set-buffer-modified-p bmp)))
16694 (org-restart-font-lock)
16695 (setq org-table-may-need-update t)
16696 (if org-display-custom-times
16697 (message "Time stamps are overlaid with custom format")
16698 (message "Time stamp overlays removed")))
16700 (defun org-display-custom-time (beg end)
16701 "Overlay modified time stamp format over timestamp between BEG and END."
16702 (let* ((ts (buffer-substring beg end))
16703 t1 with-hm tf time str (off 0))
16704 (save-match-data
16705 (setq t1 (org-parse-time-string ts t))
16706 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16707 (setq off (- (match-end 0) (match-beginning 0)))))
16708 (setq end (- end off))
16709 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16710 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16711 time (org-fix-decoded-time t1)
16712 str (org-add-props
16713 (format-time-string
16714 (substring tf 1 -1) (apply 'encode-time time))
16715 nil 'mouse-face 'highlight))
16716 (put-text-property beg end 'display str)))
16718 (defun org-fix-decoded-time (time)
16719 "Set 0 instead of nil for the first 6 elements of time.
16720 Don't touch the rest."
16721 (let ((n 0))
16722 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16724 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16725 "Difference between TIMESTAMP-STRING and now in days.
16726 If SECONDS is non-nil, return the difference in seconds."
16727 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16728 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16729 (funcall fdiff (current-time)))))
16731 (defun org-deadline-close-p (timestamp-string &optional ndays)
16732 "Is the time in TIMESTAMP-STRING close to the current date?"
16733 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16734 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16735 (not (org-entry-is-done-p))))
16737 (defun org-get-wdays (ts &optional delay zero-delay)
16738 "Get the deadline lead time appropriate for timestring TS.
16739 When DELAY is non-nil, get the delay time for scheduled items
16740 instead of the deadline lead time. When ZERO-DELAY is non-nil
16741 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16742 don't try to find the delay cookie in the scheduled timestamp."
16743 (let ((tv (if delay org-scheduled-delay-days
16744 org-deadline-warning-days)))
16745 (cond
16746 ((or (and delay (< tv 0))
16747 (and delay zero-delay (<= tv 0))
16748 (and (not delay) (<= tv 0)))
16749 ;; Enforce this value no matter what
16750 (- tv))
16751 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16752 ;; lead time is specified.
16753 (floor (* (string-to-number (match-string 1 ts))
16754 (cdr (assoc (match-string 2 ts)
16755 '(("d" . 1) ("w" . 7)
16756 ("m" . 30.4) ("y" . 365.25)
16757 ("h" . 0.041667)))))))
16758 ;; go for the default.
16759 (t tv))))
16761 (defun org-calendar-select-mouse (ev)
16762 "Return to `org-read-date' with the date currently selected.
16763 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16764 (interactive "e")
16765 (mouse-set-point ev)
16766 (when (calendar-cursor-to-date)
16767 (let* ((date (calendar-cursor-to-date))
16768 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16769 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16770 (when (active-minibuffer-window) (exit-minibuffer))))
16772 (defun org-check-deadlines (ndays)
16773 "Check if there are any deadlines due or past due.
16774 A deadline is considered due if it happens within `org-deadline-warning-days'
16775 days from today's date. If the deadline appears in an entry marked DONE,
16776 it is not shown. A numeric prefix argument NDAYS can be used to test that
16777 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16778 are shown."
16779 (interactive "P")
16780 (let* ((org-warn-days
16781 (cond
16782 ((equal ndays '(4)) 100000)
16783 (ndays (prefix-numeric-value ndays))
16784 (t (abs org-deadline-warning-days))))
16785 (case-fold-search nil)
16786 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16787 (callback
16788 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16789 (message "%d deadlines past-due or due within %d days"
16790 (org-occur regexp nil callback)
16791 org-warn-days)))
16793 (defsubst org-re-timestamp (type)
16794 "Return a regexp for timestamp TYPE.
16795 Allowed values for TYPE are:
16797 all: all timestamps
16798 active: only active timestamps (<...>)
16799 inactive: only inactive timestamps ([...])
16800 scheduled: only scheduled timestamps
16801 deadline: only deadline timestamps
16802 closed: only closed time-stamps
16804 When TYPE is nil, fall back on returning a regexp that matches
16805 both scheduled and deadline timestamps."
16806 (cl-case type
16807 (all org-ts-regexp-both)
16808 (active org-ts-regexp)
16809 (inactive org-ts-regexp-inactive)
16810 (scheduled org-scheduled-time-regexp)
16811 (deadline org-deadline-time-regexp)
16812 (closed org-closed-time-regexp)
16813 (otherwise
16814 (concat "\\<"
16815 (regexp-opt (list org-deadline-string org-scheduled-string))
16816 " *<\\([^>]+\\)>"))))
16818 (defun org-check-before-date (d)
16819 "Check if there are deadlines or scheduled entries before date D."
16820 (interactive (list (org-read-date)))
16821 (let* ((case-fold-search nil)
16822 (regexp (org-re-timestamp org-ts-type))
16823 (ts-type org-ts-type)
16824 (callback
16825 (lambda ()
16826 (let ((match (match-string 1)))
16827 (and (if (memq ts-type '(active inactive all))
16828 (eq (org-element-type (save-excursion
16829 (backward-char)
16830 (org-element-context)))
16831 'timestamp)
16832 (org-at-planning-p))
16833 (time-less-p
16834 (org-time-string-to-time match)
16835 (org-time-string-to-time d)))))))
16836 (message "%d entries before %s"
16837 (org-occur regexp nil callback)
16838 d)))
16840 (defun org-check-after-date (d)
16841 "Check if there are deadlines or scheduled entries after date D."
16842 (interactive (list (org-read-date)))
16843 (let* ((case-fold-search nil)
16844 (regexp (org-re-timestamp org-ts-type))
16845 (ts-type org-ts-type)
16846 (callback
16847 (lambda ()
16848 (let ((match (match-string 1)))
16849 (and (if (memq ts-type '(active inactive all))
16850 (eq (org-element-type (save-excursion
16851 (backward-char)
16852 (org-element-context)))
16853 'timestamp)
16854 (org-at-planning-p))
16855 (not (time-less-p
16856 (org-time-string-to-time match)
16857 (org-time-string-to-time d))))))))
16858 (message "%d entries after %s"
16859 (org-occur regexp nil callback)
16860 d)))
16862 (defun org-check-dates-range (start-date end-date)
16863 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16864 (interactive (list (org-read-date nil nil nil "Range starts")
16865 (org-read-date nil nil nil "Range end")))
16866 (let ((case-fold-search nil)
16867 (regexp (org-re-timestamp org-ts-type))
16868 (callback
16869 (let ((type org-ts-type))
16870 (lambda ()
16871 (let ((match (match-string 1)))
16872 (and
16873 (if (memq type '(active inactive all))
16874 (eq (org-element-type (save-excursion
16875 (backward-char)
16876 (org-element-context)))
16877 'timestamp)
16878 (org-at-planning-p))
16879 (not (time-less-p
16880 (org-time-string-to-time match)
16881 (org-time-string-to-time start-date)))
16882 (time-less-p
16883 (org-time-string-to-time match)
16884 (org-time-string-to-time end-date))))))))
16885 (message "%d entries between %s and %s"
16886 (org-occur regexp nil callback) start-date end-date)))
16888 (defun org-evaluate-time-range (&optional to-buffer)
16889 "Evaluate a time range by computing the difference between start and end.
16890 Normally the result is just printed in the echo area, but with prefix arg
16891 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16892 If the time range is actually in a table, the result is inserted into the
16893 next column.
16894 For time difference computation, a year is assumed to be exactly 365
16895 days in order to avoid rounding problems."
16896 (interactive "P")
16898 (org-clock-update-time-maybe)
16899 (save-excursion
16900 (unless (org-at-date-range-p t)
16901 (goto-char (point-at-bol))
16902 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16903 (unless (org-at-date-range-p t)
16904 (user-error "Not at a time-stamp range, and none found in current line")))
16905 (let* ((ts1 (match-string 1))
16906 (ts2 (match-string 2))
16907 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16908 (match-end (match-end 0))
16909 (time1 (org-time-string-to-time ts1))
16910 (time2 (org-time-string-to-time ts2))
16911 (t1 (float-time time1))
16912 (t2 (float-time time2))
16913 (diff (abs (- t2 t1)))
16914 (negative (< (- t2 t1) 0))
16915 ;; (ys (floor (* 365 24 60 60)))
16916 (ds (* 24 60 60))
16917 (hs (* 60 60))
16918 (fy "%dy %dd %02d:%02d")
16919 (fy1 "%dy %dd")
16920 (fd "%dd %02d:%02d")
16921 (fd1 "%dd")
16922 (fh "%02d:%02d")
16923 y d h m align)
16924 (if havetime
16925 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16927 d (floor (/ diff ds)) diff (mod diff ds)
16928 h (floor (/ diff hs)) diff (mod diff hs)
16929 m (floor (/ diff 60)))
16930 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16932 d (floor (+ (/ diff ds) 0.5))
16933 h 0 m 0))
16934 (if (not to-buffer)
16935 (message "%s" (org-make-tdiff-string y d h m))
16936 (if (org-at-table-p)
16937 (progn
16938 (goto-char match-end)
16939 (setq align t)
16940 (and (looking-at " *|") (goto-char (match-end 0))))
16941 (goto-char match-end))
16942 (when (looking-at
16943 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16944 (replace-match ""))
16945 (when negative (insert " -"))
16946 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16947 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16948 (insert " " (format fh h m))))
16949 (when align (org-table-align))
16950 (message "Time difference inserted")))))
16952 (defun org-make-tdiff-string (y d h m)
16953 (let ((fmt "")
16954 (l nil))
16955 (when (> y 0)
16956 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16957 (push y l))
16958 (when (> d 0)
16959 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16960 (push d l))
16961 (when (> h 0)
16962 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16963 (push h l))
16964 (when (> m 0)
16965 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16966 (push m l))
16967 (apply 'format fmt (nreverse l))))
16969 (defun org-time-string-to-time (s)
16970 "Convert timestamp string S into internal time."
16971 (apply #'encode-time (org-parse-time-string s)))
16973 (defun org-time-string-to-seconds (s)
16974 "Convert a timestamp string S into a number of seconds."
16975 (float-time (org-time-string-to-time s)))
16977 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16979 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16980 "Convert time stamp S to an absolute day number.
16982 If DAYNR in non-nil, and there is a specifier for a cyclic time
16983 stamp, get the closest date to DAYNR. If PREFER is
16984 `past' (respectively `future') return a date past (respectively
16985 after) or equal to DAYNR.
16987 POS is the location of time stamp S, as a buffer position in
16988 BUFFER.
16990 Diary sexp timestamps are matched against DAYNR, when non-nil.
16991 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16992 signaled."
16993 (cond
16994 ((string-match "\\`%%\\((.*)\\)" s)
16995 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16996 ;; only able to match individual dates. If it fails, raise an
16997 ;; error.
16998 (if (and daynr
16999 (org-diary-sexp-entry
17000 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17001 daynr
17002 (signal 'org-diary-sexp-no-match (list s))))
17003 (daynr (org-closest-date s daynr prefer))
17004 (t (time-to-days
17005 (condition-case errdata
17006 (apply #'encode-time (org-parse-time-string s))
17007 (error (error "Bad timestamp `%s'%s\nError was: %s"
17009 (if (not (and buffer pos)) ""
17010 (format-message " at %d in buffer `%s'" pos buffer))
17011 (cdr errdata))))))))
17013 (defun org-days-to-iso-week (days)
17014 "Return the iso week number."
17015 (require 'cal-iso)
17016 (car (calendar-iso-from-absolute days)))
17018 (defun org-small-year-to-year (year)
17019 "Convert 2-digit years into 4-digit years.
17020 YEAR is expanded into one of the 30 next years, if possible, or
17021 into a past one. Any year larger than 99 is returned unchanged."
17022 (if (>= year 100) year
17023 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17024 (century (/ current 100))
17025 (offset (- year (% current 100))))
17026 (cond ((> offset 30) (+ (* (1- century) 100) year))
17027 ((> offset -70) (+ (* century 100) year))
17028 (t (+ (* (1+ century) 100) year))))))
17030 (defun org-time-from-absolute (d)
17031 "Return the time corresponding to date D.
17032 D may be an absolute day number, or a calendar-type list (month day year)."
17033 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17034 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17036 (defvar org-agenda-current-date)
17037 (defun org-calendar-holiday ()
17038 "List of holidays, for Diary display in Org mode."
17039 (require 'holidays)
17040 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17041 (and hl (mapconcat #'identity hl "; "))))
17043 (defun org-diary-sexp-entry (sexp entry d)
17044 "Process a SEXP diary ENTRY for date D."
17045 (require 'diary-lib)
17046 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17047 ;; dynamically.
17048 (let* ((sexp `(let ((entry ,entry)
17049 (date ',d))
17050 ,(car (read-from-string sexp))))
17051 (result (if calendar-debug-sexp (eval sexp)
17052 (condition-case nil
17053 (eval sexp)
17054 (error
17055 (beep)
17056 (message "Bad sexp at line %d in %s: %s"
17057 (org-current-line)
17058 (buffer-file-name) sexp)
17059 (sleep-for 2))))))
17060 (cond ((stringp result) (split-string result "; "))
17061 ((and (consp result)
17062 (not (consp (cdr result)))
17063 (stringp (cdr result))) (cdr result))
17064 ((and (consp result)
17065 (stringp (car result))) result)
17066 (result entry))))
17068 (defun org-diary-to-ical-string (frombuf)
17069 "Get iCalendar entries from diary entries in buffer FROMBUF.
17070 This uses the icalendar.el library."
17071 (let* ((tmpdir temporary-file-directory)
17072 (tmpfile (make-temp-name
17073 (expand-file-name "orgics" tmpdir)))
17074 buf rtn b e)
17075 (with-current-buffer frombuf
17076 (icalendar-export-region (point-min) (point-max) tmpfile)
17077 (setq buf (find-buffer-visiting tmpfile))
17078 (set-buffer buf)
17079 (goto-char (point-min))
17080 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17081 (setq b (match-beginning 0)))
17082 (goto-char (point-max))
17083 (when (re-search-backward "^END:VEVENT" nil t)
17084 (setq e (match-end 0)))
17085 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17086 (kill-buffer buf)
17087 (delete-file tmpfile)
17088 rtn))
17090 (defun org-closest-date (start current prefer)
17091 "Return closest date to CURRENT starting from START.
17093 CURRENT and START are both time stamps.
17095 When PREFER is `past', return a date that is either CURRENT or
17096 past. When PREFER is `future', return a date that is either
17097 CURRENT or future.
17099 Only time stamps with a repeater are modified. Any other time
17100 stamp stay unchanged. In any case, return value is an absolute
17101 day number."
17102 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17103 ;; No repeater. Do not shift time stamp.
17104 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17105 (let ((value (string-to-number (match-string 1 start)))
17106 (type (match-string 2 start)))
17107 (if (= 0 value)
17108 ;; Repeater with a 0-value is considered as void.
17109 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17110 (let* ((base (org-date-to-gregorian start))
17111 (target (org-date-to-gregorian current))
17112 (sday (calendar-absolute-from-gregorian base))
17113 (cday (calendar-absolute-from-gregorian target))
17114 n1 n2)
17115 ;; If START is already past CURRENT, just return START.
17116 (if (<= cday sday) sday
17117 ;; Compute closest date before (N1) and closest date past
17118 ;; (N2) CURRENT.
17119 (pcase type
17120 ("h"
17121 (let ((missing-hours
17122 (mod (+ (- (* 24 (- cday sday))
17123 (nth 2 (org-parse-time-string start)))
17124 org-extend-today-until)
17125 value)))
17126 (setf n1 (if (= missing-hours 0) cday
17127 (- cday (1+ (/ missing-hours 24)))))
17128 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17129 ((or "d" "w")
17130 (let ((value (if (equal type "w") (* 7 value) value)))
17131 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17132 (setf n2 (+ n1 value))))
17133 ("m"
17134 (let* ((add-months
17135 (lambda (d n)
17136 ;; Add N months to gregorian date D, i.e.,
17137 ;; a list (MONTH DAY YEAR). Return a valid
17138 ;; gregorian date.
17139 (let ((m (+ (nth 0 d) n)))
17140 (list (mod m 12)
17141 (nth 1 d)
17142 (+ (/ m 12) (nth 2 d))))))
17143 (months ; Complete months to TARGET.
17144 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17145 (- (nth 0 target) (nth 0 base))
17146 ;; If START's day is greater than
17147 ;; TARGET's, remove incomplete month.
17148 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17149 value)
17150 value))
17151 (before (funcall add-months base months)))
17152 (setf n1 (calendar-absolute-from-gregorian before))
17153 (setf n2
17154 (calendar-absolute-from-gregorian
17155 (funcall add-months before value)))))
17157 (let* ((d (nth 1 base))
17158 (m (nth 0 base))
17159 (y (nth 2 base))
17160 (years ; Complete years to TARGET.
17161 (* (/ (- (nth 2 target)
17163 ;; If START's month and day are
17164 ;; greater than TARGET's, remove
17165 ;; incomplete year.
17166 (if (or (> (nth 0 target) m)
17167 (and (= (nth 0 target) m)
17168 (> (nth 1 target) d)))
17171 value)
17172 value))
17173 (before (list m d (+ y years))))
17174 (setf n1 (calendar-absolute-from-gregorian before))
17175 (setf n2 (calendar-absolute-from-gregorian
17176 (list m d (+ (nth 2 before) value)))))))
17177 ;; Handle PREFER parameter, if any.
17178 (cond
17179 ((eq prefer 'past) (if (= cday n2) n2 n1))
17180 ((eq prefer 'future) (if (= cday n1) n1 n2))
17181 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17183 (defun org-date-to-gregorian (d)
17184 "Turn any specification of date D into a Gregorian date for the calendar."
17185 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17186 ((and (listp d) (= (length d) 3)) d)
17187 ((stringp d)
17188 (let ((d (org-parse-time-string d)))
17189 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17190 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17192 (defun org-timestamp-up (&optional arg)
17193 "Increase the date item at the cursor by one.
17194 If the cursor is on the year, change the year. If it is on the month,
17195 the day or the time, change that. If the cursor is on the enclosing
17196 bracket, change the timestamp type.
17197 With prefix ARG, change by that many units."
17198 (interactive "p")
17199 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17201 (defun org-timestamp-down (&optional arg)
17202 "Decrease the date item at the cursor by one.
17203 If the cursor is on the year, change the year. If it is on the month,
17204 the day or the time, change that. If the cursor is on the enclosing
17205 bracket, change the timestamp type.
17206 With prefix ARG, change by that many units."
17207 (interactive "p")
17208 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17210 (defun org-timestamp-up-day (&optional arg)
17211 "Increase the date in the time stamp by one day.
17212 With prefix ARG, change that many days."
17213 (interactive "p")
17214 (if (and (not (org-at-timestamp-p 'lax))
17215 (org-at-heading-p))
17216 (org-todo 'up)
17217 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17219 (defun org-timestamp-down-day (&optional arg)
17220 "Decrease the date in the time stamp by one day.
17221 With prefix ARG, change that many days."
17222 (interactive "p")
17223 (if (and (not (org-at-timestamp-p 'lax))
17224 (org-at-heading-p))
17225 (org-todo 'down)
17226 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17228 (defun org-at-timestamp-p (&optional extended)
17229 "Non-nil if point is inside a timestamp.
17231 By default, the function only consider syntactically valid active
17232 timestamps. However, the caller may have a broader definition
17233 for timestamps. As a consequence, optional argument EXTENDED can
17234 be set to the following values
17236 `inactive'
17238 Include also syntactically valid inactive timestamps.
17240 `agenda'
17242 Include timestamps allowed in Agenda, i.e., those in
17243 properties drawers, planning lines and clock lines.
17245 `lax'
17247 Ignore context. The function matches any part of the
17248 document looking like a timestamp. This includes comments,
17249 example blocks...
17251 For backward-compatibility with Org 9.0, every other non-nil
17252 value is equivalent to `inactive'.
17254 When at a timestamp, return the position of the point as a symbol
17255 among `bracket', `after', `year', `month', `hour', `minute',
17256 `day' or a number of character from the last know part of the
17257 time stamp.
17259 When matching, the match groups are the following:
17260 group 1: year
17261 group 2: month
17262 group 3: day number
17263 group 4: day name
17264 group 5: hours, if any
17265 group 6: minutes, if any"
17266 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17267 (pos (point))
17268 (match?
17269 (let ((boundaries (org-in-regexp regexp)))
17270 (save-match-data
17271 (cond ((null boundaries) nil)
17272 ((eq extended 'lax) t)
17274 (or (and (eq extended 'agenda)
17275 (or (org-at-planning-p)
17276 (org-at-property-p)
17277 (and (bound-and-true-p
17278 org-agenda-include-inactive-timestamps)
17279 (org-at-clock-log-p))))
17280 (eq 'timestamp
17281 (save-excursion
17282 (when (= pos (cdr boundaries)) (forward-char -1))
17283 (org-element-type (org-element-context)))))))))))
17284 (cond
17285 ((not match?) nil)
17286 ((= pos (match-beginning 0)) 'bracket)
17287 ;; Distinguish location right before the closing bracket from
17288 ;; right after it.
17289 ((= pos (1- (match-end 0))) 'bracket)
17290 ((= pos (match-end 0)) 'after)
17291 ((org-pos-in-match-range pos 2) 'year)
17292 ((org-pos-in-match-range pos 3) 'month)
17293 ((org-pos-in-match-range pos 7) 'hour)
17294 ((org-pos-in-match-range pos 8) 'minute)
17295 ((or (org-pos-in-match-range pos 4)
17296 (org-pos-in-match-range pos 5)) 'day)
17297 ((and (> pos (or (match-end 8) (match-end 5)))
17298 (< pos (match-end 0)))
17299 (- pos (or (match-end 8) (match-end 5))))
17300 (t 'day))))
17302 (defun org-toggle-timestamp-type ()
17303 "Toggle the type (<active> or [inactive]) of a time stamp."
17304 (interactive)
17305 (when (org-at-timestamp-p 'lax)
17306 (let ((beg (match-beginning 0)) (end (match-end 0))
17307 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17308 (save-excursion
17309 (goto-char beg)
17310 (while (re-search-forward "[][<>]" end t)
17311 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17312 t t)))
17313 (message "Timestamp is now %sactive"
17314 (if (equal (char-after beg) ?<) "" "in")))))
17316 (defun org-at-clock-log-p ()
17317 "Non-nil if point is on a clock log line."
17318 (and (org-match-line org-clock-line-re)
17319 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17321 (defvar org-clock-history) ; defined in org-clock.el
17322 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17323 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17324 "Change the date in the time stamp at point.
17325 The date will be changed by N times WHAT. WHAT can be `day', `month',
17326 `year', `minute', `second'. If WHAT is not given, the cursor position
17327 in the timestamp determines what will be changed.
17328 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17329 (let ((origin (point))
17330 (timestamp? (org-at-timestamp-p 'lax))
17331 origin-cat
17332 with-hm inactive
17333 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17334 extra rem
17335 ts time time0 fixnext clrgx)
17336 (unless timestamp? (user-error "Not at a timestamp"))
17337 (if (and (not what) (eq timestamp? 'bracket))
17338 (org-toggle-timestamp-type)
17339 ;; Point isn't on brackets. Remember the part of the time-stamp
17340 ;; the point was in. Indeed, size of time-stamps may change,
17341 ;; but point must be kept in the same category nonetheless.
17342 (setq origin-cat timestamp?)
17343 (when (and (not what) (not (eq timestamp? 'day))
17344 org-display-custom-times
17345 (get-text-property (point) 'display)
17346 (not (get-text-property (1- (point)) 'display)))
17347 (setq timestamp? 'day))
17348 (setq timestamp? (or what timestamp?)
17349 inactive (= (char-after (match-beginning 0)) ?\[)
17350 ts (match-string 0))
17351 (replace-match "")
17352 (when (string-match
17353 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17355 (setq extra (match-string 1 ts))
17356 (when suppress-tmp-delay
17357 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17358 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17359 (setq with-hm t))
17360 (setq time0 (org-parse-time-string ts))
17361 (when (and updown
17362 (eq timestamp? 'minute)
17363 (not current-prefix-arg))
17364 ;; This looks like s-up and s-down. Change by one rounding step.
17365 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17366 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17367 (setcar (cdr time0) (+ (nth 1 time0)
17368 (if (> n 0) (- rem) (- dm rem))))))
17369 (setq time
17370 (apply #'encode-time
17371 (or (car time0) 0)
17372 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17373 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17374 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17375 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17376 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17377 (nthcdr 6 time0)))
17378 (when (and (memq timestamp? '(hour minute))
17379 extra
17380 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17381 (setq extra (org-modify-ts-extra
17382 extra
17383 (if (eq timestamp? 'hour) 2 5)
17384 n dm)))
17385 (when (integerp timestamp?)
17386 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17387 (when (eq what 'calendar)
17388 (let ((cal-date (org-get-date-from-calendar)))
17389 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17390 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17391 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17392 (setcar time0 (or (car time0) 0))
17393 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17394 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17395 (setq time (apply 'encode-time time0))))
17396 ;; Insert the new time-stamp, and ensure point stays in the same
17397 ;; category as before (i.e. not after the last position in that
17398 ;; category).
17399 (let ((pos (point)))
17400 ;; Stay before inserted string. `save-excursion' is of no use.
17401 (setq org-last-changed-timestamp
17402 (org-insert-time-stamp time with-hm inactive nil nil extra))
17403 (goto-char pos))
17404 (save-match-data
17405 (looking-at org-ts-regexp3)
17406 (goto-char
17407 (pcase origin-cat
17408 ;; `day' category ends before `hour' if any, or at the end
17409 ;; of the day name.
17410 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17411 (`hour (min (match-end 7) origin))
17412 (`minute (min (1- (match-end 8)) origin))
17413 ((pred integerp) (min (1- (match-end 0)) origin))
17414 ;; Point was right after the time-stamp. However, the
17415 ;; time-stamp length might have changed, so refer to
17416 ;; (match-end 0) instead.
17417 (`after (match-end 0))
17418 ;; `year' and `month' have both fixed size: point couldn't
17419 ;; have moved into another part.
17420 (_ origin))))
17421 ;; Update clock if on a CLOCK line.
17422 (org-clock-update-time-maybe)
17423 ;; Maybe adjust the closest clock in `org-clock-history'
17424 (when org-clock-adjust-closest
17425 (if (not (and (org-at-clock-log-p)
17426 (< 1 (length (delq nil (mapcar 'marker-position
17427 org-clock-history))))))
17428 (message "No clock to adjust")
17429 (cond ((save-excursion ; fix previous clock?
17430 (re-search-backward org-ts-regexp0 nil t)
17431 (looking-back (concat org-clock-string " \\[")
17432 (line-beginning-position)))
17433 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17434 ((save-excursion ; fix next clock?
17435 (re-search-backward org-ts-regexp0 nil t)
17436 (looking-at (concat org-ts-regexp0 "\\] =>")))
17437 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17438 (save-window-excursion
17439 ;; Find closest clock to point, adjust the previous/next one in history
17440 (let* ((p (save-excursion (org-back-to-heading t)))
17441 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17442 (clfixnth
17443 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17444 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17445 (if (not clfixpos)
17446 (message "No clock to adjust")
17447 (save-excursion
17448 (org-goto-marker-or-bmk clfixpos)
17449 (org-show-subtree)
17450 (when (re-search-forward clrgx nil t)
17451 (goto-char (match-beginning 1))
17452 (let (org-clock-adjust-closest)
17453 (org-timestamp-change n timestamp? updown))
17454 (message "Clock adjusted in %s for heading: %s"
17455 (file-name-nondirectory (buffer-file-name))
17456 (org-get-heading t t)))))))))
17457 ;; Try to recenter the calendar window, if any.
17458 (when (and org-calendar-follow-timestamp-change
17459 (get-buffer-window "*Calendar*" t)
17460 (memq timestamp? '(day month year)))
17461 (org-recenter-calendar (time-to-days time))))))
17463 (defun org-modify-ts-extra (s pos n dm)
17464 "Change the different parts of the lead-time and repeat fields in timestamp."
17465 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17466 ng h m new rem)
17467 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17468 (cond
17469 ((or (org-pos-in-match-range pos 2)
17470 (org-pos-in-match-range pos 3))
17471 (setq m (string-to-number (match-string 3 s))
17472 h (string-to-number (match-string 2 s)))
17473 (if (org-pos-in-match-range pos 2)
17474 (setq h (+ h n))
17475 (setq n (* dm (with-no-warnings (cl-signum n))))
17476 (unless (= 0 (setq rem (% m dm)))
17477 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17478 (setq m (+ m n)))
17479 (when (< m 0) (setq m (+ m 60) h (1- h)))
17480 (when (> m 59) (setq m (- m 60) h (1+ h)))
17481 (setq h (mod h 24))
17482 (setq ng 1 new (format "-%02d:%02d" h m)))
17483 ((org-pos-in-match-range pos 6)
17484 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17485 ((org-pos-in-match-range pos 5)
17486 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17488 ((org-pos-in-match-range pos 9)
17489 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17490 ((org-pos-in-match-range pos 8)
17491 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17493 (when ng
17494 (setq s (concat
17495 (substring s 0 (match-beginning ng))
17497 (substring s (match-end ng))))))
17500 (defun org-recenter-calendar (d)
17501 "If the calendar is visible, recenter it to date D."
17502 (let ((cwin (get-buffer-window "*Calendar*" t)))
17503 (when cwin
17504 (let ((calendar-move-hook nil))
17505 (with-selected-window cwin
17506 (calendar-goto-date
17507 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17509 (defun org-goto-calendar (&optional arg)
17510 "Go to the Emacs calendar at the current date.
17511 If there is a time stamp in the current line, go to that date.
17512 A prefix ARG can be used to force the current date."
17513 (interactive "P")
17514 (let ((calendar-move-hook nil)
17515 (calendar-view-holidays-initially-flag nil)
17516 (calendar-view-diary-initially-flag nil)
17517 diff)
17518 (when (or (org-at-timestamp-p 'lax)
17519 (org-match-line (concat ".*" org-ts-regexp)))
17520 (let ((d1 (time-to-days (current-time)))
17521 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17522 (setq diff (- d2 d1))))
17523 (calendar)
17524 (calendar-goto-today)
17525 (when (and diff (not arg)) (calendar-forward-day diff))))
17527 (defun org-get-date-from-calendar ()
17528 "Return a list (month day year) of date at point in calendar."
17529 (with-current-buffer "*Calendar*"
17530 (save-match-data
17531 (calendar-cursor-to-date))))
17533 (defun org-date-from-calendar ()
17534 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17535 If there is already a time stamp at the cursor position, update it."
17536 (interactive)
17537 (if (org-at-timestamp-p 'lax)
17538 (org-timestamp-change 0 'calendar)
17539 (let ((cal-date (org-get-date-from-calendar)))
17540 (org-insert-time-stamp
17541 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17543 (defcustom org-image-actual-width t
17544 "Should we use the actual width of images when inlining them?
17546 When set to t, always use the image width.
17548 When set to a number, use imagemagick (when available) to set
17549 the image's width to this value.
17551 When set to a number in a list, try to get the width from any
17552 #+ATTR.* keyword if it matches a width specification like
17554 #+ATTR_HTML: :width 300px
17556 and fall back on that number if none is found.
17558 When set to nil, try to get the width from an #+ATTR.* keyword
17559 and fall back on the original width if none is found.
17561 This requires Emacs >= 24.1, build with imagemagick support."
17562 :group 'org-appearance
17563 :version "24.4"
17564 :package-version '(Org . "8.0")
17565 :type '(choice
17566 (const :tag "Use the image width" t)
17567 (integer :tag "Use a number of pixels")
17568 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17569 (const :tag "Use #+ATTR* or don't resize" nil)))
17571 (defcustom org-agenda-inhibit-startup nil
17572 "Inhibit startup when preparing agenda buffers.
17573 When this variable is t, the initialization of the Org agenda
17574 buffers is inhibited: e.g. the visibility state is not set, the
17575 tables are not re-aligned, etc."
17576 :type 'boolean
17577 :version "24.3"
17578 :group 'org-agenda)
17580 (defcustom org-agenda-ignore-properties nil
17581 "Avoid updating text properties when building the agenda.
17582 Properties are used to prepare buffers for effort estimates,
17583 appointments, statistics and subtree-local categories.
17584 If you don't use these in the agenda, you can add them to this
17585 list and agenda building will be a bit faster.
17586 The value is a list, with zero or more of the symbols `effort', `appt',
17587 `stats' or `category'."
17588 :type '(set :greedy t
17589 (const effort)
17590 (const appt)
17591 (const stats)
17592 (const category))
17593 :version "26.1"
17594 :package-version '(Org . "8.3")
17595 :group 'org-agenda)
17597 ;;;; Files
17599 (defun org-save-all-org-buffers ()
17600 "Save all Org buffers without user confirmation."
17601 (interactive)
17602 (message "Saving all Org buffers...")
17603 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17604 (when (featurep 'org-id) (org-id-locations-save))
17605 (message "Saving all Org buffers... done"))
17607 (defun org-revert-all-org-buffers ()
17608 "Revert all Org buffers.
17609 Prompt for confirmation when there are unsaved changes.
17610 Be sure you know what you are doing before letting this function
17611 overwrite your changes.
17613 This function is useful in a setup where one tracks Org files
17614 with a version control system, to revert on one machine after pulling
17615 changes from another. I believe the procedure must be like this:
17617 1. M-x org-save-all-org-buffers
17618 2. Pull changes from the other machine, resolve conflicts
17619 3. M-x org-revert-all-org-buffers"
17620 (interactive)
17621 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17622 (user-error "Abort"))
17623 (save-excursion
17624 (save-window-excursion
17625 (dolist (b (buffer-list))
17626 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17627 (with-current-buffer b buffer-file-name))
17628 (pop-to-buffer-same-window b)
17629 (revert-buffer t 'no-confirm)))
17630 (when (and (featurep 'org-id) org-id-track-globally)
17631 (org-id-locations-load)))))
17633 ;;;; Agenda files
17635 ;;;###autoload
17636 (defun org-switchb (&optional arg)
17637 "Switch between Org buffers.
17639 With `\\[universal-argument]' prefix, restrict available buffers to files.
17641 With `\\[universal-argument] \\[universal-argument]' \
17642 prefix, restrict available buffers to agenda files."
17643 (interactive "P")
17644 (let ((blist (org-buffer-list
17645 (cond ((equal arg '(4)) 'files)
17646 ((equal arg '(16)) 'agenda)))))
17647 (pop-to-buffer-same-window
17648 (completing-read "Org buffer: "
17649 (mapcar #'list (mapcar #'buffer-name blist))
17650 nil t))))
17652 (defun org-buffer-list (&optional predicate exclude-tmp)
17653 "Return a list of Org buffers.
17654 PREDICATE can be `export', `files' or `agenda'.
17656 export restrict the list to Export buffers.
17657 files restrict the list to buffers visiting Org files.
17658 agenda restrict the list to buffers visiting agenda files.
17660 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17661 (let* ((bfn nil)
17662 (agenda-files (and (eq predicate 'agenda)
17663 (mapcar 'file-truename (org-agenda-files t))))
17664 (filter
17665 (cond
17666 ((eq predicate 'files)
17667 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17668 ((eq predicate 'export)
17669 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17670 ((eq predicate 'agenda)
17671 (lambda (b)
17672 (with-current-buffer b
17673 (and (derived-mode-p 'org-mode)
17674 (setq bfn (buffer-file-name b))
17675 (member (file-truename bfn) agenda-files)))))
17676 (t (lambda (b) (with-current-buffer b
17677 (or (derived-mode-p 'org-mode)
17678 (string-match "\\*Org .*Export"
17679 (buffer-name b)))))))))
17680 (delq nil
17681 (mapcar
17682 (lambda(b)
17683 (if (and (funcall filter b)
17684 (or (not exclude-tmp)
17685 (not (string-match "tmp" (buffer-name b)))))
17687 nil))
17688 (buffer-list)))))
17690 (defun org-agenda-files (&optional unrestricted archives)
17691 "Get the list of agenda files.
17692 Optional UNRESTRICTED means return the full list even if a restriction
17693 is currently in place.
17694 When ARCHIVES is t, include all archive files that are really being
17695 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17696 `org-agenda-archives-mode' is t."
17697 (let ((files
17698 (cond
17699 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17700 ((stringp org-agenda-files) (org-read-agenda-file-list))
17701 ((listp org-agenda-files) org-agenda-files)
17702 (t (error "Invalid value of `org-agenda-files'")))))
17703 (setq files (apply 'append
17704 (mapcar (lambda (f)
17705 (if (file-directory-p f)
17706 (directory-files
17707 f t org-agenda-file-regexp)
17708 (list f)))
17709 files)))
17710 (when org-agenda-skip-unavailable-files
17711 (setq files (delq nil
17712 (mapcar (function
17713 (lambda (file)
17714 (and (file-readable-p file) file)))
17715 files))))
17716 (when (or (eq archives t)
17717 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17718 (setq files (org-add-archive-files files)))
17719 files))
17721 (defun org-agenda-file-p (&optional file)
17722 "Return non-nil, if FILE is an agenda file.
17723 If FILE is omitted, use the file associated with the current
17724 buffer."
17725 (let ((fname (or file (buffer-file-name))))
17726 (and fname
17727 (member (file-truename fname)
17728 (mapcar #'file-truename (org-agenda-files t))))))
17730 (defun org-edit-agenda-file-list ()
17731 "Edit the list of agenda files.
17732 Depending on setup, this either uses customize to edit the variable
17733 `org-agenda-files', or it visits the file that is holding the list. In the
17734 latter case, the buffer is set up in a way that saving it automatically kills
17735 the buffer and restores the previous window configuration."
17736 (interactive)
17737 (if (stringp org-agenda-files)
17738 (let ((cw (current-window-configuration)))
17739 (find-file org-agenda-files)
17740 (setq-local org-window-configuration cw)
17741 (add-hook 'after-save-hook
17742 (lambda ()
17743 (set-window-configuration
17744 (prog1 org-window-configuration
17745 (kill-buffer (current-buffer))))
17746 (org-install-agenda-files-menu)
17747 (message "New agenda file list installed"))
17748 nil 'local)
17749 (message "%s" (substitute-command-keys
17750 "Edit list and finish with \\[save-buffer]")))
17751 (customize-variable 'org-agenda-files)))
17753 (defun org-store-new-agenda-file-list (list)
17754 "Set new value for the agenda file list and save it correctly."
17755 (if (stringp org-agenda-files)
17756 (let ((fe (org-read-agenda-file-list t)) b u)
17757 (while (setq b (find-buffer-visiting org-agenda-files))
17758 (kill-buffer b))
17759 (with-temp-file org-agenda-files
17760 (insert
17761 (mapconcat
17762 (lambda (f) ;; Keep un-expanded entries.
17763 (if (setq u (assoc f fe))
17764 (cdr u)
17766 list "\n")
17767 "\n")))
17768 (let ((org-mode-hook nil) (org-inhibit-startup t)
17769 (org-insert-mode-line-in-empty-file nil))
17770 (setq org-agenda-files list)
17771 (customize-save-variable 'org-agenda-files org-agenda-files))))
17773 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17774 "Read the list of agenda files from a file.
17775 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17776 filenames, used by `org-store-new-agenda-file-list' to write back
17777 un-expanded file names."
17778 (when (file-directory-p org-agenda-files)
17779 (error "`org-agenda-files' cannot be a single directory"))
17780 (when (stringp org-agenda-files)
17781 (with-temp-buffer
17782 (insert-file-contents org-agenda-files)
17783 (mapcar
17784 (lambda (f)
17785 (let ((e (expand-file-name (substitute-in-file-name f)
17786 org-directory)))
17787 (if pair-with-expansion
17788 (cons e f)
17789 e)))
17790 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17792 ;;;###autoload
17793 (defun org-cycle-agenda-files ()
17794 "Cycle through the files in `org-agenda-files'.
17795 If the current buffer visits an agenda file, find the next one in the list.
17796 If the current buffer does not, find the first agenda file."
17797 (interactive)
17798 (let* ((fs (or (org-agenda-files t)
17799 (user-error "No agenda files")))
17800 (files (copy-sequence fs))
17801 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17802 file)
17803 (when tcf
17804 (while (and (setq file (pop files))
17805 (not (equal (file-truename file) tcf)))))
17806 (find-file (car (or files fs)))
17807 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17809 (defun org-agenda-file-to-front (&optional to-end)
17810 "Move/add the current file to the top of the agenda file list.
17811 If the file is not present in the list, it is added to the front. If it is
17812 present, it is moved there. With optional argument TO-END, add/move to the
17813 end of the list."
17814 (interactive "P")
17815 (let ((org-agenda-skip-unavailable-files nil)
17816 (file-alist (mapcar (lambda (x)
17817 (cons (file-truename x) x))
17818 (org-agenda-files t)))
17819 (ctf (file-truename
17820 (or buffer-file-name
17821 (user-error "Please save the current buffer to a file"))))
17822 x had)
17823 (setq x (assoc ctf file-alist) had x)
17825 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17826 (if to-end
17827 (setq file-alist (append (delq x file-alist) (list x)))
17828 (setq file-alist (cons x (delq x file-alist))))
17829 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17830 (org-install-agenda-files-menu)
17831 (message "File %s to %s of agenda file list"
17832 (if had "moved" "added") (if to-end "end" "front"))))
17834 (defun org-remove-file (&optional file)
17835 "Remove current file from the list of files in variable `org-agenda-files'.
17836 These are the files which are being checked for agenda entries.
17837 Optional argument FILE means use this file instead of the current."
17838 (interactive)
17839 (let* ((org-agenda-skip-unavailable-files nil)
17840 (file (or file buffer-file-name
17841 (user-error "Current buffer does not visit a file")))
17842 (true-file (file-truename file))
17843 (afile (abbreviate-file-name file))
17844 (files (delq nil (mapcar
17845 (lambda (x)
17846 (unless (equal true-file
17847 (file-truename x))
17849 (org-agenda-files t)))))
17850 (if (not (= (length files) (length (org-agenda-files t))))
17851 (progn
17852 (org-store-new-agenda-file-list files)
17853 (org-install-agenda-files-menu)
17854 (message "Removed from Org Agenda list: %s" afile))
17855 (message "File was not in list: %s (not removed)" afile))))
17857 (defun org-file-menu-entry (file)
17858 (vector file (list 'find-file file) t))
17860 (defun org-check-agenda-file (file)
17861 "Make sure FILE exists. If not, ask user what to do."
17862 (unless (file-exists-p file)
17863 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17864 (abbreviate-file-name file))
17865 (let ((r (downcase (read-char-exclusive))))
17866 (cond
17867 ((equal r ?r)
17868 (org-remove-file file)
17869 (throw 'nextfile t))
17870 (t (user-error "Abort"))))))
17872 (defun org-get-agenda-file-buffer (file)
17873 "Get an agenda buffer visiting FILE.
17874 If the buffer needs to be created, add it to the list of buffers
17875 which might be released later."
17876 (let ((buf (org-find-base-buffer-visiting file)))
17877 (if buf
17878 buf ; just return it
17879 ;; Make a new buffer and remember it
17880 (setq buf (find-file-noselect file))
17881 (when buf (push buf org-agenda-new-buffers))
17882 buf)))
17884 (defun org-release-buffers (blist)
17885 "Release all buffers in list, asking the user for confirmation when needed.
17886 When a buffer is unmodified, it is just killed. When modified, it is saved
17887 \(if the user agrees) and then killed."
17888 (let (file)
17889 (dolist (buf blist)
17890 (setq file (buffer-file-name buf))
17891 (when (and (buffer-modified-p buf)
17892 file
17893 (y-or-n-p (format "Save file %s? " file)))
17894 (with-current-buffer buf (save-buffer)))
17895 (kill-buffer buf))))
17897 (defun org-agenda-prepare-buffers (files)
17898 "Create buffers for all agenda files, protect archived trees and comments."
17899 (interactive)
17900 (let ((pa '(:org-archived t))
17901 (pc '(:org-comment t))
17902 (pall '(:org-archived t :org-comment t))
17903 (inhibit-read-only t)
17904 (org-inhibit-startup org-agenda-inhibit-startup)
17905 (rea (org-make-tag-string (list org-archive-tag)))
17906 re pos)
17907 (setq org-tag-alist-for-agenda nil
17908 org-tag-groups-alist-for-agenda nil)
17909 (save-excursion
17910 (save-restriction
17911 (dolist (file files)
17912 (catch 'nextfile
17913 (if (bufferp file)
17914 (set-buffer file)
17915 (org-check-agenda-file file)
17916 (set-buffer (org-get-agenda-file-buffer file)))
17917 (widen)
17918 (org-set-regexps-and-options 'tags-only)
17919 (setq pos (point))
17920 (or (memq 'category org-agenda-ignore-properties)
17921 (org-refresh-category-properties))
17922 (or (memq 'stats org-agenda-ignore-properties)
17923 (org-refresh-stats-properties))
17924 (or (memq 'effort org-agenda-ignore-properties)
17925 (org-refresh-effort-properties))
17926 (or (memq 'appt org-agenda-ignore-properties)
17927 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17928 (setq org-todo-keywords-for-agenda
17929 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17930 (setq org-done-keywords-for-agenda
17931 (append org-done-keywords-for-agenda org-done-keywords))
17932 (setq org-todo-keyword-alist-for-agenda
17933 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17934 (setq org-tag-alist-for-agenda
17935 (org--tag-add-to-alist
17936 org-tag-alist-for-agenda
17937 org-current-tag-alist))
17938 ;; Merge current file's tag groups into global
17939 ;; `org-tag-groups-alist-for-agenda'.
17940 (when org-group-tags
17941 (dolist (alist org-tag-groups-alist)
17942 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17943 (if old
17944 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17945 (push alist org-tag-groups-alist-for-agenda)))))
17946 (with-silent-modifications
17947 (save-excursion
17948 (remove-text-properties (point-min) (point-max) pall)
17949 (when org-agenda-skip-archived-trees
17950 (goto-char (point-min))
17951 (while (re-search-forward rea nil t)
17952 (when (org-at-heading-p t)
17953 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17954 (goto-char (point-min))
17955 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17956 (while (re-search-forward re nil t)
17957 (when (save-match-data (org-in-commented-heading-p t))
17958 (add-text-properties
17959 (match-beginning 0) (org-end-of-subtree t) pc)))))
17960 (goto-char pos)))))
17961 (setq org-todo-keywords-for-agenda
17962 (org-uniquify org-todo-keywords-for-agenda))
17963 (setq org-todo-keyword-alist-for-agenda
17964 (org-uniquify org-todo-keyword-alist-for-agenda))))
17967 ;;;; CDLaTeX minor mode
17969 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17970 "Keymap for the minor `org-cdlatex-mode'.")
17972 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17973 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17974 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17975 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17976 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
17978 (defvar org-cdlatex-texmathp-advice-is-done nil
17979 "Flag remembering if we have applied the advice to texmathp already.")
17981 (define-minor-mode org-cdlatex-mode
17982 "Toggle the minor `org-cdlatex-mode'.
17983 This mode supports entering LaTeX environment and math in LaTeX fragments
17984 in Org mode.
17985 \\{org-cdlatex-mode-map}"
17986 nil " OCDL" nil
17987 (when org-cdlatex-mode
17988 (require 'cdlatex)
17989 (run-hooks 'cdlatex-mode-hook)
17990 (cdlatex-compute-tables))
17991 (unless org-cdlatex-texmathp-advice-is-done
17992 (setq org-cdlatex-texmathp-advice-is-done t)
17993 (defadvice texmathp (around org-math-always-on activate)
17994 "Always return t in Org buffers.
17995 This is because we want to insert math symbols without dollars even outside
17996 the LaTeX math segments. If Org mode thinks that point is actually inside
17997 an embedded LaTeX fragment, let `texmathp' do its job.
17998 `\\[org-cdlatex-mode-map]'"
17999 (interactive)
18000 (let (p)
18001 (cond
18002 ((not (derived-mode-p 'org-mode)) ad-do-it)
18003 ((eq this-command 'cdlatex-math-symbol)
18004 (setq ad-return-value t
18005 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18007 (let ((p (org-inside-LaTeX-fragment-p)))
18008 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18009 (setq ad-return-value t
18010 texmathp-why '("Org mode embedded math" . 0))
18011 (when p ad-do-it)))))))))
18013 (defun turn-on-org-cdlatex ()
18014 "Unconditionally turn on `org-cdlatex-mode'."
18015 (org-cdlatex-mode 1))
18017 (defun org-try-cdlatex-tab ()
18018 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18019 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18020 - inside a LaTeX fragment, or
18021 - after the first word in a line, where an abbreviation expansion could
18022 insert a LaTeX environment."
18023 (when org-cdlatex-mode
18024 (cond
18025 ;; Before any word on the line: No expansion possible.
18026 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18027 ;; Just after first word on the line: Expand it. Make sure it
18028 ;; cannot happen on headlines, though.
18029 ((save-excursion
18030 (skip-chars-backward "a-zA-Z0-9*")
18031 (skip-chars-backward " \t")
18032 (and (bolp) (not (org-at-heading-p))))
18033 (cdlatex-tab) t)
18034 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18036 (defun org-cdlatex-underscore-caret (&optional _arg)
18037 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18038 Revert to the normal definition outside of these fragments."
18039 (interactive "P")
18040 (if (org-inside-LaTeX-fragment-p)
18041 (call-interactively 'cdlatex-sub-superscript)
18042 (let (org-cdlatex-mode)
18043 (call-interactively (key-binding (vector last-input-event))))))
18045 (defun org-cdlatex-math-modify (&optional _arg)
18046 "Execute `cdlatex-math-modify' in LaTeX fragments.
18047 Revert to the normal definition outside of these fragments."
18048 (interactive "P")
18049 (if (org-inside-LaTeX-fragment-p)
18050 (call-interactively 'cdlatex-math-modify)
18051 (let (org-cdlatex-mode)
18052 (call-interactively (key-binding (vector last-input-event))))))
18054 (defun org-cdlatex-environment-indent (&optional environment item)
18055 "Execute `cdlatex-environment' and indent the inserted environment.
18057 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18059 The inserted environment is indented to current indentation
18060 unless point is at the beginning of the line, in which the
18061 environment remains unintended."
18062 (interactive)
18063 ;; cdlatex-environment always return nil. Therefore, capture output
18064 ;; first and determine if an environment was selected.
18065 (let* ((beg (point-marker))
18066 (end (copy-marker (point) t))
18067 (inserted (progn
18068 (ignore-errors (cdlatex-environment environment item))
18069 (< beg end)))
18070 ;; Figure out how many lines to move forward after the
18071 ;; environment has been inserted.
18072 (lines (when inserted
18073 (save-excursion
18074 (- (cl-loop while (< beg (point))
18075 with x = 0
18076 do (forward-line -1)
18077 (cl-incf x)
18078 finally return x)
18079 (if (progn (goto-char beg)
18080 (and (progn (skip-chars-forward " \t") (eolp))
18081 (progn (skip-chars-backward " \t") (bolp))))
18082 1 0)))))
18083 (env (org-trim (delete-and-extract-region beg end))))
18084 (when inserted
18085 ;; Get indentation of next line unless at column 0.
18086 (let ((ind (if (bolp) 0
18087 (save-excursion
18088 (org-return-indent)
18089 (prog1 (current-indentation)
18090 (when (progn (skip-chars-forward " \t") (eolp))
18091 (delete-region beg (point)))))))
18092 (bol (progn (skip-chars-backward " \t") (bolp))))
18093 ;; Insert a newline before environment unless at column zero
18094 ;; to "escape" the current line. Insert a newline if
18095 ;; something is one the same line as \end{ENVIRONMENT}.
18096 (insert
18097 (concat (unless bol "\n") env
18098 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18099 (unless (zerop ind)
18100 (save-excursion
18101 (goto-char beg)
18102 (while (< (point) end)
18103 (unless (eolp) (indent-line-to ind))
18104 (forward-line))))
18105 (goto-char beg)
18106 (forward-line lines)
18107 (indent-line-to ind)))
18108 (set-marker beg nil)
18109 (set-marker end nil)))
18112 ;;;; LaTeX fragments
18114 (defun org-inside-LaTeX-fragment-p ()
18115 "Test if point is inside a LaTeX fragment.
18116 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18117 sequence appearing also before point.
18118 Even though the matchers for math are configurable, this function assumes
18119 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18120 delimiters are skipped when they have been removed by customization.
18121 The return value is nil, or a cons cell with the delimiter and the
18122 position of this delimiter.
18124 This function does a reasonably good job, but can locally be fooled by
18125 for example currency specifications. For example it will assume being in
18126 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18127 fragments that are properly closed, but during editing, we have to live
18128 with the uncertainty caused by missing closing delimiters. This function
18129 looks only before point, not after."
18130 (catch 'exit
18131 (let ((pos (point))
18132 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18133 (lim (save-excursion (org-backward-paragraph) (point)))
18134 dd-on str (start 0) m re)
18135 (goto-char pos)
18136 (when dodollar
18137 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18138 re (nth 1 (assoc "$" org-latex-regexps)))
18139 (while (string-match re str start)
18140 (cond
18141 ((= (match-end 0) (length str))
18142 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18143 ((= (match-end 0) (- (length str) 5))
18144 (throw 'exit nil))
18145 (t (setq start (match-end 0))))))
18146 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18147 (goto-char pos)
18148 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18149 (and (match-beginning 2) (throw 'exit nil))
18150 ;; count $$
18151 (while (re-search-backward "\\$\\$" lim t)
18152 (setq dd-on (not dd-on)))
18153 (goto-char pos)
18154 (when dd-on (cons "$$" m))))))
18156 (defun org-inside-latex-macro-p ()
18157 "Is point inside a LaTeX macro or its arguments?"
18158 (save-match-data
18159 (org-in-regexp
18160 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18162 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18163 "Build an overlay between BEG and END using IMAGE file.
18164 Argument IMAGETYPE is the extension of the displayed image,
18165 as a string. It defaults to \"png\"."
18166 (let ((ov (make-overlay beg end))
18167 (imagetype (or (intern imagetype) 'png)))
18168 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18169 (overlay-put ov 'evaporate t)
18170 (overlay-put ov
18171 'modification-hooks
18172 (list (lambda (o _flag _beg _end &optional _l)
18173 (delete-overlay o))))
18174 (overlay-put ov
18175 'display
18176 (list 'image :type imagetype :file image :ascent 'center))))
18178 (defun org--list-latex-overlays (&optional beg end)
18179 "List all Org LaTeX overlays in current buffer.
18180 Limit to overlays between BEG and END when those are provided."
18181 (cl-remove-if-not
18182 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18183 (overlays-in (or beg (point-min)) (or end (point-max)))))
18185 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18186 "Remove all overlays with LaTeX fragment images in current buffer.
18187 When optional arguments BEG and END are non-nil, remove all
18188 overlays between them instead. Return a non-nil value when some
18189 overlays were removed, nil otherwise."
18190 (let ((overlays (org--list-latex-overlays beg end)))
18191 (mapc #'delete-overlay overlays)
18192 overlays))
18194 (defun org-toggle-latex-fragment (&optional arg)
18195 "Preview the LaTeX fragment at point, or all locally or globally.
18197 If the cursor is on a LaTeX fragment, create the image and overlay
18198 it over the source code, if there is none. Remove it otherwise.
18199 If there is no fragment at point, display all fragments in the
18200 current section.
18202 With prefix ARG, preview or clear image for all fragments in the
18203 current subtree or in the whole buffer when used before the first
18204 headline. With a prefix ARG `\\[universal-argument] \
18205 \\[universal-argument]' preview or clear images
18206 for all fragments in the buffer."
18207 (interactive "P")
18208 (when (display-graphic-p)
18209 (catch 'exit
18210 (save-excursion
18211 (let (beg end msg)
18212 (cond
18213 ((or (equal arg '(16))
18214 (and (equal arg '(4))
18215 (org-with-limited-levels (org-before-first-heading-p))))
18216 (if (org-remove-latex-fragment-image-overlays)
18217 (progn (message "LaTeX fragments images removed from buffer")
18218 (throw 'exit nil))
18219 (setq msg "Creating images for buffer...")))
18220 ((equal arg '(4))
18221 (org-with-limited-levels (org-back-to-heading t))
18222 (setq beg (point))
18223 (setq end (progn (org-end-of-subtree t) (point)))
18224 (if (org-remove-latex-fragment-image-overlays beg end)
18225 (progn
18226 (message "LaTeX fragment images removed from subtree")
18227 (throw 'exit nil))
18228 (setq msg "Creating images for subtree...")))
18229 ((let ((datum (org-element-context)))
18230 (when (memq (org-element-type datum)
18231 '(latex-environment latex-fragment))
18232 (setq beg (org-element-property :begin datum))
18233 (setq end (org-element-property :end datum))
18234 (if (org-remove-latex-fragment-image-overlays beg end)
18235 (progn (message "LaTeX fragment image removed")
18236 (throw 'exit nil))
18237 (setq msg "Creating image...")))))
18239 (org-with-limited-levels
18240 (setq beg (if (org-at-heading-p) (line-beginning-position)
18241 (outline-previous-heading)
18242 (point)))
18243 (setq end (progn (outline-next-heading) (point)))
18244 (if (org-remove-latex-fragment-image-overlays beg end)
18245 (progn
18246 (message "LaTeX fragment images removed from section")
18247 (throw 'exit nil))
18248 (setq msg "Creating images for section...")))))
18249 (let ((file (buffer-file-name (buffer-base-buffer))))
18250 (org-format-latex
18251 (concat org-preview-latex-image-directory "org-ltximg")
18252 beg end
18253 ;; Emacs cannot overlay images from remote hosts. Create
18254 ;; it in `temporary-file-directory' instead.
18255 (if (or (not file) (file-remote-p file))
18256 temporary-file-directory
18257 default-directory)
18258 'overlays msg 'forbuffer org-preview-latex-default-process))
18259 (message (concat msg "done")))))))
18261 (defun org-format-latex
18262 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18263 "Replace LaTeX fragments with links to an image.
18265 The function takes care of creating the replacement image.
18267 Only consider fragments between BEG and END when those are
18268 provided.
18270 When optional argument OVERLAYS is non-nil, display the image on
18271 top of the fragment instead of replacing it.
18273 PROCESSING-TYPE is the conversion method to use, as a symbol.
18275 Some of the options can be changed using the variable
18276 `org-format-latex-options', which see."
18277 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18278 (unless (eq processing-type 'verbatim)
18279 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18280 (cnt 0)
18281 checkdir-flag)
18282 (goto-char (or beg (point-min)))
18283 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18284 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18285 (overlay-recenter (or end (point-max))))
18286 (while (re-search-forward math-regexp end t)
18287 (unless (and overlays
18288 (eq (get-char-property (point) 'org-overlay-type)
18289 'org-latex-overlay))
18290 (let* ((context (org-element-context))
18291 (type (org-element-type context)))
18292 (when (memq type '(latex-environment latex-fragment))
18293 (let ((block-type (eq type 'latex-environment))
18294 (value (org-element-property :value context))
18295 (beg (org-element-property :begin context))
18296 (end (save-excursion
18297 (goto-char (org-element-property :end context))
18298 (skip-chars-backward " \r\t\n")
18299 (point))))
18300 (cond
18301 ((eq processing-type 'mathjax)
18302 ;; Prepare for MathJax processing.
18303 (if (not (string-match "\\`\\$\\$?" value))
18304 (goto-char end)
18305 (delete-region beg end)
18306 (if (string= (match-string 0 value) "$$")
18307 (insert "\\[" (substring value 2 -2) "\\]")
18308 (insert "\\(" (substring value 1 -1) "\\)"))))
18309 ((assq processing-type org-preview-latex-process-alist)
18310 ;; Process to an image.
18311 (cl-incf cnt)
18312 (goto-char beg)
18313 (let* ((processing-info
18314 (cdr (assq processing-type org-preview-latex-process-alist)))
18315 (face (face-at-point))
18316 ;; Get the colors from the face at point.
18318 (let ((color (plist-get org-format-latex-options
18319 :foreground)))
18320 (if (and forbuffer (eq color 'auto))
18321 (face-attribute face :foreground nil 'default)
18322 color)))
18324 (let ((color (plist-get org-format-latex-options
18325 :background)))
18326 (if (and forbuffer (eq color 'auto))
18327 (face-attribute face :background nil 'default)
18328 color)))
18329 (hash (sha1 (prin1-to-string
18330 (list org-format-latex-header
18331 org-latex-default-packages-alist
18332 org-latex-packages-alist
18333 org-format-latex-options
18334 forbuffer value fg bg))))
18335 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18336 (absprefix (expand-file-name prefix dir))
18337 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18338 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18339 (sep (and block-type "\n\n"))
18340 (link (concat sep "[[file:" linkfile "]]" sep))
18341 (options
18342 (org-combine-plists
18343 org-format-latex-options
18344 `(:foreground ,fg :background ,bg))))
18345 (when msg (message msg cnt))
18346 (unless checkdir-flag ; Ensure the directory exists.
18347 (setq checkdir-flag t)
18348 (let ((todir (file-name-directory absprefix)))
18349 (unless (file-directory-p todir)
18350 (make-directory todir t))))
18351 (unless (file-exists-p movefile)
18352 (org-create-formula-image
18353 value movefile options forbuffer processing-type))
18354 (if overlays
18355 (progn
18356 (dolist (o (overlays-in beg end))
18357 (when (eq (overlay-get o 'org-overlay-type)
18358 'org-latex-overlay)
18359 (delete-overlay o)))
18360 (org--format-latex-make-overlay beg end movefile imagetype)
18361 (goto-char end))
18362 (delete-region beg end)
18363 (insert
18364 (org-add-props link
18365 (list 'org-latex-src
18366 (replace-regexp-in-string "\"" "" value)
18367 'org-latex-src-embed-type
18368 (if block-type 'paragraph 'character)))))))
18369 ((eq processing-type 'mathml)
18370 ;; Process to MathML.
18371 (unless (org-format-latex-mathml-available-p)
18372 (user-error "LaTeX to MathML converter not configured"))
18373 (cl-incf cnt)
18374 (when msg (message msg cnt))
18375 (goto-char beg)
18376 (delete-region beg end)
18377 (insert (org-format-latex-as-mathml
18378 value block-type prefix dir)))
18380 (error "Unknown conversion process %s for LaTeX fragments"
18381 processing-type)))))))))))
18383 (defun org-create-math-formula (latex-frag &optional mathml-file)
18384 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18385 Use `org-latex-to-mathml-convert-command'. If the conversion is
18386 sucessful, return the portion between \"<math...> </math>\"
18387 elements otherwise return nil. When MATHML-FILE is specified,
18388 write the results in to that file. When invoked as an
18389 interactive command, prompt for LATEX-FRAG, with initial value
18390 set to the current active region and echo the results for user
18391 inspection."
18392 (interactive (list (let ((frag (when (org-region-active-p)
18393 (buffer-substring-no-properties
18394 (region-beginning) (region-end)))))
18395 (read-string "LaTeX Fragment: " frag nil frag))))
18396 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18397 (let* ((tmp-in-file
18398 (let ((file (file-relative-name
18399 (make-temp-name (expand-file-name "ltxmathml-in")))))
18400 (write-region latex-frag nil file)
18401 file))
18402 (tmp-out-file (file-relative-name
18403 (make-temp-name (expand-file-name "ltxmathml-out"))))
18404 (cmd (format-spec
18405 org-latex-to-mathml-convert-command
18406 `((?j . ,(and org-latex-to-mathml-jar-file
18407 (shell-quote-argument
18408 (expand-file-name
18409 org-latex-to-mathml-jar-file))))
18410 (?I . ,(shell-quote-argument tmp-in-file))
18411 (?i . ,latex-frag)
18412 (?o . ,(shell-quote-argument tmp-out-file)))))
18413 mathml shell-command-output)
18414 (when (called-interactively-p 'any)
18415 (unless (org-format-latex-mathml-available-p)
18416 (user-error "LaTeX to MathML converter not configured")))
18417 (message "Running %s" cmd)
18418 (setq shell-command-output (shell-command-to-string cmd))
18419 (setq mathml
18420 (when (file-readable-p tmp-out-file)
18421 (with-current-buffer (find-file-noselect tmp-out-file t)
18422 (goto-char (point-min))
18423 (when (re-search-forward
18424 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18425 (regexp-quote
18426 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18427 nil t)
18428 (prog1 (match-string 0) (kill-buffer))))))
18429 (cond
18430 (mathml
18431 (setq mathml
18432 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18433 (when mathml-file
18434 (write-region mathml nil mathml-file))
18435 (when (called-interactively-p 'any)
18436 (message mathml)))
18437 ((message "LaTeX to MathML conversion failed")
18438 (message shell-command-output)))
18439 (delete-file tmp-in-file)
18440 (when (file-exists-p tmp-out-file)
18441 (delete-file tmp-out-file))
18442 mathml))
18444 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18445 prefix &optional dir)
18446 "Use `org-create-math-formula' but check local cache first."
18447 (let* ((absprefix (expand-file-name prefix dir))
18448 (print-length nil) (print-level nil)
18449 (formula-id (concat
18450 "formula-"
18451 (sha1
18452 (prin1-to-string
18453 (list latex-frag
18454 org-latex-to-mathml-convert-command)))))
18455 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18456 (formula-cache-dir (file-name-directory formula-cache)))
18458 (unless (file-directory-p formula-cache-dir)
18459 (make-directory formula-cache-dir t))
18461 (unless (file-exists-p formula-cache)
18462 (org-create-math-formula latex-frag formula-cache))
18464 (if (file-exists-p formula-cache)
18465 ;; Successful conversion. Return the link to MathML file.
18466 (org-add-props
18467 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18468 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18469 'org-latex-src-embed-type (if latex-frag-type
18470 'paragraph 'character)))
18471 ;; Failed conversion. Return the LaTeX fragment verbatim
18472 latex-frag)))
18474 (defun org--get-display-dpi ()
18475 "Get the DPI of the display.
18476 The function assumes that the display has the same pixel width in
18477 the horizontal and vertical directions."
18478 (if (display-graphic-p)
18479 (round (/ (display-pixel-height)
18480 (/ (display-mm-height) 25.4)))
18481 (error "Attempt to calculate the dpi of a non-graphic display")))
18483 (defun org-create-formula-image
18484 (string tofile options buffer &optional processing-type)
18485 "Create an image from LaTeX source using external processes.
18487 The LaTeX STRING is saved to a temporary LaTeX file, then
18488 converted to an image file by process PROCESSING-TYPE defined in
18489 `org-preview-latex-process-alist'. A nil value defaults to
18490 `org-preview-latex-default-process'.
18492 The generated image file is eventually moved to TOFILE.
18494 The OPTIONS argument controls the size, foreground color and
18495 background color of the generated image.
18497 When BUFFER non-nil, this function is used for LaTeX previewing.
18498 Otherwise, it is used to deal with LaTeX snippets showed in
18499 a HTML file."
18500 (let* ((processing-type (or processing-type
18501 org-preview-latex-default-process))
18502 (processing-info
18503 (cdr (assq processing-type org-preview-latex-process-alist)))
18504 (programs (plist-get processing-info :programs))
18505 (error-message (or (plist-get processing-info :message) ""))
18506 (use-xcolor (plist-get processing-info :use-xcolor))
18507 (image-input-type (plist-get processing-info :image-input-type))
18508 (image-output-type (plist-get processing-info :image-output-type))
18509 (post-clean (or (plist-get processing-info :post-clean)
18510 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18511 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18512 (latex-header
18513 (or (plist-get processing-info :latex-header)
18514 (org-latex-make-preamble
18515 (org-export-get-environment (org-export-get-backend 'latex))
18516 org-format-latex-header
18517 'snippet)))
18518 (latex-compiler (plist-get processing-info :latex-compiler))
18519 (image-converter (plist-get processing-info :image-converter))
18520 (tmpdir temporary-file-directory)
18521 (texfilebase (make-temp-name
18522 (expand-file-name "orgtex" tmpdir)))
18523 (texfile (concat texfilebase ".tex"))
18524 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18525 '(1.0 . 1.0)))
18526 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18527 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18528 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18529 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18530 "Black"))
18531 (bg (or (plist-get options (if buffer :background :html-background))
18532 "Transparent"))
18533 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18534 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18535 (dolist (program programs)
18536 (org-check-external-command program error-message))
18537 (if use-xcolor
18538 (progn (if (eq fg 'default)
18539 (setq fg (org-latex-color :foreground))
18540 (setq fg (org-latex-color-format fg)))
18541 (if (eq bg 'default)
18542 (setq bg (org-latex-color :background))
18543 (setq bg (org-latex-color-format
18544 (if (string= bg "Transparent") "white" bg))))
18545 (with-temp-file texfile
18546 (insert latex-header)
18547 (insert "\n\\begin{document}\n"
18548 "\\definecolor{fg}{rgb}{" fg "}\n"
18549 "\\definecolor{bg}{rgb}{" bg "}\n"
18550 "\n\\pagecolor{bg}\n"
18551 "\n{\\color{fg}\n"
18552 string
18553 "\n}\n"
18554 "\n\\end{document}\n")))
18555 (if (eq fg 'default)
18556 (setq fg (org-dvipng-color :foreground))
18557 (unless (string= fg "Transparent")
18558 (setq fg (org-dvipng-color-format fg))))
18559 (if (eq bg 'default)
18560 (setq bg (org-dvipng-color :background))
18561 (unless (string= bg "Transparent")
18562 (setq bg (org-dvipng-color-format bg))))
18563 (with-temp-file texfile
18564 (insert latex-header)
18565 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18567 (let* ((err-msg (format "Please adjust `%s' part of \
18568 `org-preview-latex-process-alist'."
18569 processing-type))
18570 (image-input-file
18571 (org-compile-file
18572 texfile latex-compiler image-input-type err-msg log-buf))
18573 (image-output-file
18574 (org-compile-file
18575 image-input-file image-converter image-output-type err-msg log-buf
18576 `((?F . ,(shell-quote-argument fg))
18577 (?B . ,(shell-quote-argument bg))
18578 (?D . ,(shell-quote-argument (format "%s" dpi)))
18579 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18580 (copy-file image-output-file tofile 'replace)
18581 (dolist (e post-clean)
18582 (when (file-exists-p (concat texfilebase e))
18583 (delete-file (concat texfilebase e))))
18584 image-output-file)))
18586 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18587 "Fill a LaTeX header template TPL.
18588 In the template, the following place holders will be recognized:
18590 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18591 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18592 [PACKAGES] \\usepackage statements for PKG
18593 [NO-PACKAGES] do not include PKG
18594 [EXTRA] the string EXTRA
18595 [NO-EXTRA] do not include EXTRA
18597 For backward compatibility, if both the positive and the negative place
18598 holder is missing, the positive one (without the \"NO-\") will be
18599 assumed to be present at the end of the template.
18600 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18601 EXTRA is a string.
18602 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18603 (let (rpl (end ""))
18604 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18605 (setq rpl (if (or (match-end 1) (not def-pkg))
18606 "" (org-latex-packages-to-string def-pkg snippets-p t))
18607 tpl (replace-match rpl t t tpl))
18608 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18610 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18611 (setq rpl (if (or (match-end 1) (not pkg))
18612 "" (org-latex-packages-to-string pkg snippets-p t))
18613 tpl (replace-match rpl t t tpl))
18614 (when pkg (setq end
18615 (concat end "\n"
18616 (org-latex-packages-to-string pkg snippets-p)))))
18618 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18619 (setq rpl (if (or (match-end 1) (not extra))
18620 "" (concat extra "\n"))
18621 tpl (replace-match rpl t t tpl))
18622 (when (and extra (string-match "\\S-" extra))
18623 (setq end (concat end "\n" extra))))
18625 (if (string-match "\\S-" end)
18626 (concat tpl "\n" end)
18627 tpl)))
18629 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18630 "Turn an alist of packages into a string with the \\usepackage macros."
18631 (setq pkg (mapconcat (lambda(p)
18632 (cond
18633 ((stringp p) p)
18634 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18635 (format "%% Package %s omitted" (cadr p)))
18636 ((equal "" (car p))
18637 (format "\\usepackage{%s}" (cadr p)))
18639 (format "\\usepackage[%s]{%s}"
18640 (car p) (cadr p)))))
18642 "\n"))
18643 (if newline (concat pkg "\n") pkg))
18645 (defun org-dvipng-color (attr)
18646 "Return a RGB color specification for dvipng."
18647 (org-dvipng-color-format (face-attribute 'default attr nil)))
18649 (defun org-dvipng-color-format (color-name)
18650 "Convert COLOR-NAME to a RGB color value for dvipng."
18651 (apply #'format "rgb %s %s %s"
18652 (mapcar 'org-normalize-color
18653 (color-values color-name))))
18655 (defun org-latex-color (attr)
18656 "Return a RGB color for the LaTeX color package."
18657 (org-latex-color-format (face-attribute 'default attr nil)))
18659 (defun org-latex-color-format (color-name)
18660 "Convert COLOR-NAME to a RGB color value."
18661 (apply #'format "%s,%s,%s"
18662 (mapcar 'org-normalize-color
18663 (color-values color-name))))
18665 (defun org-normalize-color (value)
18666 "Return string to be used as color value for an RGB component."
18667 (format "%g" (/ value 65535.0)))
18670 ;; Image display
18672 (defvar-local org-inline-image-overlays nil)
18674 (defun org-toggle-inline-images (&optional include-linked)
18675 "Toggle the display of inline images.
18676 INCLUDE-LINKED is passed to `org-display-inline-images'."
18677 (interactive "P")
18678 (if org-inline-image-overlays
18679 (progn
18680 (org-remove-inline-images)
18681 (when (called-interactively-p 'interactive)
18682 (message "Inline image display turned off")))
18683 (org-display-inline-images include-linked)
18684 (when (called-interactively-p 'interactive)
18685 (message (if org-inline-image-overlays
18686 (format "%d images displayed inline"
18687 (length org-inline-image-overlays))
18688 "No images to display inline")))))
18690 (defun org-redisplay-inline-images ()
18691 "Refresh the display of inline images."
18692 (interactive)
18693 (if (not org-inline-image-overlays)
18694 (org-toggle-inline-images)
18695 (org-toggle-inline-images)
18696 (org-toggle-inline-images)))
18698 (defun org-display-inline-images (&optional include-linked refresh beg end)
18699 "Display inline images.
18701 An inline image is a link which follows either of these
18702 conventions:
18704 1. Its path is a file with an extension matching return value
18705 from `image-file-name-regexp' and it has no contents.
18707 2. Its description consists in a single link of the previous
18708 type.
18710 When optional argument INCLUDE-LINKED is non-nil, also links with
18711 a text description part will be inlined. This can be nice for
18712 a quick look at those images, but it does not reflect what
18713 exported files will look like.
18715 When optional argument REFRESH is non-nil, refresh existing
18716 images between BEG and END. This will create new image displays
18717 only if necessary. BEG and END default to the buffer
18718 boundaries."
18719 (interactive "P")
18720 (when (display-graphic-p)
18721 (unless refresh
18722 (org-remove-inline-images)
18723 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18724 (org-with-wide-buffer
18725 (goto-char (or beg (point-min)))
18726 (let* ((case-fold-search t)
18727 (file-extension-re (image-file-name-regexp))
18728 (link-abbrevs (mapcar #'car
18729 (append org-link-abbrev-alist-local
18730 org-link-abbrev-alist)))
18731 ;; Check absolute, relative file names and explicit
18732 ;; "file:" links. Also check link abbreviations since
18733 ;; some might expand to "file" links.
18734 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18735 (if (not link-abbrevs) ""
18736 (format "\\|\\(?:%s:\\)"
18737 (regexp-opt link-abbrevs))))))
18738 (while (re-search-forward file-types-re end t)
18739 (let ((link (save-match-data (org-element-context))))
18740 ;; Check if we're at an inline image, i.e., an image file
18741 ;; link without a description (unless INCLUDE-LINKED is
18742 ;; non-nil).
18743 (when (and (equal "file" (org-element-property :type link))
18744 (or include-linked
18745 (null (org-element-contents link)))
18746 (string-match-p file-extension-re
18747 (org-element-property :path link)))
18748 (let ((file (expand-file-name
18749 (org-link-unescape
18750 (org-element-property :path link)))))
18751 (when (file-exists-p file)
18752 (let ((width
18753 ;; Apply `org-image-actual-width' specifications.
18754 (cond
18755 ((not (image-type-available-p 'imagemagick)) nil)
18756 ((eq org-image-actual-width t) nil)
18757 ((listp org-image-actual-width)
18759 ;; First try to find a width among
18760 ;; attributes associated to the paragraph
18761 ;; containing link.
18762 (let ((paragraph
18763 (let ((e link))
18764 (while (and (setq e (org-element-property
18765 :parent e))
18766 (not (eq (org-element-type e)
18767 'paragraph))))
18768 e)))
18769 (when paragraph
18770 (save-excursion
18771 (goto-char (org-element-property :begin paragraph))
18772 (when
18773 (re-search-forward
18774 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18775 (org-element-property
18776 :post-affiliated paragraph)
18778 (string-to-number (match-string 1))))))
18779 ;; Otherwise, fall-back to provided number.
18780 (car org-image-actual-width)))
18781 ((numberp org-image-actual-width)
18782 org-image-actual-width)))
18783 (old (get-char-property-and-overlay
18784 (org-element-property :begin link)
18785 'org-image-overlay)))
18786 (if (and (car-safe old) refresh)
18787 (image-refresh (overlay-get (cdr old) 'display))
18788 (let ((image (create-image file
18789 (and width 'imagemagick)
18791 :width width)))
18792 (when image
18793 (let ((ov (make-overlay
18794 (org-element-property :begin link)
18795 (progn
18796 (goto-char
18797 (org-element-property :end link))
18798 (skip-chars-backward " \t")
18799 (point)))))
18800 (overlay-put ov 'display image)
18801 (overlay-put ov 'face 'default)
18802 (overlay-put ov 'org-image-overlay t)
18803 (overlay-put
18804 ov 'modification-hooks
18805 (list 'org-display-inline-remove-overlay))
18806 (push ov org-inline-image-overlays)))))))))))))))
18808 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18809 "Remove inline-display overlay if a corresponding region is modified."
18810 (let ((inhibit-modification-hooks t))
18811 (when (and ov after)
18812 (delete ov org-inline-image-overlays)
18813 (delete-overlay ov))))
18815 (defun org-remove-inline-images ()
18816 "Remove inline display of images."
18817 (interactive)
18818 (mapc #'delete-overlay org-inline-image-overlays)
18819 (setq org-inline-image-overlays nil))
18822 ;;; Key bindings
18824 (defun org-remap (map &rest commands)
18825 "In MAP, remap the functions given in COMMANDS.
18826 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18827 (let (new old)
18828 (while commands
18829 (setq old (pop commands) new (pop commands))
18830 (org-defkey map (vector 'remap old) new))))
18832 ;;;; Outline functions that can be remapped in Org
18833 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18834 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18835 (define-key org-mode-map [remap outline-forward-same-level]
18836 #'org-forward-heading-same-level)
18837 (define-key org-mode-map [remap outline-backward-same-level]
18838 #'org-backward-heading-same-level)
18839 (define-key org-mode-map [remap outline-show-branches]
18840 #'org-kill-note-or-show-branches)
18841 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18842 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18843 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18844 (define-key org-mode-map [remap outline-next-visible-heading]
18845 #'org-next-visible-heading)
18846 (define-key org-mode-map [remap outline-previous-visible-heading]
18847 #'org-previous-visible-heading)
18848 (define-key org-mode-map [remap show-children] #'org-show-children)
18850 ;;;; Make `C-c C-x' a prefix key
18851 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18853 ;;;; TAB key with modifiers
18854 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18855 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18856 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18857 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18858 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18860 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18861 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18862 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18864 ;;;; RET key with modifiers
18865 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18866 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18867 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18868 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18869 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18871 ;;;; Cursor keys with modifiers
18872 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18873 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18874 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18875 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18876 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18877 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18878 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18880 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18881 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18882 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18883 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18884 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18885 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18886 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18887 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18888 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18889 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18891 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18892 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18893 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18894 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18896 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18897 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18898 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18899 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18901 ;;;; Babel keys
18902 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18903 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18904 (define-key org-babel-map key def))
18906 ;;;; Extra keys for TTY access.
18908 ;; We only set them when really needed because otherwise the
18909 ;; menus don't show the simple keys
18911 (when (or org-use-extra-keys (not window-system))
18912 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18913 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18914 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18915 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18916 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18917 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18918 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18919 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18920 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18921 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18922 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18923 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18924 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18925 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18926 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18927 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18928 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18929 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18930 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18931 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18932 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18934 ;;;; Narrow map
18935 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18936 (org-defkey narrow-map "b" #'org-narrow-to-block)
18937 (org-defkey narrow-map "e" #'org-narrow-to-element)
18939 ;;;; Remap usual Emacs bindings
18940 (org-remap org-mode-map
18941 'self-insert-command 'org-self-insert-command
18942 'delete-char 'org-delete-char
18943 'delete-backward-char 'org-delete-backward-char
18944 'kill-line 'org-kill-line
18945 'open-line 'org-open-line
18946 'yank 'org-yank
18947 'comment-dwim 'org-comment-dwim
18948 'move-beginning-of-line 'org-beginning-of-line
18949 'move-end-of-line 'org-end-of-line
18950 'forward-paragraph 'org-forward-paragraph
18951 'backward-paragraph 'org-backward-paragraph
18952 'backward-sentence 'org-backward-sentence
18953 'forward-sentence 'org-forward-sentence
18954 'fill-paragraph 'org-fill-paragraph
18955 'delete-indentation 'org-delete-indentation
18956 'transpose-words 'org-transpose-words)
18958 ;;;; All the other keys
18959 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18960 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18961 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18962 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18963 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18964 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18965 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18966 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18967 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18968 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18969 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18970 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18971 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18972 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18973 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18974 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18975 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18976 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18977 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18978 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18979 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18980 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
18981 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
18982 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
18983 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
18984 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
18985 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
18986 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
18987 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
18988 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
18989 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
18990 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
18991 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
18992 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
18993 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
18994 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
18995 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
18996 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
18997 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
18998 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
18999 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
19000 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
19001 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19002 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19003 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19004 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19005 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19006 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19007 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19008 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19009 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19010 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19011 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19012 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19013 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19014 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19015 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19016 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19017 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19018 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19019 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19020 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19021 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19022 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19023 (org-defkey org-mode-map (kbd "RET") #'org-return)
19024 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19025 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19026 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19027 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19028 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19029 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19030 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19031 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19032 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19033 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19034 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19035 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19036 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19037 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19038 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19039 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19040 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19041 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19042 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19043 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19044 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19045 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19046 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19047 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19048 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19049 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19050 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19051 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19052 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19053 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19054 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19055 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19056 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19057 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19058 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19059 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19060 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19061 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19062 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19063 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19064 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19065 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19066 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19067 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19068 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19069 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19070 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19071 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19072 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19073 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19074 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19075 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19076 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19077 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19078 (org-defkey org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19079 (org-defkey org-mode-map (kbd "C-c C-x !") #'org-reload)
19080 (org-defkey org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19081 (org-defkey org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19082 (org-defkey org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19083 (org-defkey org-mode-map (kbd "C-c C-x I") #'org-info-find-node)
19086 ;;; Speed commands
19088 (defconst org-speed-commands-default
19090 ("Outline Navigation")
19091 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19092 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19093 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19094 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19095 ("F" . org-next-block)
19096 ("B" . org-previous-block)
19097 ("u" . (org-speed-move-safe 'outline-up-heading))
19098 ("j" . org-goto)
19099 ("g" . (org-refile t))
19100 ("Outline Visibility")
19101 ("c" . org-cycle)
19102 ("C" . org-shifttab)
19103 (" " . org-display-outline-path)
19104 ("s" . org-toggle-narrow-to-subtree)
19105 ("k" . org-cut-subtree)
19106 ("=" . org-columns)
19107 ("Outline Structure Editing")
19108 ("U" . org-metaup)
19109 ("D" . org-metadown)
19110 ("r" . org-metaright)
19111 ("l" . org-metaleft)
19112 ("R" . org-shiftmetaright)
19113 ("L" . org-shiftmetaleft)
19114 ("i" . (progn (forward-char 1) (call-interactively
19115 'org-insert-heading-respect-content)))
19116 ("^" . org-sort)
19117 ("w" . org-refile)
19118 ("a" . org-archive-subtree-default-with-confirmation)
19119 ("@" . org-mark-subtree)
19120 ("#" . org-toggle-comment)
19121 ("Clock Commands")
19122 ("I" . org-clock-in)
19123 ("O" . org-clock-out)
19124 ("Meta Data Editing")
19125 ("t" . org-todo)
19126 ("," . (org-priority))
19127 ("0" . (org-priority ?\ ))
19128 ("1" . (org-priority ?A))
19129 ("2" . (org-priority ?B))
19130 ("3" . (org-priority ?C))
19131 (":" . org-set-tags-command)
19132 ("e" . org-set-effort)
19133 ("E" . org-inc-effort)
19134 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19135 (org-entry-put (point) "APPT_WARNTIME" m)))
19136 ("Agenda Views etc")
19137 ("v" . org-agenda)
19138 ("/" . org-sparse-tree)
19139 ("Misc")
19140 ("o" . org-open-at-point)
19141 ("?" . org-speed-command-help)
19142 ("<" . (org-agenda-set-restriction-lock 'subtree))
19143 (">" . (org-agenda-remove-restriction-lock))
19145 "The default speed commands.")
19147 (defun org-print-speed-command (e)
19148 (if (> (length (car e)) 1)
19149 (progn
19150 (princ "\n")
19151 (princ (car e))
19152 (princ "\n")
19153 (princ (make-string (length (car e)) ?-))
19154 (princ "\n"))
19155 (princ (car e))
19156 (princ " ")
19157 (if (symbolp (cdr e))
19158 (princ (symbol-name (cdr e)))
19159 (prin1 (cdr e)))
19160 (princ "\n")))
19162 (defun org-speed-command-help ()
19163 "Show the available speed commands."
19164 (interactive)
19165 (if (not org-use-speed-commands)
19166 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19167 (with-output-to-temp-buffer "*Help*"
19168 (princ "User-defined Speed commands\n===========================\n")
19169 (mapc #'org-print-speed-command org-speed-commands-user)
19170 (princ "\n")
19171 (princ "Built-in Speed commands\n=======================\n")
19172 (mapc #'org-print-speed-command org-speed-commands-default))
19173 (with-current-buffer "*Help*"
19174 (setq truncate-lines t))))
19176 (defun org-speed-move-safe (cmd)
19177 "Execute CMD, but make sure that the cursor always ends up in a headline.
19178 If not, return to the original position and throw an error."
19179 (interactive)
19180 (let ((pos (point)))
19181 (call-interactively cmd)
19182 (unless (and (bolp) (org-at-heading-p))
19183 (goto-char pos)
19184 (error "Boundary reached while executing %s" cmd))))
19186 (defvar org-self-insert-command-undo-counter 0)
19188 (defvar org-table-auto-blank-field) ; defined in org-table.el
19189 (defvar org-speed-command nil)
19191 (defun org-speed-command-activate (keys)
19192 "Hook for activating single-letter speed commands.
19193 `org-speed-commands-default' specifies a minimal command set.
19194 Use `org-speed-commands-user' for further customization."
19195 (when (or (and (bolp) (looking-at org-outline-regexp))
19196 (and (functionp org-use-speed-commands)
19197 (funcall org-use-speed-commands)))
19198 (cdr (assoc keys (append org-speed-commands-user
19199 org-speed-commands-default)))))
19201 (defun org-babel-speed-command-activate (keys)
19202 "Hook for activating single-letter code block commands."
19203 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19204 (cdr (assoc keys org-babel-key-bindings))))
19206 (defcustom org-speed-command-hook
19207 '(org-speed-command-activate org-babel-speed-command-activate)
19208 "Hook for activating speed commands at strategic locations.
19209 Hook functions are called in sequence until a valid handler is
19210 found.
19212 Each hook takes a single argument, a user-pressed command key
19213 which is also a `self-insert-command' from the global map.
19215 Within the hook, examine the cursor position and the command key
19216 and return nil or a valid handler as appropriate. Handler could
19217 be one of an interactive command, a function, or a form.
19219 Set `org-use-speed-commands' to non-nil value to enable this
19220 hook. The default setting is `org-speed-command-activate'."
19221 :group 'org-structure
19222 :version "24.1"
19223 :type 'hook)
19225 (defun org-self-insert-command (N)
19226 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19227 If the cursor is in a table looking at whitespace, the whitespace is
19228 overwritten, and the table is not marked as requiring realignment."
19229 (interactive "p")
19230 (org-check-before-invisible-edit 'insert)
19231 (cond
19232 ((and org-use-speed-commands
19233 (let ((kv (this-command-keys-vector)))
19234 (setq org-speed-command
19235 (run-hook-with-args-until-success
19236 'org-speed-command-hook
19237 (make-string 1 (aref kv (1- (length kv))))))))
19238 (cond
19239 ((commandp org-speed-command)
19240 (setq this-command org-speed-command)
19241 (call-interactively org-speed-command))
19242 ((functionp org-speed-command)
19243 (funcall org-speed-command))
19244 ((and org-speed-command (listp org-speed-command))
19245 (eval org-speed-command))
19246 (t (let (org-use-speed-commands)
19247 (call-interactively 'org-self-insert-command)))))
19248 ((and
19249 (= N 1)
19250 (not (org-region-active-p))
19251 (org-at-table-p)
19252 (progn
19253 ;; Check if we blank the field, and if that triggers align.
19254 (and (featurep 'org-table)
19255 org-table-auto-blank-field
19256 (memq last-command
19257 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19258 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19259 ;; Got extra space, this field does not determine
19260 ;; column width.
19261 (let (org-table-may-need-update) (org-table-blank-field))
19262 ;; No extra space, this field may determine column
19263 ;; width.
19264 (org-table-blank-field)))
19266 (looking-at "[^|\n]* |"))
19267 ;; There is room for insertion without re-aligning the table.
19268 (self-insert-command N)
19269 (org-table-with-shrunk-field
19270 (save-excursion
19271 (skip-chars-forward "^|")
19272 ;; Do not delete last space, which is
19273 ;; `org-table-separator-space', but the regular space before
19274 ;; it.
19275 (delete-region (- (point) 2) (1- (point))))))
19277 (setq org-table-may-need-update t)
19278 (self-insert-command N)
19279 (org-fix-tags-on-the-fly)
19280 (when org-self-insert-cluster-for-undo
19281 (if (not (eq last-command 'org-self-insert-command))
19282 (setq org-self-insert-command-undo-counter 1)
19283 (if (>= org-self-insert-command-undo-counter 20)
19284 (setq org-self-insert-command-undo-counter 1)
19285 (and (> org-self-insert-command-undo-counter 0)
19286 buffer-undo-list (listp buffer-undo-list)
19287 (not (cadr buffer-undo-list)) ; remove nil entry
19288 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19289 (setq org-self-insert-command-undo-counter
19290 (1+ org-self-insert-command-undo-counter))))))))
19292 (defun org-check-before-invisible-edit (kind)
19293 "Check is editing if kind KIND would be dangerous with invisible text around.
19294 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19295 ;; First, try to get out of here as quickly as possible, to reduce overhead
19296 (when (and org-catch-invisible-edits
19297 (or (not (boundp 'visible-mode)) (not visible-mode))
19298 (or (get-char-property (point) 'invisible)
19299 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19300 ;; OK, we need to take a closer look. Do not consider
19301 ;; invisibility obtained through text properties (e.g., link
19302 ;; fontification), as it cannot be toggled.
19303 (let* ((invisible-at-point
19304 (pcase (get-char-property-and-overlay (point) 'invisible)
19305 (`(,_ . ,(and (pred overlayp) o)) o)))
19306 ;; Assume that point cannot land in the middle of an
19307 ;; overlay, or between two overlays.
19308 (invisible-before-point
19309 (and (not invisible-at-point)
19310 (not (bobp))
19311 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19312 (`(,_ . ,(and (pred overlayp) o)) o))))
19313 (border-and-ok-direction
19315 ;; Check if we are acting predictably before invisible
19316 ;; text.
19317 (and invisible-at-point
19318 (memq kind '(insert delete-backward)))
19319 ;; Check if we are acting predictably after invisible text
19320 ;; This works not well, and I have turned it off. It seems
19321 ;; better to always show and stop after invisible text.
19322 ;; (and (not invisible-at-point) invisible-before-point
19323 ;; (memq kind '(insert delete)))
19325 (when (or invisible-at-point invisible-before-point)
19326 (when (eq org-catch-invisible-edits 'error)
19327 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19328 (if (and org-custom-properties-overlays
19329 (y-or-n-p "Display invisible properties in this buffer? "))
19330 (org-toggle-custom-properties-visibility)
19331 ;; Make the area visible
19332 (save-excursion
19333 (when invisible-before-point
19334 (goto-char
19335 (previous-single-char-property-change (point) 'invisible)))
19336 ;; Remove whatever overlay is currently making yet-to-be
19337 ;; edited text invisible. Also remove nested invisibility
19338 ;; related overlays.
19339 (delete-overlay (or invisible-at-point invisible-before-point))
19340 (let ((origin (if invisible-at-point (point) (1- (point)))))
19341 (while (pcase (get-char-property-and-overlay origin 'invisible)
19342 (`(,_ . ,(and (pred overlayp) o))
19343 (delete-overlay o)
19344 t)))))
19345 (cond
19346 ((eq org-catch-invisible-edits 'show)
19347 ;; That's it, we do the edit after showing
19348 (message
19349 "Unfolding invisible region around point before editing")
19350 (sit-for 1))
19351 ((and (eq org-catch-invisible-edits 'smart)
19352 border-and-ok-direction)
19353 (message "Unfolding invisible region around point before editing"))
19355 ;; Don't do the edit, make the user repeat it in full visibility
19356 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19358 (defun org-fix-tags-on-the-fly ()
19359 "Align tags in headline at point.
19360 Unlike `org-align-tags', this function does nothing if point is
19361 either not currently on a tagged headline or on a tag."
19362 (when (and (org-match-line org-tag-line-re)
19363 (< (point) (match-beginning 1)))
19364 (org-align-tags)))
19366 (defun org-delete-backward-char (N)
19367 "Like `delete-backward-char', insert whitespace at field end in tables.
19368 When deleting backwards, in tables this function will insert whitespace in
19369 front of the next \"|\" separator, to keep the table aligned. The table will
19370 still be marked for re-alignment if the field did fill the entire column,
19371 because, in this case the deletion might narrow the column."
19372 (interactive "p")
19373 (save-match-data
19374 (org-check-before-invisible-edit 'delete-backward)
19375 (if (and (= N 1)
19376 (not overwrite-mode)
19377 (not (org-region-active-p))
19378 (not (eq (char-before) ?|))
19379 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19380 (looking-at-p ".*?|")
19381 (org-at-table-p))
19382 (progn (forward-char -1) (org-delete-char 1))
19383 (backward-delete-char N)
19384 (org-fix-tags-on-the-fly))))
19386 (defun org-delete-char (N)
19387 "Like `delete-char', but insert whitespace at field end in tables.
19388 When deleting characters, in tables this function will insert whitespace in
19389 front of the next \"|\" separator, to keep the table aligned. The table will
19390 still be marked for re-alignment if the field did fill the entire column,
19391 because, in this case the deletion might narrow the column."
19392 (interactive "p")
19393 (save-match-data
19394 (org-check-before-invisible-edit 'delete)
19395 (cond
19396 ((or (/= N 1)
19397 (eq (char-after) ?|)
19398 (save-excursion (skip-chars-backward " \t") (bolp))
19399 (not (org-at-table-p)))
19400 (delete-char N)
19401 (org-fix-tags-on-the-fly))
19402 ((looking-at ".\\(.*?\\)|")
19403 (let* ((update? org-table-may-need-update)
19404 (noalign (looking-at-p ".*? |")))
19405 (delete-char 1)
19406 (org-table-with-shrunk-field
19407 (save-excursion
19408 ;; Last space is `org-table-separator-space', so insert
19409 ;; a regular one before it instead.
19410 (goto-char (- (match-end 0) 2))
19411 (insert " ")))
19412 ;; If there were two spaces at the end, this field does not
19413 ;; determine the width of the column.
19414 (when noalign (setq org-table-may-need-update update?))))
19416 (delete-char N)))))
19418 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19419 (put 'org-self-insert-command 'delete-selection
19420 (lambda ()
19421 (not (run-hook-with-args-until-success
19422 'self-insert-uses-region-functions))))
19423 (put 'orgtbl-self-insert-command 'delete-selection
19424 (lambda ()
19425 (not (run-hook-with-args-until-success
19426 'self-insert-uses-region-functions))))
19427 (put 'org-delete-char 'delete-selection 'supersede)
19428 (put 'org-delete-backward-char 'delete-selection 'supersede)
19429 (put 'org-yank 'delete-selection 'yank)
19431 ;; Make `flyspell-mode' delay after some commands
19432 (put 'org-self-insert-command 'flyspell-delayed t)
19433 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19434 (put 'org-delete-char 'flyspell-delayed t)
19435 (put 'org-delete-backward-char 'flyspell-delayed t)
19437 ;; Make pabbrev-mode expand after Org mode commands
19438 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19439 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19441 (defun org-transpose-words ()
19442 "Transpose words for Org.
19443 This uses the `org-mode-transpose-word-syntax-table' syntax
19444 table, which interprets characters in `org-emphasis-alist' as
19445 word constituents."
19446 (interactive)
19447 (with-syntax-table org-mode-transpose-word-syntax-table
19448 (call-interactively 'transpose-words)))
19450 (defvar org-ctrl-c-ctrl-c-hook nil
19451 "Hook for functions attaching themselves to `C-c C-c'.
19453 This can be used to add additional functionality to the C-c C-c
19454 key which executes context-dependent commands. This hook is run
19455 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19456 run after the last test.
19458 Each function will be called with no arguments. The function
19459 must check if the context is appropriate for it to act. If yes,
19460 it should do its thing and then return a non-nil value. If the
19461 context is wrong, just do nothing and return nil.")
19463 (defvar org-ctrl-c-ctrl-c-final-hook nil
19464 "Hook for functions attaching themselves to `C-c C-c'.
19466 This can be used to add additional functionality to the C-c C-c
19467 key which executes context-dependent commands. This hook is run
19468 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19469 before the first test.
19471 Each function will be called with no arguments. The function
19472 must check if the context is appropriate for it to act. If yes,
19473 it should do its thing and then return a non-nil value. If the
19474 context is wrong, just do nothing and return nil.")
19476 (defvar org-tab-first-hook nil
19477 "Hook for functions to attach themselves to TAB.
19478 See `org-ctrl-c-ctrl-c-hook' for more information.
19479 This hook runs as the first action when TAB is pressed, even before
19480 `org-cycle' messes around with the `outline-regexp' to cater for
19481 inline tasks and plain list item folding.
19482 If any function in this hook returns t, any other actions that
19483 would have been caused by TAB (such as table field motion or visibility
19484 cycling) will not occur.")
19486 (defvar org-tab-after-check-for-table-hook nil
19487 "Hook for functions to attach themselves to TAB.
19488 See `org-ctrl-c-ctrl-c-hook' for more information.
19489 This hook runs after it has been established that the cursor is not in a
19490 table, but before checking if the cursor is in a headline or if global cycling
19491 should be done.
19492 If any function in this hook returns t, not other actions like visibility
19493 cycling will be done.")
19495 (defvar org-tab-after-check-for-cycling-hook nil
19496 "Hook for functions to attach themselves to TAB.
19497 See `org-ctrl-c-ctrl-c-hook' for more information.
19498 This hook runs after it has been established that not table field motion and
19499 not visibility should be done because of current context. This is probably
19500 the place where a package like yasnippets can hook in.")
19502 (defvar org-tab-before-tab-emulation-hook nil
19503 "Hook for functions to attach themselves to TAB.
19504 See `org-ctrl-c-ctrl-c-hook' for more information.
19505 This hook runs after every other options for TAB have been exhausted, but
19506 before indentation and \t insertion takes place.")
19508 (defvar org-metaleft-hook nil
19509 "Hook for functions attaching themselves to `M-left'.
19510 See `org-ctrl-c-ctrl-c-hook' for more information.")
19511 (defvar org-metaright-hook nil
19512 "Hook for functions attaching themselves to `M-right'.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.")
19514 (defvar org-metaup-hook nil
19515 "Hook for functions attaching themselves to `M-up'.
19516 See `org-ctrl-c-ctrl-c-hook' for more information.")
19517 (defvar org-metadown-hook nil
19518 "Hook for functions attaching themselves to `M-down'.
19519 See `org-ctrl-c-ctrl-c-hook' for more information.")
19520 (defvar org-shiftmetaleft-hook nil
19521 "Hook for functions attaching themselves to `M-S-left'.
19522 See `org-ctrl-c-ctrl-c-hook' for more information.")
19523 (defvar org-shiftmetaright-hook nil
19524 "Hook for functions attaching themselves to `M-S-right'.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.")
19526 (defvar org-shiftmetaup-hook nil
19527 "Hook for functions attaching themselves to `M-S-up'.
19528 See `org-ctrl-c-ctrl-c-hook' for more information.")
19529 (defvar org-shiftmetadown-hook nil
19530 "Hook for functions attaching themselves to `M-S-down'.
19531 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defvar org-metareturn-hook nil
19533 "Hook for functions attaching themselves to `M-RET'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-shiftup-hook nil
19536 "Hook for functions attaching themselves to `S-up'.
19537 See `org-ctrl-c-ctrl-c-hook' for more information.")
19538 (defvar org-shiftup-final-hook nil
19539 "Hook for functions attaching themselves to `S-up'.
19540 This one runs after all other options except shift-select have been excluded.
19541 See `org-ctrl-c-ctrl-c-hook' for more information.")
19542 (defvar org-shiftdown-hook nil
19543 "Hook for functions attaching themselves to `S-down'.
19544 See `org-ctrl-c-ctrl-c-hook' for more information.")
19545 (defvar org-shiftdown-final-hook nil
19546 "Hook for functions attaching themselves to `S-down'.
19547 This one runs after all other options except shift-select have been excluded.
19548 See `org-ctrl-c-ctrl-c-hook' for more information.")
19549 (defvar org-shiftleft-hook nil
19550 "Hook for functions attaching themselves to `S-left'.
19551 See `org-ctrl-c-ctrl-c-hook' for more information.")
19552 (defvar org-shiftleft-final-hook nil
19553 "Hook for functions attaching themselves to `S-left'.
19554 This one runs after all other options except shift-select have been excluded.
19555 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defvar org-shiftright-hook nil
19557 "Hook for functions attaching themselves to `S-right'.
19558 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defvar org-shiftright-final-hook nil
19560 "Hook for functions attaching themselves to `S-right'.
19561 This one runs after all other options except shift-select have been excluded.
19562 See `org-ctrl-c-ctrl-c-hook' for more information.")
19564 (defun org-modifier-cursor-error ()
19565 "Throw an error, a modified cursor command was applied in wrong context."
19566 (user-error "This command is active in special context like tables, headlines or items"))
19568 (defun org-shiftselect-error ()
19569 "Throw an error because Shift-Cursor command was applied in wrong context."
19570 (if (and (boundp 'shift-select-mode) shift-select-mode)
19571 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19572 (user-error "This command works only in special context like headlines or timestamps")))
19574 (defun org-call-for-shift-select (cmd)
19575 (let ((this-command-keys-shift-translated t))
19576 (call-interactively cmd)))
19578 (defun org-shifttab (&optional arg)
19579 "Global visibility cycling or move to previous table field.
19580 Call `org-table-previous-field' within a table.
19581 When ARG is nil, cycle globally through visibility states.
19582 When ARG is a numeric prefix, show contents of this level."
19583 (interactive "P")
19584 (cond
19585 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19586 ((integerp arg)
19587 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19588 (message "Content view to level: %d" arg)
19589 (org-content (prefix-numeric-value arg2))
19590 (org-cycle-show-empty-lines t)
19591 (setq org-cycle-global-status 'overview)))
19592 (t (call-interactively 'org-global-cycle))))
19594 (defun org-shiftmetaleft ()
19595 "Promote subtree or delete table column.
19596 Calls `org-promote-subtree', `org-outdent-item-tree', or
19597 `org-table-delete-column', depending on context. See the
19598 individual commands for more information."
19599 (interactive)
19600 (cond
19601 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19602 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19603 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19604 ((if (not (org-region-active-p)) (org-at-item-p)
19605 (save-excursion (goto-char (region-beginning))
19606 (org-at-item-p)))
19607 (call-interactively 'org-outdent-item-tree))
19608 (t (org-modifier-cursor-error))))
19610 (defun org-shiftmetaright ()
19611 "Demote subtree or insert table column.
19612 Calls `org-demote-subtree', `org-indent-item-tree', or
19613 `org-table-insert-column', depending on context. See the
19614 individual commands for more information."
19615 (interactive)
19616 (cond
19617 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19618 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19619 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19620 ((if (not (org-region-active-p)) (org-at-item-p)
19621 (save-excursion (goto-char (region-beginning))
19622 (org-at-item-p)))
19623 (call-interactively 'org-indent-item-tree))
19624 (t (org-modifier-cursor-error))))
19626 (defun org-shiftmetaup (&optional _arg)
19627 "Drag the line at point up.
19628 In a table, kill the current row.
19629 On a clock timestamp, update the value of the timestamp like `S-<up>'
19630 but also adjust the previous clocked item in the clock history.
19631 Everywhere else, drag the line at point up."
19632 (interactive "P")
19633 (cond
19634 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19635 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19636 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19637 (call-interactively 'org-timestamp-up)))
19638 (t (call-interactively 'org-drag-line-backward))))
19640 (defun org-shiftmetadown (&optional _arg)
19641 "Drag the line at point down.
19642 In a table, insert an empty row at the current line.
19643 On a clock timestamp, update the value of the timestamp like `S-<down>'
19644 but also adjust the previous clocked item in the clock history.
19645 Everywhere else, drag the line at point down."
19646 (interactive "P")
19647 (cond
19648 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19649 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19650 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19651 (call-interactively 'org-timestamp-down)))
19652 (t (call-interactively 'org-drag-line-forward))))
19654 (defsubst org-hidden-tree-error ()
19655 (user-error
19656 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19658 (defun org-metaleft (&optional _arg)
19659 "Promote heading, list item at point or move table column left.
19661 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19662 depending on context. With no specific context, calls the Emacs
19663 default `backward-word'. See the individual commands for more
19664 information.
19666 This function runs the hook `org-metaleft-hook' as a first step,
19667 and returns at first non-nil value."
19668 (interactive "P")
19669 (cond
19670 ((run-hook-with-args-until-success 'org-metaleft-hook))
19671 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19672 ((org-with-limited-levels
19673 (or (org-at-heading-p)
19674 (and (org-region-active-p)
19675 (save-excursion
19676 (goto-char (region-beginning))
19677 (org-at-heading-p)))))
19678 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19679 (call-interactively 'org-do-promote))
19680 ;; At an inline task.
19681 ((org-at-heading-p)
19682 (call-interactively 'org-inlinetask-promote))
19683 ((or (org-at-item-p)
19684 (and (org-region-active-p)
19685 (save-excursion
19686 (goto-char (region-beginning))
19687 (org-at-item-p))))
19688 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19689 (call-interactively 'org-outdent-item))
19690 (t (call-interactively 'backward-word))))
19692 (defun org-metaright (&optional _arg)
19693 "Demote heading, list item at point or move table column right.
19695 In front of a drawer or a block keyword, indent it correctly.
19697 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19698 `org-indent-drawer' or `org-indent-block' depending on context.
19699 With no specific context, calls the Emacs default `forward-word'.
19700 See the individual commands for more information.
19702 This function runs the hook `org-metaright-hook' as a first step,
19703 and returns at first non-nil value."
19704 (interactive "P")
19705 (cond
19706 ((run-hook-with-args-until-success 'org-metaright-hook))
19707 ((org-at-table-p) (call-interactively 'org-table-move-column))
19708 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19709 ((org-at-block-p) (call-interactively 'org-indent-block))
19710 ((org-with-limited-levels
19711 (or (org-at-heading-p)
19712 (and (org-region-active-p)
19713 (save-excursion
19714 (goto-char (region-beginning))
19715 (org-at-heading-p)))))
19716 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19717 (call-interactively 'org-do-demote))
19718 ;; At an inline task.
19719 ((org-at-heading-p)
19720 (call-interactively 'org-inlinetask-demote))
19721 ((or (org-at-item-p)
19722 (and (org-region-active-p)
19723 (save-excursion
19724 (goto-char (region-beginning))
19725 (org-at-item-p))))
19726 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19727 (call-interactively 'org-indent-item))
19728 (t (call-interactively 'forward-word))))
19730 (defun org-check-for-hidden (what)
19731 "Check if there are hidden headlines/items in the current visual line.
19732 WHAT can be either `headlines' or `items'. If the current line is
19733 an outline or item heading and it has a folded subtree below it,
19734 this function returns t, nil otherwise."
19735 (let ((re (cond
19736 ((eq what 'headlines) org-outline-regexp-bol)
19737 ((eq what 'items) (org-item-beginning-re))
19738 (t (error "This should not happen"))))
19739 beg end)
19740 (save-excursion
19741 (catch 'exit
19742 (unless (org-region-active-p)
19743 (setq beg (point-at-bol))
19744 (beginning-of-line 2)
19745 (while (and (not (eobp)) ;; this is like `next-line'
19746 (get-char-property (1- (point)) 'invisible))
19747 (beginning-of-line 2))
19748 (setq end (point))
19749 (goto-char beg)
19750 (goto-char (point-at-eol))
19751 (setq end (max end (point)))
19752 (while (re-search-forward re end t)
19753 (when (get-char-property (match-beginning 0) 'invisible)
19754 (throw 'exit t))))
19755 nil))))
19757 (defun org-metaup (&optional _arg)
19758 "Move subtree up or move table row up.
19759 Calls `org-move-subtree-up' or `org-table-move-row' or
19760 `org-move-item-up', depending on context. See the individual commands
19761 for more information."
19762 (interactive "P")
19763 (cond
19764 ((run-hook-with-args-until-success 'org-metaup-hook))
19765 ((org-region-active-p)
19766 (let* ((a (save-excursion
19767 (goto-char (min (region-beginning) (region-end)))
19768 (line-beginning-position)))
19769 (b (save-excursion
19770 (goto-char (max (region-beginning) (region-end)))
19771 (if (bolp) (1- (point)) (line-end-position))))
19772 (c (save-excursion
19773 (goto-char a)
19774 (move-beginning-of-line 0)
19775 (point)))
19776 (d (save-excursion
19777 (goto-char a)
19778 (move-end-of-line 0)
19779 (point))))
19780 (transpose-regions a b c d)
19781 (goto-char c)))
19782 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19783 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19784 ((org-at-item-p) (call-interactively 'org-move-item-up))
19785 (t (org-drag-element-backward))))
19787 (defun org-metadown (&optional _arg)
19788 "Move subtree down or move table row down.
19789 Calls `org-move-subtree-down' or `org-table-move-row' or
19790 `org-move-item-down', depending on context. See the individual
19791 commands for more information."
19792 (interactive "P")
19793 (cond
19794 ((run-hook-with-args-until-success 'org-metadown-hook))
19795 ((org-region-active-p)
19796 (let* ((a (save-excursion
19797 (goto-char (min (region-beginning) (region-end)))
19798 (line-beginning-position)))
19799 (b (save-excursion
19800 (goto-char (max (region-beginning) (region-end)))
19801 (if (bolp) (1- (point)) (line-end-position))))
19802 (c (save-excursion
19803 (goto-char b)
19804 (move-beginning-of-line (if (bolp) 1 2))
19805 (point)))
19806 (d (save-excursion
19807 (goto-char b)
19808 (move-end-of-line (if (bolp) 1 2))
19809 (point))))
19810 (transpose-regions a b c d)
19811 (goto-char d)))
19812 ((org-at-table-p) (call-interactively 'org-table-move-row))
19813 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19814 ((org-at-item-p) (call-interactively 'org-move-item-down))
19815 (t (org-drag-element-forward))))
19817 (defun org-shiftup (&optional arg)
19818 "Increase item in timestamp or increase priority of current headline.
19819 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19820 depending on context. See the individual commands for more information."
19821 (interactive "P")
19822 (cond
19823 ((run-hook-with-args-until-success 'org-shiftup-hook))
19824 ((and org-support-shift-select (org-region-active-p))
19825 (org-call-for-shift-select 'previous-line))
19826 ((org-at-timestamp-p 'lax)
19827 (call-interactively (if org-edit-timestamp-down-means-later
19828 'org-timestamp-down 'org-timestamp-up)))
19829 ((and (not (eq org-support-shift-select 'always))
19830 org-enable-priority-commands
19831 (org-at-heading-p))
19832 (call-interactively 'org-priority-up))
19833 ((and (not org-support-shift-select) (org-at-item-p))
19834 (call-interactively 'org-previous-item))
19835 ((org-clocktable-try-shift 'up arg))
19836 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19837 (org-support-shift-select
19838 (org-call-for-shift-select 'previous-line))
19839 (t (org-shiftselect-error))))
19841 (defun org-shiftdown (&optional arg)
19842 "Decrease item in timestamp or decrease priority of current headline.
19843 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19844 depending on context. See the individual commands for more information."
19845 (interactive "P")
19846 (cond
19847 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19848 ((and org-support-shift-select (org-region-active-p))
19849 (org-call-for-shift-select 'next-line))
19850 ((org-at-timestamp-p 'lax)
19851 (call-interactively (if org-edit-timestamp-down-means-later
19852 'org-timestamp-up 'org-timestamp-down)))
19853 ((and (not (eq org-support-shift-select 'always))
19854 org-enable-priority-commands
19855 (org-at-heading-p))
19856 (call-interactively 'org-priority-down))
19857 ((and (not org-support-shift-select) (org-at-item-p))
19858 (call-interactively 'org-next-item))
19859 ((org-clocktable-try-shift 'down arg))
19860 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19861 (org-support-shift-select
19862 (org-call-for-shift-select 'next-line))
19863 (t (org-shiftselect-error))))
19865 (defun org-shiftright (&optional arg)
19866 "Cycle the thing at point or in the current line, depending on context.
19867 Depending on context, this does one of the following:
19869 - switch a timestamp at point one day into the future
19870 - on a headline, switch to the next TODO keyword.
19871 - on an item, switch entire list to the next bullet type
19872 - on a property line, switch to the next allowed value
19873 - on a clocktable definition line, move time block into the future"
19874 (interactive "P")
19875 (cond
19876 ((run-hook-with-args-until-success 'org-shiftright-hook))
19877 ((and org-support-shift-select (org-region-active-p))
19878 (org-call-for-shift-select 'forward-char))
19879 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19880 ((and (not (eq org-support-shift-select 'always))
19881 (org-at-heading-p))
19882 (let ((org-inhibit-logging
19883 (not org-treat-S-cursor-todo-selection-as-state-change))
19884 (org-inhibit-blocking
19885 (not org-treat-S-cursor-todo-selection-as-state-change)))
19886 (org-call-with-arg 'org-todo 'right)))
19887 ((or (and org-support-shift-select
19888 (not (eq org-support-shift-select 'always))
19889 (org-at-item-bullet-p))
19890 (and (not org-support-shift-select) (org-at-item-p)))
19891 (org-call-with-arg 'org-cycle-list-bullet nil))
19892 ((and (not (eq org-support-shift-select 'always))
19893 (org-at-property-p))
19894 (call-interactively 'org-property-next-allowed-value))
19895 ((org-clocktable-try-shift 'right arg))
19896 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19897 (org-support-shift-select
19898 (org-call-for-shift-select 'forward-char))
19899 (t (org-shiftselect-error))))
19901 (defun org-shiftleft (&optional arg)
19902 "Cycle the thing at point or in the current line, depending on context.
19903 Depending on context, this does one of the following:
19905 - switch a timestamp at point one day into the past
19906 - on a headline, switch to the previous TODO keyword.
19907 - on an item, switch entire list to the previous bullet type
19908 - on a property line, switch to the previous allowed value
19909 - on a clocktable definition line, move time block into the past"
19910 (interactive "P")
19911 (cond
19912 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19913 ((and org-support-shift-select (org-region-active-p))
19914 (org-call-for-shift-select 'backward-char))
19915 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19916 ((and (not (eq org-support-shift-select 'always))
19917 (org-at-heading-p))
19918 (let ((org-inhibit-logging
19919 (not org-treat-S-cursor-todo-selection-as-state-change))
19920 (org-inhibit-blocking
19921 (not org-treat-S-cursor-todo-selection-as-state-change)))
19922 (org-call-with-arg 'org-todo 'left)))
19923 ((or (and org-support-shift-select
19924 (not (eq org-support-shift-select 'always))
19925 (org-at-item-bullet-p))
19926 (and (not org-support-shift-select) (org-at-item-p)))
19927 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19928 ((and (not (eq org-support-shift-select 'always))
19929 (org-at-property-p))
19930 (call-interactively 'org-property-previous-allowed-value))
19931 ((org-clocktable-try-shift 'left arg))
19932 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19933 (org-support-shift-select
19934 (org-call-for-shift-select 'backward-char))
19935 (t (org-shiftselect-error))))
19937 (defun org-shiftcontrolright ()
19938 "Switch to next TODO set."
19939 (interactive)
19940 (cond
19941 ((and org-support-shift-select (org-region-active-p))
19942 (org-call-for-shift-select 'forward-word))
19943 ((and (not (eq org-support-shift-select 'always))
19944 (org-at-heading-p))
19945 (org-call-with-arg 'org-todo 'nextset))
19946 (org-support-shift-select
19947 (org-call-for-shift-select 'forward-word))
19948 (t (org-shiftselect-error))))
19950 (defun org-shiftcontrolleft ()
19951 "Switch to previous TODO set."
19952 (interactive)
19953 (cond
19954 ((and org-support-shift-select (org-region-active-p))
19955 (org-call-for-shift-select 'backward-word))
19956 ((and (not (eq org-support-shift-select 'always))
19957 (org-at-heading-p))
19958 (org-call-with-arg 'org-todo 'previousset))
19959 (org-support-shift-select
19960 (org-call-for-shift-select 'backward-word))
19961 (t (org-shiftselect-error))))
19963 (defun org-shiftcontrolup (&optional n)
19964 "Change timestamps synchronously up in CLOCK log lines.
19965 Optional argument N tells to change by that many units."
19966 (interactive "P")
19967 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19968 (let (org-support-shift-select)
19969 (org-clock-timestamps-up n))
19970 (user-error "Not at a clock log")))
19972 (defun org-shiftcontroldown (&optional n)
19973 "Change timestamps synchronously down in CLOCK log lines.
19974 Optional argument N tells to change by that many units."
19975 (interactive "P")
19976 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19977 (let (org-support-shift-select)
19978 (org-clock-timestamps-down n))
19979 (user-error "Not at a clock log")))
19981 (defun org-increase-number-at-point (&optional inc)
19982 "Increment the number at point.
19983 With an optional prefix numeric argument INC, increment using
19984 this numeric value."
19985 (interactive "p")
19986 (if (not (number-at-point))
19987 (user-error "Not on a number")
19988 (unless inc (setq inc 1))
19989 (let ((pos (point))
19990 (beg (skip-chars-backward "-+^/*0-9eE."))
19991 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
19992 (setq nap (buffer-substring-no-properties
19993 (+ pos beg) (+ pos beg end)))
19994 (delete-region (+ pos beg) (+ pos beg end))
19995 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
19996 (when (org-at-table-p)
19997 (org-table-align)
19998 (org-table-end-of-field 1))))
20000 (defun org-decrease-number-at-point (&optional inc)
20001 "Decrement the number at point.
20002 With an optional prefix numeric argument INC, decrement using
20003 this numeric value."
20004 (interactive "p")
20005 (org-increase-number-at-point (- (or inc 1))))
20007 (defun org-ctrl-c-ret ()
20008 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20009 (interactive)
20010 (cond
20011 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20012 (t (call-interactively 'org-insert-heading))))
20014 (defun org-find-visible ()
20015 (let ((s (point)))
20016 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20017 (get-char-property s 'invisible)))
20019 (defun org-find-invisible ()
20020 (let ((s (point)))
20021 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20022 (not (get-char-property s 'invisible))))
20025 (defun org-copy-visible (beg end)
20026 "Copy the visible parts of the region."
20027 (interactive "r")
20028 (let ((result ""))
20029 (while (/= beg end)
20030 (when (get-char-property beg 'invisible)
20031 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20032 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20033 (setq result (concat result (buffer-substring beg next)))
20034 (setq beg next)))
20035 (setq deactivate-mark t)
20036 (kill-new result)
20037 (message "Visible strings have been copied to the kill ring.")))
20039 (defun org-copy-special ()
20040 "Copy region in table or copy current subtree.
20041 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20042 context. See the individual commands for more information."
20043 (interactive)
20044 (call-interactively
20045 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20047 (defun org-cut-special ()
20048 "Cut region in table or cut current subtree.
20049 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20050 context. See the individual commands for more information."
20051 (interactive)
20052 (call-interactively
20053 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20055 (defun org-paste-special (arg)
20056 "Paste rectangular region into table, or past subtree relative to level.
20057 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20058 See the individual commands for more information."
20059 (interactive "P")
20060 (if (org-at-table-p)
20061 (org-table-paste-rectangle)
20062 (org-paste-subtree arg)))
20064 (defun org-edit-special (&optional arg)
20065 "Call a special editor for the element at point.
20066 When at a table, call the formula editor with `org-table-edit-formulas'.
20067 When in a source code block, call `org-edit-src-code'.
20068 When in a fixed-width region, call `org-edit-fixed-width-region'.
20069 When in an export block, call `org-edit-export-block'.
20070 When in a LaTeX environment, call `org-edit-latex-environment'.
20071 When at an #+INCLUDE keyword, visit the included file.
20072 When at a footnote reference, call `org-edit-footnote-reference'.
20073 When at a planning line call, `org-deadline' and/or `org-schedule'.
20074 When at an active timestamp, call `org-time-stamp'.
20075 When at an inactive timestamp, call `org-time-stamp-inactive'.
20076 On a link, call `ffap' to visit the link at point.
20077 Otherwise, return a user error."
20078 (interactive "P")
20079 (let ((element (org-element-at-point)))
20080 (barf-if-buffer-read-only)
20081 (pcase (org-element-type element)
20082 (`src-block
20083 (if (not arg) (org-edit-src-code)
20084 (let* ((info (org-babel-get-src-block-info))
20085 (lang (nth 0 info))
20086 (params (nth 2 info))
20087 (session (cdr (assq :session params))))
20088 (if (not session) (org-edit-src-code)
20089 ;; At a source block with a session and function called
20090 ;; with an ARG: switch to the buffer related to the
20091 ;; inferior process.
20092 (switch-to-buffer
20093 (funcall (intern (concat "org-babel-prep-session:" lang))
20094 session params))))))
20095 (`keyword
20096 (unless (member (org-element-property :key element)
20097 '("INCLUDE" "SETUPFILE"))
20098 (user-error "No special environment to edit here"))
20099 (org-open-link-from-string
20100 (format "[[%s]]"
20101 (expand-file-name
20102 (let ((value (org-strip-quotes
20103 (org-element-property :value element))))
20104 (cond
20105 ((not (org-string-nw-p value))
20106 (user-error "No file to edit"))
20107 ((org-file-url-p value)
20108 (user-error "Files located with a URL cannot be edited"))
20109 (t value)))))))
20110 (`table
20111 (if (eq (org-element-property :type element) 'table.el)
20112 (org-edit-table.el)
20113 (call-interactively 'org-table-edit-formulas)))
20114 ;; Only Org tables contain `table-row' type elements.
20115 (`table-row (call-interactively 'org-table-edit-formulas))
20116 (`example-block (org-edit-src-code))
20117 (`export-block (org-edit-export-block))
20118 (`fixed-width (org-edit-fixed-width-region))
20119 (`latex-environment (org-edit-latex-environment))
20120 (`planning
20121 (let ((proplist (cadr element)))
20122 (mapc #'call-interactively
20123 (remq nil
20124 (list
20125 (when (plist-get proplist :deadline) #'org-deadline)
20126 (when (plist-get proplist :scheduled) #'org-schedule))))))
20128 ;; No notable element at point. Though, we may be at a link or
20129 ;; a footnote reference, which are objects. Thus, scan deeper.
20130 (let ((context (org-element-context element)))
20131 (pcase (org-element-type context)
20132 (`footnote-reference (org-edit-footnote-reference))
20133 (`inline-src-block (org-edit-inline-src-code))
20134 (`timestamp (if (eq 'inactive (org-element-property :type context))
20135 (call-interactively #'org-time-stamp-inactive)
20136 (call-interactively #'org-time-stamp)))
20137 (`link (call-interactively #'ffap))
20138 (_ (user-error "No special environment to edit here"))))))))
20140 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20141 (defun org-ctrl-c-ctrl-c (&optional arg)
20142 "Set tags in headline, or update according to changed information at point.
20144 This command does many different things, depending on context:
20146 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20147 this is what we do.
20149 - If the cursor is on a statistics cookie, update it.
20151 - If the cursor is in a headline, prompt for tags and insert them
20152 into the current line, aligned to `org-tags-column'. When called
20153 with prefix arg, realign all tags in the current buffer.
20155 - If the cursor is in one of the special #+KEYWORD lines, this
20156 triggers scanning the buffer for these lines and updating the
20157 information.
20159 - If the cursor is inside a table, realign the table. This command
20160 works even if the automatic table editor has been turned off.
20162 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20163 the entire table.
20165 - If the cursor is at a footnote reference or definition, jump to
20166 the corresponding definition or references, respectively.
20168 - If the cursor is a the beginning of a dynamic block, update it.
20170 - If the current buffer is a capture buffer, close note and file it.
20172 - If the cursor is on a <<<target>>>, update radio targets and
20173 corresponding links in this buffer.
20175 - If the cursor is on a numbered item in a plain list, renumber the
20176 ordered list.
20178 - If the cursor is on a checkbox, toggle it.
20180 - If the cursor is on a code block, evaluate it. The variable
20181 `org-confirm-babel-evaluate' can be used to control prompting
20182 before code block evaluation, by default every code block
20183 evaluation requires confirmation. Code block evaluation can be
20184 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20185 (interactive "P")
20186 (cond
20187 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20188 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20189 (org-remove-occur-highlights)
20190 (message "Temporary highlights/overlays removed from current buffer"))
20191 ((and (local-variable-p 'org-finish-function)
20192 (fboundp org-finish-function))
20193 (funcall org-finish-function))
20194 ((org-babel-hash-at-point))
20195 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20197 (let* ((context
20198 (org-element-lineage
20199 (org-element-context)
20200 ;; Limit to supported contexts.
20201 '(babel-call clock dynamic-block footnote-definition
20202 footnote-reference inline-babel-call inline-src-block
20203 inlinetask item keyword node-property paragraph
20204 plain-list planning property-drawer radio-target
20205 src-block statistics-cookie table table-cell table-row
20206 timestamp)
20208 (type (org-element-type context)))
20209 ;; For convenience: at the first line of a paragraph on the same
20210 ;; line as an item, apply function on that item instead.
20211 (when (eq type 'paragraph)
20212 (let ((parent (org-element-property :parent context)))
20213 (when (and (eq (org-element-type parent) 'item)
20214 (= (line-beginning-position)
20215 (org-element-property :begin parent)))
20216 (setq context parent)
20217 (setq type 'item))))
20218 ;; Act according to type of element or object at point.
20220 ;; Do nothing on a blank line, except if it is contained in
20221 ;; a source block. Hence, we first check if point is in such
20222 ;; a block and then if it is at a blank line.
20223 (pcase type
20224 ((or `inline-src-block `src-block)
20225 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20226 (org-babel-eval-wipe-error-buffer)
20227 (org-babel-execute-src-block
20228 current-prefix-arg (org-babel-get-src-block-info nil context))))
20229 ((guard (org-match-line "[ \t]*$"))
20230 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20231 (user-error
20232 (substitute-command-keys
20233 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20234 ((or `babel-call `inline-babel-call)
20235 (let ((info (org-babel-lob-get-info context)))
20236 (when info (org-babel-execute-src-block nil info))))
20237 (`clock (org-clock-update-time-maybe))
20238 (`dynamic-block
20239 (save-excursion
20240 (goto-char (org-element-property :post-affiliated context))
20241 (org-update-dblock)))
20242 (`footnote-definition
20243 (goto-char (org-element-property :post-affiliated context))
20244 (call-interactively 'org-footnote-action))
20245 (`footnote-reference (call-interactively #'org-footnote-action))
20246 ((or `headline `inlinetask)
20247 (save-excursion (goto-char (org-element-property :begin context))
20248 (call-interactively #'org-set-tags-command)))
20249 (`item
20250 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20251 ;; unconditionally, whereas `C-u' will toggle its presence.
20252 ;; Without a universal argument, if the item has a checkbox,
20253 ;; toggle it. Otherwise repair the list.
20254 (let* ((box (org-element-property :checkbox context))
20255 (struct (org-element-property :structure context))
20256 (old-struct (copy-tree struct))
20257 (parents (org-list-parents-alist struct))
20258 (prevs (org-list-prevs-alist struct))
20259 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20260 (org-list-set-checkbox
20261 (org-element-property :begin context) struct
20262 (cond ((equal arg '(16)) "[-]")
20263 ((and (not box) (equal arg '(4))) "[ ]")
20264 ((or (not box) (equal arg '(4))) nil)
20265 ((eq box 'on) "[ ]")
20266 (t "[X]")))
20267 ;; Mimic `org-list-write-struct' but with grabbing a return
20268 ;; value from `org-list-struct-fix-box'.
20269 (org-list-struct-fix-ind struct parents 2)
20270 (org-list-struct-fix-item-end struct)
20271 (org-list-struct-fix-bul struct prevs)
20272 (org-list-struct-fix-ind struct parents)
20273 (let ((block-item
20274 (org-list-struct-fix-box struct parents prevs orderedp)))
20275 (if (and box (equal struct old-struct))
20276 (if (equal arg '(16))
20277 (message "Checkboxes already reset")
20278 (user-error "Cannot toggle this checkbox: %s"
20279 (if (eq box 'on)
20280 "all subitems checked"
20281 "unchecked subitems")))
20282 (org-list-struct-apply-struct struct old-struct)
20283 (org-update-checkbox-count-maybe))
20284 (when block-item
20285 (message "Checkboxes were removed due to empty box at line %d"
20286 (org-current-line block-item))))))
20287 (`keyword
20288 (let ((org-inhibit-startup-visibility-stuff t)
20289 (org-startup-align-all-tables nil))
20290 (when (boundp 'org-table-coordinate-overlays)
20291 (mapc #'delete-overlay org-table-coordinate-overlays)
20292 (setq org-table-coordinate-overlays nil))
20293 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20294 (message "Local setup has been refreshed"))
20295 (`plain-list
20296 ;; At a plain list, with a double C-u argument, set
20297 ;; checkboxes of each item to "[-]", whereas a single one
20298 ;; will toggle their presence according to the state of the
20299 ;; first item in the list. Without an argument, repair the
20300 ;; list.
20301 (let* ((begin (org-element-property :contents-begin context))
20302 (struct (org-element-property :structure context))
20303 (old-struct (copy-tree struct))
20304 (first-box (save-excursion
20305 (goto-char begin)
20306 (looking-at org-list-full-item-re)
20307 (match-string-no-properties 3)))
20308 (new-box (cond ((equal arg '(16)) "[-]")
20309 ((equal arg '(4)) (unless first-box "[ ]"))
20310 ((equal first-box "[X]") "[ ]")
20311 (t "[X]"))))
20312 (cond
20313 (arg
20314 (dolist (pos
20315 (org-list-get-all-items
20316 begin struct (org-list-prevs-alist struct)))
20317 (org-list-set-checkbox pos struct new-box)))
20318 ((and first-box (eq (point) begin))
20319 ;; For convenience, when point is at bol on the first
20320 ;; item of the list and no argument is provided, simply
20321 ;; toggle checkbox of that item, if any.
20322 (org-list-set-checkbox begin struct new-box)))
20323 (when (equal
20324 (org-list-write-struct
20325 struct (org-list-parents-alist struct) old-struct)
20326 old-struct)
20327 (message "Cannot update this checkbox"))
20328 (org-update-checkbox-count-maybe)))
20329 ((or `property-drawer `node-property)
20330 (call-interactively #'org-property-action))
20331 (`radio-target
20332 (call-interactively #'org-update-radio-target-regexp))
20333 (`statistics-cookie
20334 (call-interactively #'org-update-statistics-cookies))
20335 ((or `table `table-cell `table-row)
20336 ;; At a table, recalculate every field and align it. Also
20337 ;; send the table if necessary. If the table has
20338 ;; a `table.el' type, just give up. At a table row or cell,
20339 ;; maybe recalculate line but always align table.
20340 (if (eq (org-element-property :type context) 'table.el)
20341 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20342 Use `\\[org-edit-special]' to edit table.el tables"))
20343 (if (or (eq type 'table)
20344 ;; Check if point is at a TBLFM line.
20345 (and (eq type 'table-row)
20346 (= (point) (org-element-property :end context))))
20347 (save-excursion
20348 (if (org-at-TBLFM-p)
20349 (progn (require 'org-table)
20350 (org-table-calc-current-TBLFM))
20351 (goto-char (org-element-property :contents-begin context))
20352 (org-call-with-arg 'org-table-recalculate (or arg t))
20353 (orgtbl-send-table 'maybe)))
20354 (org-table-maybe-eval-formula)
20355 (cond (arg (call-interactively #'org-table-recalculate))
20356 ((org-table-maybe-recalculate-line))
20357 (t (org-table-align))))))
20358 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20359 (org-timestamp-change 0 'day))
20360 ((and `nil (guard (org-at-heading-p)))
20361 ;; When point is on an unsupported object type, we can miss
20362 ;; the fact that it also is at a heading. Handle it here.
20363 (call-interactively #'org-set-tags-command))
20364 ((guard
20365 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20367 (user-error
20368 (substitute-command-keys
20369 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20371 (defun org-mode-restart ()
20372 (interactive)
20373 (let ((indent-status (bound-and-true-p org-indent-mode)))
20374 (funcall major-mode)
20375 (hack-local-variables)
20376 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20377 (org-indent-mode -1))
20378 (org-reset-file-cache))
20379 (message "%s restarted" major-mode))
20381 (defun org-kill-note-or-show-branches ()
20382 "Abort storing current note, or call `outline-show-branches'."
20383 (interactive)
20384 (if (not org-finish-function)
20385 (save-excursion
20386 (save-restriction
20387 (org-narrow-to-subtree)
20388 (org-flag-subtree t)
20389 (call-interactively 'outline-show-branches)
20390 (org-hide-archived-subtrees (point-min) (point-max))))
20391 (let ((org-note-abort t))
20392 (funcall org-finish-function))))
20394 (defun org-delete-indentation (&optional arg)
20395 "Join current line to previous and fix whitespace at join.
20397 If previous line is a headline add to headline title. Otherwise
20398 the function calls `delete-indentation'.
20400 With a non-nil optional argument, join it to the following one."
20401 (interactive "*P")
20402 (if (save-excursion
20403 (beginning-of-line (if arg 1 0))
20404 (let ((case-fold-search nil))
20405 (looking-at org-complex-heading-regexp)))
20406 ;; At headline.
20407 (let ((tags-column (when (match-beginning 5)
20408 (save-excursion (goto-char (match-beginning 5))
20409 (current-column))))
20410 (string (concat " " (progn (when arg (forward-line 1))
20411 (org-trim (delete-and-extract-region
20412 (line-beginning-position)
20413 (line-end-position)))))))
20414 (unless (bobp) (delete-region (point) (1- (point))))
20415 (goto-char (or (match-end 4)
20416 (match-beginning 5)
20417 (match-end 0)))
20418 (skip-chars-backward " \t")
20419 (save-excursion (insert string))
20420 ;; Adjust alignment of tags.
20421 (cond
20422 ((not tags-column)) ;no tags
20423 (org-auto-align-tags (org-align-tags))
20424 (t (org--align-tags-here tags-column)))) ;preserve tags column
20425 (delete-indentation arg)))
20427 (defun org-open-line (n)
20428 "Insert a new row in tables, call `open-line' elsewhere.
20429 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20430 As a special case, when a document starts with a table, allow to
20431 call `open-line' on the very first character."
20432 (interactive "*p")
20433 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20434 (org-table-insert-row)
20435 (open-line n)))
20437 (defun org-return (&optional indent)
20438 "Goto next table row or insert a newline.
20440 Calls `org-table-next-row' or `newline', depending on context.
20442 When optional INDENT argument is non-nil, call
20443 `newline-and-indent' instead of `newline'.
20445 When `org-return-follows-link' is non-nil and point is on
20446 a timestamp or a link, call `org-open-at-point'. However, it
20447 will not happen if point is in a table or on a \"dead\"
20448 object (e.g., within a comment). In these case, you need to use
20449 `org-open-at-point' directly."
20450 (interactive)
20451 (let ((context (if org-return-follows-link (org-element-context)
20452 (org-element-at-point))))
20453 (cond
20454 ;; In a table, call `org-table-next-row'. However, before first
20455 ;; column or after last one, split the table.
20456 ((or (and (eq 'table (org-element-type context))
20457 (not (eq 'table.el (org-element-property :type context)))
20458 (>= (point) (org-element-property :contents-begin context))
20459 (< (point) (org-element-property :contents-end context)))
20460 (org-element-lineage context '(table-row table-cell) t))
20461 (if (or (looking-at-p "[ \t]*$")
20462 (save-excursion (skip-chars-backward " \t") (bolp)))
20463 (insert "\n")
20464 (org-table-justify-field-maybe)
20465 (call-interactively #'org-table-next-row)))
20466 ;; On a link or a timestamp, call `org-open-at-point' if
20467 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20468 ;; locations, e.g., in a comment, as `org-open-at-point'.
20469 ((and org-return-follows-link
20470 (or (and (eq 'link (org-element-type context))
20471 ;; Ensure point is not on the white spaces after
20472 ;; the link.
20473 (let ((origin (point)))
20474 (org-with-point-at (org-element-property :end context)
20475 (skip-chars-backward " \t")
20476 (> (point) origin))))
20477 (org-in-regexp org-ts-regexp-both nil t)
20478 (org-in-regexp org-tsr-regexp-both nil t)
20479 (org-in-regexp org-any-link-re nil t)))
20480 (call-interactively #'org-open-at-point))
20481 ;; Insert newline in heading, but preserve tags.
20482 ((and (not (bolp))
20483 (let ((case-fold-search nil))
20484 (org-match-line org-complex-heading-regexp)))
20485 ;; At headline. Split line. However, if point is on keyword,
20486 ;; priority cookie or tags, do not break any of them: add
20487 ;; a newline after the headline instead.
20488 (let ((tags-column (and (match-beginning 5)
20489 (save-excursion (goto-char (match-beginning 5))
20490 (current-column))))
20491 (string
20492 (when (and (match-end 4) (org-point-in-group (point) 4))
20493 (delete-and-extract-region (point) (match-end 4)))))
20494 ;; Adjust tag alignment.
20495 (cond
20496 ((not (and tags-column string)))
20497 (org-auto-align-tags (org-align-tags))
20498 (t (org--align-tags-here tags-column))) ;preserve tags column
20499 (end-of-line)
20500 (org-show-entry)
20501 (if indent (newline-and-indent) (newline))
20502 (when string (save-excursion (insert (org-trim string))))))
20503 ;; In a list, make sure indenting keeps trailing text within.
20504 ((and indent
20505 (not (eolp))
20506 (org-element-lineage context '(item)))
20507 (let ((trailing-data
20508 (delete-and-extract-region (point) (line-end-position))))
20509 (newline-and-indent)
20510 (save-excursion (insert trailing-data))))
20512 ;; Do not auto-fill when point is in an Org property drawer.
20513 (let ((auto-fill-function (and (not (org-at-property-p))
20514 auto-fill-function)))
20515 (if indent
20516 (newline-and-indent)
20517 (newline)))))))
20519 (defun org-return-indent ()
20520 "Goto next table row or insert a newline and indent.
20521 Calls `org-table-next-row' or `newline-and-indent', depending on
20522 context. See the individual commands for more information."
20523 (interactive)
20524 (org-return t))
20526 (defun org-ctrl-c-tab (&optional _arg)
20527 "Toggle columns width in a table, or show children.
20528 Call `org-table-toggle-column-width' if point is in a table.
20529 Otherwise, call `org-show-children'."
20530 (interactive "p")
20531 (call-interactively
20532 (if (org-at-table-p) #'org-table-toggle-column-width
20533 #'org-show-children)))
20535 (defun org-ctrl-c-star ()
20536 "Compute table, or change heading status of lines.
20537 Calls `org-table-recalculate' or `org-toggle-heading',
20538 depending on context."
20539 (interactive)
20540 (cond
20541 ((org-at-table-p)
20542 (call-interactively 'org-table-recalculate))
20544 ;; Convert all lines in region to list items
20545 (call-interactively 'org-toggle-heading))))
20547 (defun org-ctrl-c-minus ()
20548 "Insert separator line in table or modify bullet status of line.
20549 Also turns a plain line or a region of lines into list items.
20550 Calls `org-table-insert-hline', `org-toggle-item', or
20551 `org-cycle-list-bullet', depending on context."
20552 (interactive)
20553 (cond
20554 ((org-at-table-p)
20555 (call-interactively 'org-table-insert-hline))
20556 ((org-region-active-p)
20557 (call-interactively 'org-toggle-item))
20558 ((org-in-item-p)
20559 (call-interactively 'org-cycle-list-bullet))
20561 (call-interactively 'org-toggle-item))))
20563 (defun org-toggle-heading (&optional nstars)
20564 "Convert headings to normal text, or items or text to headings.
20565 If there is no active region, only convert the current line.
20567 With a `\\[universal-argument]' prefix, convert the whole list at
20568 point into heading.
20570 In a region:
20572 - If the first non blank line is a headline, remove the stars
20573 from all headlines in the region.
20575 - If it is a normal line, turn each and every normal line (i.e.,
20576 not an heading or an item) in the region into headings. If you
20577 want to convert only the first line of this region, use one
20578 universal prefix argument.
20580 - If it is a plain list item, turn all plain list items into headings.
20582 When converting a line into a heading, the number of stars is chosen
20583 such that the lines become children of the current entry. However,
20584 when a numeric prefix argument is given, its value determines the
20585 number of stars to add."
20586 (interactive "P")
20587 (let ((skip-blanks
20588 (function
20589 ;; Return beginning of first non-blank line, starting from
20590 ;; line at POS.
20591 (lambda (pos)
20592 (save-excursion
20593 (goto-char pos)
20594 (while (org-at-comment-p) (forward-line))
20595 (skip-chars-forward " \r\t\n")
20596 (point-at-bol)))))
20597 beg end toggled)
20598 ;; Determine boundaries of changes. If a universal prefix has
20599 ;; been given, put the list in a region. If region ends at a bol,
20600 ;; do not consider the last line to be in the region.
20602 (when (and current-prefix-arg (org-at-item-p))
20603 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20604 (org-mark-element))
20606 (if (org-region-active-p)
20607 (setq beg (funcall skip-blanks (region-beginning))
20608 end (copy-marker (save-excursion
20609 (goto-char (region-end))
20610 (if (bolp) (point) (point-at-eol)))))
20611 (setq beg (funcall skip-blanks (point-at-bol))
20612 end (copy-marker (point-at-eol))))
20613 ;; Ensure inline tasks don't count as headings.
20614 (org-with-limited-levels
20615 (save-excursion
20616 (goto-char beg)
20617 (cond
20618 ;; Case 1. Started at an heading: de-star headings.
20619 ((org-at-heading-p)
20620 (while (< (point) end)
20621 (when (org-at-heading-p t)
20622 (looking-at org-outline-regexp) (replace-match "")
20623 (setq toggled t))
20624 (forward-line)))
20625 ;; Case 2. Started at an item: change items into headlines.
20626 ;; One star will be added by `org-list-to-subtree'.
20627 ((org-at-item-p)
20628 (while (< (point) end)
20629 (when (org-at-item-p)
20630 ;; Pay attention to cases when region ends before list.
20631 (let* ((struct (org-list-struct))
20632 (list-end
20633 (min (org-list-get-bottom-point struct) (1+ end))))
20634 (save-restriction
20635 (narrow-to-region (point) list-end)
20636 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20637 (setq toggled t))
20638 (forward-line)))
20639 ;; Case 3. Started at normal text: make every line an heading,
20640 ;; skipping headlines and items.
20641 (t (let* ((stars
20642 (make-string
20643 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20644 (add-stars
20645 (cond (nstars "") ; stars from prefix only
20646 ((equal stars "") "*") ; before first heading
20647 (org-odd-levels-only "**") ; inside heading, odd
20648 (t "*"))) ; inside heading, oddeven
20649 (rpl (concat stars add-stars " "))
20650 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20651 (while (< (point) (if (equal nstars '(4)) lend end))
20652 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20653 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20654 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20655 (forward-line)))))))
20656 (unless toggled (message "Cannot toggle heading from here"))))
20658 (defun org-meta-return (&optional arg)
20659 "Insert a new heading or wrap a region in a table.
20660 Calls `org-insert-heading', `org-insert-item' or
20661 `org-table-wrap-region', depending on context. When called with
20662 an argument, unconditionally call `org-insert-heading'."
20663 (interactive "P")
20664 (org-check-before-invisible-edit 'insert)
20665 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20666 (call-interactively (cond (arg #'org-insert-heading)
20667 ((org-at-table-p) #'org-table-wrap-region)
20668 ((org-in-item-p) #'org-insert-item)
20669 (t #'org-insert-heading)))))
20671 ;;; Menu entries
20673 (defsubst org-in-subtree-not-table-p ()
20674 "Are we in a subtree and not in a table?"
20675 (and (not (org-before-first-heading-p))
20676 (not (org-at-table-p))))
20678 ;; Define the Org mode menus
20679 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20680 '("Tbl"
20681 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20682 ["Next Field" org-cycle (org-at-table-p)]
20683 ["Previous Field" org-shifttab (org-at-table-p)]
20684 ["Next Row" org-return (org-at-table-p)]
20685 "--"
20686 ["Blank Field" org-table-blank-field (org-at-table-p)]
20687 ["Edit Field" org-table-edit-field (org-at-table-p)]
20688 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20689 "--"
20690 ("Column"
20691 ["Move Column Left" org-metaleft (org-at-table-p)]
20692 ["Move Column Right" org-metaright (org-at-table-p)]
20693 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20694 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20695 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20696 ("Row"
20697 ["Move Row Up" org-metaup (org-at-table-p)]
20698 ["Move Row Down" org-metadown (org-at-table-p)]
20699 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20700 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20701 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20702 "--"
20703 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20704 ("Rectangle"
20705 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20706 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20707 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20708 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20709 "--"
20710 ("Calculate"
20711 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20712 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20713 ["Edit Formulas" org-edit-special (org-at-table-p)]
20714 "--"
20715 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20716 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20717 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20718 "--"
20719 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20720 "--"
20721 ["Sum Column/Rectangle" org-table-sum
20722 (or (org-at-table-p) (org-region-active-p))]
20723 ["Which Column?" org-table-current-column (org-at-table-p)])
20724 ["Debug Formulas"
20725 org-table-toggle-formula-debugger
20726 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20727 ["Show Col/Row Numbers"
20728 org-table-toggle-coordinate-overlays
20729 :style toggle
20730 :selected (bound-and-true-p org-table-overlay-coordinates)]
20731 "--"
20732 ["Create" org-table-create (not (org-at-table-p))]
20733 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20734 ["Import from File" org-table-import (not (org-at-table-p))]
20735 ["Export to File" org-table-export (org-at-table-p)]
20736 "--"
20737 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20738 "--"
20739 ("Plot"
20740 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20741 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20743 (easy-menu-define org-org-menu org-mode-map "Org menu"
20744 '("Org"
20745 ("Show/Hide"
20746 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20747 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20748 ["Sparse Tree..." org-sparse-tree t]
20749 ["Reveal Context" org-reveal t]
20750 ["Show All" org-show-all t]
20751 "--"
20752 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20753 "--"
20754 ["New Heading" org-insert-heading t]
20755 ("Navigate Headings"
20756 ["Up" outline-up-heading t]
20757 ["Next" outline-next-visible-heading t]
20758 ["Previous" outline-previous-visible-heading t]
20759 ["Next Same Level" outline-forward-same-level t]
20760 ["Previous Same Level" outline-backward-same-level t]
20761 "--"
20762 ["Jump" org-goto t])
20763 ("Edit Structure"
20764 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20765 "--"
20766 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20767 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20768 "--"
20769 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20770 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20771 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20772 "--"
20773 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20774 "--"
20775 ["Copy visible text" org-copy-visible t]
20776 "--"
20777 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20778 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20779 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20780 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20781 "--"
20782 ["Sort Region/Children" org-sort t]
20783 "--"
20784 ["Convert to odd levels" org-convert-to-odd-levels t]
20785 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20786 ("Editing"
20787 ["Emphasis..." org-emphasize t]
20788 ["Edit Source Example" org-edit-special t]
20789 "--"
20790 ["Footnote new/jump" org-footnote-action t]
20791 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20792 ("Archive"
20793 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20794 "--"
20795 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20796 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20797 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20799 "--"
20800 ("Hyperlinks"
20801 ["Store Link (Global)" org-store-link t]
20802 ["Find existing link to here" org-occur-link-in-agenda-files t]
20803 ["Insert Link" org-insert-link t]
20804 ["Follow Link" org-open-at-point t]
20805 "--"
20806 ["Next link" org-next-link t]
20807 ["Previous link" org-previous-link t]
20808 "--"
20809 ["Descriptive Links"
20810 org-toggle-link-display
20811 :style radio
20812 :selected org-descriptive-links
20814 ["Literal Links"
20815 org-toggle-link-display
20816 :style radio
20817 :selected (not org-descriptive-links)])
20818 "--"
20819 ("TODO Lists"
20820 ["TODO/DONE/-" org-todo t]
20821 ("Select keyword"
20822 ["Next keyword" org-shiftright (org-at-heading-p)]
20823 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20824 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20825 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20826 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20827 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20828 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20829 "--"
20830 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20831 :selected org-enforce-todo-dependencies :style toggle :active t]
20832 "Settings for tree at point"
20833 ["Do Children sequentially" org-toggle-ordered-property :style radio
20834 :selected (org-entry-get nil "ORDERED")
20835 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20836 ["Do Children parallel" org-toggle-ordered-property :style radio
20837 :selected (not (org-entry-get nil "ORDERED"))
20838 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20839 "--"
20840 ["Set Priority" org-priority t]
20841 ["Priority Up" org-shiftup t]
20842 ["Priority Down" org-shiftdown t]
20843 "--"
20844 ["Get news from all feeds" org-feed-update-all t]
20845 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20846 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20847 ("TAGS and Properties"
20848 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20849 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20850 "--"
20851 ["Set property" org-set-property (not (org-before-first-heading-p))]
20852 ["Column view of properties" org-columns t]
20853 ["Insert Column View DBlock" org-columns-insert-dblock t])
20854 ("Dates and Scheduling"
20855 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20856 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20857 ("Change Date"
20858 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20859 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20860 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20861 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20862 ["Compute Time Range" org-evaluate-time-range t]
20863 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20864 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20865 "--"
20866 ["Custom time format" org-toggle-time-stamp-overlays
20867 :style radio :selected org-display-custom-times]
20868 "--"
20869 ["Goto Calendar" org-goto-calendar t]
20870 ["Date from Calendar" org-date-from-calendar t]
20871 "--"
20872 ["Start/Restart Timer" org-timer-start t]
20873 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20874 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20875 ["Insert Timer String" org-timer t]
20876 ["Insert Timer Item" org-timer-item t])
20877 ("Logging work"
20878 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20879 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20880 ["Clock out" org-clock-out t]
20881 ["Clock cancel" org-clock-cancel t]
20882 "--"
20883 ["Mark as default task" org-clock-mark-default-task t]
20884 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20885 ["Goto running clock" org-clock-goto t]
20886 "--"
20887 ["Display times" org-clock-display t]
20888 ["Create clock table" org-clock-report t]
20889 "--"
20890 ["Record DONE time"
20891 (progn (setq org-log-done (not org-log-done))
20892 (message "Switching to %s will %s record a timestamp"
20893 (car org-done-keywords)
20894 (if org-log-done "automatically" "not")))
20895 :style toggle :selected org-log-done])
20896 "--"
20897 ["Agenda Command..." org-agenda t]
20898 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20899 ("File List for Agenda")
20900 ("Special views current file"
20901 ["TODO Tree" org-show-todo-tree t]
20902 ["Check Deadlines" org-check-deadlines t]
20903 ["Tags/Property tree" org-match-sparse-tree t])
20904 "--"
20905 ["Export/Publish..." org-export-dispatch t]
20906 ("LaTeX"
20907 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20908 :style toggle :selected org-cdlatex-mode]
20909 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20910 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20911 ["Modify math symbol" org-cdlatex-math-modify
20912 (org-inside-LaTeX-fragment-p)]
20913 ["Insert citation" org-reftex-citation t])
20914 "--"
20915 ("MobileOrg"
20916 ["Push Files and Views" org-mobile-push t]
20917 ["Get Captured and Flagged" org-mobile-pull t]
20918 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20919 "--"
20920 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20921 "--"
20922 ("Documentation"
20923 ["Show Version" org-version t]
20924 ["Info Documentation" org-info t]
20925 ["Browse Org News" org-browse-news t])
20926 ("Customize"
20927 ["Browse Org Group" org-customize t]
20928 "--"
20929 ["Expand This Menu" org-create-customize-menu
20930 (fboundp 'customize-menu-create)])
20931 ["Send bug report" org-submit-bug-report t]
20932 "--"
20933 ("Refresh/Reload"
20934 ["Refresh setup current buffer" org-mode-restart t]
20935 ["Reload Org (after update)" org-reload t]
20936 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
20938 (defun org-info (&optional node)
20939 "Read documentation for Org in the info system.
20940 With optional NODE, go directly to that node."
20941 (interactive)
20942 (info (format "(org)%s" (or node ""))))
20944 (defun org-browse-news ()
20945 "Browse the news for the latest major release."
20946 (interactive)
20947 (browse-url "https://orgmode.org/Changes.html"))
20949 ;;;###autoload
20950 (defun org-submit-bug-report ()
20951 "Submit a bug report on Org via mail.
20953 Don't hesitate to report any problems or inaccurate documentation.
20955 If you don't have setup sending mail from (X)Emacs, please copy the
20956 output buffer into your mail program, as it gives us important
20957 information about your Org version and configuration."
20958 (interactive)
20959 (require 'reporter)
20960 (defvar reporter-prompt-for-summary-p)
20961 (org-load-modules-maybe)
20962 (org-require-autoloaded-modules)
20963 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20964 (reporter-submit-bug-report
20965 "emacs-orgmode@gnu.org"
20966 (org-version nil 'full)
20967 (let (list)
20968 (save-window-excursion
20969 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20970 (delete-other-windows)
20971 (erase-buffer)
20972 (insert "You are about to submit a bug report to the Org mailing list.
20974 We would like to add your full Org and Outline configuration to the
20975 bug report. This greatly simplifies the work of the maintainer and
20976 other experts on the mailing list.
20978 HOWEVER, some variables you have customized may contain private
20979 information. The names of customers, colleagues, or friends, might
20980 appear in the form of file names, tags, todo states, or search strings.
20981 If you answer yes to the prompt, you might want to check and remove
20982 such private information before sending the email.")
20983 (add-text-properties (point-min) (point-max) '(face org-warning))
20984 (when (yes-or-no-p "Include your Org configuration ")
20985 (mapatoms
20986 (lambda (v)
20987 (and (boundp v)
20988 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20989 (or (and (symbol-value v)
20990 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20991 (and
20992 (get v 'custom-type) (get v 'standard-value)
20993 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20994 (push v list)))))
20995 (kill-buffer (get-buffer "*Warn about privacy*"))
20996 list))
20997 nil nil
20998 "Remember to cover the basics, that is, what you expected to happen and
20999 what in fact did happen. You don't know how to make a good report? See
21001 https://orgmode.org/manual/Feedback.html#Feedback
21003 Your bug report will be posted to the Org mailing list.
21004 ------------------------------------------------------------------------")
21005 (save-excursion
21006 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21007 (replace-match "\\1Bug: \\3 [\\2]")))))
21010 (defun org-install-agenda-files-menu ()
21011 (let ((bl (buffer-list)))
21012 (save-excursion
21013 (while bl
21014 (set-buffer (pop bl))
21015 (when (derived-mode-p 'org-mode) (setq bl nil)))
21016 (when (derived-mode-p 'org-mode)
21017 (easy-menu-change
21018 '("Org") "File List for Agenda"
21019 (append
21020 (list
21021 ["Edit File List" (org-edit-agenda-file-list) t]
21022 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21023 ["Remove Current File from List" org-remove-file t]
21024 ["Cycle through agenda files" org-cycle-agenda-files t]
21025 ["Occur in all agenda files" org-occur-in-agenda-files t]
21026 "--")
21027 (mapcar 'org-file-menu-entry
21028 ;; Prevent initialization from failing.
21029 (ignore-errors (org-agenda-files t)))))))))
21031 ;;;; Documentation
21033 (defun org-require-autoloaded-modules ()
21034 (interactive)
21035 (mapc #'require
21036 '(org-agenda org-archive org-attach org-clock org-colview org-id
21037 org-table org-timer)))
21039 ;;;###autoload
21040 (defun org-reload (&optional uncompiled)
21041 "Reload all Org Lisp files.
21042 With prefix arg UNCOMPILED, load the uncompiled versions."
21043 (interactive "P")
21044 (require 'loadhist)
21045 (let* ((org-dir (org-find-library-dir "org"))
21046 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21047 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21048 (remove-re (format "\\`%s\\'"
21049 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21050 (feats (delete-dups
21051 (mapcar 'file-name-sans-extension
21052 (mapcar 'file-name-nondirectory
21053 (delq nil
21054 (mapcar 'feature-file
21055 features))))))
21056 (lfeat (append
21057 (sort
21058 (setq feats
21059 (delq nil (mapcar
21060 (lambda (f)
21061 (if (and (string-match feature-re f)
21062 (not (string-match remove-re f)))
21063 f nil))
21064 feats)))
21065 'string-lessp)
21066 (list "org-version" "org")))
21067 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21068 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21069 load-uncore load-misses)
21070 (setq load-misses
21071 (delq 't
21072 (mapcar (lambda (f)
21073 (or (org-load-noerror-mustsuffix (concat org-dir f))
21074 (and (string= org-dir contrib-dir)
21075 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21076 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21077 (add-to-list 'load-uncore f 'append)
21080 lfeat)))
21081 (when load-uncore
21082 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21083 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21084 (if load-misses
21085 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21086 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21087 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21089 ;;;###autoload
21090 (defun org-customize ()
21091 "Call the customize function with org as argument."
21092 (interactive)
21093 (org-load-modules-maybe)
21094 (org-require-autoloaded-modules)
21095 (customize-browse 'org))
21097 (defun org-create-customize-menu ()
21098 "Create a full customization menu for Org mode, insert it into the menu."
21099 (interactive)
21100 (org-load-modules-maybe)
21101 (org-require-autoloaded-modules)
21102 (if (fboundp 'customize-menu-create)
21103 (progn
21104 (easy-menu-change
21105 '("Org") "Customize"
21106 `(["Browse Org group" org-customize t]
21107 "--"
21108 ,(customize-menu-create 'org)
21109 ["Set" Custom-set t]
21110 ["Save" Custom-save t]
21111 ["Reset to Current" Custom-reset-current t]
21112 ["Reset to Saved" Custom-reset-saved t]
21113 ["Reset to Standard Settings" Custom-reset-standard t]))
21114 (message "\"Org\"-menu now contains full customization menu"))
21115 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21117 ;;;; Miscellaneous stuff
21119 ;;; Generally useful functions
21121 (defun org-link-display-format (s)
21122 "Replace links in string S with their description.
21123 If there is no description, use the link target."
21124 (save-match-data
21125 (replace-regexp-in-string
21126 org-bracket-link-analytic-regexp
21127 (lambda (m)
21128 (if (match-end 5) (match-string 5 m)
21129 (concat (match-string 1 m) (match-string 3 m))))
21130 s nil t)))
21132 (defun org-toggle-link-display ()
21133 "Toggle the literal or descriptive display of links."
21134 (interactive)
21135 (if org-descriptive-links
21136 (remove-from-invisibility-spec '(org-link))
21137 (add-to-invisibility-spec '(org-link)))
21138 (org-restart-font-lock)
21139 (setq org-descriptive-links (not org-descriptive-links)))
21141 (defun org-in-clocktable-p ()
21142 "Check if the cursor is in a clocktable."
21143 (let ((pos (point)) start)
21144 (save-excursion
21145 (end-of-line 1)
21146 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21147 (setq start (match-beginning 0))
21148 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21149 (>= (match-end 0) pos)
21150 start))))
21152 (defun org-in-verbatim-emphasis ()
21153 (save-match-data
21154 (and (org-in-regexp org-verbatim-re 2)
21155 (>= (point) (match-beginning 3))
21156 (<= (point) (match-end 4)))))
21158 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21159 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21160 (if (and marker (marker-buffer marker)
21161 (buffer-live-p (marker-buffer marker)))
21162 (progn
21163 (pop-to-buffer-same-window (marker-buffer marker))
21164 (when (or (> marker (point-max)) (< marker (point-min)))
21165 (widen))
21166 (goto-char marker)
21167 (org-show-context 'org-goto))
21168 (if bookmark
21169 (bookmark-jump bookmark)
21170 (error "Cannot find location"))))
21172 (defun org-quote-csv-field (s)
21173 "Quote field for inclusion in CSV material."
21174 (if (string-match "[\",]" s)
21175 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21178 (defun org-force-self-insert (N)
21179 "Needed to enforce self-insert under remapping."
21180 (interactive "p")
21181 (self-insert-command N))
21183 (defun org-fill-template (template alist)
21184 "Find each %key of ALIST in TEMPLATE and replace it."
21185 (let ((case-fold-search nil))
21186 (dolist (entry (sort (copy-sequence alist)
21187 (lambda (a b) (< (length (car a)) (length (car b))))))
21188 (setq template
21189 (replace-regexp-in-string
21190 (concat "%" (regexp-quote (car entry)))
21191 (or (cdr entry) "") template t t)))
21192 template))
21194 (defun org-quote-vert (s)
21195 "Replace \"|\" with \"\\vert\"."
21196 (while (string-match "|" s)
21197 (setq s (replace-match "\\vert" t t s)))
21200 (defun org-uuidgen-p (s)
21201 "Is S an ID created by UUIDGEN?"
21202 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21204 (defun org-in-src-block-p (&optional inside)
21205 "Whether point is in a code source block.
21206 When INSIDE is non-nil, don't consider we are within a source
21207 block when point is at #+BEGIN_SRC or #+END_SRC."
21208 (let ((case-fold-search t))
21209 (or (and (eq (get-char-property (point) 'src-block) t))
21210 (and (not inside)
21211 (save-match-data
21212 (save-excursion
21213 (beginning-of-line)
21214 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21216 (defun org-context ()
21217 "Return a list of contexts of the current cursor position.
21218 If several contexts apply, all are returned.
21219 Each context entry is a list with a symbol naming the context, and
21220 two positions indicating start and end of the context. Possible
21221 contexts are:
21223 :headline anywhere in a headline
21224 :headline-stars on the leading stars in a headline
21225 :todo-keyword on a TODO keyword (including DONE) in a headline
21226 :tags on the TAGS in a headline
21227 :priority on the priority cookie in a headline
21228 :item on the first line of a plain list item
21229 :item-bullet on the bullet/number of a plain list item
21230 :checkbox on the checkbox in a plain list item
21231 :table in an Org table
21232 :table-special on a special filed in a table
21233 :table-table in a table.el table
21234 :clocktable in a clocktable
21235 :src-block in a source block
21236 :link on a hyperlink
21237 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21238 :target on a <<target>>
21239 :radio-target on a <<<radio-target>>>
21240 :latex-fragment on a LaTeX fragment
21241 :latex-preview on a LaTeX fragment with overlaid preview image
21243 This function expects the position to be visible because it uses font-lock
21244 faces as a help to recognize the following contexts: :table-special, :link,
21245 and :keyword."
21246 (let* ((f (get-text-property (point) 'face))
21247 (faces (if (listp f) f (list f)))
21248 (case-fold-search t)
21249 (p (point)) clist o)
21250 ;; First the large context
21251 (cond
21252 ((org-at-heading-p t)
21253 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21254 (when (progn
21255 (beginning-of-line 1)
21256 (looking-at org-todo-line-tags-regexp))
21257 (push (org-point-in-group p 1 :headline-stars) clist)
21258 (push (org-point-in-group p 2 :todo-keyword) clist)
21259 (push (org-point-in-group p 4 :tags) clist))
21260 (goto-char p)
21261 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21262 (when (looking-at "\\[#[A-Z0-9]\\]")
21263 (push (org-point-in-group p 0 :priority) clist)))
21265 ((org-at-item-p)
21266 (push (org-point-in-group p 2 :item-bullet) clist)
21267 (push (list :item (point-at-bol)
21268 (save-excursion (org-end-of-item) (point)))
21269 clist)
21270 (and (org-at-item-checkbox-p)
21271 (push (org-point-in-group p 0 :checkbox) clist)))
21273 ((org-at-table-p)
21274 (push (list :table (org-table-begin) (org-table-end)) clist)
21275 (when (memq 'org-formula faces)
21276 (push (list :table-special
21277 (previous-single-property-change p 'face)
21278 (next-single-property-change p 'face)) clist)))
21279 ((org-at-table-p 'any)
21280 (push (list :table-table) clist)))
21281 (goto-char p)
21283 (let ((case-fold-search t))
21284 ;; New the "medium" contexts: clocktables, source blocks
21285 (cond ((org-in-clocktable-p)
21286 (push (list :clocktable
21287 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21288 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21289 (match-beginning 1))
21290 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21291 (match-end 0))) clist))
21292 ((org-in-src-block-p)
21293 (push (list :src-block
21294 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21295 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21296 (match-beginning 1))
21297 (and (search-forward "#+END_SRC" nil t)
21298 (match-beginning 0))) clist))))
21299 (goto-char p)
21301 ;; Now the small context
21302 (cond
21303 ((org-at-timestamp-p)
21304 (push (org-point-in-group p 0 :timestamp) clist))
21305 ((memq 'org-link faces)
21306 (push (list :link
21307 (previous-single-property-change p 'face)
21308 (next-single-property-change p 'face)) clist))
21309 ((memq 'org-special-keyword faces)
21310 (push (list :keyword
21311 (previous-single-property-change p 'face)
21312 (next-single-property-change p 'face)) clist))
21313 ((org-at-target-p)
21314 (push (org-point-in-group p 0 :target) clist)
21315 (goto-char (1- (match-beginning 0)))
21316 (when (looking-at org-radio-target-regexp)
21317 (push (org-point-in-group p 0 :radio-target) clist))
21318 (goto-char p))
21319 ((setq o (cl-some
21320 (lambda (o)
21321 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21323 (overlays-at (point))))
21324 (push (list :latex-fragment
21325 (overlay-start o) (overlay-end o)) clist)
21326 (push (list :latex-preview
21327 (overlay-start o) (overlay-end o)) clist))
21328 ((org-inside-LaTeX-fragment-p)
21329 ;; FIXME: positions wrong.
21330 (push (list :latex-fragment (point) (point)) clist)))
21332 (setq clist (nreverse (delq nil clist)))
21333 clist))
21335 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21336 "Non-nil when point is between matches of START-RE and END-RE.
21338 Also return a non-nil value when point is on one of the matches.
21340 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21341 buffer positions. Default values are the positions of headlines
21342 surrounding the point.
21344 The functions returns a cons cell whose car (resp. cdr) is the
21345 position before START-RE (resp. after END-RE)."
21346 (save-match-data
21347 (let ((pos (point))
21348 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21349 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21350 beg end)
21351 (save-excursion
21352 ;; Point is on a block when on START-RE or if START-RE can be
21353 ;; found before it...
21354 (and (or (org-in-regexp start-re)
21355 (re-search-backward start-re limit-up t))
21356 (setq beg (match-beginning 0))
21357 ;; ... and END-RE after it...
21358 (goto-char (match-end 0))
21359 (re-search-forward end-re limit-down t)
21360 (> (setq end (match-end 0)) pos)
21361 ;; ... without another START-RE in-between.
21362 (goto-char (match-beginning 0))
21363 (not (re-search-backward start-re (1+ beg) t))
21364 ;; Return value.
21365 (cons beg end))))))
21367 (defun org-in-block-p (names)
21368 "Non-nil when point belongs to a block whose name belongs to NAMES.
21370 NAMES is a list of strings containing names of blocks.
21372 Return first block name matched, or nil. Beware that in case of
21373 nested blocks, the returned name may not belong to the closest
21374 block from point."
21375 (save-match-data
21376 (catch 'exit
21377 (let ((case-fold-search t)
21378 (lim-up (save-excursion (outline-previous-heading)))
21379 (lim-down (save-excursion (outline-next-heading))))
21380 (dolist (name names)
21381 (let ((n (regexp-quote name)))
21382 (when (org-between-regexps-p
21383 (concat "^[ \t]*#\\+begin_" n)
21384 (concat "^[ \t]*#\\+end_" n)
21385 lim-up lim-down)
21386 (throw 'exit n)))))
21387 nil)))
21389 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21390 "Call `multi-occur' with buffers for all agenda files."
21391 (interactive "sOrg-files matching: ")
21392 (let* ((files (org-agenda-files))
21393 (tnames (mapcar #'file-truename files))
21394 (extra org-agenda-text-search-extra-files))
21395 (when (eq (car extra) 'agenda-archives)
21396 (setq extra (cdr extra))
21397 (setq files (org-add-archive-files files)))
21398 (dolist (f extra)
21399 (unless (member (file-truename f) tnames)
21400 (unless (member f files) (setq files (append files (list f))))
21401 (setq tnames (append tnames (list (file-truename f))))))
21402 (multi-occur
21403 (mapcar (lambda (x)
21404 (with-current-buffer
21405 ;; FIXME: Why not just (find-file-noselect x)?
21406 ;; Is it to avoid the "revert buffer" prompt?
21407 (or (get-file-buffer x) (find-file-noselect x))
21408 (widen)
21409 (current-buffer)))
21410 files)
21411 regexp)))
21413 (add-hook 'occur-mode-find-occurrence-hook
21414 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21416 (defun org-occur-link-in-agenda-files ()
21417 "Create a link and search for it in the agendas.
21418 The link is not stored in `org-stored-links', it is just created
21419 for the search purpose."
21420 (interactive)
21421 (let ((link (condition-case nil
21422 (org-store-link nil)
21423 (error "Unable to create a link to here"))))
21424 (org-occur-in-agenda-files (regexp-quote link))))
21426 (defun org-back-over-empty-lines ()
21427 "Move backwards over whitespace, to the beginning of the first empty line.
21428 Returns the number of empty lines passed."
21429 (let ((pos (point)))
21430 (if (cdr (assq 'heading org-blank-before-new-entry))
21431 (skip-chars-backward " \t\n\r")
21432 (unless (eobp)
21433 (forward-line -1)))
21434 (beginning-of-line 2)
21435 (goto-char (min (point) pos))
21436 (count-lines (point) pos)))
21438 (defun org-replace-escapes (string table)
21439 "Replace %-escapes in STRING with values in TABLE.
21440 TABLE is an association list with keys like \"%a\" and string values.
21441 The sequences in STRING may contain normal field width and padding information,
21442 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21443 so values can contain further %-escapes if they are define later in TABLE."
21444 (let ((tbl (copy-alist table))
21445 (case-fold-search nil)
21446 (pchg 0)
21447 re rpl)
21448 (dolist (e tbl)
21449 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21450 (when (and (cdr e) (string-match re (cdr e)))
21451 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21452 (safe "SREF"))
21453 (add-text-properties 0 3 (list 'sref sref) safe)
21454 (setcdr e (replace-match safe t t (cdr e)))))
21455 (while (string-match re string)
21456 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21457 (cdr e)))
21458 (setq string (replace-match rpl t t string))))
21459 (while (setq pchg (next-property-change pchg string))
21460 (let ((sref (get-text-property pchg 'sref string)))
21461 (when (and sref (string-match "SREF" string pchg))
21462 (setq string (replace-match sref t t string)))))
21463 string))
21465 ;;; TODO: Only called once, from ox-odt which should probably use
21466 ;;; org-export-inline-image-p or something.
21467 (defun org-file-image-p (file)
21468 "Return non-nil if FILE is an image."
21469 (save-match-data
21470 (string-match (image-file-name-regexp) file)))
21472 (defun org-get-cursor-date (&optional with-time)
21473 "Return the date at cursor in as a time.
21474 This works in the calendar and in the agenda, anywhere else it just
21475 returns the current time.
21476 If WITH-TIME is non-nil, returns the time of the event at point (in
21477 the agenda) or the current time of the day."
21478 (let (date day defd tp hod mod)
21479 (when with-time
21480 (setq tp (get-text-property (point) 'time))
21481 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21482 (setq hod (string-to-number (match-string 1 tp))
21483 mod (string-to-number (match-string 2 tp))))
21484 (or tp (let ((now (decode-time)))
21485 (setq hod (nth 2 now)
21486 mod (nth 1 now)))))
21487 (cond
21488 ((eq major-mode 'calendar-mode)
21489 (setq date (calendar-cursor-to-date)
21490 defd (encode-time 0 (or mod 0) (or hod 0)
21491 (nth 1 date) (nth 0 date) (nth 2 date))))
21492 ((eq major-mode 'org-agenda-mode)
21493 (setq day (get-text-property (point) 'day))
21494 (when day
21495 (setq date (calendar-gregorian-from-absolute day)
21496 defd (encode-time 0 (or mod 0) (or hod 0)
21497 (nth 1 date) (nth 0 date) (nth 2 date))))))
21498 (or defd (current-time))))
21500 (defun org-mark-subtree (&optional up)
21501 "Mark the current subtree.
21502 This puts point at the start of the current subtree, and mark at
21503 the end. If a numeric prefix UP is given, move up into the
21504 hierarchy of headlines by UP levels before marking the subtree."
21505 (interactive "P")
21506 (org-with-limited-levels
21507 (cond ((org-at-heading-p) (beginning-of-line))
21508 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21509 (t (outline-previous-visible-heading 1))))
21510 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21511 (if (called-interactively-p 'any)
21512 (call-interactively 'org-mark-element)
21513 (org-mark-element)))
21515 ;;; Indentation
21517 (defvar org-element-greater-elements)
21518 (defun org--get-expected-indentation (element contentsp)
21519 "Expected indentation column for current line, according to ELEMENT.
21520 ELEMENT is an element containing point. CONTENTSP is non-nil
21521 when indentation is to be computed according to contents of
21522 ELEMENT."
21523 (let ((type (org-element-type element))
21524 (start (org-element-property :begin element))
21525 (post-affiliated (org-element-property :post-affiliated element)))
21526 (org-with-wide-buffer
21527 (cond
21528 (contentsp
21529 (cl-case type
21530 ((diary-sexp footnote-definition) 0)
21531 ((headline inlinetask nil)
21532 (if (not org-adapt-indentation) 0
21533 (let ((level (org-current-level)))
21534 (if level (1+ level) 0))))
21535 ((item plain-list) (org-list-item-body-column post-affiliated))
21537 (goto-char start)
21538 (current-indentation))))
21539 ((memq type '(headline inlinetask nil))
21540 (if (org-match-line "[ \t]*$")
21541 (org--get-expected-indentation element t)
21543 ((memq type '(diary-sexp footnote-definition)) 0)
21544 ;; First paragraph of a footnote definition or an item.
21545 ;; Indent like parent.
21546 ((< (line-beginning-position) start)
21547 (org--get-expected-indentation
21548 (org-element-property :parent element) t))
21549 ;; At first line: indent according to previous sibling, if any,
21550 ;; ignoring footnote definitions and inline tasks, or parent's
21551 ;; contents.
21552 ((= (line-beginning-position) start)
21553 (catch 'exit
21554 (while t
21555 (if (= (point-min) start) (throw 'exit 0)
21556 (goto-char (1- start))
21557 (let* ((previous (org-element-at-point))
21558 (parent previous))
21559 (while (and parent (<= (org-element-property :end parent) start))
21560 (setq previous parent
21561 parent (org-element-property :parent parent)))
21562 (cond
21563 ((not previous) (throw 'exit 0))
21564 ((> (org-element-property :end previous) start)
21565 (throw 'exit (org--get-expected-indentation previous t)))
21566 ((memq (org-element-type previous)
21567 '(footnote-definition inlinetask))
21568 (setq start (org-element-property :begin previous)))
21569 (t (goto-char (org-element-property :begin previous))
21570 (throw 'exit
21571 (if (bolp) (current-indentation)
21572 ;; At first paragraph in an item or
21573 ;; a footnote definition.
21574 (org--get-expected-indentation
21575 (org-element-property :parent previous) t))))))))))
21576 ;; Otherwise, move to the first non-blank line above.
21578 (beginning-of-line)
21579 (let ((pos (point)))
21580 (skip-chars-backward " \r\t\n")
21581 (cond
21582 ;; Two blank lines end a footnote definition or a plain
21583 ;; list. When we indent an empty line after them, the
21584 ;; containing list or footnote definition is over, so it
21585 ;; qualifies as a previous sibling. Therefore, we indent
21586 ;; like its first line.
21587 ((and (memq type '(footnote-definition plain-list))
21588 (> (count-lines (point) pos) 2))
21589 (goto-char start)
21590 (current-indentation))
21591 ;; Line above is the first one of a paragraph at the
21592 ;; beginning of an item or a footnote definition. Indent
21593 ;; like parent.
21594 ((< (line-beginning-position) start)
21595 (org--get-expected-indentation
21596 (org-element-property :parent element) t))
21597 ;; Line above is the beginning of an element, i.e., point
21598 ;; was originally on the blank lines between element's start
21599 ;; and contents.
21600 ((= (line-beginning-position) post-affiliated)
21601 (org--get-expected-indentation element t))
21602 ;; POS is after contents in a greater element. Indent like
21603 ;; the beginning of the element.
21604 ((and (memq type org-element-greater-elements)
21605 (let ((cend (org-element-property :contents-end element)))
21606 (and cend (<= cend pos))))
21607 ;; As a special case, if point is at the end of a footnote
21608 ;; definition or an item, indent like the very last element
21609 ;; within. If that last element is an item, indent like
21610 ;; its contents.
21611 (if (memq type '(footnote-definition item plain-list))
21612 (let ((last (org-element-at-point)))
21613 (goto-char pos)
21614 (org--get-expected-indentation
21615 last (eq (org-element-type last) 'item)))
21616 (goto-char start)
21617 (current-indentation)))
21618 ;; In any other case, indent like the current line.
21619 (t (current-indentation)))))))))
21621 (defun org--align-node-property ()
21622 "Align node property at point.
21623 Alignment is done according to `org-property-format', which see."
21624 (when (save-excursion
21625 (beginning-of-line)
21626 (looking-at org-property-re))
21627 (replace-match
21628 (concat (match-string 4)
21629 (org-trim
21630 (format org-property-format (match-string 1) (match-string 3))))
21631 t t)))
21633 (defun org-indent-line ()
21634 "Indent line depending on context.
21636 Indentation is done according to the following rules:
21638 - Footnote definitions, diary sexps, headlines and inline tasks
21639 have to start at column 0.
21641 - On the very first line of an element, consider, in order, the
21642 next rules until one matches:
21644 1. If there's a sibling element before, ignoring footnote
21645 definitions and inline tasks, indent like its first line.
21647 2. If element has a parent, indent like its contents. More
21648 precisely, if parent is an item, indent after the
21649 description part, if any, or the bullet (see
21650 `org-list-description-max-indent'). Else, indent like
21651 parent's first line.
21653 3. Otherwise, indent relatively to current level, if
21654 `org-adapt-indentation' is non-nil, or to left margin.
21656 - On a blank line at the end of an element, indent according to
21657 the type of the element. More precisely
21659 1. If element is a plain list, an item, or a footnote
21660 definition, indent like the very last element within.
21662 2. If element is a paragraph, indent like its last non blank
21663 line.
21665 3. Otherwise, indent like its very first line.
21667 - In the code part of a source block, use language major mode
21668 to indent current line if `org-src-tab-acts-natively' is
21669 non-nil. If it is nil, do nothing.
21671 - Otherwise, indent like the first non-blank line above.
21673 The function doesn't indent an item as it could break the whole
21674 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21675 `\\[org-shiftmetaright]'.
21677 Also align node properties according to `org-property-format'."
21678 (interactive)
21679 (cond
21680 ((org-at-heading-p) 'noindent)
21682 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21683 (type (org-element-type element)))
21684 (cond ((and (memq type '(plain-list item))
21685 (= (line-beginning-position)
21686 (org-element-property :post-affiliated element)))
21687 'noindent)
21688 ((and (eq type 'latex-environment)
21689 (>= (point) (org-element-property :post-affiliated element))
21690 (< (point) (org-with-wide-buffer
21691 (goto-char (org-element-property :end element))
21692 (skip-chars-backward " \r\t\n")
21693 (line-beginning-position 2))))
21694 'noindent)
21695 ((and (eq type 'src-block)
21696 org-src-tab-acts-natively
21697 (> (line-beginning-position)
21698 (org-element-property :post-affiliated element))
21699 (< (line-beginning-position)
21700 (org-with-wide-buffer
21701 (goto-char (org-element-property :end element))
21702 (skip-chars-backward " \r\t\n")
21703 (line-beginning-position))))
21704 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21706 (let ((column (org--get-expected-indentation element nil)))
21707 ;; Preserve current column.
21708 (if (<= (current-column) (current-indentation))
21709 (indent-line-to column)
21710 (save-excursion (indent-line-to column))))
21711 ;; Align node property. Also preserve current column.
21712 (when (eq type 'node-property)
21713 (let ((column (current-column)))
21714 (org--align-node-property)
21715 (org-move-to-column column)))))))))
21717 (defun org-indent-region (start end)
21718 "Indent each non-blank line in the region.
21719 Called from a program, START and END specify the region to
21720 indent. The function will not indent contents of example blocks,
21721 verse blocks and export blocks as leading white spaces are
21722 assumed to be significant there."
21723 (interactive "r")
21724 (save-excursion
21725 (goto-char start)
21726 (skip-chars-forward " \r\t\n")
21727 (unless (eobp) (beginning-of-line))
21728 (let ((indent-to
21729 (lambda (ind pos)
21730 ;; Set IND as indentation for all lines between point and
21731 ;; POS. Blank lines are ignored. Leave point after POS
21732 ;; once done.
21733 (let ((limit (copy-marker pos)))
21734 (while (< (point) limit)
21735 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21736 (forward-line))
21737 (set-marker limit nil))))
21738 (end (copy-marker end)))
21739 (while (< (point) end)
21740 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21741 (let* ((element (org-element-at-point))
21742 (type (org-element-type element))
21743 (element-end (copy-marker (org-element-property :end element)))
21744 (ind (org--get-expected-indentation element nil)))
21745 (cond
21746 ;; Element indented as a single block. Example blocks
21747 ;; preserving indentation are a special case since the
21748 ;; "contents" must not be indented whereas the block
21749 ;; boundaries can.
21750 ((or (memq type '(export-block latex-environment))
21751 (and (eq type 'example-block)
21752 (not
21753 (or org-src-preserve-indentation
21754 (org-element-property :preserve-indent element)))))
21755 (let ((offset (- ind (current-indentation))))
21756 (unless (zerop offset)
21757 (indent-rigidly (org-element-property :begin element)
21758 (org-element-property :end element)
21759 offset)))
21760 (goto-char element-end))
21761 ;; Elements indented line wise. Be sure to exclude
21762 ;; example blocks (preserving indentation) and source
21763 ;; blocks from this category as they are treated
21764 ;; specially later.
21765 ((or (memq type '(paragraph table table-row))
21766 (not (or (org-element-property :contents-begin element)
21767 (memq type '(example-block src-block)))))
21768 (when (eq type 'node-property)
21769 (org--align-node-property)
21770 (beginning-of-line))
21771 (funcall indent-to ind (min element-end end)))
21772 ;; Elements consisting of three parts: before the
21773 ;; contents, the contents, and after the contents. The
21774 ;; contents are treated specially, according to the
21775 ;; element type, or not indented at all. Other parts are
21776 ;; indented as a single block.
21778 (let* ((post (copy-marker
21779 (org-element-property :post-affiliated element)))
21780 (cbeg
21781 (copy-marker
21782 (cond
21783 ((not (org-element-property :contents-begin element))
21784 ;; Fake contents for source blocks.
21785 (org-with-wide-buffer
21786 (goto-char post)
21787 (line-beginning-position 2)))
21788 ((memq type '(footnote-definition item plain-list))
21789 ;; Contents in these elements could start on
21790 ;; the same line as the beginning of the
21791 ;; element. Make sure we start indenting
21792 ;; from the second line.
21793 (org-with-wide-buffer
21794 (goto-char post)
21795 (end-of-line)
21796 (skip-chars-forward " \r\t\n")
21797 (if (eobp) (point) (line-beginning-position))))
21798 (t (org-element-property :contents-begin element)))))
21799 (cend (copy-marker
21800 (or (org-element-property :contents-end element)
21801 ;; Fake contents for source blocks.
21802 (org-with-wide-buffer
21803 (goto-char element-end)
21804 (skip-chars-backward " \r\t\n")
21805 (line-beginning-position)))
21806 t)))
21807 ;; Do not change items indentation individually as it
21808 ;; might break the list as a whole. On the other
21809 ;; hand, when at a plain list, indent it as a whole.
21810 (cond ((eq type 'plain-list)
21811 (let ((offset (- ind (current-indentation))))
21812 (unless (zerop offset)
21813 (indent-rigidly (org-element-property :begin element)
21814 (org-element-property :end element)
21815 offset))
21816 (goto-char cbeg)))
21817 ((eq type 'item) (goto-char cbeg))
21818 (t (funcall indent-to ind (min cbeg end))))
21819 (when (< (point) end)
21820 (cl-case type
21821 ((example-block verse-block))
21822 (src-block
21823 ;; In a source block, indent source code
21824 ;; according to language major mode, but only if
21825 ;; `org-src-tab-acts-natively' is non-nil.
21826 (when (and (< (point) end) org-src-tab-acts-natively)
21827 (ignore-errors
21828 (org-babel-do-in-edit-buffer
21829 (indent-region (point-min) (point-max))))))
21830 (t (org-indent-region (point) (min cend end))))
21831 (goto-char (min cend end))
21832 (when (< (point) end)
21833 (funcall indent-to ind (min element-end end))))
21834 (set-marker post nil)
21835 (set-marker cbeg nil)
21836 (set-marker cend nil))))
21837 (set-marker element-end nil))))
21838 (set-marker end nil))))
21840 (defun org-indent-drawer ()
21841 "Indent the drawer at point."
21842 (interactive)
21843 (unless (save-excursion
21844 (beginning-of-line)
21845 (looking-at-p org-drawer-regexp))
21846 (user-error "Not at a drawer"))
21847 (let ((element (org-element-at-point)))
21848 (unless (memq (org-element-type element) '(drawer property-drawer))
21849 (user-error "Not at a drawer"))
21850 (org-with-wide-buffer
21851 (org-indent-region (org-element-property :begin element)
21852 (org-element-property :end element))))
21853 (message "Drawer at point indented"))
21855 (defun org-indent-block ()
21856 "Indent the block at point."
21857 (interactive)
21858 (unless (save-excursion
21859 (beginning-of-line)
21860 (let ((case-fold-search t))
21861 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21862 (user-error "Not at a block"))
21863 (let ((element (org-element-at-point)))
21864 (unless (memq (org-element-type element)
21865 '(comment-block center-block dynamic-block example-block
21866 export-block quote-block special-block
21867 src-block verse-block))
21868 (user-error "Not at a block"))
21869 (org-with-wide-buffer
21870 (org-indent-region (org-element-property :begin element)
21871 (org-element-property :end element))))
21872 (message "Block at point indented"))
21875 ;;; Filling
21877 ;; We use our own fill-paragraph and auto-fill functions.
21879 ;; `org-fill-paragraph' relies on adaptive filling and context
21880 ;; checking. Appropriate `fill-prefix' is computed with
21881 ;; `org-adaptive-fill-function'.
21883 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21884 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21885 ;; `org-adaptive-fill-function' value. Internally,
21886 ;; `org-comment-line-break-function' breaks the line.
21888 ;; `org-setup-filling' installs filling and auto-filling related
21889 ;; variables during `org-mode' initialization.
21891 (defun org-setup-filling ()
21892 (require 'org-element)
21893 ;; Prevent auto-fill from inserting unwanted new items.
21894 (when (boundp 'fill-nobreak-predicate)
21895 (setq-local
21896 fill-nobreak-predicate
21897 (org-uniquify
21898 (append fill-nobreak-predicate
21899 '(org-fill-line-break-nobreak-p
21900 org-fill-n-macro-as-item-nobreak-p
21901 org-fill-paragraph-with-timestamp-nobreak-p)))))
21902 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21903 (setq-local paragraph-start paragraph-ending)
21904 (setq-local paragraph-separate paragraph-ending))
21905 (setq-local fill-paragraph-function 'org-fill-paragraph)
21906 (setq-local auto-fill-inhibit-regexp nil)
21907 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21908 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21909 (setq-local comment-line-break-function 'org-comment-line-break-function))
21911 (defun org-fill-line-break-nobreak-p ()
21912 "Non-nil when a new line at point would create an Org line break."
21913 (save-excursion
21914 (skip-chars-backward "[ \t]")
21915 (skip-chars-backward "\\\\")
21916 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21918 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21919 "Non-nil when a new line at point would split a timestamp."
21920 (and (org-at-timestamp-p 'lax)
21921 (not (looking-at org-ts-regexp-both))))
21923 (defun org-fill-n-macro-as-item-nobreak-p ()
21924 "Non-nil when a new line at point would create a new list."
21925 ;; During export, a "n" macro followed by a dot or a closing
21926 ;; parenthesis can end up being parsed as a new list item.
21927 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21929 (defvar orgtbl-line-start-regexp) ; From org-table.el
21930 (defun org-adaptive-fill-function ()
21931 "Compute a fill prefix for the current line.
21932 Return fill prefix, as a string, or nil if current line isn't
21933 meant to be filled. For convenience, if `adaptive-fill-regexp'
21934 matches in paragraphs or comments, use it."
21935 (org-with-wide-buffer
21936 (unless (org-at-heading-p)
21937 (let* ((p (line-beginning-position))
21938 (element (save-excursion
21939 (beginning-of-line)
21940 (org-element-at-point)))
21941 (type (org-element-type element))
21942 (post-affiliated (org-element-property :post-affiliated element)))
21943 (unless (< p post-affiliated)
21944 (cl-case type
21945 (comment
21946 (save-excursion
21947 (beginning-of-line)
21948 (looking-at "[ \t]*")
21949 (concat (match-string 0) "# ")))
21950 (footnote-definition "")
21951 ((item plain-list)
21952 (make-string (org-list-item-body-column post-affiliated) ?\s))
21953 (paragraph
21954 ;; Fill prefix is usually the same as the current line,
21955 ;; unless the paragraph is at the beginning of an item.
21956 (let ((parent (org-element-property :parent element)))
21957 (save-excursion
21958 (beginning-of-line)
21959 (cond ((eq (org-element-type parent) 'item)
21960 (make-string (org-list-item-body-column
21961 (org-element-property :begin parent))
21962 ?\s))
21963 ((and adaptive-fill-regexp
21964 ;; Locally disable
21965 ;; `adaptive-fill-function' to let
21966 ;; `fill-context-prefix' handle
21967 ;; `adaptive-fill-regexp' variable.
21968 (let (adaptive-fill-function)
21969 (fill-context-prefix
21970 post-affiliated
21971 (org-element-property :end element)))))
21972 ((looking-at "[ \t]+") (match-string 0))
21973 (t "")))))
21974 (comment-block
21975 ;; Only fill contents if P is within block boundaries.
21976 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21977 (forward-line)
21978 (point)))
21979 (cend (save-excursion
21980 (goto-char (org-element-property :end element))
21981 (skip-chars-backward " \r\t\n")
21982 (line-beginning-position))))
21983 (when (and (>= p cbeg) (< p cend))
21984 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21985 (match-string 0)
21986 ""))))))))))
21988 (defun org-fill-element (&optional justify)
21989 "Fill element at point, when applicable.
21991 This function only applies to comment blocks, comments, example
21992 blocks and paragraphs. Also, as a special case, re-align table
21993 when point is at one.
21995 If JUSTIFY is non-nil (interactively, with prefix argument),
21996 justify as well. If `sentence-end-double-space' is non-nil, then
21997 period followed by one space does not end a sentence, so don't
21998 break a line there. The variable `fill-column' controls the
21999 width for filling.
22001 For convenience, when point is at a plain list, an item or
22002 a footnote definition, try to fill the first paragraph within."
22003 (with-syntax-table org-mode-transpose-word-syntax-table
22004 ;; Move to end of line in order to get the first paragraph within
22005 ;; a plain list or a footnote definition.
22006 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22007 ;; First check if point is in a blank line at the beginning of
22008 ;; the buffer. In that case, ignore filling.
22009 (cl-case (org-element-type element)
22010 ;; Use major mode filling function is source blocks.
22011 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22012 ;; Align Org tables, leave table.el tables as-is.
22013 (table-row (org-table-align) t)
22014 (table
22015 (when (eq (org-element-property :type element) 'org)
22016 (save-excursion
22017 (goto-char (org-element-property :post-affiliated element))
22018 (org-table-align)))
22020 (paragraph
22021 ;; Paragraphs may contain `line-break' type objects.
22022 (let ((beg (max (point-min)
22023 (org-element-property :contents-begin element)))
22024 (end (min (point-max)
22025 (org-element-property :contents-end element))))
22026 ;; Do nothing if point is at an affiliated keyword.
22027 (if (< (line-end-position) beg) t
22028 ;; Fill paragraph, taking line breaks into account.
22029 (save-excursion
22030 (goto-char beg)
22031 (let ((cuts (list beg)))
22032 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22033 (when (eq 'line-break
22034 (org-element-type
22035 (save-excursion (backward-char)
22036 (org-element-context))))
22037 (push (point) cuts)))
22038 (dolist (c (delq end cuts))
22039 (fill-region-as-paragraph c end justify)
22040 (setq end c))))
22041 t)))
22042 ;; Contents of `comment-block' type elements should be
22043 ;; filled as plain text, but only if point is within block
22044 ;; markers.
22045 (comment-block
22046 (let* ((case-fold-search t)
22047 (beg (save-excursion
22048 (goto-char (org-element-property :begin element))
22049 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22050 (forward-line)
22051 (point)))
22052 (end (save-excursion
22053 (goto-char (org-element-property :end element))
22054 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22055 (line-beginning-position))))
22056 (if (or (< (point) beg) (> (point) end)) t
22057 (fill-region-as-paragraph
22058 (save-excursion (end-of-line)
22059 (re-search-backward "^[ \t]*$" beg 'move)
22060 (line-beginning-position))
22061 (save-excursion (beginning-of-line)
22062 (re-search-forward "^[ \t]*$" end 'move)
22063 (line-beginning-position))
22064 justify))))
22065 ;; Fill comments.
22066 (comment
22067 (let ((begin (org-element-property :post-affiliated element))
22068 (end (org-element-property :end element)))
22069 (when (and (>= (point) begin) (<= (point) end))
22070 (let ((begin (save-excursion
22071 (end-of-line)
22072 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22073 (progn (forward-line) (point))
22074 begin)))
22075 (end (save-excursion
22076 (end-of-line)
22077 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22078 (1- (line-beginning-position))
22079 (skip-chars-backward " \r\t\n")
22080 (line-end-position)))))
22081 ;; Do not fill comments when at a blank line.
22082 (when (> end begin)
22083 (let ((fill-prefix
22084 (save-excursion
22085 (beginning-of-line)
22086 (looking-at "[ \t]*#")
22087 (let ((comment-prefix (match-string 0)))
22088 (goto-char (match-end 0))
22089 (if (looking-at adaptive-fill-regexp)
22090 (concat comment-prefix (match-string 0))
22091 (concat comment-prefix " "))))))
22092 (save-excursion
22093 (fill-region-as-paragraph begin end justify))))))
22095 ;; Ignore every other element.
22096 (otherwise t)))))
22098 (defun org-fill-paragraph (&optional justify region)
22099 "Fill element at point, when applicable.
22101 This function only applies to comment blocks, comments, example
22102 blocks and paragraphs. Also, as a special case, re-align table
22103 when point is at one.
22105 For convenience, when point is at a plain list, an item or
22106 a footnote definition, try to fill the first paragraph within.
22108 If JUSTIFY is non-nil (interactively, with prefix argument),
22109 justify as well. If `sentence-end-double-space' is non-nil, then
22110 period followed by one space does not end a sentence, so don't
22111 break a line there. The variable `fill-column' controls the
22112 width for filling.
22114 The REGION argument is non-nil if called interactively; in that
22115 case, if Transient Mark mode is enabled and the mark is active,
22116 fill each of the elements in the active region, instead of just
22117 filling the current element."
22118 (interactive (progn
22119 (barf-if-buffer-read-only)
22120 (list (when current-prefix-arg 'full) t)))
22121 (cond
22122 ((and region transient-mark-mode mark-active
22123 (not (eq (region-beginning) (region-end))))
22124 (let ((origin (point-marker))
22125 (start (region-beginning)))
22126 (unwind-protect
22127 (progn
22128 (goto-char (region-end))
22129 (while (> (point) start)
22130 (org-backward-paragraph)
22131 (org-fill-element justify)))
22132 (goto-char origin)
22133 (set-marker origin nil))))
22134 (t (org-fill-element justify))))
22136 (defun org-auto-fill-function ()
22137 "Auto-fill function."
22138 ;; Check if auto-filling is meaningful.
22139 (let ((fc (current-fill-column)))
22140 (when (and fc (> (current-column) fc))
22141 (let* ((fill-prefix (org-adaptive-fill-function))
22142 ;; Enforce empty fill prefix, if required. Otherwise, it
22143 ;; will be computed again.
22144 (adaptive-fill-mode (not (equal fill-prefix ""))))
22145 (when fill-prefix (do-auto-fill))))))
22147 (defun org-comment-line-break-function (&optional soft)
22148 "Break line at point and indent, continuing comment if within one.
22149 The inserted newline is marked hard if variable
22150 `use-hard-newlines' is true, unless optional argument SOFT is
22151 non-nil."
22152 (if soft (insert-and-inherit ?\n) (newline 1))
22153 (save-excursion (forward-char -1) (delete-horizontal-space))
22154 (delete-horizontal-space)
22155 (indent-to-left-margin)
22156 (insert-before-markers-and-inherit fill-prefix))
22159 ;;; Fixed Width Areas
22161 (defun org-toggle-fixed-width ()
22162 "Toggle fixed-width markup.
22164 Add or remove fixed-width markup on current line, whenever it
22165 makes sense. Return an error otherwise.
22167 If a region is active and if it contains only fixed-width areas
22168 or blank lines, remove all fixed-width markup in it. If the
22169 region contains anything else, convert all non-fixed-width lines
22170 to fixed-width ones.
22172 Blank lines at the end of the region are ignored unless the
22173 region only contains such lines."
22174 (interactive)
22175 (if (not (org-region-active-p))
22176 ;; No region:
22178 ;; Remove fixed width marker only in a fixed-with element.
22180 ;; Add fixed width maker in paragraphs, in blank lines after
22181 ;; elements or at the beginning of a headline or an inlinetask,
22182 ;; and before any one-line elements (e.g., a clock).
22183 (progn
22184 (beginning-of-line)
22185 (let* ((element (org-element-at-point))
22186 (type (org-element-type element)))
22187 (cond
22188 ((and (eq type 'fixed-width)
22189 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22190 (replace-match
22191 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22192 ((and (memq type '(babel-call clock comment diary-sexp headline
22193 horizontal-rule keyword paragraph
22194 planning))
22195 (<= (org-element-property :post-affiliated element) (point)))
22196 (skip-chars-forward " \t")
22197 (insert ": "))
22198 ((and (looking-at-p "[ \t]*$")
22199 (or (eq type 'inlinetask)
22200 (save-excursion
22201 (skip-chars-forward " \r\t\n")
22202 (<= (org-element-property :end element) (point)))))
22203 (delete-region (point) (line-end-position))
22204 (org-indent-line)
22205 (insert ": "))
22206 (t (user-error "Cannot insert a fixed-width line here")))))
22207 ;; Region active.
22208 (let* ((begin (save-excursion
22209 (goto-char (region-beginning))
22210 (line-beginning-position)))
22211 (end (copy-marker
22212 (save-excursion
22213 (goto-char (region-end))
22214 (unless (eolp) (beginning-of-line))
22215 (if (save-excursion (re-search-backward "\\S-" begin t))
22216 (progn (skip-chars-backward " \r\t\n") (point))
22217 (point)))))
22218 (all-fixed-width-p
22219 (catch 'not-all-p
22220 (save-excursion
22221 (goto-char begin)
22222 (skip-chars-forward " \r\t\n")
22223 (when (eobp) (throw 'not-all-p nil))
22224 (while (< (point) end)
22225 (let ((element (org-element-at-point)))
22226 (if (eq (org-element-type element) 'fixed-width)
22227 (goto-char (org-element-property :end element))
22228 (throw 'not-all-p nil))))
22229 t))))
22230 (if all-fixed-width-p
22231 (save-excursion
22232 (goto-char begin)
22233 (while (< (point) end)
22234 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22235 (replace-match
22236 "" nil nil nil
22237 (if (= (line-end-position) (match-end 0)) 0 1)))
22238 (forward-line)))
22239 (let ((min-ind (point-max)))
22240 ;; Find minimum indentation across all lines.
22241 (save-excursion
22242 (goto-char begin)
22243 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22244 (setq min-ind 0)
22245 (catch 'zerop
22246 (while (< (point) end)
22247 (unless (looking-at-p "[ \t]*$")
22248 (let ((ind (current-indentation)))
22249 (setq min-ind (min min-ind ind))
22250 (when (zerop ind) (throw 'zerop t))))
22251 (forward-line)))))
22252 ;; Loop over all lines and add fixed-width markup everywhere
22253 ;; but in fixed-width lines.
22254 (save-excursion
22255 (goto-char begin)
22256 (while (< (point) end)
22257 (cond
22258 ((org-at-heading-p)
22259 (insert ": ")
22260 (forward-line)
22261 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22262 (insert ":")
22263 (forward-line)))
22264 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22265 (let* ((element (org-element-at-point))
22266 (element-end (org-element-property :end element)))
22267 (if (eq (org-element-type element) 'fixed-width)
22268 (progn (goto-char element-end)
22269 (skip-chars-backward " \r\t\n")
22270 (forward-line))
22271 (let ((limit (min end element-end)))
22272 (while (< (point) limit)
22273 (org-move-to-column min-ind t)
22274 (insert ": ")
22275 (forward-line))))))
22277 (org-move-to-column min-ind t)
22278 (insert ": ")
22279 (forward-line)))))))
22280 (set-marker end nil))))
22283 ;;; Blocks
22285 (defun org-block-map (function &optional start end)
22286 "Call FUNCTION at the head of all source blocks in the current buffer.
22287 Optional arguments START and END can be used to limit the range."
22288 (let ((start (or start (point-min)))
22289 (end (or end (point-max))))
22290 (save-excursion
22291 (goto-char start)
22292 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22293 (save-excursion
22294 (save-match-data
22295 (goto-char (match-beginning 0))
22296 (funcall function)))))))
22298 (defun org-next-block (arg &optional backward block-regexp)
22299 "Jump to the next block.
22301 With a prefix argument ARG, jump forward ARG many blocks.
22303 When BACKWARD is non-nil, jump to the previous block.
22305 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22306 Match data is set according to this regexp when the function
22307 returns.
22309 Return point at beginning of the opening line of found block.
22310 Throw an error if no block is found."
22311 (interactive "p")
22312 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22313 (case-fold-search t)
22314 (search-fn (if backward #'re-search-backward #'re-search-forward))
22315 (count (or arg 1))
22316 (origin (point))
22317 last-element)
22318 (if backward (beginning-of-line) (end-of-line))
22319 (while (and (> count 0) (funcall search-fn re nil t))
22320 (let ((element (save-excursion
22321 (goto-char (match-beginning 0))
22322 (save-match-data (org-element-at-point)))))
22323 (when (and (memq (org-element-type element)
22324 '(center-block comment-block dynamic-block
22325 example-block export-block quote-block
22326 special-block src-block verse-block))
22327 (<= (match-beginning 0)
22328 (org-element-property :post-affiliated element)))
22329 (setq last-element element)
22330 (cl-decf count))))
22331 (if (= count 0)
22332 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22333 (save-match-data (org-show-context)))
22334 (goto-char origin)
22335 (user-error "No %s code blocks" (if backward "previous" "further")))))
22337 (defun org-previous-block (arg &optional block-regexp)
22338 "Jump to the previous block.
22339 With a prefix argument ARG, jump backward ARG many source blocks.
22340 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22341 (interactive "p")
22342 (org-next-block arg t block-regexp))
22345 ;;; Comments
22347 ;; Org comments syntax is quite complex. It requires the entire line
22348 ;; to be just a comment. Also, even with the right syntax at the
22349 ;; beginning of line, some elements (e.g., verse-block or
22350 ;; example-block) don't accept comments. Usual Emacs comment commands
22351 ;; cannot cope with those requirements. Therefore, Org replaces them.
22353 ;; Org still relies on `comment-dwim', but cannot trust
22354 ;; `comment-only-p'. So, `comment-region-function' and
22355 ;; `uncomment-region-function' both point
22356 ;; to`org-comment-or-uncomment-region'. Eventually,
22357 ;; `org-insert-comment' takes care of insertion of comments at the
22358 ;; beginning of line.
22360 ;; `org-setup-comments-handling' install comments related variables
22361 ;; during `org-mode' initialization.
22363 (defun org-setup-comments-handling ()
22364 (interactive)
22365 (setq-local comment-use-syntax nil)
22366 (setq-local comment-start "# ")
22367 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22368 (setq-local comment-insert-comment-function 'org-insert-comment)
22369 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22370 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22372 (defun org-insert-comment ()
22373 "Insert an empty comment above current line.
22374 If the line is empty, insert comment at its beginning. When
22375 point is within a source block, comment according to the related
22376 major mode."
22377 (if (let ((element (org-element-at-point)))
22378 (and (eq (org-element-type element) 'src-block)
22379 (< (save-excursion
22380 (goto-char (org-element-property :post-affiliated element))
22381 (line-end-position))
22382 (point))
22383 (> (save-excursion
22384 (goto-char (org-element-property :end element))
22385 (skip-chars-backward " \r\t\n")
22386 (line-beginning-position))
22387 (point))))
22388 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22389 (beginning-of-line)
22390 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22391 (open-line 1))
22392 (org-indent-line)
22393 (insert "# ")))
22395 (defvar comment-empty-lines) ; From newcomment.el.
22396 (defun org-comment-or-uncomment-region (beg end &rest _)
22397 "Comment or uncomment each non-blank line in the region.
22398 Uncomment each non-blank line between BEG and END if it only
22399 contains commented lines. Otherwise, comment them. If region is
22400 strictly within a source block, use appropriate comment syntax."
22401 (if (let ((element (org-element-at-point)))
22402 (and (eq (org-element-type element) 'src-block)
22403 (< (save-excursion
22404 (goto-char (org-element-property :post-affiliated element))
22405 (line-end-position))
22406 beg)
22407 (>= (save-excursion
22408 (goto-char (org-element-property :end element))
22409 (skip-chars-backward " \r\t\n")
22410 (line-beginning-position))
22411 end)))
22412 ;; Translate region boundaries for the Org buffer to the source
22413 ;; buffer.
22414 (let ((offset (- end beg)))
22415 (save-excursion
22416 (goto-char beg)
22417 (org-babel-do-in-edit-buffer
22418 (comment-or-uncomment-region (point) (+ offset (point))))))
22419 (save-restriction
22420 ;; Restrict region
22421 (narrow-to-region (save-excursion (goto-char beg)
22422 (skip-chars-forward " \r\t\n" end)
22423 (line-beginning-position))
22424 (save-excursion (goto-char end)
22425 (skip-chars-backward " \r\t\n" beg)
22426 (line-end-position)))
22427 (let ((uncommentp
22428 ;; UNCOMMENTP is non-nil when every non blank line between
22429 ;; BEG and END is a comment.
22430 (save-excursion
22431 (goto-char (point-min))
22432 (while (and (not (eobp))
22433 (let ((element (org-element-at-point)))
22434 (and (eq (org-element-type element) 'comment)
22435 (goto-char (min (point-max)
22436 (org-element-property
22437 :end element)))))))
22438 (eobp))))
22439 (if uncommentp
22440 ;; Only blank lines and comments in region: uncomment it.
22441 (save-excursion
22442 (goto-char (point-min))
22443 (while (not (eobp))
22444 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22445 (replace-match "" nil nil nil 1))
22446 (forward-line)))
22447 ;; Comment each line in region.
22448 (let ((min-indent (point-max)))
22449 ;; First find the minimum indentation across all lines.
22450 (save-excursion
22451 (goto-char (point-min))
22452 (while (and (not (eobp)) (not (zerop min-indent)))
22453 (unless (looking-at "[ \t]*$")
22454 (setq min-indent (min min-indent (current-indentation))))
22455 (forward-line)))
22456 ;; Then loop over all lines.
22457 (save-excursion
22458 (goto-char (point-min))
22459 (while (not (eobp))
22460 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22461 ;; Don't get fooled by invisible text (e.g. link path)
22462 ;; when moving to column MIN-INDENT.
22463 (let ((buffer-invisibility-spec nil))
22464 (org-move-to-column min-indent t))
22465 (insert comment-start))
22466 (forward-line)))))))))
22468 (defun org-comment-dwim (_arg)
22469 "Call the comment command you mean.
22470 Call `org-toggle-comment' if on a heading, otherwise call
22471 `comment-dwim', within a source edit buffer if needed."
22472 (interactive "*P")
22473 (cond ((org-at-heading-p)
22474 (call-interactively #'org-toggle-comment))
22475 ((org-in-src-block-p)
22476 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22477 (t (call-interactively #'comment-dwim))))
22480 ;;; Timestamps API
22482 ;; This section contains tools to operate on, or create, timestamp
22483 ;; objects, as returned by, e.g. `org-element-context'.
22485 (defun org-timestamp-from-string (s)
22486 "Convert Org timestamp S, as a string, into a timestamp object.
22487 Return nil if S is not a valid timestamp string."
22488 (when (org-string-nw-p s)
22489 (with-temp-buffer
22490 (save-excursion (insert s))
22491 (org-element-timestamp-parser))))
22493 (defun org-timestamp-from-time (time &optional with-time inactive)
22494 "Convert a time value into a timestamp object.
22496 TIME is an Emacs internal time representation, as returned, e.g.,
22497 by `current-time'.
22499 When optional argument WITH-TIME is non-nil, return a timestamp
22500 object with a time part, i.e., with hours and minutes.
22502 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22503 return an active timestamp."
22504 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22505 (org-element-create 'timestamp
22506 (list :type (if inactive 'inactive 'active)
22507 :year-start year
22508 :month-start month
22509 :day-start day
22510 :hour-start (and with-time hour)
22511 :minute-start (and with-time minute)))))
22513 (defun org-timestamp-to-time (timestamp &optional end)
22514 "Convert TIMESTAMP object into an Emacs internal time value.
22515 Use end of date range or time range when END is non-nil.
22516 Otherwise, use its start."
22517 (apply #'encode-time
22518 (cons 0
22519 (mapcar
22520 (lambda (prop) (or (org-element-property prop timestamp) 0))
22521 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22522 '(:minute-start :hour-start :day-start :month-start
22523 :year-start))))))
22525 (defun org-timestamp-has-time-p (timestamp)
22526 "Non-nil when TIMESTAMP has a time specified."
22527 (org-element-property :hour-start timestamp))
22529 (defun org-timestamp-format (timestamp format &optional end utc)
22530 "Format a TIMESTAMP object into a string.
22532 FORMAT is a format specifier to be passed to
22533 `format-time-string'.
22535 When optional argument END is non-nil, use end of date-range or
22536 time-range, if possible.
22538 When optional argument UTC is non-nil, time is be expressed as
22539 Universal Time."
22540 (format-time-string format (org-timestamp-to-time timestamp end)
22541 (and utc t)))
22543 (defun org-timestamp-split-range (timestamp &optional end)
22544 "Extract a TIMESTAMP object from a date or time range.
22546 END, when non-nil, means extract the end of the range.
22547 Otherwise, extract its start.
22549 Return a new timestamp object."
22550 (let ((type (org-element-property :type timestamp)))
22551 (if (memq type '(active inactive diary)) timestamp
22552 (let ((split-ts (org-element-copy timestamp)))
22553 ;; Set new type.
22554 (org-element-put-property
22555 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22556 ;; Copy start properties over end properties if END is
22557 ;; non-nil. Otherwise, copy end properties over `start' ones.
22558 (let ((p-alist '((:minute-start . :minute-end)
22559 (:hour-start . :hour-end)
22560 (:day-start . :day-end)
22561 (:month-start . :month-end)
22562 (:year-start . :year-end))))
22563 (dolist (p-cell p-alist)
22564 (org-element-put-property
22565 split-ts
22566 (funcall (if end #'car #'cdr) p-cell)
22567 (org-element-property
22568 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22569 ;; Eventually refresh `:raw-value'.
22570 (org-element-put-property split-ts :raw-value nil)
22571 (org-element-put-property
22572 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22574 (defun org-timestamp-translate (timestamp &optional boundary)
22575 "Translate TIMESTAMP object to custom format.
22577 Format string is defined in `org-time-stamp-custom-formats',
22578 which see.
22580 When optional argument BOUNDARY is non-nil, it is either the
22581 symbol `start' or `end'. In this case, only translate the
22582 starting or ending part of TIMESTAMP if it is a date or time
22583 range. Otherwise, translate both parts.
22585 Return timestamp as-is if `org-display-custom-times' is nil or if
22586 it has a `diary' type."
22587 (let ((type (org-element-property :type timestamp)))
22588 (if (or (not org-display-custom-times) (eq type 'diary))
22589 (org-element-interpret-data timestamp)
22590 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22591 org-time-stamp-custom-formats)))
22592 (if (and (not boundary) (memq type '(active-range inactive-range)))
22593 (concat (org-timestamp-format timestamp fmt)
22594 "--"
22595 (org-timestamp-format timestamp fmt t))
22596 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22598 ;;; Other stuff
22600 (defvar reftex-docstruct-symbol)
22601 (defvar org--rds)
22603 (defun org-reftex-citation ()
22604 "Use reftex-citation to insert a citation into the buffer.
22605 This looks for a line like
22607 #+BIBLIOGRAPHY: foo plain option:-d
22609 and derives from it that foo.bib is the bibliography file relevant
22610 for this document. It then installs the necessary environment for RefTeX
22611 to work in this buffer and calls `reftex-citation' to insert a citation
22612 into the buffer.
22614 Export of such citations to both LaTeX and HTML is handled by the contributed
22615 package ox-bibtex by Taru Karttunen."
22616 (interactive)
22617 (let ((reftex-docstruct-symbol 'org--rds)
22618 org--rds bib)
22619 (org-with-wide-buffer
22620 (let ((case-fold-search t)
22621 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22622 (if (not (save-excursion
22623 (or (re-search-forward re nil t)
22624 (re-search-backward re nil t))))
22625 (user-error "No bibliography defined in file")
22626 (setq bib (concat (match-string 1) ".bib")
22627 org--rds (list (list 'bib bib))))))
22628 (call-interactively 'reftex-citation)))
22630 ;;;; Functions extending outline functionality
22632 (defun org-beginning-of-line (&optional n)
22633 "Go to the beginning of the current visible line.
22635 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22636 symbol `reversed', on the first attempt move to where the
22637 headline text starts, and only move to beginning of line when the
22638 cursor is already before the start of the text of the headline.
22640 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22641 start of the text on the second attempt.
22643 With argument N not nil or 1, move forward N - 1 lines first."
22644 (interactive "^p")
22645 (let ((origin (point))
22646 (special (pcase org-special-ctrl-a/e
22647 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22648 deactivate-mark)
22649 ;; First move to a visible line.
22650 (if (bound-and-true-p visual-line-mode)
22651 (beginning-of-visual-line n)
22652 (move-beginning-of-line n)
22653 ;; `move-beginning-of-line' may leave point after invisible
22654 ;; characters if line starts with such of these (e.g., with
22655 ;; a link at column 0). Really move to the beginning of the
22656 ;; current visible line.
22657 (beginning-of-line))
22658 (cond
22659 ;; No special behavior. Point is already at the beginning of
22660 ;; a line, logical or visual.
22661 ((not special))
22662 ;; `beginning-of-visual-line' left point before logical beginning
22663 ;; of line: point is at the beginning of a visual line. Bail
22664 ;; out.
22665 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22666 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22667 ;; At a headline, special position is before the title, but
22668 ;; after any TODO keyword or priority cookie.
22669 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22670 (line-end-position)))
22671 (bol (point)))
22672 (if (eq special 'reversed)
22673 (when (and (= origin bol) (eq last-command this-command))
22674 (goto-char refpos))
22675 (when (or (> origin refpos) (= origin bol))
22676 (goto-char refpos)))))
22677 ((and (looking-at org-list-full-item-re)
22678 (memq (org-element-type (save-match-data (org-element-at-point)))
22679 '(item plain-list)))
22680 ;; Set special position at first white space character after
22681 ;; bullet, and check-box, if any.
22682 (let ((after-bullet
22683 (let ((box (match-end 3)))
22684 (cond ((not box) (match-end 1))
22685 ((eq (char-after box) ?\s) (1+ box))
22686 (t box)))))
22687 (if (eq special 'reversed)
22688 (when (and (= (point) origin) (eq last-command this-command))
22689 (goto-char after-bullet))
22690 (when (or (> origin after-bullet) (= (point) origin))
22691 (goto-char after-bullet)))))
22692 ;; No special context. Point is already at beginning of line.
22693 (t nil))))
22695 (defun org-end-of-line (&optional n)
22696 "Go to the end of the line, but before ellipsis, if any.
22698 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22699 symbol `reversed', ignore tags on the first attempt, and only
22700 move to after the tags when the cursor is already beyond the end
22701 of the headline.
22703 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22704 on the second attempt.
22706 With argument N not nil or 1, move forward N - 1 lines first."
22707 (interactive "^p")
22708 (let ((origin (point))
22709 (special (pcase org-special-ctrl-a/e
22710 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22711 deactivate-mark)
22712 ;; First move to a visible line.
22713 (if (bound-and-true-p visual-line-mode)
22714 (beginning-of-visual-line n)
22715 (move-beginning-of-line n))
22716 (cond
22717 ;; At a headline, with tags.
22718 ((and special
22719 (save-excursion
22720 (beginning-of-line)
22721 (let ((case-fold-search nil))
22722 (looking-at org-complex-heading-regexp)))
22723 (match-end 5))
22724 (let ((tags (save-excursion
22725 (goto-char (match-beginning 5))
22726 (skip-chars-backward " \t")
22727 (point)))
22728 (visual-end (and (bound-and-true-p visual-line-mode)
22729 (save-excursion
22730 (end-of-visual-line)
22731 (point)))))
22732 ;; If `end-of-visual-line' brings us before end of line or
22733 ;; even tags, i.e., the headline spans over multiple visual
22734 ;; lines, move there.
22735 (cond ((and visual-end
22736 (< visual-end tags)
22737 (<= origin visual-end))
22738 (goto-char visual-end))
22739 ((eq special 'reversed)
22740 (if (and (= origin (line-end-position))
22741 (eq this-command last-command))
22742 (goto-char tags)
22743 (end-of-line)))
22745 (if (or (< origin tags) (= origin (line-end-position)))
22746 (goto-char tags)
22747 (end-of-line))))))
22748 ((bound-and-true-p visual-line-mode)
22749 (let ((bol (line-beginning-position)))
22750 (end-of-visual-line)
22751 ;; If `end-of-visual-line' gets us past the ellipsis at the
22752 ;; end of a line, backtrack and use `end-of-line' instead.
22753 (when (/= bol (line-beginning-position))
22754 (goto-char bol)
22755 (end-of-line))))
22756 (t (end-of-line)))))
22758 (defun org-backward-sentence (&optional _arg)
22759 "Go to beginning of sentence, or beginning of table field.
22760 This will call `backward-sentence' or `org-table-beginning-of-field',
22761 depending on context."
22762 (interactive)
22763 (let* ((element (org-element-at-point))
22764 (contents-begin (org-element-property :contents-begin element))
22765 (table (org-element-lineage element '(table) t)))
22766 (if (and table
22767 (> (point) contents-begin)
22768 (<= (point) (org-element-property :contents-end table)))
22769 (call-interactively #'org-table-beginning-of-field)
22770 (save-restriction
22771 (when (and contents-begin
22772 (< (point-min) contents-begin)
22773 (> (point) contents-begin))
22774 (narrow-to-region contents-begin
22775 (org-element-property :contents-end element)))
22776 (call-interactively #'backward-sentence)))))
22778 (defun org-forward-sentence (&optional _arg)
22779 "Go to end of sentence, or end of table field.
22780 This will call `forward-sentence' or `org-table-end-of-field',
22781 depending on context."
22782 (interactive)
22783 (if (and (org-at-heading-p)
22784 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22785 (save-restriction
22786 (narrow-to-region (line-beginning-position) (line-end-position))
22787 (call-interactively #'forward-sentence))
22788 (let* ((element (org-element-at-point))
22789 (contents-end (org-element-property :contents-end element))
22790 (table (org-element-lineage element '(table) t)))
22791 (if (and table
22792 (>= (point) (org-element-property :contents-begin table))
22793 (< (point) contents-end))
22794 (call-interactively #'org-table-end-of-field)
22795 (save-restriction
22796 (when (and contents-end
22797 (> (point-max) contents-end)
22798 ;; Skip blank lines between elements.
22799 (< (org-element-property :end element)
22800 (save-excursion (goto-char contents-end)
22801 (skip-chars-forward " \r\t\n"))))
22802 (narrow-to-region (org-element-property :contents-begin element)
22803 contents-end))
22804 ;; End of heading is considered as the end of a sentence.
22805 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22806 (call-interactively #'forward-sentence)))))))
22808 (defun org-kill-line (&optional _arg)
22809 "Kill line, to tags or end of line."
22810 (interactive)
22811 (cond
22812 ((or (not org-special-ctrl-k)
22813 (bolp)
22814 (not (org-at-heading-p)))
22815 (when (and (get-char-property (line-end-position) 'invisible)
22816 org-ctrl-k-protect-subtree
22817 (or (eq org-ctrl-k-protect-subtree 'error)
22818 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22819 (user-error
22820 (substitute-command-keys
22821 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22822 (call-interactively
22823 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22824 ((org-match-line org-tag-line-re)
22825 (let ((end (save-excursion
22826 (goto-char (match-beginning 1))
22827 (skip-chars-backward " \t")
22828 (point))))
22829 (if (<= end (point)) ;on tags part
22830 (kill-region (point) (line-end-position))
22831 (kill-region (point) end)))
22832 (org-align-tags))
22833 (t (kill-region (point) (line-end-position)))))
22835 (defun org-yank (&optional arg)
22836 "Yank. If the kill is a subtree, treat it specially.
22837 This command will look at the current kill and check if is a single
22838 subtree, or a series of subtrees[1]. If it passes the test, and if the
22839 cursor is at the beginning of a line or after the stars of a currently
22840 empty headline, then the yank is handled specially. How exactly depends
22841 on the value of the following variables.
22843 `org-yank-folded-subtrees'
22844 By default, this variable is non-nil, which results in
22845 subtree(s) being folded after insertion, except if doing so
22846 would swallow text after the yanked text.
22848 `org-yank-adjusted-subtrees'
22849 When non-nil (the default value is nil), the subtree will be
22850 promoted or demoted in order to fit into the local outline tree
22851 structure, which means that the level will be adjusted so that it
22852 becomes the smaller one of the two *visible* surrounding headings.
22854 Any prefix to this command will cause `yank' to be called directly with
22855 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22856 will just
22857 plainly yank the text as it is.
22859 \[1] The test checks if the first non-white line is a heading
22860 and if there are no other headings with fewer stars."
22861 (interactive "P")
22862 (org-yank-generic 'yank arg))
22864 (defun org-yank-generic (command arg)
22865 "Perform some yank-like command.
22867 This function implements the behavior described in the `org-yank'
22868 documentation. However, it has been generalized to work for any
22869 interactive command with similar behavior."
22871 ;; pretend to be command COMMAND
22872 (setq this-command command)
22874 (if arg
22875 (call-interactively command)
22877 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22878 (and (org-kill-is-subtree-p)
22879 (or (bolp)
22880 (and (looking-at "[ \t]*$")
22881 (string-match
22882 "\\`\\*+\\'"
22883 (buffer-substring (point-at-bol) (point)))))))
22884 swallowp)
22885 (cond
22886 ((and subtreep org-yank-folded-subtrees)
22887 (let ((beg (point))
22888 end)
22889 (if (and subtreep org-yank-adjusted-subtrees)
22890 (org-paste-subtree nil nil 'for-yank)
22891 (call-interactively command))
22893 (setq end (point))
22894 (goto-char beg)
22895 (when (and (bolp) subtreep
22896 (not (setq swallowp
22897 (org-yank-folding-would-swallow-text beg end))))
22898 (org-with-limited-levels
22899 (or (looking-at org-outline-regexp)
22900 (re-search-forward org-outline-regexp-bol end t))
22901 (while (and (< (point) end) (looking-at org-outline-regexp))
22902 (outline-hide-subtree)
22903 (org-cycle-show-empty-lines 'folded)
22904 (condition-case nil
22905 (outline-forward-same-level 1)
22906 (error (goto-char end))))))
22907 (when swallowp
22908 (message
22909 "Inserted text not folded because that would swallow text"))
22911 (goto-char end)
22912 (skip-chars-forward " \t\n\r")
22913 (beginning-of-line 1)
22914 (push-mark beg 'nomsg)))
22915 ((and subtreep org-yank-adjusted-subtrees)
22916 (let ((beg (point-at-bol)))
22917 (org-paste-subtree nil nil 'for-yank)
22918 (push-mark beg 'nomsg)))
22920 (call-interactively command))))))
22922 (defun org-yank-folding-would-swallow-text (beg end)
22923 "Would hide-subtree at BEG swallow any text after END?"
22924 (let (level)
22925 (org-with-limited-levels
22926 (save-excursion
22927 (goto-char beg)
22928 (when (or (looking-at org-outline-regexp)
22929 (re-search-forward org-outline-regexp-bol end t))
22930 (setq level (org-outline-level)))
22931 (goto-char end)
22932 (skip-chars-forward " \t\r\n\v\f")
22933 (not (or (eobp)
22934 (and (bolp) (looking-at-p org-outline-regexp)
22935 (<= (org-outline-level) level))))))))
22937 (defun org-back-to-heading (&optional invisible-ok)
22938 "Call `outline-back-to-heading', but provide a better error message."
22939 (condition-case nil
22940 (outline-back-to-heading invisible-ok)
22941 (error (error "Before first headline at position %d in buffer %s"
22942 (point) (current-buffer)))))
22944 (defun org-before-first-heading-p ()
22945 "Before first heading?"
22946 (org-with-limited-levels
22947 (save-excursion
22948 (end-of-line)
22949 (null (re-search-backward org-outline-regexp-bol nil t)))))
22951 (defun org-at-heading-p (&optional _)
22952 "Non-nil when on a headline."
22953 (outline-on-heading-p t))
22955 (defun org-in-commented-heading-p (&optional no-inheritance)
22956 "Non-nil if point is under a commented heading.
22957 This function also checks ancestors of the current headline,
22958 unless optional argument NO-INHERITANCE is non-nil."
22959 (cond
22960 ((org-before-first-heading-p) nil)
22961 ((let ((headline (nth 4 (org-heading-components))))
22962 (and headline
22963 (let ((case-fold-search nil))
22964 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22965 headline)))))
22966 (no-inheritance nil)
22968 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22970 (defun org-at-comment-p nil
22971 "Is cursor in a commented line?"
22972 (save-excursion
22973 (save-match-data
22974 (beginning-of-line)
22975 (looking-at "^[ \t]*# "))))
22977 (defun org-at-drawer-p nil
22978 "Is cursor at a drawer keyword?"
22979 (save-excursion
22980 (move-beginning-of-line 1)
22981 (looking-at org-drawer-regexp)))
22983 (defun org-at-block-p nil
22984 "Is cursor at a block keyword?"
22985 (save-excursion
22986 (move-beginning-of-line 1)
22987 (looking-at org-block-regexp)))
22989 (defun org-point-at-end-of-empty-headline ()
22990 "If point is at the end of an empty headline, return t, else nil.
22991 If the heading only contains a TODO keyword, it is still still considered
22992 empty."
22993 (let ((case-fold-search nil))
22994 (and (looking-at "[ \t]*$")
22995 org-todo-line-regexp
22996 (save-excursion
22997 (beginning-of-line)
22998 (looking-at org-todo-line-regexp)
22999 (string= (match-string 3) "")))))
23001 (defun org-at-heading-or-item-p ()
23002 (or (org-at-heading-p) (org-at-item-p)))
23004 (defun org-at-target-p ()
23005 (or (org-in-regexp org-radio-target-regexp)
23006 (org-in-regexp org-target-regexp)))
23008 (defun org-up-heading-all (arg)
23009 "Move to the heading line of which the present line is a subheading.
23010 This function considers both visible and invisible heading lines.
23011 With argument, move up ARG levels."
23012 (outline-up-heading arg t))
23014 (defun org-up-heading-safe ()
23015 "Move to the heading line of which the present line is a subheading.
23016 This version will not throw an error. It will return the level of the
23017 headline found, or nil if no higher level is found.
23019 Also, this function will be a lot faster than `outline-up-heading',
23020 because it relies on stars being the outline starters. This can really
23021 make a significant difference in outlines with very many siblings."
23022 (when (ignore-errors (org-back-to-heading t))
23023 (let ((level-up (1- (funcall outline-level))))
23024 (and (> level-up 0)
23025 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23026 (funcall outline-level)))))
23028 (defun org-first-sibling-p ()
23029 "Is this heading the first child of its parents?"
23030 (interactive)
23031 (let ((re org-outline-regexp-bol)
23032 level l)
23033 (unless (org-at-heading-p t)
23034 (user-error "Not at a heading"))
23035 (setq level (funcall outline-level))
23036 (save-excursion
23037 (if (not (re-search-backward re nil t))
23039 (setq l (funcall outline-level))
23040 (< l level)))))
23042 (defun org-goto-sibling (&optional previous)
23043 "Goto the next sibling, even if it is invisible.
23044 When PREVIOUS is set, go to the previous sibling instead. Returns t
23045 when a sibling was found. When none is found, return nil and don't
23046 move point."
23047 (let ((fun (if previous 're-search-backward 're-search-forward))
23048 (pos (point))
23049 (re org-outline-regexp-bol)
23050 level l)
23051 (when (ignore-errors (org-back-to-heading t))
23052 (setq level (funcall outline-level))
23053 (catch 'exit
23054 (or previous (forward-char 1))
23055 (while (funcall fun re nil t)
23056 (setq l (funcall outline-level))
23057 (when (< l level) (goto-char pos) (throw 'exit nil))
23058 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23059 (goto-char pos)
23060 nil))))
23062 (defun org-show-siblings ()
23063 "Show all siblings of the current headline."
23064 (save-excursion
23065 (while (org-goto-sibling) (org-flag-heading nil)))
23066 (save-excursion
23067 (while (org-goto-sibling 'previous)
23068 (org-flag-heading nil))))
23070 (defun org-goto-first-child ()
23071 "Goto the first child, even if it is invisible.
23072 Return t when a child was found. Otherwise don't move point and
23073 return nil."
23074 (let (level (pos (point)) (re org-outline-regexp-bol))
23075 (when (ignore-errors (org-back-to-heading t))
23076 (setq level (outline-level))
23077 (forward-char 1)
23078 (if (and (re-search-forward re nil t) (> (outline-level) level))
23079 (progn (goto-char (match-beginning 0)) t)
23080 (goto-char pos) nil))))
23082 (defun org-show-hidden-entry ()
23083 "Show an entry where even the heading is hidden."
23084 (save-excursion
23085 (org-show-entry)))
23087 (defun org-flag-heading (flag &optional entry)
23088 "Flag the current heading. FLAG non-nil means make invisible.
23089 When ENTRY is non-nil, show the entire entry."
23090 (save-excursion
23091 (org-back-to-heading t)
23092 ;; Check if we should show the entire entry
23093 (if (not entry)
23094 (org-flag-region
23095 (line-end-position 0) (line-end-position) flag 'outline)
23096 (org-show-entry)
23097 (save-excursion
23098 (and (outline-next-heading)
23099 (org-flag-heading nil))))))
23101 (defun org-get-next-sibling ()
23102 "Move to next heading of the same level, and return point.
23103 If there is no such heading, return nil.
23104 This is like outline-next-sibling, but invisible headings are ok."
23105 (let ((level (funcall outline-level)))
23106 (outline-next-heading)
23107 (while (and (not (eobp)) (> (funcall outline-level) level))
23108 (outline-next-heading))
23109 (unless (or (eobp) (< (funcall outline-level) level))
23110 (point))))
23112 (defun org-get-last-sibling ()
23113 "Move to previous heading of the same level, and return point.
23114 If there is no such heading, return nil."
23115 (let ((opoint (point))
23116 (level (funcall outline-level)))
23117 (outline-previous-heading)
23118 (when (and (/= (point) opoint) (outline-on-heading-p t))
23119 (while (and (> (funcall outline-level) level)
23120 (not (bobp)))
23121 (outline-previous-heading))
23122 (unless (< (funcall outline-level) level)
23123 (point)))))
23125 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23126 "Goto to the end of a subtree."
23127 ;; This contains an exact copy of the original function, but it uses
23128 ;; `org-back-to-heading', to make it work also in invisible
23129 ;; trees. And is uses an invisible-ok argument.
23130 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23131 ;; Furthermore, when used inside Org, finding the end of a large subtree
23132 ;; with many children and grandchildren etc, this can be much faster
23133 ;; than the outline version.
23134 (org-back-to-heading invisible-ok)
23135 (let ((first t)
23136 (level (funcall outline-level)))
23137 (if (and (derived-mode-p 'org-mode) (< level 1000))
23138 ;; A true heading (not a plain list item), in Org
23139 ;; This means we can easily find the end by looking
23140 ;; only for the right number of stars. Using a regexp to do
23141 ;; this is so much faster than using a Lisp loop.
23142 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23143 (forward-char 1)
23144 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23145 ;; something else, do it the slow way
23146 (while (and (not (eobp))
23147 (or first (> (funcall outline-level) level)))
23148 (setq first nil)
23149 (outline-next-heading)))
23150 (unless to-heading
23151 (when (memq (preceding-char) '(?\n ?\^M))
23152 ;; Go to end of line before heading
23153 (forward-char -1)
23154 (when (memq (preceding-char) '(?\n ?\^M))
23155 ;; leave blank line before heading
23156 (forward-char -1)))))
23157 (point))
23159 (defun org-end-of-meta-data (&optional full)
23160 "Skip planning line and properties drawer in current entry.
23161 When optional argument FULL is non-nil, also skip empty lines,
23162 clocking lines and regular drawers at the beginning of the
23163 entry."
23164 (org-back-to-heading t)
23165 (forward-line)
23166 (when (looking-at-p org-planning-line-re) (forward-line))
23167 (when (looking-at org-property-drawer-re)
23168 (goto-char (match-end 0))
23169 (forward-line))
23170 (when (and full (not (org-at-heading-p)))
23171 (catch 'exit
23172 (let ((end (save-excursion (outline-next-heading) (point)))
23173 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23174 (while (not (eobp))
23175 (cond ((looking-at-p org-drawer-regexp)
23176 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23177 (forward-line)
23178 (throw 'exit t)))
23179 ((looking-at-p re) (forward-line))
23180 (t (throw 'exit t))))))))
23182 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23183 "Move forward to the ARG'th subheading at same level as this one.
23184 Stop at the first and last subheadings of a superior heading.
23185 Normally this only looks at visible headings, but when INVISIBLE-OK is
23186 non-nil it will also look at invisible ones."
23187 (interactive "p")
23188 (let ((backward? (and arg (< arg 0))))
23189 (if (org-before-first-heading-p)
23190 (if backward? (goto-char (point-min)) (outline-next-heading))
23191 (org-back-to-heading invisible-ok)
23192 (unless backward? (end-of-line)) ;do not match current headline
23193 (let ((level (- (match-end 0) (match-beginning 0) 1))
23194 (f (if backward? #'re-search-backward #'re-search-forward))
23195 (count (if arg (abs arg) 1))
23196 (result (point)))
23197 (while (and (> count 0)
23198 (funcall f org-outline-regexp-bol nil 'move))
23199 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23200 (cond ((< l level) (setq count 0))
23201 ((and (= l level)
23202 (or invisible-ok
23203 (not (org-invisible-p
23204 (line-beginning-position)))))
23205 (cl-decf count)
23206 (when (= l level) (setq result (point)))))))
23207 (goto-char result))
23208 (beginning-of-line))))
23210 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23211 "Move backward to the ARG'th subheading at same level as this one.
23212 Stop at the first and last subheadings of a superior heading."
23213 (interactive "p")
23214 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23216 (defun org-next-visible-heading (arg)
23217 "Move to the next visible heading.
23219 This function wraps `outline-next-visible-heading' with
23220 `org-with-limited-levels' in order to skip over inline tasks and
23221 respect customization of `org-odd-levels-only'."
23222 (interactive "p")
23223 (org-with-limited-levels
23224 (outline-next-visible-heading arg)))
23226 (defun org-previous-visible-heading (arg)
23227 "Move to the previous visible heading.
23229 This function wraps `outline-previous-visible-heading' with
23230 `org-with-limited-levels' in order to skip over inline tasks and
23231 respect customization of `org-odd-levels-only'."
23232 (interactive "p")
23233 (org-with-limited-levels
23234 (outline-previous-visible-heading arg)))
23236 (defun org-forward-paragraph ()
23237 "Move forward to beginning of next paragraph or equivalent.
23239 The function moves point to the beginning of the next visible
23240 structural element, which can be a paragraph, a table, a list
23241 item, etc. It also provides some special moves for convenience:
23243 - On an affiliated keyword, jump to the beginning of the
23244 relative element.
23245 - On an item or a footnote definition, move to the second
23246 element inside, if any.
23247 - On a table or a property drawer, jump after it.
23248 - On a verse or source block, stop after blank lines."
23249 (interactive)
23250 (unless (eobp)
23251 (let* ((deactivate-mark nil)
23252 (element (org-element-at-point))
23253 (type (org-element-type element))
23254 (post-affiliated (org-element-property :post-affiliated element))
23255 (contents-begin (org-element-property :contents-begin element))
23256 (contents-end (org-element-property :contents-end element))
23257 (end (let ((end (org-element-property :end element)) (parent element))
23258 (while (and (setq parent (org-element-property :parent parent))
23259 (= (org-element-property :contents-end parent) end))
23260 (setq end (org-element-property :end parent)))
23261 end)))
23262 (cond ((not element)
23263 (skip-chars-forward " \r\t\n")
23264 (or (eobp) (beginning-of-line)))
23265 ;; On affiliated keywords, move to element's beginning.
23266 ((< (point) post-affiliated)
23267 (goto-char post-affiliated))
23268 ;; At a table row, move to the end of the table. Similarly,
23269 ;; at a node property, move to the end of the property
23270 ;; drawer.
23271 ((memq type '(node-property table-row))
23272 (goto-char (org-element-property
23273 :end (org-element-property :parent element))))
23274 ((memq type '(property-drawer table)) (goto-char end))
23275 ;; Consider blank lines as separators in verse and source
23276 ;; blocks to ease editing.
23277 ((memq type '(src-block verse-block))
23278 (when (eq type 'src-block)
23279 (setq contents-end
23280 (save-excursion (goto-char end)
23281 (skip-chars-backward " \r\t\n")
23282 (line-beginning-position))))
23283 (beginning-of-line)
23284 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23285 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23286 (goto-char end)
23287 (skip-chars-forward " \r\t\n")
23288 (if (= (point) contents-end) (goto-char end)
23289 (beginning-of-line))))
23290 ;; With no contents, just skip element.
23291 ((not contents-begin) (goto-char end))
23292 ;; If contents are invisible, skip the element altogether.
23293 ((org-invisible-p (line-end-position))
23294 (cl-case type
23295 (headline
23296 (org-with-limited-levels (outline-next-visible-heading 1)))
23297 ;; At a plain list, make sure we move to the next item
23298 ;; instead of skipping the whole list.
23299 (plain-list (forward-char)
23300 (org-forward-paragraph))
23301 (otherwise (goto-char end))))
23302 ((>= (point) contents-end) (goto-char end))
23303 ((>= (point) contents-begin)
23304 ;; This can only happen on paragraphs and plain lists.
23305 (cl-case type
23306 (paragraph (goto-char end))
23307 ;; At a plain list, try to move to second element in
23308 ;; first item, if possible.
23309 (plain-list (end-of-line)
23310 (org-forward-paragraph))))
23311 ;; When contents start on the middle of a line (e.g. in
23312 ;; items and footnote definitions), try to reach first
23313 ;; element starting after current line.
23314 ((> (line-end-position) contents-begin)
23315 (end-of-line)
23316 (org-forward-paragraph))
23317 (t (goto-char contents-begin))))))
23319 (defun org-backward-paragraph ()
23320 "Move backward to start of previous paragraph or equivalent.
23322 The function moves point to the beginning of the current
23323 structural element, which can be a paragraph, a table, a list
23324 item, etc., or to the beginning of the previous visible one if
23325 point is already there. It also provides some special moves for
23326 convenience:
23328 - On an affiliated keyword, jump to the first one.
23329 - On a table or a property drawer, move to its beginning.
23330 - On comment, example, export, src and verse blocks, stop
23331 before blank lines."
23332 (interactive)
23333 (unless (bobp)
23334 (let* ((deactivate-mark nil)
23335 (element (org-element-at-point))
23336 (type (org-element-type element))
23337 (contents-end (org-element-property :contents-end element))
23338 (post-affiliated (org-element-property :post-affiliated element))
23339 (begin (org-element-property :begin element))
23340 (special? ;blocks handled specially
23341 (memq type '(comment-block example-block export-block src-block
23342 verse-block)))
23343 (contents-begin
23344 (if special?
23345 ;; These types have no proper contents. Fake line
23346 ;; below the block opening line as contents beginning.
23347 (save-excursion (goto-char begin) (line-beginning-position 2))
23348 (org-element-property :contents-begin element))))
23349 (cond
23350 ((not element) (goto-char (point-min)))
23351 ((= (point) begin)
23352 (backward-char)
23353 (org-backward-paragraph))
23354 ((<= (point) post-affiliated) (goto-char begin))
23355 ;; Special behavior: on a table or a property drawer, move to
23356 ;; its beginning.
23357 ((memq type '(node-property table-row))
23358 (goto-char (org-element-property
23359 :post-affiliated (org-element-property :parent element))))
23360 (special?
23361 (if (<= (point) contents-begin) (goto-char post-affiliated)
23362 ;; Inside a verse block, see blank lines as paragraph
23363 ;; separators.
23364 (let ((origin (point)))
23365 (skip-chars-backward " \r\t\n" contents-begin)
23366 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23367 (skip-chars-forward " \r\t\n" origin)
23368 (if (= (point) origin) (goto-char contents-begin)
23369 (beginning-of-line))))))
23370 ((eq type 'paragraph) (goto-char contents-begin)
23371 ;; When at first paragraph in an item or a footnote definition,
23372 ;; move directly to beginning of line.
23373 (let ((parent-contents
23374 (org-element-property
23375 :contents-begin (org-element-property :parent element))))
23376 (when (and parent-contents (= parent-contents contents-begin))
23377 (beginning-of-line))))
23378 ;; At the end of a greater element, move to the beginning of
23379 ;; the last element within.
23380 ((and contents-end (>= (point) contents-end))
23381 (goto-char (1- contents-end))
23382 (org-backward-paragraph))
23383 (t (goto-char (or post-affiliated begin))))
23384 ;; Ensure we never leave point invisible.
23385 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23387 (defun org-forward-element ()
23388 "Move forward by one element.
23389 Move to the next element at the same level, when possible."
23390 (interactive)
23391 (cond ((eobp) (user-error "Cannot move further down"))
23392 ((org-with-limited-levels (org-at-heading-p))
23393 (let ((origin (point)))
23394 (goto-char (org-end-of-subtree nil t))
23395 (unless (org-with-limited-levels (org-at-heading-p))
23396 (goto-char origin)
23397 (user-error "Cannot move further down"))))
23399 (let* ((elem (org-element-at-point))
23400 (end (org-element-property :end elem))
23401 (parent (org-element-property :parent elem)))
23402 (cond ((and parent (= (org-element-property :contents-end parent) end))
23403 (goto-char (org-element-property :end parent)))
23404 ((integer-or-marker-p end) (goto-char end))
23405 (t (message "No element at point")))))))
23407 (defun org-backward-element ()
23408 "Move backward by one element.
23409 Move to the previous element at the same level, when possible."
23410 (interactive)
23411 (cond ((bobp) (user-error "Cannot move further up"))
23412 ((org-with-limited-levels (org-at-heading-p))
23413 ;; At a headline, move to the previous one, if any, or stay
23414 ;; here.
23415 (let ((origin (point)))
23416 (org-with-limited-levels (org-backward-heading-same-level 1))
23417 ;; When current headline has no sibling above, move to its
23418 ;; parent.
23419 (when (= (point) origin)
23420 (or (org-with-limited-levels (org-up-heading-safe))
23421 (progn (goto-char origin)
23422 (user-error "Cannot move further up"))))))
23424 (let* ((elem (org-element-at-point))
23425 (beg (org-element-property :begin elem)))
23426 (cond
23427 ;; Move to beginning of current element if point isn't
23428 ;; there already.
23429 ((null beg) (message "No element at point"))
23430 ((/= (point) beg) (goto-char beg))
23431 (t (goto-char beg)
23432 (skip-chars-backward " \r\t\n")
23433 (unless (bobp)
23434 (let ((prev (org-element-at-point)))
23435 (goto-char (org-element-property :begin prev))
23436 (while (and (setq prev (org-element-property :parent prev))
23437 (<= (org-element-property :end prev) beg))
23438 (goto-char (org-element-property :begin prev)))))))))))
23440 (defun org-up-element ()
23441 "Move to upper element."
23442 (interactive)
23443 (if (org-with-limited-levels (org-at-heading-p))
23444 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23445 (let* ((elem (org-element-at-point))
23446 (parent (org-element-property :parent elem)))
23447 (if parent (goto-char (org-element-property :begin parent))
23448 (if (org-with-limited-levels (org-before-first-heading-p))
23449 (user-error "No surrounding element")
23450 (org-with-limited-levels (org-back-to-heading)))))))
23452 (defun org-down-element ()
23453 "Move to inner element."
23454 (interactive)
23455 (let ((element (org-element-at-point)))
23456 (cond
23457 ((memq (org-element-type element) '(plain-list table))
23458 (goto-char (org-element-property :contents-begin element))
23459 (forward-char))
23460 ((memq (org-element-type element) org-element-greater-elements)
23461 ;; If contents are hidden, first disclose them.
23462 (when (org-invisible-p (line-end-position)) (org-cycle))
23463 (goto-char (or (org-element-property :contents-begin element)
23464 (user-error "No content for this element"))))
23465 (t (user-error "No inner element")))))
23467 (defun org-drag-element-backward ()
23468 "Move backward element at point."
23469 (interactive)
23470 (let ((elem (or (org-element-at-point)
23471 (user-error "No element at point"))))
23472 (if (eq (org-element-type elem) 'headline)
23473 ;; Preserve point when moving a whole tree, even if point was
23474 ;; on blank lines below the headline.
23475 (let ((offset (skip-chars-backward " \t\n")))
23476 (unwind-protect (org-move-subtree-up)
23477 (forward-char (- offset))))
23478 (let ((prev-elem
23479 (save-excursion
23480 (goto-char (org-element-property :begin elem))
23481 (skip-chars-backward " \r\t\n")
23482 (unless (bobp)
23483 (let* ((beg (org-element-property :begin elem))
23484 (prev (org-element-at-point))
23485 (up prev))
23486 (while (and (setq up (org-element-property :parent up))
23487 (<= (org-element-property :end up) beg))
23488 (setq prev up))
23489 prev)))))
23490 ;; Error out if no previous element or previous element is
23491 ;; a parent of the current one.
23492 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23493 (user-error "Cannot drag element backward")
23494 (let ((pos (point)))
23495 (org-element-swap-A-B prev-elem elem)
23496 (goto-char (+ (org-element-property :begin prev-elem)
23497 (- pos (org-element-property :begin elem))))))))))
23499 (defun org-drag-element-forward ()
23500 "Move forward element at point."
23501 (interactive)
23502 (let* ((pos (point))
23503 (elem (or (org-element-at-point)
23504 (user-error "No element at point"))))
23505 (when (= (point-max) (org-element-property :end elem))
23506 (user-error "Cannot drag element forward"))
23507 (goto-char (org-element-property :end elem))
23508 (let ((next-elem (org-element-at-point)))
23509 (when (or (org-element-nested-p elem next-elem)
23510 (and (eq (org-element-type next-elem) 'headline)
23511 (not (eq (org-element-type elem) 'headline))))
23512 (goto-char pos)
23513 (user-error "Cannot drag element forward"))
23514 ;; Compute new position of point: it's shifted by NEXT-ELEM
23515 ;; body's length (without final blanks) and by the length of
23516 ;; blanks between ELEM and NEXT-ELEM.
23517 (let ((size-next (- (save-excursion
23518 (goto-char (org-element-property :end next-elem))
23519 (skip-chars-backward " \r\t\n")
23520 (forward-line)
23521 ;; Small correction if buffer doesn't end
23522 ;; with a newline character.
23523 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23524 (org-element-property :begin next-elem)))
23525 (size-blank (- (org-element-property :end elem)
23526 (save-excursion
23527 (goto-char (org-element-property :end elem))
23528 (skip-chars-backward " \r\t\n")
23529 (forward-line)
23530 (point)))))
23531 (org-element-swap-A-B elem next-elem)
23532 (goto-char (+ pos size-next size-blank))))))
23534 (defun org-drag-line-forward (arg)
23535 "Drag the line at point ARG lines forward."
23536 (interactive "p")
23537 (dotimes (_ (abs arg))
23538 (let ((c (current-column)))
23539 (if (< 0 arg)
23540 (progn
23541 (beginning-of-line 2)
23542 (transpose-lines 1)
23543 (beginning-of-line 0))
23544 (transpose-lines 1)
23545 (beginning-of-line -1))
23546 (org-move-to-column c))))
23548 (defun org-drag-line-backward (arg)
23549 "Drag the line at point ARG lines backward."
23550 (interactive "p")
23551 (org-drag-line-forward (- arg)))
23553 (defun org-mark-element ()
23554 "Put point at beginning of this element, mark at end.
23556 Interactively, if this command is repeated or (in Transient Mark
23557 mode) if the mark is active, it marks the next element after the
23558 ones already marked."
23559 (interactive)
23560 (let (deactivate-mark)
23561 (if (and (called-interactively-p 'any)
23562 (or (and (eq last-command this-command) (mark t))
23563 (and transient-mark-mode mark-active)))
23564 (set-mark
23565 (save-excursion
23566 (goto-char (mark))
23567 (goto-char (org-element-property :end (org-element-at-point)))))
23568 (let ((element (org-element-at-point)))
23569 (end-of-line)
23570 (push-mark (org-element-property :end element) t t)
23571 (goto-char (org-element-property :begin element))))))
23573 (defun org-narrow-to-element ()
23574 "Narrow buffer to current element."
23575 (interactive)
23576 (let ((elem (org-element-at-point)))
23577 (cond
23578 ((eq (car elem) 'headline)
23579 (narrow-to-region
23580 (org-element-property :begin elem)
23581 (org-element-property :end elem)))
23582 ((memq (car elem) org-element-greater-elements)
23583 (narrow-to-region
23584 (org-element-property :contents-begin elem)
23585 (org-element-property :contents-end elem)))
23587 (narrow-to-region
23588 (org-element-property :begin elem)
23589 (org-element-property :end elem))))))
23591 (defun org-transpose-element ()
23592 "Transpose current and previous elements, keeping blank lines between.
23593 Point is moved after both elements."
23594 (interactive)
23595 (org-skip-whitespace)
23596 (let ((end (org-element-property :end (org-element-at-point))))
23597 (org-drag-element-backward)
23598 (goto-char end)))
23600 (defun org-unindent-buffer ()
23601 "Un-indent the visible part of the buffer.
23602 Relative indentation (between items, inside blocks, etc.) isn't
23603 modified."
23604 (interactive)
23605 (unless (eq major-mode 'org-mode)
23606 (user-error "Cannot un-indent a buffer not in Org mode"))
23607 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23608 (unindent-tree
23609 (lambda (contents)
23610 (dolist (element (reverse contents))
23611 (if (memq (org-element-type element) '(headline section))
23612 (funcall unindent-tree (org-element-contents element))
23613 (save-excursion
23614 (save-restriction
23615 (narrow-to-region
23616 (org-element-property :begin element)
23617 (org-element-property :end element))
23618 (org-do-remove-indentation))))))))
23619 (funcall unindent-tree (org-element-contents parse-tree))))
23621 (defun org-make-options-regexp (kwds &optional extra)
23622 "Make a regular expression for keyword lines.
23623 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23624 when non-nil, is a regexp matching keywords names."
23625 (concat "^[ \t]*#\\+\\("
23626 (regexp-opt kwds)
23627 (and extra (concat (and kwds "\\|") extra))
23628 "\\):[ \t]*\\(.*\\)"))
23631 ;;; Conveniently switch to Info nodes
23633 (defun org-info-find-node (&optional nodename)
23634 "Find Info documentation NODENAME or Org documentation according context.
23635 Started from `gnus-info-find-node'."
23636 (interactive)
23637 (Info-goto-node
23638 (or nodename
23639 (let ((default-org-info-node "(org) Top"))
23640 (cond
23641 ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
23642 ((eq 'org-mode major-mode)
23643 (let* ((context (org-element-at-point))
23644 (element-info-nodes ; compare to `org-element-all-elements'.
23645 `((babel-call . "(org) Evaluating Code Blocks")
23646 (center-block . "(org) Paragraphs")
23647 (clock . ,default-org-info-node)
23648 (comment . "(org) Comment Lines")
23649 (comment-block . "(org) Comment Lines")
23650 (diary-sexp . ,default-org-info-node)
23651 (drawer . "(org) Drawers")
23652 (dynamic-block . "(org) Dynamic Blocks")
23653 (example-block . "(org) Literal Examples")
23654 (export-block . "(org) ASCII/Latin-1/UTF-8 export")
23655 (fixed-width . ,default-org-info-node)
23656 (footnote-definition . "(org) Creating Footnotes")
23657 (headline . "(org) Document Structure")
23658 (horizontal-rule . "(org) Built-in Table Editor")
23659 (inlinetask . ,default-org-info-node)
23660 (item . "(org) Plain Lists")
23661 (keyword . "(org) Per-file keywords")
23662 (latex-environment . "(org) LaTeX Export")
23663 (node-property . "(org) Properties and Columns")
23664 (paragraph . "(org) Paragraphs")
23665 (plain-list . "(org) Plain Lists")
23666 (planning . "(org) Deadlines and Scheduling")
23667 (property-drawer . "(org) Properties and Columns")
23668 (quote-block . "(org) Paragraphs")
23669 (section . ,default-org-info-node)
23670 (special-block . ,default-org-info-node)
23671 (src-block . "(org) Working with Source Code")
23672 (table . "(org) Tables")
23673 (table-row . "(org) Tables")
23674 (verse-block . "(org) Paragraphs"))))
23675 (or (cdr (assoc (car context) element-info-nodes))
23676 default-org-info-node)))
23677 (t default-org-info-node))))))
23680 ;;; Finish up
23682 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23683 (lambda () (add-hook 'change-major-mode-hook
23684 'org-show-all 'append 'local)))
23686 (provide 'org)
23688 (run-hooks 'org-load-hook)
23690 ;;; org.el ends here