Silence byte-compiler
[org-mode/org-tableheadings.git] / lisp / org.el
blob71921cfe88d91980ce8fd210112677b6ef04ebbd
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]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
678 "Regular expression for specifying repeated events.
679 After a match, group 1 contains the repeat expression.")
681 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
682 "Formats for `format-time-string' which are used for time stamps.")
685 ;;; The custom variables
687 (defgroup org nil
688 "Outline-based notes management and organizer."
689 :tag "Org"
690 :group 'outlines
691 :group 'calendar)
693 (defcustom org-mode-hook nil
694 "Mode hook for Org mode, run after the mode was turned on."
695 :group 'org
696 :type 'hook)
698 (defcustom org-load-hook nil
699 "Hook that is run after org.el has been loaded."
700 :group 'org
701 :type 'hook)
703 (defcustom org-log-buffer-setup-hook nil
704 "Hook that is run after an Org log buffer is created."
705 :group 'org
706 :version "24.1"
707 :type 'hook)
709 (defvar org-modules) ; defined below
710 (defvar org-modules-loaded nil
711 "Have the modules been loaded already?")
713 (defun org-load-modules-maybe (&optional force)
714 "Load all extensions listed in `org-modules'."
715 (when (or force (not org-modules-loaded))
716 (dolist (ext org-modules)
717 (condition-case nil (require ext)
718 (error (message "Problems while trying to load feature `%s'" ext))))
719 (setq org-modules-loaded t)))
721 (defun org-set-modules (var value)
722 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
723 (set var value)
724 (when (featurep 'org)
725 (org-load-modules-maybe 'force)
726 (org-element-cache-reset 'all)))
728 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
729 "Modules that should always be loaded together with org.el.
731 If a description starts with <C>, the file is not part of Emacs
732 and loading it will require that you have downloaded and properly
733 installed the Org mode distribution.
735 You can also use this system to load external packages (i.e. neither Org
736 core modules, nor modules from the CONTRIB directory). Just add symbols
737 to the end of the list. If the package is called org-xyz.el, then you need
738 to add the symbol `xyz', and the package must have a call to:
740 (provide \\='org-xyz)
742 For export specific modules, see also `org-export-backends'."
743 :group 'org
744 :set 'org-set-modules
745 :version "26.1"
746 :package-version '(Org . "9.2")
747 :type
748 '(set :greedy t
749 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
750 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
751 (const :tag " crypt: Encryption of subtrees" org-crypt)
752 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
753 (const :tag " docview: Links to doc-view buffers" org-docview)
754 (const :tag " eww: Store link to url of eww" org-eww)
755 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
756 (const :tag " habit: Track your consistency with habits" org-habit)
757 (const :tag " id: Global IDs for identifying entries" org-id)
758 (const :tag " info: Links to Info nodes" org-info)
759 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
760 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
761 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
762 (const :tag " mouse: Additional mouse support" org-mouse)
763 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
764 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
765 (const :tag " tempo: Fast completion for structures" org-tempo)
766 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
767 (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
769 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
770 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
771 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
772 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
773 (const :tag "C collector: Collect properties into tables" org-collector)
774 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
775 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
776 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
777 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
778 (const :tag "C eval: Include command output as text" org-eval)
779 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
780 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
781 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
782 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
783 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
784 (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
785 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
786 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
787 (const :tag "C man: Support for links to manpages in Org mode" org-man)
788 (const :tag "C mew: Links to Mew folders/messages" org-mew)
789 (const :tag "C notify: Notifications for Org-mode" org-notify)
790 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
791 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
792 (const :tag "C registry: A registry for Org links" org-registry)
793 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
794 (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
795 (const :tag "C secretary: Team management with Org" org-secretary)
796 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
797 (const :tag "C toc: Table of contents for Org buffer" org-toc)
798 (const :tag "C track: Keep up with Org mode development" org-track)
799 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
800 (const :tag "C vm: Links to VM folders/messages" org-vm)
801 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
802 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
803 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
805 (defvar org-export-registered-backends) ; From ox.el.
806 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
807 (declare-function org-export-backend-name "ox" (backend) t)
808 (defcustom org-export-backends '(ascii html icalendar latex odt)
809 "List of export back-ends that should be always available.
811 If a description starts with <C>, the file is not part of Emacs
812 and loading it will require that you have downloaded and properly
813 installed the Org mode distribution.
815 Unlike to `org-modules', libraries in this list will not be
816 loaded along with Org, but only once the export framework is
817 needed.
819 This variable needs to be set before org.el is loaded. If you
820 need to make a change while Emacs is running, use the customize
821 interface or run the following code, where VAL stands for the new
822 value of the variable, after updating it:
824 (progn
825 (setq org-export-registered-backends
826 (cl-remove-if-not
827 (lambda (backend)
828 (let ((name (org-export-backend-name backend)))
829 (or (memq name val)
830 (catch \\='parentp
831 (dolist (b val)
832 (and (org-export-derived-backend-p b name)
833 (throw \\='parentp t)))))))
834 org-export-registered-backends))
835 (let ((new-list (mapcar #\\='org-export-backend-name
836 org-export-registered-backends)))
837 (dolist (backend val)
838 (cond
839 ((not (load (format \"ox-%s\" backend) t t))
840 (message \"Problems while trying to load export back-end \\=`%s\\='\"
841 backend))
842 ((not (memq backend new-list)) (push backend new-list))))
843 (set-default \\='org-export-backends new-list)))
845 Adding a back-end to this list will also pull the back-end it
846 depends on, if any."
847 :group 'org
848 :group 'org-export
849 :version "26.1"
850 :package-version '(Org . "9.0")
851 :initialize 'custom-initialize-set
852 :set (lambda (var val)
853 (if (not (featurep 'ox)) (set-default var val)
854 ;; Any back-end not required anymore (not present in VAL and not
855 ;; a parent of any back-end in the new value) is removed from the
856 ;; list of registered back-ends.
857 (setq org-export-registered-backends
858 (cl-remove-if-not
859 (lambda (backend)
860 (let ((name (org-export-backend-name backend)))
861 (or (memq name val)
862 (catch 'parentp
863 (dolist (b val)
864 (and (org-export-derived-backend-p b name)
865 (throw 'parentp t)))))))
866 org-export-registered-backends))
867 ;; Now build NEW-LIST of both new back-ends and required
868 ;; parents.
869 (let ((new-list (mapcar #'org-export-backend-name
870 org-export-registered-backends)))
871 (dolist (backend val)
872 (cond
873 ((not (load (format "ox-%s" backend) t t))
874 (message "Problems while trying to load export back-end `%s'"
875 backend))
876 ((not (memq backend new-list)) (push backend new-list))))
877 ;; Set VAR to that list with fixed dependencies.
878 (set-default var new-list))))
879 :type '(set :greedy t
880 (const :tag " ascii Export buffer to ASCII format" ascii)
881 (const :tag " beamer Export buffer to Beamer presentation" beamer)
882 (const :tag " html Export buffer to HTML format" html)
883 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
884 (const :tag " latex Export buffer to LaTeX format" latex)
885 (const :tag " man Export buffer to MAN format" man)
886 (const :tag " md Export buffer to Markdown format" md)
887 (const :tag " odt Export buffer to ODT format" odt)
888 (const :tag " org Export buffer to Org format" org)
889 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
890 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
891 (const :tag "C deck Export buffer to deck.js presentations" deck)
892 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
893 (const :tag "C groff Export buffer to Groff format" groff)
894 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
895 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
896 (const :tag "C s5 Export buffer to s5 presentations" s5)
897 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
899 (eval-after-load 'ox
900 '(dolist (backend org-export-backends)
901 (condition-case nil (require (intern (format "ox-%s" backend)))
902 (error (message "Problems while trying to load export back-end `%s'"
903 backend)))))
905 (defcustom org-support-shift-select nil
906 "Non-nil means make shift-cursor commands select text when possible.
907 \\<org-mode-map>\
909 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
910 start selecting a region, or enlarge regions started in this way.
911 In Org mode, in special contexts, these same keys are used for
912 other purposes, important enough to compete with shift selection.
913 Org tries to balance these needs by supporting `shift-select-mode'
914 outside these special contexts, under control of this variable.
916 The default of this variable is nil, to avoid confusing behavior. Shifted
917 cursor keys will then execute Org commands in the following contexts:
918 - on a headline, changing TODO state (left/right) and priority (up/down)
919 - on a time stamp, changing the time
920 - in a plain list item, changing the bullet type
921 - in a property definition line, switching between allowed values
922 - in the BEGIN line of a clock table (changing the time block).
923 Outside these contexts, the commands will throw an error.
925 When this variable is t and the cursor is not in a special
926 context, Org mode will support shift-selection for making and
927 enlarging regions. To make this more effective, the bullet
928 cycling will no longer happen anywhere in an item line, but only
929 if the cursor is exactly on the bullet.
931 If you set this variable to the symbol `always', then the keys
932 will not be special in headlines, property lines, and item lines,
933 to make shift selection work there as well. If this is what you
934 want, you can use the following alternative commands:
935 `\\[org-todo]' and `\\[org-priority]' \
936 to change TODO state and priority,
937 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
938 can be used to switch TODO sets,
939 `\\[org-ctrl-c-minus]' to cycle item bullet types,
940 and properties can be edited by hand or in column view.
942 However, when the cursor is on a timestamp, shift-cursor commands
943 will still edit the time stamp - this is just too good to give up."
944 :group 'org
945 :type '(choice
946 (const :tag "Never" nil)
947 (const :tag "When outside special context" t)
948 (const :tag "Everywhere except timestamps" always)))
950 (defcustom org-loop-over-headlines-in-active-region nil
951 "Shall some commands act upon headlines in the active region?
953 When set to t, some commands will be performed in all headlines
954 within the active region.
956 When set to `start-level', some commands will be performed in all
957 headlines within the active region, provided that these headlines
958 are of the same level than the first one.
960 When set to a string, those commands will be performed on the
961 matching headlines within the active region. Such string must be
962 a tags/property/todo match as it is used in the agenda tags view.
964 The list of commands is: `org-schedule', `org-deadline',
965 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
966 `org-archive-to-archive-sibling'. The archiving commands skip
967 already archived entries."
968 :type '(choice (const :tag "Don't loop" nil)
969 (const :tag "All headlines in active region" t)
970 (const :tag "In active region, headlines at the same level than the first one" start-level)
971 (string :tag "Tags/Property/Todo matcher"))
972 :version "24.1"
973 :group 'org-todo
974 :group 'org-archive)
976 (defcustom org-startup-folded t
977 "Non-nil means entering Org mode will switch to OVERVIEW.
979 This can also be configured on a per-file basis by adding one of
980 the following lines anywhere in the buffer:
982 #+STARTUP: fold (or `overview', this is equivalent)
983 #+STARTUP: nofold (or `showall', this is equivalent)
984 #+STARTUP: content
985 #+STARTUP: showeverything
987 Set `org-agenda-inhibit-startup' to a non-nil value if you want
988 to ignore this option when Org opens agenda files for the first
989 time."
990 :group 'org-startup
991 :type '(choice
992 (const :tag "nofold: show all" nil)
993 (const :tag "fold: overview" t)
994 (const :tag "content: all headlines" content)
995 (const :tag "show everything, even drawers" showeverything)))
997 (defcustom org-startup-truncated t
998 "Non-nil means entering Org mode will set `truncate-lines'.
999 This is useful since some lines containing links can be very long and
1000 uninteresting. Also tables look terrible when wrapped.
1002 The variable `org-startup-truncated' allows to configure
1003 truncation for Org mode different to the other modes that use the
1004 variable `truncate-lines' and as a shortcut instead of putting
1005 the variable `truncate-lines' into the `org-mode-hook'. If one
1006 wants to configure truncation for Org mode not statically but
1007 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
1008 the variable `truncate-lines' has to be used because in such a
1009 case it is too late to set the variable `org-startup-truncated'."
1010 :group 'org-startup
1011 :type 'boolean)
1013 (defcustom org-startup-indented nil
1014 "Non-nil means turn on `org-indent-mode' on startup.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1018 #+STARTUP: indent
1019 #+STARTUP: noindent"
1020 :group 'org-structure
1021 :type '(choice
1022 (const :tag "Not" nil)
1023 (const :tag "Globally (slow on startup in large files)" t)))
1025 (defcustom org-use-sub-superscripts t
1026 "Non-nil means interpret \"_\" and \"^\" for display.
1028 If you want to control how Org exports those characters, see
1029 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
1030 used to be an alias for `org-export-with-sub-superscripts' in
1031 Org <8.0, it is not anymore.
1033 When this option is turned on, you can use TeX-like syntax for
1034 sub- and superscripts within the buffer. Several characters after
1035 \"_\" or \"^\" will be considered as a single item - so grouping
1036 with {} is normally not needed. For example, the following things
1037 will be parsed as single sub- or superscripts:
1039 10^24 or 10^tau several digits will be considered 1 item.
1040 10^-12 or 10^-tau a leading sign with digits or a word
1041 x^2-y^3 will be read as x^2 - y^3, because items are
1042 terminated by almost any nonword/nondigit char.
1043 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1045 Still, ambiguity is possible. So when in doubt, use {} to enclose
1046 the sub/superscript. If you set this variable to the symbol `{}',
1047 the braces are *required* in order to trigger interpretations as
1048 sub/superscript. This can be helpful in documents that need \"_\"
1049 frequently in plain text."
1050 :group 'org-startup
1051 :version "24.4"
1052 :package-version '(Org . "8.0")
1053 :type '(choice
1054 (const :tag "Always interpret" t)
1055 (const :tag "Only with braces" {})
1056 (const :tag "Never interpret" nil)))
1058 (defcustom org-startup-with-beamer-mode nil
1059 "Non-nil means turn on `org-beamer-mode' on startup.
1060 This can also be configured on a per-file basis by adding one of
1061 the following lines anywhere in the buffer:
1063 #+STARTUP: beamer"
1064 :group 'org-startup
1065 :version "24.1"
1066 :type 'boolean)
1068 (defcustom org-startup-align-all-tables nil
1069 "Non-nil means align all tables when visiting a file.
1070 This can also be configured on a per-file basis by adding one of
1071 the following lines anywhere in the buffer:
1072 #+STARTUP: align
1073 #+STARTUP: noalign"
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-startup-shrink-all-tables nil
1078 "Non-nil means shrink all table columns with a width cookie.
1079 This can also be configured on a per-file basis by adding one of
1080 the following lines anywhere in the buffer:
1081 #+STARTUP: shrink"
1082 :group 'org-startup
1083 :type 'boolean
1084 :version "27.1"
1085 :package-version '(Org . "9.2")
1086 :safe #'booleanp)
1088 (defcustom org-startup-with-inline-images nil
1089 "Non-nil means show inline images when loading a new Org file.
1090 This can also be configured on a per-file basis by adding one of
1091 the following lines anywhere in the buffer:
1092 #+STARTUP: inlineimages
1093 #+STARTUP: noinlineimages"
1094 :group 'org-startup
1095 :version "24.1"
1096 :type 'boolean)
1098 (defcustom org-startup-with-latex-preview nil
1099 "Non-nil means preview LaTeX fragments when loading a new Org file.
1101 This can also be configured on a per-file basis by adding one of
1102 the following lines anywhere in the buffer:
1103 #+STARTUP: latexpreview
1104 #+STARTUP: nolatexpreview"
1105 :group 'org-startup
1106 :version "24.4"
1107 :package-version '(Org . "8.0")
1108 :type 'boolean)
1110 (defcustom org-insert-mode-line-in-empty-file nil
1111 "Non-nil means insert the first line setting Org mode in empty files.
1112 When the function `org-mode' is called interactively in an empty file, this
1113 normally means that the file name does not automatically trigger Org mode.
1114 To ensure that the file will always be in Org mode in the future, a
1115 line enforcing Org mode will be inserted into the buffer, if this option
1116 has been set."
1117 :group 'org-startup
1118 :type 'boolean)
1120 (defcustom org-replace-disputed-keys nil
1121 "Non-nil means use alternative key bindings for some keys.
1123 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1124 These keys are also used by other packages like Shift Select mode,
1125 CUA mode or Windmove. If you want to use Org mode together with
1126 one of these other modes, or more generally if you would like to
1127 move some Org mode commands to other keys, set this variable and
1128 configure the keys with the variable `org-disputed-keys'.
1130 This option is only relevant at load-time of Org mode, and must be set
1131 *before* org.el is loaded. Changing it requires a restart of Emacs to
1132 become effective."
1133 :group 'org-startup
1134 :type 'boolean)
1136 (defcustom org-use-extra-keys nil
1137 "Non-nil means use extra key sequence definitions for certain commands.
1138 This happens automatically if `window-system' is nil. This
1139 variable lets you do the same manually. You must set it before
1140 loading Org."
1141 :group 'org-startup
1142 :type 'boolean)
1144 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1146 (defcustom org-disputed-keys
1147 '(([(shift up)] . [(meta p)])
1148 ([(shift down)] . [(meta n)])
1149 ([(shift left)] . [(meta -)])
1150 ([(shift right)] . [(meta +)])
1151 ([(control shift right)] . [(meta shift +)])
1152 ([(control shift left)] . [(meta shift -)]))
1153 "Keys for which Org mode and other modes compete.
1154 This is an alist, cars are the default keys, second element specifies
1155 the alternative to use when `org-replace-disputed-keys' is t.
1157 Keys can be specified in any syntax supported by `define-key'.
1158 The value of this option takes effect only at Org mode startup,
1159 therefore you'll have to restart Emacs to apply it after changing."
1160 :group 'org-startup
1161 :type 'alist)
1163 (defun org-key (key)
1164 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1165 Or return the original if not disputed."
1166 (when org-replace-disputed-keys
1167 (let* ((nkey (key-description key))
1168 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1169 org-disputed-keys)))
1170 (setq key (if x (cdr x) key))))
1171 key)
1173 (defun org-defkey (keymap key def)
1174 "Define a key, possibly translated, as returned by `org-key'."
1175 (define-key keymap (org-key key) def))
1177 (defcustom org-ellipsis nil
1178 "The ellipsis to use in the Org mode outline.
1180 When nil, just use the standard three dots. When a non-empty string,
1181 use that string instead.
1183 The change affects only Org mode (which will then use its own display table).
1184 Changing this requires executing `\\[org-mode]' in a buffer to become
1185 effective."
1186 :group 'org-startup
1187 :type '(choice (const :tag "Default" nil)
1188 (string :tag "String" :value "...#"))
1189 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1191 (defvar org-display-table nil
1192 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1194 (defgroup org-keywords nil
1195 "Keywords in Org mode."
1196 :tag "Org Keywords"
1197 :group 'org)
1199 (defcustom org-closed-keep-when-no-todo nil
1200 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1201 :group 'org-todo
1202 :group 'org-keywords
1203 :version "24.4"
1204 :package-version '(Org . "8.0")
1205 :type 'boolean)
1207 (defgroup org-structure nil
1208 "Options concerning the general structure of Org files."
1209 :tag "Org Structure"
1210 :group 'org)
1212 (defgroup org-reveal-location nil
1213 "Options about how to make context of a location visible."
1214 :tag "Org Reveal Location"
1215 :group 'org-structure)
1217 (defcustom org-show-context-detail '((agenda . local)
1218 (bookmark-jump . lineage)
1219 (isearch . lineage)
1220 (default . ancestors))
1221 "Alist between context and visibility span when revealing a location.
1223 \\<org-mode-map>Some actions may move point into invisible
1224 locations. As a consequence, Org always expose a neighborhood
1225 around point. How much is shown depends on the initial action,
1226 or context. Valid contexts are
1228 agenda when exposing an entry from the agenda
1229 org-goto when using the command `org-goto' (`\\[org-goto]')
1230 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1231 tags-tree when constructing a sparse tree based on tags matches
1232 link-search when exposing search matches associated with a link
1233 mark-goto when exposing the jump goal of a mark
1234 bookmark-jump when exposing a bookmark location
1235 isearch when exiting from an incremental search
1236 default default for all contexts not set explicitly
1238 Allowed visibility spans are
1240 minimal show current headline; if point is not on headline,
1241 also show entry
1243 local show current headline, entry and next headline
1245 ancestors show current headline and its direct ancestors; if
1246 point is not on headline, also show entry
1248 lineage show current headline, its direct ancestors and all
1249 their children; if point is not on headline, also show
1250 entry and first child
1252 tree show current headline, its direct ancestors and all
1253 their children; if point is not on headline, also show
1254 entry and all children
1256 canonical show current headline, its direct ancestors along with
1257 their entries and children; if point is not located on
1258 the headline, also show current entry and all children
1260 As special cases, a nil or t value means show all contexts in
1261 `minimal' or `canonical' view, respectively.
1263 Some views can make displayed information very compact, but also
1264 make it harder to edit the location of the match. In such
1265 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1266 more context."
1267 :group 'org-reveal-location
1268 :version "26.1"
1269 :package-version '(Org . "9.0")
1270 :type '(choice
1271 (const :tag "Canonical" t)
1272 (const :tag "Minimal" nil)
1273 (repeat :greedy t :tag "Individual contexts"
1274 (cons
1275 (choice :tag "Context"
1276 (const agenda)
1277 (const org-goto)
1278 (const occur-tree)
1279 (const tags-tree)
1280 (const link-search)
1281 (const mark-goto)
1282 (const bookmark-jump)
1283 (const isearch)
1284 (const default))
1285 (choice :tag "Detail level"
1286 (const minimal)
1287 (const local)
1288 (const ancestors)
1289 (const lineage)
1290 (const tree)
1291 (const canonical))))))
1293 (defcustom org-indirect-buffer-display 'other-window
1294 "How should indirect tree buffers be displayed?
1296 This applies to indirect buffers created with the commands
1297 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1299 Valid values are:
1300 current-window Display in the current window
1301 other-window Just display in another window.
1302 dedicated-frame Create one new frame, and re-use it each time.
1303 new-frame Make a new frame each time. Note that in this case
1304 previously-made indirect buffers are kept, and you need to
1305 kill these buffers yourself."
1306 :group 'org-structure
1307 :group 'org-agenda-windows
1308 :type '(choice
1309 (const :tag "In current window" current-window)
1310 (const :tag "In current frame, other window" other-window)
1311 (const :tag "Each time a new frame" new-frame)
1312 (const :tag "One dedicated frame" dedicated-frame)))
1314 (defcustom org-use-speed-commands nil
1315 "Non-nil means activate single letter commands at beginning of a headline.
1316 This may also be a function to test for appropriate locations where speed
1317 commands should be active.
1319 For example, to activate speed commands when the point is on any
1320 star at the beginning of the headline, you can do this:
1322 (setq org-use-speed-commands
1323 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1324 :group 'org-structure
1325 :type '(choice
1326 (const :tag "Never" nil)
1327 (const :tag "At beginning of headline stars" t)
1328 (function)))
1330 (defcustom org-speed-commands-user nil
1331 "Alist of additional speed commands.
1332 This list will be checked before `org-speed-commands-default'
1333 when the variable `org-use-speed-commands' is non-nil
1334 and when the cursor is at the beginning of a headline.
1335 The car of each entry is a string with a single letter, which must
1336 be assigned to `self-insert-command' in the global map.
1337 The cdr is either a command to be called interactively, a function
1338 to be called, or a form to be evaluated.
1339 An entry that is just a list with a single string will be interpreted
1340 as a descriptive headline that will be added when listing the speed
1341 commands in the Help buffer using the `?' speed command."
1342 :group 'org-structure
1343 :type '(repeat :value ("k" . ignore)
1344 (choice :value ("k" . ignore)
1345 (list :tag "Descriptive Headline" (string :tag "Headline"))
1346 (cons :tag "Letter and Command"
1347 (string :tag "Command letter")
1348 (choice
1349 (function)
1350 (sexp))))))
1352 (defcustom org-bookmark-names-plist
1353 '(:last-capture "org-capture-last-stored"
1354 :last-refile "org-refile-last-stored"
1355 :last-capture-marker "org-capture-last-stored-marker")
1356 "Names for bookmarks automatically set by some Org commands.
1357 This can provide strings as names for a number of bookmarks Org sets
1358 automatically. The following keys are currently implemented:
1359 :last-capture
1360 :last-capture-marker
1361 :last-refile
1362 When a key does not show up in the property list, the corresponding bookmark
1363 is not set."
1364 :group 'org-structure
1365 :type 'plist)
1367 (defgroup org-cycle nil
1368 "Options concerning visibility cycling in Org mode."
1369 :tag "Org Cycle"
1370 :group 'org-structure)
1372 (defcustom org-cycle-skip-children-state-if-no-children t
1373 "Non-nil means skip CHILDREN state in entries that don't have any."
1374 :group 'org-cycle
1375 :type 'boolean)
1377 (defcustom org-cycle-max-level nil
1378 "Maximum level which should still be subject to visibility cycling.
1379 Levels higher than this will, for cycling, be treated as text, not a headline.
1380 When `org-odd-levels-only' is set, a value of N in this variable actually
1381 means 2N-1 stars as the limiting headline.
1382 When nil, cycle all levels.
1383 Note that the limiting level of cycling is also influenced by
1384 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1385 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1386 than its value."
1387 :group 'org-cycle
1388 :type '(choice
1389 (const :tag "No limit" nil)
1390 (integer :tag "Maximum level")))
1392 (defcustom org-hide-block-startup nil
1393 "Non-nil means entering Org mode will fold all blocks.
1394 This can also be set in on a per-file basis with
1396 #+STARTUP: hideblocks
1397 #+STARTUP: showblocks"
1398 :group 'org-startup
1399 :group 'org-cycle
1400 :type 'boolean)
1402 (defcustom org-cycle-global-at-bob nil
1403 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1405 This makes it possible to do global cycling without having to use `S-TAB'
1406 or `\\[universal-argument] TAB'. For this special case to work, the first \
1407 line of the buffer
1408 must not be a headline -- it may be empty or some other text.
1410 When used in this way, `org-cycle-hook' is disabled temporarily to make
1411 sure the cursor stays at the beginning of the buffer.
1413 When this option is nil, don't do anything special at the beginning of
1414 the buffer."
1415 :group 'org-cycle
1416 :type 'boolean)
1418 (defcustom org-cycle-level-after-item/entry-creation t
1419 "Non-nil means cycle entry level or item indentation in new empty entries.
1421 When the cursor is at the end of an empty headline, i.e., with only stars
1422 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1423 and then all possible ancestor states, before returning to the original state.
1424 This makes data entry extremely fast: M-RET to create a new headline,
1425 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1427 When the cursor is at the end of an empty plain list item, one TAB will
1428 make it a subitem, two or more tabs will back up to make this an item
1429 higher up in the item hierarchy."
1430 :group 'org-cycle
1431 :type 'boolean)
1433 (defcustom org-cycle-emulate-tab t
1434 "Where should `org-cycle' emulate TAB.
1435 nil Never
1436 white Only in completely white lines
1437 whitestart Only at the beginning of lines, before the first non-white char
1438 t Everywhere except in headlines
1439 exc-hl-bol Everywhere except at the start of a headline
1440 If TAB is used in a place where it does not emulate TAB, the current subtree
1441 visibility is cycled."
1442 :group 'org-cycle
1443 :type '(choice (const :tag "Never" nil)
1444 (const :tag "Only in completely white lines" white)
1445 (const :tag "Before first char in a line" whitestart)
1446 (const :tag "Everywhere except in headlines" t)
1447 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1449 (defcustom org-cycle-separator-lines 2
1450 "Number of empty lines needed to keep an empty line between collapsed trees.
1451 If you leave an empty line between the end of a subtree and the following
1452 headline, this empty line is hidden when the subtree is folded.
1453 Org mode will leave (exactly) one empty line visible if the number of
1454 empty lines is equal or larger to the number given in this variable.
1455 So the default 2 means at least 2 empty lines after the end of a subtree
1456 are needed to produce free space between a collapsed subtree and the
1457 following headline.
1459 If the number is negative, and the number of empty lines is at least -N,
1460 all empty lines are shown.
1462 Special case: when 0, never leave empty lines in collapsed view."
1463 :group 'org-cycle
1464 :type 'integer)
1465 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1467 (defcustom org-pre-cycle-hook nil
1468 "Hook that is run before visibility cycling is happening.
1469 The function(s) in this hook must accept a single argument which indicates
1470 the new state that will be set right after running this hook. The
1471 argument is a symbol. Before a global state change, it can have the values
1472 `overview', `content', or `all'. Before a local state change, it can have
1473 the values `folded', `children', or `subtree'."
1474 :group 'org-cycle
1475 :type 'hook)
1477 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1478 org-cycle-show-empty-lines
1479 org-optimize-window-after-visibility-change)
1480 "Hook that is run after `org-cycle' has changed the buffer visibility.
1481 The function(s) in this hook must accept a single argument which indicates
1482 the new state that was set by the most recent `org-cycle' command. The
1483 argument is a symbol. After a global state change, it can have the values
1484 `overview', `contents', or `all'. After a local state change, it can have
1485 the values `folded', `children', or `subtree'."
1486 :group 'org-cycle
1487 :type 'hook
1488 :version "26.1"
1489 :package-version '(Org . "8.3"))
1491 (defgroup org-edit-structure nil
1492 "Options concerning structure editing in Org mode."
1493 :tag "Org Edit Structure"
1494 :group 'org-structure)
1496 (defcustom org-odd-levels-only nil
1497 "Non-nil means skip even levels and only use odd levels for the outline.
1498 This has the effect that two stars are being added/taken away in
1499 promotion/demotion commands. It also influences how levels are
1500 handled by the exporters.
1501 Changing it requires restart of `font-lock-mode' to become effective
1502 for fontification also in regions already fontified.
1503 You may also set this on a per-file basis by adding one of the following
1504 lines to the buffer:
1506 #+STARTUP: odd
1507 #+STARTUP: oddeven"
1508 :group 'org-edit-structure
1509 :group 'org-appearance
1510 :type 'boolean)
1512 (defcustom org-adapt-indentation t
1513 "Non-nil means adapt indentation to outline node level.
1515 When this variable is set, Org assumes that you write outlines by
1516 indenting text in each node to align with the headline (after the
1517 stars). The following issues are influenced by this variable:
1519 - The indentation is increased by one space in a demotion
1520 command, and decreased by one in a promotion command. However,
1521 in the latter case, if shifting some line in the entry body
1522 would alter document structure (e.g., insert a new headline),
1523 indentation is not changed at all.
1525 - Property drawers and planning information is inserted indented
1526 when this variable is set. When nil, they will not be indented.
1528 - TAB indents a line relative to current level. The lines below
1529 a headline will be indented when this variable is set.
1531 Note that this is all about true indentation, by adding and
1532 removing space characters. See also \"org-indent.el\" which does
1533 level-dependent indentation in a virtual way, i.e. at display
1534 time in Emacs."
1535 :group 'org-edit-structure
1536 :type 'boolean
1537 :safe #'booleanp)
1539 (defcustom org-special-ctrl-a/e nil
1540 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1542 When t, `C-a' will bring back the cursor to the beginning of the
1543 headline text, i.e. after the stars and after a possible TODO
1544 keyword. In an item, this will be the position after bullet and
1545 check-box, if any. When the cursor is already at that position,
1546 another `C-a' will bring it to the beginning of the line.
1548 `C-e' will jump to the end of the headline, ignoring the presence
1549 of tags in the headline. A second `C-e' will then jump to the
1550 true end of the line, after any tags. This also means that, when
1551 this variable is non-nil, `C-e' also will never jump beyond the
1552 end of the heading of a folded section, i.e. not after the
1553 ellipses.
1555 When set to the symbol `reversed', the first `C-a' or `C-e' works
1556 normally, going to the true line boundary first. Only a directly
1557 following, identical keypress will bring the cursor to the
1558 special positions.
1560 This may also be a cons cell where the behavior for `C-a' and
1561 `C-e' is set separately."
1562 :group 'org-edit-structure
1563 :type '(choice
1564 (const :tag "off" nil)
1565 (const :tag "on: after stars/bullet and before tags first" t)
1566 (const :tag "reversed: true line boundary first" reversed)
1567 (cons :tag "Set C-a and C-e separately"
1568 (choice :tag "Special C-a"
1569 (const :tag "off" nil)
1570 (const :tag "on: after stars/bullet first" t)
1571 (const :tag "reversed: before stars/bullet first" reversed))
1572 (choice :tag "Special C-e"
1573 (const :tag "off" nil)
1574 (const :tag "on: before tags first" t)
1575 (const :tag "reversed: after tags first" reversed)))))
1576 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1578 (defcustom org-special-ctrl-k nil
1579 "Non-nil means `C-k' will behave specially in headlines.
1580 When nil, `C-k' will call the default `kill-line' command.
1581 When t, the following will happen while the cursor is in the headline:
1583 - When the cursor is at the beginning of a headline, kill the entire
1584 line and possible the folded subtree below the line.
1585 - When in the middle of the headline text, kill the headline up to the tags.
1586 - When after the headline text, kill the tags."
1587 :group 'org-edit-structure
1588 :type 'boolean)
1590 (defcustom org-ctrl-k-protect-subtree nil
1591 "Non-nil means, do not delete a hidden subtree with C-k.
1592 When set to the symbol `error', simply throw an error when C-k is
1593 used to kill (part-of) a headline that has hidden text behind it.
1594 Any other non-nil value will result in a query to the user, if it is
1595 OK to kill that hidden subtree. When nil, kill without remorse."
1596 :group 'org-edit-structure
1597 :version "24.1"
1598 :type '(choice
1599 (const :tag "Do not protect hidden subtrees" nil)
1600 (const :tag "Protect hidden subtrees with a security query" t)
1601 (const :tag "Never kill a hidden subtree with C-k" error)))
1603 (defcustom org-special-ctrl-o t
1604 "Non-nil means, make `C-o' insert a row in tables."
1605 :group 'org-edit-structure
1606 :type 'boolean)
1608 (defcustom org-catch-invisible-edits nil
1609 "Check if in invisible region before inserting or deleting a character.
1610 Valid values are:
1612 nil Do not check, so just do invisible edits.
1613 error Throw an error and do nothing.
1614 show Make point visible, and do the requested edit.
1615 show-and-error Make point visible, then throw an error and abort the edit.
1616 smart Make point visible, and do insertion/deletion if it is
1617 adjacent to visible text and the change feels predictable.
1618 Never delete a previously invisible character or add in the
1619 middle or right after an invisible region. Basically, this
1620 allows insertion and backward-delete right before ellipses.
1621 FIXME: maybe in this case we should not even show?"
1622 :group 'org-edit-structure
1623 :version "24.1"
1624 :type '(choice
1625 (const :tag "Do not check" nil)
1626 (const :tag "Throw error when trying to edit" error)
1627 (const :tag "Unhide, but do not do the edit" show-and-error)
1628 (const :tag "Show invisible part and do the edit" show)
1629 (const :tag "Be smart and do the right thing" smart)))
1631 (defcustom org-yank-folded-subtrees t
1632 "Non-nil means when yanking subtrees, fold them.
1633 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1634 it starts with a heading and all other headings in it are either children
1635 or siblings, then fold all the subtrees. However, do this only if no
1636 text after the yank would be swallowed into a folded tree by this action."
1637 :group 'org-edit-structure
1638 :type 'boolean)
1640 (defcustom org-yank-adjusted-subtrees nil
1641 "Non-nil means when yanking subtrees, adjust the level.
1642 With this setting, `org-paste-subtree' is used to insert the subtree, see
1643 this function for details."
1644 :group 'org-edit-structure
1645 :type 'boolean)
1647 (defcustom org-M-RET-may-split-line '((default . t))
1648 "Non-nil means M-RET will split the line at the cursor position.
1649 When nil, it will go to the end of the line before making a
1650 new line.
1651 You may also set this option in a different way for different
1652 contexts. Valid contexts are:
1654 headline when creating a new headline
1655 item when creating a new item
1656 table in a table field
1657 default the value to be used for all contexts not explicitly
1658 customized"
1659 :group 'org-structure
1660 :group 'org-table
1661 :type '(choice
1662 (const :tag "Always" t)
1663 (const :tag "Never" nil)
1664 (repeat :greedy t :tag "Individual contexts"
1665 (cons
1666 (choice :tag "Context"
1667 (const headline)
1668 (const item)
1669 (const table)
1670 (const default))
1671 (boolean)))))
1674 (defcustom org-insert-heading-respect-content nil
1675 "Non-nil means insert new headings after the current subtree.
1676 \\<org-mode-map>
1677 When nil, the new heading is created directly after the current line.
1678 The commands `\\[org-insert-heading-respect-content]' and \
1679 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1680 for the duration of the command."
1681 :group 'org-structure
1682 :type 'boolean)
1684 (defcustom org-blank-before-new-entry '((heading . auto)
1685 (plain-list-item . auto))
1686 "Should `org-insert-heading' leave a blank line before new heading/item?
1687 The value is an alist, with `heading' and `plain-list-item' as CAR,
1688 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1689 which case Org will look at the surrounding headings/items and try to
1690 make an intelligent decision whether to insert a blank line or not."
1691 :group 'org-edit-structure
1692 :type '(list
1693 (cons (const heading)
1694 (choice (const :tag "Never" nil)
1695 (const :tag "Always" t)
1696 (const :tag "Auto" auto)))
1697 (cons (const plain-list-item)
1698 (choice (const :tag "Never" nil)
1699 (const :tag "Always" t)
1700 (const :tag "Auto" auto)))))
1702 (defcustom org-insert-heading-hook nil
1703 "Hook being run after inserting a new heading."
1704 :group 'org-edit-structure
1705 :type 'hook)
1707 (defcustom org-enable-fixed-width-editor t
1708 "Non-nil means lines starting with \":\" are treated as fixed-width.
1709 This currently only means they are never auto-wrapped.
1710 When nil, such lines will be treated like ordinary lines."
1711 :group 'org-edit-structure
1712 :type 'boolean)
1714 (defgroup org-sparse-trees nil
1715 "Options concerning sparse trees in Org mode."
1716 :tag "Org Sparse Trees"
1717 :group 'org-structure)
1719 (defcustom org-highlight-sparse-tree-matches t
1720 "Non-nil means highlight all matches that define a sparse tree.
1721 The highlights will automatically disappear the next time the buffer is
1722 changed by an edit command."
1723 :group 'org-sparse-trees
1724 :type 'boolean)
1726 (defcustom org-remove-highlights-with-change t
1727 "Non-nil means any change to the buffer will remove temporary highlights.
1728 \\<org-mode-map>\
1729 Such highlights are created by `org-occur' and `org-clock-display'.
1730 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1731 to get rid of the highlights.
1732 The highlights created by `org-toggle-latex-fragment' always need
1733 `\\[org-toggle-latex-fragment]' to be removed."
1734 :group 'org-sparse-trees
1735 :group 'org-time
1736 :type 'boolean)
1738 (defcustom org-occur-case-fold-search t
1739 "Non-nil means `org-occur' should be case-insensitive.
1740 If set to `smart' the search will be case-insensitive only if it
1741 doesn't specify any upper case character."
1742 :group 'org-sparse-trees
1743 :version "26.1"
1744 :type '(choice
1745 (const :tag "Case-sensitive" nil)
1746 (const :tag "Case-insensitive" t)
1747 (const :tag "Case-insensitive for lower case searches only" smart)))
1749 (defcustom org-occur-hook '(org-first-headline-recenter)
1750 "Hook that is run after `org-occur' has constructed a sparse tree.
1751 This can be used to recenter the window to show as much of the structure
1752 as possible."
1753 :group 'org-sparse-trees
1754 :type 'hook)
1756 (defgroup org-table nil
1757 "Options concerning tables in Org mode."
1758 :tag "Org Table"
1759 :group 'org)
1761 (defcustom org-self-insert-cluster-for-undo nil
1762 "Non-nil means cluster self-insert commands for undo when possible.
1763 If this is set, then, like in the Emacs command loop, 20 consecutive
1764 characters will be undone together.
1765 This is configurable, because there is some impact on typing performance."
1766 :group 'org-table
1767 :type 'boolean)
1769 (defcustom org-table-tab-recognizes-table.el t
1770 "Non-nil means TAB will automatically notice a table.el table.
1771 When it sees such a table, it moves point into it and - if necessary -
1772 calls `table-recognize-table'."
1773 :group 'org-table-editing
1774 :type 'boolean)
1776 (defgroup org-link nil
1777 "Options concerning links in Org mode."
1778 :tag "Org Link"
1779 :group 'org)
1781 (defvar-local org-link-abbrev-alist-local nil
1782 "Buffer-local version of `org-link-abbrev-alist', which see.
1783 The value of this is taken from the #+LINK lines.")
1785 (defcustom org-link-parameters
1786 '(("doi" :follow org--open-doi-link)
1787 ("elisp" :follow org--open-elisp-link)
1788 ("file" :complete org-file-complete-link)
1789 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1790 ("help" :follow org--open-help-link)
1791 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1792 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1793 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1794 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1795 ("shell" :follow org--open-shell-link))
1796 "An alist of properties that defines all the links in Org mode.
1797 The key in each association is a string of the link type.
1798 Subsequent optional elements make up a p-list of link properties.
1800 :follow - A function that takes the link path as an argument.
1802 :export - A function that takes the link path, description and
1803 export-backend as arguments.
1805 :store - A function responsible for storing the link. See the
1806 function `org-store-link-functions'.
1808 :complete - A function that inserts a link with completion. The
1809 function takes one optional prefix arg.
1811 :face - A face for the link, or a function that returns a face.
1812 The function takes one argument which is the link path. The
1813 default face is `org-link'.
1815 :mouse-face - The mouse-face. The default is `highlight'.
1817 :display - `full' will not fold the link in descriptive
1818 display. Default is `org-link'.
1820 :help-echo - A string or function that takes (window object position)
1821 as arguments and returns a string.
1823 :keymap - A keymap that is active on the link. The default is
1824 `org-mouse-map'.
1826 :htmlize-link - A function for the htmlize-link. Defaults
1827 to (list :uri \"type:path\")
1829 :activate-func - A function to run at the end of font-lock
1830 activation. The function must accept (link-start link-end path bracketp)
1831 as arguments."
1832 :group 'org-link
1833 :type '(alist :tag "Link display parameters"
1834 :value-type plist)
1835 :version "26.1"
1836 :package-version '(Org . "9.1"))
1838 (defun org-link-get-parameter (type key)
1839 "Get TYPE link property for KEY.
1840 TYPE is a string and KEY is a plist keyword."
1841 (plist-get
1842 (cdr (assoc type org-link-parameters))
1843 key))
1845 (defun org-link-set-parameters (type &rest parameters)
1846 "Set link TYPE properties to PARAMETERS.
1847 PARAMETERS should be :key val pairs."
1848 (let ((data (assoc type org-link-parameters)))
1849 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1850 (push (cons type parameters) org-link-parameters)
1851 (org-make-link-regexps)
1852 (org-element-update-syntax))))
1854 (defun org-link-types ()
1855 "Return a list of known link types."
1856 (mapcar #'car org-link-parameters))
1858 (defcustom org-link-abbrev-alist nil
1859 "Alist of link abbreviations.
1860 The car of each element is a string, to be replaced at the start of a link.
1861 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1862 links in Org buffers can have an optional tag after a double colon, e.g.,
1864 [[linkkey:tag][description]]
1866 The `linkkey' must be a single word, starting with a letter, followed
1867 by letters, numbers, `-' or `_'.
1869 If REPLACE is a string, the tag will simply be appended to create the link.
1870 If the string contains \"%s\", the tag will be inserted there. If the string
1871 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1872 at that point (see the function `url-hexify-string'). If the string contains
1873 the specifier \"%(my-function)\", then the custom function `my-function' will
1874 be invoked: this function takes the tag as its only argument and must return
1875 a string.
1877 REPLACE may also be a function that will be called with the tag as the
1878 only argument to create the link, which should be returned as a string.
1880 See the manual for examples."
1881 :group 'org-link
1882 :type '(repeat
1883 (cons
1884 (string :tag "Protocol")
1885 (choice
1886 (string :tag "Format")
1887 (function)))))
1889 (defcustom org-descriptive-links t
1890 "Non-nil means Org will display descriptive links.
1891 E.g. [[https://orgmode.org][Org website]] will be displayed as
1892 \"Org Website\", hiding the link itself and just displaying its
1893 description. When set to nil, Org will display the full links
1894 literally.
1896 You can interactively set the value of this variable by calling
1897 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1898 :group 'org-link
1899 :type 'boolean)
1901 (defcustom org-link-file-path-type 'adaptive
1902 "How the path name in file links should be stored.
1903 Valid values are:
1905 relative Relative to the current directory, i.e. the directory of the file
1906 into which the link is being inserted.
1907 absolute Absolute path, if possible with ~ for home directory.
1908 noabbrev Absolute path, no abbreviation of home directory.
1909 adaptive Use relative path for files in the current directory and sub-
1910 directories of it. For other files, use an absolute path."
1911 :group 'org-link
1912 :type '(choice
1913 (const relative)
1914 (const absolute)
1915 (const noabbrev)
1916 (const adaptive)))
1918 (defvaralias 'org-activate-links 'org-highlight-links)
1919 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1920 "Types of links that should be highlighted in Org files.
1922 This is a list of symbols, each one of them leading to the
1923 highlighting of a certain link type.
1925 You can still open links that are not highlighted.
1927 In principle, it does not hurt to turn on highlighting for all
1928 link types. There may be a small gain when turning off unused
1929 link types. The types are:
1931 bracket The recommended [[link][description]] or [[link]] links with hiding.
1932 angle Links in angular brackets that may contain whitespace like
1933 <bbdb:Carsten Dominik>.
1934 plain Plain links in normal text, no whitespace, like http://google.com.
1935 radio Text that is matched by a radio target, see manual for details.
1936 tag Tag settings in a headline (link to tag search).
1937 date Time stamps (link to calendar).
1938 footnote Footnote labels.
1940 If you set this variable during an Emacs session, use `org-mode-restart'
1941 in the Org buffer so that the change takes effect."
1942 :group 'org-link
1943 :group 'org-appearance
1944 :type '(set :greedy t
1945 (const :tag "Double bracket links" bracket)
1946 (const :tag "Angular bracket links" angle)
1947 (const :tag "Plain text links" plain)
1948 (const :tag "Radio target matches" radio)
1949 (const :tag "Tags" tag)
1950 (const :tag "Timestamps" date)
1951 (const :tag "Footnotes" footnote)))
1953 (defcustom org-make-link-description-function nil
1954 "Function to use for generating link descriptions from links.
1955 This function must take two parameters: the first one is the
1956 link, the second one is the description generated by
1957 `org-insert-link'. The function should return the description to
1958 use."
1959 :group 'org-link
1960 :type '(choice (const nil) (function)))
1962 (defgroup org-link-store nil
1963 "Options concerning storing links in Org mode."
1964 :tag "Org Store Link"
1965 :group 'org-link)
1967 (defcustom org-url-hexify-p t
1968 "When non-nil, hexify URL when creating a link."
1969 :type 'boolean
1970 :version "24.3"
1971 :group 'org-link-store)
1973 (defcustom org-email-link-description-format "Email %c: %.30s"
1974 "Format of the description part of a link to an email or usenet message.
1975 The following %-escapes will be replaced by corresponding information:
1977 %F full \"From\" field
1978 %f name, taken from \"From\" field, address if no name
1979 %T full \"To\" field
1980 %t first name in \"To\" field, address if no name
1981 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1982 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1983 %s subject
1984 %d date
1985 %m message-id.
1987 You may use normal field width specification between the % and the letter.
1988 This is for example useful to limit the length of the subject.
1990 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1991 :group 'org-link-store
1992 :type 'string)
1994 (defcustom org-from-is-user-regexp
1995 (let (r1 r2)
1996 (when (and user-mail-address (not (string= user-mail-address "")))
1997 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1998 (when (and user-full-name (not (string= user-full-name "")))
1999 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
2000 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2001 "Regexp matched against the \"From:\" header of an email or usenet message.
2002 It should match if the message is from the user him/herself."
2003 :group 'org-link-store
2004 :type 'regexp)
2006 (defcustom org-context-in-file-links t
2007 "Non-nil means file links from `org-store-link' contain context.
2008 \\<org-mode-map>
2009 A search string will be added to the file name with :: as separator
2010 and used to find the context when the link is activated by the command
2011 `org-open-at-point'. When this option is t, the entire active region
2012 will be placed in the search string of the file link. If set to a
2013 positive integer, only the first n lines of context will be stored.
2015 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2016 \\[org-store-link]')
2017 negates this setting for the duration of the command."
2018 :group 'org-link-store
2019 :type '(choice boolean integer))
2021 (defcustom org-keep-stored-link-after-insertion nil
2022 "Non-nil means keep link in list for entire session.
2023 \\<org-mode-map>
2024 The command `org-store-link' adds a link pointing to the current
2025 location to an internal list. These links accumulate during a session.
2026 The command `org-insert-link' can be used to insert links into any
2027 Org file (offering completion for all stored links).
2029 When this option is nil, every link which has been inserted once using
2030 `\\[org-insert-link]' will be removed from the list, to make completing the \
2031 unused
2032 links more efficient."
2033 :group 'org-link-store
2034 :type 'boolean)
2036 (defgroup org-link-follow nil
2037 "Options concerning following links in Org mode."
2038 :tag "Org Follow Link"
2039 :group 'org-link)
2041 (defcustom org-link-translation-function nil
2042 "Function to translate links with different syntax to Org syntax.
2043 This can be used to translate links created for example by the Planner
2044 or emacs-wiki packages to Org syntax.
2045 The function must accept two parameters, a TYPE containing the link
2046 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2047 which is everything after the link protocol. It should return a cons
2048 with possibly modified values of type and path.
2049 Org contains a function for this, so if you set this variable to
2050 `org-translate-link-from-planner', you should be able follow many
2051 links created by planner."
2052 :group 'org-link-follow
2053 :type '(choice (const nil) (function)))
2055 (defcustom org-follow-link-hook nil
2056 "Hook that is run after a link has been followed."
2057 :group 'org-link-follow
2058 :type 'hook)
2060 (defcustom org-tab-follows-link nil
2061 "Non-nil means on links TAB will follow the link.
2062 Needs to be set before org.el is loaded.
2063 This really should not be used, it does not make sense, and the
2064 implementation is bad."
2065 :group 'org-link-follow
2066 :type 'boolean)
2068 (defcustom org-return-follows-link nil
2069 "Non-nil means on links RET will follow the link.
2070 In tables, the special behavior of RET has precedence."
2071 :group 'org-link-follow
2072 :type 'boolean)
2074 (defcustom org-mouse-1-follows-link
2075 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2076 "Non-nil means mouse-1 on a link will follow the link.
2077 A longer mouse click will still set point. Needs to be set
2078 before org.el is loaded."
2079 :group 'org-link-follow
2080 :version "26.1"
2081 :package-version '(Org . "8.3")
2082 :type '(choice
2083 (const :tag "A double click follows the link" double)
2084 (const :tag "Unconditionally follow the link with mouse-1" t)
2085 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2087 (defcustom org-mark-ring-length 4
2088 "Number of different positions to be recorded in the ring.
2089 Changing this requires a restart of Emacs to work correctly."
2090 :group 'org-link-follow
2091 :type 'integer)
2093 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2094 "Non-nil means internal fuzzy links can only match headlines.
2096 When nil, the a fuzzy link may point to a target or a named
2097 construct in the document. When set to the special value
2098 `query-to-create', offer to create a new headline when none
2099 matched.
2101 Spaces and statistics cookies are ignored during heading searches."
2102 :group 'org-link-follow
2103 :version "24.1"
2104 :type '(choice
2105 (const :tag "Use fuzzy text search" nil)
2106 (const :tag "Match only exact headline" t)
2107 (const :tag "Match exact headline or query to create it"
2108 query-to-create))
2109 :safe #'symbolp)
2111 (defcustom org-link-frame-setup
2112 '((vm . vm-visit-folder-other-frame)
2113 (vm-imap . vm-visit-imap-folder-other-frame)
2114 (gnus . org-gnus-no-new-news)
2115 (file . find-file-other-window)
2116 (wl . wl-other-frame))
2117 "Setup the frame configuration for following links.
2118 When following a link with Emacs, it may often be useful to display
2119 this link in another window or frame. This variable can be used to
2120 set this up for the different types of links.
2121 For VM, use any of
2122 `vm-visit-folder'
2123 `vm-visit-folder-other-window'
2124 `vm-visit-folder-other-frame'
2125 For Gnus, use any of
2126 `gnus'
2127 `gnus-other-frame'
2128 `org-gnus-no-new-news'
2129 For FILE, use any of
2130 `find-file'
2131 `find-file-other-window'
2132 `find-file-other-frame'
2133 For Wanderlust use any of
2134 `wl'
2135 `wl-other-frame'
2136 For the calendar, use the variable `calendar-setup'.
2137 For BBDB, it is currently only possible to display the matches in
2138 another window."
2139 :group 'org-link-follow
2140 :type '(list
2141 (cons (const vm)
2142 (choice
2143 (const vm-visit-folder)
2144 (const vm-visit-folder-other-window)
2145 (const vm-visit-folder-other-frame)))
2146 (cons (const vm-imap)
2147 (choice
2148 (const vm-visit-imap-folder)
2149 (const vm-visit-imap-folder-other-window)
2150 (const vm-visit-imap-folder-other-frame)))
2151 (cons (const gnus)
2152 (choice
2153 (const gnus)
2154 (const gnus-other-frame)
2155 (const org-gnus-no-new-news)))
2156 (cons (const file)
2157 (choice
2158 (const find-file)
2159 (const find-file-other-window)
2160 (const find-file-other-frame)))
2161 (cons (const wl)
2162 (choice
2163 (const wl)
2164 (const wl-other-frame)))))
2166 (defcustom org-display-internal-link-with-indirect-buffer nil
2167 "Non-nil means use indirect buffer to display infile links.
2168 Activating internal links (from one location in a file to another location
2169 in the same file) normally just jumps to the location. When the link is
2170 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2171 is displayed in
2172 another window. When this option is set, the other window actually displays
2173 an indirect buffer clone of the current buffer, to avoid any visibility
2174 changes to the current buffer."
2175 :group 'org-link-follow
2176 :type 'boolean)
2178 (defcustom org-open-non-existing-files nil
2179 "Non-nil means `org-open-file' will open non-existing files.
2180 When nil, an error will be generated.
2181 This variable applies only to external applications because they
2182 might choke on non-existing files. If the link is to a file that
2183 will be opened in Emacs, the variable is ignored."
2184 :group 'org-link-follow
2185 :type 'boolean)
2187 (defcustom org-open-directory-means-index-dot-org nil
2188 "Non-nil means a link to a directory really means to index.org.
2189 When nil, following a directory link will run dired or open a finder/explorer
2190 window on that directory."
2191 :group 'org-link-follow
2192 :type 'boolean)
2194 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2195 "Non-nil means ask for confirmation before executing shell links.
2196 Shell links can be dangerous: just think about a link
2198 [[shell:rm -rf ~/*][Google Search]]
2200 This link would show up in your Org document as \"Google Search\",
2201 but really it would remove your entire home directory.
2202 Therefore we advise against setting this variable to nil.
2203 Just change it to `y-or-n-p' if you want to confirm with a
2204 single keystroke rather than having to type \"yes\"."
2205 :group 'org-link-follow
2206 :type '(choice
2207 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2208 (const :tag "with y-or-n (faster)" y-or-n-p)
2209 (const :tag "no confirmation (dangerous)" nil)))
2210 (put 'org-confirm-shell-link-function
2211 'safe-local-variable
2212 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2214 (defcustom org-confirm-shell-link-not-regexp ""
2215 "A regexp to skip confirmation for shell links."
2216 :group 'org-link-follow
2217 :version "24.1"
2218 :type 'regexp)
2220 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2221 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2222 Elisp links can be dangerous: just think about a link
2224 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2226 This link would show up in your Org document as \"Google Search\",
2227 but really it would remove your entire home directory.
2228 Therefore we advise against setting this variable to nil.
2229 Just change it to `y-or-n-p' if you want to confirm with a
2230 single keystroke rather than having to type \"yes\"."
2231 :group 'org-link-follow
2232 :type '(choice
2233 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2234 (const :tag "with y-or-n (faster)" y-or-n-p)
2235 (const :tag "no confirmation (dangerous)" nil)))
2236 (put 'org-confirm-shell-link-function
2237 'safe-local-variable
2238 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2240 (defcustom org-confirm-elisp-link-not-regexp ""
2241 "A regexp to skip confirmation for Elisp links."
2242 :group 'org-link-follow
2243 :version "24.1"
2244 :type 'regexp)
2246 (defconst org-file-apps-defaults-gnu
2247 '((remote . emacs)
2248 (system . mailcap)
2249 (t . mailcap))
2250 "Default file applications on a UNIX or GNU/Linux system.
2251 See `org-file-apps'.")
2253 (defconst org-file-apps-defaults-macosx
2254 '((remote . emacs)
2255 (system . "open %s")
2256 ("ps.gz" . "gv %s")
2257 ("eps.gz" . "gv %s")
2258 ("dvi" . "xdvi %s")
2259 ("fig" . "xfig %s")
2260 (t . "open %s"))
2261 "Default file applications on a macOS system.
2262 The system \"open\" is known as a default, but we use X11 applications
2263 for some files for which the OS does not have a good default.
2264 See `org-file-apps'.")
2266 (defconst org-file-apps-defaults-windowsnt
2267 (list '(remote . emacs)
2268 (cons 'system (lambda (file _path)
2269 (with-no-warnings (w32-shell-execute "open" file))))
2270 (cons t (lambda (file _path)
2271 (with-no-warnings (w32-shell-execute "open" file)))))
2272 "Default file applications on a Windows NT system.
2273 The system \"open\" is used for most files.
2274 See `org-file-apps'.")
2276 (defcustom org-file-apps
2277 '((auto-mode . emacs)
2278 ("\\.mm\\'" . default)
2279 ("\\.x?html?\\'" . default)
2280 ("\\.pdf\\'" . default))
2281 "External applications for opening `file:path' items in a document.
2282 \\<org-mode-map>\
2284 Org mode uses system defaults for different file types, but
2285 you can use this variable to set the application for a given file
2286 extension. The entries in this list are cons cells where the car identifies
2287 files and the cdr the corresponding command.
2289 Possible values for the file identifier are:
2291 \"string\" A string as a file identifier can be interpreted in different
2292 ways, depending on its contents:
2294 - Alphanumeric characters only:
2295 Match links with this file extension.
2296 Example: (\"pdf\" . \"evince %s\")
2297 to open PDFs with evince.
2299 - Regular expression: Match links where the
2300 filename matches the regexp. If you want to
2301 use groups here, use shy groups.
2303 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2304 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2305 to open *.html and *.xhtml with firefox.
2307 - Regular expression which contains (non-shy) groups:
2308 Match links where the whole link, including \"::\", and
2309 anything after that, matches the regexp.
2310 In a custom command string, %1, %2, etc. are replaced with
2311 the parts of the link that were matched by the groups.
2312 For backwards compatibility, if a command string is given
2313 that does not use any of the group matches, this case is
2314 handled identically to the second one (i.e. match against
2315 file name only).
2316 In a custom function, you can access the group matches with
2317 (match-string n link).
2319 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2320 \"evince -p %1 %s\")
2321 to open [[file:document.pdf::5]] with evince at page 5.
2323 `directory' Matches a directory
2324 `remote' Matches a remote file, accessible through tramp or efs.
2325 Remote files most likely should be visited through Emacs
2326 because external applications cannot handle such paths.
2327 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2328 so all files Emacs knows how to handle. Using this with
2329 command `emacs' will open most files in Emacs. Beware that this
2330 will also open html files inside Emacs, unless you add
2331 (\"html\" . default) to the list as well.
2332 `system' The system command to open files, like `open' on Windows
2333 and macOS, and mailcap under GNU/Linux. This is the command
2334 that will be selected if you call `org-open-at-point' with a
2335 double prefix argument (`\\[universal-argument] \
2336 \\[universal-argument] \\[org-open-at-point]').
2337 t Default for files not matched by any of the other options.
2339 Possible values for the command are:
2341 `emacs' The file will be visited by the current Emacs process.
2342 `default' Use the default application for this file type, which is the
2343 association for t in the list, most likely in the system-specific
2344 part. This can be used to overrule an unwanted setting in the
2345 system-specific variable.
2346 `system' Use the system command for opening files, like \"open\".
2347 This command is specified by the entry whose car is `system'.
2348 Most likely, the system-specific version of this variable
2349 does define this command, but you can overrule/replace it
2350 here.
2351 `mailcap' Use command specified in the mailcaps.
2352 string A command to be executed by a shell; %s will be replaced
2353 by the path to the file.
2354 function A Lisp function, which will be called with two arguments:
2355 the file path and the original link string, without the
2356 \"file:\" prefix.
2358 For more examples, see the system specific constants
2359 `org-file-apps-defaults-macosx'
2360 `org-file-apps-defaults-windowsnt'
2361 `org-file-apps-defaults-gnu'."
2362 :group 'org-link-follow
2363 :type '(repeat
2364 (cons (choice :value ""
2365 (string :tag "Extension")
2366 (const :tag "System command to open files" system)
2367 (const :tag "Default for unrecognized files" t)
2368 (const :tag "Remote file" remote)
2369 (const :tag "Links to a directory" directory)
2370 (const :tag "Any files that have Emacs modes"
2371 auto-mode))
2372 (choice :value ""
2373 (const :tag "Visit with Emacs" emacs)
2374 (const :tag "Use default" default)
2375 (const :tag "Use the system command" system)
2376 (string :tag "Command")
2377 (function :tag "Function")))))
2379 (defcustom org-doi-server-url "http://dx.doi.org/"
2380 "The URL of the DOI server."
2381 :type 'string
2382 :version "24.3"
2383 :group 'org-link-follow)
2385 (defgroup org-refile nil
2386 "Options concerning refiling entries in Org mode."
2387 :tag "Org Refile"
2388 :group 'org)
2390 (defcustom org-directory "~/org"
2391 "Directory with Org files.
2392 This is just a default location to look for Org files. There is no need
2393 at all to put your files into this directory. It is used in the
2394 following situations:
2396 1. When a capture template specifies a target file that is not an
2397 absolute path. The path will then be interpreted relative to
2398 `org-directory'
2399 2. When the value of variable `org-agenda-files' is a single file, any
2400 relative paths in this file will be taken as relative to
2401 `org-directory'."
2402 :group 'org-refile
2403 :group 'org-capture
2404 :type 'directory)
2406 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2407 "Default target for storing notes.
2408 Used as a fall back file for org-capture.el, for templates that
2409 do not specify a target file."
2410 :group 'org-refile
2411 :group 'org-capture
2412 :type 'file)
2414 (defcustom org-reverse-note-order nil
2415 "Non-nil means store new notes at the beginning of a file or entry.
2416 When nil, new notes will be filed to the end of a file or entry.
2417 This can also be a list with cons cells of regular expressions that
2418 are matched against file names, and values."
2419 :group 'org-capture
2420 :group 'org-refile
2421 :type '(choice
2422 (const :tag "Reverse always" t)
2423 (const :tag "Reverse never" nil)
2424 (repeat :tag "By file name regexp"
2425 (cons regexp boolean))))
2427 (defcustom org-log-refile nil
2428 "Information to record when a task is refiled.
2430 Possible values are:
2432 nil Don't add anything
2433 time Add a time stamp to the task
2434 note Prompt for a note and add it with template `org-log-note-headings'
2436 This option can also be set with on a per-file-basis with
2438 #+STARTUP: nologrefile
2439 #+STARTUP: logrefile
2440 #+STARTUP: lognoterefile
2442 You can have local logging settings for a subtree by setting the LOGGING
2443 property to one or more of these keywords.
2445 When bulk-refiling from the agenda, the value `note' is forbidden and
2446 will temporarily be changed to `time'."
2447 :group 'org-refile
2448 :group 'org-progress
2449 :version "24.1"
2450 :type '(choice
2451 (const :tag "No logging" nil)
2452 (const :tag "Record timestamp" time)
2453 (const :tag "Record timestamp with note." note)))
2455 (defcustom org-refile-targets nil
2456 "Targets for refiling entries with `\\[org-refile]'.
2457 This is a list of cons cells. Each cell contains:
2458 - a specification of the files to be considered, either a list of files,
2459 or a symbol whose function or variable value will be used to retrieve
2460 a file name or a list of file names. If you use `org-agenda-files' for
2461 that, all agenda files will be scanned for targets. Nil means consider
2462 headings in the current buffer.
2463 - A specification of how to find candidate refile targets. This may be
2464 any of:
2465 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2466 This tag has to be present in all target headlines, inheritance will
2467 not be considered.
2468 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2469 todo keyword.
2470 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2471 headlines that are refiling targets.
2472 - a cons cell (:level . N). Any headline of level N is considered a target.
2473 Note that, when `org-odd-levels-only' is set, level corresponds to
2474 order in hierarchy, not to the number of stars.
2475 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2476 Note that, when `org-odd-levels-only' is set, level corresponds to
2477 order in hierarchy, not to the number of stars.
2479 Each element of this list generates a set of possible targets.
2480 The union of these sets is presented (with completion) to
2481 the user by `org-refile'.
2483 You can set the variable `org-refile-target-verify-function' to a function
2484 to verify each headline found by the simple criteria above.
2486 When this variable is nil, all top-level headlines in the current buffer
2487 are used, equivalent to the value `((nil . (:level . 1))'."
2488 :group 'org-refile
2489 :type '(repeat
2490 (cons
2491 (choice :value org-agenda-files
2492 (const :tag "All agenda files" org-agenda-files)
2493 (const :tag "Current buffer" nil)
2494 (function) (variable) (file))
2495 (choice :tag "Identify target headline by"
2496 (cons :tag "Specific tag" (const :value :tag) (string))
2497 (cons :tag "TODO keyword" (const :value :todo) (string))
2498 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2499 (cons :tag "Level number" (const :value :level) (integer))
2500 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2502 (defcustom org-refile-target-verify-function nil
2503 "Function to verify if the headline at point should be a refile target.
2504 The function will be called without arguments, with point at the
2505 beginning of the headline. It should return t and leave point
2506 where it is if the headline is a valid target for refiling.
2508 If the target should not be selected, the function must return nil.
2509 In addition to this, it may move point to a place from where the search
2510 should be continued. For example, the function may decide that the entire
2511 subtree of the current entry should be excluded and move point to the end
2512 of the subtree."
2513 :group 'org-refile
2514 :type '(choice
2515 (const nil)
2516 (function)))
2518 (defcustom org-refile-use-cache nil
2519 "Non-nil means cache refile targets to speed up the process.
2520 \\<org-mode-map>\
2521 The cache for a particular file will be updated automatically when
2522 the buffer has been killed, or when any of the marker used for flagging
2523 refile targets no longer points at a live buffer.
2524 If you have added new entries to a buffer that might themselves be targets,
2525 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2526 if you find that easier, \
2527 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2528 \\[org-refile]'."
2529 :group 'org-refile
2530 :version "24.1"
2531 :type 'boolean)
2533 (defcustom org-refile-use-outline-path nil
2534 "Non-nil means provide refile targets as paths.
2535 So a level 3 headline will be available as level1/level2/level3.
2537 When the value is `file', also include the file name (without directory)
2538 into the path. In this case, you can also stop the completion after
2539 the file name, to get entries inserted as top level in the file.
2541 When `full-file-path', include the full file path.
2543 When `buffer-name', use the buffer name."
2544 :group 'org-refile
2545 :type '(choice
2546 (const :tag "Not" nil)
2547 (const :tag "Yes" t)
2548 (const :tag "Start with file name" file)
2549 (const :tag "Start with full file path" full-file-path)
2550 (const :tag "Start with buffer name" buffer-name)))
2552 (defcustom org-outline-path-complete-in-steps t
2553 "Non-nil means complete the outline path in hierarchical steps.
2554 When Org uses the refile interface to select an outline path (see
2555 `org-refile-use-outline-path'), the completion of the path can be
2556 done in a single go, or it can be done in steps down the headline
2557 hierarchy. Going in steps is probably the best if you do not use
2558 a special completion package like `ido' or `icicles'. However,
2559 when using these packages, going in one step can be very fast,
2560 while still showing the whole path to the entry."
2561 :group 'org-refile
2562 :type 'boolean)
2564 (defcustom org-refile-allow-creating-parent-nodes nil
2565 "Non-nil means allow the creation of new nodes as refile targets.
2566 New nodes are then created by adding \"/new node name\" to the completion
2567 of an existing node. When the value of this variable is `confirm',
2568 new node creation must be confirmed by the user (recommended).
2569 When nil, the completion must match an existing entry.
2571 Note that, if the new heading is not seen by the criteria
2572 listed in `org-refile-targets', multiple instances of the same
2573 heading would be created by trying again to file under the new
2574 heading."
2575 :group 'org-refile
2576 :type '(choice
2577 (const :tag "Never" nil)
2578 (const :tag "Always" t)
2579 (const :tag "Prompt for confirmation" confirm)))
2581 (defcustom org-refile-active-region-within-subtree nil
2582 "Non-nil means also refile active region within a subtree.
2584 By default `org-refile' doesn't allow refiling regions if they
2585 don't contain a set of subtrees, but it might be convenient to
2586 do so sometimes: in that case, the first line of the region is
2587 converted to a headline before refiling."
2588 :group 'org-refile
2589 :version "24.1"
2590 :type 'boolean)
2592 (defgroup org-todo nil
2593 "Options concerning TODO items in Org mode."
2594 :tag "Org TODO"
2595 :group 'org)
2597 (defgroup org-progress nil
2598 "Options concerning Progress logging in Org mode."
2599 :tag "Org Progress"
2600 :group 'org-time)
2602 (defvar org-todo-interpretation-widgets
2603 '((:tag "Sequence (cycling hits every state)" sequence)
2604 (:tag "Type (cycling directly to DONE)" type))
2605 "The available interpretation symbols for customizing `org-todo-keywords'.
2606 Interested libraries should add to this list.")
2608 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2609 "List of TODO entry keyword sequences and their interpretation.
2610 \\<org-mode-map>This is a list of sequences.
2612 Each sequence starts with a symbol, either `sequence' or `type',
2613 indicating if the keywords should be interpreted as a sequence of
2614 action steps, or as different types of TODO items. The first
2615 keywords are states requiring action - these states will select a headline
2616 for inclusion into the global TODO list Org produces. If one of the
2617 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2618 signify that no further action is necessary. If \"|\" is not found,
2619 the last keyword is treated as the only DONE state of the sequence.
2621 The command `\\[org-todo]' cycles an entry through these states, and one
2622 additional state where no keyword is present. For details about this
2623 cycling, see the manual.
2625 TODO keywords and interpretation can also be set on a per-file basis with
2626 the special #+SEQ_TODO and #+TYP_TODO lines.
2628 Each keyword can optionally specify a character for fast state selection
2629 \(in combination with the variable `org-use-fast-todo-selection')
2630 and specifiers for state change logging, using the same syntax that
2631 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2632 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2633 indicates to record a time stamp each time this state is selected.
2635 Each keyword may also specify if a timestamp or a note should be
2636 recorded when entering or leaving the state, by adding additional
2637 characters in the parenthesis after the keyword. This looks like this:
2638 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2639 record only the time of the state change. With X and Y being either
2640 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2641 Y when leaving the state if and only if the *target* state does not
2642 define X. You may omit any of the fast-selection key or X or /Y,
2643 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2645 For backward compatibility, this variable may also be just a list
2646 of keywords. In this case the interpretation (sequence or type) will be
2647 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2648 :group 'org-todo
2649 :group 'org-keywords
2650 :type '(choice
2651 (repeat :tag "Old syntax, just keywords"
2652 (string :tag "Keyword"))
2653 (repeat :tag "New syntax"
2654 (cons
2655 (choice
2656 :tag "Interpretation"
2657 ;;Quick and dirty way to see
2658 ;;`org-todo-interpretations'. This takes the
2659 ;;place of item arguments
2660 :convert-widget
2661 (lambda (widget)
2662 (widget-put widget
2663 :args (mapcar
2664 (lambda (x)
2665 (widget-convert
2666 (cons 'const x)))
2667 org-todo-interpretation-widgets))
2668 widget))
2669 (repeat
2670 (string :tag "Keyword"))))))
2672 (defvar-local org-todo-keywords-1 nil
2673 "All TODO and DONE keywords active in a buffer.")
2674 (defvar org-todo-keywords-for-agenda nil)
2675 (defvar org-done-keywords-for-agenda nil)
2676 (defvar org-todo-keyword-alist-for-agenda nil)
2677 (defvar org-tag-alist-for-agenda nil
2678 "Alist of all tags from all agenda files.")
2679 (defvar org-tag-groups-alist-for-agenda nil
2680 "Alist of all groups tags from all current agenda files.")
2681 (defvar-local org-tag-groups-alist nil)
2682 (defvar org-agenda-contributing-files nil)
2683 (defvar-local org-current-tag-alist nil
2684 "Alist of all tag groups in current buffer.
2685 This variable takes into consideration `org-tag-alist',
2686 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2687 (defvar-local org-not-done-keywords nil)
2688 (defvar-local org-done-keywords nil)
2689 (defvar-local org-todo-heads nil)
2690 (defvar-local org-todo-sets nil)
2691 (defvar-local org-todo-log-states nil)
2692 (defvar-local org-todo-kwd-alist nil)
2693 (defvar-local org-todo-key-alist nil)
2694 (defvar-local org-todo-key-trigger nil)
2696 (defcustom org-todo-interpretation 'sequence
2697 "Controls how TODO keywords are interpreted.
2698 This variable is in principle obsolete and is only used for
2699 backward compatibility, if the interpretation of todo keywords is
2700 not given already in `org-todo-keywords'. See that variable for
2701 more information."
2702 :group 'org-todo
2703 :group 'org-keywords
2704 :type '(choice (const sequence)
2705 (const type)))
2707 (defcustom org-use-fast-todo-selection t
2708 "\\<org-mode-map>\
2709 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2710 This variable describes if and under what circumstances the cycling
2711 mechanism for TODO keywords will be replaced by a single-key, direct
2712 selection scheme.
2714 When nil, fast selection is never used.
2716 When the symbol `prefix', it will be used when `org-todo' is called
2717 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2718 in an Org buffer, and
2719 `\\[universal-argument] t' in an agenda buffer.
2721 When t, fast selection is used by default. In this case, the prefix
2722 argument forces cycling instead.
2724 In all cases, the special interface is only used if access keys have
2725 actually been assigned by the user, i.e. if keywords in the configuration
2726 are followed by a letter in parenthesis, like TODO(t)."
2727 :group 'org-todo
2728 :type '(choice
2729 (const :tag "Never" nil)
2730 (const :tag "By default" t)
2731 (const :tag "Only with C-u C-c C-t" prefix)))
2733 (defcustom org-provide-todo-statistics t
2734 "Non-nil means update todo statistics after insert and toggle.
2735 ALL-HEADLINES means update todo statistics by including headlines
2736 with no TODO keyword as well, counting them as not done.
2737 A list of TODO keywords means the same, but skip keywords that are
2738 not in this list.
2739 When set to a list of two lists, the first list contains keywords
2740 to consider as TODO keywords, the second list contains keywords
2741 to consider as DONE keywords.
2743 When this is set, todo statistics is updated in the parent of the
2744 current entry each time a todo state is changed."
2745 :group 'org-todo
2746 :type '(choice
2747 (const :tag "Yes, only for TODO entries" t)
2748 (const :tag "Yes, including all entries" all-headlines)
2749 (repeat :tag "Yes, for TODOs in this list"
2750 (string :tag "TODO keyword"))
2751 (list :tag "Yes, for TODOs and DONEs in these lists"
2752 (repeat (string :tag "TODO keyword"))
2753 (repeat (string :tag "DONE keyword")))
2754 (other :tag "No TODO statistics" nil)))
2756 (defcustom org-hierarchical-todo-statistics t
2757 "Non-nil means TODO statistics covers just direct children.
2758 When nil, all entries in the subtree are considered.
2759 This has only an effect if `org-provide-todo-statistics' is set.
2760 To set this to nil for only a single subtree, use a COOKIE_DATA
2761 property and include the word \"recursive\" into the value."
2762 :group 'org-todo
2763 :type 'boolean)
2765 (defcustom org-after-todo-state-change-hook nil
2766 "Hook which is run after the state of a TODO item was changed.
2767 The new state (a string with a TODO keyword, or nil) is available in the
2768 Lisp variable `org-state'."
2769 :group 'org-todo
2770 :type 'hook)
2772 (defvar org-blocker-hook nil
2773 "Hook for functions that are allowed to block a state change.
2775 Functions in this hook should not modify the buffer.
2776 Each function gets as its single argument a property list,
2777 see `org-trigger-hook' for more information about this list.
2779 If any of the functions in this hook returns nil, the state change
2780 is blocked.")
2782 (defvar org-trigger-hook nil
2783 "Hook for functions that are triggered by a state change.
2785 Each function gets as its single argument a property list with at
2786 least the following elements:
2788 (:type type-of-change :position pos-at-entry-start
2789 :from old-state :to new-state)
2791 Depending on the type, more properties may be present.
2793 This mechanism is currently implemented for:
2795 TODO state changes
2796 ------------------
2797 :type todo-state-change
2798 :from previous state (keyword as a string), or nil, or a symbol
2799 `todo' or `done', to indicate the general type of state.
2800 :to new state, like in :from")
2802 (defcustom org-enforce-todo-dependencies nil
2803 "Non-nil means undone TODO entries will block switching the parent to DONE.
2804 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2805 be blocked if any prior sibling is not yet done.
2806 Finally, if the parent is blocked because of ordered siblings of its own,
2807 the child will also be blocked."
2808 :set (lambda (var val)
2809 (set var val)
2810 (if val
2811 (add-hook 'org-blocker-hook
2812 'org-block-todo-from-children-or-siblings-or-parent)
2813 (remove-hook 'org-blocker-hook
2814 'org-block-todo-from-children-or-siblings-or-parent)))
2815 :group 'org-todo
2816 :type 'boolean)
2818 (defcustom org-enforce-todo-checkbox-dependencies nil
2819 "Non-nil means unchecked boxes will block switching the parent to DONE.
2820 When this is nil, checkboxes have no influence on switching TODO states.
2821 When non-nil, you first need to check off all check boxes before the TODO
2822 entry can be switched to DONE.
2823 This variable needs to be set before org.el is loaded, and you need to
2824 restart Emacs after a change to make the change effective. The only way
2825 to change it while Emacs is running is through the customize interface."
2826 :set (lambda (var val)
2827 (set var val)
2828 (if val
2829 (add-hook 'org-blocker-hook
2830 'org-block-todo-from-checkboxes)
2831 (remove-hook 'org-blocker-hook
2832 'org-block-todo-from-checkboxes)))
2833 :group 'org-todo
2834 :type 'boolean)
2836 (defcustom org-treat-insert-todo-heading-as-state-change nil
2837 "Non-nil means inserting a TODO heading is treated as state change.
2838 So when the command `\\[org-insert-todo-heading]' is used, state change
2839 logging will apply if appropriate. When nil, the new TODO item will
2840 be inserted directly, and no logging will take place."
2841 :group 'org-todo
2842 :type 'boolean)
2844 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2845 "Non-nil means switching TODO states with S-cursor counts as state change.
2846 This is the default behavior. However, setting this to nil allows a
2847 convenient way to select a TODO state and bypass any logging associated
2848 with that."
2849 :group 'org-todo
2850 :type 'boolean)
2852 (defcustom org-todo-state-tags-triggers nil
2853 "Tag changes that should be triggered by TODO state changes.
2854 This is a list. Each entry is
2856 (state-change (tag . flag) .......)
2858 State-change can be a string with a state, and empty string to indicate the
2859 state that has no TODO keyword, or it can be one of the symbols `todo'
2860 or `done', meaning any not-done or done state, respectively."
2861 :group 'org-todo
2862 :group 'org-tags
2863 :type '(repeat
2864 (cons (choice :tag "When changing to"
2865 (const :tag "Not-done state" todo)
2866 (const :tag "Done state" done)
2867 (string :tag "State"))
2868 (repeat
2869 (cons :tag "Tag action"
2870 (string :tag "Tag")
2871 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2873 (defcustom org-log-done nil
2874 "Information to record when a task moves to the DONE state.
2876 Possible values are:
2878 nil Don't add anything, just change the keyword
2879 time Add a time stamp to the task
2880 note Prompt for a note and add it with template `org-log-note-headings'
2882 This option can also be set with on a per-file-basis with
2884 #+STARTUP: nologdone
2885 #+STARTUP: logdone
2886 #+STARTUP: lognotedone
2888 You can have local logging settings for a subtree by setting the LOGGING
2889 property to one or more of these keywords."
2890 :group 'org-todo
2891 :group 'org-progress
2892 :type '(choice
2893 (const :tag "No logging" nil)
2894 (const :tag "Record CLOSED timestamp" time)
2895 (const :tag "Record CLOSED timestamp with note." note)))
2897 ;; Normalize old uses of org-log-done.
2898 (cond
2899 ((eq org-log-done t) (setq org-log-done 'time))
2900 ((and (listp org-log-done) (memq 'done org-log-done))
2901 (setq org-log-done 'note)))
2903 (defcustom org-log-reschedule nil
2904 "Information to record when the scheduling date of a task is modified.
2906 Possible values are:
2908 nil Don't add anything, just change the date
2909 time Add a time stamp to the task
2910 note Prompt for a note and add it with template `org-log-note-headings'
2912 This option can also be set with on a per-file-basis with
2914 #+STARTUP: nologreschedule
2915 #+STARTUP: logreschedule
2916 #+STARTUP: lognotereschedule
2918 You can have local logging settings for a subtree by setting the LOGGING
2919 property to one or more of these keywords.
2921 This variable has an effect when calling `org-schedule' or
2922 `org-agenda-schedule' only."
2923 :group 'org-todo
2924 :group 'org-progress
2925 :type '(choice
2926 (const :tag "No logging" nil)
2927 (const :tag "Record timestamp" time)
2928 (const :tag "Record timestamp with note" note)))
2930 (defcustom org-log-redeadline nil
2931 "Information to record when the deadline date of a task is modified.
2933 Possible values are:
2935 nil Don't add anything, just change the date
2936 time Add a time stamp to the task
2937 note Prompt for a note and add it with template `org-log-note-headings'
2939 This option can also be set with on a per-file-basis with
2941 #+STARTUP: nologredeadline
2942 #+STARTUP: logredeadline
2943 #+STARTUP: lognoteredeadline
2945 You can have local logging settings for a subtree by setting the LOGGING
2946 property to one or more of these keywords.
2948 This variable has an effect when calling `org-deadline' or
2949 `org-agenda-deadline' only."
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type '(choice
2953 (const :tag "No logging" nil)
2954 (const :tag "Record timestamp" time)
2955 (const :tag "Record timestamp with note." note)))
2957 (defcustom org-log-note-clock-out nil
2958 "Non-nil means record a note when clocking out of an item.
2959 This can also be configured on a per-file basis by adding one of
2960 the following lines anywhere in the buffer:
2962 #+STARTUP: lognoteclock-out
2963 #+STARTUP: nolognoteclock-out"
2964 :group 'org-todo
2965 :group 'org-progress
2966 :type 'boolean)
2968 (defcustom org-log-done-with-time t
2969 "Non-nil means the CLOSED time stamp will contain date and time.
2970 When nil, only the date will be recorded."
2971 :group 'org-progress
2972 :type 'boolean)
2974 (defcustom org-log-note-headings
2975 '((done . "CLOSING NOTE %t")
2976 (state . "State %-12s from %-12S %t")
2977 (note . "Note taken on %t")
2978 (reschedule . "Rescheduled from %S on %t")
2979 (delschedule . "Not scheduled, was %S on %t")
2980 (redeadline . "New deadline from %S on %t")
2981 (deldeadline . "Removed deadline, was %S on %t")
2982 (refile . "Refiled on %t")
2983 (clock-out . ""))
2984 "Headings for notes added to entries.
2986 The value is an alist, with the car being a symbol indicating the
2987 note context, and the cdr is the heading to be used. The heading
2988 may also be the empty string. The following placeholders can be
2989 used:
2991 %t a time stamp.
2992 %T an active time stamp instead the default inactive one
2993 %d a short-format time stamp.
2994 %D an active short-format time stamp.
2995 %s the new TODO state or time stamp (inactive), in double quotes.
2996 %S the old TODO state or time stamp (inactive), in double quotes.
2997 %u the user name.
2998 %U full user name.
3000 In fact, it is not a good idea to change the `state' entry,
3001 because Agenda Log mode depends on the format of these entries."
3002 :group 'org-todo
3003 :group 'org-progress
3004 :type '(list :greedy t
3005 (cons (const :tag "Heading when closing an item" done) string)
3006 (cons (const :tag
3007 "Heading when changing todo state (todo sequence only)"
3008 state) string)
3009 (cons (const :tag "Heading when just taking a note" note) string)
3010 (cons (const :tag "Heading when rescheduling" reschedule) string)
3011 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3012 (cons (const :tag "Heading when changing deadline" redeadline) string)
3013 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3014 (cons (const :tag "Heading when refiling" refile) string)
3015 (cons (const :tag "Heading when clocking out" clock-out) string)))
3017 (unless (assq 'note org-log-note-headings)
3018 (push '(note . "%t") org-log-note-headings))
3020 (defcustom org-log-into-drawer nil
3021 "Non-nil means insert state change notes and time stamps into a drawer.
3022 When nil, state changes notes will be inserted after the headline and
3023 any scheduling and clock lines, but not inside a drawer.
3025 The value of this variable should be the name of the drawer to use.
3026 LOGBOOK is proposed as the default drawer for this purpose, you can
3027 also set this to a string to define the drawer of your choice.
3029 A value of t is also allowed, representing \"LOGBOOK\".
3031 A value of t or nil can also be set with on a per-file-basis with
3033 #+STARTUP: logdrawer
3034 #+STARTUP: nologdrawer
3036 If this variable is set, `org-log-state-notes-insert-after-drawers'
3037 will be ignored.
3039 You can set the property LOG_INTO_DRAWER to overrule this setting for
3040 a subtree.
3042 Do not check directly this variable in a Lisp program. Call
3043 function `org-log-into-drawer' instead."
3044 :group 'org-todo
3045 :group 'org-progress
3046 :type '(choice
3047 (const :tag "Not into a drawer" nil)
3048 (const :tag "LOGBOOK" t)
3049 (string :tag "Other")))
3051 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3053 (defun org-log-into-drawer ()
3054 "Name of the log drawer, as a string, or nil.
3055 This is the value of `org-log-into-drawer'. However, if the
3056 current entry has or inherits a LOG_INTO_DRAWER property, it will
3057 be used instead of the default value."
3058 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3059 (cond ((equal p "nil") nil)
3060 ((equal p "t") "LOGBOOK")
3061 ((stringp p) p)
3062 (p "LOGBOOK")
3063 ((stringp org-log-into-drawer) org-log-into-drawer)
3064 (org-log-into-drawer "LOGBOOK"))))
3066 (defcustom org-log-state-notes-insert-after-drawers nil
3067 "Non-nil means insert state change notes after any drawers in entry.
3068 Only the drawers that *immediately* follow the headline and the
3069 deadline/scheduled line are skipped.
3070 When nil, insert notes right after the heading and perhaps the line
3071 with deadline/scheduling if present.
3073 This variable will have no effect if `org-log-into-drawer' is
3074 set."
3075 :group 'org-todo
3076 :group 'org-progress
3077 :type 'boolean)
3079 (defcustom org-log-states-order-reversed t
3080 "Non-nil means the latest state note will be directly after heading.
3081 When nil, the state change notes will be ordered according to time.
3083 This option can also be set with on a per-file-basis with
3085 #+STARTUP: logstatesreversed
3086 #+STARTUP: nologstatesreversed"
3087 :group 'org-todo
3088 :group 'org-progress
3089 :type 'boolean)
3091 (defcustom org-todo-repeat-to-state nil
3092 "The TODO state to which a repeater should return the repeating task.
3093 By default this is the first task of a TODO sequence or the
3094 previous state of a TYPE_TODO set. But you can specify to use
3095 the previous state in a TODO sequence or a string.
3097 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3098 entry, which has precedence over this option."
3099 :group 'org-todo
3100 :version "24.1"
3101 :type '(choice (const :tag "Use the previous TODO state" t)
3102 (const :tag "Use the head of the TODO sequence" nil)
3103 (string :tag "Use a specific TODO state")))
3105 (defcustom org-log-repeat 'time
3106 "Non-nil means record moving through the DONE state when triggering repeat.
3107 An auto-repeating task is immediately switched back to TODO when
3108 marked DONE. If you are not logging state changes (by adding \"@\"
3109 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3110 record a closing note, there will be no record of the task moving
3111 through DONE. This variable forces taking a note anyway.
3113 nil Don't force a record
3114 time Record a time stamp
3115 note Prompt for a note and add it with template `org-log-note-headings'
3117 This option can also be set with on a per-file-basis with
3119 #+STARTUP: nologrepeat
3120 #+STARTUP: logrepeat
3121 #+STARTUP: lognoterepeat
3123 You can have local logging settings for a subtree by setting the LOGGING
3124 property to one or more of these keywords."
3125 :group 'org-todo
3126 :group 'org-progress
3127 :type '(choice
3128 (const :tag "Don't force a record" nil)
3129 (const :tag "Force recording the DONE state" time)
3130 (const :tag "Force recording a note with the DONE state" note)))
3133 (defgroup org-priorities nil
3134 "Priorities in Org mode."
3135 :tag "Org Priorities"
3136 :group 'org-todo)
3138 (defcustom org-enable-priority-commands t
3139 "Non-nil means priority commands are active.
3140 When nil, these commands will be disabled, so that you never accidentally
3141 set a priority."
3142 :group 'org-priorities
3143 :type 'boolean)
3145 (defcustom org-highest-priority ?A
3146 "The highest priority of TODO items. A character like ?A, ?B etc.
3147 Must have a smaller ASCII number than `org-lowest-priority'."
3148 :group 'org-priorities
3149 :type 'character)
3151 (defcustom org-lowest-priority ?C
3152 "The lowest priority of TODO items. A character like ?A, ?B etc.
3153 Must have a larger ASCII number than `org-highest-priority'."
3154 :group 'org-priorities
3155 :type 'character)
3157 (defcustom org-default-priority ?B
3158 "The default priority of TODO items.
3159 This is the priority an item gets if no explicit priority is given.
3160 When starting to cycle on an empty priority the first step in the cycle
3161 depends on `org-priority-start-cycle-with-default'. The resulting first
3162 step priority must not exceed the range from `org-highest-priority' to
3163 `org-lowest-priority' which means that `org-default-priority' has to be
3164 in this range exclusive or inclusive the range boundaries. Else the
3165 first step refuses to set the default and the second will fall back
3166 to (depending on the command used) the highest or lowest priority."
3167 :group 'org-priorities
3168 :type 'character)
3170 (defcustom org-priority-start-cycle-with-default t
3171 "Non-nil means start with default priority when starting to cycle.
3172 When this is nil, the first step in the cycle will be (depending on the
3173 command used) one higher or lower than the default priority.
3174 See also `org-default-priority'."
3175 :group 'org-priorities
3176 :type 'boolean)
3178 (defcustom org-get-priority-function nil
3179 "Function to extract the priority from a string.
3180 The string is normally the headline. If this is nil Org computes the
3181 priority from the priority cookie like [#A] in the headline. It returns
3182 an integer, increasing by 1000 for each priority level.
3183 The user can set a different function here, which should take a string
3184 as an argument and return the numeric priority."
3185 :group 'org-priorities
3186 :version "24.1"
3187 :type '(choice
3188 (const nil)
3189 (function)))
3191 (defgroup org-time nil
3192 "Options concerning time stamps and deadlines in Org mode."
3193 :tag "Org Time"
3194 :group 'org)
3196 (defcustom org-time-stamp-rounding-minutes '(0 5)
3197 "Number of minutes to round time stamps to.
3198 \\<org-mode-map>\
3199 These are two values, the first applies when first creating a time stamp.
3200 The second applies when changing it with the commands `S-up' and `S-down'.
3201 When changing the time stamp, this means that it will change in steps
3202 of N minutes, as given by the second value.
3204 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3205 numbers should be factors of 60, so for example 5, 10, 15.
3207 When this is larger than 1, you can still force an exact time stamp by using
3208 a double prefix argument to a time stamp command like \
3209 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3210 and by using a prefix arg to `S-up/down' to specify the exact number
3211 of minutes to shift."
3212 :group 'org-time
3213 :get (lambda (var) ; Make sure both elements are there
3214 (if (integerp (default-value var))
3215 (list (default-value var) 5)
3216 (default-value var)))
3217 :type '(list
3218 (integer :tag "when inserting times")
3219 (integer :tag "when modifying times")))
3221 ;; Normalize old customizations of this variable.
3222 (when (integerp org-time-stamp-rounding-minutes)
3223 (setq org-time-stamp-rounding-minutes
3224 (list org-time-stamp-rounding-minutes
3225 org-time-stamp-rounding-minutes)))
3227 (defcustom org-display-custom-times nil
3228 "Non-nil means overlay custom formats over all time stamps.
3229 The formats are defined through the variable `org-time-stamp-custom-formats'.
3230 To turn this on on a per-file basis, insert anywhere in the file:
3231 #+STARTUP: customtime"
3232 :group 'org-time
3233 :set 'set-default
3234 :type 'sexp)
3235 (make-variable-buffer-local 'org-display-custom-times)
3237 (defcustom org-time-stamp-custom-formats
3238 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3239 "Custom formats for time stamps. See `format-time-string' for the syntax.
3240 These are overlaid over the default ISO format if the variable
3241 `org-display-custom-times' is set. Time like %H:%M should be at the
3242 end of the second format. The custom formats are also honored by export
3243 commands, if custom time display is turned on at the time of export."
3244 :group 'org-time
3245 :type 'sexp)
3247 (defun org-time-stamp-format (&optional long inactive)
3248 "Get the right format for a time string."
3249 (let ((f (if long (cdr org-time-stamp-formats)
3250 (car org-time-stamp-formats))))
3251 (if inactive
3252 (concat "[" (substring f 1 -1) "]")
3253 f)))
3255 (defcustom org-deadline-warning-days 14
3256 "Number of days before expiration during which a deadline becomes active.
3257 This variable governs the display in sparse trees and in the agenda.
3258 When 0 or negative, it means use this number (the absolute value of it)
3259 even if a deadline has a different individual lead time specified.
3261 Custom commands can set this variable in the options section."
3262 :group 'org-time
3263 :group 'org-agenda-daily/weekly
3264 :type 'integer)
3266 (defcustom org-scheduled-delay-days 0
3267 "Number of days before a scheduled item becomes active.
3268 This variable governs the display in sparse trees and in the agenda.
3269 The default value (i.e. 0) means: don't delay scheduled item.
3270 When negative, it means use this number (the absolute value of it)
3271 even if a scheduled item has a different individual delay time
3272 specified.
3274 Custom commands can set this variable in the options section."
3275 :group 'org-time
3276 :group 'org-agenda-daily/weekly
3277 :version "24.4"
3278 :package-version '(Org . "8.0")
3279 :type 'integer)
3281 (defcustom org-read-date-prefer-future t
3282 "Non-nil means assume future for incomplete date input from user.
3283 This affects the following situations:
3284 1. The user gives a month but not a year.
3285 For example, if it is April and you enter \"feb 2\", this will be read
3286 as Feb 2, *next* year. \"May 5\", however, will be this year.
3287 2. The user gives a day, but no month.
3288 For example, if today is the 15th, and you enter \"3\", Org will read
3289 this as the third of *next* month. However, if you enter \"17\",
3290 it will be considered as *this* month.
3292 If you set this variable to the symbol `time', then also the following
3293 will work:
3295 3. If the user gives a time.
3296 If the time is before now, it will be interpreted as tomorrow.
3298 Currently none of this works for ISO week specifications.
3300 When this option is nil, the current day, month and year will always be
3301 used as defaults.
3303 See also `org-agenda-jump-prefer-future'."
3304 :group 'org-time
3305 :type '(choice
3306 (const :tag "Never" nil)
3307 (const :tag "Check month and day" t)
3308 (const :tag "Check month, day, and time" time)))
3310 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3311 "Should the agenda jump command prefer the future for incomplete dates?
3312 The default is to do the same as configured in `org-read-date-prefer-future'.
3313 But you can also set a deviating value here.
3314 This may t or nil, or the symbol `org-read-date-prefer-future'."
3315 :group 'org-agenda
3316 :group 'org-time
3317 :version "24.1"
3318 :type '(choice
3319 (const :tag "Use org-read-date-prefer-future"
3320 org-read-date-prefer-future)
3321 (const :tag "Never" nil)
3322 (const :tag "Always" t)))
3324 (defcustom org-read-date-force-compatible-dates t
3325 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3327 Depending on the system Emacs is running on, certain dates cannot
3328 be represented with the type used internally to represent time.
3329 Dates between 1970-1-1 and 2038-1-1 can always be represented
3330 correctly. Some systems allow for earlier dates, some for later,
3331 some for both. One way to find out it to insert any date into an
3332 Org buffer, putting the cursor on the year and hitting S-up and
3333 S-down to test the range.
3335 When this variable is set to t, the date/time prompt will not let
3336 you specify dates outside the 1970-2037 range, so it is certain that
3337 these dates will work in whatever version of Emacs you are
3338 running, and also that you can move a file from one Emacs implementation
3339 to another. WHenever Org is forcing the year for you, it will display
3340 a message and beep.
3342 When this variable is nil, Org will check if the date is
3343 representable in the specific Emacs implementation you are using.
3344 If not, it will force a year, usually the current year, and beep
3345 to remind you. Currently this setting is not recommended because
3346 the likelihood that you will open your Org files in an Emacs that
3347 has limited date range is not negligible.
3349 A workaround for this problem is to use diary sexp dates for time
3350 stamps outside of this range."
3351 :group 'org-time
3352 :version "24.1"
3353 :type 'boolean)
3355 (defcustom org-read-date-display-live t
3356 "Non-nil means display current interpretation of date prompt live.
3357 This display will be in an overlay, in the minibuffer."
3358 :group 'org-time
3359 :type 'boolean)
3361 (defcustom org-read-date-popup-calendar t
3362 "Non-nil means pop up a calendar when prompting for a date.
3363 In the calendar, the date can be selected with mouse-1. However, the
3364 minibuffer will also be active, and you can simply enter the date as well.
3365 When nil, only the minibuffer will be available."
3366 :group 'org-time
3367 :type 'boolean)
3368 (defvaralias 'org-popup-calendar-for-date-prompt
3369 'org-read-date-popup-calendar)
3371 (defcustom org-extend-today-until 0
3372 "The hour when your day really ends. Must be an integer.
3373 This has influence for the following applications:
3374 - When switching the agenda to \"today\". It it is still earlier than
3375 the time given here, the day recognized as TODAY is actually yesterday.
3376 - When a date is read from the user and it is still before the time given
3377 here, the current date and time will be assumed to be yesterday, 23:59.
3378 Also, timestamps inserted in capture templates follow this rule.
3380 IMPORTANT: This is a feature whose implementation is and likely will
3381 remain incomplete. Really, it is only here because past midnight seems to
3382 be the favorite working time of John Wiegley :-)"
3383 :group 'org-time
3384 :type 'integer)
3386 (defcustom org-use-effective-time nil
3387 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3388 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3389 \"effective time\" of any timestamps between midnight and 8am will be
3390 23:59 of the previous day."
3391 :group 'org-time
3392 :version "24.1"
3393 :type 'boolean)
3395 (defcustom org-use-last-clock-out-time-as-effective-time nil
3396 "When non-nil, use the last clock out time for `org-todo'.
3397 Note that this option has precedence over the combined use of
3398 `org-use-effective-time' and `org-extend-today-until'."
3399 :group 'org-time
3400 :version "24.4"
3401 :package-version '(Org . "8.0")
3402 :type 'boolean)
3404 (defcustom org-edit-timestamp-down-means-later nil
3405 "Non-nil means S-down will increase the time in a time stamp.
3406 When nil, S-up will increase."
3407 :group 'org-time
3408 :type 'boolean)
3410 (defcustom org-calendar-follow-timestamp-change t
3411 "Non-nil means make the calendar window follow timestamp changes.
3412 When a timestamp is modified and the calendar window is visible, it will be
3413 moved to the new date."
3414 :group 'org-time
3415 :type 'boolean)
3417 (defgroup org-tags nil
3418 "Options concerning tags in Org mode."
3419 :tag "Org Tags"
3420 :group 'org)
3422 (defcustom org-tag-alist nil
3423 "Default tags available in Org files.
3425 The value of this variable is an alist. Associations either:
3427 (TAG)
3428 (TAG . SELECT)
3429 (SPECIAL)
3431 where TAG is a tag as a string, SELECT is character, used to
3432 select that tag through the fast tag selection interface, and
3433 SPECIAL is one of the following keywords: `:startgroup',
3434 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
3435 `:newline'. These keywords are used to define a hierarchy of
3436 tags. See manual for details.
3438 When this variable is nil, Org mode bases tag input on what is
3439 already in the buffer. The value can be overridden locally by
3440 using a TAGS keyword, e.g.,
3442 #+TAGS: tag1 tag2
3444 See also `org-tag-persistent-alist' to sidestep this behavior."
3445 :group 'org-tags
3446 :type '(repeat
3447 (choice
3448 (cons :tag "Tag with key"
3449 (string :tag "Tag name")
3450 (character :tag "Access char"))
3451 (list :tag "Tag" (string :tag "Tag name"))
3452 (const :tag "Start radio group" (:startgroup))
3453 (const :tag "Start tag group, non distinct" (:startgrouptag))
3454 (const :tag "Group tags delimiter" (:grouptags))
3455 (const :tag "End radio group" (:endgroup))
3456 (const :tag "End tag group, non distinct" (:endgrouptag))
3457 (const :tag "New line" (:newline)))))
3459 (defcustom org-tag-persistent-alist nil
3460 "Tags always available in Org files.
3462 The value of this variable is an alist. Associations either:
3464 (TAG)
3465 (TAG . SELECT)
3466 (SPECIAL)
3468 where TAG is a tag as a string, SELECT is a character, used to
3469 select that tag through the fast tag selection interface, and
3470 SPECIAL is one of the following keywords: `:startgroup',
3471 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
3472 `:newline'. These keywords are used to define a hierarchy of
3473 tags. See manual for details.
3475 Unlike to `org-tag-alist', tags defined in this variable do not
3476 depend on a local TAGS keyword. Instead, to disable these tags
3477 on a per-file basis, insert anywhere in the file:
3479 #+STARTUP: noptag"
3480 :group 'org-tags
3481 :type '(repeat
3482 (choice
3483 (cons :tag "Tag with key"
3484 (string :tag "Tag name")
3485 (character :tag "Access char"))
3486 (list :tag "Tag" (string :tag "Tag name"))
3487 (const :tag "Start radio group" (:startgroup))
3488 (const :tag "Start tag group, non distinct" (:startgrouptag))
3489 (const :tag "Group tags delimiter" (:grouptags))
3490 (const :tag "End radio group" (:endgroup))
3491 (const :tag "End tag group, non distinct" (:endgrouptag))
3492 (const :tag "New line" (:newline)))))
3494 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3495 "If non-nil, always offer completion for all tags of all agenda files.
3497 Setting this variable locally allows for dynamic generation of tag
3498 completions in capture buffers.
3500 (add-hook \\='org-capture-mode-hook
3501 (lambda ()
3502 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3503 :group 'org-tags
3504 :version "24.1"
3505 :type 'boolean)
3507 (defvar org-file-tags nil
3508 "List of tags that can be inherited by all entries in the file.
3509 The tags will be inherited if the variable `org-use-tag-inheritance'
3510 says they should be.
3511 This variable is populated from #+FILETAGS lines.")
3513 (defcustom org-use-fast-tag-selection 'auto
3514 "Non-nil means use fast tag selection scheme.
3515 This is a special interface to select and deselect tags with single keys.
3516 When nil, fast selection is never used.
3517 When the symbol `auto', fast selection is used if and only if selection
3518 characters for tags have been configured, either through the variable
3519 `org-tag-alist' or through a #+TAGS line in the buffer.
3520 When t, fast selection is always used and selection keys are assigned
3521 automatically if necessary."
3522 :group 'org-tags
3523 :type '(choice
3524 (const :tag "Always" t)
3525 (const :tag "Never" nil)
3526 (const :tag "When selection characters are configured" auto)))
3528 (defcustom org-fast-tag-selection-single-key nil
3529 "Non-nil means fast tag selection exits after first change.
3530 When nil, you have to press RET to exit it.
3531 During fast tag selection, you can toggle this flag with `C-c'.
3532 This variable can also have the value `expert'. In this case, the window
3533 displaying the tags menu is not even shown, until you press C-c again."
3534 :group 'org-tags
3535 :type '(choice
3536 (const :tag "No" nil)
3537 (const :tag "Yes" t)
3538 (const :tag "Expert" expert)))
3540 (defvar org-fast-tag-selection-include-todo nil
3541 "Non-nil means fast tags selection interface will also offer TODO states.
3542 This is an undocumented feature, you should not rely on it.")
3544 (defcustom org-tags-column -77
3545 "The column to which tags should be indented in a headline.
3546 If this number is positive, it specifies the column. If it is negative,
3547 it means that the tags should be flushright to that column. For example,
3548 -80 works well for a normal 80 character screen.
3549 When 0, place tags directly after headline text, with only one space in
3550 between."
3551 :group 'org-tags
3552 :type 'integer)
3554 (defcustom org-auto-align-tags t
3555 "Non-nil keeps tags aligned when modifying headlines.
3556 Some operations (i.e. demoting) change the length of a headline and
3557 therefore shift the tags around. With this option turned on, after
3558 each such operation the tags are again aligned to `org-tags-column'."
3559 :group 'org-tags
3560 :type 'boolean)
3562 (defcustom org-use-tag-inheritance t
3563 "Non-nil means tags in levels apply also for sublevels.
3564 When nil, only the tags directly given in a specific line apply there.
3565 This may also be a list of tags that should be inherited, or a regexp that
3566 matches tags that should be inherited. Additional control is possible
3567 with the variable `org-tags-exclude-from-inheritance' which gives an
3568 explicit list of tags to be excluded from inheritance, even if the value of
3569 `org-use-tag-inheritance' would select it for inheritance.
3571 If this option is t, a match early-on in a tree can lead to a large
3572 number of matches in the subtree when constructing the agenda or creating
3573 a sparse tree. If you only want to see the first match in a tree during
3574 a search, check out the variable `org-tags-match-list-sublevels'."
3575 :group 'org-tags
3576 :type '(choice
3577 (const :tag "Not" nil)
3578 (const :tag "Always" t)
3579 (repeat :tag "Specific tags" (string :tag "Tag"))
3580 (regexp :tag "Tags matched by regexp")))
3582 (defcustom org-tags-exclude-from-inheritance nil
3583 "List of tags that should never be inherited.
3584 This is a way to exclude a few tags from inheritance. For way to do
3585 the opposite, to actively allow inheritance for selected tags,
3586 see the variable `org-use-tag-inheritance'."
3587 :group 'org-tags
3588 :type '(repeat (string :tag "Tag")))
3590 (defun org-tag-inherit-p (tag)
3591 "Check if TAG is one that should be inherited."
3592 (cond
3593 ((member tag org-tags-exclude-from-inheritance) nil)
3594 ((eq org-use-tag-inheritance t) t)
3595 ((not org-use-tag-inheritance) nil)
3596 ((stringp org-use-tag-inheritance)
3597 (string-match org-use-tag-inheritance tag))
3598 ((listp org-use-tag-inheritance)
3599 (member tag org-use-tag-inheritance))
3600 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3602 (defcustom org-tags-match-list-sublevels t
3603 "Non-nil means list also sublevels of headlines matching a search.
3604 This variable applies to tags/property searches, and also to stuck
3605 projects because this search is based on a tags match as well.
3607 When set to the symbol `indented', sublevels are indented with
3608 leading dots.
3610 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3611 the sublevels of a headline matching a tag search often also match
3612 the same search. Listing all of them can create very long lists.
3613 Setting this variable to nil causes subtrees of a match to be skipped.
3615 This variable is semi-obsolete and probably should always be true. It
3616 is better to limit inheritance to certain tags using the variables
3617 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3618 :group 'org-tags
3619 :type '(choice
3620 (const :tag "No, don't list them" nil)
3621 (const :tag "Yes, do list them" t)
3622 (const :tag "List them, indented with leading dots" indented)))
3624 (defcustom org-tags-sort-function nil
3625 "When set, tags are sorted using this function as a comparator."
3626 :group 'org-tags
3627 :type '(choice
3628 (const :tag "No sorting" nil)
3629 (const :tag "Alphabetical" org-string-collate-lessp)
3630 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3631 (function :tag "Custom function" nil)))
3633 (defvar org-tags-history nil
3634 "History of minibuffer reads for tags.")
3635 (defvar org-last-tags-completion-table nil
3636 "The last used completion table for tags.")
3637 (defvar org-after-tags-change-hook nil
3638 "Hook that is run after the tags in a line have changed.")
3640 (defgroup org-properties nil
3641 "Options concerning properties in Org mode."
3642 :tag "Org Properties"
3643 :group 'org)
3645 (defcustom org-property-format "%-10s %s"
3646 "How property key/value pairs should be formatted by `indent-line'.
3647 When `indent-line' hits a property definition, it will format the line
3648 according to this format, mainly to make sure that the values are
3649 lined-up with respect to each other."
3650 :group 'org-properties
3651 :type 'string)
3653 (defcustom org-properties-postprocess-alist nil
3654 "Alist of properties and functions to adjust inserted values.
3655 Elements of this alist must be of the form
3657 ([string] [function])
3659 where [string] must be a property name and [function] must be a
3660 lambda expression: this lambda expression must take one argument,
3661 the value to adjust, and return the new value as a string.
3663 For example, this element will allow the property \"Remaining\"
3664 to be updated wrt the relation between the \"Effort\" property
3665 and the clock summary:
3667 ((\"Remaining\" (lambda(value)
3668 (let ((clocksum (org-clock-sum-current-item))
3669 (effort (org-duration-to-minutes
3670 (org-entry-get (point) \"Effort\"))))
3671 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3672 :group 'org-properties
3673 :version "24.1"
3674 :type '(alist :key-type (string :tag "Property")
3675 :value-type (function :tag "Function")))
3677 (defcustom org-use-property-inheritance nil
3678 "Non-nil means properties apply also for sublevels.
3680 This setting is chiefly used during property searches. Turning it on can
3681 cause significant overhead when doing a search, which is why it is not
3682 on by default.
3684 When nil, only the properties directly given in the current entry count.
3685 When t, every property is inherited. The value may also be a list of
3686 properties that should have inheritance, or a regular expression matching
3687 properties that should be inherited.
3689 However, note that some special properties use inheritance under special
3690 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3691 and the properties ending in \"_ALL\" when they are used as descriptor
3692 for valid values of a property.
3694 Note for programmers:
3695 When querying an entry with `org-entry-get', you can control if inheritance
3696 should be used. By default, `org-entry-get' looks only at the local
3697 properties. You can request inheritance by setting the inherit argument
3698 to t (to force inheritance) or to `selective' (to respect the setting
3699 in this variable)."
3700 :group 'org-properties
3701 :type '(choice
3702 (const :tag "Not" nil)
3703 (const :tag "Always" t)
3704 (repeat :tag "Specific properties" (string :tag "Property"))
3705 (regexp :tag "Properties matched by regexp")))
3707 (defun org-property-inherit-p (property)
3708 "Return a non-nil value if PROPERTY should be inherited."
3709 (cond
3710 ((eq org-use-property-inheritance t) t)
3711 ((not org-use-property-inheritance) nil)
3712 ((stringp org-use-property-inheritance)
3713 (string-match org-use-property-inheritance property))
3714 ((listp org-use-property-inheritance)
3715 (member-ignore-case property org-use-property-inheritance))
3716 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3718 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3719 "The default column format, if no other format has been defined.
3720 This variable can be set on the per-file basis by inserting a line
3722 #+COLUMNS: %25ITEM ....."
3723 :group 'org-properties
3724 :type 'string)
3726 (defcustom org-columns-ellipses ".."
3727 "The ellipses to be used when a field in column view is truncated.
3728 When this is the empty string, as many characters as possible are shown,
3729 but then there will be no visual indication that the field has been truncated.
3730 When this is a string of length N, the last N characters of a truncated
3731 field are replaced by this string. If the column is narrower than the
3732 ellipses string, only part of the ellipses string will be shown."
3733 :group 'org-properties
3734 :type 'string)
3736 (defconst org-global-properties-fixed
3737 '(("VISIBILITY_ALL" . "folded children content all")
3738 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3739 "List of property/value pairs that can be inherited by any entry.
3741 These are fixed values, for the preset properties. The user variable
3742 that can be used to add to this list is `org-global-properties'.
3744 The entries in this list are cons cells where the car is a property
3745 name and cdr is a string with the value. If the value represents
3746 multiple items like an \"_ALL\" property, separate the items by
3747 spaces.")
3749 (defcustom org-global-properties nil
3750 "List of property/value pairs that can be inherited by any entry.
3752 This list will be combined with the constant `org-global-properties-fixed'.
3754 The entries in this list are cons cells where the car is a property
3755 name and cdr is a string with the value.
3757 You can set buffer-local values for the same purpose in the variable
3758 `org-file-properties' this by adding lines like
3760 #+PROPERTY: NAME VALUE"
3761 :group 'org-properties
3762 :type '(repeat
3763 (cons (string :tag "Property")
3764 (string :tag "Value"))))
3766 (defvar-local org-file-properties nil
3767 "List of property/value pairs that can be inherited by any entry.
3768 Valid for the current buffer.
3769 This variable is populated from #+PROPERTY lines.")
3771 (defgroup org-agenda nil
3772 "Options concerning agenda views in Org mode."
3773 :tag "Org Agenda"
3774 :group 'org)
3776 (defvar-local org-category nil
3777 "Variable used by Org files to set a category for agenda display.
3778 Such files should use a file variable to set it, for example
3780 # -*- mode: org; org-category: \"ELisp\"
3782 or contain a special line
3784 #+CATEGORY: ELisp
3786 If the file does not specify a category, then file's base name
3787 is used instead.")
3788 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3790 (defcustom org-agenda-files nil
3791 "The files to be used for agenda display.
3793 If an entry is a directory, all files in that directory that are matched
3794 by `org-agenda-file-regexp' will be part of the file list.
3796 If the value of the variable is not a list but a single file name, then
3797 the list of agenda files is actually stored and maintained in that file,
3798 one agenda file per line. In this file paths can be given relative to
3799 `org-directory'. Tilde expansion and environment variable substitution
3800 are also made.
3802 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3803 and removed with `\\[org-remove-file]'."
3804 :group 'org-agenda
3805 :type '(choice
3806 (repeat :tag "List of files and directories" file)
3807 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3809 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3810 "Regular expression to match files for `org-agenda-files'.
3811 If any element in the list in that variable contains a directory instead
3812 of a normal file, all files in that directory that are matched by this
3813 regular expression will be included."
3814 :group 'org-agenda
3815 :type 'regexp)
3817 (defcustom org-agenda-text-search-extra-files nil
3818 "List of extra files to be searched by text search commands.
3819 These files will be searched in addition to the agenda files by the
3820 commands `org-search-view' (`\\[org-agenda] s') \
3821 and `org-occur-in-agenda-files'.
3822 Note that these files will only be searched for text search commands,
3823 not for the other agenda views like todo lists, tag searches or the weekly
3824 agenda. This variable is intended to list notes and possibly archive files
3825 that should also be searched by these two commands.
3826 In fact, if the first element in the list is the symbol `agenda-archives',
3827 then all archive files of all agenda files will be added to the search
3828 scope."
3829 :group 'org-agenda
3830 :type '(set :greedy t
3831 (const :tag "Agenda Archives" agenda-archives)
3832 (repeat :inline t (file))))
3834 (defvaralias 'org-agenda-multi-occur-extra-files
3835 'org-agenda-text-search-extra-files)
3837 (defcustom org-agenda-skip-unavailable-files nil
3838 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3839 A nil value means to remove them, after a query, from the list."
3840 :group 'org-agenda
3841 :type 'boolean)
3843 (defcustom org-agenda-diary-file 'diary-file
3844 "File to which to add new entries with the `i' key in agenda and calendar.
3845 When this is the symbol `diary-file', the functionality in the Emacs
3846 calendar will be used to add entries to the `diary-file'. But when this
3847 points to a file, `org-agenda-diary-entry' will be used instead."
3848 :group 'org-agenda
3849 :type '(choice
3850 (const :tag "The standard Emacs diary file" diary-file)
3851 (file :tag "Special Org file diary entries")))
3853 (defgroup org-latex nil
3854 "Options for embedding LaTeX code into Org mode."
3855 :tag "Org LaTeX"
3856 :group 'org)
3858 (defcustom org-format-latex-options
3859 '(:foreground default :background default :scale 1.0
3860 :html-foreground "Black" :html-background "Transparent"
3861 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3862 "Options for creating images from LaTeX fragments.
3863 This is a property list with the following properties:
3864 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3865 `default' means use the foreground of the default face.
3866 `auto' means use the foreground from the text face.
3867 :background the background color, or \"Transparent\".
3868 `default' means use the background of the default face.
3869 `auto' means use the background from the text face.
3870 :scale a scaling factor for the size of the images, to get more pixels
3871 :html-foreground, :html-background, :html-scale
3872 the same numbers for HTML export.
3873 :matchers a list indicating which matchers should be used to
3874 find LaTeX fragments. Valid members of this list are:
3875 \"begin\" find environments
3876 \"$1\" find single characters surrounded by $.$
3877 \"$\" find math expressions surrounded by $...$
3878 \"$$\" find math expressions surrounded by $$....$$
3879 \"\\(\" find math expressions surrounded by \\(...\\)
3880 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3881 :group 'org-latex
3882 :type 'plist)
3884 (defcustom org-format-latex-signal-error t
3885 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3886 When nil, just push out a message."
3887 :group 'org-latex
3888 :version "24.1"
3889 :type 'boolean)
3891 (defcustom org-latex-to-mathml-jar-file nil
3892 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3893 Use this to specify additional executable file say a jar file.
3895 When using MathToWeb as the converter, specify the full-path to
3896 your mathtoweb.jar file."
3897 :group 'org-latex
3898 :version "24.1"
3899 :type '(choice
3900 (const :tag "None" nil)
3901 (file :tag "JAR file" :must-match t)))
3903 (defcustom org-latex-to-mathml-convert-command nil
3904 "Command to convert LaTeX fragments to MathML.
3905 Replace format-specifiers in the command as noted below and use
3906 `shell-command' to convert LaTeX to MathML.
3907 %j: Executable file in fully expanded form as specified by
3908 `org-latex-to-mathml-jar-file'.
3909 %I: Input LaTeX file in fully expanded form.
3910 %i: The latex fragment to be converted.
3911 %o: Output MathML file.
3913 This command is used by `org-create-math-formula'.
3915 When using MathToWeb as the converter, set this option to
3916 \"java -jar %j -unicode -force -df %o %I\".
3918 When using LaTeXML set this option to
3919 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3920 :group 'org-latex
3921 :version "24.1"
3922 :type '(choice
3923 (const :tag "None" nil)
3924 (string :tag "\nShell command")))
3926 (defcustom org-preview-latex-default-process 'dvipng
3927 "The default process to convert LaTeX fragments to image files.
3928 All available processes and theirs documents can be found in
3929 `org-preview-latex-process-alist', which see."
3930 :group 'org-latex
3931 :version "26.1"
3932 :package-version '(Org . "9.0")
3933 :type 'symbol)
3935 (defcustom org-preview-latex-process-alist
3936 '((dvipng
3937 :programs ("latex" "dvipng")
3938 :description "dvi > png"
3939 :message "you need to install the programs: latex and dvipng."
3940 :image-input-type "dvi"
3941 :image-output-type "png"
3942 :image-size-adjust (1.0 . 1.0)
3943 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3944 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3945 (dvisvgm
3946 :programs ("latex" "dvisvgm")
3947 :description "dvi > svg"
3948 :message "you need to install the programs: latex and dvisvgm."
3949 :use-xcolor t
3950 :image-input-type "dvi"
3951 :image-output-type "svg"
3952 :image-size-adjust (1.7 . 1.5)
3953 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3954 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3955 (imagemagick
3956 :programs ("latex" "convert")
3957 :description "pdf > png"
3958 :message "you need to install the programs: latex and imagemagick."
3959 :use-xcolor t
3960 :image-input-type "pdf"
3961 :image-output-type "png"
3962 :image-size-adjust (1.0 . 1.0)
3963 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3964 :image-converter
3965 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3966 "Definitions of external processes for LaTeX previewing.
3967 Org mode can use some external commands to generate TeX snippet's images for
3968 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3969 `org-create-formula-image' how to call them.
3971 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3972 PROPERTIES accepts the following attributes:
3974 :programs list of strings, required programs.
3975 :description string, describe the process.
3976 :message string, message it when required programs cannot be found.
3977 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3978 :image-output-type string, output file type of image converter (e.g., \"png\").
3979 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3980 deal with background and foreground color of image.
3981 Otherwise, dvipng style background and foreground color
3982 format are generated. You may then refer to them in
3983 command options with \"%F\" and \"%B\".
3984 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3985 image size showed in buffer and the cdr element is for
3986 HTML file. This option is only useful for process
3987 developers, users should use variable
3988 `org-format-latex-options' instead.
3989 :post-clean list of strings, files matched are to be cleaned up once
3990 the image is generated. When nil, the files with \".dvi\",
3991 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3992 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3993 be cleaned up.
3994 :latex-header list of strings, the LaTeX header of the snippet file.
3995 When nil, the fallback value is used instead, which is
3996 controlled by `org-format-latex-header',
3997 `org-latex-default-packages-alist' and
3998 `org-latex-packages-alist', which see.
3999 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4000 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4001 replaced with values defined below.
4002 :image-converter list of image converter commands strings. Each of them is
4003 given to the shell and supports any of the following
4004 place-holders defined below.
4006 Place-holders used by `:image-converter' and `:latex-compiler':
4008 %f input file name
4009 %b base name of input file
4010 %o base directory of input file
4011 %O absolute output file name
4013 Place-holders only used by `:image-converter':
4015 %F foreground of image
4016 %B background of image
4017 %D dpi, which is used to adjust image size by some processing commands.
4018 %S the image size scale ratio, which is used to adjust image size by some
4019 processing commands."
4020 :group 'org-latex
4021 :version "26.1"
4022 :package-version '(Org . "9.0")
4023 :type '(alist :tag "LaTeX to image backends"
4024 :value-type (plist)))
4026 (defcustom org-preview-latex-image-directory "ltximg/"
4027 "Path to store latex preview images.
4028 A relative path here creates many directories relative to the
4029 processed Org files paths. An absolute path puts all preview
4030 images at the same place."
4031 :group 'org-latex
4032 :version "26.1"
4033 :package-version '(Org . "9.0")
4034 :type 'string)
4036 (defun org-format-latex-mathml-available-p ()
4037 "Return t if `org-latex-to-mathml-convert-command' is usable."
4038 (save-match-data
4039 (when (and (boundp 'org-latex-to-mathml-convert-command)
4040 org-latex-to-mathml-convert-command)
4041 (let ((executable (car (split-string
4042 org-latex-to-mathml-convert-command))))
4043 (when (executable-find executable)
4044 (if (string-match
4045 "%j" org-latex-to-mathml-convert-command)
4046 (file-readable-p org-latex-to-mathml-jar-file)
4047 t))))))
4049 (defcustom org-format-latex-header "\\documentclass{article}
4050 \\usepackage[usenames]{color}
4051 \[PACKAGES]
4052 \[DEFAULT-PACKAGES]
4053 \\pagestyle{empty} % do not remove
4054 % The settings below are copied from fullpage.sty
4055 \\setlength{\\textwidth}{\\paperwidth}
4056 \\addtolength{\\textwidth}{-3cm}
4057 \\setlength{\\oddsidemargin}{1.5cm}
4058 \\addtolength{\\oddsidemargin}{-2.54cm}
4059 \\setlength{\\evensidemargin}{\\oddsidemargin}
4060 \\setlength{\\textheight}{\\paperheight}
4061 \\addtolength{\\textheight}{-\\headheight}
4062 \\addtolength{\\textheight}{-\\headsep}
4063 \\addtolength{\\textheight}{-\\footskip}
4064 \\addtolength{\\textheight}{-3cm}
4065 \\setlength{\\topmargin}{1.5cm}
4066 \\addtolength{\\topmargin}{-2.54cm}"
4067 "The document header used for processing LaTeX fragments.
4068 It is imperative that this header make sure that no page number
4069 appears on the page. The package defined in the variables
4070 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4071 will either replace the placeholder \"[PACKAGES]\" in this
4072 header, or they will be appended."
4073 :group 'org-latex
4074 :type 'string)
4076 (defun org-set-packages-alist (var val)
4077 "Set the packages alist and make sure it has 3 elements per entry."
4078 (set var (mapcar (lambda (x)
4079 (if (and (consp x) (= (length x) 2))
4080 (list (car x) (nth 1 x) t)
4082 val)))
4084 (defun org-get-packages-alist (var)
4085 "Get the packages alist and make sure it has 3 elements per entry."
4086 (mapcar (lambda (x)
4087 (if (and (consp x) (= (length x) 2))
4088 (list (car x) (nth 1 x) t)
4090 (default-value var)))
4092 (defcustom org-latex-default-packages-alist
4093 '(("AUTO" "inputenc" t ("pdflatex"))
4094 ("T1" "fontenc" t ("pdflatex"))
4095 ("" "graphicx" t)
4096 ("" "grffile" t)
4097 ("" "longtable" nil)
4098 ("" "wrapfig" nil)
4099 ("" "rotating" nil)
4100 ("normalem" "ulem" t)
4101 ("" "amsmath" t)
4102 ("" "textcomp" t)
4103 ("" "amssymb" t)
4104 ("" "capt-of" nil)
4105 ("" "hyperref" nil))
4106 "Alist of default packages to be inserted in the header.
4108 Change this only if one of the packages here causes an
4109 incompatibility with another package you are using.
4111 The packages in this list are needed by one part or another of
4112 Org mode to function properly:
4114 - inputenc, fontenc: for basic font and character selection
4115 - graphicx: for including images
4116 - grffile: allow periods and spaces in graphics file names
4117 - longtable: For multipage tables
4118 - wrapfig: for figure placement
4119 - rotating: for sideways figures and tables
4120 - ulem: for underline and strike-through
4121 - amsmath: for subscript and superscript and math environments
4122 - textcomp, amssymb: for various symbols used
4123 for interpreting the entities in `org-entities'. You can skip
4124 some of these packages if you don't use any of their symbols.
4125 - capt-of: for captions outside of floats
4126 - hyperref: for cross references
4128 Therefore you should not modify this variable unless you know
4129 what you are doing. The one reason to change it anyway is that
4130 you might be loading some other package that conflicts with one
4131 of the default packages. Each element is either a cell or
4132 a string.
4134 A cell is of the format
4136 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4138 If SNIPPET-FLAG is non-nil, the package also needs to be included
4139 when compiling LaTeX snippets into images for inclusion into
4140 non-LaTeX output. COMPILERS is a list of compilers that should
4141 include the package, see `org-latex-compiler'. If the document
4142 compiler is not in the list, and the list is non-nil, the package
4143 will not be inserted in the final document.
4145 A string will be inserted as-is in the header of the document."
4146 :group 'org-latex
4147 :group 'org-export-latex
4148 :set 'org-set-packages-alist
4149 :get 'org-get-packages-alist
4150 :version "26.1"
4151 :package-version '(Org . "8.3")
4152 :type '(repeat
4153 (choice
4154 (list :tag "options/package pair"
4155 (string :tag "options")
4156 (string :tag "package")
4157 (boolean :tag "Snippet")
4158 (choice
4159 (const :tag "For all compilers" nil)
4160 (repeat :tag "Allowed compiler" string)))
4161 (string :tag "A line of LaTeX"))))
4163 (defcustom org-latex-packages-alist nil
4164 "Alist of packages to be inserted in every LaTeX header.
4166 These will be inserted after `org-latex-default-packages-alist'.
4167 Each element is either a cell or a string.
4169 A cell is of the format:
4171 (\"options\" \"package\" SNIPPET-FLAG)
4173 SNIPPET-FLAG, when non-nil, indicates that this package is also
4174 needed when turning LaTeX snippets into images for inclusion into
4175 non-LaTeX output.
4177 A string will be inserted as-is in the header of the document.
4179 Make sure that you only list packages here which:
4181 - you want in every file;
4182 - do not conflict with the setup in `org-format-latex-header';
4183 - do not conflict with the default packages in
4184 `org-latex-default-packages-alist'."
4185 :group 'org-latex
4186 :group 'org-export-latex
4187 :set 'org-set-packages-alist
4188 :get 'org-get-packages-alist
4189 :type '(repeat
4190 (choice
4191 (list :tag "options/package pair"
4192 (string :tag "options")
4193 (string :tag "package")
4194 (boolean :tag "Snippet"))
4195 (string :tag "A line of LaTeX"))))
4197 (defgroup org-appearance nil
4198 "Settings for Org mode appearance."
4199 :tag "Org Appearance"
4200 :group 'org)
4202 (defcustom org-level-color-stars-only nil
4203 "Non-nil means fontify only the stars in each headline.
4204 When nil, the entire headline is fontified.
4205 Changing it requires restart of `font-lock-mode' to become effective
4206 also in regions already fontified."
4207 :group 'org-appearance
4208 :type 'boolean)
4210 (defcustom org-hide-leading-stars nil
4211 "Non-nil means hide the first N-1 stars in a headline.
4212 This works by using the face `org-hide' for these stars. This
4213 face is white for a light background, and black for a dark
4214 background. You may have to customize the face `org-hide' to
4215 make this work.
4216 Changing it requires restart of `font-lock-mode' to become effective
4217 also in regions already fontified.
4218 You may also set this on a per-file basis by adding one of the following
4219 lines to the buffer:
4221 #+STARTUP: hidestars
4222 #+STARTUP: showstars"
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-hidden-keywords nil
4227 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4228 For example, a value \\='(title) for this list makes the document's title
4229 appear in the buffer without the initial \"#+TITLE:\" part."
4230 :group 'org-appearance
4231 :version "24.1"
4232 :type '(set (const :tag "#+AUTHOR" author)
4233 (const :tag "#+DATE" date)
4234 (const :tag "#+EMAIL" email)
4235 (const :tag "#+TITLE" title)))
4237 (defcustom org-custom-properties nil
4238 "List of properties (as strings) with a special meaning.
4239 The default use of these custom properties is to let the user
4240 hide them with `org-toggle-custom-properties-visibility'."
4241 :group 'org-properties
4242 :group 'org-appearance
4243 :version "24.3"
4244 :type '(repeat (string :tag "Property Name")))
4246 (defcustom org-fontify-done-headline nil
4247 "Non-nil means change the face of a headline if it is marked DONE.
4248 Normally, only the TODO/DONE keyword indicates the state of a headline.
4249 When this is non-nil, the headline after the keyword is set to the
4250 `org-headline-done' as an additional indication."
4251 :group 'org-appearance
4252 :type 'boolean)
4254 (defcustom org-fontify-emphasized-text t
4255 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4256 Changing this variable requires a restart of Emacs to take effect."
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-fontify-whole-heading-line nil
4261 "Non-nil means fontify the whole line for headings.
4262 This is useful when setting a background color for the
4263 org-level-* faces."
4264 :group 'org-appearance
4265 :type 'boolean)
4267 (defcustom org-highlight-latex-and-related nil
4268 "Non-nil means highlight LaTeX related syntax in the buffer.
4269 When non nil, the value should be a list containing any of the
4270 following symbols:
4271 `latex' Highlight LaTeX snippets and environments.
4272 `script' Highlight subscript and superscript.
4273 `entities' Highlight entities."
4274 :group 'org-appearance
4275 :version "24.4"
4276 :package-version '(Org . "8.0")
4277 :type '(choice
4278 (const :tag "No highlighting" nil)
4279 (set :greedy t :tag "Highlight"
4280 (const :tag "LaTeX snippets and environments" latex)
4281 (const :tag "Subscript and superscript" script)
4282 (const :tag "Entities" entities))))
4284 (defcustom org-hide-emphasis-markers nil
4285 "Non-nil mean font-lock should hide the emphasis marker characters."
4286 :group 'org-appearance
4287 :type 'boolean
4288 :safe #'booleanp)
4290 (defcustom org-hide-macro-markers nil
4291 "Non-nil mean font-lock should hide the brackets marking macro calls."
4292 :group 'org-appearance
4293 :type 'boolean)
4295 (defcustom org-pretty-entities nil
4296 "Non-nil means show entities as UTF8 characters.
4297 When nil, the \\name form remains in the buffer."
4298 :group 'org-appearance
4299 :version "24.1"
4300 :type 'boolean)
4302 (defcustom org-pretty-entities-include-sub-superscripts t
4303 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4304 :group 'org-appearance
4305 :version "24.1"
4306 :type 'boolean)
4308 (defvar org-emph-re nil
4309 "Regular expression for matching emphasis.
4310 After a match, the match groups contain these elements:
4311 0 The match of the full regular expression, including the characters
4312 before and after the proper match
4313 1 The character before the proper match, or empty at beginning of line
4314 2 The proper match, including the leading and trailing markers
4315 3 The leading marker like * or /, indicating the type of highlighting
4316 4 The text between the emphasis markers, not including the markers
4317 5 The character after the match, empty at the end of a line")
4319 (defvar org-verbatim-re nil
4320 "Regular expression for matching verbatim text.")
4322 (defvar org-emphasis-regexp-components) ; defined just below
4323 (defvar org-emphasis-alist) ; defined just below
4324 (defun org-set-emph-re (var val)
4325 "Set variable and compute the emphasis regular expression."
4326 (set var val)
4327 (when (and (boundp 'org-emphasis-alist)
4328 (boundp 'org-emphasis-regexp-components)
4329 org-emphasis-alist org-emphasis-regexp-components)
4330 (pcase-let*
4331 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4332 (body (if (<= nl 0) body
4333 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4334 (template
4335 (format (concat "\\([%s]\\|^\\)" ;before markers
4336 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4337 "\\([%s]\\|$\\)") ;after markers
4338 pre border border body border post)))
4339 (setq org-emph-re (format template "*/_+"))
4340 (setq org-verbatim-re (format template "=~")))))
4342 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4343 ;; set this option proved cumbersome. See this message/thread:
4344 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4345 (defvar org-emphasis-regexp-components
4346 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4347 "Components used to build the regular expression for emphasis.
4348 This is a list with five entries. Terminology: In an emphasis string
4349 like \" *strong word* \", we call the initial space PREMATCH, the final
4350 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4351 and \"trong wor\" is the body. The different components in this variable
4352 specify what is allowed/forbidden in each part:
4354 pre Chars allowed as prematch. Beginning of line will be allowed too.
4355 post Chars allowed as postmatch. End of line will be allowed too.
4356 border The chars *forbidden* as border characters.
4357 body-regexp A regexp like \".\" to match a body character. Don't use
4358 non-shy groups here, and don't allow newline here.
4359 newline The maximum number of newlines allowed in an emphasis exp.
4361 You need to reload Org or to restart Emacs after setting this.")
4363 (defcustom org-emphasis-alist
4364 '(("*" bold)
4365 ("/" italic)
4366 ("_" underline)
4367 ("=" org-verbatim verbatim)
4368 ("~" org-code verbatim)
4369 ("+" (:strike-through t)))
4370 "Alist of characters and faces to emphasize text.
4371 Text starting and ending with a special character will be emphasized,
4372 for example *bold*, _underlined_ and /italic/. This variable sets the
4373 marker characters and the face to be used by font-lock for highlighting
4374 in Org buffers.
4376 You need to reload Org or to restart Emacs after customizing this."
4377 :group 'org-appearance
4378 :set 'org-set-emph-re
4379 :version "24.4"
4380 :package-version '(Org . "8.0")
4381 :type '(repeat
4382 (list
4383 (string :tag "Marker character")
4384 (choice
4385 (face :tag "Font-lock-face")
4386 (plist :tag "Face property list"))
4387 (option (const verbatim)))))
4389 (defvar org-protecting-blocks '("src" "example" "export")
4390 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4391 This is needed for font-lock setup.")
4393 ;;; Functions and variables from their packages
4394 ;; Declared here to avoid compiler warnings
4395 (defvar mark-active)
4397 ;; Various packages
4398 (declare-function calc-eval "calc" (str &optional separator &rest args))
4399 (declare-function calendar-forward-day "cal-move" (arg))
4400 (declare-function calendar-goto-date "cal-move" (date))
4401 (declare-function calendar-goto-today "cal-move" ())
4402 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4403 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4404 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4405 (declare-function cdlatex-tab "ext:cdlatex" ())
4406 (declare-function dired-get-filename
4407 "dired"
4408 (&optional localp no-error-if-not-filep))
4409 (declare-function iswitchb-read-buffer
4410 "iswitchb"
4411 (prompt &optional
4412 default require-match _predicate start matches-set))
4413 (declare-function org-agenda-change-all-lines
4414 "org-agenda"
4415 (newhead hdmarker &optional fixface just-this))
4416 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4417 "org-agenda"
4418 (&optional end))
4419 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4420 (declare-function org-agenda-format-item
4421 "org-agenda"
4422 (extra txt &optional level category tags dotime
4423 remove-re habitp))
4424 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4425 (declare-function org-agenda-save-markers-for-cut-and-paste
4426 "org-agenda"
4427 (beg end))
4428 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4429 (declare-function org-agenda-skip "org-agenda" ())
4430 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4431 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4432 (declare-function org-indent-mode "org-indent" (&optional arg))
4433 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4434 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4435 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4436 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4437 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4438 (declare-function parse-time-string "parse-time" (string))
4440 (defvar align-mode-rules-list)
4441 (defvar calc-embedded-close-formula)
4442 (defvar calc-embedded-open-formula)
4443 (defvar calc-embedded-open-mode)
4444 (defvar font-lock-unfontify-region-function)
4445 (defvar iswitchb-temp-buflist)
4446 (defvar org-agenda-tags-todo-honor-ignore-options)
4447 (defvar remember-data-file)
4448 (defvar texmathp-why)
4450 ;;;###autoload
4451 (defun turn-on-orgtbl ()
4452 "Unconditionally turn on `orgtbl-mode'."
4453 (require 'org-table)
4454 (orgtbl-mode 1))
4456 (defun org-at-table-p (&optional table-type)
4457 "Non-nil if the cursor is inside an Org table.
4458 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4459 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4460 (or (not (derived-mode-p 'org-mode))
4461 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4462 (and e (or table-type
4463 (eq 'org (org-element-property :type e))))))))
4465 (defun org-at-table.el-p ()
4466 "Non-nil when point is at a table.el table."
4467 (and (org-match-line "[ \t]*[|+]")
4468 (let ((element (org-element-at-point)))
4469 (and (eq (org-element-type element) 'table)
4470 (eq (org-element-property :type element) 'table.el)))))
4472 (defun org-at-table-hline-p ()
4473 "Non-nil when point is inside a hline in a table.
4474 Assume point is already in a table."
4475 (org-match-line org-table-hline-regexp))
4477 (defun org-table-map-tables (function &optional quietly)
4478 "Apply FUNCTION to the start of all tables in the buffer."
4479 (org-with-wide-buffer
4480 (goto-char (point-min))
4481 (while (re-search-forward org-table-any-line-regexp nil t)
4482 (unless quietly
4483 (message "Mapping tables: %d%%"
4484 (floor (* 100.0 (point)) (buffer-size))))
4485 (beginning-of-line 1)
4486 (when (and (looking-at org-table-line-regexp)
4487 ;; Exclude tables in src/example/verbatim/clocktable blocks
4488 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4489 (save-excursion (funcall function))
4490 (or (looking-at org-table-line-regexp)
4491 (forward-char 1)))
4492 (re-search-forward org-table-any-border-regexp nil 1)))
4493 (unless quietly (message "Mapping tables: done")))
4495 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4496 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
4497 (declare-function org-resolve-clocks "org-clock"
4498 (&optional also-non-dangling-p prompt last-valid))
4500 (defun org-at-TBLFM-p (&optional pos)
4501 "Non-nil when point (or POS) is in #+TBLFM line."
4502 (save-excursion
4503 (goto-char (or pos (point)))
4504 (beginning-of-line)
4505 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4506 (eq (org-element-type (org-element-at-point)) 'table))))
4508 (defvar org-clock-start-time)
4509 (defvar org-clock-marker (make-marker)
4510 "Marker recording the last clock-in.")
4511 (defvar org-clock-hd-marker (make-marker)
4512 "Marker recording the last clock-in, but the headline position.")
4513 (defvar org-clock-heading ""
4514 "The heading of the current clock entry.")
4515 (defun org-clock-is-active ()
4516 "Return the buffer where the clock is currently running.
4517 Return nil if no clock is running."
4518 (marker-buffer org-clock-marker))
4520 (defun org-check-running-clock ()
4521 "Check if the current buffer contains the running clock.
4522 If yes, offer to stop it and to save the buffer with the changes."
4523 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4524 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4525 (buffer-name))))
4526 (org-clock-out)
4527 (when (y-or-n-p "Save changed buffer?")
4528 (save-buffer))))
4530 (defun org-clocktable-try-shift (dir n)
4531 "Check if this line starts a clock table, if yes, shift the time block."
4532 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4533 (org-clocktable-shift dir n)))
4535 ;;;###autoload
4536 (defun org-clock-persistence-insinuate ()
4537 "Set up hooks for clock persistence."
4538 (require 'org-clock)
4539 (add-hook 'org-mode-hook 'org-clock-load)
4540 (add-hook 'kill-emacs-hook 'org-clock-save))
4542 (defgroup org-archive nil
4543 "Options concerning archiving in Org mode."
4544 :tag "Org Archive"
4545 :group 'org-structure)
4547 (defcustom org-archive-location "%s_archive::"
4548 "The location where subtrees should be archived.
4550 The value of this variable is a string, consisting of two parts,
4551 separated by a double-colon. The first part is a filename and
4552 the second part is a headline.
4554 When the filename is omitted, archiving happens in the same file.
4555 %s in the filename will be replaced by the current file
4556 name (without the directory part). Archiving to a different file
4557 is useful to keep archived entries from contributing to the
4558 Org Agenda.
4560 The archived entries will be filed as subtrees of the specified
4561 headline. When the headline is omitted, the subtrees are simply
4562 filed away at the end of the file, as top-level entries. Also in
4563 the heading you can use %s to represent the file name, this can be
4564 useful when using the same archive for a number of different files.
4566 Here are a few examples:
4567 \"%s_archive::\"
4568 If the current file is Projects.org, archive in file
4569 Projects.org_archive, as top-level trees. This is the default.
4571 \"::* Archived Tasks\"
4572 Archive in the current file, under the top-level headline
4573 \"* Archived Tasks\".
4575 \"~/org/archive.org::\"
4576 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4578 \"~/org/archive.org::* From %s\"
4579 Archive in file ~/org/archive.org (absolute path), under headlines
4580 \"From FILENAME\" where file name is the current file name.
4582 \"~/org/datetree.org::datetree/* Finished Tasks\"
4583 The \"datetree/\" string is special, signifying to archive
4584 items to the datetree. Items are placed in either the CLOSED
4585 date of the item, or the current date if there is no CLOSED date.
4586 The heading will be a subentry to the current date. There doesn't
4587 need to be a heading, but there always needs to be a slash after
4588 datetree. For example, to store archived items directly in the
4589 datetree, use \"~/org/datetree.org::datetree/\".
4591 \"basement::** Finished Tasks\"
4592 Archive in file ./basement (relative path), as level 3 trees
4593 below the level 2 heading \"** Finished Tasks\".
4595 You may set this option on a per-file basis by adding to the buffer a
4596 line like
4598 #+ARCHIVE: basement::** Finished Tasks
4600 You may also define it locally for a subtree by setting an ARCHIVE property
4601 in the entry. If such a property is found in an entry, or anywhere up
4602 the hierarchy, it will be used."
4603 :group 'org-archive
4604 :type 'string)
4606 (defcustom org-agenda-skip-archived-trees t
4607 "Non-nil means the agenda will skip any items located in archived trees.
4608 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4609 variable is no longer recommended, you should leave it at the value t.
4610 Instead, use the key `v' to cycle the archives-mode in the agenda."
4611 :group 'org-archive
4612 :group 'org-agenda-skip
4613 :type 'boolean)
4615 (defcustom org-columns-skip-archived-trees t
4616 "Non-nil means ignore archived trees when creating column view."
4617 :group 'org-archive
4618 :group 'org-properties
4619 :type 'boolean)
4621 (defcustom org-cycle-open-archived-trees nil
4622 "Non-nil means `org-cycle' will open archived trees.
4623 An archived tree is a tree marked with the tag ARCHIVE.
4624 When nil, archived trees will stay folded. You can still open them with
4625 normal outline commands like `show-all', but not with the cycling commands."
4626 :group 'org-archive
4627 :group 'org-cycle
4628 :type 'boolean)
4630 (defcustom org-sparse-tree-open-archived-trees nil
4631 "Non-nil means sparse tree construction shows matches in archived trees.
4632 When nil, matches in these trees are highlighted, but the trees are kept in
4633 collapsed state."
4634 :group 'org-archive
4635 :group 'org-sparse-trees
4636 :type 'boolean)
4638 (defcustom org-sparse-tree-default-date-type nil
4639 "The default date type when building a sparse tree.
4640 When this is nil, a date is a scheduled or a deadline timestamp.
4641 Otherwise, these types are allowed:
4643 all: all timestamps
4644 active: only active timestamps (<...>)
4645 inactive: only inactive timestamps ([...])
4646 scheduled: only scheduled timestamps
4647 deadline: only deadline timestamps"
4648 :type '(choice (const :tag "Scheduled or deadline" nil)
4649 (const :tag "All timestamps" all)
4650 (const :tag "Only active timestamps" active)
4651 (const :tag "Only inactive timestamps" inactive)
4652 (const :tag "Only scheduled timestamps" scheduled)
4653 (const :tag "Only deadline timestamps" deadline)
4654 (const :tag "Only closed timestamps" closed))
4655 :version "26.1"
4656 :package-version '(Org . "8.3")
4657 :group 'org-sparse-trees)
4659 (defun org-cycle-hide-archived-subtrees (state)
4660 "Re-hide all archived subtrees after a visibility state change.
4661 STATE should be one of the symbols listed in the docstring of
4662 `org-cycle-hook'."
4663 (when (and (not org-cycle-open-archived-trees)
4664 (not (memq state '(overview folded))))
4665 (save-excursion
4666 (let* ((globalp (memq state '(contents all)))
4667 (beg (if globalp (point-min) (point)))
4668 (end (if globalp (point-max) (org-end-of-subtree t))))
4669 (org-hide-archived-subtrees beg end)
4670 (goto-char beg)
4671 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4672 (message "%s" (substitute-command-keys
4673 "Subtree is archived and stays closed. Use \
4674 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4676 (defun org-force-cycle-archived ()
4677 "Cycle subtree even if it is archived."
4678 (interactive)
4679 (setq this-command 'org-cycle)
4680 (let ((org-cycle-open-archived-trees t))
4681 (call-interactively 'org-cycle)))
4683 (defun org-hide-archived-subtrees (beg end)
4684 "Re-hide all archived subtrees after a visibility state change."
4685 (org-with-wide-buffer
4686 (let ((case-fold-search nil)
4687 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4688 (goto-char beg)
4689 ;; Include headline point is currently on.
4690 (beginning-of-line)
4691 (while (and (< (point) end) (re-search-forward re end t))
4692 (when (member org-archive-tag (org-get-tags nil t))
4693 (org-flag-subtree t)
4694 (org-end-of-subtree t))))))
4696 (defun org-flag-subtree (flag)
4697 (save-excursion
4698 (org-back-to-heading t)
4699 (org-flag-region (line-end-position)
4700 (progn (org-end-of-subtree t) (point))
4701 flag
4702 'outline)))
4704 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4706 ;; Declare Column View Code
4708 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4709 (declare-function org-columns-compute "org-colview" (property))
4711 ;; Declare ID code
4713 (declare-function org-id-store-link "org-id")
4714 (declare-function org-id-locations-load "org-id")
4715 (declare-function org-id-locations-save "org-id")
4716 (defvar org-id-track-globally)
4718 ;;; Variables for pre-computed regular expressions, all buffer local
4720 (defvar-local org-todo-regexp nil
4721 "Matches any of the TODO state keywords.
4722 Since TODO keywords are case-sensitive, `case-fold-search' is
4723 expected to be bound to nil when matching against this regexp.")
4725 (defvar-local org-not-done-regexp nil
4726 "Matches any of the TODO state keywords except the last one.
4727 Since TODO keywords are case-sensitive, `case-fold-search' is
4728 expected to be bound to nil when matching against this regexp.")
4730 (defvar-local org-not-done-heading-regexp nil
4731 "Matches a TODO headline that is not done.
4732 Since TODO keywords are case-sensitive, `case-fold-search' is
4733 expected to be bound to nil when matching against this regexp.")
4735 (defvar-local org-todo-line-regexp nil
4736 "Matches a headline and puts TODO state into group 2 if present.
4737 Since TODO keywords are case-sensitive, `case-fold-search' is
4738 expected to be bound to nil when matching against this regexp.")
4740 (defvar-local org-complex-heading-regexp nil
4741 "Matches a headline and puts everything into groups:
4743 group 1: Stars
4744 group 2: The TODO keyword, maybe
4745 group 3: Priority cookie
4746 group 4: True headline
4747 group 5: Tags
4749 Since TODO keywords are case-sensitive, `case-fold-search' is
4750 expected to be bound to nil when matching against this regexp.")
4752 (defvar-local org-complex-heading-regexp-format nil
4753 "Printf format to make regexp to match an exact headline.
4754 This regexp will match the headline of any node which has the
4755 exact headline text that is put into the format, but may have any
4756 TODO state, priority and tags.")
4758 (defvar-local org-todo-line-tags-regexp nil
4759 "Matches a headline and puts TODO state into group 2 if present.
4760 Also put tags into group 4 if tags are present.")
4762 (defconst org-plain-time-of-day-regexp
4763 (concat
4764 "\\(\\<[012]?[0-9]"
4765 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4766 "\\(--?"
4767 "\\(\\<[012]?[0-9]"
4768 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4769 "\\)?")
4770 "Regular expression to match a plain time or time range.
4771 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4772 groups carry important information:
4773 0 the full match
4774 1 the first time, range or not
4775 8 the second time, if it is a range.")
4777 (defconst org-plain-time-extension-regexp
4778 (concat
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4782 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4783 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4784 groups carry important information:
4785 0 the full match
4786 7 hours of duration
4787 9 minutes of duration")
4789 (defconst org-stamp-time-of-day-regexp
4790 (concat
4791 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4792 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4793 "\\(--?"
4794 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4795 "Regular expression to match a timestamp time or time range.
4796 After a match, the following groups carry important information:
4797 0 the full match
4798 1 date plus weekday, for back referencing to make sure both times are on the same day
4799 2 the first time, range or not
4800 4 the second time, if it is a range.")
4802 (defconst org-startup-options
4803 '(("fold" org-startup-folded t)
4804 ("overview" org-startup-folded t)
4805 ("nofold" org-startup-folded nil)
4806 ("showall" org-startup-folded nil)
4807 ("showeverything" org-startup-folded showeverything)
4808 ("content" org-startup-folded content)
4809 ("indent" org-startup-indented t)
4810 ("noindent" org-startup-indented nil)
4811 ("hidestars" org-hide-leading-stars t)
4812 ("showstars" org-hide-leading-stars nil)
4813 ("odd" org-odd-levels-only t)
4814 ("oddeven" org-odd-levels-only nil)
4815 ("align" org-startup-align-all-tables t)
4816 ("noalign" org-startup-align-all-tables nil)
4817 ("shrink" org-startup-shrink-all-tables t)
4818 ("inlineimages" org-startup-with-inline-images t)
4819 ("noinlineimages" org-startup-with-inline-images nil)
4820 ("latexpreview" org-startup-with-latex-preview t)
4821 ("nolatexpreview" org-startup-with-latex-preview nil)
4822 ("customtime" org-display-custom-times t)
4823 ("logdone" org-log-done time)
4824 ("lognotedone" org-log-done note)
4825 ("nologdone" org-log-done nil)
4826 ("lognoteclock-out" org-log-note-clock-out t)
4827 ("nolognoteclock-out" org-log-note-clock-out nil)
4828 ("logrepeat" org-log-repeat state)
4829 ("lognoterepeat" org-log-repeat note)
4830 ("logdrawer" org-log-into-drawer t)
4831 ("nologdrawer" org-log-into-drawer nil)
4832 ("logstatesreversed" org-log-states-order-reversed t)
4833 ("nologstatesreversed" org-log-states-order-reversed nil)
4834 ("nologrepeat" org-log-repeat nil)
4835 ("logreschedule" org-log-reschedule time)
4836 ("lognotereschedule" org-log-reschedule note)
4837 ("nologreschedule" org-log-reschedule nil)
4838 ("logredeadline" org-log-redeadline time)
4839 ("lognoteredeadline" org-log-redeadline note)
4840 ("nologredeadline" org-log-redeadline nil)
4841 ("logrefile" org-log-refile time)
4842 ("lognoterefile" org-log-refile note)
4843 ("nologrefile" org-log-refile nil)
4844 ("fninline" org-footnote-define-inline t)
4845 ("nofninline" org-footnote-define-inline nil)
4846 ("fnlocal" org-footnote-section nil)
4847 ("fnauto" org-footnote-auto-label t)
4848 ("fnprompt" org-footnote-auto-label nil)
4849 ("fnconfirm" org-footnote-auto-label confirm)
4850 ("fnplain" org-footnote-auto-label plain)
4851 ("fnadjust" org-footnote-auto-adjust t)
4852 ("nofnadjust" org-footnote-auto-adjust nil)
4853 ("constcgs" constants-unit-system cgs)
4854 ("constSI" constants-unit-system SI)
4855 ("noptag" org-tag-persistent-alist nil)
4856 ("hideblocks" org-hide-block-startup t)
4857 ("nohideblocks" org-hide-block-startup nil)
4858 ("beamer" org-startup-with-beamer-mode t)
4859 ("entitiespretty" org-pretty-entities t)
4860 ("entitiesplain" org-pretty-entities nil))
4861 "Variable associated with STARTUP options for Org.
4862 Each element is a list of three items: the startup options (as written
4863 in the #+STARTUP line), the corresponding variable, and the value to set
4864 this variable to if the option is found. An optional forth element PUSH
4865 means to push this value onto the list in the variable.")
4867 (defcustom org-group-tags t
4868 "When non-nil (the default), use group tags.
4869 This can be turned on/off through `org-toggle-tags-groups'."
4870 :group 'org-tags
4871 :group 'org-startup
4872 :type 'boolean)
4874 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4876 (defun org-toggle-tags-groups ()
4877 "Toggle support for group tags.
4878 Support for group tags is controlled by the option
4879 `org-group-tags', which is non-nil by default."
4880 (interactive)
4881 (setq org-group-tags (not org-group-tags))
4882 (cond ((and (derived-mode-p 'org-agenda-mode)
4883 org-group-tags)
4884 (org-agenda-redo))
4885 ((derived-mode-p 'org-mode)
4886 (let ((org-inhibit-startup t)) (org-mode))))
4887 (message "Groups tags support has been turned %s"
4888 (if org-group-tags "on" "off")))
4890 (defun org--tag-add-to-alist (alist1 alist2)
4891 "Merge tags from ALIST1 into ALIST2.
4893 Duplicates tags outside a group are removed. Keywords and order
4894 are preserved.
4896 The function assumes ALIST1 and ALIST2 are proper tag alists.
4897 See `org-tag-alist' for their structure."
4898 (cond
4899 ((null alist2) alist1)
4900 ((null alist1) alist2)
4902 (let ((to-add nil)
4903 (group-flag nil))
4904 (dolist (tag-pair alist1)
4905 (pcase tag-pair
4906 (`(,(or :startgrouptag :startgroup))
4907 (setq group-flag t)
4908 (push tag-pair to-add))
4909 (`(,(or :endgrouptag :endgroup))
4910 (setq group-flag nil)
4911 (push tag-pair to-add))
4912 (`(,(or :grouptags :newline))
4913 (push tag-pair to-add))
4914 (`(,tag . ,_)
4915 ;; Remove duplicates from ALIST1, unless they are in
4916 ;; a group. Indeed, it makes sense to have a tag appear in
4917 ;; multiple groups.
4918 (when (or group-flag (not (assoc tag alist2)))
4919 (push tag-pair to-add)))
4920 (_ (error "Invalid association in tag alist: %S" tag-pair))))
4921 ;; Preserve order of ALIST1.
4922 (append (nreverse to-add) alist2)))))
4924 (defun org-set-regexps-and-options (&optional tags-only)
4925 "Precompute regular expressions used in the current buffer.
4926 When optional argument TAGS-ONLY is non-nil, only compute tags
4927 related expressions."
4928 (when (derived-mode-p 'org-mode)
4929 (let ((alist (org--setup-collect-keywords
4930 (org-make-options-regexp
4931 (append '("FILETAGS" "TAGS" "SETUPFILE")
4932 (and (not tags-only)
4933 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4934 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4935 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4936 ;; Startup options. Get this early since it does change
4937 ;; behavior for other options (e.g., tags).
4938 (let ((startup (cdr (assq 'startup alist))))
4939 (dolist (option startup)
4940 (let ((entry (assoc-string option org-startup-options t)))
4941 (when entry
4942 (let ((var (nth 1 entry))
4943 (val (nth 2 entry)))
4944 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4945 (unless (listp (symbol-value var))
4946 (set (make-local-variable var) nil))
4947 (add-to-list var val)))))))
4948 (setq-local org-file-tags
4949 (mapcar #'org-add-prop-inherited
4950 (cdr (assq 'filetags alist))))
4951 (setq org-current-tag-alist
4952 (org--tag-add-to-alist
4953 org-tag-persistent-alist
4954 (let ((tags (cdr (assq 'tags alist))))
4955 (if tags (org-tag-string-to-alist tags)
4956 org-tag-alist))))
4957 (setq org-tag-groups-alist
4958 (org-tag-alist-to-groups org-current-tag-alist))
4959 (unless tags-only
4960 ;; File properties.
4961 (setq-local org-file-properties (cdr (assq 'property alist)))
4962 ;; Archive location.
4963 (let ((archive (cdr (assq 'archive alist))))
4964 (when archive (setq-local org-archive-location archive)))
4965 ;; Category.
4966 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4967 (when cat
4968 (setq-local org-category (intern cat))
4969 (setq-local org-file-properties
4970 (org--update-property-plist
4971 "CATEGORY" cat org-file-properties))))
4972 ;; Columns.
4973 (let ((column (cdr (assq 'columns alist))))
4974 (when column (setq-local org-columns-default-format column)))
4975 ;; Constants.
4976 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4977 ;; Link abbreviations.
4978 (let ((links (cdr (assq 'link alist))))
4979 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4980 ;; Priorities.
4981 (let ((priorities (cdr (assq 'priorities alist))))
4982 (when priorities
4983 (setq-local org-highest-priority (nth 0 priorities))
4984 (setq-local org-lowest-priority (nth 1 priorities))
4985 (setq-local org-default-priority (nth 2 priorities))))
4986 ;; Scripts.
4987 (let ((scripts (assq 'scripts alist)))
4988 (when scripts
4989 (setq-local org-use-sub-superscripts (cdr scripts))))
4990 ;; TODO keywords.
4991 (setq-local org-todo-kwd-alist nil)
4992 (setq-local org-todo-key-alist nil)
4993 (setq-local org-todo-key-trigger nil)
4994 (setq-local org-todo-keywords-1 nil)
4995 (setq-local org-done-keywords nil)
4996 (setq-local org-todo-heads nil)
4997 (setq-local org-todo-sets nil)
4998 (setq-local org-todo-log-states nil)
4999 (let ((todo-sequences
5000 (or (nreverse (cdr (assq 'todo alist)))
5001 (let ((d (default-value 'org-todo-keywords)))
5002 (if (not (stringp (car d))) d
5003 ;; XXX: Backward compatibility code.
5004 (list (cons org-todo-interpretation d)))))))
5005 (dolist (sequence todo-sequences)
5006 (let* ((sequence (or (run-hook-with-args-until-success
5007 'org-todo-setup-filter-hook sequence)
5008 sequence))
5009 (sequence-type (car sequence))
5010 (keywords (cdr sequence))
5011 (sep (member "|" keywords))
5012 names alist)
5013 (dolist (k (remove "|" keywords))
5014 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5016 (error "Invalid TODO keyword %s" k))
5017 (let ((name (match-string 1 k))
5018 (key (match-string 2 k))
5019 (log (org-extract-log-state-settings k)))
5020 (push name names)
5021 (push (cons name (and key (string-to-char key))) alist)
5022 (when log (push log org-todo-log-states))))
5023 (let* ((names (nreverse names))
5024 (done (if sep (org-remove-keyword-keys (cdr sep))
5025 (last names)))
5026 (head (car names))
5027 (tail (list sequence-type head (car done) (org-last done))))
5028 (add-to-list 'org-todo-heads head 'append)
5029 (push names org-todo-sets)
5030 (setq org-done-keywords (append org-done-keywords done nil))
5031 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5032 (setq org-todo-key-alist
5033 (append org-todo-key-alist
5034 (and alist
5035 (append '((:startgroup))
5036 (nreverse alist)
5037 '((:endgroup))))))
5038 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5039 (setq org-todo-sets (nreverse org-todo-sets)
5040 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5041 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5042 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5043 ;; Compute the regular expressions and other local variables.
5044 ;; Using `org-outline-regexp-bol' would complicate them much,
5045 ;; because of the fixed white space at the end of that string.
5046 (unless org-done-keywords
5047 (setq org-done-keywords
5048 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5049 (setq org-not-done-keywords
5050 (org-delete-all org-done-keywords
5051 (copy-sequence org-todo-keywords-1))
5052 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5053 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5054 org-not-done-heading-regexp
5055 (format org-heading-keyword-regexp-format org-not-done-regexp)
5056 org-todo-line-regexp
5057 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5058 org-complex-heading-regexp
5059 (concat "^\\(\\*+\\)"
5060 "\\(?: +" org-todo-regexp "\\)?"
5061 "\\(?: +\\(\\[#.\\]\\)\\)?"
5062 "\\(?: +\\(.*?\\)\\)??"
5063 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5064 "[ \t]*$")
5065 org-complex-heading-regexp-format
5066 (concat "^\\(\\*+\\)"
5067 "\\(?: +" org-todo-regexp "\\)?"
5068 "\\(?: +\\(\\[#.\\]\\)\\)?"
5069 "\\(?: +"
5070 ;; Stats cookies can be stuck to body.
5071 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5072 "\\(%s\\)"
5073 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5074 "\\)"
5075 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5076 "[ \t]*$")
5077 org-todo-line-tags-regexp
5078 (concat "^\\(\\*+\\)"
5079 "\\(?: +" org-todo-regexp "\\)?"
5080 "\\(?: +\\(.*?\\)\\)??"
5081 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5082 "[ \t]*$"))
5083 (org-compute-latex-and-related-regexp)))))
5085 (defun org--setup-collect-keywords (regexp &optional files alist)
5086 "Return setup keywords values as an alist.
5088 REGEXP matches a subset of setup keywords. FILES is a list of
5089 file names already visited. It is used to avoid circular setup
5090 files. ALIST, when non-nil, is the alist computed so far.
5092 Return value contains the following keys: `archive', `category',
5093 `columns', `constants', `filetags', `link', `priorities',
5094 `property', `scripts', `startup', `tags' and `todo'."
5095 (org-with-wide-buffer
5096 (goto-char (point-min))
5097 (let ((case-fold-search t))
5098 (while (re-search-forward regexp nil t)
5099 (let ((element (org-element-at-point)))
5100 (when (eq (org-element-type element) 'keyword)
5101 (let ((key (org-element-property :key element))
5102 (value (org-element-property :value element)))
5103 (cond
5104 ((equal key "ARCHIVE")
5105 (when (org-string-nw-p value)
5106 (push (cons 'archive value) alist)))
5107 ((equal key "CATEGORY") (push (cons 'category value) alist))
5108 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5109 ((equal key "CONSTANTS")
5110 (let* ((constants (assq 'constants alist))
5111 (store (cdr constants)))
5112 (dolist (pair (split-string value))
5113 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5114 pair)
5115 (let* ((name (match-string 1 pair))
5116 (value (match-string 2 pair))
5117 (old (assoc name store)))
5118 (if old (setcdr old value)
5119 (push (cons name value) store)))))
5120 (if constants (setcdr constants store)
5121 (push (cons 'constants store) alist))))
5122 ((equal key "FILETAGS")
5123 (when (org-string-nw-p value)
5124 (let ((old (assq 'filetags alist))
5125 (new (apply #'nconc
5126 (mapcar (lambda (x) (org-split-string x ":"))
5127 (split-string value)))))
5128 (if old (setcdr old (append new (cdr old)))
5129 (push (cons 'filetags new) alist)))))
5130 ((equal key "LINK")
5131 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5132 (let ((links (assq 'link alist))
5133 (pair (cons (match-string-no-properties 1 value)
5134 (match-string-no-properties 2 value))))
5135 (if links (push pair (cdr links))
5136 (push (list 'link pair) alist)))))
5137 ((equal key "OPTIONS")
5138 (when (and (org-string-nw-p value)
5139 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5140 (push (cons 'scripts (read (match-string 1 value))) alist)))
5141 ((equal key "PRIORITIES")
5142 (push (cons 'priorities
5143 (let ((prio (split-string value)))
5144 (if (< (length prio) 3) '(?A ?C ?B)
5145 (mapcar #'string-to-char prio))))
5146 alist))
5147 ((equal key "PROPERTY")
5148 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5149 (let* ((property (assq 'property alist))
5150 (value (org--update-property-plist
5151 (match-string-no-properties 1 value)
5152 (match-string-no-properties 2 value)
5153 (cdr property))))
5154 (if property (setcdr property value)
5155 (push (cons 'property value) alist)))))
5156 ((equal key "STARTUP")
5157 (let ((startup (assq 'startup alist)))
5158 (if startup
5159 (setcdr startup
5160 (append (cdr startup) (split-string value)))
5161 (push (cons 'startup (split-string value)) alist))))
5162 ((equal key "TAGS")
5163 (let ((tag-cell (assq 'tags alist)))
5164 (if tag-cell
5165 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5166 (push (cons 'tags value) alist))))
5167 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5168 (let ((todo (assq 'todo alist))
5169 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5170 (split-string value))))
5171 (if todo (push value (cdr todo))
5172 (push (list 'todo value) alist))))
5173 ((equal key "SETUPFILE")
5174 (unless buffer-read-only ; Do not check in Gnus messages.
5175 (let ((f (and (org-string-nw-p value)
5176 (expand-file-name
5177 (org-unbracket-string "\"" "\"" value)))))
5178 (when (and f (file-readable-p f) (not (member f files)))
5179 (with-temp-buffer
5180 (setq default-directory (file-name-directory f))
5181 (insert-file-contents f)
5182 (setq alist
5183 ;; Fake Org mode to benefit from cache
5184 ;; without recurring needlessly.
5185 (let ((major-mode 'org-mode))
5186 (org--setup-collect-keywords
5187 regexp (cons f files) alist)))))))))))))))
5188 alist)
5190 (defun org-tag-string-to-alist (s)
5191 "Return tag alist associated to string S.
5192 S is a value for TAGS keyword or produced with
5193 `org-tag-alist-to-string'. Return value is an alist suitable for
5194 `org-tag-alist' or `org-tag-persistent-alist'."
5195 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5196 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5197 "\\(?:(\\(.\\))\\)?\\'"))
5198 alist group-flag)
5199 (dolist (tokens lines (cdr (nreverse alist)))
5200 (push '(:newline) alist)
5201 (while tokens
5202 (let ((token (pop tokens)))
5203 (pcase token
5204 ("{"
5205 (push '(:startgroup) alist)
5206 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5207 ("}"
5208 (push '(:endgroup) alist)
5209 (setq group-flag nil))
5210 ("["
5211 (push '(:startgrouptag) alist)
5212 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5213 ("]"
5214 (push '(:endgrouptag) alist)
5215 (setq group-flag nil))
5216 (":"
5217 (push '(:grouptags) alist))
5218 ((guard (string-match tag-re token))
5219 (let ((tag (match-string 1 token))
5220 (key (and (match-beginning 2)
5221 (string-to-char (match-string 2 token)))))
5222 ;; Push all tags in groups, no matter if they already
5223 ;; appear somewhere else in the list.
5224 (when (or group-flag (not (assoc tag alist)))
5225 (push (cons tag key) alist))))))))))
5227 (defun org-tag-alist-to-string (alist &optional skip-key)
5228 "Return tag string associated to ALIST.
5230 ALIST is an alist, as defined in `org-tag-alist' or
5231 `org-tag-persistent-alist', or produced with
5232 `org-tag-string-to-alist'.
5234 Return value is a string suitable as a value for \"TAGS\"
5235 keyword.
5237 When optional argument SKIP-KEY is non-nil, skip selection keys
5238 next to tags."
5239 (mapconcat (lambda (token)
5240 (pcase token
5241 (`(:startgroup) "{")
5242 (`(:endgroup) "}")
5243 (`(:startgrouptag) "[")
5244 (`(:endgrouptag) "]")
5245 (`(:grouptags) ":")
5246 (`(:newline) "\\n")
5247 ((and
5248 (guard (not skip-key))
5249 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5250 (format "%s(%c)" tag key))
5251 (`(,(and tag (pred stringp)) . ,_) tag)
5252 (_ (user-error "Invalid tag token: %S" token))))
5253 alist
5254 " "))
5256 (defun org-tag-alist-to-groups (alist)
5257 "Return group alist from tag ALIST.
5258 ALIST is an alist, as defined in `org-tag-alist' or
5259 `org-tag-persistent-alist', or produced with
5260 `org-tag-string-to-alist'. Return value is an alist following
5261 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5262 a string, summarizing TAGS, as a list of strings."
5263 (let (groups group-status current-group)
5264 (dolist (token alist (nreverse groups))
5265 (pcase token
5266 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5267 (`(,(or :endgroup :endgrouptag))
5268 (when (eq group-status 'append)
5269 (push (nreverse current-group) groups))
5270 (setq group-status nil current-group nil))
5271 (`(:grouptags) (setq group-status 'append))
5272 ((and `(,tag . ,_) (guard group-status))
5273 (if (eq group-status 'append) (push tag current-group)
5274 (setq current-group (list tag))))
5275 (_ nil)))))
5277 (defvar org--file-cache (make-hash-table :test #'equal)
5278 "Hash table to store contents of files referenced via a URL.
5279 This is the cache of file URLs read using `org-file-contents'.")
5281 (defun org-reset-file-cache ()
5282 "Reset the cache of files downloaded by `org-file-contents'."
5283 (clrhash org--file-cache))
5285 (defun org-file-url-p (file)
5286 "Non-nil if FILE is a URL."
5287 (require 'ffap)
5288 (string-match-p ffap-url-regexp file))
5290 (defun org-file-contents (file &optional noerror nocache)
5291 "Return the contents of FILE, as a string.
5293 FILE can be a file name or URL.
5295 If FILE is a URL, download the contents. If the URL contents are
5296 already cached in the `org--file-cache' hash table, the download step
5297 is skipped.
5299 If NOERROR is non-nil, ignore the error when unable to read the FILE
5300 from file or URL.
5302 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5303 is available. This option applies only if FILE is a URL."
5304 (let* ((is-url (org-file-url-p file))
5305 (cache (and is-url
5306 (not nocache)
5307 (gethash file org--file-cache))))
5308 (cond
5309 (cache)
5310 (is-url
5311 (with-current-buffer (url-retrieve-synchronously file)
5312 (goto-char (point-min))
5313 ;; Move point to after the url-retrieve header.
5314 (search-forward "\n\n" nil :move)
5315 ;; Search for the success code only in the url-retrieve header.
5316 (if (save-excursion
5317 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5318 ;; Update the cache `org--file-cache' and return contents.
5319 (puthash file
5320 (buffer-substring-no-properties (point) (point-max))
5321 org--file-cache)
5322 (funcall (if noerror #'message #'user-error)
5323 "Unable to fetch file from %S"
5324 file))))
5326 (with-temp-buffer
5327 (condition-case nil
5328 (progn
5329 (insert-file-contents file)
5330 (buffer-string))
5331 (file-error
5332 (funcall (if noerror #'message #'user-error)
5333 "Unable to read file %S"
5334 file))))))))
5336 (defun org-extract-log-state-settings (x)
5337 "Extract the log state setting from a TODO keyword string.
5338 This will extract info from a string like \"WAIT(w@/!)\"."
5339 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5340 (let ((kw (match-string 1 x))
5341 (log1 (and (match-end 3) (match-string 3 x)))
5342 (log2 (and (match-end 4) (match-string 4 x))))
5343 (and (or log1 log2)
5344 (list kw
5345 (and log1 (if (equal log1 "!") 'time 'note))
5346 (and log2 (if (equal log2 "!") 'time 'note)))))))
5348 (defun org-remove-keyword-keys (list)
5349 "Remove a pair of parenthesis at the end of each string in LIST."
5350 (mapcar (lambda (x)
5351 (if (string-match "(.*)$" x)
5352 (substring x 0 (match-beginning 0))
5354 list))
5356 (defun org-assign-fast-keys (alist)
5357 "Assign fast keys to a keyword-key alist.
5358 Respect keys that are already there."
5359 (let (new e (alt ?0))
5360 (while (setq e (pop alist))
5361 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5362 (cdr e)) ;; Key already assigned.
5363 (push e new)
5364 (let ((clist (string-to-list (downcase (car e))))
5365 (used (append new alist)))
5366 (when (= (car clist) ?@)
5367 (pop clist))
5368 (while (and clist (rassoc (car clist) used))
5369 (pop clist))
5370 (unless clist
5371 (while (rassoc alt used)
5372 (cl-incf alt)))
5373 (push (cons (car e) (or (car clist) alt)) new))))
5374 (nreverse new)))
5376 ;;; Some variables used in various places
5378 (defvar org-window-configuration nil
5379 "Used in various places to store a window configuration.")
5380 (defvar org-selected-window nil
5381 "Used in various places to store a window configuration.")
5382 (defvar org-finish-function nil
5383 "Function to be called when `C-c C-c' is used.
5384 This is for getting out of special buffers like capture.")
5385 (defvar org-last-state)
5387 ;; Defined somewhere in this file, but used before definition.
5388 (defvar org-entities) ;; defined in org-entities.el
5389 (defvar org-struct-menu)
5390 (defvar org-org-menu)
5391 (defvar org-tbl-menu)
5393 ;;;; Define the Org mode
5395 ;; We use a before-change function to check if a table might need
5396 ;; an update.
5397 (defvar org-table-may-need-update t
5398 "Indicates that a table might need an update.
5399 This variable is set by `org-before-change-function'.
5400 `org-table-align' sets it back to nil.")
5401 (defun org-before-change-function (_beg _end)
5402 "Every change indicates that a table might need an update."
5403 (setq org-table-may-need-update t))
5404 (defvar org-mode-map)
5405 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5406 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5407 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5408 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5409 (defvar org-table-buffer-is-an nil)
5411 (defvar bidi-paragraph-direction)
5412 (defvar buffer-face-mode-face)
5414 (require 'outline)
5416 ;; Other stuff we need.
5417 (require 'time-date)
5418 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5419 (require 'easymenu)
5420 (autoload 'easy-menu-add "easymenu")
5421 (require 'overlay)
5423 ;; (require 'org-macs) moved higher up in the file before it is first used
5424 (require 'org-entities)
5425 ;; (require 'org-compat) moved higher up in the file before it is first used
5426 (require 'org-faces)
5427 (require 'org-list)
5428 (require 'org-pcomplete)
5429 (require 'org-src)
5430 (require 'org-footnote)
5431 (require 'org-macro)
5433 ;; babel
5434 (require 'ob)
5436 ;;;###autoload
5437 (define-derived-mode org-mode outline-mode "Org"
5438 "Outline-based notes management and organizer, alias
5439 \"Carsten's outline-mode for keeping track of everything.\"
5441 Org mode develops organizational tasks around a NOTES file which
5442 contains information about projects as plain text. Org mode is
5443 implemented on top of Outline mode, which is ideal to keep the content
5444 of large files well structured. It supports ToDo items, deadlines and
5445 time stamps, which magically appear in the diary listing of the Emacs
5446 calendar. Tables are easily created with a built-in table editor.
5447 Plain text URL-like links connect to websites, emails (VM), Usenet
5448 messages (Gnus), BBDB entries, and any files related to the project.
5449 For printing and sharing of notes, an Org file (or a part of it)
5450 can be exported as a structured ASCII or HTML file.
5452 The following commands are available:
5454 \\{org-mode-map}"
5456 ;; Get rid of Outline menus, they are not needed
5457 ;; Need to do this here because define-derived-mode sets up
5458 ;; the keymap so late. Still, it is a waste to call this each time
5459 ;; we switch another buffer into Org mode.
5460 (define-key org-mode-map [menu-bar headings] 'undefined)
5461 (define-key org-mode-map [menu-bar hide] 'undefined)
5462 (define-key org-mode-map [menu-bar show] 'undefined)
5464 (org-load-modules-maybe)
5465 (org-install-agenda-files-menu)
5466 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5467 (add-to-invisibility-spec '(org-hide-block . t))
5468 (add-to-invisibility-spec '(org-hide-drawer . t))
5469 (setq-local outline-regexp org-outline-regexp)
5470 (setq-local outline-level 'org-outline-level)
5471 (setq bidi-paragraph-direction 'left-to-right)
5472 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5473 (unless org-display-table
5474 (setq org-display-table (make-display-table)))
5475 (set-display-table-slot
5476 org-display-table 4
5477 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5478 org-ellipsis)))
5479 (setq buffer-display-table org-display-table))
5480 (org-set-regexps-and-options)
5481 (org-set-font-lock-defaults)
5482 (when (and org-tag-faces (not org-tags-special-faces-re))
5483 ;; tag faces set outside customize.... force initialization.
5484 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5485 ;; Calc embedded
5486 (setq-local calc-embedded-open-mode "# ")
5487 ;; Modify a few syntax entries
5488 (modify-syntax-entry ?\" "\"")
5489 (modify-syntax-entry ?\\ "_")
5490 (modify-syntax-entry ?~ "_")
5491 (modify-syntax-entry ?< "(>")
5492 (modify-syntax-entry ?> ")<")
5493 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5494 ;; Activate before-change-function
5495 (setq-local org-table-may-need-update t)
5496 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5497 ;; Check for running clock before killing a buffer
5498 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5499 ;; Initialize macros templates.
5500 (org-macro-initialize-templates)
5501 ;; Initialize radio targets.
5502 (org-update-radio-target-regexp)
5503 ;; Indentation.
5504 (setq-local indent-line-function 'org-indent-line)
5505 (setq-local indent-region-function 'org-indent-region)
5506 ;; Filling and auto-filling.
5507 (org-setup-filling)
5508 ;; Comments.
5509 (org-setup-comments-handling)
5510 ;; Initialize cache.
5511 (org-element-cache-reset)
5512 ;; Beginning/end of defun
5513 (setq-local beginning-of-defun-function 'org-backward-element)
5514 (setq-local end-of-defun-function
5515 (lambda ()
5516 (if (not (org-at-heading-p))
5517 (org-forward-element)
5518 (org-forward-element)
5519 (forward-char -1))))
5520 ;; Next error for sparse trees
5521 (setq-local next-error-function 'org-occur-next-match)
5522 ;; Make commit log messages from Org documents easier.
5523 (setq-local add-log-current-defun-function #'org-add-log-current-headline)
5524 ;; Make sure dependence stuff works reliably, even for users who set it
5525 ;; too late :-(
5526 (if org-enforce-todo-dependencies
5527 (add-hook 'org-blocker-hook
5528 'org-block-todo-from-children-or-siblings-or-parent)
5529 (remove-hook 'org-blocker-hook
5530 'org-block-todo-from-children-or-siblings-or-parent))
5531 (if org-enforce-todo-checkbox-dependencies
5532 (add-hook 'org-blocker-hook
5533 'org-block-todo-from-checkboxes)
5534 (remove-hook 'org-blocker-hook
5535 'org-block-todo-from-checkboxes))
5537 ;; Align options lines
5538 (setq-local
5539 align-mode-rules-list
5540 '((org-in-buffer-settings
5541 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5542 (modes . '(org-mode)))))
5544 ;; Make isearch reveal context
5545 (setq-local outline-isearch-open-invisible-function
5546 (lambda (&rest _) (org-show-context 'isearch)))
5548 ;; Setup the pcomplete hooks
5549 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5550 (setq-local pcomplete-command-name-function 'org-command-at-point)
5551 (setq-local pcomplete-default-completion-function 'ignore)
5552 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5553 (setq-local pcomplete-termination-string "")
5554 (setq-local buffer-face-mode-face 'org-default)
5556 ;; If empty file that did not turn on Org mode automatically, make
5557 ;; it to.
5558 (when (and org-insert-mode-line-in-empty-file
5559 (called-interactively-p 'any)
5560 (= (point-min) (point-max)))
5561 (insert "# -*- mode: org -*-\n\n"))
5562 (unless org-inhibit-startup
5563 (org-unmodified
5564 (when org-startup-with-beamer-mode (org-beamer-mode))
5565 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5566 (org-table-map-tables
5567 (cond ((and org-startup-align-all-tables
5568 org-startup-shrink-all-tables)
5569 (lambda () (org-table-align) (org-table-shrink)))
5570 (org-startup-align-all-tables #'org-table-align)
5571 (t #'org-table-shrink))
5573 (when org-startup-with-inline-images (org-display-inline-images))
5574 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5575 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5576 (when org-startup-truncated (setq truncate-lines t))
5577 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5578 (org-refresh-effort-properties)))
5579 ;; Try to set `org-hide' face correctly.
5580 (let ((foreground (org-find-invisible-foreground)))
5581 (when foreground
5582 (set-face-foreground 'org-hide foreground))))
5584 ;; Update `customize-package-emacs-version-alist'
5585 (add-to-list 'customize-package-emacs-version-alist
5586 '(Org ("8.0" . "24.4")
5587 ("8.1" . "24.4")
5588 ("8.2" . "24.4")
5589 ("8.2.7" . "24.4")
5590 ("8.3" . "26.1")
5591 ("9.0" . "26.1")
5592 ("9.1" . "26.1")
5593 ("9.2" . "27.1")))
5595 (defvar org-mode-transpose-word-syntax-table
5596 (let ((st (make-syntax-table text-mode-syntax-table)))
5597 (dolist (c org-emphasis-alist st)
5598 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5600 (when (fboundp 'abbrev-table-put)
5601 (abbrev-table-put org-mode-abbrev-table
5602 :parents (list text-mode-abbrev-table)))
5604 (defun org-find-invisible-foreground ()
5605 (let ((candidates (remove
5606 "unspecified-bg"
5607 (nconc
5608 (list (face-background 'default)
5609 (face-background 'org-default))
5610 (mapcar
5611 (lambda (alist)
5612 (when (boundp alist)
5613 (cdr (assq 'background-color (symbol-value alist)))))
5614 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5615 (list (face-foreground 'org-hide))))))
5616 (car (remove nil candidates))))
5618 (defun org-current-time (&optional rounding-minutes past)
5619 "Current time, possibly rounded to ROUNDING-MINUTES.
5620 When ROUNDING-MINUTES is not an integer, fall back on the car of
5621 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5622 the rounding returns a past time."
5623 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5624 (car org-time-stamp-rounding-minutes)))
5625 (time (decode-time)) res)
5626 (if (< r 1)
5627 (current-time)
5628 (setq res
5629 (apply 'encode-time
5630 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5631 (nthcdr 2 time))))
5632 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5633 (seconds-to-time (- (float-time res) (* r 60)))
5634 res))))
5636 (defun org-today ()
5637 "Return today date, considering `org-extend-today-until'."
5638 (time-to-days
5639 (time-subtract (current-time)
5640 (list 0 (* 3600 org-extend-today-until) 0))))
5642 ;;;; Font-Lock stuff, including the activators
5644 (defvar org-mouse-map (make-sparse-keymap))
5645 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5646 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5647 (when org-mouse-1-follows-link
5648 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5649 (when org-tab-follows-link
5650 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5651 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5653 (require 'font-lock)
5655 (defconst org-non-link-chars "]\t\n\r<>")
5656 (defvar org-link-types-re nil
5657 "Matches a link that has a url-like prefix like \"http:\"")
5658 (defvar org-link-re-with-space nil
5659 "Matches a link with spaces, optional angular brackets around it.")
5660 (defvar org-link-re-with-space2 nil
5661 "Matches a link with spaces, optional angular brackets around it.")
5662 (defvar org-link-re-with-space3 nil
5663 "Matches a link with spaces, only for internal part in bracket links.")
5664 (defvar org-angle-link-re nil
5665 "Matches link with angular brackets, spaces are allowed.")
5666 (defvar org-plain-link-re nil
5667 "Matches plain link, without spaces.")
5668 (defvar org-bracket-link-regexp nil
5669 "Matches a link in double brackets.")
5670 (defvar org-bracket-link-analytic-regexp nil
5671 "Regular expression used to analyze links.
5672 Here is what the match groups contain after a match:
5673 1: http:
5674 2: http
5675 3: path
5676 4: [desc]
5677 5: desc")
5678 (defvar org-bracket-link-analytic-regexp++ nil
5679 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5680 (defvar org-any-link-re nil
5681 "Regular expression matching any link.")
5683 (defconst org-match-sexp-depth 3
5684 "Number of stacked braces for sub/superscript matching.")
5686 (defun org-create-multibrace-regexp (left right n)
5687 "Create a regular expression which will match a balanced sexp.
5688 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5689 as single character strings.
5690 The regexp returned will match the entire expression including the
5691 delimiters. It will also define a single group which contains the
5692 match except for the outermost delimiters. The maximum depth of
5693 stacked delimiters is N. Escaping delimiters is not possible."
5694 (let* ((nothing (concat "[^" left right "]*?"))
5695 (or "\\|")
5696 (re nothing)
5697 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5698 (while (> n 1)
5699 (setq n (1- n)
5700 re (concat re or next)
5701 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5702 (concat left "\\(" re "\\)" right)))
5704 (defconst org-match-substring-regexp
5705 (concat
5706 "\\(\\S-\\)\\([_^]\\)\\("
5707 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5708 "\\|"
5709 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5710 "\\|"
5711 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5712 "The regular expression matching a sub- or superscript.")
5714 (defconst org-match-substring-with-braces-regexp
5715 (concat
5716 "\\(\\S-\\)\\([_^]\\)"
5717 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5718 "The regular expression matching a sub- or superscript, forcing braces.")
5720 (defun org-make-link-regexps ()
5721 "Update the link regular expressions.
5722 This should be called after the variable `org-link-parameters' has changed."
5723 (let ((types-re (regexp-opt (org-link-types) t)))
5724 (setq org-link-types-re
5725 (concat "\\`" types-re ":")
5726 org-link-re-with-space
5727 (concat "<?" types-re ":"
5728 "\\([^" org-non-link-chars " ]"
5729 "[^" org-non-link-chars "]*"
5730 "[^" org-non-link-chars " ]\\)>?")
5731 org-link-re-with-space2
5732 (concat "<?" types-re ":"
5733 "\\([^" org-non-link-chars " ]"
5734 "[^\t\n\r]*"
5735 "[^" org-non-link-chars " ]\\)>?")
5736 org-link-re-with-space3
5737 (concat "<?" types-re ":"
5738 "\\([^" org-non-link-chars " ]"
5739 "[^\t\n\r]*\\)")
5740 org-angle-link-re
5741 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5742 types-re)
5743 org-plain-link-re
5744 (concat
5745 "\\<" types-re ":"
5746 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5747 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5748 org-bracket-link-regexp
5749 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5750 org-bracket-link-analytic-regexp
5751 (concat
5752 "\\[\\["
5753 "\\(" types-re ":\\)?"
5754 "\\([^]]+\\)"
5755 "\\]"
5756 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5757 "\\]")
5758 org-bracket-link-analytic-regexp++
5759 (concat
5760 "\\[\\["
5761 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5762 "\\([^]]+\\)"
5763 "\\]"
5764 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5765 "\\]")
5766 org-any-link-re
5767 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5768 org-angle-link-re "\\)\\|\\("
5769 org-plain-link-re "\\)"))))
5771 (org-make-link-regexps)
5773 (defvar org-emph-face nil)
5775 (defun org-do-emphasis-faces (limit)
5776 "Run through the buffer and emphasize strings."
5777 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5778 (car org-emphasis-regexp-components))))
5779 (catch :exit
5780 (while (re-search-forward quick-re limit t)
5781 (let* ((marker (match-string 2))
5782 (verbatim? (member marker '("~" "="))))
5783 (when (save-excursion
5784 (goto-char (match-beginning 0))
5785 (and
5786 ;; Do not match table hlines.
5787 (not (and (equal marker "+")
5788 (org-match-line
5789 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5790 ;; Do not match headline stars. Do not consider
5791 ;; stars of a headline as closing marker for bold
5792 ;; markup either.
5793 (not (and (equal marker "*")
5794 (save-excursion
5795 (forward-char)
5796 (skip-chars-backward "*")
5797 (looking-at-p org-outline-regexp-bol))))
5798 ;; Match full emphasis markup regexp.
5799 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5800 ;; Do not span over paragraph boundaries.
5801 (not (string-match-p org-element-paragraph-separate
5802 (match-string 2)))
5803 ;; Do not span over cells in table rows.
5804 (not (and (save-match-data (org-match-line "[ \t]*|"))
5805 (string-match-p "|" (match-string 4))))))
5806 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5807 (font-lock-prepend-text-property
5808 (match-beginning 2) (match-end 2) 'face face)
5809 (when verbatim?
5810 (org-remove-flyspell-overlays-in
5811 (match-beginning 0) (match-end 0))
5812 (remove-text-properties (match-beginning 2) (match-end 2)
5813 '(display t invisible t intangible t)))
5814 (add-text-properties (match-beginning 2) (match-end 2)
5815 '(font-lock-multiline t org-emphasis t))
5816 (when org-hide-emphasis-markers
5817 (add-text-properties (match-end 4) (match-beginning 5)
5818 '(invisible org-link))
5819 (add-text-properties (match-beginning 3) (match-end 3)
5820 '(invisible org-link)))
5821 (throw :exit t))))))))
5823 (defun org-emphasize (&optional char)
5824 "Insert or change an emphasis, i.e. a font like bold or italic.
5825 If there is an active region, change that region to a new emphasis.
5826 If there is no region, just insert the marker characters and position
5827 the cursor between them.
5828 CHAR should be the marker character. If it is a space, it means to
5829 remove the emphasis of the selected region.
5830 If CHAR is not given (for example in an interactive call) it will be
5831 prompted for."
5832 (interactive)
5833 (let ((erc org-emphasis-regexp-components)
5834 (string "") beg end move s)
5835 (if (org-region-active-p)
5836 (setq beg (region-beginning)
5837 end (region-end)
5838 string (buffer-substring beg end))
5839 (setq move t))
5841 (unless char
5842 (message "Emphasis marker or tag: [%s]"
5843 (mapconcat #'car org-emphasis-alist ""))
5844 (setq char (read-char-exclusive)))
5845 (if (equal char ?\s)
5846 (setq s ""
5847 move nil)
5848 (unless (assoc (char-to-string char) org-emphasis-alist)
5849 (user-error "No such emphasis marker: \"%c\"" char))
5850 (setq s (char-to-string char)))
5851 (while (and (> (length string) 1)
5852 (equal (substring string 0 1) (substring string -1))
5853 (assoc (substring string 0 1) org-emphasis-alist))
5854 (setq string (substring string 1 -1)))
5855 (setq string (concat s string s))
5856 (when beg (delete-region beg end))
5857 (unless (or (bolp)
5858 (string-match (concat "[" (nth 0 erc) "\n]")
5859 (char-to-string (char-before (point)))))
5860 (insert " "))
5861 (unless (or (eobp)
5862 (string-match (concat "[" (nth 1 erc) "\n]")
5863 (char-to-string (char-after (point)))))
5864 (insert " ") (backward-char 1))
5865 (insert string)
5866 (and move (backward-char 1))))
5868 (defconst org-nonsticky-props
5869 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5871 (defsubst org-rear-nonsticky-at (pos)
5872 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5874 (defun org-activate-links (limit)
5875 "Add link properties to links.
5876 This includes angle, plain, and bracket links."
5877 (catch :exit
5878 (while (re-search-forward org-any-link-re limit t)
5879 (let* ((start (match-beginning 0))
5880 (end (match-end 0))
5881 (style (cond ((eq ?< (char-after start)) 'angle)
5882 ((eq ?\[ (char-after (1+ start))) 'bracket)
5883 (t 'plain))))
5884 (when (and (memq style org-highlight-links)
5885 ;; Do not confuse plain links with tags.
5886 (not (and (eq style 'plain)
5887 (let ((face (get-text-property
5888 (max (1- start) (point-min)) 'face)))
5889 (if (consp face) (memq 'org-tag face)
5890 (eq 'org-tag face))))))
5891 (let* ((link-object (save-excursion
5892 (goto-char start)
5893 (save-match-data (org-element-link-parser))))
5894 (link (org-element-property :raw-link link-object))
5895 (type (org-element-property :type link-object))
5896 (path (org-element-property :path link-object))
5897 (properties ;for link's visible part
5898 (list
5899 'face (pcase (org-link-get-parameter type :face)
5900 ((and (pred functionp) face) (funcall face path))
5901 ((and (pred facep) face) face)
5902 ((and (pred consp) face) face) ;anonymous
5903 (_ 'org-link))
5904 'mouse-face (or (org-link-get-parameter type :mouse-face)
5905 'highlight)
5906 'keymap (or (org-link-get-parameter type :keymap)
5907 org-mouse-map)
5908 'help-echo (pcase (org-link-get-parameter type :help-echo)
5909 ((and (pred stringp) echo) echo)
5910 ((and (pred functionp) echo) echo)
5911 (_ (concat "LINK: " link)))
5912 'htmlize-link (pcase (org-link-get-parameter type
5913 :htmlize-link)
5914 ((and (pred functionp) f) (funcall f))
5915 (_ `(:uri ,link)))
5916 'font-lock-multiline t)))
5917 (org-remove-flyspell-overlays-in start end)
5918 (org-rear-nonsticky-at end)
5919 (if (not (eq 'bracket style))
5920 (add-text-properties start end properties)
5921 ;; Handle invisible parts in bracket links.
5922 (remove-text-properties start end '(invisible nil))
5923 (let ((hidden
5924 (append `(invisible
5925 ,(or (org-link-get-parameter type :display)
5926 'org-link))
5927 properties))
5928 (visible-start (or (match-beginning 4) (match-beginning 2)))
5929 (visible-end (or (match-end 4) (match-end 2))))
5930 (add-text-properties start visible-start hidden)
5931 (add-text-properties visible-start visible-end properties)
5932 (add-text-properties visible-end end hidden)
5933 (org-rear-nonsticky-at visible-start)
5934 (org-rear-nonsticky-at visible-end)))
5935 (let ((f (org-link-get-parameter type :activate-func)))
5936 (when (functionp f)
5937 (funcall f start end path (eq style 'bracket))))
5938 (throw :exit t))))) ;signal success
5939 nil))
5941 (defun org-activate-code (limit)
5942 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5943 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5944 (remove-text-properties (match-beginning 0) (match-end 0)
5945 '(display t invisible t intangible t))
5948 (defcustom org-src-fontify-natively t
5949 "When non-nil, fontify code in code blocks.
5950 See also the `org-block' face."
5951 :type 'boolean
5952 :version "26.1"
5953 :package-version '(Org . "8.3")
5954 :group 'org-appearance
5955 :group 'org-babel)
5957 (defcustom org-allow-promoting-top-level-subtree nil
5958 "When non-nil, allow promoting a top level subtree.
5959 The leading star of the top level headline will be replaced
5960 by a #."
5961 :type 'boolean
5962 :version "24.1"
5963 :group 'org-appearance)
5965 (defun org-fontify-meta-lines-and-blocks (limit)
5966 (condition-case nil
5967 (org-fontify-meta-lines-and-blocks-1 limit)
5968 (error (message "Org mode fontification error in %S at %d"
5969 (current-buffer)
5970 (line-number-at-pos)))))
5972 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5973 "Fontify #+ lines and blocks."
5974 (let ((case-fold-search t))
5975 (when (re-search-forward
5976 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5977 limit t)
5978 (let ((beg (match-beginning 0))
5979 (block-start (match-end 0))
5980 (block-end nil)
5981 (lang (match-string 7))
5982 (beg1 (line-beginning-position 2))
5983 (dc1 (downcase (match-string 2)))
5984 (dc3 (downcase (match-string 3)))
5985 end end1 quoting block-type)
5986 (cond
5987 ((and (match-end 4) (equal dc3 "+begin"))
5988 ;; Truly a block
5989 (setq block-type (downcase (match-string 5))
5990 quoting (member block-type org-protecting-blocks))
5991 (when (re-search-forward
5992 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5993 nil t) ;; on purpose, we look further than LIMIT
5994 (setq end (min (point-max) (match-end 0))
5995 end1 (min (point-max) (1- (match-beginning 0))))
5996 (setq block-end (match-beginning 0))
5997 (when quoting
5998 (org-remove-flyspell-overlays-in beg1 end1)
5999 (remove-text-properties beg end
6000 '(display t invisible t intangible t)))
6001 (add-text-properties
6002 beg end '(font-lock-fontified t font-lock-multiline t))
6003 (add-text-properties beg beg1 '(face org-meta-line))
6004 (org-remove-flyspell-overlays-in beg beg1)
6005 (add-text-properties ; For end_src
6006 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6007 (org-remove-flyspell-overlays-in end1 end)
6008 (cond
6009 ((and lang (not (string= lang "")) org-src-fontify-natively)
6010 (org-src-font-lock-fontify-block lang block-start block-end)
6011 (add-text-properties beg1 block-end '(src-block t)))
6012 (quoting
6013 (add-text-properties beg1 (min (point-max) (1+ end1))
6014 (list 'face
6015 (list :inherit
6016 (let ((face-name
6017 (intern (format "org-block-%s" lang))))
6018 (append (and (facep face-name) (list face-name))
6019 '(org-block))))))) ; end of source block
6020 ((not org-fontify-quote-and-verse-blocks))
6021 ((string= block-type "quote")
6022 (add-face-text-property
6023 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6024 ((string= block-type "verse")
6025 (add-face-text-property
6026 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6027 (add-text-properties beg beg1 '(face org-block-begin-line))
6028 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6029 '(face org-block-end-line))
6031 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6032 (org-remove-flyspell-overlays-in
6033 (match-beginning 0)
6034 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6035 (add-text-properties
6036 beg (match-end 3)
6037 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6038 '(font-lock-fontified t invisible t)
6039 '(font-lock-fontified t face org-document-info-keyword)))
6040 (add-text-properties
6041 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6042 (if (string-equal dc1 "+title:")
6043 '(font-lock-fontified t face org-document-title)
6044 '(font-lock-fontified t face org-document-info))))
6045 ((string-prefix-p "+caption" dc1)
6046 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6047 (remove-text-properties (match-beginning 0) (match-end 0)
6048 '(display t invisible t intangible t))
6049 ;; Handle short captions.
6050 (save-excursion
6051 (beginning-of-line)
6052 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6053 (add-text-properties (line-beginning-position) (match-end 1)
6054 '(font-lock-fontified t face org-meta-line))
6055 (add-text-properties (match-end 0) (line-end-position)
6056 '(font-lock-fontified t face org-block))
6058 ((member dc3 '(" " ""))
6059 (org-remove-flyspell-overlays-in beg (match-end 0))
6060 (add-text-properties
6061 beg (match-end 0)
6062 '(font-lock-fontified t face font-lock-comment-face)))
6063 (t ;; just any other in-buffer setting, but not indented
6064 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6065 (remove-text-properties (match-beginning 0) (match-end 0)
6066 '(display t invisible t intangible t))
6067 (add-text-properties beg (match-end 0)
6068 '(font-lock-fontified t face org-meta-line))
6069 t))))))
6071 (defun org-fontify-drawers (limit)
6072 "Fontify drawers."
6073 (when (re-search-forward org-drawer-regexp limit t)
6074 (add-text-properties
6075 (match-beginning 0) (match-end 0)
6076 '(font-lock-fontified t face org-special-keyword))
6077 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6080 (defun org-fontify-macros (limit)
6081 "Fontify macros."
6082 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6083 (let ((begin (match-beginning 0))
6084 (opening-end (match-beginning 1)))
6085 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6086 (match-string 1))
6087 (let ((end (match-end 1))
6088 (closing-start (match-beginning 1)))
6089 (add-text-properties
6090 begin end
6091 '(font-lock-multiline t font-lock-fontified t face org-macro))
6092 (org-remove-flyspell-overlays-in begin end)
6093 (when org-hide-macro-markers
6094 (add-text-properties begin opening-end '(invisible t))
6095 (add-text-properties closing-start end '(invisible t)))
6096 t)))))
6098 (defun org-activate-footnote-links (limit)
6099 "Add text properties for footnotes."
6100 (let ((fn (org-footnote-next-reference-or-definition limit)))
6101 (when fn
6102 (let* ((beg (nth 1 fn))
6103 (end (nth 2 fn))
6104 (label (car fn))
6105 (referencep (/= (line-beginning-position) beg)))
6106 (when (and referencep (nth 3 fn))
6107 (save-excursion
6108 (goto-char beg)
6109 (search-forward (or label "fn:"))
6110 (org-remove-flyspell-overlays-in beg (match-end 0))))
6111 (add-text-properties beg end
6112 (list 'mouse-face 'highlight
6113 'keymap org-mouse-map
6114 'help-echo
6115 (if referencep "Footnote reference"
6116 "Footnote definition")
6117 'font-lock-fontified t
6118 'font-lock-multiline t
6119 'face 'org-footnote))))))
6121 (defun org-activate-dates (limit)
6122 "Add text properties for dates."
6123 (when (and (re-search-forward org-tsr-regexp-both limit t)
6124 (not (equal (char-before (match-beginning 0)) 91)))
6125 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6126 (add-text-properties (match-beginning 0) (match-end 0)
6127 (list 'mouse-face 'highlight
6128 'keymap org-mouse-map))
6129 (org-rear-nonsticky-at (match-end 0))
6130 (when org-display-custom-times
6131 ;; If it's a date range, activate custom time for second date.
6132 (when (match-end 3)
6133 (org-display-custom-time (match-beginning 3) (match-end 3)))
6134 (org-display-custom-time (match-beginning 1) (match-end 1)))
6137 (defvar-local org-target-link-regexp nil
6138 "Regular expression matching radio targets in plain text.")
6140 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6141 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6142 border border border))
6143 "Regular expression matching a link target.")
6145 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6146 "Regular expression matching a radio target.")
6148 (defconst org-any-target-regexp
6149 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6150 "Regular expression matching any target.")
6152 (defun org-activate-target-links (limit)
6153 "Add text properties for target matches."
6154 (when org-target-link-regexp
6155 (let ((case-fold-search t))
6156 (when (re-search-forward org-target-link-regexp limit t)
6157 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6158 (add-text-properties (match-beginning 1) (match-end 1)
6159 (list 'mouse-face 'highlight
6160 'keymap org-mouse-map
6161 'help-echo "Radio target link"
6162 'org-linked-text t))
6163 (org-rear-nonsticky-at (match-end 1))
6164 t))))
6166 (defun org-update-radio-target-regexp ()
6167 "Find all radio targets in this file and update the regular expression.
6168 Also refresh fontification if needed."
6169 (interactive)
6170 (let ((old-regexp org-target-link-regexp)
6171 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6172 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6173 (targets
6174 (org-with-wide-buffer
6175 (goto-char (point-min))
6176 (let (rtn)
6177 (while (re-search-forward org-radio-target-regexp nil t)
6178 ;; Make sure point is really within the object.
6179 (backward-char)
6180 (let ((obj (org-element-context)))
6181 (when (eq (org-element-type obj) 'radio-target)
6182 (cl-pushnew (org-element-property :value obj) rtn
6183 :test #'equal))))
6184 rtn))))
6185 (setq org-target-link-regexp
6186 (and targets
6187 (concat before-re
6188 (mapconcat
6189 (lambda (x)
6190 (replace-regexp-in-string
6191 " +" "\\s-+" (regexp-quote x) t t))
6192 targets
6193 "\\|")
6194 after-re)))
6195 (unless (equal old-regexp org-target-link-regexp)
6196 ;; Clean-up cache.
6197 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6198 ((not org-target-link-regexp) old-regexp)
6200 (concat before-re
6201 (mapconcat
6202 (lambda (re)
6203 (substring re (length before-re)
6204 (- (length after-re))))
6205 (list old-regexp org-target-link-regexp)
6206 "\\|")
6207 after-re)))))
6208 (org-with-wide-buffer
6209 (goto-char (point-min))
6210 (while (re-search-forward regexp nil t)
6211 (org-element-cache-refresh (match-beginning 1)))))
6212 ;; Re fontify buffer.
6213 (when (memq 'radio org-highlight-links)
6214 (org-restart-font-lock)))))
6216 (defvar org-latex-and-related-regexp nil
6217 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6219 (defun org-compute-latex-and-related-regexp ()
6220 "Compute regular expression for LaTeX, entities and sub/superscript.
6221 Result depends on variable `org-highlight-latex-and-related'."
6222 (setq-local
6223 org-latex-and-related-regexp
6224 (let* ((re-sub
6225 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6226 ((eq org-use-sub-superscripts '{})
6227 (list org-match-substring-with-braces-regexp))
6228 (org-use-sub-superscripts (list org-match-substring-regexp))))
6229 (re-latex
6230 (when (memq 'latex org-highlight-latex-and-related)
6231 (let ((matchers (plist-get org-format-latex-options :matchers)))
6232 (delq nil
6233 (mapcar (lambda (x)
6234 (and (member (car x) matchers) (nth 1 x)))
6235 org-latex-regexps)))))
6236 (re-entities
6237 (when (memq 'entities org-highlight-latex-and-related)
6238 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6239 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6241 (defun org-do-latex-and-related (limit)
6242 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6243 LIMIT bounds the search for syntax to highlight. Stop at first
6244 highlighted object, if any. Return t if some highlighting was
6245 done, nil otherwise."
6246 (when (org-string-nw-p org-latex-and-related-regexp)
6247 (catch 'found
6248 (while (re-search-forward org-latex-and-related-regexp limit t)
6249 (unless
6250 (cl-some
6251 (lambda (f)
6252 (memq f '(org-code org-verbatim underline org-special-keyword)))
6253 (save-excursion
6254 (goto-char (1+ (match-beginning 0)))
6255 (face-at-point nil t)))
6256 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6257 '(?_ ?^))
6259 0)))
6260 (font-lock-prepend-text-property
6261 (+ offset (match-beginning 0)) (match-end 0)
6262 'face 'org-latex-and-related)
6263 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6264 '(font-lock-multiline t)))
6265 (throw 'found t)))
6266 nil)))
6268 (defun org-restart-font-lock ()
6269 "Restart `font-lock-mode', to force refontification."
6270 (when (and (boundp 'font-lock-mode) font-lock-mode)
6271 (font-lock-mode -1)
6272 (font-lock-mode 1)))
6274 (defun org-activate-tags (limit)
6275 (when (re-search-forward org-tag-line-re limit t)
6276 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6277 (add-text-properties (match-beginning 1) (match-end 1)
6278 (list 'mouse-face 'highlight
6279 'keymap org-mouse-map))
6280 (org-rear-nonsticky-at (match-end 1))
6283 (defun org-outline-level ()
6284 "Compute the outline level of the heading at point.
6286 If this is called at a normal headline, the level is the number
6287 of stars. Use `org-reduced-level' to remove the effect of
6288 `org-odd-levels'. Unlike to `org-current-level', this function
6289 takes into consideration inlinetasks."
6290 (org-with-wide-buffer
6291 (end-of-line)
6292 (if (re-search-backward org-outline-regexp-bol nil t)
6293 (1- (- (match-end 0) (match-beginning 0)))
6294 0)))
6296 (defvar org-font-lock-keywords nil)
6298 (defsubst org-re-property (property &optional literal allow-null value)
6299 "Return a regexp matching a PROPERTY line.
6301 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6302 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6303 non-nil, match properties even without a value.
6305 Match group 3 is set to the value when it exists. If there is no
6306 value and ALLOW-NULL is non-nil, it is set to the empty string.
6308 With optional argument VALUE, match only property lines with
6309 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6310 unless LITERAL is non-nil."
6311 (concat
6312 "^\\(?4:[ \t]*\\)"
6313 (format "\\(?1::\\(?2:%s\\):\\)"
6314 (if literal property (regexp-quote property)))
6315 (cond (value
6316 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6317 (if literal value (regexp-quote value))))
6318 (allow-null
6319 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6321 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6323 (defconst org-property-re
6324 (org-re-property "\\S-+" 'literal t)
6325 "Regular expression matching a property line.
6326 There are four matching groups:
6327 1: :PROPKEY: including the leading and trailing colon,
6328 2: PROPKEY without the leading and trailing colon,
6329 3: PROPVAL without leading or trailing spaces,
6330 4: the indentation of the current line,
6331 5: trailing whitespace.")
6333 (defvar org-font-lock-hook nil
6334 "Functions to be called for special font lock stuff.")
6336 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6338 (defvar org-font-lock-set-keywords-hook nil
6339 "Functions that can manipulate `org-font-lock-extra-keywords'.
6340 This is called after `org-font-lock-extra-keywords' is defined, but before
6341 it is installed to be used by font lock. This can be useful if something
6342 needs to be inserted at a specific position in the font-lock sequence.")
6344 (defun org-font-lock-hook (limit)
6345 "Run `org-font-lock-hook' within LIMIT."
6346 (run-hook-with-args 'org-font-lock-hook limit))
6348 (defun org-set-font-lock-defaults ()
6349 "Set font lock defaults for the current buffer."
6350 (let* ((em org-fontify-emphasized-text)
6351 (lk org-highlight-links)
6352 (org-font-lock-extra-keywords
6353 (list
6354 ;; Call the hook
6355 '(org-font-lock-hook)
6356 ;; Headlines
6357 `(,(if org-fontify-whole-heading-line
6358 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6359 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6360 (1 (org-get-level-face 1))
6361 (2 (org-get-level-face 2))
6362 (3 (org-get-level-face 3)))
6363 ;; Table lines
6364 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6365 (1 'org-table t))
6366 ;; Table internals
6367 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6368 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6369 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6370 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6371 ;; Drawers
6372 '(org-fontify-drawers)
6373 ;; Properties
6374 (list org-property-re
6375 '(1 'org-special-keyword t)
6376 '(3 'org-property-value t))
6377 ;; Link related fontification.
6378 '(org-activate-links)
6379 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6380 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6381 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6382 (when (memq 'footnote lk) '(org-activate-footnote-links))
6383 ;; Targets.
6384 (list org-any-target-regexp '(0 'org-target t))
6385 ;; Diary sexps.
6386 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6387 ;; Macro
6388 '(org-fontify-macros)
6389 ;; TODO keyword
6390 (list (format org-heading-keyword-regexp-format
6391 org-todo-regexp)
6392 '(2 (org-get-todo-face 2) t))
6393 ;; DONE
6394 (if org-fontify-done-headline
6395 (list (format org-heading-keyword-regexp-format
6396 (concat
6397 "\\(?:"
6398 (mapconcat 'regexp-quote org-done-keywords "\\|")
6399 "\\)"))
6400 '(2 'org-headline-done t))
6401 nil)
6402 ;; Priorities
6403 '(org-font-lock-add-priority-faces)
6404 ;; Tags
6405 '(org-font-lock-add-tag-faces)
6406 ;; Tags groups
6407 (when (and org-group-tags org-tag-groups-alist)
6408 (list (concat org-outline-regexp-bol ".+\\(:"
6409 (regexp-opt (mapcar 'car org-tag-groups-alist))
6410 ":\\).*$")
6411 '(1 'org-tag-group prepend)))
6412 ;; Special keywords
6413 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6414 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6415 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6416 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6417 ;; Emphasis
6418 (when em '(org-do-emphasis-faces))
6419 ;; Checkboxes
6420 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6421 1 'org-checkbox prepend)
6422 (when (cdr (assq 'checkbox org-list-automatic-rules))
6423 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6424 (0 (org-get-checkbox-statistics-face) t)))
6425 ;; Description list items
6426 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6427 1 'org-list-dt prepend)
6428 ;; ARCHIVEd headings
6429 (list (concat
6430 org-outline-regexp-bol
6431 "\\(.*:" org-archive-tag ":.*\\)")
6432 '(1 'org-archived prepend))
6433 ;; Specials
6434 '(org-do-latex-and-related)
6435 '(org-fontify-entities)
6436 '(org-raise-scripts)
6437 ;; Code
6438 '(org-activate-code (1 'org-code t))
6439 ;; COMMENT
6440 (list (format
6441 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6442 org-todo-regexp
6443 org-comment-string)
6444 '(9 'org-special-keyword t))
6445 ;; Blocks and meta lines
6446 '(org-fontify-meta-lines-and-blocks))))
6447 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6448 (run-hooks 'org-font-lock-set-keywords-hook)
6449 ;; Now set the full font-lock-keywords
6450 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6451 (setq-local font-lock-defaults
6452 '(org-font-lock-keywords t nil nil backward-paragraph))
6453 (kill-local-variable 'font-lock-keywords)
6454 nil))
6456 (defun org-toggle-pretty-entities ()
6457 "Toggle the composition display of entities as UTF8 characters."
6458 (interactive)
6459 (setq-local org-pretty-entities (not org-pretty-entities))
6460 (org-restart-font-lock)
6461 (if org-pretty-entities
6462 (message "Entities are now displayed as UTF8 characters")
6463 (save-restriction
6464 (widen)
6465 (decompose-region (point-min) (point-max))
6466 (message "Entities are now displayed as plain text"))))
6468 (defvar-local org-custom-properties-overlays nil
6469 "List of overlays used for custom properties.")
6471 (defun org-toggle-custom-properties-visibility ()
6472 "Display or hide properties in `org-custom-properties'."
6473 (interactive)
6474 (if org-custom-properties-overlays
6475 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6476 (setq org-custom-properties-overlays nil))
6477 (when org-custom-properties
6478 (org-with-wide-buffer
6479 (goto-char (point-min))
6480 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6481 (while (re-search-forward regexp nil t)
6482 (let ((end (cdr (save-match-data (org-get-property-block)))))
6483 (when (and end (< (point) end))
6484 ;; Hide first custom property in current drawer.
6485 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6486 (overlay-put o 'invisible t)
6487 (overlay-put o 'org-custom-property t)
6488 (push o org-custom-properties-overlays))
6489 ;; Hide additional custom properties in the same drawer.
6490 (while (re-search-forward regexp end t)
6491 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6492 (overlay-put o 'invisible t)
6493 (overlay-put o 'org-custom-property t)
6494 (push o org-custom-properties-overlays)))))
6495 ;; Each entry is limited to a single property drawer.
6496 (outline-next-heading)))))))
6498 (defun org-fontify-entities (limit)
6499 "Find an entity to fontify."
6500 (let (ee)
6501 (when org-pretty-entities
6502 (catch 'match
6503 ;; "\_ "-family is left out on purpose. Only the first one,
6504 ;; i.e., "\_ ", could be fontified anyway, and it would be
6505 ;; confusing when adding a second white space character.
6506 (while (re-search-forward
6507 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6508 limit t)
6509 (when (and (not (org-at-comment-p))
6510 (setq ee (org-entity-get (match-string 1)))
6511 (= (length (nth 6 ee)) 1))
6512 (let* ((end (if (equal (match-string 2) "{}")
6513 (match-end 2)
6514 (match-end 1))))
6515 (add-text-properties
6516 (match-beginning 0) end
6517 (list 'font-lock-fontified t))
6518 (compose-region (match-beginning 0) end
6519 (nth 6 ee) nil)
6520 (backward-char 1)
6521 (throw 'match t))))
6522 nil))))
6524 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6525 "Fontify string S like in Org mode."
6526 (with-temp-buffer
6527 (insert s)
6528 (let ((org-odd-levels-only odd-levels))
6529 (org-mode)
6530 (org-font-lock-ensure)
6531 (buffer-string))))
6533 (defvar org-m nil)
6534 (defvar org-l nil)
6535 (defvar org-f nil)
6536 (defun org-get-level-face (n)
6537 "Get the right face for match N in font-lock matching of headlines."
6538 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6539 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6540 (if org-cycle-level-faces
6541 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6542 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6543 (cond
6544 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6545 ((eq n 2) org-f)
6546 (t (unless org-level-color-stars-only org-f))))
6548 (defun org-face-from-face-or-color (context inherit face-or-color)
6549 "Create a face list that inherits INHERIT, but sets the foreground color.
6550 When FACE-OR-COLOR is not a string, just return it."
6551 (if (stringp face-or-color)
6552 (list :inherit inherit
6553 (cdr (assoc context org-faces-easy-properties))
6554 face-or-color)
6555 face-or-color))
6557 (defun org-get-todo-face (kwd)
6558 "Get the right face for a TODO keyword KWD.
6559 If KWD is a number, get the corresponding match group."
6560 (when (numberp kwd) (setq kwd (match-string kwd)))
6561 (or (org-face-from-face-or-color
6562 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6563 (and (member kwd org-done-keywords) 'org-done)
6564 'org-todo))
6566 (defun org-get-priority-face (priority)
6567 "Get the right face for PRIORITY.
6568 PRIORITY is a character."
6569 (or (org-face-from-face-or-color
6570 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6571 'org-priority))
6573 (defun org-get-tag-face (tag)
6574 "Get the right face for TAG.
6575 If TAG is a number, get the corresponding match group."
6576 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6577 (or (org-face-from-face-or-color
6578 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6579 'org-tag)))
6581 (defun org-font-lock-add-priority-faces (limit)
6582 "Add the special priority faces."
6583 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6584 (add-text-properties
6585 (match-beginning 1) (match-end 1)
6586 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6587 'font-lock-fontified t))))
6589 (defun org-font-lock-add-tag-faces (limit)
6590 "Add the special tag faces."
6591 (when (and org-tag-faces org-tags-special-faces-re)
6592 (while (re-search-forward org-tags-special-faces-re limit t)
6593 (add-text-properties (match-beginning 1) (match-end 1)
6594 (list 'face (org-get-tag-face 1)
6595 'font-lock-fontified t))
6596 (backward-char 1))))
6598 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6599 "Remove fontification and activation overlays from links."
6600 (font-lock-default-unfontify-region beg end)
6601 (let* ((buffer-undo-list t)
6602 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6603 (inhibit-modification-hooks t)
6604 deactivate-mark buffer-file-name buffer-file-truename)
6605 (decompose-region beg end)
6606 (remove-text-properties beg end
6607 '(mouse-face t keymap t org-linked-text t
6608 invisible t intangible t
6609 org-emphasis t))
6610 (org-remove-font-lock-display-properties beg end)))
6612 (defconst org-script-display '(((raise -0.3) (height 0.7))
6613 ((raise 0.3) (height 0.7))
6614 ((raise -0.5))
6615 ((raise 0.5)))
6616 "Display properties for showing superscripts and subscripts.")
6618 (defun org-remove-font-lock-display-properties (beg end)
6619 "Remove specific display properties that have been added by font lock.
6620 The will remove the raise properties that are used to show superscripts
6621 and subscripts."
6622 (let (next prop)
6623 (while (< beg end)
6624 (setq next (next-single-property-change beg 'display nil end)
6625 prop (get-text-property beg 'display))
6626 (when (member prop org-script-display)
6627 (put-text-property beg next 'display nil))
6628 (setq beg next))))
6630 (defun org-raise-scripts (limit)
6631 "Add raise properties to sub/superscripts."
6632 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6633 (re-search-forward
6634 (if (eq org-use-sub-superscripts t)
6635 org-match-substring-regexp
6636 org-match-substring-with-braces-regexp)
6637 limit t))
6638 (let* ((pos (point)) table-p comment-p
6639 (mpos (match-beginning 3))
6640 (emph-p (get-text-property mpos 'org-emphasis))
6641 (link-p (get-text-property mpos 'mouse-face))
6642 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6643 (goto-char (point-at-bol))
6644 (setq table-p (looking-at-p org-table-dataline-regexp)
6645 comment-p (looking-at-p "^[ \t]*#[ +]"))
6646 (goto-char pos)
6647 ;; Handle a_b^c
6648 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6649 (unless (or comment-p emph-p link-p keyw-p)
6650 (put-text-property (match-beginning 3) (match-end 0)
6651 'display
6652 (if (equal (char-after (match-beginning 2)) ?^)
6653 (nth (if table-p 3 1) org-script-display)
6654 (nth (if table-p 2 0) org-script-display)))
6655 (add-text-properties (match-beginning 2) (match-end 2)
6656 (list 'invisible t))
6657 (when (and (eq (char-after (match-beginning 3)) ?{)
6658 (eq (char-before (match-end 3)) ?}))
6659 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6660 (list 'invisible t))
6661 (add-text-properties (1- (match-end 3)) (match-end 3)
6662 (list 'invisible t))))
6663 t)))
6665 (defun org-remove-empty-overlays-at (pos)
6666 "Remove outline overlays that do not contain non-white stuff."
6667 (dolist (o (overlays-at pos))
6668 (and (eq 'outline (overlay-get o 'invisible))
6669 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6670 (overlay-end o))))
6671 (delete-overlay o))))
6673 (defun org-show-empty-lines-in-parent ()
6674 "Move to the parent and re-show empty lines before visible headlines."
6675 (save-excursion
6676 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6677 (org-cycle-show-empty-lines context))))
6679 (defun org-files-list ()
6680 "Return `org-agenda-files' list, plus all open Org files.
6681 This is useful for operations that need to scan all of a user's
6682 open and agenda-wise Org files."
6683 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6684 (dolist (buf (buffer-list))
6685 (with-current-buffer buf
6686 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6687 (cl-pushnew (expand-file-name (buffer-file-name)) files
6688 :test #'equal))))
6689 files))
6691 (defsubst org-entry-beginning-position ()
6692 "Return the beginning position of the current entry."
6693 (save-excursion (org-back-to-heading t) (point)))
6695 (defsubst org-entry-end-position ()
6696 "Return the end position of the current entry."
6697 (save-excursion (outline-next-heading) (point)))
6699 (defun org-subtree-end-visible-p ()
6700 "Is the end of the current subtree visible?"
6701 (pos-visible-in-window-p
6702 (save-excursion (org-end-of-subtree t) (point))))
6704 (defun org-first-headline-recenter ()
6705 "Move cursor to the first headline and recenter the headline."
6706 (let ((window (get-buffer-window)))
6707 (when window
6708 (goto-char (point-min))
6709 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6710 (set-window-start window (line-beginning-position))))))
6713 ;;; Visibility (headlines, blocks, drawers)
6715 ;;;; Headlines visibility
6717 (defun org-show-entry ()
6718 "Show the body directly following this heading.
6719 Show the heading too, if it is currently invisible."
6720 (interactive)
6721 (save-excursion
6722 (ignore-errors
6723 (org-back-to-heading t)
6724 (org-flag-region
6725 (line-end-position 0)
6726 (save-excursion
6727 (if (re-search-forward
6728 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6729 (match-beginning 1)
6730 (point-max)))
6732 'outline))))
6734 (defun org-show-children (&optional level)
6735 "Show all direct subheadings of this heading.
6736 Prefix arg LEVEL is how many levels below the current level
6737 should be shown. Default is enough to cause the following
6738 heading to appear."
6739 (interactive "p")
6740 (save-excursion
6741 (org-back-to-heading t)
6742 (let* ((current-level (funcall outline-level))
6743 (max-level (org-get-valid-level
6744 current-level
6745 (if level (prefix-numeric-value level) 1)))
6746 (end (save-excursion (org-end-of-subtree t t)))
6747 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6748 (past-first-child nil)
6749 ;; Make sure to skip inlinetasks.
6750 (re (format regexp-fmt
6751 current-level
6752 (cond
6753 ((not (featurep 'org-inlinetask)) "")
6754 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6756 (t (1- org-inlinetask-min-level))))))
6757 ;; Display parent heading.
6758 (org-flag-heading nil)
6759 (forward-line)
6760 ;; Display children. First child may be deeper than expected
6761 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6762 ;; MAX-LEVEL accordingly.
6763 (while (re-search-forward re end t)
6764 (unless past-first-child
6765 (setq re (format regexp-fmt
6766 current-level
6767 (max (funcall outline-level) max-level)))
6768 (setq past-first-child t))
6769 (org-flag-heading nil)))))
6771 (defun org-show-subtree ()
6772 "Show everything after this heading at deeper levels."
6773 (interactive)
6774 (org-flag-region
6775 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6777 ;;;; Blocks visibility
6779 (defun org-hide-block-toggle-maybe ()
6780 "Toggle visibility of block at point.
6781 Unlike to `org-hide-block-toggle', this function does not throw
6782 an error. Return a non-nil value when toggling is successful."
6783 (interactive)
6784 (ignore-errors (org-hide-block-toggle)))
6786 (defun org-hide-block-toggle (&optional force)
6787 "Toggle the visibility of the current block.
6788 When optional argument FORCE is `off', make block visible. If it
6789 is non-nil, hide it unconditionally. Throw an error when not at
6790 a block. Return a non-nil value when toggling is successful."
6791 (interactive)
6792 (let ((element (org-element-at-point)))
6793 (unless (memq (org-element-type element)
6794 '(center-block comment-block dynamic-block example-block
6795 export-block quote-block special-block
6796 src-block verse-block))
6797 (user-error "Not at a block"))
6798 (let* ((post (org-element-property :post-affiliated element))
6799 (start (save-excursion
6800 (goto-char post)
6801 (line-end-position)))
6802 (end (save-excursion
6803 (goto-char (org-element-property :end element))
6804 (skip-chars-backward " \t\n")
6805 (line-end-position))))
6806 ;; Do nothing when not before or at the block opening line or at
6807 ;; the block closing line.
6808 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6809 (cond ((eq force 'off)
6810 (org-flag-region start end nil 'org-hide-block))
6811 (force
6812 (org-flag-region start end t 'org-hide-block))
6813 ((eq (get-char-property start 'invisible) 'org-hide-block)
6814 (org-flag-region start end nil 'org-hide-block))
6816 (org-flag-region start end t 'org-hide-block)))
6817 ;; When the block is hidden away, make sure point is left in
6818 ;; a visible part of the buffer.
6819 (when (invisible-p (max (1- (point)) (point-min)))
6820 (goto-char post))
6821 ;; Signal success.
6822 t))))
6824 (defun org-hide-block-toggle-all ()
6825 "Toggle the visibility of all blocks in the current buffer."
6826 (org-block-map 'org-hide-block-toggle))
6828 (defun org-hide-block-all ()
6829 "Fold all blocks in the current buffer."
6830 (interactive)
6831 (org-show-all '(blocks))
6832 (org-block-map 'org-hide-block-toggle-maybe))
6834 ;;;; Drawers visibility
6836 (defun org-cycle-hide-drawers (state &optional exceptions)
6837 "Re-hide all drawers after a visibility state change.
6838 STATE should be one of the symbols listed in the docstring of
6839 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6840 a list of strings specifying which drawers should not be hidden."
6841 (when (and (derived-mode-p 'org-mode)
6842 (not (memq state '(overview folded contents))))
6843 (save-excursion
6844 (let* ((globalp (eq state 'all))
6845 (beg (if globalp (point-min) (point)))
6846 (end (if globalp (point-max)
6847 (if (eq state 'children)
6848 (save-excursion (outline-next-heading) (point))
6849 (org-end-of-subtree t)))))
6850 (goto-char beg)
6851 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6852 (unless (member-ignore-case (match-string 1) exceptions)
6853 (let ((drawer (org-element-at-point)))
6854 (when (memq (org-element-type drawer) '(drawer property-drawer))
6855 (org-flag-drawer t drawer)
6856 ;; Make sure to skip drawer entirely or we might flag
6857 ;; it another time when matching its ending line with
6858 ;; `org-drawer-regexp'.
6859 (goto-char (org-element-property :end drawer))))))))))
6861 (defun org-flag-drawer (flag &optional element)
6862 "When FLAG is non-nil, hide the drawer we are at.
6863 Otherwise make it visible. When optional argument ELEMENT is
6864 a parsed drawer, as returned by `org-element-at-point', hide or
6865 show that drawer instead."
6866 (let ((drawer (or element
6867 (and (save-excursion
6868 (beginning-of-line)
6869 (looking-at-p org-drawer-regexp))
6870 (org-element-at-point)))))
6871 (when (memq (org-element-type drawer) '(drawer property-drawer))
6872 (let ((post (org-element-property :post-affiliated drawer)))
6873 (org-flag-region
6874 (save-excursion (goto-char post) (line-end-position))
6875 (save-excursion (goto-char (org-element-property :end drawer))
6876 (skip-chars-backward " \t\n")
6877 (line-end-position))
6878 flag 'org-hide-drawer)
6879 ;; When the drawer is hidden away, make sure point lies in
6880 ;; a visible part of the buffer.
6881 (when (invisible-p (max (1- (point)) (point-min)))
6882 (goto-char post))))))
6884 ;;;; Visibility cycling
6886 (defvar-local org-cycle-global-status nil)
6887 (put 'org-cycle-global-status 'org-state t)
6888 (defvar-local org-cycle-subtree-status nil)
6889 (put 'org-cycle-subtree-status 'org-state t)
6891 (defun org-show-all (&optional types)
6892 "Show all contents in the visible part of the buffer.
6893 By default, the function expands headings, blocks and drawers.
6894 When optional argument TYPE is a list of symbols among `blocks',
6895 `drawers' and `headings', to only expand one specific type."
6896 (dolist (type (or types '(blocks drawers headings)))
6897 (org-flag-region (point-min) (point-max) nil
6898 (pcase type
6899 (`blocks 'org-hide-block)
6900 (`drawers 'org-hide-drawer)
6901 (`headings 'outline)
6902 (_ (error "Invalid type: %S" type))))))
6904 ;;;###autoload
6905 (defun org-cycle (&optional arg)
6906 "TAB-action and visibility cycling for Org mode.
6908 This is the command invoked in Org mode by the `TAB' key. Its main
6909 purpose is outline visibility cycling, but it also invokes other actions
6910 in special contexts.
6912 When this function is called with a `\\[universal-argument]' prefix, rotate \
6913 the entire
6914 buffer through 3 states (global cycling)
6915 1. OVERVIEW: Show only top-level headlines.
6916 2. CONTENTS: Show all headlines of all levels, but no body text.
6917 3. SHOW ALL: Show everything.
6919 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6920 switch to the startup visibility,
6921 determined by the variable `org-startup-folded', and by any VISIBILITY
6922 properties in the buffer.
6924 With a `\\[universal-argument] \\[universal-argument] \
6925 \\[universal-argument]' prefix argument, show the entire buffer, including
6926 any drawers.
6928 When inside a table, re-align the table and move to the next field.
6930 When point is at the beginning of a headline, rotate the subtree started
6931 by this line through 3 different states (local cycling)
6932 1. FOLDED: Only the main headline is shown.
6933 2. CHILDREN: The main headline and the direct children are shown.
6934 From this state, you can move to one of the children
6935 and zoom in further.
6936 3. SUBTREE: Show the entire subtree, including body text.
6937 If there is no subtree, switch directly from CHILDREN to FOLDED.
6939 When point is at the beginning of an empty headline and the variable
6940 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6941 of the headline by demoting and promoting it to likely levels. This
6942 speeds up creation document structure by pressing `TAB' once or several
6943 times right after creating a new headline.
6945 When there is a numeric prefix, go up to a heading with level ARG, do
6946 a `show-subtree' and return to the previous cursor position. If ARG
6947 is negative, go up that many levels.
6949 When point is not at the beginning of a headline, execute the global
6950 binding for `TAB', which is re-indenting the line. See the option
6951 `org-cycle-emulate-tab' for details.
6953 As a special case, if point is at the beginning of the buffer and there is
6954 no headline in line 1, this function will act as if called with prefix arg
6955 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6956 prefix arg, but only
6957 if the variable `org-cycle-global-at-bob' is t."
6958 (interactive "P")
6959 (org-load-modules-maybe)
6960 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6961 (and org-cycle-level-after-item/entry-creation
6962 (or (org-cycle-level)
6963 (org-cycle-item-indentation))))
6964 (let* ((limit-level
6965 (or org-cycle-max-level
6966 (and (boundp 'org-inlinetask-min-level)
6967 org-inlinetask-min-level
6968 (1- org-inlinetask-min-level))))
6969 (nstars (and limit-level
6970 (if org-odd-levels-only
6971 (and limit-level (1- (* limit-level 2)))
6972 limit-level)))
6973 (org-outline-regexp
6974 (if (not (derived-mode-p 'org-mode))
6975 outline-regexp
6976 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6977 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6978 (not (looking-at org-outline-regexp))))
6979 (org-cycle-hook
6980 (if bob-special
6981 (delq 'org-optimize-window-after-visibility-change
6982 (copy-sequence org-cycle-hook))
6983 org-cycle-hook))
6984 (pos (point)))
6986 (cond
6988 ((equal arg '(16))
6989 (setq last-command 'dummy)
6990 (org-set-startup-visibility)
6991 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6993 ((equal arg '(64))
6994 (org-show-all)
6995 (org-unlogged-message "Entire buffer visible, including drawers"))
6997 ((equal arg '(4)) (org-cycle-internal-global))
6999 ;; Try hiding block at point.
7000 ((org-hide-block-toggle-maybe))
7002 ;; Try cdlatex TAB completion
7003 ((org-try-cdlatex-tab))
7005 ;; Table: enter it or move to the next field.
7006 ((org-at-table-p 'any)
7007 (if (org-at-table.el-p)
7008 (message "%s" (substitute-command-keys "\\<org-mode-map>\
7009 Use `\\[org-edit-special]' to edit table.el tables"))
7010 (if arg (org-table-edit-field t)
7011 (org-table-justify-field-maybe)
7012 (call-interactively 'org-table-next-field))))
7014 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
7016 ;; Global cycling: delegate to `org-cycle-internal-global'.
7017 (bob-special (org-cycle-internal-global))
7019 ;; Drawers: delegate to `org-flag-drawer'.
7020 ((save-excursion
7021 (beginning-of-line 1)
7022 (looking-at org-drawer-regexp))
7023 (org-flag-drawer ; toggle block visibility
7024 (not (get-char-property (match-end 0) 'invisible))))
7026 ;; Show-subtree, ARG levels up from here.
7027 ((integerp arg)
7028 (save-excursion
7029 (org-back-to-heading)
7030 (outline-up-heading (if (< arg 0) (- arg)
7031 (- (funcall outline-level) arg)))
7032 (org-show-subtree)))
7034 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
7035 ((and (featurep 'org-inlinetask)
7036 (org-inlinetask-at-task-p)
7037 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7038 (org-inlinetask-toggle-visibility))
7040 ;; At an item/headline: delegate to `org-cycle-internal-local'.
7041 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
7042 (save-excursion (move-beginning-of-line 1)
7043 (looking-at org-outline-regexp)))
7044 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7045 (org-cycle-internal-local))
7047 ;; From there: TAB emulation and template completion.
7048 (buffer-read-only (org-back-to-heading))
7050 ((run-hook-with-args-until-success
7051 'org-tab-after-check-for-cycling-hook))
7053 ((run-hook-with-args-until-success
7054 'org-tab-before-tab-emulation-hook))
7056 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7057 (or (not (bolp))
7058 (not (looking-at org-outline-regexp))))
7059 (call-interactively (global-key-binding "\t")))
7061 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7062 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7063 (or (and (eq org-cycle-emulate-tab 'white)
7064 (= (match-end 0) (point-at-eol)))
7065 (and (eq org-cycle-emulate-tab 'whitestart)
7066 (>= (match-end 0) pos))))
7068 (eq org-cycle-emulate-tab t))
7069 (call-interactively (global-key-binding "\t")))
7071 (t (save-excursion
7072 (org-back-to-heading)
7073 (org-cycle)))))))
7075 (defun org-cycle-internal-global ()
7076 "Do the global cycling action."
7077 ;; Hack to avoid display of messages for .org attachments in Gnus
7078 (let ((ga (string-match "\\*fontification" (buffer-name))))
7079 (cond
7080 ((and (eq last-command this-command)
7081 (eq org-cycle-global-status 'overview))
7082 ;; We just created the overview - now do table of contents
7083 ;; This can be slow in very large buffers, so indicate action
7084 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7085 (unless ga (org-unlogged-message "CONTENTS..."))
7086 (org-content)
7087 (unless ga (org-unlogged-message "CONTENTS...done"))
7088 (setq org-cycle-global-status 'contents)
7089 (run-hook-with-args 'org-cycle-hook 'contents))
7091 ((and (eq last-command this-command)
7092 (eq org-cycle-global-status 'contents))
7093 ;; We just showed the table of contents - now show everything
7094 (run-hook-with-args 'org-pre-cycle-hook 'all)
7095 (org-show-all '(headings blocks))
7096 (unless ga (org-unlogged-message "SHOW ALL"))
7097 (setq org-cycle-global-status 'all)
7098 (run-hook-with-args 'org-cycle-hook 'all))
7101 ;; Default action: go to overview
7102 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7103 (org-overview)
7104 (unless ga (org-unlogged-message "OVERVIEW"))
7105 (setq org-cycle-global-status 'overview)
7106 (run-hook-with-args 'org-cycle-hook 'overview)))))
7108 (defvar org-called-with-limited-levels nil
7109 "Non-nil when `org-with-limited-levels' is currently active.")
7111 (defun org-cycle-internal-local ()
7112 "Do the local cycling action."
7113 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7114 ;; First, determine end of headline (EOH), end of subtree or item
7115 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7116 (save-excursion
7117 (if (org-at-item-p)
7118 (progn
7119 (beginning-of-line)
7120 (setq struct (org-list-struct))
7121 (setq eoh (point-at-eol))
7122 (setq eos (org-list-get-item-end-before-blank (point) struct))
7123 (setq has-children (org-list-has-child-p (point) struct)))
7124 (org-back-to-heading)
7125 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7126 (setq eos (save-excursion (org-end-of-subtree t t)
7127 (when (bolp) (backward-char)) (point)))
7128 (setq has-children
7129 (or (save-excursion
7130 (let ((level (funcall outline-level)))
7131 (outline-next-heading)
7132 (and (org-at-heading-p t)
7133 (> (funcall outline-level) level))))
7134 (save-excursion
7135 (org-list-search-forward (org-item-beginning-re) eos t)))))
7136 ;; Determine end invisible part of buffer (EOL)
7137 (beginning-of-line 2)
7138 (while (and (not (eobp)) ;This is like `next-line'.
7139 (get-char-property (1- (point)) 'invisible))
7140 (goto-char (next-single-char-property-change (point) 'invisible))
7141 (and (eolp) (beginning-of-line 2)))
7142 (setq eol (point)))
7143 ;; Find out what to do next and set `this-command'
7144 (cond
7145 ((= eos eoh)
7146 ;; Nothing is hidden behind this heading
7147 (unless (org-before-first-heading-p)
7148 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7149 (org-unlogged-message "EMPTY ENTRY")
7150 (setq org-cycle-subtree-status nil)
7151 (save-excursion
7152 (goto-char eos)
7153 (outline-next-heading)
7154 (when (org-invisible-p) (org-flag-heading nil))))
7155 ((and (or (>= eol eos)
7156 (not (string-match "\\S-" (buffer-substring eol eos))))
7157 (or has-children
7158 (not (setq children-skipped
7159 org-cycle-skip-children-state-if-no-children))))
7160 ;; Entire subtree is hidden in one line: children view
7161 (unless (org-before-first-heading-p)
7162 (run-hook-with-args 'org-pre-cycle-hook 'children))
7163 (if (org-at-item-p)
7164 (org-list-set-item-visibility (point-at-bol) struct 'children)
7165 (org-show-entry)
7166 (org-with-limited-levels (org-show-children))
7167 (org-show-set-visibility 'canonical)
7168 ;; Fold every list in subtree to top-level items.
7169 (when (eq org-cycle-include-plain-lists 'integrate)
7170 (save-excursion
7171 (org-back-to-heading)
7172 (while (org-list-search-forward (org-item-beginning-re) eos t)
7173 (beginning-of-line 1)
7174 (let* ((struct (org-list-struct))
7175 (prevs (org-list-prevs-alist struct))
7176 (end (org-list-get-bottom-point struct)))
7177 (dolist (e (org-list-get-all-items (point) struct prevs))
7178 (org-list-set-item-visibility e struct 'folded))
7179 (goto-char (if (< end eos) end eos)))))))
7180 (org-unlogged-message "CHILDREN")
7181 (save-excursion
7182 (goto-char eos)
7183 (outline-next-heading)
7184 (when (org-invisible-p) (org-flag-heading nil)))
7185 (setq org-cycle-subtree-status 'children)
7186 (unless (org-before-first-heading-p)
7187 (run-hook-with-args 'org-cycle-hook 'children)))
7188 ((or children-skipped
7189 (and (eq last-command this-command)
7190 (eq org-cycle-subtree-status 'children)))
7191 ;; We just showed the children, or no children are there,
7192 ;; now show everything.
7193 (unless (org-before-first-heading-p)
7194 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7195 (org-flag-region eoh eos nil 'outline)
7196 (org-unlogged-message
7197 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7198 (setq org-cycle-subtree-status 'subtree)
7199 (unless (org-before-first-heading-p)
7200 (run-hook-with-args 'org-cycle-hook 'subtree)))
7202 ;; Default action: hide the subtree.
7203 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7204 (org-flag-region eoh eos t 'outline)
7205 (org-unlogged-message "FOLDED")
7206 (setq org-cycle-subtree-status 'folded)
7207 (unless (org-before-first-heading-p)
7208 (run-hook-with-args 'org-cycle-hook 'folded))))))
7210 ;;;###autoload
7211 (defun org-global-cycle (&optional arg)
7212 "Cycle the global visibility. For details see `org-cycle'.
7213 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7214 With a numeric prefix, show all headlines up to that level."
7215 (interactive "P")
7216 (let ((org-cycle-include-plain-lists
7217 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7218 (cond
7219 ((integerp arg)
7220 (org-show-all '(headings blocks))
7221 (outline-hide-sublevels arg)
7222 (setq org-cycle-global-status 'contents))
7223 ((equal arg '(4))
7224 (org-set-startup-visibility)
7225 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7227 (org-cycle '(4))))))
7229 (defun org-set-startup-visibility ()
7230 "Set the visibility required by startup options and properties."
7231 (cond
7232 ((eq org-startup-folded t)
7233 (org-overview))
7234 ((eq org-startup-folded 'content)
7235 (org-content))
7236 ((or (eq org-startup-folded 'showeverything)
7237 (eq org-startup-folded nil))
7238 (org-show-all)))
7239 (unless (eq org-startup-folded 'showeverything)
7240 (when org-hide-block-startup (org-hide-block-all))
7241 (org-set-visibility-according-to-property)
7242 (org-cycle-hide-archived-subtrees 'all)
7243 (org-cycle-hide-drawers 'all)
7244 (org-cycle-show-empty-lines t)))
7246 (defun org-set-visibility-according-to-property ()
7247 "Switch subtree visibilities according to :VISIBILITY: property."
7248 (interactive)
7249 (org-with-wide-buffer
7250 (goto-char (point-min))
7251 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7252 (if (not (org-at-property-p)) (outline-next-heading)
7253 (let ((state (match-string 3)))
7254 (save-excursion
7255 (org-back-to-heading t)
7256 (outline-hide-subtree)
7257 (org-reveal)
7258 (cond
7259 ((equal state "folded")
7260 (outline-hide-subtree))
7261 ((equal state "children")
7262 (org-show-hidden-entry)
7263 (org-show-children))
7264 ((equal state "content")
7265 (save-excursion
7266 (save-restriction
7267 (org-narrow-to-subtree)
7268 (org-content))))
7269 ((member state '("all" "showall"))
7270 (outline-show-subtree)))))))))
7272 (defun org-overview ()
7273 "Switch to overview mode, showing only top-level headlines.
7274 This shows all headlines with a level equal or greater than the level
7275 of the first headline in the buffer. This is important, because if the
7276 first headline is not level one, then (hide-sublevels 1) gives confusing
7277 results."
7278 (interactive)
7279 (save-excursion
7280 (let ((level
7281 (save-excursion
7282 (goto-char (point-min))
7283 (when (re-search-forward org-outline-regexp-bol nil t)
7284 (goto-char (match-beginning 0))
7285 (funcall outline-level)))))
7286 (and level (outline-hide-sublevels level)))))
7288 (defun org-content (&optional arg)
7289 "Show all headlines in the buffer, like a table of contents.
7290 With numerical argument N, show content up to level N."
7291 (interactive "P")
7292 (org-overview)
7293 (save-excursion
7294 ;; Visit all headings and show their offspring
7295 (and (integerp arg) (org-overview))
7296 (goto-char (point-max))
7297 (catch 'exit
7298 (while (and (progn (condition-case nil
7299 (outline-previous-visible-heading 1)
7300 (error (goto-char (point-min))))
7302 (looking-at org-outline-regexp))
7303 (if (integerp arg)
7304 (org-show-children (1- arg))
7305 (outline-show-branches))
7306 (when (bobp) (throw 'exit nil))))))
7308 (defun org-optimize-window-after-visibility-change (state)
7309 "Adjust the window after a change in outline visibility.
7310 This function is the default value of the hook `org-cycle-hook'."
7311 (when (get-buffer-window (current-buffer))
7312 (cond
7313 ((eq state 'content) nil)
7314 ((eq state 'all) nil)
7315 ((eq state 'folded) nil)
7316 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7317 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7319 (defun org-clean-visibility-after-subtree-move ()
7320 "Fix visibility issues after moving a subtree."
7321 ;; First, find a reasonable region to look at:
7322 ;; Start two siblings above, end three below
7323 (let* ((beg (save-excursion
7324 (and (org-get-last-sibling)
7325 (org-get-last-sibling))
7326 (point)))
7327 (end (save-excursion
7328 (and (org-get-next-sibling)
7329 (org-get-next-sibling)
7330 (org-get-next-sibling))
7331 (if (org-at-heading-p)
7332 (point-at-eol)
7333 (point))))
7334 (level (looking-at "\\*+"))
7335 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7336 (save-excursion
7337 (save-restriction
7338 (narrow-to-region beg end)
7339 (when re
7340 ;; Properly fold already folded siblings
7341 (goto-char (point-min))
7342 (while (re-search-forward re nil t)
7343 (when (and (not (org-invisible-p))
7344 (org-invisible-p (line-end-position)))
7345 (outline-hide-entry))))
7346 (org-cycle-hide-drawers 'all)
7347 (org-cycle-show-empty-lines 'overview)))))
7349 (defun org-cycle-show-empty-lines (state)
7350 "Show empty lines above all visible headlines.
7351 The region to be covered depends on STATE when called through
7352 `org-cycle-hook'. Lisp program can use t for STATE to get the
7353 entire buffer covered. Note that an empty line is only shown if there
7354 are at least `org-cycle-separator-lines' empty lines before the headline."
7355 (when (/= org-cycle-separator-lines 0)
7356 (save-excursion
7357 (let* ((n (abs org-cycle-separator-lines))
7358 (re (cond
7359 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7360 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7361 (t (let ((ns (number-to-string (- n 2))))
7362 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7363 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7364 beg end)
7365 (cond
7366 ((memq state '(overview contents t))
7367 (setq beg (point-min) end (point-max)))
7368 ((memq state '(children folded))
7369 (setq beg (point)
7370 end (progn (org-end-of-subtree t t)
7371 (line-beginning-position 2)))))
7372 (when beg
7373 (goto-char beg)
7374 (while (re-search-forward re end t)
7375 (unless (get-char-property (match-end 1) 'invisible)
7376 (let ((e (match-end 1))
7377 (b (if (>= org-cycle-separator-lines 0)
7378 (match-beginning 1)
7379 (save-excursion
7380 (goto-char (match-beginning 0))
7381 (skip-chars-backward " \t\n")
7382 (line-end-position)))))
7383 (org-flag-region b e nil 'outline))))))))
7384 ;; Never hide empty lines at the end of the file.
7385 (save-excursion
7386 (goto-char (point-max))
7387 (outline-previous-heading)
7388 (outline-end-of-heading)
7389 (when (and (looking-at "[ \t\n]+")
7390 (= (match-end 0) (point-max)))
7391 (org-flag-region (point) (match-end 0) nil 'outline))))
7393 ;;;; Reveal point location
7395 (defun org-show-context (&optional key)
7396 "Make sure point and context are visible.
7397 Optional argument KEY, when non-nil, is a symbol. See
7398 `org-show-context-detail' for allowed values and how much is to
7399 be shown."
7400 (org-show-set-visibility
7401 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7402 ((cdr (assq key org-show-context-detail)))
7403 (t (cdr (assq 'default org-show-context-detail))))))
7405 (defun org-show-set-visibility (detail)
7406 "Set visibility around point according to DETAIL.
7407 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7408 `tree', `canonical' or t. See `org-show-context-detail' for more
7409 information."
7410 ;; Show current heading and possibly its entry, following headline
7411 ;; or all children.
7412 (if (and (org-at-heading-p) (not (eq detail 'local)))
7413 (org-flag-heading nil)
7414 (org-show-entry)
7415 ;; If point is hidden within a drawer or a block, make sure to
7416 ;; expose it.
7417 (dolist (o (overlays-at (point)))
7418 (when (memq (overlay-get o 'invisible)
7419 '(org-hide-block org-hide-drawer outline))
7420 (delete-overlay o)))
7421 (unless (org-before-first-heading-p)
7422 (org-with-limited-levels
7423 (cl-case detail
7424 ((tree canonical t) (org-show-children))
7425 ((nil minimal ancestors))
7426 (t (save-excursion
7427 (outline-next-heading)
7428 (org-flag-heading nil)))))))
7429 ;; Show all siblings.
7430 (when (eq detail 'lineage) (org-show-siblings))
7431 ;; Show ancestors, possibly with their children.
7432 (when (memq detail '(ancestors lineage tree canonical t))
7433 (save-excursion
7434 (while (org-up-heading-safe)
7435 (org-flag-heading nil)
7436 (when (memq detail '(canonical t)) (org-show-entry))
7437 (when (memq detail '(tree canonical t)) (org-show-children))))))
7439 (defvar org-reveal-start-hook nil
7440 "Hook run before revealing a location.")
7442 (defun org-reveal (&optional siblings)
7443 "Show current entry, hierarchy above it, and the following headline.
7445 This can be used to show a consistent set of context around
7446 locations exposed with `org-show-context'.
7448 With optional argument SIBLINGS, on each level of the hierarchy all
7449 siblings are shown. This repairs the tree structure to what it would
7450 look like when opened with hierarchical calls to `org-cycle'.
7452 With a \\[universal-argument] \\[universal-argument] prefix, \
7453 go to the parent and show the entire tree."
7454 (interactive "P")
7455 (run-hooks 'org-reveal-start-hook)
7456 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7457 ((equal siblings '(16))
7458 (save-excursion
7459 (when (org-up-heading-safe)
7460 (org-show-subtree)
7461 (run-hook-with-args 'org-cycle-hook 'subtree))))
7462 (t (org-show-set-visibility 'lineage))))
7465 ;;; Indirect buffer display of subtrees
7467 (defvar org-indirect-dedicated-frame nil
7468 "This is the frame being used for indirect tree display.")
7469 (defvar org-last-indirect-buffer nil)
7471 (defun org-tree-to-indirect-buffer (&optional arg)
7472 "Create indirect buffer and narrow it to current subtree.
7474 With a numerical prefix ARG, go up to this level and then take that tree.
7475 If ARG is negative, go up that many levels.
7477 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7478 indirect buffer previously made with this command, to avoid proliferation of
7479 indirect buffers. However, when you call the command with a \
7480 `\\[universal-argument]' prefix, or
7481 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7482 so that you can work with several indirect buffers at the same time. If
7483 `org-indirect-buffer-display' is `dedicated-frame', the \
7484 `\\[universal-argument]' prefix also
7485 requests that a new frame be made for the new buffer, so that the dedicated
7486 frame is not changed."
7487 (interactive "P")
7488 (let ((cbuf (current-buffer))
7489 (cwin (selected-window))
7490 (pos (point))
7491 beg end level heading ibuf)
7492 (save-excursion
7493 (org-back-to-heading t)
7494 (when (numberp arg)
7495 (setq level (org-outline-level))
7496 (when (< arg 0) (setq arg (+ level arg)))
7497 (while (> (setq level (org-outline-level)) arg)
7498 (org-up-heading-safe)))
7499 (setq beg (point)
7500 heading (org-get-heading 'no-tags))
7501 (org-end-of-subtree t t)
7502 (when (org-at-heading-p) (backward-char 1))
7503 (setq end (point)))
7504 (when (and (buffer-live-p org-last-indirect-buffer)
7505 (not (eq org-indirect-buffer-display 'new-frame))
7506 (not arg))
7507 (kill-buffer org-last-indirect-buffer))
7508 (setq ibuf (org-get-indirect-buffer cbuf heading)
7509 org-last-indirect-buffer ibuf)
7510 (cond
7511 ((or (eq org-indirect-buffer-display 'new-frame)
7512 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7513 (select-frame (make-frame))
7514 (delete-other-windows)
7515 (pop-to-buffer-same-window ibuf)
7516 (org-set-frame-title heading))
7517 ((eq org-indirect-buffer-display 'dedicated-frame)
7518 (raise-frame
7519 (select-frame (or (and org-indirect-dedicated-frame
7520 (frame-live-p org-indirect-dedicated-frame)
7521 org-indirect-dedicated-frame)
7522 (setq org-indirect-dedicated-frame (make-frame)))))
7523 (delete-other-windows)
7524 (pop-to-buffer-same-window ibuf)
7525 (org-set-frame-title (concat "Indirect: " heading)))
7526 ((eq org-indirect-buffer-display 'current-window)
7527 (pop-to-buffer-same-window ibuf))
7528 ((eq org-indirect-buffer-display 'other-window)
7529 (pop-to-buffer ibuf))
7530 (t (error "Invalid value")))
7531 (narrow-to-region beg end)
7532 (org-show-all '(headings blocks))
7533 (goto-char pos)
7534 (run-hook-with-args 'org-cycle-hook 'all)
7535 (and (window-live-p cwin) (select-window cwin))))
7537 (defun org-get-indirect-buffer (&optional buffer heading)
7538 (setq buffer (or buffer (current-buffer)))
7539 (let ((n 1) (base (buffer-name buffer)) bname)
7540 (while (buffer-live-p
7541 (get-buffer
7542 (setq bname
7543 (concat base "-"
7544 (if heading (concat heading "-" (number-to-string n))
7545 (number-to-string n))))))
7546 (setq n (1+ n)))
7547 (condition-case nil
7548 (make-indirect-buffer buffer bname 'clone)
7549 (error (make-indirect-buffer buffer bname)))))
7551 (defun org-set-frame-title (title)
7552 "Set the title of the current frame to the string TITLE."
7553 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7555 ;;;; Structure editing
7557 ;;; Inserting headlines
7559 (defun org--line-empty-p (n)
7560 "Is the Nth next line empty?
7562 Counts the current line as N = 1 and the previous line as N = 0;
7563 see `beginning-of-line'."
7564 (save-excursion
7565 (and (not (bobp))
7566 (or (beginning-of-line n) t)
7567 (save-match-data
7568 (looking-at "[ \t]*$")))))
7570 (defun org-previous-line-empty-p ()
7571 "Is the previous line a blank line?
7572 When NEXT is non-nil, check the next line instead."
7573 (org--line-empty-p 0))
7575 (defun org-next-line-empty-p ()
7576 "Is the previous line a blank line?
7577 When NEXT is non-nil, check the next line instead."
7578 (org--line-empty-p 2))
7580 (defun org--blank-before-heading-p (&optional parent)
7581 "Non-nil when an empty line should precede a new heading here.
7582 When optional argument PARENT is non-nil, consider parent
7583 headline instead of current one."
7584 (pcase (assq 'heading org-blank-before-new-entry)
7585 (`(heading . auto)
7586 (save-excursion
7587 (org-with-limited-levels
7588 (unless (and (org-before-first-heading-p)
7589 (not (outline-next-heading)))
7590 (org-back-to-heading t)
7591 (when parent (org-up-heading-safe))
7592 (cond ((not (bobp))
7593 (org-previous-line-empty-p))
7594 ((outline-next-heading)
7595 (org-previous-line-empty-p))
7596 ;; Ignore trailing spaces on last buffer line.
7597 ((progn (skip-chars-backward " \t") (bolp))
7598 (org-previous-line-empty-p))
7599 (t nil))))))
7600 (`(heading . ,value) value)
7601 (_ nil)))
7603 (defun org-insert-heading (&optional arg invisible-ok top)
7604 "Insert a new heading or an item with the same depth at point.
7606 If point is at the beginning of a heading, insert a new heading
7607 or a new headline above the current one. When at the beginning
7608 of a regular line of text, turn it into a heading.
7610 If point is in the middle of a line, split it and create a new
7611 headline with the text in the current line after point (see
7612 `org-M-RET-may-split-line' on how to modify this behavior). As
7613 a special case, on a headline, splitting can only happen on the
7614 title itself. E.g., this excludes breaking stars or tags.
7616 With a `\\[universal-argument]' prefix, set \
7617 `org-insert-heading-respect-content' to
7618 a non-nil value for the duration of the command. This forces the
7619 insertion of a heading after the current subtree, independently
7620 on the location of point.
7622 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7623 insert the heading at the end of the tree
7624 above the current heading. For example, if point is within a
7625 2nd-level heading, then it will insert a 2nd-level heading at
7626 the end of the 1st-level parent subtree.
7628 When INVISIBLE-OK is set, stop at invisible headlines when going
7629 back. This is important for non-interactive uses of the
7630 command.
7632 When optional argument TOP is non-nil, insert a level 1 heading,
7633 unconditionally."
7634 (interactive "P")
7635 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7636 (level (org-current-level))
7637 (stars (make-string (if (and level (not top)) level 1) ?*)))
7638 (cond
7639 ((or org-insert-heading-respect-content
7640 (member arg '((4) (16)))
7641 (and (not invisible-ok)
7642 (invisible-p (max (1- (point)) (point-min)))))
7643 ;; Position point at the location of insertion.
7644 (if (not level) ;before first headline
7645 (org-with-limited-levels (outline-next-heading))
7646 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7647 ;; is nil.
7648 (org-with-limited-levels (org-back-to-heading invisible-ok))
7649 (cond ((equal arg '(16))
7650 (org-up-heading-safe)
7651 (org-end-of-subtree t t))
7653 (org-end-of-subtree t t))))
7654 (unless (bolp) (insert "\n")) ;ensure final newline
7655 (unless (and blank? (org-previous-line-empty-p))
7656 (org-N-empty-lines-before-current (if blank? 1 0)))
7657 (insert stars " \n")
7658 (forward-char -1))
7659 ;; At a headline...
7660 ((org-at-heading-p)
7661 (cond ((bolp)
7662 (when blank? (save-excursion (insert "\n")))
7663 (save-excursion (insert stars " \n"))
7664 (unless (and blank? (org-previous-line-empty-p))
7665 (org-N-empty-lines-before-current (if blank? 1 0)))
7666 (end-of-line))
7667 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7668 (org-match-line org-complex-heading-regexp)
7669 (org-pos-in-match-range (point) 4))
7670 ;; Grab the text that should moved to the new headline.
7671 ;; Preserve tags.
7672 (let ((split (delete-and-extract-region (point) (match-end 4))))
7673 (if (looking-at "[ \t]*$") (replace-match "")
7674 (org-align-tags))
7675 (end-of-line)
7676 (when blank? (insert "\n"))
7677 (insert "\n" stars " ")
7678 (when (org-string-nw-p split) (insert split))
7679 (when (eobp) (save-excursion (insert "\n")))))
7681 (end-of-line)
7682 (when blank? (insert "\n"))
7683 (insert "\n" stars " ")
7684 (when (eobp) (save-excursion (insert "\n"))))))
7685 ;; On regular text, turn line into a headline or split, if
7686 ;; appropriate.
7687 ((bolp)
7688 (insert stars " ")
7689 (unless (and blank? (org-previous-line-empty-p))
7690 (org-N-empty-lines-before-current (if blank? 1 0))))
7692 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7693 (end-of-line))
7694 (insert "\n" stars " ")
7695 (unless (and blank? (org-previous-line-empty-p))
7696 (org-N-empty-lines-before-current (if blank? 1 0))))))
7697 (run-hooks 'org-insert-heading-hook))
7699 (defun org-N-empty-lines-before-current (n)
7700 "Make the number of empty lines before current exactly N.
7701 So this will delete or add empty lines."
7702 (let ((column (current-column)))
7703 (beginning-of-line)
7704 (unless (bobp)
7705 (let ((start (save-excursion
7706 (skip-chars-backward " \r\t\n")
7707 (line-end-position))))
7708 (delete-region start (line-end-position 0))))
7709 (insert (make-string n ?\n))
7710 (move-to-column column)))
7712 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7713 "Return the heading of the current entry, without the stars.
7714 When NO-TAGS is non-nil, don't include tags.
7715 When NO-TODO is non-nil, don't include TODO keywords.
7716 When NO-PRIORITY is non-nil, don't include priority cookie.
7717 When NO-COMMENT is non-nil, don't include COMMENT string.
7718 Return nil before first heading."
7719 (unless (org-before-first-heading-p)
7720 (save-excursion
7721 (org-back-to-heading t)
7722 (let ((case-fold-search nil))
7723 (looking-at org-complex-heading-regexp)
7724 (let ((todo (and (not no-todo) (match-string 2)))
7725 (priority (and (not no-priority) (match-string 3)))
7726 (headline (pcase (match-string 4)
7727 (`nil "")
7728 ((and (guard no-comment) h)
7729 (replace-regexp-in-string
7730 (eval-when-compile
7731 (format "\\`%s[ \t]+" org-comment-string))
7732 "" h))
7733 (h h)))
7734 (tags (and (not no-tags) (match-string 5))))
7735 (mapconcat #'identity
7736 (delq nil (list todo priority headline tags))
7737 " "))))))
7739 (defun org-heading-components ()
7740 "Return the components of the current heading.
7741 This is a list with the following elements:
7742 - the level as an integer
7743 - the reduced level, different if `org-odd-levels-only' is set.
7744 - the TODO keyword, or nil
7745 - the priority character, like ?A, or nil if no priority is given
7746 - the headline text itself, or the tags string if no headline text
7747 - the tags string, or nil."
7748 (save-excursion
7749 (org-back-to-heading t)
7750 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7751 (list (length (match-string 1))
7752 (org-reduced-level (length (match-string 1)))
7753 (match-string-no-properties 2)
7754 (and (match-end 3) (aref (match-string 3) 2))
7755 (match-string-no-properties 4)
7756 (match-string-no-properties 5)))))
7758 (defun org-get-entry ()
7759 "Get the entry text, after heading, entire subtree."
7760 (save-excursion
7761 (org-back-to-heading t)
7762 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7764 (defun org-edit-headline (&optional heading)
7765 "Edit the current headline.
7766 Set it to HEADING when provided."
7767 (interactive)
7768 (org-with-wide-buffer
7769 (org-back-to-heading t)
7770 (let ((case-fold-search nil))
7771 (when (looking-at org-complex-heading-regexp)
7772 (let* ((old (match-string-no-properties 4))
7773 (new (save-match-data
7774 (org-trim (or heading (read-string "Edit: " old))))))
7775 (unless (equal old new)
7776 (if old (replace-match new t t nil 4)
7777 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7778 (insert " " new))
7779 (org-align-tags)
7780 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7782 (defun org-insert-heading-after-current ()
7783 "Insert a new heading with same level as current, after current subtree."
7784 (interactive)
7785 (org-back-to-heading)
7786 (org-insert-heading)
7787 (org-move-subtree-down)
7788 (end-of-line 1))
7790 (defun org-insert-heading-respect-content (&optional invisible-ok)
7791 "Insert heading with `org-insert-heading-respect-content' set to t."
7792 (interactive)
7793 (org-insert-heading '(4) invisible-ok))
7795 (defun org-insert-todo-heading-respect-content (&optional force-state)
7796 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7797 (interactive)
7798 (org-insert-todo-heading force-state '(4)))
7800 (defun org-insert-todo-heading (arg &optional force-heading)
7801 "Insert a new heading with the same level and TODO state as current heading.
7803 If the heading has no TODO state, or if the state is DONE, use
7804 the first state (TODO by default). Also with one prefix arg,
7805 force first state. With two prefix args, force inserting at the
7806 end of the parent subtree.
7808 When called at a plain list item, insert a new item with an
7809 unchecked check box."
7810 (interactive "P")
7811 (when (or force-heading (not (org-insert-item 'checkbox)))
7812 (org-insert-heading (or (and (equal arg '(16)) '(16))
7813 force-heading))
7814 (save-excursion
7815 (org-forward-heading-same-level -1)
7816 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7817 (let* ((new-mark-x
7818 (if (or (equal arg '(4))
7819 (not (match-beginning 2))
7820 (member (match-string 2) org-done-keywords))
7821 (car org-todo-keywords-1)
7822 (match-string 2)))
7823 (new-mark
7825 (run-hook-with-args-until-success
7826 'org-todo-get-default-hook new-mark-x nil)
7827 new-mark-x)))
7828 (beginning-of-line 1)
7829 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7830 (if org-treat-insert-todo-heading-as-state-change
7831 (org-todo new-mark)
7832 (insert new-mark " "))))
7833 (when org-provide-todo-statistics
7834 (org-update-parent-todo-statistics))))
7836 (defun org-insert-subheading (arg)
7837 "Insert a new subheading and demote it.
7838 Works for outline headings and for plain lists alike."
7839 (interactive "P")
7840 (org-insert-heading arg)
7841 (cond
7842 ((org-at-heading-p) (org-do-demote))
7843 ((org-at-item-p) (org-indent-item))))
7845 (defun org-insert-todo-subheading (arg)
7846 "Insert a new subheading with TODO keyword or checkbox and demote it.
7847 Works for outline headings and for plain lists alike."
7848 (interactive "P")
7849 (org-insert-todo-heading arg)
7850 (cond
7851 ((org-at-heading-p) (org-do-demote))
7852 ((org-at-item-p) (org-indent-item))))
7854 ;;; Promotion and Demotion
7856 (defvar org-after-demote-entry-hook nil
7857 "Hook run after an entry has been demoted.
7858 The cursor will be at the beginning of the entry.
7859 When a subtree is being demoted, the hook will be called for each node.")
7861 (defvar org-after-promote-entry-hook nil
7862 "Hook run after an entry has been promoted.
7863 The cursor will be at the beginning of the entry.
7864 When a subtree is being promoted, the hook will be called for each node.")
7866 (defun org-promote-subtree ()
7867 "Promote the entire subtree.
7868 See also `org-promote'."
7869 (interactive)
7870 (save-excursion
7871 (org-with-limited-levels (org-map-tree 'org-promote)))
7872 (org-fix-position-after-promote))
7874 (defun org-demote-subtree ()
7875 "Demote the entire subtree.
7876 See `org-demote' and `org-promote'."
7877 (interactive)
7878 (save-excursion
7879 (org-with-limited-levels (org-map-tree 'org-demote)))
7880 (org-fix-position-after-promote))
7882 (defun org-do-promote ()
7883 "Promote the current heading higher up the tree.
7884 If the region is active in `transient-mark-mode', promote all
7885 headings in the region."
7886 (interactive)
7887 (save-excursion
7888 (if (org-region-active-p)
7889 (org-map-region 'org-promote (region-beginning) (region-end))
7890 (org-promote)))
7891 (org-fix-position-after-promote))
7893 (defun org-do-demote ()
7894 "Demote the current heading lower down the tree.
7895 If the region is active in `transient-mark-mode', demote all
7896 headings in the region."
7897 (interactive)
7898 (save-excursion
7899 (if (org-region-active-p)
7900 (org-map-region 'org-demote (region-beginning) (region-end))
7901 (org-demote)))
7902 (org-fix-position-after-promote))
7904 (defun org-fix-position-after-promote ()
7905 "Fix cursor position and indentation after demoting/promoting."
7906 (let ((pos (point)))
7907 (when (save-excursion
7908 (beginning-of-line)
7909 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7910 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7911 (cond ((eobp) (insert " "))
7912 ((eolp) (insert " "))
7913 ((equal (char-after) ?\s) (forward-char 1))))))
7915 (defun org-current-level ()
7916 "Return the level of the current entry, or nil if before the first headline.
7917 The level is the number of stars at the beginning of the
7918 headline. Use `org-reduced-level' to remove the effect of
7919 `org-odd-levels'. Unlike to `org-outline-level', this function
7920 ignores inlinetasks."
7921 (let ((level (org-with-limited-levels (org-outline-level))))
7922 (and (> level 0) level)))
7924 (defun org-get-previous-line-level ()
7925 "Return the outline depth of the last headline before the current line.
7926 Returns 0 for the first headline in the buffer, and nil if before the
7927 first headline."
7928 (and (org-current-level)
7929 (or (and (/= (line-beginning-position) (point-min))
7930 (save-excursion (beginning-of-line 0) (org-current-level)))
7931 0)))
7933 (defun org-reduced-level (l)
7934 "Compute the effective level of a heading.
7935 This takes into account the setting of `org-odd-levels-only'."
7936 (cond
7937 ((zerop l) 0)
7938 (org-odd-levels-only (1+ (floor (/ l 2))))
7939 (t l)))
7941 (defun org-level-increment ()
7942 "Return the number of stars that will be added or removed at a
7943 time to headlines when structure editing, based on the value of
7944 `org-odd-levels-only'."
7945 (if org-odd-levels-only 2 1))
7947 (defun org-get-valid-level (level &optional change)
7948 "Rectify a level change under the influence of `org-odd-levels-only'.
7949 LEVEL is a current level, CHANGE is by how much the level should
7950 be modified. Even if CHANGE is nil, LEVEL may be returned
7951 modified because even level numbers will become the next higher
7952 odd number. Returns values greater than 0."
7953 (if org-odd-levels-only
7954 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7955 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7956 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7957 (max 1 (+ level (or change 0)))))
7959 (defun org-promote ()
7960 "Promote the current heading higher up the tree."
7961 (org-with-wide-buffer
7962 (org-back-to-heading t)
7963 (let* ((after-change-functions (remq 'flyspell-after-change-function
7964 after-change-functions))
7965 (level (save-match-data (funcall outline-level)))
7966 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7967 (diff (abs (- level (length up-head) -1))))
7968 (cond
7969 ((and (= level 1) org-allow-promoting-top-level-subtree)
7970 (replace-match "# " nil t))
7971 ((= level 1)
7972 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7973 (t (replace-match up-head nil t)))
7974 (unless (= level 1)
7975 (when org-auto-align-tags (org-align-tags))
7976 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7977 (run-hooks 'org-after-promote-entry-hook))))
7979 (defun org-demote ()
7980 "Demote the current heading lower down the tree."
7981 (org-with-wide-buffer
7982 (org-back-to-heading t)
7983 (let* ((after-change-functions (remq 'flyspell-after-change-function
7984 after-change-functions))
7985 (level (save-match-data (funcall outline-level)))
7986 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7987 (diff (abs (- level (length down-head) -1))))
7988 (replace-match down-head nil t)
7989 (when org-auto-align-tags (org-align-tags))
7990 (when org-adapt-indentation (org-fixup-indentation diff))
7991 (run-hooks 'org-after-demote-entry-hook))))
7993 (defun org-cycle-level ()
7994 "Cycle the level of an empty headline through possible states.
7995 This goes first to child, then to parent, level, then up the hierarchy.
7996 After top level, it switches back to sibling level."
7997 (interactive)
7998 (let ((org-adapt-indentation nil))
7999 (when (org-point-at-end-of-empty-headline)
8000 (setq this-command 'org-cycle-level) ; Only needed for caching
8001 (let ((cur-level (org-current-level))
8002 (prev-level (org-get-previous-line-level)))
8003 (cond
8004 ;; If first headline in file, promote to top-level.
8005 ((= prev-level 0)
8006 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8007 do (org-do-promote)))
8008 ;; If same level as prev, demote one.
8009 ((= prev-level cur-level)
8010 (org-do-demote))
8011 ;; If parent is top-level, promote to top level if not already.
8012 ((= prev-level 1)
8013 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8014 do (org-do-promote)))
8015 ;; If top-level, return to prev-level.
8016 ((= cur-level 1)
8017 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8018 do (org-do-demote)))
8019 ;; If less than prev-level, promote one.
8020 ((< cur-level prev-level)
8021 (org-do-promote))
8022 ;; If deeper than prev-level, promote until higher than
8023 ;; prev-level.
8024 ((> cur-level prev-level)
8025 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8026 do (org-do-promote))))
8027 t))))
8029 (defun org-map-tree (fun)
8030 "Call FUN for every heading underneath the current one."
8031 (org-back-to-heading t)
8032 (let ((level (funcall outline-level)))
8033 (save-excursion
8034 (funcall fun)
8035 (while (and (progn
8036 (outline-next-heading)
8037 (> (funcall outline-level) level))
8038 (not (eobp)))
8039 (funcall fun)))))
8041 (defun org-map-region (fun beg end)
8042 "Call FUN for every heading between BEG and END."
8043 (let ((org-ignore-region t))
8044 (save-excursion
8045 (setq end (copy-marker end))
8046 (goto-char beg)
8047 (when (and (re-search-forward org-outline-regexp-bol nil t)
8048 (< (point) end))
8049 (funcall fun))
8050 (while (and (progn
8051 (outline-next-heading)
8052 (< (point) end))
8053 (not (eobp)))
8054 (funcall fun)))))
8056 (defun org-fixup-indentation (diff)
8057 "Change the indentation in the current entry by DIFF.
8059 DIFF is an integer. Indentation is done according to the
8060 following rules:
8062 - Planning information and property drawers are always indented
8063 according to the new level of the headline;
8065 - Footnote definitions and their contents are ignored;
8067 - Inlinetasks' boundaries are not shifted;
8069 - Empty lines are ignored;
8071 - Other lines' indentation are shifted by DIFF columns, unless
8072 it would introduce a structural change in the document, in
8073 which case no shifting is done at all.
8075 Assume point is at a heading or an inlinetask beginning."
8076 (org-with-wide-buffer
8077 (narrow-to-region (line-beginning-position)
8078 (save-excursion
8079 (if (org-with-limited-levels (org-at-heading-p))
8080 (org-with-limited-levels (outline-next-heading))
8081 (org-inlinetask-goto-end))
8082 (point)))
8083 (forward-line)
8084 ;; Indent properly planning info and property drawer.
8085 (when (looking-at-p org-planning-line-re)
8086 (org-indent-line)
8087 (forward-line))
8088 (when (looking-at org-property-drawer-re)
8089 (goto-char (match-end 0))
8090 (forward-line)
8091 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8092 (catch 'no-shift
8093 (when (zerop diff) (throw 'no-shift nil))
8094 ;; If DIFF is negative, first check if a shift is possible at all
8095 ;; (e.g., it doesn't break structure). This can only happen if
8096 ;; some contents are not properly indented.
8097 (let ((case-fold-search t))
8098 (when (< diff 0)
8099 (let ((diff (- diff))
8100 (forbidden-re (concat org-outline-regexp
8101 "\\|"
8102 (substring org-footnote-definition-re 1))))
8103 (save-excursion
8104 (while (not (eobp))
8105 (cond
8106 ((looking-at-p "[ \t]*$") (forward-line))
8107 ((and (looking-at-p org-footnote-definition-re)
8108 (let ((e (org-element-at-point)))
8109 (and (eq (org-element-type e) 'footnote-definition)
8110 (goto-char (org-element-property :end e))))))
8111 ((looking-at-p org-outline-regexp) (forward-line))
8112 ;; Give up if shifting would move before column 0 or
8113 ;; if it would introduce a headline or a footnote
8114 ;; definition.
8116 (skip-chars-forward " \t")
8117 (let ((ind (current-column)))
8118 (when (or (< ind diff)
8119 (and (= ind diff) (looking-at-p forbidden-re)))
8120 (throw 'no-shift nil)))
8121 ;; Ignore contents of example blocks and source
8122 ;; blocks if their indentation is meant to be
8123 ;; preserved. Jump to block's closing line.
8124 (beginning-of-line)
8125 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8126 (let ((e (org-element-at-point)))
8127 (and (memq (org-element-type e)
8128 '(example-block src-block))
8129 (or org-src-preserve-indentation
8130 (org-element-property :preserve-indent e))
8131 (goto-char (org-element-property :end e))
8132 (progn (skip-chars-backward " \r\t\n")
8133 (beginning-of-line)
8134 t))))
8135 (forward-line))))))))
8136 ;; Shift lines but footnote definitions, inlinetasks boundaries
8137 ;; by DIFF. Also skip contents of source or example blocks
8138 ;; when indentation is meant to be preserved.
8139 (while (not (eobp))
8140 (cond
8141 ((and (looking-at-p org-footnote-definition-re)
8142 (let ((e (org-element-at-point)))
8143 (and (eq (org-element-type e) 'footnote-definition)
8144 (goto-char (org-element-property :end e))))))
8145 ((looking-at-p org-outline-regexp) (forward-line))
8146 ((looking-at-p "[ \t]*$") (forward-line))
8148 (indent-line-to (+ (current-indentation) diff))
8149 (beginning-of-line)
8150 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8151 (let ((e (org-element-at-point)))
8152 (and (memq (org-element-type e)
8153 '(example-block src-block))
8154 (or org-src-preserve-indentation
8155 (org-element-property :preserve-indent e))
8156 (goto-char (org-element-property :end e))
8157 (progn (skip-chars-backward " \r\t\n")
8158 (beginning-of-line)
8159 t))))
8160 (forward-line)))))))))
8162 (defun org-convert-to-odd-levels ()
8163 "Convert an Org file with all levels allowed to one with odd levels.
8164 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8165 level 5 etc."
8166 (interactive)
8167 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8168 (let ((outline-level 'org-outline-level)
8169 (org-odd-levels-only nil) n)
8170 (save-excursion
8171 (goto-char (point-min))
8172 (while (re-search-forward "^\\*\\*+ " nil t)
8173 (setq n (- (length (match-string 0)) 2))
8174 (while (>= (setq n (1- n)) 0)
8175 (org-demote))
8176 (end-of-line 1))))))
8178 (defun org-convert-to-oddeven-levels ()
8179 "Convert an Org file with only odd levels to one with odd/even levels.
8180 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8181 file contains a section with an even level, conversion would
8182 destroy the structure of the file. An error is signaled in this
8183 case."
8184 (interactive)
8185 (goto-char (point-min))
8186 ;; First check if there are no even levels
8187 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8188 (org-show-set-visibility 'canonical)
8189 (error "Not all levels are odd in this file. Conversion not possible"))
8190 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8191 (let ((outline-regexp org-outline-regexp)
8192 (outline-level 'org-outline-level)
8193 (org-odd-levels-only nil) n)
8194 (save-excursion
8195 (goto-char (point-min))
8196 (while (re-search-forward "^\\*\\*+ " nil t)
8197 (setq n (/ (1- (length (match-string 0))) 2))
8198 (while (>= (setq n (1- n)) 0)
8199 (org-promote))
8200 (end-of-line 1))))))
8202 (defun org-tr-level (n)
8203 "Make N odd if required."
8204 (if org-odd-levels-only (1+ (/ n 2)) n))
8206 ;;; Vertical tree motion, cutting and pasting of subtrees
8208 (defun org-move-subtree-up (&optional arg)
8209 "Move the current subtree up past ARG headlines of the same level."
8210 (interactive "p")
8211 (org-move-subtree-down (- (prefix-numeric-value arg))))
8213 (defun org-move-subtree-down (&optional arg)
8214 "Move the current subtree down past ARG headlines of the same level."
8215 (interactive "p")
8216 (setq arg (prefix-numeric-value arg))
8217 (org-preserve-local-variables
8218 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8219 'org-get-last-sibling))
8220 (ins-point (make-marker))
8221 (cnt (abs arg))
8222 (col (current-column))
8223 beg end txt folded)
8224 ;; Select the tree
8225 (org-back-to-heading)
8226 (setq beg (point))
8227 (save-match-data
8228 (save-excursion (outline-end-of-heading)
8229 (setq folded (org-invisible-p)))
8230 (progn (org-end-of-subtree nil t)
8231 (unless (eobp) (backward-char))))
8232 (outline-next-heading)
8233 (setq end (point))
8234 (goto-char beg)
8235 ;; Find insertion point, with error handling
8236 (while (> cnt 0)
8237 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8238 (goto-char beg)
8239 (user-error "Cannot move past superior level or buffer limit"))
8240 (setq cnt (1- cnt)))
8241 (when (> arg 0)
8242 ;; Moving forward - still need to move over subtree
8243 (org-end-of-subtree t t)
8244 (save-excursion
8245 (org-back-over-empty-lines)
8246 (or (bolp) (newline))))
8247 (move-marker ins-point (point))
8248 (setq txt (buffer-substring beg end))
8249 (org-save-markers-in-region beg end)
8250 (delete-region beg end)
8251 (org-remove-empty-overlays-at beg)
8252 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8253 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8254 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8255 (let ((bbb (point)))
8256 (insert-before-markers txt)
8257 (org-reinstall-markers-in-region bbb)
8258 (move-marker ins-point bbb))
8259 (or (bolp) (insert "\n"))
8260 (goto-char ins-point)
8261 (org-skip-whitespace)
8262 (move-marker ins-point nil)
8263 (if folded
8264 (outline-hide-subtree)
8265 (org-show-entry)
8266 (org-show-children))
8267 (org-clean-visibility-after-subtree-move)
8268 ;; move back to the initial column we were at
8269 (move-to-column col))))
8271 (defvar org-subtree-clip ""
8272 "Clipboard for cut and paste of subtrees.
8273 This is actually only a copy of the kill, because we use the normal kill
8274 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8276 (defvar org-subtree-clip-folded nil
8277 "Was the last copied subtree folded?
8278 This is used to fold the tree back after pasting.")
8280 (defun org-cut-subtree (&optional n)
8281 "Cut the current subtree into the clipboard.
8282 With prefix arg N, cut this many sequential subtrees.
8283 This is a short-hand for marking the subtree and then cutting it."
8284 (interactive "p")
8285 (org-copy-subtree n 'cut))
8287 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8288 "Copy the current subtree into the clipboard.
8289 With prefix arg N, copy this many sequential subtrees.
8290 This is a short-hand for marking the subtree and then copying it.
8291 If CUT is non-nil, actually cut the subtree.
8292 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8293 of some markers in the region, even if CUT is non-nil. This is
8294 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8295 (interactive "p")
8296 (org-preserve-local-variables
8297 (let (beg end folded (beg0 (point)))
8298 (if (called-interactively-p 'any)
8299 (org-back-to-heading nil) ; take what looks like a subtree
8300 (org-back-to-heading t)) ; take what is really there
8301 (setq beg (point))
8302 (skip-chars-forward " \t\r\n")
8303 (save-match-data
8304 (if nosubtrees
8305 (outline-next-heading)
8306 (save-excursion (outline-end-of-heading)
8307 (setq folded (org-invisible-p)))
8308 (ignore-errors (org-forward-heading-same-level (1- n) t))
8309 (org-end-of-subtree t t)))
8310 ;; Include the end of an inlinetask
8311 (when (and (featurep 'org-inlinetask)
8312 (looking-at-p (concat (org-inlinetask-outline-regexp)
8313 "END[ \t]*$")))
8314 (end-of-line))
8315 (setq end (point))
8316 (goto-char beg0)
8317 (when (> end beg)
8318 (setq org-subtree-clip-folded folded)
8319 (when (or cut force-store-markers)
8320 (org-save-markers-in-region beg end))
8321 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8322 (setq org-subtree-clip (current-kill 0))
8323 (message "%s: Subtree(s) with %d characters"
8324 (if cut "Cut" "Copied")
8325 (length org-subtree-clip))))))
8327 (defun org-paste-subtree (&optional level tree for-yank remove)
8328 "Paste the clipboard as a subtree, with modification of headline level.
8330 The entire subtree is promoted or demoted in order to match a new headline
8331 level.
8333 If the cursor is at the beginning of a headline, the same level as
8334 that headline is used to paste the tree.
8336 If not, the new level is derived from the *visible* headings
8337 before and after the insertion point, and taken to be the inferior headline
8338 level of the two. So if the previous visible heading is level 3 and the
8339 next is level 4 (or vice versa), level 4 will be used for insertion.
8340 This makes sure that the subtree remains an independent subtree and does
8341 not swallow low level entries.
8343 You can also force a different level, either by using a numeric prefix
8344 argument, or by inserting the heading marker by hand. For example, if the
8345 cursor is after \"*****\", then the tree will be shifted to level 5.
8347 If optional TREE is given, use this text instead of the kill ring.
8349 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8350 move back over whitespace before inserting, and move point to the end of
8351 the inserted text when done.
8353 When REMOVE is non-nil, remove the subtree from the clipboard."
8354 (interactive "P")
8355 (setq tree (or tree (and kill-ring (current-kill 0))))
8356 (unless (org-kill-is-subtree-p tree)
8357 (user-error
8358 (substitute-command-keys
8359 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8360 (org-with-limited-levels
8361 (let* ((visp (not (org-invisible-p)))
8362 (txt tree)
8363 (old-level (if (string-match org-outline-regexp-bol txt)
8364 (- (match-end 0) (match-beginning 0) 1)
8365 -1))
8366 (force-level
8367 (cond
8368 (level (prefix-numeric-value level))
8369 ;; When point is after the stars in an otherwise empty
8370 ;; headline, use the number of stars as the forced level.
8371 ((and (org-match-line "^\\*+[ \t]*$")
8372 (not (eq ?* (char-after))))
8373 (org-outline-level))
8374 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8375 (previous-level
8376 (save-excursion
8377 (org-previous-visible-heading 1)
8378 (if (org-at-heading-p) (org-outline-level) 1)))
8379 (next-level
8380 (save-excursion
8381 (if (org-at-heading-p) (org-outline-level)
8382 (org-next-visible-heading 1)
8383 (if (org-at-heading-p) (org-outline-level) 1))))
8384 (new-level (or force-level (max previous-level next-level)))
8385 (shift (if (or (= old-level -1)
8386 (= new-level -1)
8387 (= old-level new-level))
8389 (- new-level old-level)))
8390 (delta (if (> shift 0) -1 1))
8391 (func (if (> shift 0) #'org-demote #'org-promote))
8392 (org-odd-levels-only nil)
8393 beg end newend)
8394 ;; Remove the forced level indicator.
8395 (when (and force-level (not level))
8396 (delete-region (line-beginning-position) (point)))
8397 ;; Paste before the next visible heading or at end of buffer,
8398 ;; unless point is at the beginning of a headline.
8399 (unless (and (bolp) (org-at-heading-p))
8400 (org-next-visible-heading 1)
8401 (unless (bolp) (insert "\n")))
8402 (setq beg (point))
8403 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8404 (insert-before-markers txt)
8405 (unless (string-suffix-p "\n" txt) (insert "\n"))
8406 (setq newend (point))
8407 (org-reinstall-markers-in-region beg)
8408 (setq end (point))
8409 (goto-char beg)
8410 (skip-chars-forward " \t\n\r")
8411 (setq beg (point))
8412 (when (and (org-invisible-p) visp)
8413 (save-excursion (outline-show-heading)))
8414 ;; Shift if necessary.
8415 (unless (= shift 0)
8416 (save-restriction
8417 (narrow-to-region beg end)
8418 (while (not (= shift 0))
8419 (org-map-region func (point-min) (point-max))
8420 (setq shift (+ delta shift)))
8421 (goto-char (point-min))
8422 (setq newend (point-max))))
8423 (when (or for-yank (called-interactively-p 'interactive))
8424 (message "Clipboard pasted as level %d subtree" new-level))
8425 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8426 kill-ring
8427 (equal org-subtree-clip (current-kill 0))
8428 org-subtree-clip-folded)
8429 ;; The tree was folded before it was killed/copied
8430 (outline-hide-subtree))
8431 (when for-yank (goto-char newend))
8432 (when remove (pop kill-ring)))))
8434 (defun org-kill-is-subtree-p (&optional txt)
8435 "Check if the current kill is an outline subtree, or a set of trees.
8436 Returns nil if kill does not start with a headline, or if the first
8437 headline level is not the largest headline level in the tree.
8438 So this will actually accept several entries of equal levels as well,
8439 which is OK for `org-paste-subtree'.
8440 If optional TXT is given, check this string instead of the current kill."
8441 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8442 (re (org-get-limited-outline-regexp))
8443 (^re (concat "^" re))
8444 (start-level (and kill
8445 (string-match
8446 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8447 kill)
8448 (- (match-end 2) (match-beginning 2) 1)))
8449 (start (1+ (or (match-beginning 2) -1))))
8450 (if (not start-level)
8451 (progn
8452 nil) ;; does not even start with a heading
8453 (catch 'exit
8454 (while (setq start (string-match ^re kill (1+ start)))
8455 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8456 (throw 'exit nil)))
8457 t))))
8459 (defvar org-markers-to-move nil
8460 "Markers that should be moved with a cut-and-paste operation.
8461 Those markers are stored together with their positions relative to
8462 the start of the region.")
8464 (defun org-save-markers-in-region (beg end)
8465 "Check markers in region.
8466 If these markers are between BEG and END, record their position relative
8467 to BEG, so that after moving the block of text, we can put the markers back
8468 into place.
8469 This function gets called just before an entry or tree gets cut from the
8470 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8471 called immediately, to move the markers with the entries."
8472 (setq org-markers-to-move nil)
8473 (when (featurep 'org-clock)
8474 (org-clock-save-markers-for-cut-and-paste beg end))
8475 (when (featurep 'org-agenda)
8476 (org-agenda-save-markers-for-cut-and-paste beg end)))
8478 (defun org-check-and-save-marker (marker beg end)
8479 "Check if MARKER is between BEG and END.
8480 If yes, remember the marker and the distance to BEG."
8481 (when (and (marker-buffer marker)
8482 (equal (marker-buffer marker) (current-buffer))
8483 (>= marker beg) (< marker end))
8484 (push (cons marker (- marker beg)) org-markers-to-move)))
8486 (defun org-reinstall-markers-in-region (beg)
8487 "Move all remembered markers to their position relative to BEG."
8488 (dolist (x org-markers-to-move)
8489 (move-marker (car x) (+ beg (cdr x))))
8490 (setq org-markers-to-move nil))
8492 (defun org-narrow-to-subtree ()
8493 "Narrow buffer to the current subtree."
8494 (interactive)
8495 (save-excursion
8496 (save-match-data
8497 (org-with-limited-levels
8498 (narrow-to-region
8499 (progn (org-back-to-heading t) (point))
8500 (progn (org-end-of-subtree t t)
8501 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8502 (point)))))))
8504 (defun org-toggle-narrow-to-subtree ()
8505 "Narrow to the subtree at point or widen a narrowed buffer."
8506 (interactive)
8507 (if (buffer-narrowed-p)
8508 (widen)
8509 (org-narrow-to-subtree)))
8511 (defun org-narrow-to-block ()
8512 "Narrow buffer to the current block."
8513 (interactive)
8514 (let* ((case-fold-search t)
8515 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8516 "^[ \t]*#\\+end_.*")))
8517 (if blockp
8518 (narrow-to-region (car blockp) (cdr blockp))
8519 (user-error "Not in a block"))))
8521 (defun org-clone-subtree-with-time-shift (n &optional shift)
8522 "Clone the task (subtree) at point N times.
8523 The clones will be inserted as siblings.
8525 In interactive use, the user will be prompted for the number of
8526 clones to be produced. If the entry has a timestamp, the user
8527 will also be prompted for a time shift, which may be a repeater
8528 as used in time stamps, for example `+3d'. To disable this,
8529 you can call the function with a universal prefix argument.
8531 When a valid repeater is given and the entry contains any time
8532 stamps, the clones will become a sequence in time, with time
8533 stamps in the subtree shifted for each clone produced. If SHIFT
8534 is nil or the empty string, time stamps will be left alone. The
8535 ID property of the original subtree is removed.
8537 In each clone, all the CLOCK entries will be removed. This
8538 prevents Org from considering that the clocked times overlap.
8540 If the original subtree did contain time stamps with a repeater,
8541 the following will happen:
8542 - the repeater will be removed in each clone
8543 - an additional clone will be produced, with the current, unshifted
8544 date(s) in the entry.
8545 - the original entry will be placed *after* all the clones, with
8546 repeater intact.
8547 - the start days in the repeater in the original entry will be shifted
8548 to past the last clone.
8549 In this way you can spell out a number of instances of a repeating task,
8550 and still retain the repeater to cover future instances of the task.
8552 As described above, N+1 clones are produced when the original
8553 subtree has a repeater. Setting N to 0, then, can be used to
8554 remove the repeater from a subtree and create a shifted clone
8555 with the original repeater."
8556 (interactive "nNumber of clones to produce: ")
8557 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8558 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8559 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8560 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8561 (shift
8562 (or shift
8563 (if (and (not (equal current-prefix-arg '(4)))
8564 (save-excursion
8565 (goto-char beg)
8566 (re-search-forward org-ts-regexp-both end-of-tree t)))
8567 (read-from-minibuffer
8568 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8569 ""))) ;No time shift
8570 (doshift
8571 (and (org-string-nw-p shift)
8572 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8573 shift)
8574 (user-error "Invalid shift specification %s" shift)))))
8575 (goto-char end-of-tree)
8576 (unless (bolp) (insert "\n"))
8577 (let* ((end (point))
8578 (template (buffer-substring beg end))
8579 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8580 (shift-what (pcase (and doshift (match-string 2 shift))
8581 (`nil nil)
8582 ("d" 'day)
8583 ("w" (setq shift-n (* 7 shift-n)) 'day)
8584 ("m" 'month)
8585 ("y" 'year)
8586 (_ (error "Unsupported time unit"))))
8587 (nmin 1)
8588 (nmax n)
8589 (n-no-remove -1)
8590 (idprop (org-entry-get nil "ID")))
8591 (when (and doshift
8592 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8593 template))
8594 (delete-region beg end)
8595 (setq end beg)
8596 (setq nmin 0)
8597 (setq nmax (1+ nmax))
8598 (setq n-no-remove nmax))
8599 (goto-char end)
8600 (cl-loop for n from nmin to nmax do
8601 (insert
8602 ;; Prepare clone.
8603 (with-temp-buffer
8604 (insert template)
8605 (org-mode)
8606 (goto-char (point-min))
8607 (org-show-subtree)
8608 (and idprop (if org-clone-delete-id
8609 (org-entry-delete nil "ID")
8610 (org-id-get-create t)))
8611 (unless (= n 0)
8612 (while (re-search-forward org-clock-line-re nil t)
8613 (delete-region (line-beginning-position)
8614 (line-beginning-position 2)))
8615 (goto-char (point-min))
8616 (while (re-search-forward org-drawer-regexp nil t)
8617 (org-remove-empty-drawer-at (point))))
8618 (goto-char (point-min))
8619 (when doshift
8620 (while (re-search-forward org-ts-regexp-both nil t)
8621 (org-timestamp-change (* n shift-n) shift-what))
8622 (unless (= n n-no-remove)
8623 (goto-char (point-min))
8624 (while (re-search-forward org-ts-regexp nil t)
8625 (save-excursion
8626 (goto-char (match-beginning 0))
8627 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8628 (delete-region (match-beginning 1) (match-end 1)))))))
8629 (buffer-string)))))
8630 (goto-char beg)))
8632 ;;; Outline Sorting
8634 (defun org-sort (&optional with-case)
8635 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8636 Optional argument WITH-CASE means sort case-sensitively."
8637 (interactive "P")
8638 (org-call-with-arg
8639 (cond ((org-at-table-p) #'org-table-sort-lines)
8640 ((org-at-item-p) #'org-sort-list)
8641 (t #'org-sort-entries))
8642 with-case))
8644 (defun org-sort-remove-invisible (s)
8645 "Remove invisible part of links and emphasis markers from string S."
8646 (remove-text-properties 0 (length s) org-rm-props s)
8647 (replace-regexp-in-string
8648 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8649 (replace-regexp-in-string
8650 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8651 (org-link-display-format s)
8652 t t) t t))
8654 (defvar org-priority-regexp) ; defined later in the file
8656 (defvar org-after-sorting-entries-or-items-hook nil
8657 "Hook that is run after a bunch of entries or items have been sorted.
8658 When children are sorted, the cursor is in the parent line when this
8659 hook gets called. When a region or a plain list is sorted, the cursor
8660 will be in the first entry of the sorted region/list.")
8662 (defun org-sort-entries
8663 (&optional with-case sorting-type getkey-func compare-func property
8664 interactive?)
8665 "Sort entries on a certain level of an outline tree.
8666 If there is an active region, the entries in the region are sorted.
8667 Else, if the cursor is before the first entry, sort the top-level items.
8668 Else, the children of the entry at point are sorted.
8670 Sorting can be alphabetically, numerically, by date/time as given by
8671 a time stamp, by a property, by priority order, or by a custom function.
8673 The command prompts for the sorting type unless it has been given to the
8674 function through the SORTING-TYPE argument, which needs to be a character,
8675 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8676 the precise meaning of each character:
8678 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8679 c By creation time, which is assumed to be the first inactive time stamp
8680 at the beginning of a line.
8681 d By deadline date/time.
8682 k By clocking time.
8683 n Numerically, by converting the beginning of the entry/item to a number.
8684 o By order of TODO keywords.
8685 p By priority according to the cookie.
8686 r By the value of a property.
8687 s By scheduled date/time.
8688 t By date/time, either the first active time stamp in the entry, or, if
8689 none exist, by the first inactive one.
8691 Capital letters will reverse the sort order.
8693 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8694 called with point at the beginning of the record. It must return a
8695 value that is compatible with COMPARE-FUNC, the function used to
8696 compare entries.
8698 Comparing entries ignores case by default. However, with an optional argument
8699 WITH-CASE, the sorting considers case as well.
8701 Sorting is done against the visible part of the headlines, it ignores hidden
8702 links.
8704 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8706 A non-nil value for INTERACTIVE? is used to signal that this
8707 function is being called interactively."
8708 (interactive (list current-prefix-arg nil nil nil nil t))
8709 (let ((case-func (if with-case 'identity 'downcase))
8710 start beg end stars re re2
8711 txt what tmp)
8712 ;; Find beginning and end of region to sort
8713 (cond
8714 ((org-region-active-p)
8715 ;; we will sort the region
8716 (setq end (region-end)
8717 what "region")
8718 (goto-char (region-beginning))
8719 (unless (org-at-heading-p) (outline-next-heading))
8720 (setq start (point)))
8721 ((or (org-at-heading-p)
8722 (ignore-errors (progn (org-back-to-heading) t)))
8723 ;; we will sort the children of the current headline
8724 (org-back-to-heading)
8725 (setq start (point)
8726 end (progn (org-end-of-subtree t t)
8727 (or (bolp) (insert "\n"))
8728 (when (>= (org-back-over-empty-lines) 1)
8729 (forward-line 1))
8730 (point))
8731 what "children")
8732 (goto-char start)
8733 (outline-show-subtree)
8734 (outline-next-heading))
8736 ;; we will sort the top-level entries in this file
8737 (goto-char (point-min))
8738 (or (org-at-heading-p) (outline-next-heading))
8739 (setq start (point))
8740 (goto-char (point-max))
8741 (beginning-of-line 1)
8742 (when (looking-at ".*?\\S-")
8743 ;; File ends in a non-white line
8744 (end-of-line 1)
8745 (insert "\n"))
8746 (setq end (point-max))
8747 (setq what "top-level")
8748 (goto-char start)
8749 (org-show-all '(headings blocks))))
8751 (setq beg (point))
8752 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8754 (looking-at "\\(\\*+\\)")
8755 (setq stars (match-string 1)
8756 re (concat "^" (regexp-quote stars) " +")
8757 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8758 txt (buffer-substring beg end))
8759 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8760 (when (and (not (equal stars "*")) (string-match re2 txt))
8761 (user-error "Region to sort contains a level above the first entry"))
8763 (unless sorting-type
8764 (message
8765 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8766 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8767 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8768 what)
8769 (setq sorting-type (read-char-exclusive)))
8771 (unless getkey-func
8772 (and (= (downcase sorting-type) ?f)
8773 (setq getkey-func
8774 (or (and interactive?
8775 (org-read-function
8776 "Function for extracting keys: "))
8777 (error "Missing key extractor")))))
8779 (and (= (downcase sorting-type) ?r)
8780 (not property)
8781 (setq property
8782 (completing-read "Property: "
8783 (mapcar #'list (org-buffer-property-keys t))
8784 nil t)))
8786 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8787 (message "Sorting entries...")
8789 (save-restriction
8790 (narrow-to-region start end)
8791 (let ((restore-clock?
8792 ;; The clock marker is lost when using `sort-subr'; mark
8793 ;; the clock with temporary `:org-clock-marker-backup'
8794 ;; text property.
8795 (when (and (eq (org-clock-is-active) (current-buffer))
8796 (<= start (marker-position org-clock-marker))
8797 (>= end (marker-position org-clock-marker)))
8798 (with-silent-modifications
8799 (put-text-property (1- org-clock-marker) org-clock-marker
8800 :org-clock-marker-backup t))
8802 (dcst (downcase sorting-type))
8803 (case-fold-search nil)
8804 (now (current-time)))
8805 (org-preserve-local-variables
8806 (sort-subr
8807 (/= dcst sorting-type)
8808 ;; This function moves to the beginning character of the
8809 ;; "record" to be sorted.
8810 (lambda nil
8811 (if (re-search-forward re nil t)
8812 (goto-char (match-beginning 0))
8813 (goto-char (point-max))))
8814 ;; This function moves to the last character of the "record" being
8815 ;; sorted.
8816 (lambda nil
8817 (save-match-data
8818 (condition-case nil
8819 (outline-forward-same-level 1)
8820 (error
8821 (goto-char (point-max))))))
8822 ;; This function returns the value that gets sorted against.
8823 (lambda ()
8824 (cond
8825 ((= dcst ?n)
8826 (string-to-number
8827 (org-sort-remove-invisible (org-get-heading t t t t))))
8828 ((= dcst ?a)
8829 (funcall case-func
8830 (org-sort-remove-invisible (org-get-heading t t t t))))
8831 ((= dcst ?k)
8832 (or (get-text-property (point) :org-clock-minutes) 0))
8833 ((= dcst ?t)
8834 (let ((end (save-excursion (outline-next-heading) (point))))
8835 (if (or (re-search-forward org-ts-regexp end t)
8836 (re-search-forward org-ts-regexp-both end t))
8837 (org-time-string-to-seconds (match-string 0))
8838 (float-time now))))
8839 ((= dcst ?c)
8840 (let ((end (save-excursion (outline-next-heading) (point))))
8841 (if (re-search-forward
8842 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8843 end t)
8844 (org-time-string-to-seconds (match-string 0))
8845 (float-time now))))
8846 ((= dcst ?s)
8847 (let ((end (save-excursion (outline-next-heading) (point))))
8848 (if (re-search-forward org-scheduled-time-regexp end t)
8849 (org-time-string-to-seconds (match-string 1))
8850 (float-time now))))
8851 ((= dcst ?d)
8852 (let ((end (save-excursion (outline-next-heading) (point))))
8853 (if (re-search-forward org-deadline-time-regexp end t)
8854 (org-time-string-to-seconds (match-string 1))
8855 (float-time now))))
8856 ((= dcst ?p)
8857 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8858 (string-to-char (match-string 2))
8859 org-default-priority))
8860 ((= dcst ?r)
8861 (or (org-entry-get nil property) ""))
8862 ((= dcst ?o)
8863 (when (looking-at org-complex-heading-regexp)
8864 (let* ((m (match-string 2))
8865 (s (if (member m org-done-keywords) '- '+)))
8866 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8867 ((= dcst ?f)
8868 (if getkey-func
8869 (progn
8870 (setq tmp (funcall getkey-func))
8871 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8872 tmp)
8873 (error "Invalid key function `%s'" getkey-func)))
8874 (t (error "Invalid sorting type `%c'" sorting-type))))
8876 (cond
8877 ((= dcst ?a) 'org-string-collate-lessp)
8878 ((= dcst ?f)
8879 (or compare-func
8880 (and interactive?
8881 (org-read-function
8882 (concat "Function for comparing keys "
8883 "(empty for default `sort-subr' predicate): ")
8884 'allow-empty))))
8885 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8886 (when restore-clock?
8887 (move-marker org-clock-marker
8888 (1+ (next-single-property-change
8889 start :org-clock-marker-backup)))
8890 (remove-text-properties (1- org-clock-marker) org-clock-marker
8891 '(:org-clock-marker-backup t)))))
8892 (run-hooks 'org-after-sorting-entries-or-items-hook)
8893 (message "Sorting entries...done")))
8895 (defun org-contextualize-keys (alist contexts)
8896 "Return valid elements in ALIST depending on CONTEXTS.
8898 `org-agenda-custom-commands' or `org-capture-templates' are the
8899 values used for ALIST, and `org-agenda-custom-commands-contexts'
8900 or `org-capture-templates-contexts' are the associated contexts
8901 definitions."
8902 (let ((contexts
8903 ;; normalize contexts
8904 (mapcar
8905 (lambda(c) (cond ((listp (cadr c))
8906 (list (car c) (car c) (nth 1 c)))
8907 ((string= "" (cadr c))
8908 (list (car c) (car c) (nth 2 c)))
8909 (t c)))
8910 contexts))
8911 (a alist) r s)
8912 ;; loop over all commands or templates
8913 (dolist (c a)
8914 (let (vrules repl)
8915 (cond
8916 ((not (assoc (car c) contexts))
8917 (push c r))
8918 ((and (assoc (car c) contexts)
8919 (setq vrules (org-contextualize-validate-key
8920 (car c) contexts)))
8921 (mapc (lambda (vr)
8922 (unless (equal (car vr) (cadr vr))
8923 (setq repl vr)))
8924 vrules)
8925 (if (not repl) (push c r)
8926 (push (cadr repl) s)
8927 (push
8928 (cons (car c)
8929 (cdr (or (assoc (cadr repl) alist)
8930 (error "Undefined key `%s' as contextual replacement for `%s'"
8931 (cadr repl) (car c)))))
8932 r))))))
8933 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8934 (delq
8936 (delete-dups
8937 (mapcar (lambda (x)
8938 (let ((tpl (car x)))
8939 (unless (delq
8941 (mapcar (lambda (y)
8942 (equal y tpl))
8944 x)))
8945 (reverse r))))))
8947 (defun org-contextualize-validate-key (key contexts)
8948 "Check CONTEXTS for agenda or capture KEY."
8949 (let (res)
8950 (dolist (r contexts)
8951 (dolist (rr (car (last r)))
8952 (when
8953 (and (equal key (car r))
8954 (if (functionp rr) (funcall rr)
8955 (or (and (eq (car rr) 'in-file)
8956 (buffer-file-name)
8957 (string-match (cdr rr) (buffer-file-name)))
8958 (and (eq (car rr) 'in-mode)
8959 (string-match (cdr rr) (symbol-name major-mode)))
8960 (and (eq (car rr) 'in-buffer)
8961 (string-match (cdr rr) (buffer-name)))
8962 (when (and (eq (car rr) 'not-in-file)
8963 (buffer-file-name))
8964 (not (string-match (cdr rr) (buffer-file-name))))
8965 (when (eq (car rr) 'not-in-mode)
8966 (not (string-match (cdr rr) (symbol-name major-mode))))
8967 (when (eq (car rr) 'not-in-buffer)
8968 (not (string-match (cdr rr) (buffer-name)))))))
8969 (push r res))))
8970 (delete-dups (delq nil res))))
8972 ;; Defined to provide a value for defcustom, since there is no
8973 ;; string-collate-greaterp in Emacs.
8974 (defun org-string-collate-greaterp (s1 s2)
8975 "Return non-nil if S1 is greater than S2 in collation order."
8976 (not (org-string-collate-lessp s1 s2)))
8978 ;;;###autoload
8979 (defun org-run-like-in-org-mode (cmd)
8980 "Run a command, pretending that the current buffer is in Org mode.
8981 This will temporarily bind local variables that are typically bound in
8982 Org mode to the values they have in Org mode, and then interactively
8983 call CMD."
8984 (org-load-modules-maybe)
8985 (let (binds)
8986 (dolist (var (org-get-local-variables))
8987 (when (or (not (boundp (car var)))
8988 (eq (symbol-value (car var))
8989 (default-value (car var))))
8990 (push (list (car var) `(quote ,(cadr var))) binds)))
8991 (eval `(let ,binds
8992 (call-interactively (quote ,cmd))))))
8994 (defun org-get-category (&optional pos force-refresh)
8995 "Get the category applying to position POS."
8996 (save-match-data
8997 (when force-refresh (org-refresh-category-properties))
8998 (let ((pos (or pos (point))))
8999 (or (get-text-property pos 'org-category)
9000 (progn (org-refresh-category-properties)
9001 (get-text-property pos 'org-category))))))
9003 ;;; Refresh properties
9005 (defun org-refresh-properties (dprop tprop)
9006 "Refresh buffer text properties.
9007 DPROP is the drawer property and TPROP is either the
9008 corresponding text property to set, or an alist with each element
9009 being a text property (as a symbol) and a function to apply to
9010 the value of the drawer property."
9011 (let* ((case-fold-search t)
9012 (inhibit-read-only t)
9013 (inherit? (org-property-inherit-p dprop))
9014 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9015 (global (and inherit? (org--property-global-value dprop nil))))
9016 (with-silent-modifications
9017 (org-with-point-at 1
9018 ;; Set global values (e.g., values defined through
9019 ;; "#+PROPERTY:" keywords) to the whole buffer.
9020 (when global (put-text-property (point-min) (point-max) tprop global))
9021 ;; Set local values.
9022 (while (re-search-forward property-re nil t)
9023 (when (org-at-property-p)
9024 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9025 (outline-next-heading))))))
9027 (defun org-refresh-property (tprop p &optional inherit)
9028 "Refresh the buffer text property TPROP from the drawer property P.
9029 The refresh happens only for the current headline, or the whole
9030 sub-tree if optional argument INHERIT is non-nil."
9031 (unless (org-before-first-heading-p)
9032 (save-excursion
9033 (org-back-to-heading t)
9034 (let ((start (point))
9035 (end (save-excursion
9036 (if inherit (org-end-of-subtree t t)
9037 (or (outline-next-heading) (point-max))))))
9038 (if (symbolp tprop)
9039 ;; TPROP is a text property symbol.
9040 (put-text-property start end tprop p)
9041 ;; TPROP is an alist with (property . function) elements.
9042 (pcase-dolist (`(,prop . ,f) tprop)
9043 (put-text-property start end prop (funcall f p))))))))
9045 (defun org-refresh-category-properties ()
9046 "Refresh category text properties in the buffer."
9047 (let ((case-fold-search t)
9048 (inhibit-read-only t)
9049 (default-category
9050 (cond ((null org-category)
9051 (if buffer-file-name
9052 (file-name-sans-extension
9053 (file-name-nondirectory buffer-file-name))
9054 "???"))
9055 ((symbolp org-category) (symbol-name org-category))
9056 (t org-category))))
9057 (with-silent-modifications
9058 (org-with-wide-buffer
9059 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9060 ;; This is the default category for the buffer. If none is
9061 ;; found, fall-back to `org-category' or buffer file name.
9062 (put-text-property
9063 (point-min) (point-max)
9064 'org-category
9065 (catch 'buffer-category
9066 (goto-char (point-max))
9067 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9068 (let ((element (org-element-at-point)))
9069 (when (eq (org-element-type element) 'keyword)
9070 (throw 'buffer-category
9071 (org-element-property :value element)))))
9072 default-category))
9073 ;; Set sub-tree specific categories.
9074 (goto-char (point-min))
9075 (let ((regexp (org-re-property "CATEGORY")))
9076 (while (re-search-forward regexp nil t)
9077 (let ((value (match-string-no-properties 3)))
9078 (when (org-at-property-p)
9079 (put-text-property
9080 (save-excursion (org-back-to-heading t) (point))
9081 (save-excursion (org-end-of-subtree t t) (point))
9082 'org-category
9083 value)))))))))
9085 (defun org-refresh-stats-properties ()
9086 "Refresh stats text properties in the buffer."
9087 (with-silent-modifications
9088 (org-with-point-at 1
9089 (let ((regexp (concat org-outline-regexp-bol
9090 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9091 (while (re-search-forward regexp nil t)
9092 (let* ((numerator (string-to-number (match-string 1)))
9093 (denominator (and (match-end 2)
9094 (string-to-number (match-string 2))))
9095 (stats (cond ((not denominator) numerator) ;percent
9096 ((= denominator 0) 0)
9097 (t (/ (* numerator 100) denominator)))))
9098 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9099 'org-stats stats)))))))
9101 (defun org-refresh-effort-properties ()
9102 "Refresh effort properties"
9103 (org-refresh-properties
9104 org-effort-property
9105 '((effort . identity)
9106 (effort-minutes . org-duration-to-minutes))))
9108 ;;;; Link Stuff
9110 ;;; Link abbreviations
9112 (defun org-link-expand-abbrev (link)
9113 "Apply replacements as defined in `org-link-abbrev-alist'."
9114 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9115 (let* ((key (match-string 1 link))
9116 (as (or (assoc key org-link-abbrev-alist-local)
9117 (assoc key org-link-abbrev-alist)))
9118 (tag (and (match-end 2) (match-string 3 link)))
9119 rpl)
9120 (if (not as)
9121 link
9122 (setq rpl (cdr as))
9123 (cond
9124 ((symbolp rpl) (funcall rpl tag))
9125 ((string-match "%(\\([^)]+\\))" rpl)
9126 (replace-match
9127 (save-match-data
9128 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9129 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9130 ((string-match "%h" rpl)
9131 (replace-match (url-hexify-string (or tag "")) t t rpl))
9132 (t (concat rpl tag)))))
9133 link))
9135 ;;; Storing and inserting links
9137 (defvar org-insert-link-history nil
9138 "Minibuffer history for links inserted with `org-insert-link'.")
9140 (defvar org-stored-links nil
9141 "Contains the links stored with `org-store-link'.")
9143 (defvar org-store-link-plist nil
9144 "Plist with info about the most recently link created with `org-store-link'.")
9146 (defun org-store-link-functions ()
9147 "Return a list of functions that are called to create and store a link.
9148 The functions defined in the :store property of
9149 `org-link-parameters'.
9151 Each function will be called in turn until one returns a non-nil
9152 value. Each function should check if it is responsible for
9153 creating this link (for example by looking at the major mode).
9154 If not, it must exit and return nil. If yes, it should return
9155 a non-nil value after calling `org-store-link-props' with a list
9156 of properties and values. Special properties are:
9158 :type The link prefix, like \"http\". This must be given.
9159 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9160 This is obligatory as well.
9161 :description Optional default description for the second pair
9162 of brackets in an Org mode link. The user can still change
9163 this when inserting this link into an Org mode buffer.
9165 In addition to these, any additional properties can be specified
9166 and then used in capture templates."
9167 (cl-loop for link in org-link-parameters
9168 with store-func
9169 do (setq store-func (org-link-get-parameter (car link) :store))
9170 if store-func
9171 collect store-func))
9173 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9174 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9176 ;;;###autoload
9177 (defun org-store-link (arg &optional interactive?)
9178 "Store a link to the current location.
9179 \\<org-mode-map>
9180 This link is added to `org-stored-links' and can later be inserted
9181 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9183 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9184 A single
9185 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9186 `org-gnus-prefer-web-links' for links to Usenet articles.
9188 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9189 skipping storing functions that are not
9190 part of Org core.
9192 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9193 prefix ARG forces storing a link for each line in the
9194 active region.
9196 Assume the function is called interactively if INTERACTIVE? is
9197 non-nil."
9198 (interactive "P\np")
9199 (org-load-modules-maybe)
9200 (if (and (equal arg '(64)) (org-region-active-p))
9201 (save-excursion
9202 (let ((end (region-end)))
9203 (goto-char (region-beginning))
9204 (set-mark (point))
9205 (while (< (point-at-eol) end)
9206 (move-end-of-line 1) (activate-mark)
9207 (let (current-prefix-arg)
9208 (call-interactively 'org-store-link))
9209 (move-beginning-of-line 2)
9210 (set-mark (point)))))
9211 (setq org-store-link-plist nil)
9212 (let (link cpltxt desc description search txt custom-id agenda-link)
9213 (cond
9214 ;; Store a link using an external link type, if any function is
9215 ;; available. If more than one can generate a link from current
9216 ;; location, ask which one to use.
9217 ((and (not (equal arg '(16)))
9218 (let ((results-alist nil))
9219 (dolist (f (org-store-link-functions))
9220 (when (funcall f)
9221 ;; XXX: return value is not link's plist, so we
9222 ;; store the new value before it is modified. It
9223 ;; would be cleaner to ask store link functions to
9224 ;; return the plist instead.
9225 (push (cons f (copy-sequence org-store-link-plist))
9226 results-alist)))
9227 (pcase results-alist
9228 (`nil nil)
9229 (`((,_ . ,_)) t) ;single choice: nothing to do
9230 (`((,name . ,_) . ,_)
9231 ;; Reinstate link plist associated to the chosen
9232 ;; function.
9233 (apply #'org-store-link-props
9234 (cdr (assoc-string
9235 (completing-read
9236 "Which function for creating the link? "
9237 (mapcar #'car results-alist)
9238 nil t (symbol-name name))
9239 results-alist)))
9240 t))))
9241 (setq link (plist-get org-store-link-plist :link))
9242 (setq desc (or (plist-get org-store-link-plist :description)
9243 link)))
9245 ;; Store a link from a remote editing buffer.
9246 ((org-src-edit-buffer-p)
9247 (let ((coderef-format (org-src-coderef-format)))
9248 (cond
9249 ;; A code reference exists. Use it.
9250 ((save-excursion
9251 (beginning-of-line)
9252 (re-search-forward (org-src-coderef-regexp coderef-format)
9253 (line-end-position)
9255 (setq link (format "(%s)" (match-string-no-properties 3))))
9256 ;; No code reference. Create a new one then store the link
9257 ;; to it, but only in the function is called interactively.
9258 (interactive?
9259 (end-of-line)
9260 (let* ((label (read-string "Code line label: "))
9261 (reference (format coderef-format label))
9262 (gc (- 79 (length link))))
9263 (if (< (current-column) gc)
9264 (org-move-to-column gc t)
9265 (insert " "))
9266 (insert reference)
9267 (setq link (format "(%s)" label))))
9268 (t (setq link nil)))))
9270 ;; We are in the agenda, link to referenced location
9271 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9272 (let ((m (or (get-text-property (point) 'org-hd-marker)
9273 (get-text-property (point) 'org-marker))))
9274 (when m
9275 (org-with-point-at m
9276 (setq agenda-link (org-store-link nil interactive?))))))
9278 ((eq major-mode 'calendar-mode)
9279 (let ((cd (calendar-cursor-to-date)))
9280 (setq link
9281 (format-time-string
9282 (car org-time-stamp-formats)
9283 (apply 'encode-time
9284 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9285 nil nil nil))))
9286 (org-store-link-props :type "calendar" :date cd)))
9288 ((eq major-mode 'help-mode)
9289 (setq link (concat "help:" (save-excursion
9290 (goto-char (point-min))
9291 (looking-at "^[^ ]+")
9292 (match-string 0))))
9293 (org-store-link-props :type "help"))
9295 ((eq major-mode 'w3-mode)
9296 (setq cpltxt (if (and (buffer-name)
9297 (not (string-match "Untitled" (buffer-name))))
9298 (buffer-name)
9299 (url-view-url t))
9300 link (url-view-url t))
9301 (org-store-link-props :type "w3" :url (url-view-url t)))
9303 ((eq major-mode 'image-mode)
9304 (setq cpltxt (concat "file:"
9305 (abbreviate-file-name buffer-file-name))
9306 link cpltxt)
9307 (org-store-link-props :type "image" :file buffer-file-name))
9309 ;; In dired, store a link to the file of the current line
9310 ((derived-mode-p 'dired-mode)
9311 (let ((file (dired-get-filename nil t)))
9312 (setq file (if file
9313 (abbreviate-file-name
9314 (expand-file-name (dired-get-filename nil t)))
9315 ;; otherwise, no file so use current directory.
9316 default-directory))
9317 (setq cpltxt (concat "file:" file)
9318 link cpltxt)))
9320 ((setq search (run-hook-with-args-until-success
9321 'org-create-file-search-functions))
9322 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9323 "::" search))
9324 (setq cpltxt (or description link)))
9326 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9327 (org-with-limited-levels
9328 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9329 (cond
9330 ;; Store a link using the target at point
9331 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9332 (setq cpltxt
9333 (concat "file:"
9334 (abbreviate-file-name
9335 (buffer-file-name (buffer-base-buffer)))
9336 "::" (match-string 1))
9337 link cpltxt))
9338 ((and (featurep 'org-id)
9339 (or (eq org-id-link-to-org-use-id t)
9340 (and interactive?
9341 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9342 (and (eq org-id-link-to-org-use-id
9343 'create-if-interactive-and-no-custom-id)
9344 (not custom-id))))
9345 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9346 ;; Store a link using the ID at point
9347 (setq link (condition-case nil
9348 (prog1 (org-id-store-link)
9349 (setq desc (or (plist-get org-store-link-plist
9350 :description)
9351 "")))
9352 (error
9353 ;; Probably before first headline, link only to file
9354 (concat "file:"
9355 (abbreviate-file-name
9356 (buffer-file-name (buffer-base-buffer))))))))
9358 ;; Just link to current headline
9359 (setq cpltxt (concat "file:"
9360 (abbreviate-file-name
9361 (buffer-file-name (buffer-base-buffer)))))
9362 ;; Add a context search string
9363 (when (org-xor org-context-in-file-links
9364 (equal arg '(4)))
9365 (let* ((element (org-element-at-point))
9366 (name (org-element-property :name element)))
9367 (setq txt (cond
9368 ((org-at-heading-p) nil)
9369 (name)
9370 ((org-region-active-p)
9371 (buffer-substring (region-beginning) (region-end)))))
9372 (when (or (null txt) (string-match "\\S-" txt))
9373 (setq cpltxt
9374 (concat cpltxt "::"
9375 (condition-case nil
9376 (org-make-org-heading-search-string txt)
9377 (error "")))
9378 desc (or name
9379 (nth 4 (ignore-errors (org-heading-components)))
9380 "NONE")))))
9381 (when (string-match "::\\'" cpltxt)
9382 (setq cpltxt (substring cpltxt 0 -2)))
9383 (setq link cpltxt)))))
9385 ((buffer-file-name (buffer-base-buffer))
9386 ;; Just link to this file here.
9387 (setq cpltxt (concat "file:"
9388 (abbreviate-file-name
9389 (buffer-file-name (buffer-base-buffer)))))
9390 ;; Add a context string.
9391 (when (org-xor org-context-in-file-links
9392 (equal arg '(4)))
9393 (setq txt (if (org-region-active-p)
9394 (buffer-substring (region-beginning) (region-end))
9395 (buffer-substring (point-at-bol) (point-at-eol))))
9396 ;; Only use search option if there is some text.
9397 (when (string-match "\\S-" txt)
9398 (setq cpltxt
9399 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9400 desc "NONE")))
9401 (setq link cpltxt))
9403 (interactive?
9404 (user-error "No method for storing a link from this buffer"))
9406 (t (setq link nil)))
9408 ;; We're done setting link and desc, clean up
9409 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9410 (setq link (or link cpltxt)
9411 desc (or desc cpltxt))
9412 (cond ((not desc))
9413 ((equal desc "NONE") (setq desc nil))
9414 (t (setq desc
9415 (replace-regexp-in-string
9416 org-bracket-link-analytic-regexp
9417 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9418 desc))))
9419 ;; Return the link
9420 (if (not (and interactive? link))
9421 (or agenda-link (and link (org-make-link-string link desc)))
9422 (push (list link desc) org-stored-links)
9423 (message "Stored: %s" (or desc link))
9424 (when custom-id
9425 (setq link (concat "file:" (abbreviate-file-name
9426 (buffer-file-name)) "::#" custom-id))
9427 (push (list link desc) org-stored-links))
9428 (car org-stored-links)))))
9430 (defun org-store-link-props (&rest plist)
9431 "Store link properties.
9432 The properties are pre-processed by extracting names, addresses
9433 and dates."
9434 (let ((x (plist-get plist :from)))
9435 (when x
9436 (let ((adr (mail-extract-address-components x)))
9437 (setq plist (plist-put plist :fromname (car adr)))
9438 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9439 (let ((x (plist-get plist :to)))
9440 (when x
9441 (let ((adr (mail-extract-address-components x)))
9442 (setq plist (plist-put plist :toname (car adr)))
9443 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9444 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9445 (when x
9446 (setq plist (plist-put plist :date-timestamp
9447 (format-time-string
9448 (org-time-stamp-format t) x)))
9449 (setq plist (plist-put plist :date-timestamp-inactive
9450 (format-time-string
9451 (org-time-stamp-format t t) x)))))
9452 (let ((from (plist-get plist :from))
9453 (to (plist-get plist :to)))
9454 (when (and from to org-from-is-user-regexp)
9455 (setq plist
9456 (plist-put plist :fromto
9457 (if (string-match org-from-is-user-regexp from)
9458 (concat "to %t")
9459 (concat "from %f"))))))
9460 (setq org-store-link-plist plist))
9462 (defun org-add-link-props (&rest plist)
9463 "Add these properties to the link property list."
9464 (let (key value)
9465 (while plist
9466 (setq key (pop plist) value (pop plist))
9467 (setq org-store-link-plist
9468 (plist-put org-store-link-plist key value)))))
9470 (defun org-email-link-description (&optional fmt)
9471 "Return the description part of an email link.
9472 This takes information from `org-store-link-plist' and formats it
9473 according to FMT (default from `org-email-link-description-format')."
9474 (setq fmt (or fmt org-email-link-description-format))
9475 (let* ((p org-store-link-plist)
9476 (to (plist-get p :toaddress))
9477 (from (plist-get p :fromaddress))
9478 (table
9479 (list
9480 (cons "%c" (plist-get p :fromto))
9481 (cons "%F" (plist-get p :from))
9482 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9483 (cons "%T" (plist-get p :to))
9484 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9485 (cons "%s" (plist-get p :subject))
9486 (cons "%d" (plist-get p :date))
9487 (cons "%m" (plist-get p :message-id)))))
9488 (when (string-match "%c" fmt)
9489 ;; Check if the user wrote this message
9490 (if (and org-from-is-user-regexp from to
9491 (save-match-data (string-match org-from-is-user-regexp from)))
9492 (setq fmt (replace-match "to %t" t t fmt))
9493 (setq fmt (replace-match "from %f" t t fmt))))
9494 (org-replace-escapes fmt table)))
9496 (defun org-make-org-heading-search-string (&optional string)
9497 "Make search string for the current headline or STRING."
9498 (let ((s (or string
9499 (and (derived-mode-p 'org-mode)
9500 (save-excursion
9501 (org-back-to-heading t)
9502 (org-element-property :raw-value (org-element-at-point))))))
9503 (lines org-context-in-file-links))
9504 (unless string (setq s (concat "*" s))) ;Add * for headlines
9505 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9506 (when (and string (integerp lines) (> lines 0))
9507 (let ((slines (org-split-string s "\n")))
9508 (when (< lines (length slines))
9509 (setq s (mapconcat
9510 'identity
9511 (reverse (nthcdr (- (length slines) lines)
9512 (reverse slines))) "\n")))))
9513 (mapconcat #'identity (split-string s) " ")))
9515 (defconst org-link-escape-chars
9516 ;;%20 %5B %5D %25
9517 '(?\s ?\[ ?\] ?%)
9518 "List of characters that should be escaped in a link when stored to Org.
9519 This is the list that is used for internal purposes.")
9521 (defun org-make-link-string (link &optional description)
9522 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9523 (unless (org-string-nw-p link) (error "Empty link"))
9524 (let ((uri (cond ((string-match org-link-types-re link)
9525 (concat (match-string 1 link)
9526 (org-link-escape (substring link (match-end 1)))))
9527 ((or (file-name-absolute-p link)
9528 (string-match-p "\\`\\.\\.?/" link))
9529 (org-link-escape link))
9530 ;; For readability, do not encode space characters
9531 ;; in fuzzy links.
9532 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9533 (description
9534 (and (org-string-nw-p description)
9535 ;; Remove brackets from description, as they are fatal.
9536 (replace-regexp-in-string
9537 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9538 (org-trim description)))))
9539 (format "[[%s]%s]"
9541 (if description (format "[%s]" description) ""))))
9543 (defun org-link-escape (text &optional table merge)
9544 "Return percent escaped representation of TEXT.
9545 TEXT is a string with the text to escape.
9546 Optional argument TABLE is a list with characters that should be
9547 escaped. When nil, `org-link-escape-chars' is used.
9548 If optional argument MERGE is set, merge TABLE into
9549 `org-link-escape-chars'."
9550 (let ((characters-to-encode
9551 (cond ((null table) org-link-escape-chars)
9552 (merge (append org-link-escape-chars table))
9553 (t table))))
9554 (mapconcat
9555 (lambda (c)
9556 (if (or (memq c characters-to-encode)
9557 (and org-url-hexify-p (or (< c 32) (> c 126))))
9558 (mapconcat (lambda (e) (format "%%%.2X" e))
9559 (or (encode-coding-char c 'utf-8)
9560 (error "Unable to percent escape character: %c" c))
9562 (char-to-string c)))
9563 text "")))
9565 (defun org-link-unescape (str)
9566 "Unhex hexified Unicode parts in string STR.
9567 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9568 reciprocal of `org-link-escape', which see."
9569 (if (org-string-nw-p str)
9570 (replace-regexp-in-string
9571 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9572 str))
9574 (defun org-link-unescape-compound (hex)
9575 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9576 Note: this function also decodes single byte encodings like
9577 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9578 (save-match-data
9579 (let* ((bytes (cdr (split-string hex "%")))
9580 (ret "")
9581 (eat 0)
9582 (sum 0))
9583 (while bytes
9584 (let* ((val (string-to-number (pop bytes) 16))
9585 (shift-xor
9586 (if (= 0 eat)
9587 (cond
9588 ((>= val 252) (cons 6 252))
9589 ((>= val 248) (cons 5 248))
9590 ((>= val 240) (cons 4 240))
9591 ((>= val 224) (cons 3 224))
9592 ((>= val 192) (cons 2 192))
9593 (t (cons 0 0)))
9594 (cons 6 128))))
9595 (when (>= val 192) (setq eat (car shift-xor)))
9596 (setq val (logxor val (cdr shift-xor)))
9597 (setq sum (+ (lsh sum (car shift-xor)) val))
9598 (when (> eat 0) (setq eat (- eat 1)))
9599 (cond
9600 ((= 0 eat) ;multi byte
9601 (setq ret (concat ret (char-to-string sum)))
9602 (setq sum 0))
9603 ((not bytes) ; single byte(s)
9604 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9605 ret)))
9607 (defun org-link-unescape-single-byte-sequence (hex)
9608 "Unhexify hex-encoded single byte character sequences."
9609 (mapconcat (lambda (byte)
9610 (char-to-string (string-to-number byte 16)))
9611 (cdr (split-string hex "%")) ""))
9613 (defun org-fixup-message-id-for-http (s)
9614 "Replace special characters in a message id, so it can be used in an http query."
9615 (when (string-match "%" s)
9616 (setq s (mapconcat (lambda (c)
9617 (if (eq c ?%)
9618 "%25"
9619 (char-to-string c)))
9620 s "")))
9621 (while (string-match "<" s)
9622 (setq s (replace-match "%3C" t t s)))
9623 (while (string-match ">" s)
9624 (setq s (replace-match "%3E" t t s)))
9625 (while (string-match "@" s)
9626 (setq s (replace-match "%40" t t s)))
9629 (defun org-link-prettify (link)
9630 "Return a human-readable representation of LINK.
9631 The car of LINK must be a raw link.
9632 The cdr of LINK must be either a link description or nil."
9633 (let ((desc (or (cadr link) "<no description>")))
9634 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9635 "<" (car link) ">")))
9637 ;;;###autoload
9638 (defun org-insert-link-global ()
9639 "Insert a link like Org mode does.
9640 This command can be called in any mode to insert a link in Org syntax."
9641 (interactive)
9642 (org-load-modules-maybe)
9643 (org-run-like-in-org-mode 'org-insert-link))
9645 (defun org-insert-all-links (arg &optional pre post)
9646 "Insert all links in `org-stored-links'.
9647 When a universal prefix, do not delete the links from `org-stored-links'.
9648 When `ARG' is a number, insert the last N link(s).
9649 `PRE' and `POST' are optional arguments to define a string to
9650 prepend or to append."
9651 (interactive "P")
9652 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9653 (links (copy-sequence org-stored-links))
9654 (pr (or pre "- "))
9655 (po (or post "\n"))
9656 (cnt 1) l)
9657 (if (null org-stored-links)
9658 (message "No link to insert")
9659 (while (and (or (listp arg) (>= arg cnt))
9660 (setq l (if (listp arg)
9661 (pop links)
9662 (pop org-stored-links))))
9663 (setq cnt (1+ cnt))
9664 (insert pr)
9665 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9666 (insert po)))))
9668 (defun org-insert-last-stored-link (arg)
9669 "Insert the last link stored in `org-stored-links'."
9670 (interactive "p")
9671 (org-insert-all-links arg "" "\n"))
9673 (defun org-link-fontify-links-to-this-file ()
9674 "Fontify links to the current file in `org-stored-links'."
9675 (let ((f (buffer-file-name)) a b)
9676 (setq a (mapcar (lambda(l)
9677 (let ((ll (car l)))
9678 (when (and (string-match "^file:\\(.+\\)::" ll)
9679 (equal f (expand-file-name (match-string 1 ll))))
9680 ll)))
9681 org-stored-links))
9682 (when (featurep 'org-id)
9683 (setq b (mapcar (lambda(l)
9684 (let ((ll (car l)))
9685 (when (and (string-match "^id:\\(.+\\)$" ll)
9686 (equal f (expand-file-name
9687 (or (org-id-find-id-file
9688 (match-string 1 ll)) ""))))
9689 ll)))
9690 org-stored-links)))
9691 (mapcar (lambda(l)
9692 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9693 (delq nil (append a b)))))
9695 (defvar org--links-history nil)
9696 (defun org-insert-link (&optional complete-file link-location default-description)
9697 "Insert a link. At the prompt, enter the link.
9699 Completion can be used to insert any of the link protocol prefixes in use.
9701 The history can be used to select a link previously stored with
9702 `org-store-link'. When the empty string is entered (i.e. if you just
9703 press `RET' at the prompt), the link defaults to the most recently
9704 stored link. As `SPC' triggers completion in the minibuffer, you need to
9705 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9707 You will also be prompted for a description, and if one is given, it will
9708 be displayed in the buffer instead of the link.
9710 If there is already a link at point, this command will allow you to edit
9711 link and description parts.
9713 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9714 file name can be
9715 selected using completion. The path to the file will be relative to the
9716 current directory if the file is in the current directory or a subdirectory.
9717 Otherwise, the link will be the absolute path as completed in the minibuffer
9718 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9719 option `org-link-file-path-type'.
9721 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9722 absolute path even if the file is in
9723 the current directory or below.
9725 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9726 prefix negates `org-keep-stored-link-after-insertion'.
9728 If the LINK-LOCATION parameter is non-nil, this value will be used as
9729 the link location instead of reading one interactively.
9731 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9732 be used as the default description. Otherwise, if
9733 `org-make-link-description-function' is non-nil, this function
9734 will be called with the link target, and the result will be the
9735 default link description. When called non-interactivily, don't
9736 allow to edit the default description."
9737 (interactive "P")
9738 (let* ((wcf (current-window-configuration))
9739 (origbuf (current-buffer))
9740 (region (when (org-region-active-p)
9741 (buffer-substring (region-beginning) (region-end))))
9742 (remove (and region (list (region-beginning) (region-end))))
9743 (desc region)
9744 (link link-location)
9745 (abbrevs org-link-abbrev-alist-local)
9746 entry all-prefixes auto-desc)
9747 (cond
9748 (link-location) ; specified by arg, just use it.
9749 ((org-in-regexp org-bracket-link-regexp 1)
9750 ;; We do have a link at point, and we are going to edit it.
9751 (setq remove (list (match-beginning 0) (match-end 0)))
9752 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9753 (setq link (read-string "Link: "
9754 (org-link-unescape
9755 (match-string-no-properties 1)))))
9756 ((or (org-in-regexp org-angle-link-re)
9757 (org-in-regexp org-plain-link-re))
9758 ;; Convert to bracket link
9759 (setq remove (list (match-beginning 0) (match-end 0))
9760 link (read-string "Link: "
9761 (org-unbracket-string "<" ">" (match-string 0)))))
9762 ((member complete-file '((4) (16)))
9763 ;; Completing read for file names.
9764 (setq link (org-file-complete-link complete-file)))
9766 ;; Read link, with completion for stored links.
9767 (org-link-fontify-links-to-this-file)
9768 (org-switch-to-buffer-other-window "*Org Links*")
9769 (with-current-buffer "*Org Links*"
9770 (erase-buffer)
9771 (insert "Insert a link.
9772 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9773 (when org-stored-links
9774 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9775 (insert (mapconcat 'org-link-prettify
9776 (reverse org-stored-links) "\n")))
9777 (goto-char (point-min)))
9778 (let ((cw (selected-window)))
9779 (select-window (get-buffer-window "*Org Links*" 'visible))
9780 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9781 (unless (pos-visible-in-window-p (point-max))
9782 (org-fit-window-to-buffer))
9783 (and (window-live-p cw) (select-window cw)))
9784 (setq all-prefixes (append (mapcar 'car abbrevs)
9785 (mapcar 'car org-link-abbrev-alist)
9786 (org-link-types)))
9787 (unwind-protect
9788 ;; Fake a link history, containing the stored links.
9789 (let ((org--links-history
9790 (append (mapcar #'car org-stored-links)
9791 org-insert-link-history)))
9792 (setq link
9793 (org-completing-read
9794 "Link: "
9795 (append
9796 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9797 (mapcar #'car org-stored-links))
9798 nil nil nil
9799 'org--links-history
9800 (caar org-stored-links)))
9801 (unless (org-string-nw-p link) (user-error "No link selected"))
9802 (dolist (l org-stored-links)
9803 (when (equal link (cadr l))
9804 (setq link (car l))
9805 (setq auto-desc t)))
9806 (when (or (member link all-prefixes)
9807 (and (equal ":" (substring link -1))
9808 (member (substring link 0 -1) all-prefixes)
9809 (setq link (substring link 0 -1))))
9810 (setq link (with-current-buffer origbuf
9811 (org-link-try-special-completion link)))))
9812 (set-window-configuration wcf)
9813 (kill-buffer "*Org Links*"))
9814 (setq entry (assoc link org-stored-links))
9815 (or entry (push link org-insert-link-history))
9816 (setq desc (or desc (nth 1 entry)))))
9818 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9819 (not org-keep-stored-link-after-insertion))
9820 (setq org-stored-links (delq (assoc link org-stored-links)
9821 org-stored-links)))
9823 (when (and (string-match org-plain-link-re link)
9824 (not (string-match org-ts-regexp link)))
9825 ;; URL-like link, normalize the use of angular brackets.
9826 (setq link (org-unbracket-string "<" ">" link)))
9828 ;; Check if we are linking to the current file with a search
9829 ;; option If yes, simplify the link by using only the search
9830 ;; option.
9831 (when (and buffer-file-name
9832 (let ((case-fold-search nil))
9833 (string-match "\\`file:\\(.+?\\)::" link)))
9834 (let ((path (match-string-no-properties 1 link))
9835 (search (substring-no-properties link (match-end 0))))
9836 (save-match-data
9837 (when (equal (file-truename buffer-file-name) (file-truename path))
9838 ;; We are linking to this same file, with a search option
9839 (setq link search)))))
9841 ;; Check if we can/should use a relative path. If yes, simplify
9842 ;; the link.
9843 (let ((case-fold-search nil))
9844 (when (string-match "\\`\\(file\\|docview\\):" link)
9845 (let* ((type (match-string-no-properties 0 link))
9846 (path-start (match-end 0))
9847 (search (and (string-match "::\\(.*\\)\\'" link)
9848 (match-string 1 link)))
9849 (path
9850 (if search
9851 (substring-no-properties
9852 link path-start (match-beginning 0))
9853 (substring-no-properties link (match-end 0))))
9854 (origpath path))
9855 (cond
9856 ((or (eq org-link-file-path-type 'absolute)
9857 (equal complete-file '(16)))
9858 (setq path (abbreviate-file-name (expand-file-name path))))
9859 ((eq org-link-file-path-type 'noabbrev)
9860 (setq path (expand-file-name path)))
9861 ((eq org-link-file-path-type 'relative)
9862 (setq path (file-relative-name path)))
9864 (save-match-data
9865 (if (string-match (concat "^" (regexp-quote
9866 (expand-file-name
9867 (file-name-as-directory
9868 default-directory))))
9869 (expand-file-name path))
9870 ;; We are linking a file with relative path name.
9871 (setq path (substring (expand-file-name path)
9872 (match-end 0)))
9873 (setq path (abbreviate-file-name (expand-file-name path)))))))
9874 (setq link (concat type path (and search (concat "::" search))))
9875 (when (equal desc origpath)
9876 (setq desc path)))))
9878 (unless auto-desc
9879 (let ((initial-input
9880 (cond
9881 (default-description)
9882 ((not org-make-link-description-function) desc)
9883 (t (condition-case nil
9884 (funcall org-make-link-description-function link desc)
9885 (error
9886 (message "Can't get link description from `%s'"
9887 (symbol-name org-make-link-description-function))
9888 (sit-for 2)
9889 nil))))))
9890 (setq desc (if (called-interactively-p 'any)
9891 (read-string "Description: " initial-input)
9892 initial-input))))
9894 (unless (string-match "\\S-" desc) (setq desc nil))
9895 (when remove (apply 'delete-region remove))
9896 (insert (org-make-link-string link desc))
9897 ;; Redisplay so as the new link has proper invisible characters.
9898 (sit-for 0)))
9900 (defun org-link-try-special-completion (type)
9901 "If there is completion support for link type TYPE, offer it."
9902 (let ((fun (org-link-get-parameter type :complete)))
9903 (if (functionp fun)
9904 (funcall fun)
9905 (read-string "Link (no completion support): " (concat type ":")))))
9907 (defun org-file-complete-link (&optional arg)
9908 "Create a file link using completion."
9909 (let ((file (read-file-name "File: "))
9910 (pwd (file-name-as-directory (expand-file-name ".")))
9911 (pwd1 (file-name-as-directory (abbreviate-file-name
9912 (expand-file-name ".")))))
9913 (cond ((equal arg '(16))
9914 (concat "file:"
9915 (abbreviate-file-name (expand-file-name file))))
9916 ((string-match
9917 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9918 (concat "file:" (match-string 1 file)))
9919 ((string-match
9920 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9921 (expand-file-name file))
9922 (concat "file:"
9923 (match-string 1 (expand-file-name file))))
9924 (t (concat "file:" file)))))
9927 ;;; Opening/following a link
9929 (defvar org-link-search-failed nil)
9931 (defvar org-open-link-functions nil
9932 "Hook for functions finding a plain text link.
9933 These functions must take a single argument, the link content.
9934 They will be called for links that look like [[link text][description]]
9935 when LINK TEXT does not have a protocol like \"http:\" and does not look
9936 like a filename (e.g. \"./blue.png\").
9938 These functions will be called *before* Org attempts to resolve the
9939 link by doing text searches in the current buffer - so if you want a
9940 link \"[[target]]\" to still find \"<<target>>\", your function should
9941 handle this as a special case.
9943 When the function does handle the link, it must return a non-nil value.
9944 If it decides that it is not responsible for this link, it must return
9945 nil to indicate that that Org can continue with other options like
9946 exact and fuzzy text search.")
9948 (defun org-next-link (&optional search-backward)
9949 "Move forward to the next link.
9950 If the link is in hidden text, expose it."
9951 (interactive "P")
9952 (when (and org-link-search-failed (eq this-command last-command))
9953 (goto-char (point-min))
9954 (message "Link search wrapped back to beginning of buffer"))
9955 (setq org-link-search-failed nil)
9956 (let* ((pos (point))
9957 (ct (org-context))
9958 (a (assq :link ct))
9959 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9960 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9961 ((looking-at org-any-link-re)
9962 ;; Don't stay stuck at link without an org-link face
9963 (forward-char (if search-backward -1 1))))
9964 (if (funcall srch-fun org-any-link-re nil t)
9965 (progn
9966 (goto-char (match-beginning 0))
9967 (when (org-invisible-p) (org-show-context)))
9968 (goto-char pos)
9969 (setq org-link-search-failed t)
9970 (message "No further link found"))))
9972 (defun org-previous-link ()
9973 "Move backward to the previous link.
9974 If the link is in hidden text, expose it."
9975 (interactive)
9976 (org-next-link t))
9978 (defun org-translate-link (s)
9979 "Translate a link string if a translation function has been defined."
9980 (with-temp-buffer
9981 (insert (org-trim s))
9982 (org-trim (org-element-interpret-data (org-element-context)))))
9984 (defun org-translate-link-from-planner (type path)
9985 "Translate a link from Emacs Planner syntax so that Org can follow it.
9986 This is still an experimental function, your mileage may vary."
9987 (cond
9988 ((member type '("http" "https" "news" "ftp"))
9989 ;; standard Internet links are the same.
9990 nil)
9991 ((and (equal type "irc") (string-match "^//" path))
9992 ;; Planner has two / at the beginning of an irc link, we have 1.
9993 ;; We should have zero, actually....
9994 (setq path (substring path 1)))
9995 ((and (equal type "lisp") (string-match "^/" path))
9996 ;; Planner has a slash, we do not.
9997 (setq type "elisp" path (substring path 1)))
9998 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9999 ;; A typical message link. Planner has the id after the final slash,
10000 ;; we separate it with a hash mark
10001 (setq path (concat (match-string 1 path) "#"
10002 (org-unbracket-string "<" ">" (match-string 2 path))))))
10003 (cons type path))
10005 (defun org-find-file-at-mouse (ev)
10006 "Open file link or URL at mouse."
10007 (interactive "e")
10008 (mouse-set-point ev)
10009 (org-open-at-point 'in-emacs))
10011 (defun org-open-at-mouse (ev)
10012 "Open file link or URL at mouse.
10013 See the docstring of `org-open-file' for details."
10014 (interactive "e")
10015 (mouse-set-point ev)
10016 (when (eq major-mode 'org-agenda-mode)
10017 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10018 (org-open-at-point))
10020 (defvar org-window-config-before-follow-link nil
10021 "The window configuration before following a link.
10022 This is saved in case the need arises to restore it.")
10024 ;;;###autoload
10025 (defun org-open-at-point-global ()
10026 "Follow a link or a time-stamp like Org mode does.
10027 Also follow links and emails as seen by `thing-at-point'.
10028 This command can be called in any mode to follow an external
10029 link or a time-stamp that has Org mode syntax. Its behavior
10030 is undefined when called on internal links like fuzzy links.
10031 Raise a user error when there is nothing to follow."
10032 (interactive)
10033 (let ((tap-url (thing-at-point 'url))
10034 (tap-email (thing-at-point 'email)))
10035 (cond ((org-in-regexp org-any-link-re)
10036 (org-open-link-from-string (match-string-no-properties 0)))
10037 ((or (org-in-regexp org-ts-regexp-both nil t)
10038 (org-in-regexp org-tsr-regexp-both nil t))
10039 (org-follow-timestamp-link))
10040 (tap-url (org-open-link-from-string tap-url))
10041 (tap-email (org-open-link-from-string
10042 (concat "mailto:" tap-email)))
10043 (t (user-error "No link found")))))
10045 ;;;###autoload
10046 (defun org-open-link-from-string (s &optional arg reference-buffer)
10047 "Open a link in the string S, as if it was in Org mode."
10048 (interactive "sLink: \nP")
10049 (let ((reference-buffer (or reference-buffer (current-buffer))))
10050 (with-temp-buffer
10051 (let ((org-inhibit-startup (not reference-buffer)))
10052 (org-mode)
10053 (insert s)
10054 (goto-char (point-min))
10055 (when reference-buffer
10056 (setq org-link-abbrev-alist-local
10057 (with-current-buffer reference-buffer
10058 org-link-abbrev-alist-local)))
10059 (org-open-at-point arg reference-buffer)))))
10061 (defvar org-open-at-point-functions nil
10062 "Hook that is run when following a link at point.
10064 Functions in this hook must return t if they identify and follow
10065 a link at point. If they don't find anything interesting at point,
10066 they must return nil.")
10068 (defvar org-link-search-inhibit-query nil)
10069 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10070 (defun org--open-doi-link (path)
10071 "Open a \"doi\" type link.
10072 PATH is a the path to search for, as a string."
10073 (browse-url (url-encode-url (concat org-doi-server-url path))))
10075 (defun org--open-elisp-link (path)
10076 "Open a \"elisp\" type link.
10077 PATH is the sexp to evaluate, as a string."
10078 (let ((cmd path))
10079 (if (or (and (org-string-nw-p
10080 org-confirm-elisp-link-not-regexp)
10081 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10082 (not org-confirm-elisp-link-function)
10083 (funcall org-confirm-elisp-link-function
10084 (format "Execute \"%s\" as elisp? "
10085 (org-add-props cmd nil 'face 'org-warning))))
10086 (message "%s => %s" cmd
10087 (if (eq (string-to-char cmd) ?\()
10088 (eval (read cmd))
10089 (call-interactively (read cmd))))
10090 (user-error "Abort"))))
10092 (defun org--open-help-link (path)
10093 "Open a \"help\" type link.
10094 PATH is a symbol name, as a string."
10095 (pcase (intern path)
10096 ((and (pred fboundp) variable) (describe-function variable))
10097 ((and (pred boundp) function) (describe-variable function))
10098 (name (user-error "Unknown function or variable: %s" name))))
10100 (defun org--open-shell-link (path)
10101 "Open a \"shell\" type link.
10102 PATH is the command to execute, as a string."
10103 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10104 (cmd path))
10105 (if (or (and (org-string-nw-p
10106 org-confirm-shell-link-not-regexp)
10107 (string-match
10108 org-confirm-shell-link-not-regexp cmd))
10109 (not org-confirm-shell-link-function)
10110 (funcall org-confirm-shell-link-function
10111 (format "Execute \"%s\" in shell? "
10112 (org-add-props cmd nil
10113 'face 'org-warning))))
10114 (progn
10115 (message "Executing %s" cmd)
10116 (shell-command cmd buf)
10117 (when (featurep 'midnight)
10118 (setq clean-buffer-list-kill-buffer-names
10119 (cons (buffer-name buf)
10120 clean-buffer-list-kill-buffer-names))))
10121 (user-error "Abort"))))
10123 (defun org-open-at-point (&optional arg reference-buffer)
10124 "Open link, timestamp, footnote or tags at point.
10126 When point is on a link, follow it. Normally, files will be
10127 opened by an appropriate application. If the optional prefix
10128 argument ARG is non-nil, Emacs will visit the file. With
10129 a double prefix argument, try to open outside of Emacs, in the
10130 application the system uses for this file type.
10132 When point is on a timestamp, open the agenda at the day
10133 specified.
10135 When point is a footnote definition, move to the first reference
10136 found. If it is on a reference, move to the associated
10137 definition.
10139 When point is on a headline, display a list of every link in the
10140 entry, so it is possible to pick one, or all, of them. If point
10141 is on a tag, call `org-tags-view' instead.
10143 When optional argument REFERENCE-BUFFER is non-nil, it should
10144 specify a buffer from where the link search should happen. This
10145 is used internally by `org-open-link-from-string'.
10147 On top of syntactically correct links, this function also tries
10148 to open links and time-stamps in comments, node properties, and
10149 keywords if point is on something looking like a timestamp or
10150 a link."
10151 (interactive "P")
10152 (org-load-modules-maybe)
10153 (setq org-window-config-before-follow-link (current-window-configuration))
10154 (org-remove-occur-highlights nil nil t)
10155 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10156 (let* ((context
10157 ;; Only consider supported types, even if they are not the
10158 ;; closest one.
10159 (org-element-lineage
10160 (org-element-context)
10161 '(clock comment comment-block footnote-definition
10162 footnote-reference headline inline-src-block inlinetask
10163 keyword link node-property src-block timestamp)
10165 (type (org-element-type context))
10166 (value (org-element-property :value context)))
10167 (cond
10168 ((not type) (user-error "No link found"))
10169 ;; No valid link at point. For convenience, look if something
10170 ;; looks like a link under point in some specific places.
10171 ((memq type '(comment comment-block node-property keyword))
10172 (call-interactively #'org-open-at-point-global))
10173 ;; On a headline or an inlinetask, but not on a timestamp,
10174 ;; a link, a footnote reference.
10175 ((memq type '(headline inlinetask))
10176 (org-match-line org-complex-heading-regexp)
10177 (if (and (match-beginning 5)
10178 (>= (point) (match-beginning 5))
10179 (< (point) (match-end 5)))
10180 ;; On tags.
10181 (org-tags-view arg (substring (match-string 5) 0 -1))
10182 ;; Not on tags.
10183 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10184 (`(nil . ,_)
10185 (require 'org-attach)
10186 (org-attach-reveal 'if-exists))
10187 (`(,links . ,links-end)
10188 (dolist (link (if (stringp links) (list links) links))
10189 (search-forward link nil links-end)
10190 (goto-char (match-beginning 0))
10191 (org-open-at-point))))))
10192 ;; On a footnote reference or at definition's label.
10193 ((or (eq type 'footnote-reference)
10194 (and (eq type 'footnote-definition)
10195 (save-excursion
10196 ;; Do not validate action when point is on the
10197 ;; spaces right after the footnote label, in order
10198 ;; to be on par with behavior on links.
10199 (skip-chars-forward " \t")
10200 (let ((begin
10201 (org-element-property :contents-begin context)))
10202 (if begin (< (point) begin)
10203 (= (org-element-property :post-affiliated context)
10204 (line-beginning-position)))))))
10205 (org-footnote-action))
10206 ;; On a clock line, make sure point is on the timestamp
10207 ;; before opening it.
10208 ((and (eq type 'clock)
10209 value
10210 (>= (point) (org-element-property :begin value))
10211 (<= (point) (org-element-property :end value)))
10212 (org-follow-timestamp-link))
10213 ((eq type 'src-block) (org-babel-open-src-block-result))
10214 ;; Do nothing on white spaces after an object.
10215 ((>= (point)
10216 (save-excursion
10217 (goto-char (org-element-property :end context))
10218 (skip-chars-backward " \t")
10219 (point)))
10220 (user-error "No link found"))
10221 ((eq type 'inline-src-block) (org-babel-open-src-block-result))
10222 ((eq type 'timestamp) (org-follow-timestamp-link))
10223 ((eq type 'link)
10224 (let ((type (org-element-property :type context))
10225 (path (org-link-unescape (org-element-property :path context))))
10226 ;; Switch back to REFERENCE-BUFFER needed when called in
10227 ;; a temporary buffer through `org-open-link-from-string'.
10228 (with-current-buffer (or reference-buffer (current-buffer))
10229 (cond
10230 ((equal type "file")
10231 (if (string-match "[*?{]" (file-name-nondirectory path))
10232 (dired path)
10233 ;; Look into `org-link-parameters' in order to find
10234 ;; a DEDICATED-FUNCTION to open file. The function
10235 ;; will be applied on raw link instead of parsed link
10236 ;; due to the limitation in `org-add-link-type'
10237 ;; ("open" function called with a single argument).
10238 ;; If no such function is found, fallback to
10239 ;; `org-open-file'.
10240 (let* ((option (org-element-property :search-option context))
10241 (app (org-element-property :application context))
10242 (dedicated-function
10243 (org-link-get-parameter
10244 (if app (concat type "+" app) type)
10245 :follow)))
10246 (if dedicated-function
10247 (funcall dedicated-function
10248 (concat path
10249 (and option (concat "::" option))))
10250 (apply #'org-open-file
10251 path
10252 (cond (arg)
10253 ((equal app "emacs") 'emacs)
10254 ((equal app "sys") 'system))
10255 (cond ((not option) nil)
10256 ((string-match-p "\\`[0-9]+\\'" option)
10257 (list (string-to-number option)))
10258 (t (list nil
10259 (org-link-unescape option)))))))))
10260 ((functionp (org-link-get-parameter type :follow))
10261 (funcall (org-link-get-parameter type :follow) path))
10262 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10263 (unless (run-hook-with-args-until-success
10264 'org-open-link-functions path)
10265 (if (not arg) (org-mark-ring-push)
10266 (switch-to-buffer-other-window
10267 (org-get-buffer-for-internal-link (current-buffer))))
10268 (let ((destination
10269 (org-with-wide-buffer
10270 (if (equal type "radio")
10271 (org-search-radio-target
10272 (org-element-property :path context))
10273 (org-link-search
10274 (if (member type '("custom-id" "coderef"))
10275 (org-element-property :raw-link context)
10276 path)
10277 ;; Prevent fuzzy links from matching
10278 ;; themselves.
10279 (and (equal type "fuzzy")
10280 (+ 2 (org-element-property :begin context)))))
10281 (point))))
10282 (unless (and (<= (point-min) destination)
10283 (>= (point-max) destination))
10284 (widen))
10285 (goto-char destination))))
10286 (t (browse-url-at-point))))))
10287 (t (user-error "No link found")))))
10288 (run-hook-with-args 'org-follow-link-hook))
10290 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10291 "Offer links in the current entry and return the selected link.
10292 If there is only one link, return it.
10293 If NTH is an integer, return the NTH link found.
10294 If ZERO is a string, check also this string for a link, and if
10295 there is one, return it."
10296 (with-current-buffer buffer
10297 (org-with-wide-buffer
10298 (goto-char marker)
10299 (let ((cnt ?0)
10300 have-zero end links link c)
10301 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10302 (push (match-string 0 zero) links)
10303 (setq cnt (1- cnt) have-zero t))
10304 (save-excursion
10305 (org-back-to-heading t)
10306 (setq end (save-excursion (outline-next-heading) (point)))
10307 (while (re-search-forward org-any-link-re end t)
10308 (push (match-string 0) links))
10309 (setq links (org-uniquify (reverse links))))
10310 (cond
10311 ((null links)
10312 (message "No links"))
10313 ((equal (length links) 1)
10314 (setq link (car links)))
10315 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10316 (setq link (nth (if have-zero nth (1- nth)) links)))
10317 (t ; we have to select a link
10318 (save-excursion
10319 (save-window-excursion
10320 (delete-other-windows)
10321 (with-output-to-temp-buffer "*Select Link*"
10322 (dolist (l links)
10323 (cond
10324 ((not (string-match org-bracket-link-regexp l))
10325 (princ (format "[%c] %s\n" (cl-incf cnt)
10326 (org-unbracket-string "<" ">" l))))
10327 ((match-end 3)
10328 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10329 (match-string 3 l) (match-string 1 l))))
10330 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10331 (match-string 1 l)))))))
10332 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10333 (message "Select link to open, RET to open all:")
10334 (setq c (read-char-exclusive))
10335 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10336 (when (equal c ?q) (user-error "Abort"))
10337 (if (equal c ?\C-m)
10338 (setq link links)
10339 (setq nth (- c ?0))
10340 (when have-zero (setq nth (1+ nth)))
10341 (unless (and (integerp nth) (>= (length links) nth))
10342 (user-error "Invalid link selection"))
10343 (setq link (nth (1- nth) links)))))
10344 (cons link end)))))
10346 ;; TODO: These functions are deprecated since `org-open-at-point'
10347 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10348 (defun org-open-file-with-system (path)
10349 "Open file at PATH using the system way of opening it."
10350 (org-open-file path 'system))
10351 (defun org-open-file-with-emacs (path)
10352 "Open file at PATH in Emacs."
10353 (org-open-file path 'emacs))
10356 ;;; File search
10358 (defvar org-create-file-search-functions nil
10359 "List of functions to construct the right search string for a file link.
10360 These functions are called in turn with point at the location to
10361 which the link should point.
10363 A function in the hook should first test if it would like to
10364 handle this file type, for example by checking the `major-mode'
10365 or the file extension. If it decides not to handle this file, it
10366 should just return nil to give other functions a chance. If it
10367 does handle the file, it must return the search string to be used
10368 when following the link. The search string will be part of the
10369 file link, given after a double colon, and `org-open-at-point'
10370 will automatically search for it. If special measures must be
10371 taken to make the search successful, another function should be
10372 added to the companion hook `org-execute-file-search-functions',
10373 which see.
10375 A function in this hook may also use `setq' to set the variable
10376 `description' to provide a suggestion for the descriptive text to
10377 be used for this link when it gets inserted into an Org buffer
10378 with \\[org-insert-link].")
10380 (defvar org-execute-file-search-functions nil
10381 "List of functions to execute a file search triggered by a link.
10383 Functions added to this hook must accept a single argument, the
10384 search string that was part of the file link, the part after the
10385 double colon. The function must first check if it would like to
10386 handle this search, for example by checking the `major-mode' or
10387 the file extension. If it decides not to handle this search, it
10388 should just return nil to give other functions a chance. If it
10389 does handle the search, it must return a non-nil value to keep
10390 other functions from trying.
10392 Each function can access the current prefix argument through the
10393 variable `current-prefix-arg'. Note that a single prefix is used
10394 to force opening a link in Emacs, so it may be good to only use a
10395 numeric or double prefix to guide the search function.
10397 In case this is needed, a function in this hook can also restore
10398 the window configuration before `org-open-at-point' was called using:
10400 (set-window-configuration org-window-config-before-follow-link)")
10402 (defun org-search-radio-target (target)
10403 "Search a radio target matching TARGET in current buffer.
10404 White spaces are not significant."
10405 (let ((re (format "<<<%s>>>"
10406 (mapconcat #'regexp-quote
10407 (split-string target)
10408 "[ \t]+\\(?:\n[ \t]*\\)?")))
10409 (origin (point)))
10410 (goto-char (point-min))
10411 (catch :radio-match
10412 (while (re-search-forward re nil t)
10413 (backward-char)
10414 (let ((object (org-element-context)))
10415 (when (eq (org-element-type object) 'radio-target)
10416 (goto-char (org-element-property :begin object))
10417 (org-show-context 'link-search)
10418 (throw :radio-match nil))))
10419 (goto-char origin)
10420 (user-error "No match for radio target: %s" target))))
10422 (defun org-link-search (s &optional avoid-pos stealth)
10423 "Search for a search string S.
10425 If S starts with \"#\", it triggers a custom ID search.
10427 If S is enclosed within parenthesis, it initiates a coderef
10428 search.
10430 If S is surrounded by forward slashes, it is interpreted as
10431 a regular expression. In Org mode files, this will create an
10432 `org-occur' sparse tree. In ordinary files, `occur' will be used
10433 to list matches. If the current buffer is in `dired-mode', grep
10434 will be used to search in all files.
10436 When AVOID-POS is given, ignore matches near that position.
10438 When optional argument STEALTH is non-nil, do not modify
10439 visibility around point, thus ignoring `org-show-context-detail'
10440 variable.
10442 Search is case-insensitive and ignores white spaces. Return type
10443 of matched result, which is either `dedicated' or `fuzzy'."
10444 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10445 (let* ((case-fold-search t)
10446 (origin (point))
10447 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10448 (starred (eq (string-to-char normalized) ?*))
10449 (words (split-string (if starred (substring s 1) s)))
10450 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10451 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10452 type)
10453 (cond
10454 ;; Check if there are any special search functions.
10455 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10456 ((eq (string-to-char s) ?#)
10457 ;; Look for a custom ID S if S starts with "#".
10458 (let* ((id (substring normalized 1))
10459 (match (org-find-property "CUSTOM_ID" id)))
10460 (if match (progn (goto-char match) (setf type 'dedicated))
10461 (error "No match for custom ID: %s" id))))
10462 ((string-match "\\`(\\(.*\\))\\'" normalized)
10463 ;; Look for coderef targets if S is enclosed within parenthesis.
10464 (let ((coderef (match-string-no-properties 1 normalized))
10465 (re (substring s-single-re 1 -1)))
10466 (goto-char (point-min))
10467 (catch :coderef-match
10468 (while (re-search-forward re nil t)
10469 (let ((element (org-element-at-point)))
10470 (when (and (memq (org-element-type element)
10471 '(example-block src-block))
10472 ;; Build proper regexp according to current
10473 ;; block's label format.
10474 (let ((label-fmt
10475 (regexp-quote
10476 (or (org-element-property :label-fmt element)
10477 org-coderef-label-format))))
10478 (save-excursion
10479 (beginning-of-line)
10480 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10481 (format label-fmt coderef))))))
10482 (setq type 'dedicated)
10483 (goto-char (match-beginning 1))
10484 (throw :coderef-match nil))))
10485 (goto-char origin)
10486 (error "No match for coderef: %s" coderef))))
10487 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10488 ;; Look for a regular expression.
10489 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10490 (match-string 1 s)))
10491 ;; From here, we handle fuzzy links.
10493 ;; Look for targets, only if not in a headline search.
10494 ((and (not starred)
10495 (let ((target (format "<<%s>>" s-multi-re)))
10496 (catch :target-match
10497 (goto-char (point-min))
10498 (while (re-search-forward target nil t)
10499 (backward-char)
10500 (let ((context (org-element-context)))
10501 (when (eq (org-element-type context) 'target)
10502 (setq type 'dedicated)
10503 (goto-char (org-element-property :begin context))
10504 (throw :target-match t))))
10505 nil))))
10506 ;; Look for elements named after S, only if not in a headline
10507 ;; search.
10508 ((and (not starred)
10509 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10510 (catch :name-match
10511 (goto-char (point-min))
10512 (while (re-search-forward name nil t)
10513 (let ((element (org-element-at-point)))
10514 (when (equal words
10515 (split-string
10516 (org-element-property :name element)))
10517 (setq type 'dedicated)
10518 (beginning-of-line)
10519 (throw :name-match t))))
10520 nil))))
10521 ;; Regular text search. Prefer headlines in Org mode buffers.
10522 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10523 ;; statistics cookies and tags.
10524 ((and (derived-mode-p 'org-mode)
10525 (let ((title-re
10526 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10527 org-outline-regexp-bol
10528 org-comment-string
10529 (mapconcat #'regexp-quote words ".+")))
10530 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10531 (comment-re (eval-when-compile
10532 (format "\\`%s[ \t]+" org-comment-string))))
10533 (goto-char (point-min))
10534 (catch :found
10535 (while (re-search-forward title-re nil t)
10536 (when (equal words
10537 (split-string
10538 (replace-regexp-in-string
10539 cookie-re ""
10540 (replace-regexp-in-string
10541 comment-re "" (org-get-heading t t t)))))
10542 (throw :found t)))
10543 nil)))
10544 (beginning-of-line)
10545 (setq type 'dedicated))
10546 ;; Offer to create non-existent headline depending on
10547 ;; `org-link-search-must-match-exact-headline'.
10548 ((and (derived-mode-p 'org-mode)
10549 (not org-link-search-inhibit-query)
10550 (eq org-link-search-must-match-exact-headline 'query-to-create)
10551 (yes-or-no-p "No match - create this as a new heading? "))
10552 (goto-char (point-max))
10553 (unless (bolp) (newline))
10554 (org-insert-heading nil t t)
10555 (insert s "\n")
10556 (beginning-of-line 0))
10557 ;; Only headlines are looked after. No need to process
10558 ;; further: throw an error.
10559 ((and (derived-mode-p 'org-mode)
10560 (or starred org-link-search-must-match-exact-headline))
10561 (goto-char origin)
10562 (error "No match for fuzzy expression: %s" normalized))
10563 ;; Regular text search.
10564 ((catch :fuzzy-match
10565 (goto-char (point-min))
10566 (while (re-search-forward s-multi-re nil t)
10567 ;; Skip match if it contains AVOID-POS or it is included in
10568 ;; a link with a description but outside the description.
10569 (unless (or (and avoid-pos
10570 (<= (match-beginning 0) avoid-pos)
10571 (> (match-end 0) avoid-pos))
10572 (and (save-match-data
10573 (org-in-regexp org-bracket-link-regexp))
10574 (match-beginning 3)
10575 (or (> (match-beginning 3) (point))
10576 (<= (match-end 3) (point)))
10577 (org-element-lineage
10578 (save-match-data (org-element-context))
10579 '(link) t)))
10580 (goto-char (match-beginning 0))
10581 (setq type 'fuzzy)
10582 (throw :fuzzy-match t)))
10583 nil))
10584 ;; All failed. Throw an error.
10585 (t (goto-char origin)
10586 (error "No match for fuzzy expression: %s" normalized)))
10587 ;; Disclose surroundings of match, if appropriate.
10588 (when (and (derived-mode-p 'org-mode) (not stealth))
10589 (org-show-context 'link-search))
10590 type))
10592 (defun org-get-buffer-for-internal-link (buffer)
10593 "Return a buffer to be used for displaying the link target of internal links."
10594 (cond
10595 ((not org-display-internal-link-with-indirect-buffer)
10596 buffer)
10597 ((string-suffix-p "(Clone)" (buffer-name buffer))
10598 (message "Buffer is already a clone, not making another one")
10599 ;; we also do not modify visibility in this case
10600 buffer)
10601 (t ; make a new indirect buffer for displaying the link
10602 (let* ((bn (buffer-name buffer))
10603 (ibn (concat bn "(Clone)"))
10604 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10605 (with-current-buffer ib (org-overview))
10606 ib))))
10608 (defun org-do-occur (regexp &optional cleanup)
10609 "Call the Emacs command `occur'.
10610 If CLEANUP is non-nil, remove the printout of the regular expression
10611 in the *Occur* buffer. This is useful if the regex is long and not useful
10612 to read."
10613 (occur regexp)
10614 (when cleanup
10615 (let ((cwin (selected-window)) win beg end)
10616 (when (setq win (get-buffer-window "*Occur*"))
10617 (select-window win))
10618 (goto-char (point-min))
10619 (when (re-search-forward "match[a-z]+" nil t)
10620 (setq beg (match-end 0))
10621 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10622 (setq end (1- (match-beginning 0)))))
10623 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10624 (goto-char (point-min))
10625 (select-window cwin))))
10628 ;;; The Mark Ring
10630 (defvar org-mark-ring nil
10631 "Mark ring for positions before jumps in Org mode.")
10633 (defvar org-mark-ring-last-goto nil
10634 "Last position in the mark ring used to go back.")
10636 ;; Fill and close the ring
10637 (setq org-mark-ring nil)
10638 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10640 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10641 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10642 org-mark-ring)
10644 (defun org-mark-ring-push (&optional pos buffer)
10645 "Put the current position into the mark ring and rotate it.
10646 Also push position into the Emacs mark ring. If optional
10647 argument POS and BUFFER are not nil, mark this location instead."
10648 (interactive)
10649 (let ((pos (or pos (point)))
10650 (buffer (or buffer (current-buffer))))
10651 (with-current-buffer buffer
10652 (org-with-point-at pos (push-mark nil t)))
10653 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10654 (move-marker (car org-mark-ring) pos buffer))
10655 (message
10656 (substitute-command-keys
10657 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10659 (defun org-mark-ring-goto (&optional n)
10660 "Jump to the previous position in the mark ring.
10661 With prefix arg N, jump back that many stored positions. When
10662 called several times in succession, walk through the entire ring.
10663 Org mode commands jumping to a different position in the current file,
10664 or to another Org file, automatically push the old position onto the ring."
10665 (interactive "p")
10666 (let (p m)
10667 (if (eq last-command this-command)
10668 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10669 (setq p org-mark-ring))
10670 (setq org-mark-ring-last-goto p)
10671 (setq m (car p))
10672 (pop-to-buffer-same-window (marker-buffer m))
10673 (goto-char m)
10674 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10676 (defun org-add-angle-brackets (s)
10677 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10678 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10681 ;;; Following specific links
10683 (defvar org-agenda-buffer-tmp-name)
10684 (defvar org-agenda-start-on-weekday)
10685 (defun org-follow-timestamp-link ()
10686 "Open an agenda view for the time-stamp date/range at point."
10687 (cond
10688 ((org-at-date-range-p t)
10689 (let ((org-agenda-start-on-weekday)
10690 (t1 (match-string 1))
10691 (t2 (match-string 2)) tt1 tt2)
10692 (setq tt1 (time-to-days (org-time-string-to-time t1))
10693 tt2 (time-to-days (org-time-string-to-time t2)))
10694 (let ((org-agenda-buffer-tmp-name
10695 (format "*Org Agenda(a:%s)"
10696 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10697 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10698 ((org-at-timestamp-p 'lax)
10699 (let ((org-agenda-buffer-tmp-name
10700 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10701 (org-agenda-list nil (time-to-days (org-time-string-to-time
10702 (substring (match-string 1) 0 10)))
10703 1)))
10704 (t (error "This should not happen"))))
10707 ;;; Following file links
10708 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10709 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10710 (declare-function mailcap-mime-info
10711 "mailcap" (string &optional request no-decode))
10712 (defvar org-wait nil)
10713 (defun org-open-file (path &optional in-emacs line search)
10714 "Open the file at PATH.
10715 First, this expands any special file name abbreviations. Then the
10716 configuration variable `org-file-apps' is checked if it contains an
10717 entry for this file type, and if yes, the corresponding command is launched.
10719 If no application is found, Emacs simply visits the file.
10721 With optional prefix argument IN-EMACS, Emacs will visit the file.
10722 With a double \\[universal-argument] \\[universal-argument] \
10723 prefix arg, Org tries to avoid opening in Emacs
10724 and to use an external application to visit the file.
10726 Optional LINE specifies a line to go to, optional SEARCH a string
10727 to search for. If LINE or SEARCH is given, the file will be
10728 opened in Emacs, unless an entry from org-file-apps that makes
10729 use of groups in a regexp matches.
10731 If you want to change the way frames are used when following a
10732 link, please customize `org-link-frame-setup'.
10734 If the file does not exist, an error is thrown."
10735 (let* ((file (if (equal path "")
10736 buffer-file-name
10737 (substitute-in-file-name (expand-file-name path))))
10738 (file-apps (append org-file-apps (org-default-apps)))
10739 (apps (cl-remove-if
10740 'org-file-apps-entry-match-against-dlink-p file-apps))
10741 (apps-dlink (cl-remove-if-not
10742 'org-file-apps-entry-match-against-dlink-p file-apps))
10743 (remp (and (assq 'remote apps) (file-remote-p file)))
10744 (dirp (unless remp (file-directory-p file)))
10745 (file (if (and dirp org-open-directory-means-index-dot-org)
10746 (concat (file-name-as-directory file) "index.org")
10747 file))
10748 (a-m-a-p (assq 'auto-mode apps))
10749 (dfile (downcase file))
10750 ;; Reconstruct the original link from the PATH, LINE and
10751 ;; SEARCH args.
10752 (link (cond (line (concat file "::" (number-to-string line)))
10753 (search (concat file "::" search))
10754 (t file)))
10755 (dlink (downcase link))
10756 (ext
10757 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10758 (match-string 1 dfile)))
10759 (save-position-maybe
10760 (let ((old-buffer (current-buffer))
10761 (old-pos (point))
10762 (old-mode major-mode))
10763 (lambda ()
10764 (and (derived-mode-p 'org-mode)
10765 (eq old-mode 'org-mode)
10766 (or (not (eq old-buffer (current-buffer)))
10767 (not (eq old-pos (point))))
10768 (org-mark-ring-push old-pos old-buffer)))))
10769 cmd link-match-data)
10770 (cond
10771 ((member in-emacs '((16) system))
10772 (setq cmd (cdr (assq 'system apps))))
10773 (in-emacs (setq cmd 'emacs))
10775 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10776 (and dirp (cdr (assq 'directory apps)))
10777 ;; First, try matching against apps-dlink if we
10778 ;; get a match here, store the match data for
10779 ;; later.
10780 (let ((match (assoc-default dlink apps-dlink
10781 'string-match)))
10782 (if match
10783 (progn (setq link-match-data (match-data))
10784 match)
10785 (progn (setq in-emacs (or in-emacs line search))
10786 nil))) ; if we have no match in apps-dlink,
10787 ; always open the file in emacs if line or search
10788 ; is given (for backwards compatibility)
10789 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10790 'string-match)
10791 (cdr (assoc ext apps))
10792 (cdr (assq t apps))))))
10793 (when (eq cmd 'system)
10794 (setq cmd (cdr (assq 'system apps))))
10795 (when (eq cmd 'default)
10796 (setq cmd (cdr (assoc t apps))))
10797 (when (eq cmd 'mailcap)
10798 (require 'mailcap)
10799 (mailcap-parse-mailcaps)
10800 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10801 (command (mailcap-mime-info mime-type)))
10802 (if (stringp command)
10803 (setq cmd command)
10804 (setq cmd 'emacs))))
10805 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10806 (not (file-exists-p file))
10807 (not org-open-non-existing-files))
10808 (user-error "No such file: %s" file))
10809 (cond
10810 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10811 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10812 (while (string-match "['\"]%s['\"]" cmd)
10813 (setq cmd (replace-match "%s" t t cmd)))
10814 (setq cmd (replace-regexp-in-string
10815 "%s"
10816 (shell-quote-argument (convert-standard-filename file))
10818 nil t))
10820 ;; Replace "%1", "%2" etc. in command with group matches from regex
10821 (save-match-data
10822 (let ((match-index 1)
10823 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10824 (set-match-data link-match-data)
10825 (while (<= match-index number-of-groups)
10826 (let ((regex (concat "%" (number-to-string match-index)))
10827 (replace-with (match-string match-index dlink)))
10828 (while (string-match regex cmd)
10829 (setq cmd (replace-match replace-with t t cmd))))
10830 (setq match-index (+ match-index 1)))))
10832 (save-window-excursion
10833 (message "Running %s...done" cmd)
10834 (start-process-shell-command cmd nil cmd)
10835 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10836 ((or (stringp cmd)
10837 (eq cmd 'emacs))
10838 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10839 (widen)
10840 (cond (line (org-goto-line line)
10841 (when (derived-mode-p 'org-mode) (org-reveal)))
10842 (search (condition-case err
10843 (org-link-search search)
10844 ;; Save position before error-ing out so user
10845 ;; can easily move back to the original buffer.
10846 (error (funcall save-position-maybe)
10847 (error (nth 1 err)))))))
10848 ((functionp cmd)
10849 (save-match-data
10850 (set-match-data link-match-data)
10851 (condition-case nil
10852 (funcall cmd file link)
10853 ;; FIXME: Remove this check when most default installations
10854 ;; of Emacs have at least Org 9.0.
10855 ((debug wrong-number-of-arguments wrong-type-argument
10856 invalid-function)
10857 (user-error "Please see Org News for version 9.0 about \
10858 `org-file-apps'--Lisp error: %S" cmd)))))
10859 ((consp cmd)
10860 ;; FIXME: Remove this check when most default installations of
10861 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10862 ;; fall back to `org-link-frame-setup' for an old usage of
10863 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10864 (user-error "Please see Org News for version 9.0 about \
10865 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10866 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10867 (funcall save-position-maybe)))
10869 (defun org-file-apps-entry-match-against-dlink-p (entry)
10870 "This function returns non-nil if `entry' uses a regular
10871 expression which should be matched against the whole link by
10872 org-open-file.
10874 It assumes that is the case when the entry uses a regular
10875 expression which has at least one grouping construct and the
10876 action is either a lisp form or a command string containing
10877 `%1', i.e. using at least one subexpression match as a
10878 parameter."
10879 (let ((selector (car entry))
10880 (action (cdr entry)))
10881 (if (stringp selector)
10882 (and (> (regexp-opt-depth selector) 0)
10883 (or (and (stringp action)
10884 (string-match "%[0-9]" action))
10885 (consp action)))
10886 nil)))
10888 (defun org-default-apps ()
10889 "Return the default applications for this operating system."
10890 (cond
10891 ((eq system-type 'darwin)
10892 org-file-apps-defaults-macosx)
10893 ((eq system-type 'windows-nt)
10894 org-file-apps-defaults-windowsnt)
10895 (t org-file-apps-defaults-gnu)))
10897 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10898 "Convert extensions to regular expressions in the cars of LIST.
10899 Also, weed out any non-string entries, because the return value is used
10900 only for regexp matching.
10901 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10902 point to the symbol `emacs', indicating that the file should
10903 be opened in Emacs."
10904 (append
10905 (delq nil
10906 (mapcar (lambda (x)
10907 (unless (not (stringp (car x)))
10908 (if (string-match "\\W" (car x))
10910 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10911 list))
10912 (when add-auto-mode
10913 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10916 ;;;; Refiling
10918 (defun org-get-org-file ()
10919 "Read a filename, with default directory `org-directory'."
10920 (let ((default (or org-default-notes-file remember-data-file)))
10921 (read-file-name (format "File name [%s]: " default)
10922 (file-name-as-directory org-directory)
10923 default)))
10925 (defun org-notes-order-reversed-p ()
10926 "Check if the current file should receive notes in reversed order."
10927 (cond
10928 ((not org-reverse-note-order) nil)
10929 ((eq t org-reverse-note-order) t)
10930 ((not (listp org-reverse-note-order)) nil)
10931 (t (catch 'exit
10932 (dolist (entry org-reverse-note-order)
10933 (when (string-match (car entry) buffer-file-name)
10934 (throw 'exit (cdr entry))))))))
10936 (defvar org-refile-target-table nil
10937 "The list of refile targets, created by `org-refile'.")
10939 (defvar org-agenda-new-buffers nil
10940 "Buffers created to visit agenda files.")
10942 (defvar org-refile-cache nil
10943 "Cache for refile targets.")
10945 (defvar org-refile-markers nil
10946 "All the markers used for caching refile locations.")
10948 (defun org-refile-marker (pos)
10949 "Get a new refile marker, but only if caching is in use."
10950 (if (not org-refile-use-cache)
10952 (let ((m (make-marker)))
10953 (move-marker m pos)
10954 (push m org-refile-markers)
10955 m)))
10957 (defun org-refile-cache-clear ()
10958 "Clear the refile cache and disable all the markers."
10959 (dolist (m org-refile-markers) (move-marker m nil))
10960 (setq org-refile-markers nil)
10961 (setq org-refile-cache nil)
10962 (message "Refile cache has been cleared"))
10964 (defun org-refile-cache-check-set (set)
10965 "Check if all the markers in the cache still have live buffers."
10966 (let (marker)
10967 (catch 'exit
10968 (while (and set (setq marker (nth 3 (pop set))))
10969 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10970 (when (and marker (null (marker-buffer marker)))
10971 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10972 (sit-for 3)
10973 (throw 'exit nil)))
10974 t)))
10976 (defun org-refile-cache-put (set &rest identifiers)
10977 "Push the refile targets SET into the cache, under IDENTIFIERS."
10978 (let* ((key (sha1 (prin1-to-string identifiers)))
10979 (entry (assoc key org-refile-cache)))
10980 (if entry
10981 (setcdr entry set)
10982 (push (cons key set) org-refile-cache))))
10984 (defun org-refile-cache-get (&rest identifiers)
10985 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10986 (cond
10987 ((not org-refile-cache) nil)
10988 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10990 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10991 org-refile-cache))))
10992 (and set (org-refile-cache-check-set set) set)))))
10994 (defvar org-outline-path-cache nil
10995 "Alist between buffer positions and outline paths.
10996 It value is an alist (POSITION . PATH) where POSITION is the
10997 buffer position at the beginning of an entry and PATH is a list
10998 of strings describing the outline path for that entry, in reverse
10999 order.")
11001 (defun org-refile-get-targets (&optional default-buffer)
11002 "Produce a table with refile targets."
11003 (let ((case-fold-search nil)
11004 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11005 (entries (or org-refile-targets '((nil . (:level . 1)))))
11006 targets tgs files desc descre)
11007 (message "Getting targets...")
11008 (with-current-buffer (or default-buffer (current-buffer))
11009 (dolist (entry entries)
11010 (setq files (car entry) desc (cdr entry))
11011 (cond
11012 ((null files) (setq files (list (current-buffer))))
11013 ((eq files 'org-agenda-files)
11014 (setq files (org-agenda-files 'unrestricted)))
11015 ((and (symbolp files) (fboundp files))
11016 (setq files (funcall files)))
11017 ((and (symbolp files) (boundp files))
11018 (setq files (symbol-value files))))
11019 (when (stringp files) (setq files (list files)))
11020 (cond
11021 ((eq (car desc) :tag)
11022 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11023 ((eq (car desc) :todo)
11024 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11025 ((eq (car desc) :regexp)
11026 (setq descre (cdr desc)))
11027 ((eq (car desc) :level)
11028 (setq descre (concat "^\\*\\{" (number-to-string
11029 (if org-odd-levels-only
11030 (1- (* 2 (cdr desc)))
11031 (cdr desc)))
11032 "\\}[ \t]")))
11033 ((eq (car desc) :maxlevel)
11034 (setq descre (concat "^\\*\\{1," (number-to-string
11035 (if org-odd-levels-only
11036 (1- (* 2 (cdr desc)))
11037 (cdr desc)))
11038 "\\}[ \t]")))
11039 (t (error "Bad refiling target description %s" desc)))
11040 (dolist (f files)
11041 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11043 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11044 (progn
11045 (when (bufferp f)
11046 (setq f (buffer-file-name (buffer-base-buffer f))))
11047 (setq f (and f (expand-file-name f)))
11048 (when (eq org-refile-use-outline-path 'file)
11049 (push (list (file-name-nondirectory f) f nil nil) tgs))
11050 (when (eq org-refile-use-outline-path 'buffer-name)
11051 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11052 (when (eq org-refile-use-outline-path 'full-file-path)
11053 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11054 (org-with-wide-buffer
11055 (goto-char (point-min))
11056 (setq org-outline-path-cache nil)
11057 (while (re-search-forward descre nil t)
11058 (beginning-of-line)
11059 (let ((case-fold-search nil))
11060 (looking-at org-complex-heading-regexp))
11061 (let ((begin (point))
11062 (heading (match-string-no-properties 4)))
11063 (unless (or (and
11064 org-refile-target-verify-function
11065 (not
11066 (funcall org-refile-target-verify-function)))
11067 (not heading))
11068 (let ((re (format org-complex-heading-regexp-format
11069 (regexp-quote heading)))
11070 (target
11071 (if (not org-refile-use-outline-path) heading
11072 (mapconcat
11073 #'identity
11074 (append
11075 (pcase org-refile-use-outline-path
11076 (`file (list (file-name-nondirectory
11077 (buffer-file-name
11078 (buffer-base-buffer)))))
11079 (`full-file-path
11080 (list (buffer-file-name
11081 (buffer-base-buffer))))
11082 (`buffer-name
11083 (list (buffer-name
11084 (buffer-base-buffer))))
11085 (_ nil))
11086 (mapcar (lambda (s) (replace-regexp-in-string
11087 "/" "\\/" s nil t))
11088 (org-get-outline-path t t)))
11089 "/"))))
11090 (push (list target f re (org-refile-marker (point)))
11091 tgs)))
11092 (when (= (point) begin)
11093 ;; Verification function has not moved point.
11094 (end-of-line)))))))
11095 (when org-refile-use-cache
11096 (org-refile-cache-put tgs (buffer-file-name) descre))
11097 (setq targets (append tgs targets))))))
11098 (message "Getting targets...done")
11099 (delete-dups (nreverse targets))))
11101 (defun org--get-outline-path-1 (&optional use-cache)
11102 "Return outline path to current headline.
11104 Outline path is a list of strings, in reverse order. When
11105 optional argument USE-CACHE is non-nil, make use of a cache. See
11106 `org-get-outline-path' for details.
11108 Assume buffer is widened and point is on a headline."
11109 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11110 (let ((p (point))
11111 (heading (let ((case-fold-search nil))
11112 (looking-at org-complex-heading-regexp)
11113 (if (not (match-end 4)) ""
11114 ;; Remove statistics cookies.
11115 (org-trim
11116 (org-link-display-format
11117 (replace-regexp-in-string
11118 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11119 (match-string-no-properties 4))))))))
11120 (if (org-up-heading-safe)
11121 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11122 (when use-cache
11123 (push (cons p path) org-outline-path-cache))
11124 path)
11125 ;; This is a new root node. Since we assume we are moving
11126 ;; forward, we can drop previous cache so as to limit number
11127 ;; of associations there.
11128 (let ((path (list heading)))
11129 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11130 path)))))
11132 (defun org-get-outline-path (&optional with-self use-cache)
11133 "Return the outline path to the current entry.
11135 An outline path is a list of ancestors for current headline, as
11136 a list of strings. Statistics cookies are removed and links are
11137 replaced with their description, if any, or their path otherwise.
11139 When optional argument WITH-SELF is non-nil, the path also
11140 includes the current headline.
11142 When optional argument USE-CACHE is non-nil, cache outline paths
11143 between calls to this function so as to avoid backtracking. This
11144 argument is useful when planning to find more than one outline
11145 path in the same document. In that case, there are two
11146 conditions to satisfy:
11147 - `org-outline-path-cache' is set to nil before starting the
11148 process;
11149 - outline paths are computed by increasing buffer positions."
11150 (org-with-wide-buffer
11151 (and (or (and with-self (org-back-to-heading t))
11152 (org-up-heading-safe))
11153 (reverse (org--get-outline-path-1 use-cache)))))
11155 (defun org-format-outline-path (path &optional width prefix separator)
11156 "Format the outline path PATH for display.
11157 WIDTH is the maximum number of characters that is available.
11158 PREFIX is a prefix to be included in the returned string,
11159 such as the file name.
11160 SEPARATOR is inserted between the different parts of the path,
11161 the default is \"/\"."
11162 (setq width (or width 79))
11163 (setq path (delq nil path))
11164 (unless (> width 0)
11165 (user-error "Argument `width' must be positive"))
11166 (setq separator (or separator "/"))
11167 (let* ((org-odd-levels-only nil)
11168 (fpath (concat
11169 prefix (and prefix path separator)
11170 (mapconcat
11171 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11172 (cl-loop for head in path
11173 for n from 0
11174 collect (org-add-props
11175 head nil 'face
11176 (nth (% n org-n-level-faces) org-level-faces)))
11177 separator))))
11178 (when (> (length fpath) width)
11179 (if (< width 7)
11180 ;; It's unlikely that `width' will be this small, but don't
11181 ;; waste characters by adding ".." if it is.
11182 (setq fpath (substring fpath 0 width))
11183 (setf (substring fpath (- width 2)) "..")))
11184 fpath))
11186 (defun org-display-outline-path (&optional file current separator just-return-string)
11187 "Display the current outline path in the echo area.
11189 If FILE is non-nil, prepend the output with the file name.
11190 If CURRENT is non-nil, append the current heading to the output.
11191 SEPARATOR is passed through to `org-format-outline-path'. It separates
11192 the different parts of the path and defaults to \"/\".
11193 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11194 (interactive "P")
11195 (let* (case-fold-search
11196 (bfn (buffer-file-name (buffer-base-buffer)))
11197 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11198 res)
11199 (when current (setq path (append path
11200 (save-excursion
11201 (org-back-to-heading t)
11202 (when (looking-at org-complex-heading-regexp)
11203 (list (match-string 4)))))))
11204 (setq res
11205 (org-format-outline-path
11206 path
11207 (1- (frame-width))
11208 (and file bfn (concat (file-name-nondirectory bfn) separator))
11209 separator))
11210 (if just-return-string
11211 (org-no-properties res)
11212 (org-unlogged-message "%s" res))))
11214 (defvar org-refile-history nil
11215 "History for refiling operations.")
11217 (defvar org-after-refile-insert-hook nil
11218 "Hook run after `org-refile' has inserted its stuff at the new location.
11219 Note that this is still *before* the stuff will be removed from
11220 the *old* location.")
11222 (defvar org-capture-last-stored-marker)
11223 (defvar org-refile-keep nil
11224 "Non-nil means `org-refile' will copy instead of refile.")
11226 (defun org-copy ()
11227 "Like `org-refile', but copy."
11228 (interactive)
11229 (let ((org-refile-keep t))
11230 (org-refile nil nil nil "Copy")))
11232 (defun org-refile (&optional arg default-buffer rfloc msg)
11233 "Move the entry or entries at point to another heading.
11235 The list of target headings is compiled using the information in
11236 `org-refile-targets', which see.
11238 At the target location, the entry is filed as a subitem of the
11239 target heading. Depending on `org-reverse-note-order', the new
11240 subitem will either be the first or the last subitem.
11242 If there is an active region, all entries in that region will be
11243 refiled. However, the region must fulfill the requirement that
11244 the first heading sets the top-level of the moved text.
11246 With a `\\[universal-argument]' ARG, the command will only visit the target \
11247 location
11248 and not actually move anything.
11250 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11251 location where the last
11252 refiling operation has put the subtree.
11254 With a numeric prefix argument of `2', refile to the running clock.
11256 With a numeric prefix argument of `3', emulate `org-refile-keep'
11257 being set to t and copy to the target location, don't move it.
11258 Beware that keeping refiled entries may result in duplicated ID
11259 properties.
11261 RFLOC can be a refile location obtained in a different way.
11263 MSG is a string to replace \"Refile\" in the default prompt with
11264 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11266 See also `org-refile-use-outline-path'.
11268 If you are using target caching (see `org-refile-use-cache'), you
11269 have to clear the target cache in order to find new targets.
11270 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11271 prefix argument (`C-u C-u C-u C-c C-w')."
11272 (interactive "P")
11273 (if (member arg '(0 (64)))
11274 (org-refile-cache-clear)
11275 (let* ((actionmsg (cond (msg msg)
11276 ((equal arg 3) "Refile (and keep)")
11277 (t "Refile")))
11278 (regionp (org-region-active-p))
11279 (region-start (and regionp (region-beginning)))
11280 (region-end (and regionp (region-end)))
11281 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11282 pos it nbuf file level reversed)
11283 (setq last-command nil)
11284 (when regionp
11285 (goto-char region-start)
11286 (or (bolp) (goto-char (point-at-bol)))
11287 (setq region-start (point))
11288 (unless (or (org-kill-is-subtree-p
11289 (buffer-substring region-start region-end))
11290 (prog1 org-refile-active-region-within-subtree
11291 (let ((s (point-at-eol)))
11292 (org-toggle-heading)
11293 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11294 (user-error "The region is not a (sequence of) subtree(s)")))
11295 (if (equal arg '(16))
11296 (org-refile-goto-last-stored)
11297 (when (or
11298 (and (equal arg 2)
11299 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11300 (prog1
11301 (setq it (list (or org-clock-heading "running clock")
11302 (buffer-file-name
11303 (marker-buffer org-clock-hd-marker))
11305 (marker-position org-clock-hd-marker)))
11306 (setq arg nil)))
11307 (setq it
11308 (or rfloc
11309 (let (heading-text)
11310 (save-excursion
11311 (unless (and arg (listp arg))
11312 (org-back-to-heading t)
11313 (setq heading-text
11314 (replace-regexp-in-string
11315 org-bracket-link-regexp
11316 "\\3"
11317 (or (nth 4 (org-heading-components))
11318 ""))))
11319 (org-refile-get-location
11320 (cond ((and arg (listp arg)) "Goto")
11321 (regionp (concat actionmsg " region to"))
11322 (t (concat actionmsg " subtree \""
11323 heading-text "\" to")))
11324 default-buffer
11325 (and (not (equal '(4) arg))
11326 org-refile-allow-creating-parent-nodes)))))))
11327 (setq file (nth 1 it)
11328 pos (nth 3 it))
11329 (when (and (not arg)
11331 (equal (buffer-file-name) file)
11332 (if regionp
11333 (and (>= pos region-start)
11334 (<= pos region-end))
11335 (and (>= pos (point))
11336 (< pos (save-excursion
11337 (org-end-of-subtree t t))))))
11338 (error "Cannot refile to position inside the tree or region"))
11339 (setq nbuf (or (find-buffer-visiting file)
11340 (find-file-noselect file)))
11341 (if (and arg (not (equal arg 3)))
11342 (progn
11343 (pop-to-buffer-same-window nbuf)
11344 (goto-char (cond (pos)
11345 ((org-notes-order-reversed-p) (point-min))
11346 (t (point-max))))
11347 (org-show-context 'org-goto))
11348 (if regionp
11349 (progn
11350 (org-kill-new (buffer-substring region-start region-end))
11351 (org-save-markers-in-region region-start region-end))
11352 (org-copy-subtree 1 nil t))
11353 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11354 (find-file-noselect file)))
11355 (setq reversed (org-notes-order-reversed-p))
11356 (org-with-wide-buffer
11357 (if pos
11358 (progn
11359 (goto-char pos)
11360 (setq level (org-get-valid-level (funcall outline-level) 1))
11361 (goto-char
11362 (if reversed
11363 (or (outline-next-heading) (point-max))
11364 (or (save-excursion (org-get-next-sibling))
11365 (org-end-of-subtree t t)
11366 (point-max)))))
11367 (setq level 1)
11368 (if (not reversed)
11369 (goto-char (point-max))
11370 (goto-char (point-min))
11371 (or (outline-next-heading) (goto-char (point-max)))))
11372 (unless (bolp) (newline))
11373 (org-paste-subtree level nil nil t)
11374 (when org-log-refile
11375 (org-add-log-setup 'refile nil nil org-log-refile)
11376 (unless (eq org-log-refile 'note)
11377 (save-excursion (org-add-log-note))))
11378 (and org-auto-align-tags
11379 (let ((org-loop-over-headlines-in-active-region nil))
11380 (org-align-tags)))
11381 (let ((bookmark-name (plist-get org-bookmark-names-plist
11382 :last-refile)))
11383 (when bookmark-name
11384 (with-demoted-errors
11385 (bookmark-set bookmark-name))))
11386 ;; If we are refiling for capture, make sure that the
11387 ;; last-capture pointers point here
11388 (when (bound-and-true-p org-capture-is-refiling)
11389 (let ((bookmark-name (plist-get org-bookmark-names-plist
11390 :last-capture-marker)))
11391 (when bookmark-name
11392 (with-demoted-errors
11393 (bookmark-set bookmark-name))))
11394 (move-marker org-capture-last-stored-marker (point)))
11395 (when (fboundp 'deactivate-mark) (deactivate-mark))
11396 (run-hooks 'org-after-refile-insert-hook)))
11397 (unless org-refile-keep
11398 (if regionp
11399 (delete-region (point) (+ (point) (- region-end region-start)))
11400 (org-preserve-local-variables
11401 (delete-region
11402 (and (org-back-to-heading t) (point))
11403 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11404 (when (featurep 'org-inlinetask)
11405 (org-inlinetask-remove-END-maybe))
11406 (setq org-markers-to-move nil)
11407 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11409 (defun org-refile-goto-last-stored ()
11410 "Go to the location where the last refile was stored."
11411 (interactive)
11412 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11413 (message "This is the location of the last refile"))
11415 (defun org-refile--get-location (refloc tbl)
11416 "When user refile to REFLOC, find the associated target in TBL.
11417 Also check `org-refile-target-table'."
11418 (car (delq
11420 (mapcar
11421 (lambda (r) (or (assoc r tbl)
11422 (assoc r org-refile-target-table)))
11423 (list (replace-regexp-in-string "/$" "" refloc)
11424 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11426 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11427 "Prompt the user for a refile location, using PROMPT.
11428 PROMPT should not be suffixed with a colon and a space, because
11429 this function appends the default value from
11430 `org-refile-history' automatically, if that is not empty."
11431 (let ((org-refile-targets org-refile-targets)
11432 (org-refile-use-outline-path org-refile-use-outline-path))
11433 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11434 (unless org-refile-target-table
11435 (user-error "No refile targets"))
11436 (let* ((cbuf (current-buffer))
11437 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11438 (cfunc (if (and org-refile-use-outline-path
11439 org-outline-path-complete-in-steps)
11440 #'org-olpath-completing-read
11441 #'completing-read))
11442 (extra (if org-refile-use-outline-path "/" ""))
11443 (cbnex (concat (buffer-name) extra))
11444 (filename (and cfn (expand-file-name cfn)))
11445 (tbl (mapcar
11446 (lambda (x)
11447 (if (and (not (member org-refile-use-outline-path
11448 '(file full-file-path)))
11449 (not (equal filename (nth 1 x))))
11450 (cons (concat (car x) extra " ("
11451 (file-name-nondirectory (nth 1 x)) ")")
11452 (cdr x))
11453 (cons (concat (car x) extra) (cdr x))))
11454 org-refile-target-table))
11455 (completion-ignore-case t)
11456 cdef
11457 (prompt (concat prompt
11458 (or (and (car org-refile-history)
11459 (concat " (default " (car org-refile-history) ")"))
11460 (and (assoc cbnex tbl) (setq cdef cbnex)
11461 (concat " (default " cbnex ")"))) ": "))
11462 pa answ parent-target child parent old-hist)
11463 (setq old-hist org-refile-history)
11464 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11465 nil 'org-refile-history (or cdef (car org-refile-history))))
11466 (if (setq pa (org-refile--get-location answ tbl))
11467 (progn
11468 (org-refile-check-position pa)
11469 (when (or (not org-refile-history)
11470 (not (eq old-hist org-refile-history))
11471 (not (equal (car pa) (car org-refile-history))))
11472 (setq org-refile-history
11473 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11474 org-refile-history
11475 (cdr org-refile-history))))
11476 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11477 (pop org-refile-history)))
11479 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11480 (progn
11481 (setq parent (match-string 1 answ)
11482 child (match-string 2 answ))
11483 (setq parent-target (org-refile--get-location parent tbl))
11484 (when (and parent-target
11485 (or (eq new-nodes t)
11486 (and (eq new-nodes 'confirm)
11487 (y-or-n-p (format "Create new node \"%s\"? "
11488 child)))))
11489 (org-refile-new-child parent-target child)))
11490 (user-error "Invalid target location")))))
11492 (declare-function org-string-nw-p "org-macs" (s))
11493 (defun org-refile-check-position (refile-pointer)
11494 "Check if the refile pointer matches the headline to which it points."
11495 (let* ((file (nth 1 refile-pointer))
11496 (re (nth 2 refile-pointer))
11497 (pos (nth 3 refile-pointer))
11498 buffer)
11499 (if (and (not (markerp pos)) (not file))
11500 (user-error "Please indicate a target file in the refile path")
11501 (when (org-string-nw-p re)
11502 (setq buffer (if (markerp pos)
11503 (marker-buffer pos)
11504 (or (find-buffer-visiting file)
11505 (find-file-noselect file))))
11506 (with-current-buffer buffer
11507 (org-with-wide-buffer
11508 (goto-char pos)
11509 (beginning-of-line 1)
11510 (unless (looking-at-p re)
11511 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11513 (defun org-refile-new-child (parent-target child)
11514 "Use refile target PARENT-TARGET to add new CHILD below it."
11515 (unless parent-target
11516 (error "Cannot find parent for new node"))
11517 (let ((file (nth 1 parent-target))
11518 (pos (nth 3 parent-target))
11519 level)
11520 (with-current-buffer (or (find-buffer-visiting file)
11521 (find-file-noselect file))
11522 (org-with-wide-buffer
11523 (if pos
11524 (goto-char pos)
11525 (goto-char (point-max))
11526 (unless (bolp) (newline)))
11527 (when (looking-at org-outline-regexp)
11528 (setq level (funcall outline-level))
11529 (org-end-of-subtree t t))
11530 (org-back-over-empty-lines)
11531 (insert "\n" (make-string
11532 (if pos (org-get-valid-level level 1) 1) ?*)
11533 " " child "\n")
11534 (beginning-of-line 0)
11535 (list (concat (car parent-target) "/" child) file "" (point))))))
11537 (defun org-olpath-completing-read (prompt collection &rest args)
11538 "Read an outline path like a file name."
11539 (let ((thetable collection))
11540 (apply #'completing-read
11541 prompt
11542 (lambda (string predicate &optional flag)
11543 (cond
11544 ((eq flag nil) (try-completion string thetable))
11545 ((eq flag t)
11546 (let ((l (length string)))
11547 (mapcar (lambda (x)
11548 (let ((r (substring x l))
11549 (f (if (string-match " ([^)]*)$" x)
11550 (match-string 0 x)
11551 "")))
11552 (if (string-match "/" r)
11553 (concat string (substring r 0 (match-end 0)) f)
11554 x)))
11555 (all-completions string thetable predicate))))
11556 ;; Exact match?
11557 ((eq flag 'lambda) (assoc string thetable))))
11558 args)))
11560 ;;;; Dynamic blocks
11562 (defun org-find-dblock (name)
11563 "Find the first dynamic block with name NAME in the buffer.
11564 If not found, stay at current position and return nil."
11565 (let ((case-fold-search t) pos)
11566 (save-excursion
11567 (goto-char (point-min))
11568 (setq pos (and (re-search-forward
11569 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11570 (match-beginning 0))))
11571 (when pos (goto-char pos))
11572 pos))
11574 (defun org-create-dblock (plist)
11575 "Create a dynamic block section, with parameters taken from PLIST.
11576 PLIST must contain a :name entry which is used as the name of the block."
11577 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11578 (end-of-line 1)
11579 (newline))
11580 (let ((col (current-column))
11581 (name (plist-get plist :name)))
11582 (insert "#+BEGIN: " name)
11583 (while plist
11584 (if (eq (car plist) :name)
11585 (setq plist (cddr plist))
11586 (insert " " (prin1-to-string (pop plist)))))
11587 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11588 (beginning-of-line -2)))
11590 (defun org-prepare-dblock ()
11591 "Prepare dynamic block for refresh.
11592 This empties the block, puts the cursor at the insert position and returns
11593 the property list including an extra property :name with the block name."
11594 (unless (looking-at org-dblock-start-re)
11595 (user-error "Not at a dynamic block"))
11596 (let* ((begdel (1+ (match-end 0)))
11597 (name (org-no-properties (match-string 1)))
11598 (params (append (list :name name)
11599 (read (concat "(" (match-string 3) ")")))))
11600 (save-excursion
11601 (beginning-of-line 1)
11602 (skip-chars-forward " \t")
11603 (setq params (plist-put params :indentation-column (current-column))))
11604 (unless (re-search-forward org-dblock-end-re nil t)
11605 (error "Dynamic block not terminated"))
11606 (setq params
11607 (append params
11608 (list :content (buffer-substring
11609 begdel (match-beginning 0)))))
11610 (delete-region begdel (match-beginning 0))
11611 (goto-char begdel)
11612 (open-line 1)
11613 params))
11615 (defun org-map-dblocks (&optional command)
11616 "Apply COMMAND to all dynamic blocks in the current buffer.
11617 If COMMAND is not given, use `org-update-dblock'."
11618 (let ((cmd (or command 'org-update-dblock)))
11619 (save-excursion
11620 (goto-char (point-min))
11621 (while (re-search-forward org-dblock-start-re nil t)
11622 (goto-char (match-beginning 0))
11623 (save-excursion
11624 (condition-case nil
11625 (funcall cmd)
11626 (error (message "Error during update of dynamic block"))))
11627 (unless (re-search-forward org-dblock-end-re nil t)
11628 (error "Dynamic block not terminated"))))))
11630 (defun org-dblock-update (&optional arg)
11631 "User command for updating dynamic blocks.
11632 Update the dynamic block at point. With prefix ARG, update all dynamic
11633 blocks in the buffer."
11634 (interactive "P")
11635 (if arg
11636 (org-update-all-dblocks)
11637 (or (looking-at org-dblock-start-re)
11638 (org-beginning-of-dblock))
11639 (org-update-dblock)))
11641 (defun org-update-dblock ()
11642 "Update the dynamic block at point.
11643 This means to empty the block, parse for parameters and then call
11644 the correct writing function."
11645 (interactive)
11646 (save-excursion
11647 (let* ((win (selected-window))
11648 (pos (point))
11649 (line (org-current-line))
11650 (params (org-prepare-dblock))
11651 (name (plist-get params :name))
11652 (indent (plist-get params :indentation-column))
11653 (cmd (intern (concat "org-dblock-write:" name))))
11654 (message "Updating dynamic block `%s' at line %d..." name line)
11655 (funcall cmd params)
11656 (message "Updating dynamic block `%s' at line %d...done" name line)
11657 (goto-char pos)
11658 (when (and indent (> indent 0))
11659 (setq indent (make-string indent ?\ ))
11660 (save-excursion
11661 (select-window win)
11662 (org-beginning-of-dblock)
11663 (forward-line 1)
11664 (while (not (looking-at org-dblock-end-re))
11665 (insert indent)
11666 (beginning-of-line 2))
11667 (when (looking-at org-dblock-end-re)
11668 (and (looking-at "[ \t]+")
11669 (replace-match ""))
11670 (insert indent)))))))
11672 (defun org-beginning-of-dblock ()
11673 "Find the beginning of the dynamic block at point.
11674 Error if there is no such block at point."
11675 (let ((pos (point))
11676 beg)
11677 (end-of-line 1)
11678 (if (and (re-search-backward org-dblock-start-re nil t)
11679 (setq beg (match-beginning 0))
11680 (re-search-forward org-dblock-end-re nil t)
11681 (> (match-end 0) pos))
11682 (goto-char beg)
11683 (goto-char pos)
11684 (error "Not in a dynamic block"))))
11686 (defun org-update-all-dblocks ()
11687 "Update all dynamic blocks in the buffer.
11688 This function can be used in a hook."
11689 (interactive)
11690 (when (derived-mode-p 'org-mode)
11691 (org-map-dblocks 'org-update-dblock)))
11694 ;;;; Completion
11696 (declare-function org-export-backend-options "ox" (cl-x) t)
11697 (defun org-get-export-keywords ()
11698 "Return a list of all currently understood export keywords.
11699 Export keywords include options, block names, attributes and
11700 keywords relative to each registered export back-end."
11701 (let (keywords)
11702 (dolist (backend
11703 (bound-and-true-p org-export-registered-backends)
11704 (delq nil keywords))
11705 ;; Back-end name (for keywords, like #+LATEX:)
11706 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11707 (dolist (option-entry (org-export-backend-options backend))
11708 ;; Back-end options.
11709 (push (nth 1 option-entry) keywords)))))
11711 (defconst org-options-keywords
11712 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11713 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11714 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11715 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11716 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11718 (defcustom org-structure-template-alist
11719 '(("a" . "export ascii")
11720 ("c" . "center")
11721 ("C" . "comment")
11722 ("e" . "example")
11723 ("E" . "export")
11724 ("h" . "export html")
11725 ("l" . "export latex")
11726 ("q" . "quote")
11727 ("s" . "src")
11728 ("v" . "verse"))
11729 "An alist of keys and block types.
11730 `org-insert-structure-template' will display a menu with this
11731 list of templates to choose from. The block type is inserted,
11732 with \"#+BEGIN_\" and \"#+END_\" added automatically.
11734 The menu keys are defined by the car of each entry in this alist.
11735 If two entries have the keys \"a\" and \"aa\" respectively, the
11736 former will be inserted by typing \"a TAB/RET/SPC\" and the
11737 latter will be inserted by typing \"aa\". If an entry with the
11738 key \"aab\" is later added, it can be inserted by typing \"ab\".
11740 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11741 block can be inserted by pressing TAB after the string \"<KEY\"."
11742 :group 'org-edit-structure
11743 :type '(repeat
11744 (cons (string :tag "Key")
11745 (string :tag "Template")))
11746 :package-version '(Org . "9.2"))
11748 (defun org--check-org-structure-template-alist (&optional checklist)
11749 "Check whether `org-structure-template-alist' is set up correctly.
11750 In particular, check if the Org 9.2 format is used as opposed to
11751 previous format.
11753 (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
11754 (or (eval checklist)
11755 org-structure-template-alist))))
11756 (when elm
11757 (org-display-warning
11758 (format "
11759 Please update the entries of `%s'.
11761 In Org 9.2 the format was changed from something like
11763 (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
11765 to something like
11767 (\"s\" . \"src\")
11769 Please refer to the documentation of `org-structure-template-alist'.
11771 The following entries must be updated:
11774 (or checklist 'org-structure-template-alist)
11775 (pp-to-string elm))))))
11777 (defun org--insert-structure-template-mks ()
11778 "Present `org-structure-template-alist' with `org-mks'.
11780 Menus are added if keys require more than one keystroke. Tabs
11781 are added to single key entries when more than one stroke is
11782 needed. Keys longer than two characters are reduced to two
11783 characters."
11784 (org--check-org-structure-template-alist)
11785 (let* (case-fold-search
11786 (templates (append org-structure-template-alist
11787 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11788 (keys (mapcar #'car templates))
11789 (start-letters
11790 (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11791 ;; Sort each element of `org-structure-template-alist' into
11792 ;; sublists according to the first letter.
11793 (superlist
11794 (mapcar (lambda (letter)
11795 (list letter
11796 (cl-remove-if-not
11797 (apply-partially #'string-match-p (concat "^" letter))
11798 templates :key #'car)))
11799 start-letters)))
11800 (org-mks
11801 (apply #'append
11802 ;; Make an `org-mks' table. If only one element is
11803 ;; present in a sublist, make it part of the top-menu,
11804 ;; otherwise make a submenu according to the starting
11805 ;; letter and populate it.
11806 (mapcar (lambda (sublist)
11807 (if (eq 1 (length (cadr sublist)))
11808 (mapcar (lambda (elm)
11809 (list (substring (car elm) 0 1)
11810 (cdr elm) ""))
11811 (cadr sublist))
11812 ;; Create submenu.
11813 (let* ((topkey (car sublist))
11814 (elms (cadr sublist))
11815 (keys (mapcar #'car elms))
11816 (long (> (length elms) 3)))
11817 (append
11818 (list
11819 ;; Make a description of the submenu.
11820 (list topkey
11821 (concat
11822 (mapconcat #'cdr
11823 (cl-subseq elms 0 (if long 3 (length elms)))
11824 ", ")
11825 (when long ", ..."))))
11826 ;; List of entries in submenu.
11827 (cl-mapcar #'list
11828 (org--insert-structure-template-unique-keys keys)
11829 (mapcar #'cdr elms)
11830 (make-list (length elms) ""))))))
11831 superlist))
11832 "Select a key\n============"
11833 "Key: ")))
11835 (defun org--insert-structure-template-unique-keys (keys)
11836 "Make a list of unique, two characters long elements from KEYS.
11838 Elements of length one have a tab appended. Elements of length
11839 two are kept as is. Longer elements are truncated to length two.
11841 If an element cannot be made unique, an error is raised."
11842 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11843 menu-keys)
11844 (dolist (key orderd-keys)
11845 (let ((potential-key
11846 (cl-case (length key)
11847 (1 (concat key "\t"))
11848 (2 key)
11849 (otherwise
11850 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11851 (mapcar (apply-partially #'concat (substring key 0 1))
11852 (split-string (substring key 1) "" t)))))))
11853 (if (or (not potential-key) (assoc potential-key menu-keys))
11854 (user-error "Could not make unique key for %s." key)
11855 (push (cons potential-key key) menu-keys))))
11856 (mapcar #'car
11857 (cl-sort menu-keys #'<
11858 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11860 (defun org-insert-structure-template (type)
11861 "Insert a block structure of the type #+begin_foo/#+end_foo.
11862 Select a block from `org-structure-template-alist' then type
11863 either RET, TAB or SPC to write the block type. With an active
11864 region, wrap the region in the block. Otherwise, insert an empty
11865 block."
11866 (interactive
11867 (list (pcase (org--insert-structure-template-mks)
11868 (`("\t" . ,_) (read-string "Structure type: "))
11869 (`(,_ ,choice . ,_) choice))))
11870 (let* ((region? (use-region-p))
11871 (region-start (and region? (region-beginning)))
11872 (region-end (and region? (copy-marker (region-end))))
11873 (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
11874 (verbatim? (string-match-p
11875 (concat "\\`" (regexp-opt '("example" "export" "src")))
11876 type)))
11877 (when region? (goto-char region-start))
11878 (let ((column (current-indentation)))
11879 (if (save-excursion (skip-chars-backward " \t") (bolp))
11880 (beginning-of-line)
11881 (insert "\n"))
11882 (save-excursion
11883 (indent-to column)
11884 (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
11885 (when region?
11886 (when verbatim? (org-escape-code-in-region (point) region-end))
11887 (goto-char region-end)
11888 ;; Ignore empty lines at the end of the region.
11889 (skip-chars-backward " \r\t\n")
11890 (end-of-line))
11891 (unless (bolp) (insert "\n"))
11892 (indent-to column)
11893 (insert (format "#+end_%s" (car (split-string type))))
11894 (if (looking-at "[ \t]*$") (replace-match "")
11895 (insert "\n"))
11896 (when (and (eobp) (not (bolp))) (insert "\n")))
11897 (if extended? (end-of-line)
11898 (forward-line)
11899 (skip-chars-forward " \t")))))
11902 ;;;; TODO, DEADLINE, Comments
11904 (defun org-toggle-comment ()
11905 "Change the COMMENT state of an entry."
11906 (interactive)
11907 (save-excursion
11908 (org-back-to-heading)
11909 (let ((case-fold-search nil))
11910 (looking-at org-complex-heading-regexp))
11911 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11912 (skip-chars-forward " \t")
11913 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11914 (if (org-in-commented-heading-p t)
11915 (delete-region (point)
11916 (progn (search-forward " " (line-end-position) 'move)
11917 (skip-chars-forward " \t")
11918 (point)))
11919 (insert org-comment-string)
11920 (unless (eolp) (insert " ")))))
11922 (defvar org-last-todo-state-is-todo nil
11923 "This is non-nil when the last TODO state change led to a TODO state.
11924 If the last change removed the TODO tag or switched to DONE, then
11925 this is nil.")
11927 (defvar org-todo-setup-filter-hook nil
11928 "Hook for functions that pre-filter todo specs.
11929 Each function takes a todo spec and returns either nil or the spec
11930 transformed into canonical form." )
11932 (defvar org-todo-get-default-hook nil
11933 "Hook for functions that get a default item for todo.
11934 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11935 nil or a string to be used for the todo mark." )
11937 (defvar org-agenda-headline-snapshot-before-repeat)
11939 (defun org-current-effective-time ()
11940 "Return current time adjusted for `org-extend-today-until' variable."
11941 (let* ((ct (org-current-time))
11942 (dct (decode-time ct))
11943 (ct1
11944 (cond
11945 (org-use-last-clock-out-time-as-effective-time
11946 (or (org-clock-get-last-clock-out-time) ct))
11947 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11948 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11949 (t ct))))
11950 ct1))
11952 (defun org-todo-yesterday (&optional arg)
11953 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11954 (interactive "P")
11955 (if (eq major-mode 'org-agenda-mode)
11956 (apply 'org-agenda-todo-yesterday arg)
11957 (let* ((org-use-effective-time t)
11958 (hour (nth 2 (decode-time (org-current-time))))
11959 (org-extend-today-until (1+ hour)))
11960 (org-todo arg))))
11962 (defvar org-block-entry-blocking ""
11963 "First entry preventing the TODO state change.")
11965 (defun org-cancel-repeater ()
11966 "Cancel a repeater by setting its numeric value to zero."
11967 (interactive)
11968 (save-excursion
11969 (org-back-to-heading t)
11970 (let ((bound1 (point))
11971 (bound0 (save-excursion (outline-next-heading) (point))))
11972 (when (and (re-search-forward
11973 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11974 org-deadline-time-regexp "\\)\\|\\("
11975 org-ts-regexp "\\)")
11976 bound0 t)
11977 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11978 bound1 t))
11979 (replace-match "0" t nil nil 1)))))
11981 (defvar org-state)
11982 (defvar org-blocked-by-checkboxes)
11983 (defun org-todo (&optional arg)
11984 "Change the TODO state of an item.
11986 The state of an item is given by a keyword at the start of the heading,
11987 like
11988 *** TODO Write paper
11989 *** DONE Call mom
11991 The different keywords are specified in the variable `org-todo-keywords'.
11992 By default the available states are \"TODO\" and \"DONE\". So, for this
11993 example: when the item starts with TODO, it is changed to DONE.
11994 When it starts with DONE, the DONE is removed. And when neither TODO nor
11995 DONE are present, add TODO at the beginning of the heading.
11997 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11998 state.
11999 With numeric prefix ARG, switch to that state.
12000 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12001 next set of TODO \
12002 keywords (nextset).
12003 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12004 prefix, circumvent any state blocking.
12005 With a numeric prefix arg of 0, inhibit note taking for the change.
12006 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12008 When called through ELisp, arg is also interpreted in the following way:
12009 `none' -> empty state
12010 \"\" -> switch to empty state
12011 `done' -> switch to DONE
12012 `nextset' -> switch to the next set of keywords
12013 `previousset' -> switch to the previous set of keywords
12014 \"WAITING\" -> switch to the specified keyword, but only if it
12015 really is a member of `org-todo-keywords'."
12016 (interactive "P")
12017 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12018 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12019 'region-start-level 'region))
12020 org-loop-over-headlines-in-active-region)
12021 (org-map-entries
12022 `(org-todo ,arg)
12023 org-loop-over-headlines-in-active-region
12024 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12025 (when (equal arg '(16)) (setq arg 'nextset))
12026 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12027 (let ((org-blocker-hook org-blocker-hook)
12028 commentp
12029 case-fold-search)
12030 (when (equal arg '(64))
12031 (setq arg nil org-blocker-hook nil))
12032 (when (and org-blocker-hook
12033 (or org-inhibit-blocking
12034 (org-entry-get nil "NOBLOCKING")))
12035 (setq org-blocker-hook nil))
12036 (save-excursion
12037 (catch 'exit
12038 (org-back-to-heading t)
12039 (when (org-in-commented-heading-p t)
12040 (org-toggle-comment)
12041 (setq commentp t))
12042 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12043 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12044 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12045 (let* ((match-data (match-data))
12046 (startpos (copy-marker (line-beginning-position)))
12047 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12048 (org-log-done org-log-done)
12049 (org-log-repeat org-log-repeat)
12050 (org-todo-log-states org-todo-log-states)
12051 (org-inhibit-logging
12052 (if (equal arg 0)
12053 (progn (setq arg nil) 'note) org-inhibit-logging))
12054 (this (match-string 1))
12055 (hl-pos (match-beginning 0))
12056 (head (org-get-todo-sequence-head this))
12057 (ass (assoc head org-todo-kwd-alist))
12058 (interpret (nth 1 ass))
12059 (done-word (nth 3 ass))
12060 (final-done-word (nth 4 ass))
12061 (org-last-state (or this ""))
12062 (completion-ignore-case t)
12063 (member (member this org-todo-keywords-1))
12064 (tail (cdr member))
12065 (org-state (cond
12066 ((and org-todo-key-trigger
12067 (or (and (equal arg '(4))
12068 (eq org-use-fast-todo-selection 'prefix))
12069 (and (not arg) org-use-fast-todo-selection
12070 (not (eq org-use-fast-todo-selection
12071 'prefix)))))
12072 ;; Use fast selection.
12073 (org-fast-todo-selection))
12074 ((and (equal arg '(4))
12075 (or (not org-use-fast-todo-selection)
12076 (not org-todo-key-trigger)))
12077 ;; Read a state with completion.
12078 (completing-read
12079 "State: " (mapcar #'list org-todo-keywords-1)
12080 nil t))
12081 ((eq arg 'right)
12082 (if this
12083 (if tail (car tail) nil)
12084 (car org-todo-keywords-1)))
12085 ((eq arg 'left)
12086 (unless (equal member org-todo-keywords-1)
12087 (if this
12088 (nth (- (length org-todo-keywords-1)
12089 (length tail) 2)
12090 org-todo-keywords-1)
12091 (org-last org-todo-keywords-1))))
12092 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12093 (setq arg nil))) ;hack to fall back to cycling
12094 (arg
12095 ;; User or caller requests a specific state.
12096 (cond
12097 ((equal arg "") nil)
12098 ((eq arg 'none) nil)
12099 ((eq arg 'done) (or done-word (car org-done-keywords)))
12100 ((eq arg 'nextset)
12101 (or (car (cdr (member head org-todo-heads)))
12102 (car org-todo-heads)))
12103 ((eq arg 'previousset)
12104 (let ((org-todo-heads (reverse org-todo-heads)))
12105 (or (car (cdr (member head org-todo-heads)))
12106 (car org-todo-heads))))
12107 ((car (member arg org-todo-keywords-1)))
12108 ((stringp arg)
12109 (user-error "State `%s' not valid in this file" arg))
12110 ((nth (1- (prefix-numeric-value arg))
12111 org-todo-keywords-1))))
12112 ((null member) (or head (car org-todo-keywords-1)))
12113 ((equal this final-done-word) nil) ;-> make empty
12114 ((null tail) nil) ;-> first entry
12115 ((memq interpret '(type priority))
12116 (if (eq this-command last-command)
12117 (car tail)
12118 (if (> (length tail) 0)
12119 (or done-word (car org-done-keywords))
12120 nil)))
12122 (car tail))))
12123 (org-state (or
12124 (run-hook-with-args-until-success
12125 'org-todo-get-default-hook org-state org-last-state)
12126 org-state))
12127 (next (if org-state (concat " " org-state " ") " "))
12128 (change-plist (list :type 'todo-state-change :from this :to org-state
12129 :position startpos))
12130 dolog now-done-p)
12131 (when org-blocker-hook
12132 (let (org-blocked-by-checkboxes block-reason)
12133 (setq org-last-todo-state-is-todo
12134 (not (member this org-done-keywords)))
12135 (unless (save-excursion
12136 (save-match-data
12137 (org-with-wide-buffer
12138 (run-hook-with-args-until-failure
12139 'org-blocker-hook change-plist))))
12140 (setq block-reason (if org-blocked-by-checkboxes
12141 "contained checkboxes"
12142 (format "\"%s\"" org-block-entry-blocking)))
12143 (if (called-interactively-p 'interactive)
12144 (user-error "TODO state change from %s to %s blocked (by %s)"
12145 this org-state block-reason)
12146 ;; Fail silently.
12147 (message "TODO state change from %s to %s blocked (by %s)"
12148 this org-state block-reason)
12149 (throw 'exit nil)))))
12150 (store-match-data match-data)
12151 (replace-match next t t)
12152 (cond ((equal this org-state)
12153 (message "TODO state was already %s" (org-trim next)))
12154 ((not (pos-visible-in-window-p hl-pos))
12155 (message "TODO state changed to %s" (org-trim next))))
12156 (unless head
12157 (setq head (org-get-todo-sequence-head org-state)
12158 ass (assoc head org-todo-kwd-alist)
12159 interpret (nth 1 ass)
12160 done-word (nth 3 ass)
12161 final-done-word (nth 4 ass)))
12162 (when (memq arg '(nextset previousset))
12163 (message "Keyword-Set %d/%d: %s"
12164 (- (length org-todo-sets) -1
12165 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12166 (length org-todo-sets)
12167 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12168 (setq org-last-todo-state-is-todo
12169 (not (member org-state org-done-keywords)))
12170 (setq now-done-p (and (member org-state org-done-keywords)
12171 (not (member this org-done-keywords))))
12172 (and logging (org-local-logging logging))
12173 (when (and (or org-todo-log-states org-log-done)
12174 (not (eq org-inhibit-logging t))
12175 (not (memq arg '(nextset previousset))))
12176 ;; We need to look at recording a time and note.
12177 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12178 (nth 2 (assoc this org-todo-log-states))))
12179 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12180 (setq dolog 'time))
12181 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12182 (and org-state
12183 (member org-state org-not-done-keywords)
12184 (not (member this org-not-done-keywords))))
12185 ;; This is now a todo state and was not one before
12186 ;; If there was a CLOSED time stamp, get rid of it.
12187 (org-add-planning-info nil nil 'closed))
12188 (when (and now-done-p org-log-done)
12189 ;; It is now done, and it was not done before.
12190 (org-add-planning-info 'closed (org-current-effective-time))
12191 (when (and (not dolog) (eq 'note org-log-done))
12192 (org-add-log-setup 'done org-state this 'note)))
12193 (when (and org-state dolog)
12194 ;; This is a non-nil state, and we need to log it.
12195 (org-add-log-setup 'state org-state this dolog)))
12196 ;; Fixup tag positioning.
12197 (org-todo-trigger-tag-changes org-state)
12198 (when org-auto-align-tags (org-align-tags))
12199 (when org-provide-todo-statistics
12200 (org-update-parent-todo-statistics))
12201 (run-hooks 'org-after-todo-state-change-hook)
12202 (when (and arg (not (member org-state org-done-keywords)))
12203 (setq head (org-get-todo-sequence-head org-state)))
12204 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12205 ;; Do we need to trigger a repeat?
12206 (when now-done-p
12207 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12208 ;; This is for the agenda, take a snapshot of the headline.
12209 (save-match-data
12210 (setq org-agenda-headline-snapshot-before-repeat
12211 (org-get-heading))))
12212 (org-auto-repeat-maybe org-state))
12213 ;; Fixup cursor location if close to the keyword.
12214 (when (and (outline-on-heading-p)
12215 (not (bolp))
12216 (save-excursion (beginning-of-line 1)
12217 (looking-at org-todo-line-regexp))
12218 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12219 (goto-char (or (match-end 2) (match-end 1)))
12220 (and (looking-at " ") (just-one-space)))
12221 (when org-trigger-hook
12222 (save-excursion
12223 (run-hook-with-args 'org-trigger-hook change-plist)))
12224 (when commentp (org-toggle-comment))))))))
12226 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12227 "Block turning an entry into a TODO, using the hierarchy.
12228 This checks whether the current task should be blocked from state
12229 changes. Such blocking occurs when:
12231 1. The task has children which are not all in a completed state.
12233 2. A task has a parent with the property :ORDERED:, and there
12234 are siblings prior to the current task with incomplete
12235 status.
12237 3. The parent of the task is blocked because it has siblings that should
12238 be done first, or is child of a block grandparent TODO entry."
12240 (if (not org-enforce-todo-dependencies)
12241 t ; if locally turned off don't block
12242 (catch 'dont-block
12243 ;; If this is not a todo state change, or if this entry is already DONE,
12244 ;; do not block
12245 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12246 (member (plist-get change-plist :from)
12247 (cons 'done org-done-keywords))
12248 (member (plist-get change-plist :to)
12249 (cons 'todo org-not-done-keywords))
12250 (not (plist-get change-plist :to)))
12251 (throw 'dont-block t))
12252 ;; If this task has children, and any are undone, it's blocked
12253 (save-excursion
12254 (org-back-to-heading t)
12255 (let ((this-level (funcall outline-level)))
12256 (outline-next-heading)
12257 (let ((child-level (funcall outline-level)))
12258 (while (and (not (eobp))
12259 (> child-level this-level))
12260 ;; this todo has children, check whether they are all
12261 ;; completed
12262 (when (and (not (org-entry-is-done-p))
12263 (org-entry-is-todo-p))
12264 (setq org-block-entry-blocking (org-get-heading))
12265 (throw 'dont-block nil))
12266 (outline-next-heading)
12267 (setq child-level (funcall outline-level))))))
12268 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12269 ;; any previous siblings are undone, it's blocked
12270 (save-excursion
12271 (org-back-to-heading t)
12272 (let* ((pos (point))
12273 (parent-pos (and (org-up-heading-safe) (point)))
12274 (case-fold-search nil))
12275 (unless parent-pos (throw 'dont-block t)) ; no parent
12276 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12277 (forward-line 1)
12278 (re-search-forward org-not-done-heading-regexp pos t))
12279 (setq org-block-entry-blocking (match-string 0))
12280 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12281 ;; Search further up the hierarchy, to see if an ancestor is blocked
12282 (while t
12283 (goto-char parent-pos)
12284 (unless (looking-at org-not-done-heading-regexp)
12285 (throw 'dont-block t)) ; do not block, parent is not a TODO
12286 (setq pos (point))
12287 (setq parent-pos (and (org-up-heading-safe) (point)))
12288 (unless parent-pos (throw 'dont-block t)) ; no parent
12289 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12290 (forward-line 1)
12291 (re-search-forward org-not-done-heading-regexp pos t)
12292 (setq org-block-entry-blocking (org-get-heading)))
12293 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12295 (defcustom org-track-ordered-property-with-tag nil
12296 "Should the ORDERED property also be shown as a tag?
12297 The ORDERED property decides if an entry should require subtasks to be
12298 completed in sequence. Since a property is not very visible, setting
12299 this option means that toggling the ORDERED property with the command
12300 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12301 not relevant for the behavior, but it makes things more visible.
12303 Note that toggling the tag with tags commands will not change the property
12304 and therefore not influence behavior!
12306 This can be t, meaning the tag ORDERED should be used, It can also be a
12307 string to select a different tag for this task."
12308 :group 'org-todo
12309 :type '(choice
12310 (const :tag "No tracking" nil)
12311 (const :tag "Track with ORDERED tag" t)
12312 (string :tag "Use other tag")))
12314 (defun org-toggle-ordered-property ()
12315 "Toggle the ORDERED property of the current entry.
12316 For better visibility, you can track the value of this property with a tag.
12317 See variable `org-track-ordered-property-with-tag'."
12318 (interactive)
12319 (let* ((t1 org-track-ordered-property-with-tag)
12320 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12321 (save-excursion
12322 (org-back-to-heading)
12323 (if (org-entry-get nil "ORDERED")
12324 (progn
12325 (org-delete-property "ORDERED")
12326 (and tag (org-toggle-tag tag 'off))
12327 (message "Subtasks can be completed in arbitrary order"))
12328 (org-entry-put nil "ORDERED" "t")
12329 (and tag (org-toggle-tag tag 'on))
12330 (message "Subtasks must be completed in sequence")))))
12332 (defun org-block-todo-from-checkboxes (change-plist)
12333 "Block turning an entry into a TODO, using checkboxes.
12334 This checks whether the current task should be blocked from state
12335 changes because there are unchecked boxes in this entry."
12336 (if (not org-enforce-todo-checkbox-dependencies)
12337 t ; if locally turned off don't block
12338 (catch 'dont-block
12339 ;; If this is not a todo state change, or if this entry is already DONE,
12340 ;; do not block
12341 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12342 (member (plist-get change-plist :from)
12343 (cons 'done org-done-keywords))
12344 (member (plist-get change-plist :to)
12345 (cons 'todo org-not-done-keywords))
12346 (not (plist-get change-plist :to)))
12347 (throw 'dont-block t))
12348 ;; If this task has checkboxes that are not checked, it's blocked
12349 (save-excursion
12350 (org-back-to-heading t)
12351 (let ((beg (point)) end)
12352 (outline-next-heading)
12353 (setq end (point))
12354 (goto-char beg)
12355 (when (org-list-search-forward
12356 (concat (org-item-beginning-re)
12357 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12358 "\\[[- ]\\]")
12359 end t)
12360 (when (boundp 'org-blocked-by-checkboxes)
12361 (setq org-blocked-by-checkboxes t))
12362 (throw 'dont-block nil))))
12363 t))) ; do not block
12365 (defun org-entry-blocked-p ()
12366 "Non-nil if entry at point is blocked."
12367 (and (not (org-entry-get nil "NOBLOCKING"))
12368 (member (org-entry-get nil "TODO") org-not-done-keywords)
12369 (not (run-hook-with-args-until-failure
12370 'org-blocker-hook
12371 (list :type 'todo-state-change
12372 :position (point)
12373 :from 'todo
12374 :to 'done)))))
12376 (defun org-update-statistics-cookies (all)
12377 "Update the statistics cookie, either from TODO or from checkboxes.
12378 This should be called with the cursor in a line with a statistics
12379 cookie. When called with a \\[universal-argument] prefix, update
12380 all statistics cookies in the buffer."
12381 (interactive "P")
12382 (if all
12383 (progn
12384 (org-update-checkbox-count 'all)
12385 (org-map-entries 'org-update-parent-todo-statistics))
12386 (if (not (org-at-heading-p))
12387 (org-update-checkbox-count)
12388 (let ((pos (point-marker))
12389 end l1 l2)
12390 (ignore-errors (org-back-to-heading t))
12391 (if (not (org-at-heading-p))
12392 (org-update-checkbox-count)
12393 (setq l1 (org-outline-level))
12394 (setq end (save-excursion
12395 (outline-next-heading)
12396 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12397 (point)))
12398 (if (and (save-excursion
12399 (re-search-forward
12400 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12401 (not (save-excursion (re-search-forward
12402 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12403 (org-update-checkbox-count)
12404 (if (and l2 (> l2 l1))
12405 (progn
12406 (goto-char end)
12407 (org-update-parent-todo-statistics))
12408 (goto-char pos)
12409 (beginning-of-line 1)
12410 (while (re-search-forward
12411 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12412 (point-at-eol) t)
12413 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12414 (goto-char pos)
12415 (move-marker pos nil)))))
12417 (defvar org-entry-property-inherited-from) ;; defined below
12418 (defun org-update-parent-todo-statistics ()
12419 "Update any statistics cookie in the parent of the current headline.
12420 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12421 the entire subtree and this will travel up the hierarchy and update
12422 statistics everywhere."
12423 (let* ((prop (save-excursion (org-up-heading-safe)
12424 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12425 (recursive (or (not org-hierarchical-todo-statistics)
12426 (and prop (string-match "\\<recursive\\>" prop))))
12427 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12429 (first t)
12430 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12431 level ltoggle l1 new ndel
12432 (cnt-all 0) (cnt-done 0) is-percent kwd
12433 checkbox-beg cookie-present)
12434 (catch 'exit
12435 (save-excursion
12436 (beginning-of-line 1)
12437 (setq ltoggle (funcall outline-level))
12438 ;; Three situations are to consider:
12440 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12441 ;; to the top-level ancestor on the headline;
12443 ;; 2. If parent has "recursive" property, repeat up to the
12444 ;; headline setting that property, taking inheritance into
12445 ;; account;
12447 ;; 3. Else, move up to direct parent and proceed only once.
12448 (while (and (setq level (org-up-heading-safe))
12449 (or recursive first)
12450 (>= (point) lim))
12451 (setq first nil cookie-present nil)
12452 (unless (and level
12453 (not (string-match
12454 "\\<checkbox\\>"
12455 (downcase (or (org-entry-get nil "COOKIE_DATA")
12456 "")))))
12457 (throw 'exit nil))
12458 (while (re-search-forward box-re (point-at-eol) t)
12459 (setq cnt-all 0 cnt-done 0 cookie-present t)
12460 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12461 (save-match-data
12462 (unless (outline-next-heading) (throw 'exit nil))
12463 (while (and (looking-at org-complex-heading-regexp)
12464 (> (setq l1 (length (match-string 1))) level))
12465 (setq kwd (and (or recursive (= l1 ltoggle))
12466 (match-string 2)))
12467 (if (or (eq org-provide-todo-statistics 'all-headlines)
12468 (and (eq org-provide-todo-statistics t)
12469 (or (member kwd org-done-keywords)))
12470 (and (listp org-provide-todo-statistics)
12471 (stringp (car org-provide-todo-statistics))
12472 (or (member kwd org-provide-todo-statistics)
12473 (member kwd org-done-keywords)))
12474 (and (listp org-provide-todo-statistics)
12475 (listp (car org-provide-todo-statistics))
12476 (or (member kwd (car org-provide-todo-statistics))
12477 (and (member kwd org-done-keywords)
12478 (member kwd (cadr org-provide-todo-statistics))))))
12479 (setq cnt-all (1+ cnt-all))
12480 (and (eq org-provide-todo-statistics t)
12482 (setq cnt-all (1+ cnt-all))))
12483 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12484 (member kwd org-done-keywords))
12485 (and (listp org-provide-todo-statistics)
12486 (listp (car org-provide-todo-statistics))
12487 (member kwd org-done-keywords)
12488 (member kwd (cadr org-provide-todo-statistics)))
12489 (and (listp org-provide-todo-statistics)
12490 (stringp (car org-provide-todo-statistics))
12491 (member kwd org-done-keywords)))
12492 (setq cnt-done (1+ cnt-done)))
12493 (outline-next-heading)))
12494 (setq new
12495 (if is-percent
12496 (format "[%d%%]" (floor (* 100.0 cnt-done)
12497 (max 1 cnt-all)))
12498 (format "[%d/%d]" cnt-done cnt-all))
12499 ndel (- (match-end 0) checkbox-beg))
12500 (goto-char checkbox-beg)
12501 (insert new)
12502 (delete-region (point) (+ (point) ndel))
12503 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12504 (when cookie-present
12505 (run-hook-with-args 'org-after-todo-statistics-hook
12506 cnt-done (- cnt-all cnt-done))))))
12507 (run-hooks 'org-todo-statistics-hook)))
12509 (defvar org-after-todo-statistics-hook nil
12510 "Hook that is called after a TODO statistics cookie has been updated.
12511 Each function is called with two arguments: the number of not-done entries
12512 and the number of done entries.
12514 For example, the following function, when added to this hook, will switch
12515 an entry to DONE when all children are done, and back to TODO when new
12516 entries are set to a TODO status. Note that this hook is only called
12517 when there is a statistics cookie in the headline!
12519 (defun org-summary-todo (n-done n-not-done)
12520 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12521 (let (org-log-done org-log-states) ; turn off logging
12522 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12525 (defvar org-todo-statistics-hook nil
12526 "Hook that is run whenever Org thinks TODO statistics should be updated.
12527 This hook runs even if there is no statistics cookie present, in which case
12528 `org-after-todo-statistics-hook' would not run.")
12530 (defun org-todo-trigger-tag-changes (state)
12531 "Apply the changes defined in `org-todo-state-tags-triggers'."
12532 (let ((l org-todo-state-tags-triggers)
12533 changes)
12534 (when (or (not state) (equal state ""))
12535 (setq changes (append changes (cdr (assoc "" l)))))
12536 (when (and (stringp state) (> (length state) 0))
12537 (setq changes (append changes (cdr (assoc state l)))))
12538 (when (member state org-not-done-keywords)
12539 (setq changes (append changes (cdr (assq 'todo l)))))
12540 (when (member state org-done-keywords)
12541 (setq changes (append changes (cdr (assq 'done l)))))
12542 (dolist (c changes)
12543 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12545 (defun org-local-logging (value)
12546 "Get logging settings from a property VALUE."
12547 ;; Directly set the variables, they are already local.
12548 (setq org-log-done nil
12549 org-log-repeat nil
12550 org-todo-log-states nil)
12551 (dolist (w (split-string value))
12552 (let (a)
12553 (cond
12554 ((setq a (assoc w org-startup-options))
12555 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12556 (set (nth 1 a) (nth 2 a))))
12557 ((setq a (org-extract-log-state-settings w))
12558 (and (member (car a) org-todo-keywords-1)
12559 (push a org-todo-log-states)))))))
12561 (defun org-get-todo-sequence-head (kwd)
12562 "Return the head of the TODO sequence to which KWD belongs.
12563 If KWD is not set, check if there is a text property remembering the
12564 right sequence."
12565 (let (p)
12566 (cond
12567 ((not kwd)
12568 (or (get-text-property (point-at-bol) 'org-todo-head)
12569 (progn
12570 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12571 nil (point-at-eol)))
12572 (get-text-property p 'org-todo-head))))
12573 ((not (member kwd org-todo-keywords-1))
12574 (car org-todo-keywords-1))
12575 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12577 (defun org-fast-todo-selection ()
12578 "Fast TODO keyword selection with single keys.
12579 Returns the new TODO keyword, or nil if no state change should occur."
12580 (let* ((fulltable org-todo-key-alist)
12581 (done-keywords org-done-keywords) ;; needed for the faces.
12582 (maxlen (apply 'max (mapcar
12583 (lambda (x)
12584 (if (stringp (car x)) (string-width (car x)) 0))
12585 fulltable)))
12586 (expert nil)
12587 (fwidth (+ maxlen 3 1 3))
12588 (ncol (/ (- (window-width) 4) fwidth))
12589 tg cnt e c tbl
12590 groups ingroup)
12591 (save-excursion
12592 (save-window-excursion
12593 (if expert
12594 (set-buffer (get-buffer-create " *Org todo*"))
12595 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12596 (erase-buffer)
12597 (setq-local org-done-keywords done-keywords)
12598 (setq tbl fulltable cnt 0)
12599 (while (setq e (pop tbl))
12600 (cond
12601 ((equal e '(:startgroup))
12602 (push '() groups) (setq ingroup t)
12603 (unless (= cnt 0)
12604 (setq cnt 0)
12605 (insert "\n"))
12606 (insert "{ "))
12607 ((equal e '(:endgroup))
12608 (setq ingroup nil cnt 0)
12609 (insert "}\n"))
12610 ((equal e '(:newline))
12611 (unless (= cnt 0)
12612 (setq cnt 0)
12613 (insert "\n")
12614 (setq e (car tbl))
12615 (while (equal (car tbl) '(:newline))
12616 (insert "\n")
12617 (setq tbl (cdr tbl)))))
12619 (setq tg (car e) c (cdr e))
12620 (when ingroup (push tg (car groups)))
12621 (setq tg (org-add-props tg nil 'face
12622 (org-get-todo-face tg)))
12623 (when (and (= cnt 0) (not ingroup)) (insert " "))
12624 (insert "[" c "] " tg (make-string
12625 (- fwidth 4 (length tg)) ?\ ))
12626 (when (= (setq cnt (1+ cnt)) ncol)
12627 (insert "\n")
12628 (when ingroup (insert " "))
12629 (setq cnt 0)))))
12630 (insert "\n")
12631 (goto-char (point-min))
12632 (unless expert (org-fit-window-to-buffer))
12633 (message "[a-z..]:Set [SPC]:clear")
12634 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12635 (cond
12636 ((or (= c ?\C-g)
12637 (and (= c ?q) (not (rassoc c fulltable))))
12638 (setq quit-flag t))
12639 ((= c ?\ ) nil)
12640 ((setq e (rassoc c fulltable) tg (car e))
12642 (t (setq quit-flag t)))))))
12644 (defun org-entry-is-todo-p ()
12645 (member (org-get-todo-state) org-not-done-keywords))
12647 (defun org-entry-is-done-p ()
12648 (member (org-get-todo-state) org-done-keywords))
12650 (defun org-get-todo-state ()
12651 "Return the TODO keyword of the current subtree."
12652 (save-excursion
12653 (org-back-to-heading t)
12654 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12655 (match-end 2)
12656 (match-string 2))))
12658 (defun org-at-date-range-p (&optional inactive-ok)
12659 "Non-nil if point is inside a date range.
12661 When optional argument INACTIVE-OK is non-nil, also consider
12662 inactive time ranges.
12664 When this function returns a non-nil value, match data is set
12665 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12666 on INACTIVE-OK."
12667 (interactive)
12668 (save-excursion
12669 (catch 'exit
12670 (let ((pos (point)))
12671 (skip-chars-backward "^[<\r\n")
12672 (skip-chars-backward "<[")
12673 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12674 (>= (match-end 0) pos)
12675 (throw 'exit t))
12676 (skip-chars-backward "^<[\r\n")
12677 (skip-chars-backward "<[")
12678 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12679 (>= (match-end 0) pos)
12680 (throw 'exit t)))
12681 nil)))
12683 (defun org-get-repeat (&optional timestamp)
12684 "Check if there is a time-stamp with repeater in this entry.
12686 Return the repeater, as a string, or nil. Also return nil when
12687 this function is called before first heading.
12689 When optional argument TIMESTAMP is a string, extract the
12690 repeater from there instead."
12691 (save-match-data
12692 (cond (timestamp
12693 (and (string-match org-repeat-re timestamp)
12694 (match-string-no-properties 1 timestamp)))
12695 ((org-before-first-heading-p) nil)
12697 (save-excursion
12698 (org-back-to-heading t)
12699 (let ((end (org-entry-end-position)))
12700 (catch :repeat
12701 (while (re-search-forward org-repeat-re end t)
12702 (when (save-match-data (org-at-timestamp-p 'agenda))
12703 (throw :repeat (match-string-no-properties 1)))))))))))
12705 (defvar org-last-changed-timestamp)
12706 (defvar org-last-inserted-timestamp)
12707 (defvar org-log-post-message)
12708 (defvar org-log-note-purpose)
12709 (defvar org-log-note-how nil)
12710 (defvar org-log-note-extra)
12711 (defun org-auto-repeat-maybe (done-word)
12712 "Check if the current headline contains a repeated time-stamp.
12714 If yes, set TODO state back to what it was and change the base date
12715 of repeating deadline/scheduled time stamps to new date.
12717 This function is run automatically after each state change to a DONE state."
12718 (let* ((repeat (org-get-repeat))
12719 (aa (assoc org-last-state org-todo-kwd-alist))
12720 (interpret (nth 1 aa))
12721 (head (nth 2 aa))
12722 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12723 (msg "Entry repeats: ")
12724 (org-log-done nil)
12725 (org-todo-log-states nil)
12726 (end (copy-marker (org-entry-end-position))))
12727 (unwind-protect
12728 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12729 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12730 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12731 (and (stringp org-todo-repeat-to-state)
12732 org-todo-repeat-to-state)
12733 (and org-todo-repeat-to-state org-last-state))))
12734 (org-todo (cond
12735 ((and to-state (member to-state org-todo-keywords-1))
12736 to-state)
12737 ((eq interpret 'type) org-last-state)
12738 (head)
12739 (t 'none))))
12740 (org-back-to-heading t)
12741 (org-add-planning-info nil nil 'closed)
12742 ;; When `org-log-repeat' is non-nil or entry contains
12743 ;; a clock, set LAST_REPEAT property.
12744 (when (or org-log-repeat
12745 (catch :clock
12746 (save-excursion
12747 (while (re-search-forward org-clock-line-re end t)
12748 (when (org-at-clock-log-p) (throw :clock t))))))
12749 (org-entry-put nil "LAST_REPEAT" (format-time-string
12750 (org-time-stamp-format t t)
12751 (current-time))))
12752 (when org-log-repeat
12753 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12754 (memq 'org-add-log-note post-command-hook))
12755 ;; We are already setup for some record.
12756 (when (eq org-log-repeat 'note)
12757 ;; Make sure we take a note, not only a time stamp.
12758 (setq org-log-note-how 'note))
12759 ;; Set up for taking a record.
12760 (org-add-log-setup 'state
12761 (or done-word (car org-done-keywords))
12762 org-last-state
12763 org-log-repeat)))
12764 (let ((planning-re (regexp-opt
12765 (list org-scheduled-string org-deadline-string))))
12766 (while (re-search-forward org-ts-regexp end t)
12767 (let* ((ts (match-string 0))
12768 (planning? (org-at-planning-p))
12769 (type (if (not planning?) "Plain:"
12770 (save-excursion
12771 (re-search-backward
12772 planning-re (line-beginning-position) t)
12773 (match-string 0)))))
12774 (cond
12775 ;; Ignore fake time-stamps (e.g., within comments).
12776 ((not (org-at-timestamp-p 'agenda)))
12777 ;; Time-stamps without a repeater are usually
12778 ;; skipped. However, a SCHEDULED time-stamp without
12779 ;; one is removed, as they are no longer relevant.
12780 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12781 ts))
12782 (when (equal type org-scheduled-string)
12783 (org-remove-timestamp-with-keyword type)))
12785 (let ((n (string-to-number (match-string 2 ts)))
12786 (what (match-string 3 ts)))
12787 (when (equal what "w") (setq n (* n 7) what "d"))
12788 (when (and (equal what "h")
12789 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12790 ts)))
12791 (user-error
12792 "Cannot repeat in Repeat in %d hour(s) because no hour \
12793 has been set"
12795 ;; Preparation, see if we need to modify the start
12796 ;; date for the change.
12797 (when (match-end 1)
12798 (let ((time (save-match-data
12799 (org-time-string-to-time ts))))
12800 (cond
12801 ((equal (match-string 1 ts) ".")
12802 ;; Shift starting date to today
12803 (org-timestamp-change
12804 (- (org-today) (time-to-days time))
12805 'day))
12806 ((equal (match-string 1 ts) "+")
12807 (let ((nshiftmax 10)
12808 (nshift 0))
12809 (while (or (= nshift 0)
12810 (not (time-less-p (current-time) time)))
12811 (when (= (cl-incf nshift) nshiftmax)
12812 (or (y-or-n-p
12813 (format "%d repeater intervals were not \
12814 enough to shift date past today. Continue? "
12815 nshift))
12816 (user-error "Abort")))
12817 (org-timestamp-change n (cdr (assoc what whata)))
12818 (org-in-regexp org-ts-regexp3)
12819 (setq ts (match-string 1))
12820 (setq time
12821 (save-match-data
12822 (org-time-string-to-time ts)))))
12823 (org-timestamp-change (- n) (cdr (assoc what whata)))
12824 ;; Rematch, so that we have everything in place
12825 ;; for the real shift.
12826 (org-in-regexp org-ts-regexp3)
12827 (setq ts (match-string 1))
12828 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12829 ts)))))
12830 (save-excursion
12831 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12832 (setq msg
12833 (concat
12834 msg type " " org-last-changed-timestamp " "))))))))
12835 (setq org-log-post-message msg)
12836 (message "%s" msg))
12837 (set-marker end nil))))
12839 (defun org-show-todo-tree (arg)
12840 "Make a compact tree which shows all headlines marked with TODO.
12841 The tree will show the lines where the regexp matches, and all higher
12842 headlines above the match.
12843 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12844 With a numeric prefix N, construct a sparse tree for the Nth element
12845 of `org-todo-keywords-1'."
12846 (interactive "P")
12847 (let ((case-fold-search nil)
12848 (kwd-re
12849 (cond ((null arg) org-not-done-regexp)
12850 ((equal arg '(4))
12851 (let ((kwd
12852 (completing-read "Keyword (or KWD1|KWD2|...): "
12853 (mapcar #'list org-todo-keywords-1))))
12854 (concat "\\("
12855 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12856 "\\)\\>")))
12857 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12858 (regexp-quote (nth (1- (prefix-numeric-value arg))
12859 org-todo-keywords-1)))
12860 (t (user-error "Invalid prefix argument: %s" arg)))))
12861 (message "%d TODO entries found"
12862 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12864 (defun org--deadline-or-schedule (arg type time)
12865 "Insert DEADLINE or SCHEDULE information in current entry.
12866 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12867 `org-schedule' for information about ARG and TIME arguments."
12868 (let* ((deadline? (eq type 'deadline))
12869 (keyword (if deadline? org-deadline-string org-scheduled-string))
12870 (log (if deadline? org-log-redeadline org-log-reschedule))
12871 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12872 (old-date-time (and old-date (org-time-string-to-time old-date)))
12873 ;; Save repeater cookie from either TIME or current scheduled
12874 ;; time stamp. We are going to insert it back at the end of
12875 ;; the process.
12876 (repeater (or (and (org-string-nw-p time)
12877 ;; We use `org-repeat-re' because we need
12878 ;; to tell the difference between a real
12879 ;; repeater and a time delta, e.g. "+2d".
12880 (string-match org-repeat-re time)
12881 (match-string 1 time))
12882 (and (org-string-nw-p old-date)
12883 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12884 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12885 old-date)
12886 (match-string 1 old-date)))))
12887 (pcase arg
12888 (`(4)
12889 (if (not old-date)
12890 (message (if deadline? "Entry had no deadline to remove"
12891 "Entry was not scheduled"))
12892 (when (and old-date log)
12893 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12894 nil old-date log))
12895 (org-remove-timestamp-with-keyword keyword)
12896 (message (if deadline? "Entry no longer has a deadline."
12897 "Entry is no longer scheduled."))))
12898 (`(16)
12899 (save-excursion
12900 (org-back-to-heading t)
12901 (let ((regexp (if deadline? org-deadline-time-regexp
12902 org-scheduled-time-regexp)))
12903 (if (not (re-search-forward regexp (line-end-position 2) t))
12904 (user-error (if deadline? "No deadline information to update"
12905 "No scheduled information to update"))
12906 (let* ((rpl0 (match-string 1))
12907 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12908 (msg (if deadline? "Warn starting from" "Delay until")))
12909 (replace-match
12910 (concat keyword
12911 " <" rpl
12912 (format " -%dd"
12913 (abs (- (time-to-days
12914 (save-match-data
12915 (org-read-date
12916 nil t nil msg old-date-time)))
12917 (time-to-days old-date-time))))
12918 ">") t t))))))
12920 (org-add-planning-info type time 'closed)
12921 (when (and old-date
12923 (not (equal old-date org-last-inserted-timestamp)))
12924 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12925 org-last-inserted-timestamp
12926 old-date
12927 log))
12928 (when repeater
12929 (save-excursion
12930 (org-back-to-heading t)
12931 (when (re-search-forward
12932 (concat keyword " " org-last-inserted-timestamp)
12933 (line-end-position 2)
12935 (goto-char (1- (match-end 0)))
12936 (insert " " repeater)
12937 (setq org-last-inserted-timestamp
12938 (concat (substring org-last-inserted-timestamp 0 -1)
12939 " " repeater
12940 (substring org-last-inserted-timestamp -1))))))
12941 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12942 org-last-inserted-timestamp)))))
12944 (defun org-deadline (arg &optional time)
12945 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12946 With one universal prefix argument, remove any deadline from the item.
12947 With two universal prefix arguments, prompt for a warning delay.
12948 With argument TIME, set the deadline at the corresponding date. TIME
12949 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12950 (interactive "P")
12951 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12952 (org-map-entries
12953 (lambda () (org--deadline-or-schedule arg 'deadline time))
12955 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12956 'region-start-level
12957 'region)
12958 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12959 (org--deadline-or-schedule arg 'deadline time)))
12961 (defun org-schedule (arg &optional time)
12962 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12963 With one universal prefix argument, remove any scheduling date from the item.
12964 With two universal prefix arguments, prompt for a delay cookie.
12965 With argument TIME, scheduled at the corresponding date. TIME can
12966 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12967 (interactive "P")
12968 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12969 (org-map-entries
12970 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12972 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12973 'region-start-level
12974 'region)
12975 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12976 (org--deadline-or-schedule arg 'scheduled time)))
12978 (defun org-get-scheduled-time (pom &optional inherit)
12979 "Get the scheduled time as a time tuple, of a format suitable
12980 for calling org-schedule with, or if there is no scheduling,
12981 returns nil."
12982 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12983 (when time
12984 (apply 'encode-time (org-parse-time-string time)))))
12986 (defun org-get-deadline-time (pom &optional inherit)
12987 "Get the deadline as a time tuple, of a format suitable for
12988 calling org-deadline with, or if there is no scheduling, returns
12989 nil."
12990 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12991 (when time
12992 (apply 'encode-time (org-parse-time-string time)))))
12994 (defun org-remove-timestamp-with-keyword (keyword)
12995 "Remove all time stamps with KEYWORD in the current entry."
12996 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12997 beg)
12998 (save-excursion
12999 (org-back-to-heading t)
13000 (setq beg (point))
13001 (outline-next-heading)
13002 (while (re-search-backward re beg t)
13003 (replace-match "")
13004 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13005 (equal (char-before) ?\ ))
13006 (backward-delete-char 1)
13007 (when (string-match "^[ \t]*$" (buffer-substring
13008 (point-at-bol) (point-at-eol)))
13009 (delete-region (point-at-bol)
13010 (min (point-max) (1+ (point-at-eol))))))))))
13012 (defvar org-time-was-given) ; dynamically scoped parameter
13013 (defvar org-end-time-was-given) ; dynamically scoped parameter
13015 (defun org-at-planning-p ()
13016 "Non-nil when point is on a planning info line."
13017 ;; This is as accurate and faster than `org-element-at-point' since
13018 ;; planning info location is fixed in the section.
13019 (org-with-wide-buffer
13020 (beginning-of-line)
13021 (and (looking-at-p org-planning-line-re)
13022 (eq (point)
13023 (ignore-errors
13024 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13025 (org-back-to-heading t)
13026 (org-with-limited-levels (org-back-to-heading t)))
13027 (line-beginning-position 2))))))
13029 (defun org-add-planning-info (what &optional time &rest remove)
13030 "Insert new timestamp with keyword in the planning line.
13031 WHAT indicates what kind of time stamp to add. It is a symbol
13032 among `closed', `deadline', `scheduled' and nil. TIME indicates
13033 the time to use. If none is given, the user is prompted for
13034 a date. REMOVE indicates what kind of entries to remove. An old
13035 WHAT entry will also be removed."
13036 (let (org-time-was-given org-end-time-was-given default-time default-input)
13037 (catch 'exit
13038 (when (and (memq what '(scheduled deadline))
13039 (or (not time)
13040 (and (stringp time)
13041 (string-match "^[-+]+[0-9]" time))))
13042 ;; Try to get a default date/time from existing timestamp
13043 (save-excursion
13044 (org-back-to-heading t)
13045 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13046 (when (re-search-forward (if (eq what 'scheduled)
13047 org-scheduled-time-regexp
13048 org-deadline-time-regexp)
13049 end t)
13050 (setq ts (match-string 1)
13051 default-time (apply 'encode-time (org-parse-time-string ts))
13052 default-input (and ts (org-get-compact-tod ts)))))))
13053 (when what
13054 (setq time
13055 (if (stringp time)
13056 ;; This is a string (relative or absolute), set
13057 ;; proper date.
13058 (apply #'encode-time
13059 (org-read-date-analyze
13060 time default-time (decode-time default-time)))
13061 ;; If necessary, get the time from the user
13062 (or time (org-read-date nil 'to-time nil
13063 (cl-case what
13064 (deadline "DEADLINE")
13065 (scheduled "SCHEDULED")
13066 (otherwise nil))
13067 default-time default-input)))))
13068 (org-with-wide-buffer
13069 (org-back-to-heading t)
13070 (forward-line)
13071 (unless (bolp) (insert "\n"))
13072 (cond ((looking-at-p org-planning-line-re)
13073 ;; Move to current indentation.
13074 (skip-chars-forward " \t")
13075 ;; Check if we have to remove something.
13076 (dolist (type (if what (cons what remove) remove))
13077 (save-excursion
13078 (when (re-search-forward
13079 (cl-case type
13080 (closed org-closed-time-regexp)
13081 (deadline org-deadline-time-regexp)
13082 (scheduled org-scheduled-time-regexp)
13083 (otherwise
13084 (error "Invalid planning type: %s" type)))
13085 (line-end-position) t)
13086 ;; Delete until next keyword or end of line.
13087 (delete-region
13088 (match-beginning 0)
13089 (if (re-search-forward org-keyword-time-not-clock-regexp
13090 (line-end-position)
13092 (match-beginning 0)
13093 (line-end-position))))))
13094 ;; If there is nothing more to add and no more keyword
13095 ;; is left, remove the line completely.
13096 (if (and (looking-at-p "[ \t]*$") (not what))
13097 (delete-region (line-beginning-position)
13098 (line-beginning-position 2))
13099 ;; If we removed last keyword, do not leave trailing
13100 ;; white space at the end of line.
13101 (let ((p (point)))
13102 (save-excursion
13103 (end-of-line)
13104 (unless (= (skip-chars-backward " \t" p) 0)
13105 (delete-region (point) (line-end-position)))))))
13106 ((not what) (throw 'exit nil)) ; Nothing to do.
13107 (t (insert-before-markers "\n")
13108 (backward-char 1)
13109 (when org-adapt-indentation
13110 (indent-to-column (1+ (org-outline-level))))))
13111 (when what
13112 ;; Insert planning keyword.
13113 (insert (cl-case what
13114 (closed org-closed-string)
13115 (deadline org-deadline-string)
13116 (scheduled org-scheduled-string)
13117 (otherwise (error "Invalid planning type: %s" what)))
13118 " ")
13119 ;; Insert associated timestamp.
13120 (let ((ts (org-insert-time-stamp
13121 time
13122 (or org-time-was-given
13123 (and (eq what 'closed) org-log-done-with-time))
13124 (eq what 'closed)
13125 nil nil (list org-end-time-was-given))))
13126 (unless (eolp) (insert " "))
13127 ts))))))
13129 (defvar org-log-note-marker (make-marker)
13130 "Marker pointing at the entry where the note is to be inserted.")
13131 (defvar org-log-note-purpose nil)
13132 (defvar org-log-note-state nil)
13133 (defvar org-log-note-previous-state nil)
13134 (defvar org-log-note-extra nil)
13135 (defvar org-log-note-window-configuration nil)
13136 (defvar org-log-note-return-to (make-marker))
13137 (defvar org-log-note-effective-time nil
13138 "Remembered current time so that dynamically scoped
13139 `org-extend-today-until' affects timestamps in state change log")
13141 (defvar org-log-post-message nil
13142 "Message to be displayed after a log note has been stored.
13143 The auto-repeater uses this.")
13145 (defun org-add-note ()
13146 "Add a note to the current entry.
13147 This is done in the same way as adding a state change note."
13148 (interactive)
13149 (org-add-log-setup 'note))
13151 (defun org-log-beginning (&optional create)
13152 "Return expected start of log notes in current entry.
13153 When optional argument CREATE is non-nil, the function creates
13154 a drawer to store notes, if necessary. Returned position ignores
13155 narrowing."
13156 (org-with-wide-buffer
13157 (let ((drawer (org-log-into-drawer)))
13158 (cond
13159 (drawer
13160 (org-end-of-meta-data)
13161 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13162 (end (if (org-at-heading-p) (point)
13163 (save-excursion (outline-next-heading) (point))))
13164 (case-fold-search t))
13165 (catch 'exit
13166 ;; Try to find existing drawer.
13167 (while (re-search-forward regexp end t)
13168 (let ((element (org-element-at-point)))
13169 (when (eq (org-element-type element) 'drawer)
13170 (let ((cend (org-element-property :contents-end element)))
13171 (when (and (not org-log-states-order-reversed) cend)
13172 (goto-char cend)))
13173 (throw 'exit nil))))
13174 ;; No drawer found. Create one, if permitted.
13175 (when create
13176 (unless (bolp) (insert "\n"))
13177 (let ((beg (point)))
13178 (insert ":" drawer ":\n:END:\n")
13179 (org-indent-region beg (point))
13180 (org-flag-region
13181 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13182 (end-of-line -1)))))
13184 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13185 (skip-chars-forward " \t\n")
13186 (beginning-of-line)
13187 (unless org-log-states-order-reversed
13188 (org-skip-over-state-notes)
13189 (skip-chars-backward " \t\n")
13190 (forward-line)))))
13191 (if (bolp) (point) (line-beginning-position 2))))
13193 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13194 "Set up the post command hook to take a note.
13195 If this is about to TODO state change, the new state is expected in STATE.
13196 HOW is an indicator what kind of note should be created.
13197 EXTRA is additional text that will be inserted into the notes buffer."
13198 (move-marker org-log-note-marker (point))
13199 (setq org-log-note-purpose purpose
13200 org-log-note-state state
13201 org-log-note-previous-state prev-state
13202 org-log-note-how how
13203 org-log-note-extra extra
13204 org-log-note-effective-time (org-current-effective-time))
13205 (add-hook 'post-command-hook 'org-add-log-note 'append))
13207 (defun org-skip-over-state-notes ()
13208 "Skip past the list of State notes in an entry."
13209 (when (ignore-errors (goto-char (org-in-item-p)))
13210 (let* ((struct (org-list-struct))
13211 (prevs (org-list-prevs-alist struct))
13212 (regexp
13213 (concat "[ \t]*- +"
13214 (replace-regexp-in-string
13215 " +" " +"
13216 (org-replace-escapes
13217 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13218 `(("%d" . ,org-ts-regexp-inactive)
13219 ("%D" . ,org-ts-regexp)
13220 ("%s" . "\\(?:\"\\S-+\"\\)?")
13221 ("%S" . "\\(?:\"\\S-+\"\\)?")
13222 ("%t" . ,org-ts-regexp-inactive)
13223 ("%T" . ,org-ts-regexp)
13224 ("%u" . ".*?")
13225 ("%U" . ".*?")))))))
13226 (while (looking-at-p regexp)
13227 (goto-char (or (org-list-get-next-item (point) struct prevs)
13228 (org-list-get-item-end (point) struct)))))))
13230 (defun org-add-log-note (&optional _purpose)
13231 "Pop up a window for taking a note, and add this note later."
13232 (remove-hook 'post-command-hook 'org-add-log-note)
13233 (setq org-log-note-window-configuration (current-window-configuration))
13234 (delete-other-windows)
13235 (move-marker org-log-note-return-to (point))
13236 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13237 (goto-char org-log-note-marker)
13238 (org-switch-to-buffer-other-window "*Org Note*")
13239 (erase-buffer)
13240 (if (memq org-log-note-how '(time state))
13241 (org-store-log-note)
13242 (let ((org-inhibit-startup t)) (org-mode))
13243 (insert (format "# Insert note for %s.
13244 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13245 (cl-case org-log-note-purpose
13246 (clock-out "stopped clock")
13247 (done "closed todo item")
13248 (reschedule "rescheduling")
13249 (delschedule "no longer scheduled")
13250 (redeadline "changing deadline")
13251 (deldeadline "removing deadline")
13252 (refile "refiling")
13253 (note "this entry")
13254 (state
13255 (format "state change from \"%s\" to \"%s\""
13256 (or org-log-note-previous-state "")
13257 (or org-log-note-state "")))
13258 (t (error "This should not happen")))))
13259 (when org-log-note-extra (insert org-log-note-extra))
13260 (setq-local org-finish-function 'org-store-log-note)
13261 (run-hooks 'org-log-buffer-setup-hook)))
13263 (defvar org-note-abort nil) ; dynamically scoped
13264 (defun org-store-log-note ()
13265 "Finish taking a log note, and insert it to where it belongs."
13266 (let ((txt (prog1 (buffer-string)
13267 (kill-buffer)))
13268 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13269 lines)
13270 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13271 (setq txt (replace-match "" t t txt)))
13272 (when (string-match "\\s-+\\'" txt)
13273 (setq txt (replace-match "" t t txt)))
13274 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13275 (when (org-string-nw-p note)
13276 (setq note
13277 (org-replace-escapes
13278 note
13279 (list (cons "%u" (user-login-name))
13280 (cons "%U" user-full-name)
13281 (cons "%t" (format-time-string
13282 (org-time-stamp-format 'long 'inactive)
13283 org-log-note-effective-time))
13284 (cons "%T" (format-time-string
13285 (org-time-stamp-format 'long nil)
13286 org-log-note-effective-time))
13287 (cons "%d" (format-time-string
13288 (org-time-stamp-format nil 'inactive)
13289 org-log-note-effective-time))
13290 (cons "%D" (format-time-string
13291 (org-time-stamp-format nil nil)
13292 org-log-note-effective-time))
13293 (cons "%s" (cond
13294 ((not org-log-note-state) "")
13295 ((string-match-p org-ts-regexp
13296 org-log-note-state)
13297 (format "\"[%s]\""
13298 (substring org-log-note-state 1 -1)))
13299 (t (format "\"%s\"" org-log-note-state))))
13300 (cons "%S"
13301 (cond
13302 ((not org-log-note-previous-state) "")
13303 ((string-match-p org-ts-regexp
13304 org-log-note-previous-state)
13305 (format "\"[%s]\""
13306 (substring
13307 org-log-note-previous-state 1 -1)))
13308 (t (format "\"%s\""
13309 org-log-note-previous-state)))))))
13310 (when lines (setq note (concat note " \\\\")))
13311 (push note lines))
13312 (when (and lines (not org-note-abort))
13313 (with-current-buffer (marker-buffer org-log-note-marker)
13314 (org-with-wide-buffer
13315 ;; Find location for the new note.
13316 (goto-char org-log-note-marker)
13317 (set-marker org-log-note-marker nil)
13318 ;; Note associated to a clock is to be located right after
13319 ;; the clock. Do not move point.
13320 (unless (eq org-log-note-purpose 'clock-out)
13321 (goto-char (org-log-beginning t)))
13322 ;; Make sure point is at the beginning of an empty line.
13323 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13324 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13325 ;; In an existing list, add a new item at the top level.
13326 ;; Otherwise, indent line like a regular one.
13327 (let ((itemp (org-in-item-p)))
13328 (if itemp
13329 (indent-line-to
13330 (let ((struct (save-excursion
13331 (goto-char itemp) (org-list-struct))))
13332 (org-list-get-ind (org-list-get-top-point struct) struct)))
13333 (org-indent-line)))
13334 (insert (org-list-bullet-string "-") (pop lines))
13335 (let ((ind (org-list-item-body-column (line-beginning-position))))
13336 (dolist (line lines)
13337 (insert "\n")
13338 (indent-line-to ind)
13339 (insert line)))
13340 (message "Note stored")
13341 (org-back-to-heading t))
13342 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13343 ;; from within `org-add-log-note' because `buffer-undo-list'
13344 ;; is then modified outside of `org-with-remote-undo'.
13345 (when (eq this-command 'org-agenda-todo)
13346 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13347 ;; Don't add undo information when called from `org-agenda-todo'.
13348 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13349 (set-window-configuration org-log-note-window-configuration)
13350 (with-current-buffer (marker-buffer org-log-note-return-to)
13351 (goto-char org-log-note-return-to))
13352 (move-marker org-log-note-return-to nil)
13353 (when org-log-post-message (message "%s" org-log-post-message))))
13355 (defun org-remove-empty-drawer-at (pos)
13356 "Remove an empty drawer at position POS.
13357 POS may also be a marker."
13358 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13359 (org-with-wide-buffer
13360 (goto-char pos)
13361 (let ((drawer (org-element-at-point)))
13362 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13363 (not (org-element-property :contents-begin drawer)))
13364 (delete-region (org-element-property :begin drawer)
13365 (progn (goto-char (org-element-property :end drawer))
13366 (skip-chars-backward " \r\t\n")
13367 (forward-line)
13368 (point))))))))
13370 (defvar org-ts-type nil)
13371 (defun org-sparse-tree (&optional arg type)
13372 "Create a sparse tree, prompt for the details.
13373 This command can create sparse trees. You first need to select the type
13374 of match used to create the tree:
13376 t Show all TODO entries.
13377 T Show entries with a specific TODO keyword.
13378 m Show entries selected by a tags/property match.
13379 p Enter a property name and its value (both with completion on existing
13380 names/values) and show entries with that property.
13381 r Show entries matching a regular expression (`/' can be used as well).
13382 b Show deadlines and scheduled items before a date.
13383 a Show deadlines and scheduled items after a date.
13384 d Show deadlines due within `org-deadline-warning-days'.
13385 D Show deadlines and scheduled items between a date range."
13386 (interactive "P")
13387 (setq type (or type org-sparse-tree-default-date-type))
13388 (setq org-ts-type type)
13389 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13390 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13391 \[c]ycle through date types: %s"
13392 (cl-case type
13393 (all "all timestamps")
13394 (scheduled "only scheduled")
13395 (deadline "only deadline")
13396 (active "only active timestamps")
13397 (inactive "only inactive timestamps")
13398 (closed "with a closed time-stamp")
13399 (otherwise "scheduled/deadline")))
13400 (let ((answer (read-char-exclusive)))
13401 (cl-case answer
13403 (org-sparse-tree
13405 (cadr
13406 (memq type '(nil all scheduled deadline active inactive closed)))))
13407 (?d (call-interactively 'org-check-deadlines))
13408 (?b (call-interactively 'org-check-before-date))
13409 (?a (call-interactively 'org-check-after-date))
13410 (?D (call-interactively 'org-check-dates-range))
13411 (?t (call-interactively 'org-show-todo-tree))
13412 (?T (org-show-todo-tree '(4)))
13413 (?m (call-interactively 'org-match-sparse-tree))
13414 ((?p ?P)
13415 (let* ((kwd (completing-read
13416 "Property: " (mapcar #'list (org-buffer-property-keys))))
13417 (value (completing-read
13418 "Value: " (mapcar #'list (org-property-values kwd)))))
13419 (unless (string-match "\\`{.*}\\'" value)
13420 (setq value (concat "\"" value "\"")))
13421 (org-match-sparse-tree arg (concat kwd "=" value))))
13422 ((?r ?R ?/) (call-interactively 'org-occur))
13423 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13425 (defvar-local org-occur-highlights nil
13426 "List of overlays used for occur matches.")
13427 (defvar-local org-occur-parameters nil
13428 "Parameters of the active org-occur calls.
13429 This is a list, each call to org-occur pushes as cons cell,
13430 containing the regular expression and the callback, onto the list.
13431 The list can contain several entries if `org-occur' has been called
13432 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13433 will only contain one set of parameters. When the highlights are
13434 removed (for example with `C-c C-c', or with the next edit (depending
13435 on `org-remove-highlights-with-change'), this variable is emptied
13436 as well.")
13438 (defun org-occur (regexp &optional keep-previous callback)
13439 "Make a compact tree which shows all matches of REGEXP.
13441 The tree will show the lines where the regexp matches, and any other context
13442 defined in `org-show-context-detail', which see.
13444 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13445 done by a previous call to `org-occur' will be kept, to allow stacking of
13446 calls to this command.
13448 Optional argument CALLBACK can be a function of no argument. In this case,
13449 it is called with point at the end of the match, match data being set
13450 accordingly. Current match is shown only if the return value is non-nil.
13451 The function must neither move point nor alter narrowing."
13452 (interactive "sRegexp: \nP")
13453 (when (equal regexp "")
13454 (user-error "Regexp cannot be empty"))
13455 (unless keep-previous
13456 (org-remove-occur-highlights nil nil t))
13457 (push (cons regexp callback) org-occur-parameters)
13458 (let ((cnt 0))
13459 (save-excursion
13460 (goto-char (point-min))
13461 (when (or (not keep-previous) ; do not want to keep
13462 (not org-occur-highlights)) ; no previous matches
13463 ;; hide everything
13464 (org-overview))
13465 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13466 (isearch-no-upper-case-p regexp t)
13467 org-occur-case-fold-search)))
13468 (while (re-search-forward regexp nil t)
13469 (when (or (not callback)
13470 (save-match-data (funcall callback)))
13471 (setq cnt (1+ cnt))
13472 (when org-highlight-sparse-tree-matches
13473 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13474 (org-show-context 'occur-tree)))))
13475 (when org-remove-highlights-with-change
13476 (add-hook 'before-change-functions 'org-remove-occur-highlights
13477 nil 'local))
13478 (unless org-sparse-tree-open-archived-trees
13479 (org-hide-archived-subtrees (point-min) (point-max)))
13480 (run-hooks 'org-occur-hook)
13481 (when (called-interactively-p 'interactive)
13482 (message "%d match(es) for regexp %s" cnt regexp))
13483 cnt))
13485 (defun org-occur-next-match (&optional n _reset)
13486 "Function for `next-error-function' to find sparse tree matches.
13487 N is the number of matches to move, when negative move backwards.
13488 This function always goes back to the starting point when no
13489 match is found."
13490 (let* ((limit (if (< n 0) (point-min) (point-max)))
13491 (search-func (if (< n 0)
13492 'previous-single-char-property-change
13493 'next-single-char-property-change))
13494 (n (abs n))
13495 (pos (point))
13497 (catch 'exit
13498 (while (setq p1 (funcall search-func (point) 'org-type))
13499 (when (equal p1 limit)
13500 (goto-char pos)
13501 (user-error "No more matches"))
13502 (when (equal (get-char-property p1 'org-type) 'org-occur)
13503 (setq n (1- n))
13504 (when (= n 0)
13505 (goto-char p1)
13506 (throw 'exit (point))))
13507 (goto-char p1))
13508 (goto-char p1)
13509 (user-error "No more matches"))))
13511 (defun org-highlight-new-match (beg end)
13512 "Highlight from BEG to END and mark the highlight is an occur headline."
13513 (let ((ov (make-overlay beg end)))
13514 (overlay-put ov 'face 'secondary-selection)
13515 (overlay-put ov 'org-type 'org-occur)
13516 (push ov org-occur-highlights)))
13518 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13519 "Remove the occur highlights from the buffer.
13520 BEG and END are ignored. If NOREMOVE is nil, remove this function
13521 from the `before-change-functions' in the current buffer."
13522 (interactive)
13523 (unless org-inhibit-highlight-removal
13524 (mapc #'delete-overlay org-occur-highlights)
13525 (setq org-occur-highlights nil)
13526 (setq org-occur-parameters nil)
13527 (unless noremove
13528 (remove-hook 'before-change-functions
13529 'org-remove-occur-highlights 'local))))
13531 ;;;; Priorities
13533 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13534 "Regular expression matching the priority indicator.")
13536 (defvar org-remove-priority-next-time nil)
13538 (defun org-priority-up ()
13539 "Increase the priority of the current item."
13540 (interactive)
13541 (org-priority 'up))
13543 (defun org-priority-down ()
13544 "Decrease the priority of the current item."
13545 (interactive)
13546 (org-priority 'down))
13548 (defun org-priority (&optional action show)
13549 "Change the priority of an item.
13551 When called interactively with a `\\[universal-argument]' prefix,
13552 show the priority in the minibuffer instead of changing it.
13554 When called programatically, ACTION can be `set', `up', `down',
13555 or a character."
13556 (interactive "P")
13557 (when show
13558 ;; Deprecation warning inserted for Org 9.2; once enough time has
13559 ;; passed the SHOW argument should be removed.
13560 (warn "`org-priority' called with deprecated SHOW argument"))
13561 (if (equal action '(4))
13562 (org-show-priority)
13563 (unless org-enable-priority-commands
13564 (user-error "Priority commands are disabled"))
13565 (setq action (or action 'set))
13566 (let (current new news have remove)
13567 (save-excursion
13568 (org-back-to-heading t)
13569 (when (looking-at org-priority-regexp)
13570 (setq current (string-to-char (match-string 2))
13571 have t))
13572 (cond
13573 ((eq action 'remove)
13574 (setq remove t new ?\ ))
13575 ((or (eq action 'set)
13576 (integerp action))
13577 (if (not (eq action 'set))
13578 (setq new action)
13579 (message "Priority %c-%c, SPC to remove: "
13580 org-highest-priority org-lowest-priority)
13581 (save-match-data
13582 (setq new (read-char-exclusive))))
13583 (when (and (= (upcase org-highest-priority) org-highest-priority)
13584 (= (upcase org-lowest-priority) org-lowest-priority))
13585 (setq new (upcase new)))
13586 (cond ((equal new ?\s) (setq remove t))
13587 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13588 (user-error "Priority must be between `%c' and `%c'"
13589 org-highest-priority org-lowest-priority))))
13590 ((eq action 'up)
13591 (setq new (if have
13592 (1- current) ; normal cycling
13593 ;; last priority was empty
13594 (if (eq last-command this-command)
13595 org-lowest-priority ; wrap around empty to lowest
13596 ;; default
13597 (if org-priority-start-cycle-with-default
13598 org-default-priority
13599 (1- org-default-priority))))))
13600 ((eq action 'down)
13601 (setq new (if have
13602 (1+ current) ; normal cycling
13603 ;; last priority was empty
13604 (if (eq last-command this-command)
13605 org-highest-priority ; wrap around empty to highest
13606 ;; default
13607 (if org-priority-start-cycle-with-default
13608 org-default-priority
13609 (1+ org-default-priority))))))
13610 (t (user-error "Invalid action")))
13611 (when (or (< (upcase new) org-highest-priority)
13612 (> (upcase new) org-lowest-priority))
13613 (if (and (memq action '(up down))
13614 (not have) (not (eq last-command this-command)))
13615 ;; `new' is from default priority
13616 (error
13617 "The default can not be set, see `org-default-priority' why")
13618 ;; normal cycling: `new' is beyond highest/lowest priority
13619 ;; and is wrapped around to the empty priority
13620 (setq remove t)))
13621 (setq news (format "%c" new))
13622 (if have
13623 (if remove
13624 (replace-match "" t t nil 1)
13625 (replace-match news t t nil 2))
13626 (if remove
13627 (user-error "No priority cookie found in line")
13628 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13629 (if (match-end 2)
13630 (progn
13631 (goto-char (match-end 2))
13632 (insert " [#" news "]"))
13633 (goto-char (match-beginning 3))
13634 (insert "[#" news "] "))))
13635 (org-align-tags))
13636 (if remove
13637 (message "Priority removed")
13638 (message "Priority of current item set to %s" news)))))
13640 (defun org-show-priority ()
13641 "Show the priority of the current item.
13642 This priority is composed of the main priority given with the [#A] cookies,
13643 and by additional input from the age of a schedules or deadline entry."
13644 (interactive)
13645 (let ((pri (if (eq major-mode 'org-agenda-mode)
13646 (org-get-at-bol 'priority)
13647 (save-excursion
13648 (save-match-data
13649 (beginning-of-line)
13650 (and (looking-at org-heading-regexp)
13651 (org-get-priority (match-string 0))))))))
13652 (message "Priority is %d" (if pri pri -1000))))
13654 (defun org-get-priority (s)
13655 "Find priority cookie and return priority."
13656 (save-match-data
13657 (if (functionp org-get-priority-function)
13658 (funcall org-get-priority-function)
13659 (if (not (string-match org-priority-regexp s))
13660 (* 1000 (- org-lowest-priority org-default-priority))
13661 (* 1000 (- org-lowest-priority
13662 (string-to-char (match-string 2 s))))))))
13664 ;;;; Tags
13666 (defvar org-agenda-archives-mode)
13667 (defvar org-map-continue-from nil
13668 "Position from where mapping should continue.
13669 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13671 (defvar org-scanner-tags nil
13672 "The current tag list while the tags scanner is running.")
13674 (defvar org-trust-scanner-tags nil
13675 "Should `org-get-tags' use the tags for the scanner.
13676 This is for internal dynamical scoping only.
13677 When this is non-nil, the function `org-get-tags' will return the value
13678 of `org-scanner-tags' instead of building the list by itself. This
13679 can lead to large speed-ups when the tags scanner is used in a file with
13680 many entries, and when the list of tags is retrieved, for example to
13681 obtain a list of properties. Building the tags list for each entry in such
13682 a file becomes an N^2 operation - but with this variable set, it scales
13683 as N.")
13685 (defvar org--matcher-tags-todo-only nil)
13687 (defun org-scan-tags (action matcher todo-only &optional start-level)
13688 "Scan headline tags with inheritance and produce output ACTION.
13690 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13691 or `agenda' to produce an entry list for an agenda view. It can also be
13692 a Lisp form or a function that should be called at each matched headline, in
13693 this case the return value is a list of all return values from these calls.
13695 MATCHER is a function accepting three arguments, returning
13696 a non-nil value whenever a given set of tags qualifies a headline
13697 for inclusion. See `org-make-tags-matcher' for more information.
13698 As a special case, it can also be set to t (respectively nil) in
13699 order to match all (respectively none) headline.
13701 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13702 included in the output.
13704 START-LEVEL can be a string with asterisks, reducing the scope to
13705 headlines matching this string."
13706 (require 'org-agenda)
13707 (let* ((re (concat "^"
13708 (if start-level
13709 ;; Get the correct level to match
13710 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13711 org-outline-regexp)
13712 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13713 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13714 (props (list 'face 'default
13715 'done-face 'org-agenda-done
13716 'undone-face 'default
13717 'mouse-face 'highlight
13718 'org-not-done-regexp org-not-done-regexp
13719 'org-todo-regexp org-todo-regexp
13720 'org-complex-heading-regexp org-complex-heading-regexp
13721 'help-echo
13722 (format "mouse-2 or RET jump to Org file %S"
13723 (abbreviate-file-name
13724 (or (buffer-file-name (buffer-base-buffer))
13725 (buffer-name (buffer-base-buffer)))))))
13726 (org-map-continue-from nil)
13727 lspos tags tags-list
13728 (tags-alist (list (cons 0 org-file-tags)))
13729 (llast 0) rtn rtn1 level category i txt
13730 todo marker entry priority
13731 ts-date ts-date-type ts-date-pair)
13732 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13733 (setq action (list 'lambda nil action)))
13734 (save-excursion
13735 (goto-char (point-min))
13736 (when (eq action 'sparse-tree)
13737 (org-overview)
13738 (org-remove-occur-highlights))
13739 (while (let (case-fold-search)
13740 (re-search-forward re nil t))
13741 (setq org-map-continue-from nil)
13742 (catch :skip
13743 ;; Ignore closing parts of inline tasks.
13744 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13745 (throw :skip t))
13746 (setq todo (and (match-end 1) (match-string-no-properties 1)))
13747 (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
13748 (goto-char (setq lspos (match-beginning 0)))
13749 (setq level (org-reduced-level (org-outline-level))
13750 category (org-get-category))
13751 (when (eq action 'agenda)
13752 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13753 ts-date (car ts-date-pair)
13754 ts-date-type (cdr ts-date-pair)))
13755 (setq i llast llast level)
13756 ;; remove tag lists from same and sublevels
13757 (while (>= i level)
13758 (when (setq entry (assoc i tags-alist))
13759 (setq tags-alist (delete entry tags-alist)))
13760 (setq i (1- i)))
13761 ;; add the next tags
13762 (when tags
13763 (setq tags (org-split-string tags ":")
13764 tags-alist
13765 (cons (cons level tags) tags-alist)))
13766 ;; compile tags for current headline
13767 (setq tags-list
13768 (if org-use-tag-inheritance
13769 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13770 tags)
13771 org-scanner-tags tags-list)
13772 (when org-use-tag-inheritance
13773 (setcdr (car tags-alist)
13774 (mapcar (lambda (x)
13775 (setq x (copy-sequence x))
13776 (org-add-prop-inherited x))
13777 (cdar tags-alist))))
13778 (when (and tags org-use-tag-inheritance
13779 (or (not (eq t org-use-tag-inheritance))
13780 org-tags-exclude-from-inheritance))
13781 ;; Selective inheritance, remove uninherited ones.
13782 (setcdr (car tags-alist)
13783 (org-remove-uninherited-tags (cdar tags-alist))))
13784 (when (and
13786 ;; eval matcher only when the todo condition is OK
13787 (and (or (not todo-only) (member todo org-todo-keywords-1))
13788 (if (functionp matcher)
13789 (let ((case-fold-search t) (org-trust-scanner-tags t))
13790 (funcall matcher todo tags-list level))
13791 matcher))
13793 ;; Call the skipper, but return t if it does not
13794 ;; skip, so that the `and' form continues evaluating.
13795 (progn
13796 (unless (eq action 'sparse-tree) (org-agenda-skip))
13799 ;; Check if timestamps are deselecting this entry
13800 (or (not todo-only)
13801 (and (member todo org-todo-keywords-1)
13802 (or (not org-agenda-tags-todo-honor-ignore-options)
13803 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13805 ;; select this headline
13806 (cond
13807 ((eq action 'sparse-tree)
13808 (and org-highlight-sparse-tree-matches
13809 (org-get-heading) (match-end 0)
13810 (org-highlight-new-match
13811 (match-beginning 1) (match-end 1)))
13812 (org-show-context 'tags-tree))
13813 ((eq action 'agenda)
13814 (setq txt (org-agenda-format-item
13816 (concat
13817 (if (eq org-tags-match-list-sublevels 'indented)
13818 (make-string (1- level) ?.) "")
13819 (org-get-heading))
13820 (make-string level ?\s)
13821 category
13822 tags-list)
13823 priority (org-get-priority txt))
13824 (goto-char lspos)
13825 (setq marker (org-agenda-new-marker))
13826 (org-add-props txt props
13827 'org-marker marker 'org-hd-marker marker 'org-category category
13828 'todo-state todo
13829 'ts-date ts-date
13830 'priority priority
13831 'type (concat "tagsmatch" ts-date-type))
13832 (push txt rtn))
13833 ((functionp action)
13834 (setq org-map-continue-from nil)
13835 (save-excursion
13836 (setq rtn1 (funcall action))
13837 (push rtn1 rtn)))
13838 (t (user-error "Invalid action")))
13840 ;; if we are to skip sublevels, jump to end of subtree
13841 (unless org-tags-match-list-sublevels
13842 (org-end-of-subtree t)
13843 (backward-char 1))))
13844 ;; Get the correct position from where to continue
13845 (if org-map-continue-from
13846 (goto-char org-map-continue-from)
13847 (and (= (point) lspos) (end-of-line 1)))))
13848 (when (and (eq action 'sparse-tree)
13849 (not org-sparse-tree-open-archived-trees))
13850 (org-hide-archived-subtrees (point-min) (point-max)))
13851 (nreverse rtn)))
13853 (defun org-remove-uninherited-tags (tags)
13854 "Remove all tags that are not inherited from the list TAGS."
13855 (cond
13856 ((eq org-use-tag-inheritance t)
13857 (if org-tags-exclude-from-inheritance
13858 (org-delete-all org-tags-exclude-from-inheritance tags)
13859 tags))
13860 ((not org-use-tag-inheritance) nil)
13861 ((stringp org-use-tag-inheritance)
13862 (delq nil (mapcar
13863 (lambda (x)
13864 (if (and (string-match org-use-tag-inheritance x)
13865 (not (member x org-tags-exclude-from-inheritance)))
13866 x nil))
13867 tags)))
13868 ((listp org-use-tag-inheritance)
13869 (delq nil (mapcar
13870 (lambda (x)
13871 (if (member x org-use-tag-inheritance) x nil))
13872 tags)))))
13874 (defun org-match-sparse-tree (&optional todo-only match)
13875 "Create a sparse tree according to tags string MATCH.
13877 MATCH is a string with match syntax. It can contain a selection
13878 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13879 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13880 those. See the manual for details.
13882 If optional argument TODO-ONLY is non-nil, only select lines that
13883 are also TODO tasks."
13884 (interactive "P")
13885 (org-agenda-prepare-buffers (list (current-buffer)))
13886 (let ((org--matcher-tags-todo-only todo-only))
13887 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13888 org--matcher-tags-todo-only)))
13890 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13892 (defvar org-cached-props nil)
13893 (defun org-cached-entry-get (pom property)
13894 (if (or (eq t org-use-property-inheritance)
13895 (and (stringp org-use-property-inheritance)
13896 (let ((case-fold-search t))
13897 (string-match-p org-use-property-inheritance property)))
13898 (and (listp org-use-property-inheritance)
13899 (member-ignore-case property org-use-property-inheritance)))
13900 ;; Caching is not possible, check it directly.
13901 (org-entry-get pom property 'inherit)
13902 ;; Get all properties, so we can do complicated checks easily.
13903 (cdr (assoc-string property
13904 (or org-cached-props
13905 (setq org-cached-props (org-entry-properties pom)))
13906 t))))
13908 (defun org-global-tags-completion-table (&optional files)
13909 "Return the list of all tags in all agenda buffer/files.
13910 Optional FILES argument is a list of files which can be used
13911 instead of the agenda files."
13912 (save-excursion
13913 (org-uniquify
13914 (delq nil
13915 (apply #'append
13916 (mapcar
13917 (lambda (file)
13918 (set-buffer (find-file-noselect file))
13919 (org--tag-add-to-alist
13920 (org-get-buffer-tags)
13921 (mapcar (lambda (x)
13922 (and (stringp (car-safe x))
13923 (list (car-safe x))))
13924 org-current-tag-alist)))
13925 (if (car-safe files) files
13926 (org-agenda-files))))))))
13928 (defun org-make-tags-matcher (match)
13929 "Create the TAGS/TODO matcher form for the selection string MATCH.
13931 Returns a cons of the selection string MATCH and a function
13932 implementing the matcher.
13934 The matcher is to be called at an Org entry, with point on the
13935 headline, and returns non-nil if the entry matches the selection
13936 string MATCH. It must be called with three arguments: the TODO
13937 keyword at the entry (or nil if none), the list of all tags at
13938 the entry including inherited ones and the reduced level of the
13939 headline. Additionally, the category of the entry, if any, must
13940 be specified as the text property `org-category' on the headline.
13942 This function sets the variable `org--matcher-tags-todo-only' to
13943 a non-nil value if the matcher restricts matching to TODO
13944 entries, otherwise it is not touched.
13946 See also `org-scan-tags'."
13947 (unless match
13948 ;; Get a new match request, with completion against the global
13949 ;; tags table and the local tags in current buffer.
13950 (let ((org-last-tags-completion-table
13951 (org--tag-add-to-alist
13952 (org-get-buffer-tags)
13953 (org-global-tags-completion-table))))
13954 (setq match
13955 (completing-read
13956 "Match: "
13957 'org-tags-completion-function nil nil nil 'org-tags-history))))
13959 (let ((match0 match)
13960 (re (concat
13961 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13962 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13963 "\\([<>=]\\{1,2\\}\\)"
13964 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13965 "\\|" org-tag-re "\\)"))
13966 (start 0)
13967 tagsmatch todomatch tagsmatcher todomatcher)
13969 ;; Expand group tags.
13970 (setq match (org-tags-expand match))
13972 ;; Check if there is a TODO part of this match, which would be the
13973 ;; part after a "/". To make sure that this slash is not part of
13974 ;; a property value to be matched against, we also check that
13975 ;; there is no / after that slash. First, find the last slash.
13976 (let ((s 0))
13977 (while (string-match "/+" match s)
13978 (setq start (match-beginning 0))
13979 (setq s (match-end 0))))
13980 (if (and (string-match "/+" match start)
13981 (not (string-match-p "\"" match start)))
13982 ;; Match contains also a TODO-matching request.
13983 (progn
13984 (setq tagsmatch (substring match 0 (match-beginning 0)))
13985 (setq todomatch (substring match (match-end 0)))
13986 (when (string-prefix-p "!" todomatch)
13987 (setq org--matcher-tags-todo-only t)
13988 (setq todomatch (substring todomatch 1)))
13989 (when (string-match "\\`\\s-*\\'" todomatch)
13990 (setq todomatch nil)))
13991 ;; Only matching tags.
13992 (setq tagsmatch match)
13993 (setq todomatch nil))
13995 ;; Make the tags matcher.
13996 (when (org-string-nw-p tagsmatch)
13997 (let ((orlist nil)
13998 (orterms (org-split-string tagsmatch "|"))
13999 term)
14000 (while (setq term (pop orterms))
14001 (while (and (equal (substring term -1) "\\") orterms)
14002 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14003 (while (string-match re term)
14004 (let* ((rest (substring term (match-end 0)))
14005 (minus (and (match-end 1)
14006 (equal (match-string 1 term) "-")))
14007 (tag (save-match-data
14008 (replace-regexp-in-string
14009 "\\\\-" "-" (match-string 2 term))))
14010 (regexp (eq (string-to-char tag) ?{))
14011 (levelp (match-end 4))
14012 (propp (match-end 5))
14014 (cond
14015 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14016 (levelp
14017 `(,(org-op-to-function (match-string 3 term))
14018 level
14019 ,(string-to-number (match-string 4 term))))
14020 (propp
14021 (let* ((gv (pcase (upcase (match-string 5 term))
14022 ("CATEGORY"
14023 '(get-text-property (point) 'org-category))
14024 ("TODO" 'todo)
14025 (p `(org-cached-entry-get nil ,p))))
14026 (pv (match-string 7 term))
14027 (regexp (eq (string-to-char pv) ?{))
14028 (strp (eq (string-to-char pv) ?\"))
14029 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14030 (po (org-op-to-function (match-string 6 term)
14031 (if timep 'time strp))))
14032 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14033 (when timep (setq pv (org-matcher-time pv)))
14034 (cond ((and regexp (eq po '/=))
14035 `(not (string-match ,pv (or ,gv ""))))
14036 (regexp `(string-match ,pv (or ,gv "")))
14037 (strp `(,po (or ,gv "") ,pv))
14039 `(,po
14040 (string-to-number (or ,gv ""))
14041 ,(string-to-number pv))))))
14042 (t `(member ,tag tags-list)))))
14043 (push (if minus `(not ,mm) mm) tagsmatcher)
14044 (setq term rest)))
14045 (push `(and ,@tagsmatcher) orlist)
14046 (setq tagsmatcher nil))
14047 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14049 ;; Make the TODO matcher.
14050 (when (org-string-nw-p todomatch)
14051 (let ((orlist nil))
14052 (dolist (term (org-split-string todomatch "|"))
14053 (while (string-match re term)
14054 (let* ((minus (and (match-end 1)
14055 (equal (match-string 1 term) "-")))
14056 (kwd (match-string 2 term))
14057 (regexp (eq (string-to-char kwd) ?{))
14058 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14059 `(equal todo ,kwd))))
14060 (push (if minus `(not ,mm) mm) todomatcher))
14061 (setq term (substring term (match-end 0))))
14062 (push (if (> (length todomatcher) 1)
14063 (cons 'and todomatcher)
14064 (car todomatcher))
14065 orlist)
14066 (setq todomatcher nil))
14067 (setq todomatcher (cons 'or orlist))))
14069 ;; Return the string and function of the matcher. If no
14070 ;; tags-specific or todo-specific matcher exists, match
14071 ;; everything.
14072 (let ((matcher (if (and tagsmatcher todomatcher)
14073 `(and ,tagsmatcher ,todomatcher)
14074 (or tagsmatcher todomatcher t))))
14075 (when org--matcher-tags-todo-only
14076 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14077 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14079 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14080 "Expand group tags in MATCH.
14082 This replaces every group tag in MATCH with a regexp tag search.
14083 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14084 will be replaced like this:
14086 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14087 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14088 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14090 Replacing by a regexp preserves the structure of the match.
14091 E.g., this expansion
14093 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14095 will match anything tagged with \"Lab\" and \"Home\", or tagged
14096 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14098 A group tag in MATCH can contain regular expressions of its own.
14099 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14100 will be replaced like this:
14102 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14104 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14105 assumed to be a single group tag, and the function will return
14106 the list of tags in this group.
14108 When DOWNCASE is non-nil, expand downcased TAGS."
14109 (if org-group-tags
14110 (let* ((case-fold-search t)
14111 (stable org-mode-syntax-table)
14112 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14113 (taggroups (if downcased
14114 (mapcar (lambda (tg) (mapcar #'downcase tg))
14115 taggroups)
14116 taggroups))
14117 (taggroups-keys (mapcar #'car taggroups))
14118 (return-match (if downcased (downcase match) match))
14119 (count 0)
14120 (work-already-expanded tags-already-expanded)
14121 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14122 ;; @ and _ are allowed as word-components in tags.
14123 (modify-syntax-entry ?@ "w" stable)
14124 (modify-syntax-entry ?_ "w" stable)
14125 ;; Temporarily replace regexp-expressions in the match-expression.
14126 (while (string-match "{.+?}" return-match)
14127 (cl-incf count)
14128 (push (match-string 0 return-match) regexps-in-match)
14129 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14130 (while (and taggroups-keys
14131 (with-syntax-table stable
14132 (string-match
14133 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14134 (regexp-opt taggroups-keys) "\\>\\)")
14135 return-match)))
14136 (let* ((dir (match-string 1 return-match))
14137 (tag (match-string 2 return-match))
14138 (tag (if downcased (downcase tag) tag)))
14139 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14140 (member tag tags-already-expanded))
14141 (setq tags-in-group (assoc tag taggroups))
14142 (push tag work-already-expanded)
14143 ;; Recursively expand each tag in the group, if the tag hasn't
14144 ;; already been expanded. Restore the match-data after all recursive calls.
14145 (save-match-data
14146 (let (tags-expanded)
14147 (dolist (x (cdr tags-in-group))
14148 (if (and (member x taggroups-keys)
14149 (not (member x work-already-expanded)))
14150 (setq tags-expanded
14151 (delete-dups
14152 (append
14153 (org-tags-expand x t downcased
14154 work-already-expanded)
14155 tags-expanded)))
14156 (setq tags-expanded
14157 (append (list x) tags-expanded)))
14158 (setq work-already-expanded
14159 (delete-dups
14160 (append tags-expanded
14161 work-already-expanded))))
14162 (setq tags-in-group
14163 (delete-dups (cons (car tags-in-group)
14164 tags-expanded)))))
14165 ;; Filter tag-regexps from tags.
14166 (setq regexp-in-group-escaped
14167 (delq nil (mapcar (lambda (x)
14168 (if (stringp x)
14169 (and (equal "{" (substring x 0 1))
14170 (equal "}" (substring x -1))
14173 tags-in-group))
14174 regexp-in-group
14175 (mapcar (lambda (x)
14176 (substring x 1 -1))
14177 regexp-in-group-escaped)
14178 tags-in-group
14179 (delq nil (mapcar (lambda (x)
14180 (if (stringp x)
14181 (and (not (equal "{" (substring x 0 1)))
14182 (not (equal "}" (substring x -1)))
14185 tags-in-group)))
14186 ;; If single-as-list, do no more in the while-loop.
14187 (if (not single-as-list)
14188 (progn
14189 (when regexp-in-group
14190 (setq regexp-in-group
14191 (concat "\\|"
14192 (mapconcat 'identity regexp-in-group
14193 "\\|"))))
14194 (setq tags-in-group
14195 (concat dir
14196 "{\\<"
14197 (regexp-opt tags-in-group)
14198 "\\>"
14199 regexp-in-group
14200 "}"))
14201 (when (stringp tags-in-group)
14202 (org-add-props tags-in-group '(grouptag t)))
14203 (setq return-match
14204 (replace-match tags-in-group t t return-match)))
14205 (setq tags-in-group
14206 (append regexp-in-group-escaped tags-in-group))))
14207 (setq taggroups-keys (delete tag taggroups-keys))))
14208 ;; Add the regular expressions back into the match-expression again.
14209 (while regexps-in-match
14210 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14211 (pop regexps-in-match)
14212 return-match t t))
14213 (cl-decf count))
14214 (if single-as-list
14215 (if tags-in-group tags-in-group (list return-match))
14216 return-match))
14217 (if single-as-list
14218 (list (if downcased (downcase match) match))
14219 match)))
14221 (defun org-op-to-function (op &optional stringp)
14222 "Turn an operator into the appropriate function."
14223 (setq op
14224 (cond
14225 ((equal op "<" ) '(< org-string< org-time<))
14226 ((equal op ">" ) '(> org-string> org-time>))
14227 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14228 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14229 ((member op '("=" "==")) '(= string= org-time=))
14230 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14231 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14233 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14234 (defvar org-tags-overlay (make-overlay 1 1))
14235 (delete-overlay org-tags-overlay)
14237 (defun org-add-prop-inherited (s)
14238 (add-text-properties 0 (length s) '(inherited t) s)
14241 (defun org-toggle-tag (tag &optional onoff)
14242 "Toggle the tag TAG for the current line.
14243 If ONOFF is `on' or `off', don't toggle but set to this state."
14244 (save-excursion
14245 (org-back-to-heading t)
14246 (let ((current
14247 ;; Reverse the tags list so any new tag is appended to the
14248 ;; current list of tags.
14249 (nreverse (org-get-tags nil t)))
14250 res)
14251 (pcase onoff
14252 (`off (setq current (delete tag current)))
14253 ((or `on (guard (not (member tag current))))
14254 (setq res t)
14255 (cl-pushnew tag current :test #'equal))
14256 (_ (setq current (delete tag current))))
14257 (org-set-tags (nreverse current))
14258 res)))
14260 (defun org--align-tags-here (to-col)
14261 "Align tags on the current headline to TO-COL.
14262 Assume point is on a headline. Preserve point when aligning
14263 tags."
14264 (when (org-match-line org-tag-line-re)
14265 (let* ((tags-start (match-beginning 1))
14266 (blank-start (save-excursion
14267 (goto-char tags-start)
14268 (skip-chars-backward " \t")
14269 (point)))
14270 (new (max (if (>= to-col 0) to-col
14271 (- (abs to-col) (string-width (match-string 1))))
14272 ;; Introduce at least one space after the heading
14273 ;; or the stars.
14274 (save-excursion
14275 (goto-char blank-start)
14276 (1+ (current-column)))))
14277 (current
14278 (save-excursion (goto-char tags-start) (current-column)))
14279 (origin (point-marker))
14280 (column (current-column))
14281 (in-blank? (and (> origin blank-start) (<= origin tags-start))))
14282 (when (/= new current)
14283 (delete-region blank-start tags-start)
14284 (goto-char blank-start)
14285 (let ((indent-tabs-mode nil)) (indent-to new))
14286 ;; Try to move back to original position. If point was in the
14287 ;; blanks before the tags, ORIGIN marker is of no use because
14288 ;; it now points to BLANK-START. Use COLUMN instead.
14289 (if in-blank? (org-move-to-column column) (goto-char origin))))))
14291 (defun org-set-tags-command (&optional arg)
14292 "Set the tags for the current visible entry.
14294 When called with `\\[universal-argument]' prefix argument ARG, \
14295 realign all tags
14296 in the current buffer. If a region is active, set tags for
14297 all headlines in the region.
14299 This function is for interactive use only;
14300 in Lisp code use `org-set-tags' instead."
14301 (interactive "P")
14302 (cond
14303 (arg (org-align-tags t))
14304 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14305 ;; Disable `org-loop-over-headlines-in-active-region' for
14306 ;; successive calls.
14307 (let (org-loop-over-headlines-in-active-region)
14308 (org-map-entries
14309 #'org-set-tags-command
14311 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14312 'region-start-level
14313 'region)
14314 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14316 (save-excursion
14317 (org-back-to-heading)
14318 (let* ((all-tags (org-get-tags))
14319 (table (setq org-last-tags-completion-table
14320 (org--tag-add-to-alist
14321 (and org-complete-tags-always-offer-all-agenda-tags
14322 (org-global-tags-completion-table
14323 (org-agenda-files)))
14324 (or org-current-tag-alist (org-get-buffer-tags)))))
14325 (current-tags
14326 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14327 all-tags))
14328 (inherited-tags
14329 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14330 all-tags))
14331 (tags
14332 (replace-regexp-in-string
14333 ;; Ignore all forbidden characters in tags.
14334 "[^[:alnum:]_@#%]+" ":"
14335 (if (or (eq t org-use-fast-tag-selection)
14336 (and org-use-fast-tag-selection
14337 (delq nil (mapcar #'cdr table))))
14338 (org-fast-tag-selection
14339 current-tags
14340 inherited-tags
14341 table
14342 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14343 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14344 (org-trim (completing-read
14345 "Tags: "
14346 #'org-tags-completion-function
14347 nil nil (org-make-tag-string current-tags)
14348 'org-tags-history)))))))
14349 (org-set-tags tags))))))
14351 (defun org-align-tags (&optional all)
14352 "Align tags in current entry.
14353 When optional argument ALL is non-nil, align all tags in the
14354 visible part of the buffer."
14355 (let ((get-indent-column
14356 (lambda ()
14357 (let ((offset (if (bound-and-true-p org-indent-mode)
14358 (* (1- org-indent-indentation-per-level)
14359 (1- (org-current-level)))
14360 0)))
14361 (+ org-tags-column
14362 (if (> org-tags-column 0) (- offset) offset))))))
14363 (if (and (not all) (org-at-heading-p))
14364 (org--align-tags-here (funcall get-indent-column))
14365 (save-excursion
14366 (if all
14367 (while (re-search-forward org-tag-line-re nil t)
14368 (org--align-tags-here (funcall get-indent-column)))
14369 (org-back-to-heading t)
14370 (org--align-tags-here (funcall get-indent-column)))))))
14372 (defun org-set-tags (tags)
14373 "Set the tags of the current entry to TAGS, replacing current tags.
14375 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14376 If TAGS is nil or the empty string, all tags are removed.
14378 This function assumes point is on a headline."
14379 (org-with-wide-buffer
14380 (let ((tags (pcase tags
14381 ((pred listp) tags)
14382 ((pred stringp) (split-string (org-trim tags) ":" t))
14383 (_ (error "Invalid tag specification: %S" tags))))
14384 (old-tags (org-get-tags nil t))
14385 (tags-change? nil))
14386 (when (functionp org-tags-sort-function)
14387 (setq tags (sort tags org-tags-sort-function)))
14388 (setq tags-change? (not (equal tags old-tags)))
14389 (when tags-change?
14390 ;; Delete previous tags and any trailing white space.
14391 (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
14392 (line-end-position)))
14393 (skip-chars-backward " \t")
14394 (delete-region (point) (line-end-position))
14395 ;; Deleting white spaces may break an otherwise empty headline.
14396 ;; Re-introduce one space in this case.
14397 (unless (org-at-heading-p) (insert " "))
14398 (when tags
14399 (save-excursion (insert " " (org-make-tag-string tags)))
14400 ;; When text is being inserted on an invisible region
14401 ;; boundary, it can be inadvertently sucked into
14402 ;; invisibility.
14403 (unless (org-invisible-p (line-beginning-position))
14404 (org-flag-region (point) (line-end-position) nil 'outline))))
14405 ;; Align tags, if any.
14406 (when tags (org-align-tags))
14407 (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
14409 (defun org-change-tag-in-region (beg end tag off)
14410 "Add or remove TAG for each entry in the region.
14411 This works in the agenda, and also in an Org buffer."
14412 (interactive
14413 (list (region-beginning) (region-end)
14414 (let ((org-last-tags-completion-table
14415 (if (derived-mode-p 'org-mode)
14416 (org--tag-add-to-alist
14417 (org-get-buffer-tags)
14418 (org-global-tags-completion-table))
14419 (org-global-tags-completion-table))))
14420 (completing-read
14421 "Tag: " 'org-tags-completion-function nil nil nil
14422 'org-tags-history))
14423 (progn
14424 (message "[s]et or [r]emove? ")
14425 (equal (read-char-exclusive) ?r))))
14426 (when (fboundp 'deactivate-mark) (deactivate-mark))
14427 (let ((agendap (equal major-mode 'org-agenda-mode))
14428 l1 l2 m buf pos newhead (cnt 0))
14429 (goto-char end)
14430 (setq l2 (1- (org-current-line)))
14431 (goto-char beg)
14432 (setq l1 (org-current-line))
14433 (cl-loop for l from l1 to l2 do
14434 (org-goto-line l)
14435 (setq m (get-text-property (point) 'org-hd-marker))
14436 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14437 (and agendap m))
14438 (setq buf (if agendap (marker-buffer m) (current-buffer))
14439 pos (if agendap m (point)))
14440 (with-current-buffer buf
14441 (save-excursion
14442 (save-restriction
14443 (goto-char pos)
14444 (setq cnt (1+ cnt))
14445 (org-toggle-tag tag (if off 'off 'on))
14446 (setq newhead (org-get-heading)))))
14447 (and agendap (org-agenda-change-all-lines newhead m))))
14448 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14450 (defun org-tags-completion-function (string _predicate &optional flag)
14451 "Complete tag STRING.
14452 FLAG specifies the type of completion operation to perform. This
14453 function is passed as a collection function to `completing-read',
14454 which see."
14455 (let ((completion-ignore-case nil) ;tags are case-sensitive
14456 (confirm (lambda (x) (stringp (car x))))
14457 (prefix ""))
14458 (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14459 (setq prefix (match-string 1 string))
14460 (setq string (match-string 2 string)))
14461 (pcase flag
14462 (`t (all-completions string org-last-tags-completion-table confirm))
14463 (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
14464 (`nil
14465 (pcase (try-completion string org-last-tags-completion-table confirm)
14466 ((and completion (pred stringp))
14467 (concat prefix
14468 completion
14469 (if (and org-add-colon-after-tag-completion
14470 (assoc completion org-last-tags-completion-table))
14472 "")))
14473 (completion completion)))
14474 (_ nil))))
14476 (defun org-fast-tag-insert (kwd tags face &optional end)
14477 "Insert KWD, and the TAGS, the latter with face FACE.
14478 Also insert END."
14479 (insert (format "%-12s" (concat kwd ":"))
14480 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14481 (or end "")))
14483 (defun org-fast-tag-show-exit (flag)
14484 (save-excursion
14485 (org-goto-line 3)
14486 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14487 (replace-match ""))
14488 (when flag
14489 (end-of-line 1)
14490 (org-move-to-column (- (window-width) 19) t)
14491 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14493 (defun org-set-current-tags-overlay (current prefix)
14494 "Add an overlay to CURRENT tag with PREFIX."
14495 (let ((s (org-make-tag-string current)))
14496 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14497 (org-overlay-display org-tags-overlay (concat prefix s))))
14499 (defvar org-last-tag-selection-key nil)
14500 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14501 "Fast tag selection with single keys.
14502 CURRENT is the current list of tags in the headline, INHERITED is the
14503 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14504 possibly with grouping information. TODO-TABLE is a similar table with
14505 TODO keywords, should these have keys assigned to them.
14506 If the keys are nil, a-z are automatically assigned.
14507 Returns the new tags string, or nil to not change the current settings."
14508 (let* ((fulltable (append table todo-table))
14509 (maxlen (if (null fulltable) 0
14510 (apply #'max
14511 (mapcar (lambda (x)
14512 (if (stringp (car x)) (string-width (car x))
14514 fulltable))))
14515 (buf (current-buffer))
14516 (expert (eq org-fast-tag-selection-single-key 'expert))
14517 (buffer-tags nil)
14518 (fwidth (+ maxlen 3 1 3))
14519 (ncol (/ (- (window-width) 4) fwidth))
14520 (i-face 'org-done)
14521 (c-face 'org-todo)
14522 tg cnt e c char c1 c2 ntable tbl rtn
14523 ov-start ov-end ov-prefix
14524 (exit-after-next org-fast-tag-selection-single-key)
14525 (done-keywords org-done-keywords)
14526 groups ingroup intaggroup)
14527 (save-excursion
14528 (beginning-of-line)
14529 (if (looking-at org-tag-line-re)
14530 (setq ov-start (match-beginning 1)
14531 ov-end (match-end 1)
14532 ov-prefix "")
14533 (setq ov-start (1- (point-at-eol))
14534 ov-end (1+ ov-start))
14535 (skip-chars-forward "^\n\r")
14536 (setq ov-prefix
14537 (concat
14538 (buffer-substring (1- (point)) (point))
14539 (if (> (current-column) org-tags-column)
14541 (make-string (- org-tags-column (current-column)) ?\ ))))))
14542 (move-overlay org-tags-overlay ov-start ov-end)
14543 (save-window-excursion
14544 (if expert
14545 (set-buffer (get-buffer-create " *Org tags*"))
14546 (delete-other-windows)
14547 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14548 (org-switch-to-buffer-other-window " *Org tags*"))
14549 (erase-buffer)
14550 (setq-local org-done-keywords done-keywords)
14551 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14552 (org-fast-tag-insert "Current" current c-face "\n\n")
14553 (org-fast-tag-show-exit exit-after-next)
14554 (org-set-current-tags-overlay current ov-prefix)
14555 (setq tbl fulltable char ?a cnt 0)
14556 (while (setq e (pop tbl))
14557 (cond
14558 ((eq (car e) :startgroup)
14559 (push '() groups) (setq ingroup t)
14560 (unless (zerop cnt)
14561 (setq cnt 0)
14562 (insert "\n"))
14563 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14564 ((eq (car e) :endgroup)
14565 (setq ingroup nil cnt 0)
14566 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14567 ((eq (car e) :startgrouptag)
14568 (setq intaggroup t)
14569 (unless (zerop cnt)
14570 (setq cnt 0)
14571 (insert "\n"))
14572 (insert "[ "))
14573 ((eq (car e) :endgrouptag)
14574 (setq intaggroup nil cnt 0)
14575 (insert "]\n"))
14576 ((equal e '(:newline))
14577 (unless (zerop cnt)
14578 (setq cnt 0)
14579 (insert "\n")
14580 (setq e (car tbl))
14581 (while (equal (car tbl) '(:newline))
14582 (insert "\n")
14583 (setq tbl (cdr tbl)))))
14584 ((equal e '(:grouptags)) (insert " : "))
14586 (setq tg (copy-sequence (car e)) c2 nil)
14587 (if (cdr e)
14588 (setq c (cdr e))
14589 ;; automatically assign a character.
14590 (setq c1 (string-to-char
14591 (downcase (substring
14592 tg (if (= (string-to-char tg) ?@) 1 0)))))
14593 (if (or (rassoc c1 ntable) (rassoc c1 table))
14594 (while (or (rassoc char ntable) (rassoc char table))
14595 (setq char (1+ char)))
14596 (setq c2 c1))
14597 (setq c (or c2 char)))
14598 (when ingroup (push tg (car groups)))
14599 (setq tg (org-add-props tg nil 'face
14600 (cond
14601 ((not (assoc tg table))
14602 (org-get-todo-face tg))
14603 ((member tg current) c-face)
14604 ((member tg inherited) i-face))))
14605 (when (equal (caar tbl) :grouptags)
14606 (org-add-props tg nil 'face 'org-tag-group))
14607 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14608 (insert "[" c "] " tg (make-string
14609 (- fwidth 4 (length tg)) ?\ ))
14610 (push (cons tg c) ntable)
14611 (when (= (cl-incf cnt) ncol)
14612 (insert "\n")
14613 (when (or ingroup intaggroup) (insert " "))
14614 (setq cnt 0)))))
14615 (setq ntable (nreverse ntable))
14616 (insert "\n")
14617 (goto-char (point-min))
14618 (unless expert (org-fit-window-to-buffer))
14619 (setq rtn
14620 (catch 'exit
14621 (while t
14622 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14623 (if (not groups) "no " "")
14624 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14625 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14626 (setq org-last-tag-selection-key c)
14627 (cond
14628 ((= c ?\r) (throw 'exit t))
14629 ((= c ?!)
14630 (setq groups (not groups))
14631 (goto-char (point-min))
14632 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14633 ((= c ?\C-c)
14634 (if (not expert)
14635 (org-fast-tag-show-exit
14636 (setq exit-after-next (not exit-after-next)))
14637 (setq expert nil)
14638 (delete-other-windows)
14639 (set-window-buffer (split-window-vertically) " *Org tags*")
14640 (org-switch-to-buffer-other-window " *Org tags*")
14641 (org-fit-window-to-buffer)))
14642 ((or (= c ?\C-g)
14643 (and (= c ?q) (not (rassoc c ntable))))
14644 (delete-overlay org-tags-overlay)
14645 (setq quit-flag t))
14646 ((= c ?\ )
14647 (setq current nil)
14648 (when exit-after-next (setq exit-after-next 'now)))
14649 ((= c ?\t)
14650 (condition-case nil
14651 (setq tg (completing-read
14652 "Tag: "
14653 (or buffer-tags
14654 (with-current-buffer buf
14655 (setq buffer-tags
14656 (org-get-buffer-tags))))))
14657 (quit (setq tg "")))
14658 (when (string-match "\\S-" tg)
14659 (cl-pushnew (list tg) buffer-tags :test #'equal)
14660 (if (member tg current)
14661 (setq current (delete tg current))
14662 (push tg current)))
14663 (when exit-after-next (setq exit-after-next 'now)))
14664 ((setq e (rassoc c todo-table) tg (car e))
14665 (with-current-buffer buf
14666 (save-excursion (org-todo tg)))
14667 (when exit-after-next (setq exit-after-next 'now)))
14668 ((setq e (rassoc c ntable) tg (car e))
14669 (if (member tg current)
14670 (setq current (delete tg current))
14671 (cl-loop for g in groups do
14672 (when (member tg g)
14673 (dolist (x g) (setq current (delete x current)))))
14674 (push tg current))
14675 (when exit-after-next (setq exit-after-next 'now))))
14677 ;; Create a sorted list
14678 (setq current
14679 (sort current
14680 (lambda (a b)
14681 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14682 (when (eq exit-after-next 'now) (throw 'exit t))
14683 (goto-char (point-min))
14684 (beginning-of-line 2)
14685 (delete-region (point) (point-at-eol))
14686 (org-fast-tag-insert "Current" current c-face)
14687 (org-set-current-tags-overlay current ov-prefix)
14688 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14689 (while (re-search-forward tag-re nil t)
14690 (let ((tag (match-string 1)))
14691 (add-text-properties
14692 (match-beginning 1) (match-end 1)
14693 (list 'face
14694 (cond
14695 ((member tag current) c-face)
14696 ((member tag inherited) i-face)
14697 (t (get-text-property (match-beginning 1) '
14698 face))))))))
14699 (goto-char (point-min)))))
14700 (delete-overlay org-tags-overlay)
14701 (if rtn
14702 (mapconcat 'identity current ":")
14703 nil))))
14705 (defun org-make-tag-string (tags)
14706 "Return string associated to TAGS.
14707 TAGS is a list of strings."
14708 (if (null tags) ""
14709 (format ":%s:" (mapconcat #'identity tags ":"))))
14711 (defun org--get-local-tags ()
14712 "Return list of tags for the current headline.
14713 Assume point is at the beginning of the headline."
14714 (and (looking-at org-tag-line-re)
14715 (split-string (match-string-no-properties 2) ":" t)))
14717 (defun org-get-tags (&optional pos local)
14718 "Get the list of tags specified in the current headline.
14720 When argument POS is non-nil, retrieve tags for headline at POS.
14722 Accoring to `org-use-tags-inheritance', tags may be inherited
14723 from parent headlines, and from the whole document, through
14724 `org-file-tags'. However, when optional argument LOCAL is
14725 non-nil, only return tags really specified in the considered
14726 headline.
14728 Inherited tags have the `inherited' text property."
14729 (if (and org-trust-scanner-tags
14730 (or (not pos) (eq pos (point)))
14731 (not local))
14732 org-scanner-tags
14733 (org-with-point-at (or pos (point))
14734 (unless (org-before-first-heading-p)
14735 (org-back-to-heading t)
14736 (let ((ltags (org--get-local-tags)) itags)
14737 (if (or local (not org-use-tag-inheritance)) ltags
14738 (setq itags org-file-tags)
14739 (while (org-up-heading-safe)
14740 (setq itags (append (mapcar #'org-add-prop-inherited
14741 (org--get-local-tags))
14742 itags)))
14743 (delete-dups
14744 (append (org-remove-uninherited-tags itags) ltags))))))))
14746 (defun org-get-buffer-tags ()
14747 "Get a table of all tags used in the buffer, for completion."
14748 (org-with-point-at 1
14749 (let (tags)
14750 (while (re-search-forward org-tag-line-re nil t)
14751 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14752 tags)))
14753 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14755 ;;;; The mapping API
14757 (defvar org-agenda-skip-comment-trees)
14758 (defvar org-agenda-skip-function)
14759 (defun org-map-entries (func &optional match scope &rest skip)
14760 "Call FUNC at each headline selected by MATCH in SCOPE.
14762 FUNC is a function or a lisp form. The function will be called without
14763 arguments, with the cursor positioned at the beginning of the headline.
14764 The return values of all calls to the function will be collected and
14765 returned as a list.
14767 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14768 does not need to preserve point. After evaluation, the cursor will be
14769 moved to the end of the line (presumably of the headline of the
14770 processed entry) and search continues from there. Under some
14771 circumstances, this may not produce the wanted results. For example,
14772 if you have removed (e.g. archived) the current (sub)tree it could
14773 mean that the next entry will be skipped entirely. In such cases, you
14774 can specify the position from where search should continue by making
14775 FUNC set the variable `org-map-continue-from' to the desired buffer
14776 position.
14778 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14779 Only headlines that are matched by this query will be considered during
14780 the iteration. When MATCH is nil or t, all headlines will be
14781 visited by the iteration.
14783 SCOPE determines the scope of this command. It can be any of:
14785 nil The current buffer, respecting the restriction if any
14786 tree The subtree started with the entry at point
14787 region The entries within the active region, if any
14788 region-start-level
14789 The entries within the active region, but only those at
14790 the same level than the first one.
14791 file The current buffer, without restriction
14792 file-with-archives
14793 The current buffer, and any archives associated with it
14794 agenda All agenda files
14795 agenda-with-archives
14796 All agenda files with any archive files associated with them
14797 \(file1 file2 ...)
14798 If this is a list, all files in the list will be scanned
14800 The remaining args are treated as settings for the skipping facilities of
14801 the scanner. The following items can be given here:
14803 archive skip trees with the archive tag
14804 comment skip trees with the COMMENT keyword
14805 function or Emacs Lisp form:
14806 will be used as value for `org-agenda-skip-function', so
14807 whenever the function returns a position, FUNC will not be
14808 called for that entry and search will continue from the
14809 position returned
14811 If your function needs to retrieve the tags including inherited tags
14812 at the *current* entry, you can use the value of the variable
14813 `org-scanner-tags' which will be much faster than getting the value
14814 with `org-get-tags'. If your function gets properties with
14815 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14816 to t around the call to `org-entry-properties' to get the same speedup.
14817 Note that if your function moves around to retrieve tags and properties at
14818 a *different* entry, you cannot use these techniques."
14819 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14820 (not (org-region-active-p)))
14821 (let* ((org-agenda-archives-mode nil) ; just to make sure
14822 (org-agenda-skip-archived-trees (memq 'archive skip))
14823 (org-agenda-skip-comment-trees (memq 'comment skip))
14824 (org-agenda-skip-function
14825 (car (org-delete-all '(comment archive) skip)))
14826 (org-tags-match-list-sublevels t)
14827 (start-level (eq scope 'region-start-level))
14828 matcher res
14829 org-todo-keywords-for-agenda
14830 org-done-keywords-for-agenda
14831 org-todo-keyword-alist-for-agenda
14832 org-tag-alist-for-agenda
14833 org--matcher-tags-todo-only)
14835 (cond
14836 ((eq match t) (setq matcher t))
14837 ((eq match nil) (setq matcher t))
14838 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14840 (save-excursion
14841 (save-restriction
14842 (cond ((eq scope 'tree)
14843 (org-back-to-heading t)
14844 (org-narrow-to-subtree)
14845 (setq scope nil))
14846 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14847 (org-region-active-p))
14848 ;; If needed, set start-level to a string like "2"
14849 (when start-level
14850 (save-excursion
14851 (goto-char (region-beginning))
14852 (unless (org-at-heading-p) (outline-next-heading))
14853 (setq start-level (org-current-level))))
14854 (narrow-to-region (region-beginning)
14855 (save-excursion
14856 (goto-char (region-end))
14857 (unless (and (bolp) (org-at-heading-p))
14858 (outline-next-heading))
14859 (point)))
14860 (setq scope nil)))
14862 (if (not scope)
14863 (progn
14864 (org-agenda-prepare-buffers
14865 (and buffer-file-name (list buffer-file-name)))
14866 (setq res
14867 (org-scan-tags
14868 func matcher org--matcher-tags-todo-only start-level)))
14869 ;; Get the right scope
14870 (cond
14871 ((and scope (listp scope) (symbolp (car scope)))
14872 (setq scope (eval scope)))
14873 ((eq scope 'agenda)
14874 (setq scope (org-agenda-files t)))
14875 ((eq scope 'agenda-with-archives)
14876 (setq scope (org-agenda-files t))
14877 (setq scope (org-add-archive-files scope)))
14878 ((eq scope 'file)
14879 (setq scope (and buffer-file-name (list buffer-file-name))))
14880 ((eq scope 'file-with-archives)
14881 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14882 (org-agenda-prepare-buffers scope)
14883 (dolist (file scope)
14884 (with-current-buffer (org-find-base-buffer-visiting file)
14885 (org-with-wide-buffer
14886 (goto-char (point-min))
14887 (setq res
14888 (append
14890 (org-scan-tags
14891 func matcher org--matcher-tags-todo-only)))))))))
14892 res)))
14894 ;;; Properties API
14896 (defconst org-special-properties
14897 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14898 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14899 "The special properties valid in Org mode.
14900 These are properties that are not defined in the property drawer,
14901 but in some other way.")
14903 (defconst org-default-properties
14904 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14905 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14906 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14907 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14908 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14909 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14910 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14911 "Some properties that are used by Org mode for various purposes.
14912 Being in this list makes sure that they are offered for completion.")
14914 (defun org--valid-property-p (property)
14915 "Non nil when string PROPERTY is a valid property name."
14916 (not
14917 (or (equal property "")
14918 (string-match-p "\\s-" property))))
14920 (defun org--update-property-plist (key val props)
14921 "Associate KEY to VAL in alist PROPS.
14922 Modifications are made by side-effect. Return new alist."
14923 (let* ((appending (string= (substring key -1) "+"))
14924 (key (if appending (substring key 0 -1) key))
14925 (old (assoc-string key props t)))
14926 (if (not old) (cons (cons key val) props)
14927 (setcdr old (if appending (concat (cdr old) " " val) val))
14928 props)))
14930 (defun org-get-property-block (&optional beg force)
14931 "Return the (beg . end) range of the body of the property drawer.
14932 BEG is the beginning of the current subtree, or of the part
14933 before the first headline. If it is not given, it will be found.
14934 If the drawer does not exist, create it if FORCE is non-nil, or
14935 return nil."
14936 (org-with-wide-buffer
14937 (when beg (goto-char beg))
14938 (unless (org-before-first-heading-p)
14939 (let ((beg (cond (beg)
14940 ((or (not (featurep 'org-inlinetask))
14941 (org-inlinetask-in-task-p))
14942 (org-back-to-heading t))
14943 (t (org-with-limited-levels (org-back-to-heading t))))))
14944 (forward-line)
14945 (when (looking-at-p org-planning-line-re) (forward-line))
14946 (cond ((looking-at org-property-drawer-re)
14947 (forward-line)
14948 (cons (point) (progn (goto-char (match-end 0))
14949 (line-beginning-position))))
14950 (force
14951 (goto-char beg)
14952 (org-insert-property-drawer)
14953 (let ((pos (save-excursion (search-forward ":END:")
14954 (line-beginning-position))))
14955 (cons pos pos))))))))
14957 (defun org-at-property-p ()
14958 "Non-nil when point is inside a property drawer.
14959 See `org-property-re' for match data, if applicable."
14960 (save-excursion
14961 (beginning-of-line)
14962 (and (looking-at org-property-re)
14963 (let ((property-drawer (save-match-data (org-get-property-block))))
14964 (and property-drawer
14965 (>= (point) (car property-drawer))
14966 (< (point) (cdr property-drawer)))))))
14968 (defun org-property-action ()
14969 "Do an action on properties."
14970 (interactive)
14971 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14972 (let ((c (read-char-exclusive)))
14973 (cl-case c
14974 (?s (call-interactively #'org-set-property))
14975 (?d (call-interactively #'org-delete-property))
14976 (?D (call-interactively #'org-delete-property-globally))
14977 (?c (call-interactively #'org-compute-property-at-point))
14978 (otherwise (user-error "No such property action %c" c)))))
14980 (defun org-inc-effort ()
14981 "Increment the value of the effort property in the current entry."
14982 (interactive)
14983 (org-set-effort t))
14985 (defvar org-clock-effort) ; Defined in org-clock.el.
14986 (defvar org-clock-current-task) ; Defined in org-clock.el.
14987 (defun org-set-effort (&optional increment value)
14988 "Set the effort property of the current entry.
14989 If INCREMENT is non-nil, set the property to the next allowed
14990 value. Otherwise, if optional argument VALUE is provided, use
14991 it. Eventually, prompt for the new value if none of the previous
14992 variables is set."
14993 (interactive "P")
14994 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14995 (current (org-entry-get nil org-effort-property))
14996 (value
14997 (cond
14998 (increment
14999 (unless allowed (user-error "Allowed effort values are not set"))
15000 (or (cl-caadr (member (list current) allowed))
15001 (user-error "Unknown value %S among allowed values" current)))
15002 (value
15003 (if (stringp value) value
15004 (error "Invalid effort value: %S" value)))
15006 (let ((must-match
15007 (and allowed
15008 (not (get-text-property 0 'org-unrestricted
15009 (caar allowed))))))
15010 (completing-read "Effort: " allowed nil must-match))))))
15011 (unless (equal current value)
15012 (org-entry-put nil org-effort-property value))
15013 (org-refresh-property '((effort . identity)
15014 (effort-minutes . org-duration-to-minutes))
15015 value)
15016 (when (equal (org-get-heading t t t t)
15017 (bound-and-true-p org-clock-current-task))
15018 (setq org-clock-effort (org-get-at-bol 'effort))
15019 (org-clock-update-mode-line))
15020 (message "%s is now %s" org-effort-property value)))
15022 (defun org-entry-properties (&optional pom which)
15023 "Get all properties of the current entry.
15025 When POM is a buffer position, get all properties from the entry
15026 there instead.
15028 This includes the TODO keyword, the tags, time strings for
15029 deadline, scheduled, and clocking, and any additional properties
15030 defined in the entry.
15032 If WHICH is nil or `all', get all properties. If WHICH is
15033 `special' or `standard', only get that subclass. If WHICH is
15034 a string, only get that property.
15036 Return value is an alist. Keys are properties, as upcased
15037 strings."
15038 (org-with-point-at pom
15039 (when (and (derived-mode-p 'org-mode)
15040 (ignore-errors (org-back-to-heading t)))
15041 (catch 'exit
15042 (let* ((beg (point))
15043 (specific (and (stringp which) (upcase which)))
15044 (which (cond ((not specific) which)
15045 ((member specific org-special-properties) 'special)
15046 (t 'standard)))
15047 props)
15048 ;; Get the special properties, like TODO and TAGS.
15049 (when (memq which '(nil all special))
15050 (when (or (not specific) (string= specific "CLOCKSUM"))
15051 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15052 (when clocksum
15053 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15054 props)))
15055 (when specific (throw 'exit props)))
15056 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15057 (let ((clocksumt (get-text-property (point)
15058 :org-clock-minutes-today)))
15059 (when clocksumt
15060 (push (cons "CLOCKSUM_T"
15061 (org-duration-from-minutes clocksumt))
15062 props)))
15063 (when specific (throw 'exit props)))
15064 (when (or (not specific) (string= specific "ITEM"))
15065 (let ((case-fold-search nil))
15066 (when (looking-at org-complex-heading-regexp)
15067 (push (cons "ITEM"
15068 (let ((title (match-string-no-properties 4)))
15069 (if (org-string-nw-p title)
15070 (org-remove-tabs title)
15071 "")))
15072 props)))
15073 (when specific (throw 'exit props)))
15074 (when (or (not specific) (string= specific "TODO"))
15075 (let ((case-fold-search nil))
15076 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15077 (push (cons "TODO" (match-string-no-properties 2)) props)))
15078 (when specific (throw 'exit props)))
15079 (when (or (not specific) (string= specific "PRIORITY"))
15080 (push (cons "PRIORITY"
15081 (if (looking-at org-priority-regexp)
15082 (match-string-no-properties 2)
15083 (char-to-string org-default-priority)))
15084 props)
15085 (when specific (throw 'exit props)))
15086 (when (or (not specific) (string= specific "FILE"))
15087 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15088 props)
15089 (when specific (throw 'exit props)))
15090 (when (or (not specific) (string= specific "TAGS"))
15091 (let ((tags (org-get-tags nil t)))
15092 (when tags
15093 (push (cons "TAGS" (org-make-tag-string tags))
15094 props)))
15095 (when specific (throw 'exit props)))
15096 (when (or (not specific) (string= specific "ALLTAGS"))
15097 (let ((tags (org-get-tags)))
15098 (when tags
15099 (push (cons "ALLTAGS" (org-make-tag-string tags))
15100 props)))
15101 (when specific (throw 'exit props)))
15102 (when (or (not specific) (string= specific "BLOCKED"))
15103 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15104 (when specific (throw 'exit props)))
15105 (when (or (not specific)
15106 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15107 (forward-line)
15108 (when (looking-at-p org-planning-line-re)
15109 (end-of-line)
15110 (let ((bol (line-beginning-position))
15111 ;; Backward compatibility: time keywords used to
15112 ;; be configurable (before 8.3). Make sure we
15113 ;; get the correct keyword.
15114 (key-assoc `(("CLOSED" . ,org-closed-string)
15115 ("DEADLINE" . ,org-deadline-string)
15116 ("SCHEDULED" . ,org-scheduled-string))))
15117 (dolist (pair (if specific (list (assoc specific key-assoc))
15118 key-assoc))
15119 (save-excursion
15120 (when (search-backward (cdr pair) bol t)
15121 (goto-char (match-end 0))
15122 (skip-chars-forward " \t")
15123 (and (looking-at org-ts-regexp-both)
15124 (push (cons (car pair)
15125 (match-string-no-properties 0))
15126 props)))))))
15127 (when specific (throw 'exit props)))
15128 (when (or (not specific)
15129 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15130 (let ((find-ts
15131 (lambda (end ts)
15132 ;; Fix next time-stamp before END. TS is the
15133 ;; list of time-stamps found so far.
15134 (let ((ts ts)
15135 (regexp (cond
15136 ((string= specific "TIMESTAMP")
15137 org-ts-regexp)
15138 ((string= specific "TIMESTAMP_IA")
15139 org-ts-regexp-inactive)
15140 ((assoc "TIMESTAMP_IA" ts)
15141 org-ts-regexp)
15142 ((assoc "TIMESTAMP" ts)
15143 org-ts-regexp-inactive)
15144 (t org-ts-regexp-both))))
15145 (catch 'next
15146 (while (re-search-forward regexp end t)
15147 (backward-char)
15148 (let ((object (org-element-context)))
15149 ;; Accept to match timestamps in node
15150 ;; properties, too.
15151 (when (memq (org-element-type object)
15152 '(node-property timestamp))
15153 (let ((type
15154 (org-element-property :type object)))
15155 (cond
15156 ((and (memq type '(active active-range))
15157 (not (equal specific "TIMESTAMP_IA")))
15158 (unless (assoc "TIMESTAMP" ts)
15159 (push (cons "TIMESTAMP"
15160 (org-element-property
15161 :raw-value object))
15163 (when specific (throw 'exit ts))))
15164 ((and (memq type '(inactive inactive-range))
15165 (not (string= specific "TIMESTAMP")))
15166 (unless (assoc "TIMESTAMP_IA" ts)
15167 (push (cons "TIMESTAMP_IA"
15168 (org-element-property
15169 :raw-value object))
15171 (when specific (throw 'exit ts))))))
15172 ;; Both timestamp types are found,
15173 ;; move to next part.
15174 (when (= (length ts) 2) (throw 'next ts)))))
15175 ts)))))
15176 (goto-char beg)
15177 ;; First look for timestamps within headline.
15178 (let ((ts (funcall find-ts (line-end-position) nil)))
15179 (if (= (length ts) 2) (setq props (nconc ts props))
15180 ;; Then find timestamps in the section, skipping
15181 ;; planning line.
15182 (let ((end (save-excursion (outline-next-heading))))
15183 (forward-line)
15184 (when (looking-at-p org-planning-line-re) (forward-line))
15185 (setq props (nconc (funcall find-ts end ts) props))))))))
15186 ;; Get the standard properties, like :PROP:.
15187 (when (memq which '(nil all standard))
15188 ;; If we are looking after a specific property, delegate
15189 ;; to `org-entry-get', which is faster. However, make an
15190 ;; exception for "CATEGORY", since it can be also set
15191 ;; through keywords (i.e. #+CATEGORY).
15192 (if (and specific (not (equal specific "CATEGORY")))
15193 (let ((value (org-entry-get beg specific nil t)))
15194 (throw 'exit (and value (list (cons specific value)))))
15195 (let ((range (org-get-property-block beg)))
15196 (when range
15197 (let ((end (cdr range)) seen-base)
15198 (goto-char (car range))
15199 ;; Unlike to `org--update-property-plist', we
15200 ;; handle the case where base values is found
15201 ;; after its extension. We also forbid standard
15202 ;; properties to be named as special properties.
15203 (while (re-search-forward org-property-re end t)
15204 (let* ((key (upcase (match-string-no-properties 2)))
15205 (extendp (string-match-p "\\+\\'" key))
15206 (key-base (if extendp (substring key 0 -1) key))
15207 (value (match-string-no-properties 3)))
15208 (cond
15209 ((member-ignore-case key-base org-special-properties))
15210 (extendp
15211 (setq props
15212 (org--update-property-plist key value props)))
15213 ((member key seen-base))
15214 (t (push key seen-base)
15215 (let ((p (assoc-string key props t)))
15216 (if p (setcdr p (concat value " " (cdr p)))
15217 (push (cons key value) props))))))))))))
15218 (unless (assoc "CATEGORY" props)
15219 (push (cons "CATEGORY" (org-get-category beg)) props)
15220 (when (string= specific "CATEGORY") (throw 'exit props)))
15221 ;; Return value.
15222 props)))))
15224 (defun org--property-local-values (property literal-nil)
15225 "Return value for PROPERTY in current entry.
15226 Value is a list whose car is the base value for PROPERTY and cdr
15227 a list of accumulated values. Return nil if neither is found in
15228 the entry. Also return nil when PROPERTY is set to \"nil\",
15229 unless LITERAL-NIL is non-nil."
15230 (let ((range (org-get-property-block)))
15231 (when range
15232 (goto-char (car range))
15233 (let* ((case-fold-search t)
15234 (end (cdr range))
15235 (value
15236 ;; Base value.
15237 (save-excursion
15238 (let ((v (and (re-search-forward
15239 (org-re-property property nil t) end t)
15240 (match-string-no-properties 3))))
15241 (list (if literal-nil v (org-not-nil v)))))))
15242 ;; Find additional values.
15243 (let* ((property+ (org-re-property (concat property "+") nil t)))
15244 (while (re-search-forward property+ end t)
15245 (push (match-string-no-properties 3) value)))
15246 ;; Return final values.
15247 (and (not (equal value '(nil))) (nreverse value))))))
15249 (defun org--property-global-value (property literal-nil)
15250 "Return value for PROPERTY in current buffer.
15251 Return value is a string. Return nil if property is not set
15252 globally. Also return nil when PROPERTY is set to \"nil\",
15253 unless LITERAL-NIL is non-nil."
15254 (let ((global
15255 (cdr (or (assoc-string property org-file-properties t)
15256 (assoc-string property org-global-properties t)
15257 (assoc-string property org-global-properties-fixed t)))))
15258 (if literal-nil global (org-not-nil global))))
15260 (defun org-entry-get (pom property &optional inherit literal-nil)
15261 "Get value of PROPERTY for entry or content at point-or-marker POM.
15263 If INHERIT is non-nil and the entry does not have the property,
15264 then also check higher levels of the hierarchy. If INHERIT is
15265 the symbol `selective', use inheritance only if the setting in
15266 `org-use-property-inheritance' selects PROPERTY for inheritance.
15268 If the property is present but empty, the return value is the
15269 empty string. If the property is not present at all, nil is
15270 returned. In any other case, return the value as a string.
15271 Search is case-insensitive.
15273 If LITERAL-NIL is set, return the string value \"nil\" as
15274 a string, do not interpret it as the list atom nil. This is used
15275 for inheritance when a \"nil\" value can supersede a non-nil
15276 value higher up the hierarchy."
15277 (org-with-point-at pom
15278 (cond
15279 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15280 ;; We need a special property. Use `org-entry-properties' to
15281 ;; retrieve it, but specify the wanted property.
15282 (cdr (assoc-string property (org-entry-properties nil property))))
15283 ((and inherit
15284 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15285 (org-entry-get-with-inheritance property literal-nil))
15287 (let* ((local (org--property-local-values property literal-nil))
15288 (value (and local (mapconcat #'identity (delq nil local) " "))))
15289 (if literal-nil value (org-not-nil value)))))))
15291 (defun org-property-or-variable-value (var &optional inherit)
15292 "Check if there is a property fixing the value of VAR.
15293 If yes, return this value. If not, return the current value of the variable."
15294 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15295 (if (and prop (stringp prop) (string-match "\\S-" prop))
15296 (read prop)
15297 (symbol-value var))))
15299 (defun org-entry-delete (pom property)
15300 "Delete PROPERTY from entry at point-or-marker POM.
15301 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15302 non-nil when a property was removed."
15303 (org-with-point-at pom
15304 (pcase (org-get-property-block)
15305 (`(,begin . ,origin)
15306 (let* ((end (copy-marker origin))
15307 (re (org-re-property
15308 (concat (regexp-quote property) "\\+?") t t)))
15309 (goto-char begin)
15310 (while (re-search-forward re end t)
15311 (delete-region (match-beginning 0) (line-beginning-position 2)))
15312 ;; If drawer is empty, remove it altogether.
15313 (when (= begin end)
15314 (delete-region (line-beginning-position 0)
15315 (line-beginning-position 2)))
15316 ;; Return non-nil if some property was removed.
15317 (prog1 (/= end origin) (set-marker end nil))))
15318 (_ nil))))
15320 ;; Multi-values properties are properties that contain multiple values
15321 ;; These values are assumed to be single words, separated by whitespace.
15322 (defun org-entry-add-to-multivalued-property (pom property value)
15323 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15324 (let* ((old (org-entry-get pom property))
15325 (values (and old (split-string old))))
15326 (setq value (org-entry-protect-space value))
15327 (unless (member value values)
15328 (setq values (append values (list value)))
15329 (org-entry-put pom property (mapconcat #'identity values " ")))))
15331 (defun org-entry-remove-from-multivalued-property (pom property value)
15332 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15333 (let* ((old (org-entry-get pom property))
15334 (values (and old (split-string old))))
15335 (setq value (org-entry-protect-space value))
15336 (when (member value values)
15337 (setq values (delete value values))
15338 (org-entry-put pom property (mapconcat #'identity values " ")))))
15340 (defun org-entry-member-in-multivalued-property (pom property value)
15341 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15342 (let* ((old (org-entry-get pom property))
15343 (values (and old (split-string old))))
15344 (setq value (org-entry-protect-space value))
15345 (member value values)))
15347 (defun org-entry-get-multivalued-property (pom property)
15348 "Return a list of values in a multivalued property."
15349 (let* ((value (org-entry-get pom property))
15350 (values (and value (split-string value))))
15351 (mapcar #'org-entry-restore-space values)))
15353 (defun org-entry-put-multivalued-property (pom property &rest values)
15354 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15355 VALUES should be a list of strings. Spaces will be protected."
15356 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15357 (let* ((value (org-entry-get pom property))
15358 (values (and value (split-string value))))
15359 (mapcar #'org-entry-restore-space values)))
15361 (defun org-entry-protect-space (s)
15362 "Protect spaces and newline in string S."
15363 (while (string-match " " s)
15364 (setq s (replace-match "%20" t t s)))
15365 (while (string-match "\n" s)
15366 (setq s (replace-match "%0A" t t s)))
15369 (defun org-entry-restore-space (s)
15370 "Restore spaces and newline in string S."
15371 (while (string-match "%20" s)
15372 (setq s (replace-match " " t t s)))
15373 (while (string-match "%0A" s)
15374 (setq s (replace-match "\n" t t s)))
15377 (defvar org-entry-property-inherited-from (make-marker)
15378 "Marker pointing to the entry from where a property was inherited.
15379 Each call to `org-entry-get-with-inheritance' will set this marker to the
15380 location of the entry where the inheritance search matched. If there was
15381 no match, the marker will point nowhere.
15382 Note that also `org-entry-get' calls this function, if the INHERIT flag
15383 is set.")
15385 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15386 "Get PROPERTY of entry or content at point, search higher levels if needed.
15387 The search will stop at the first ancestor which has the property defined.
15388 If the value found is \"nil\", return nil to show that the property
15389 should be considered as undefined (this is the meaning of nil here).
15390 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15391 (move-marker org-entry-property-inherited-from nil)
15392 (org-with-wide-buffer
15393 (let (value)
15394 (catch 'exit
15395 (while t
15396 (let ((v (org--property-local-values property literal-nil)))
15397 (when v
15398 (setq value
15399 (concat (mapconcat #'identity (delq nil v) " ")
15400 (and value " ")
15401 value)))
15402 (cond
15403 ((car v)
15404 (org-back-to-heading t)
15405 (move-marker org-entry-property-inherited-from (point))
15406 (throw 'exit nil))
15407 ((org-up-heading-safe))
15409 (let ((global (org--property-global-value property literal-nil)))
15410 (cond ((not global))
15411 (value (setq value (concat global " " value)))
15412 (t (setq value global))))
15413 (throw 'exit nil))))))
15414 (if literal-nil value (org-not-nil value)))))
15416 (defvar org-property-changed-functions nil
15417 "Hook called when the value of a property has changed.
15418 Each hook function should accept two arguments, the name of the property
15419 and the new value.")
15421 (defun org-entry-put (pom property value)
15422 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15424 If the value is nil, it is converted to the empty string. If it
15425 is not a string, an error is raised. Also raise an error on
15426 invalid property names.
15428 PROPERTY can be any regular property (see
15429 `org-special-properties'). It can also be \"TODO\",
15430 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15432 For the last two properties, VALUE may have any of the special
15433 values \"earlier\" and \"later\". The function then increases or
15434 decreases scheduled or deadline date by one day."
15435 (cond ((null value) (setq value ""))
15436 ((not (stringp value)) (error "Properties values should be strings"))
15437 ((not (org--valid-property-p property))
15438 (user-error "Invalid property name: \"%s\"" property)))
15439 (org-with-point-at pom
15440 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15441 (org-back-to-heading t)
15442 (org-with-limited-levels (org-back-to-heading t)))
15443 (let ((beg (point)))
15444 (cond
15445 ((equal property "TODO")
15446 (cond ((not (org-string-nw-p value)) (setq value 'none))
15447 ((not (member value org-todo-keywords-1))
15448 (user-error "\"%s\" is not a valid TODO state" value)))
15449 (org-todo value)
15450 (org-align-tags))
15451 ((equal property "PRIORITY")
15452 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15453 (org-align-tags))
15454 ((equal property "SCHEDULED")
15455 (forward-line)
15456 (if (and (looking-at-p org-planning-line-re)
15457 (re-search-forward
15458 org-scheduled-time-regexp (line-end-position) t))
15459 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15460 ((string= value "later") (org-timestamp-change 1 'day))
15461 ((string= value "") (org-schedule '(4)))
15462 (t (org-schedule nil value)))
15463 (if (member value '("earlier" "later" ""))
15464 (call-interactively #'org-schedule)
15465 (org-schedule nil value))))
15466 ((equal property "DEADLINE")
15467 (forward-line)
15468 (if (and (looking-at-p org-planning-line-re)
15469 (re-search-forward
15470 org-deadline-time-regexp (line-end-position) t))
15471 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15472 ((string= value "later") (org-timestamp-change 1 'day))
15473 ((string= value "") (org-deadline '(4)))
15474 (t (org-deadline nil value)))
15475 (if (member value '("earlier" "later" ""))
15476 (call-interactively #'org-deadline)
15477 (org-deadline nil value))))
15478 ((member property org-special-properties)
15479 (error "The %s property cannot be set with `org-entry-put'" property))
15481 (let* ((range (org-get-property-block beg 'force))
15482 (end (cdr range))
15483 (case-fold-search t))
15484 (goto-char (car range))
15485 (if (re-search-forward (org-re-property property nil t) end t)
15486 (progn (delete-region (match-beginning 0) (match-end 0))
15487 (goto-char (match-beginning 0)))
15488 (goto-char end)
15489 (insert "\n")
15490 (backward-char))
15491 (insert ":" property ":")
15492 (when value (insert " " value))
15493 (org-indent-line)))))
15494 (run-hook-with-args 'org-property-changed-functions property value)))
15496 (defun org-buffer-property-keys (&optional specials defaults columns)
15497 "Get all property keys in the current buffer.
15499 When SPECIALS is non-nil, also list the special properties that
15500 reflect things like tags and TODO state.
15502 When DEFAULTS is non-nil, also include properties that has
15503 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15504 DESCRIPTION, LOCATION, and LOGGING and others.
15506 When COLUMNS in non-nil, also include property names given in
15507 COLUMN formats in the current buffer."
15508 (let ((case-fold-search t)
15509 (props (append
15510 (and specials org-special-properties)
15511 (and defaults (cons org-effort-property org-default-properties))
15512 nil)))
15513 (org-with-wide-buffer
15514 (goto-char (point-min))
15515 (while (re-search-forward org-property-start-re nil t)
15516 (catch :skip
15517 (let ((range (org-get-property-block)))
15518 (unless range (throw :skip nil))
15519 (goto-char (car range))
15520 (let ((begin (car range))
15521 (end (cdr range)))
15522 ;; Make sure that found property block is not located
15523 ;; before current point, as it would generate an infloop.
15524 ;; It can happen, for example, in the following
15525 ;; situation:
15527 ;; * Headline
15528 ;; :PROPERTIES:
15529 ;; ...
15530 ;; :END:
15531 ;; *************** Inlinetask
15532 ;; #+BEGIN_EXAMPLE
15533 ;; :PROPERTIES:
15534 ;; #+END_EXAMPLE
15536 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15537 (while (< (point) end)
15538 (let ((p (progn (looking-at org-property-re)
15539 (match-string-no-properties 2))))
15540 ;; Only add true property name, not extension symbol.
15541 (push (if (not (string-match-p "\\+\\'" p)) p
15542 (substring p 0 -1))
15543 props))
15544 (forward-line))))
15545 (outline-next-heading)))
15546 (when columns
15547 (goto-char (point-min))
15548 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15549 (let ((element (org-element-at-point)))
15550 (when (memq (org-element-type element) '(keyword node-property))
15551 (let ((value (org-element-property :value element))
15552 (start 0))
15553 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15554 \\(?:{[^}]+}\\)?"
15555 value start)
15556 (setq start (match-end 0))
15557 (let ((p (match-string-no-properties 1 value)))
15558 (unless (member-ignore-case p org-special-properties)
15559 (push p props))))))))))
15560 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15562 (defun org-property-values (key)
15563 "List all non-nil values of property KEY in current buffer."
15564 (org-with-wide-buffer
15565 (goto-char (point-min))
15566 (let ((case-fold-search t)
15567 (re (org-re-property key))
15568 values)
15569 (while (re-search-forward re nil t)
15570 (push (org-entry-get (point) key) values))
15571 (delete-dups values))))
15573 (defun org-insert-property-drawer ()
15574 "Insert a property drawer into the current entry."
15575 (org-with-wide-buffer
15576 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15577 (org-back-to-heading t)
15578 (org-with-limited-levels (org-back-to-heading t)))
15579 (forward-line)
15580 (when (looking-at-p org-planning-line-re) (forward-line))
15581 (unless (looking-at-p org-property-drawer-re)
15582 ;; Make sure we start editing a line from current entry, not from
15583 ;; next one. It prevents extending text properties or overlays
15584 ;; belonging to the latter.
15585 (when (bolp) (backward-char))
15586 (let ((begin (1+ (point)))
15587 (inhibit-read-only t))
15588 (insert "\n:PROPERTIES:\n:END:")
15589 (when (eobp) (insert "\n"))
15590 (org-indent-region begin (point))))))
15592 (defun org-insert-drawer (&optional arg drawer)
15593 "Insert a drawer at point.
15595 When optional argument ARG is non-nil, insert a property drawer.
15597 Optional argument DRAWER, when non-nil, is a string representing
15598 drawer's name. Otherwise, the user is prompted for a name.
15600 If a region is active, insert the drawer around that region
15601 instead.
15603 Point is left between drawer's boundaries."
15604 (interactive "P")
15605 (let* ((drawer (if arg "PROPERTIES"
15606 (or drawer (read-from-minibuffer "Drawer: ")))))
15607 (cond
15608 ;; With C-u, fall back on `org-insert-property-drawer'
15609 (arg (org-insert-property-drawer))
15610 ;; Check validity of suggested drawer's name.
15611 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15612 (user-error "Invalid drawer name"))
15613 ;; With an active region, insert a drawer at point.
15614 ((not (org-region-active-p))
15615 (progn
15616 (unless (bolp) (insert "\n"))
15617 (insert (format ":%s:\n\n:END:\n" drawer))
15618 (forward-line -2)))
15619 ;; Otherwise, insert the drawer at point
15621 (let ((rbeg (region-beginning))
15622 (rend (copy-marker (region-end))))
15623 (unwind-protect
15624 (progn
15625 (goto-char rbeg)
15626 (beginning-of-line)
15627 (when (save-excursion
15628 (re-search-forward org-outline-regexp-bol rend t))
15629 (user-error "Drawers cannot contain headlines"))
15630 ;; Position point at the beginning of the first
15631 ;; non-blank line in region. Insert drawer's opening
15632 ;; there, then indent it.
15633 (org-skip-whitespace)
15634 (beginning-of-line)
15635 (insert ":" drawer ":\n")
15636 (forward-line -1)
15637 (indent-for-tab-command)
15638 ;; Move point to the beginning of the first blank line
15639 ;; after the last non-blank line in region. Insert
15640 ;; drawer's closing, then indent it.
15641 (goto-char rend)
15642 (skip-chars-backward " \r\t\n")
15643 (insert "\n:END:")
15644 (deactivate-mark t)
15645 (indent-for-tab-command)
15646 (unless (eolp) (insert "\n")))
15647 ;; Clear marker, whatever the outcome of insertion is.
15648 (set-marker rend nil)))))))
15650 (defvar org-property-set-functions-alist nil
15651 "Property set function alist.
15652 Each entry should have the following format:
15654 (PROPERTY . READ-FUNCTION)
15656 The read function will be called with the same argument as
15657 `org-completing-read'.")
15659 (defun org-set-property-function (property)
15660 "Get the function that should be used to set PROPERTY.
15661 This is computed according to `org-property-set-functions-alist'."
15662 (or (cdr (assoc property org-property-set-functions-alist))
15663 'org-completing-read))
15665 (defun org-read-property-value (property &optional pom)
15666 "Read value for PROPERTY, as a string.
15667 When optional argument POM is non-nil, completion uses additional
15668 information, i.e., allowed or existing values at point or marker
15669 POM."
15670 (let* ((completion-ignore-case t)
15671 (allowed
15672 (or (org-property-get-allowed-values nil property 'table)
15673 (and pom (org-property-get-allowed-values pom property 'table))))
15674 (current (org-entry-get nil property))
15675 (prompt (format "%s value%s: "
15676 property
15677 (if (org-string-nw-p current)
15678 (format " [%s]" current)
15679 "")))
15680 (set-function (org-set-property-function property)))
15681 (org-trim
15682 (if allowed
15683 (funcall set-function
15684 prompt allowed nil
15685 (not (get-text-property 0 'org-unrestricted (caar allowed))))
15686 (let ((all (mapcar #'list
15687 (append (org-property-values property)
15688 (and pom
15689 (org-with-point-at pom
15690 (org-property-values property)))))))
15691 (funcall set-function prompt all nil nil "" nil current))))))
15693 (defvar org-last-set-property nil)
15694 (defvar org-last-set-property-value nil)
15695 (defun org-read-property-name ()
15696 "Read a property name."
15697 (let ((completion-ignore-case t)
15698 (default-prop (or (and (org-at-property-p)
15699 (match-string-no-properties 2))
15700 org-last-set-property)))
15701 (org-completing-read
15702 (concat "Property"
15703 (if default-prop (concat " [" default-prop "]") "")
15704 ": ")
15705 (mapcar #'list (org-buffer-property-keys nil t t))
15706 nil nil nil nil default-prop)))
15708 (defun org-set-property-and-value (use-last)
15709 "Allow to set [PROPERTY]: [value] direction from prompt.
15710 When use-default, don't even ask, just use the last
15711 \"[PROPERTY]: [value]\" string from the history."
15712 (interactive "P")
15713 (let* ((completion-ignore-case t)
15714 (pv (or (and use-last org-last-set-property-value)
15715 (org-completing-read
15716 "Enter a \"[Property]: [value]\" pair: "
15717 nil nil nil nil nil
15718 org-last-set-property-value)))
15719 prop val)
15720 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15721 (setq prop (match-string 1 pv)
15722 val (match-string 2 pv))
15723 (org-set-property prop val))))
15725 (defun org-set-property (property value)
15726 "In the current entry, set PROPERTY to VALUE.
15728 When called interactively, this will prompt for a property name, offering
15729 completion on existing and default properties. And then it will prompt
15730 for a value, offering completion either on allowed values (via an inherited
15731 xxx_ALL property) or on existing values in other instances of this property
15732 in the current file.
15734 Throw an error when trying to set a property with an invalid name."
15735 (interactive (list nil nil))
15736 (let ((property (or property (org-read-property-name))))
15737 ;; `org-entry-put' also makes the following check, but this one
15738 ;; avoids polluting `org-last-set-property' and
15739 ;; `org-last-set-property-value' needlessly.
15740 (unless (org--valid-property-p property)
15741 (user-error "Invalid property name: \"%s\"" property))
15742 (let ((value (or value (org-read-property-value property)))
15743 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15744 (setq org-last-set-property property)
15745 (setq org-last-set-property-value (concat property ": " value))
15746 ;; Possibly postprocess the inserted value:
15747 (when fn (setq value (funcall fn value)))
15748 (unless (equal (org-entry-get nil property) value)
15749 (org-entry-put nil property value)))))
15751 (defun org-find-property (property &optional value)
15752 "Find first entry in buffer that sets PROPERTY.
15754 When optional argument VALUE is non-nil, only consider an entry
15755 if it contains PROPERTY set to this value. If PROPERTY should be
15756 explicitly set to nil, use string \"nil\" for VALUE.
15758 Return position where the entry begins, or nil if there is no
15759 such entry. If narrowing is in effect, only search the visible
15760 part of the buffer."
15761 (save-excursion
15762 (goto-char (point-min))
15763 (let ((case-fold-search t)
15764 (re (org-re-property property nil (not value) value)))
15765 (catch 'exit
15766 (while (re-search-forward re nil t)
15767 (when (if value (org-at-property-p)
15768 (org-entry-get (point) property nil t))
15769 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15771 (defun org-delete-property (property)
15772 "In the current entry, delete PROPERTY."
15773 (interactive
15774 (let* ((completion-ignore-case t)
15775 (cat (org-entry-get (point) "CATEGORY"))
15776 (props0 (org-entry-properties nil 'standard))
15777 (props (if cat props0
15778 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15779 (prop (if (< 1 (length props))
15780 (completing-read "Property: " props nil t)
15781 (caar props))))
15782 (list prop)))
15783 (if (not property)
15784 (message "No property to delete in this entry")
15785 (org-entry-delete nil property)
15786 (message "Property \"%s\" deleted" property)))
15788 (defun org-delete-property-globally (property)
15789 "Remove PROPERTY globally, from all entries.
15790 This function ignores narrowing, if any."
15791 (interactive
15792 (let* ((completion-ignore-case t)
15793 (prop (completing-read
15794 "Globally remove property: "
15795 (mapcar #'list (org-buffer-property-keys)))))
15796 (list prop)))
15797 (org-with-wide-buffer
15798 (goto-char (point-min))
15799 (let ((count 0)
15800 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15801 (while (re-search-forward re nil t)
15802 (when (org-entry-delete (point) property) (cl-incf count)))
15803 (message "Property \"%s\" removed from %d entries" property count))))
15805 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15807 (defun org-compute-property-at-point ()
15808 "Compute the property at point.
15809 This looks for an enclosing column format, extracts the operator and
15810 then applies it to the property in the column format's scope."
15811 (interactive)
15812 (unless (org-at-property-p)
15813 (user-error "Not at a property"))
15814 (let ((prop (match-string-no-properties 2)))
15815 (org-columns-get-format-and-top-level)
15816 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15817 (user-error "No operator defined for property %s" prop))
15818 (org-columns-compute prop)))
15820 (defvar org-property-allowed-value-functions nil
15821 "Hook for functions supplying allowed values for a specific property.
15822 The functions must take a single argument, the name of the property, and
15823 return a flat list of allowed values. If \":ETC\" is one of
15824 the values, this means that these values are intended as defaults for
15825 completion, but that other values should be allowed too.
15826 The functions must return nil if they are not responsible for this
15827 property.")
15829 (defun org-property-get-allowed-values (pom property &optional table)
15830 "Get allowed values for the property PROPERTY.
15831 When TABLE is non-nil, return an alist that can directly be used for
15832 completion."
15833 (let (vals)
15834 (cond
15835 ((equal property "TODO")
15836 (setq vals (org-with-point-at pom
15837 (append org-todo-keywords-1 '("")))))
15838 ((equal property "PRIORITY")
15839 (let ((n org-lowest-priority))
15840 (while (>= n org-highest-priority)
15841 (push (char-to-string n) vals)
15842 (setq n (1- n)))))
15843 ((equal property "CATEGORY"))
15844 ((member property org-special-properties))
15845 ((setq vals (run-hook-with-args-until-success
15846 'org-property-allowed-value-functions property)))
15848 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15849 (when (and vals (string-match "\\S-" vals))
15850 (setq vals (car (read-from-string (concat "(" vals ")"))))
15851 (setq vals (mapcar (lambda (x)
15852 (cond ((stringp x) x)
15853 ((numberp x) (number-to-string x))
15854 ((symbolp x) (symbol-name x))
15855 (t "???")))
15856 vals)))))
15857 (when (member ":ETC" vals)
15858 (setq vals (remove ":ETC" vals))
15859 (org-add-props (car vals) '(org-unrestricted t)))
15860 (if table (mapcar 'list vals) vals)))
15862 (defun org-property-previous-allowed-value (&optional _previous)
15863 "Switch to the next allowed value for this property."
15864 (interactive)
15865 (org-property-next-allowed-value t))
15867 (defun org-property-next-allowed-value (&optional previous)
15868 "Switch to the next allowed value for this property."
15869 (interactive)
15870 (unless (org-at-property-p)
15871 (user-error "Not at a property"))
15872 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15873 (key (match-string 2))
15874 (value (match-string 3))
15875 (allowed (or (org-property-get-allowed-values (point) key)
15876 (and (member value '("[ ]" "[-]" "[X]"))
15877 '("[ ]" "[X]"))))
15878 (heading (save-match-data (nth 4 (org-heading-components))))
15879 nval)
15880 (unless allowed
15881 (user-error "Allowed values for this property have not been defined"))
15882 (when previous (setq allowed (reverse allowed)))
15883 (when (member value allowed)
15884 (setq nval (car (cdr (member value allowed)))))
15885 (setq nval (or nval (car allowed)))
15886 (when (equal nval value)
15887 (user-error "Only one allowed value for this property"))
15888 (org-at-property-p)
15889 (replace-match (concat " :" key ": " nval) t t)
15890 (org-indent-line)
15891 (beginning-of-line 1)
15892 (skip-chars-forward " \t")
15893 (when (equal prop org-effort-property)
15894 (org-refresh-property
15895 '((effort . identity)
15896 (effort-minutes . org-duration-to-minutes))
15897 nval)
15898 (when (string= org-clock-current-task heading)
15899 (setq org-clock-effort nval)
15900 (org-clock-update-mode-line)))
15901 (run-hook-with-args 'org-property-changed-functions key nval)))
15903 (defun org-find-olp (path &optional this-buffer)
15904 "Return a marker pointing to the entry at outline path OLP.
15905 If anything goes wrong, throw an error.
15906 You can wrap this call to catch the error like this:
15908 (condition-case msg
15909 (org-mobile-locate-entry (match-string 4))
15910 (error (nth 1 msg)))
15912 The return value will then be either a string with the error message,
15913 or a marker if everything is OK.
15915 If THIS-BUFFER is set, the outline path does not contain a file,
15916 only headings."
15917 (let* ((file (if this-buffer buffer-file-name (pop path)))
15918 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15919 (level 1)
15920 (lmin 1)
15921 (lmax 1)
15922 end found flevel)
15923 (unless buffer (error "File not found :%s" file))
15924 (with-current-buffer buffer
15925 (unless (derived-mode-p 'org-mode)
15926 (error "Buffer %s needs to be in Org mode" buffer))
15927 (org-with-wide-buffer
15928 (goto-char (point-min))
15929 (dolist (heading path)
15930 (let ((re (format org-complex-heading-regexp-format
15931 (regexp-quote heading)))
15932 (cnt 0))
15933 (while (re-search-forward re end t)
15934 (setq level (- (match-end 1) (match-beginning 1)))
15935 (when (and (>= level lmin) (<= level lmax))
15936 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15937 (when (= cnt 0)
15938 (error "Heading not found on level %d: %s" lmax heading))
15939 (when (> cnt 1)
15940 (error "Heading not unique on level %d: %s" lmax heading))
15941 (goto-char found)
15942 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15943 (setq end (save-excursion (org-end-of-subtree t t)))))
15944 (when (org-at-heading-p)
15945 (point-marker))))))
15947 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15948 "Find node HEADING in BUFFER.
15949 Return a marker to the heading if it was found, or nil if not.
15950 If POS-ONLY is set, return just the position instead of a marker.
15952 The heading text must match exact, but it may have a TODO keyword,
15953 a priority cookie and tags in the standard locations."
15954 (with-current-buffer (or buffer (current-buffer))
15955 (org-with-wide-buffer
15956 (goto-char (point-min))
15957 (let (case-fold-search)
15958 (when (re-search-forward
15959 (format org-complex-heading-regexp-format
15960 (regexp-quote heading)) nil t)
15961 (if pos-only
15962 (match-beginning 0)
15963 (move-marker (make-marker) (match-beginning 0))))))))
15965 (defun org-find-exact-heading-in-directory (heading &optional dir)
15966 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15967 When the target headline is found, return a marker to this location."
15968 (let ((files (directory-files (or dir default-directory)
15969 t "\\`[^.#].*\\.org\\'"))
15970 visiting m buffer)
15971 (catch 'found
15972 (dolist (file files)
15973 (message "trying %s" file)
15974 (setq visiting (org-find-base-buffer-visiting file))
15975 (setq buffer (or visiting (find-file-noselect file)))
15976 (setq m (org-find-exact-headline-in-buffer
15977 heading buffer))
15978 (when (and (not m) (not visiting)) (kill-buffer buffer))
15979 (and m (throw 'found m))))))
15981 (defun org-find-entry-with-id (ident)
15982 "Locate the entry that contains the ID property with exact value IDENT.
15983 IDENT can be a string, a symbol or a number, this function will search for
15984 the string representation of it.
15985 Return the position where this entry starts, or nil if there is no such entry."
15986 (interactive "sID: ")
15987 (let ((id (cond
15988 ((stringp ident) ident)
15989 ((symbolp ident) (symbol-name ident))
15990 ((numberp ident) (number-to-string ident))
15991 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15992 (org-with-wide-buffer (org-find-property "ID" id))))
15994 ;;;; Timestamps
15996 (defvar org-last-changed-timestamp nil)
15997 (defvar org-last-inserted-timestamp nil
15998 "The last time stamp inserted with `org-insert-time-stamp'.")
16000 (defun org-time-stamp (arg &optional inactive)
16001 "Prompt for a date/time and insert a time stamp.
16003 If the user specifies a time like HH:MM or if this command is
16004 called with at least one prefix argument, the time stamp contains
16005 the date and the time. Otherwise, only the date is included.
16007 All parts of a date not specified by the user are filled in from
16008 the timestamp at point, if any, or the current date/time
16009 otherwise.
16011 If there is already a timestamp at the cursor, it is replaced.
16013 With two universal prefix arguments, insert an active timestamp
16014 with the current time without prompting the user.
16016 When called from lisp, the timestamp is inactive if INACTIVE is
16017 non-nil."
16018 (interactive "P")
16019 (let* ((ts (cond
16020 ((org-at-date-range-p t)
16021 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16022 ((org-at-timestamp-p 'lax) (match-string 0))))
16023 ;; Default time is either the timestamp at point or today.
16024 ;; When entering a range, only the range start is considered.
16025 (default-time (if (not ts) (current-time)
16026 (apply #'encode-time (org-parse-time-string ts))))
16027 (default-input (and ts (org-get-compact-tod ts)))
16028 (repeater (and ts
16029 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16030 (match-string 0 ts)))
16031 org-time-was-given
16032 org-end-time-was-given
16033 (time
16034 (and (if (equal arg '(16)) (current-time)
16035 ;; Preserve `this-command' and `last-command'.
16036 (let ((this-command this-command)
16037 (last-command last-command))
16038 (org-read-date
16039 arg 'totime nil nil default-time default-input
16040 inactive))))))
16041 (cond
16042 ((and ts
16043 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16044 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16045 (insert "--")
16046 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16048 ;; Make sure we're on a timestamp. When in the middle of a date
16049 ;; range, move arbitrarily to range end.
16050 (unless (org-at-timestamp-p 'lax)
16051 (skip-chars-forward "-")
16052 (org-at-timestamp-p 'lax))
16053 (replace-match "")
16054 (setq org-last-changed-timestamp
16055 (org-insert-time-stamp
16056 time (or org-time-was-given arg)
16057 inactive nil nil (list org-end-time-was-given)))
16058 (when repeater
16059 (backward-char)
16060 (insert " " repeater)
16061 (setq org-last-changed-timestamp
16062 (concat (substring org-last-inserted-timestamp 0 -1)
16063 " " repeater ">")))
16064 (message "Timestamp updated"))
16065 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16066 (t (org-insert-time-stamp
16067 time (or org-time-was-given arg) inactive nil nil
16068 (list org-end-time-was-given))))))
16070 ;; FIXME: can we use this for something else, like computing time differences?
16071 (defun org-get-compact-tod (s)
16072 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16073 (let* ((t1 (match-string 1 s))
16074 (h1 (string-to-number (match-string 2 s)))
16075 (m1 (string-to-number (match-string 3 s)))
16076 (t2 (and (match-end 4) (match-string 5 s)))
16077 (h2 (and t2 (string-to-number (match-string 6 s))))
16078 (m2 (and t2 (string-to-number (match-string 7 s))))
16079 dh dm)
16080 (if (not t2)
16082 (setq dh (- h2 h1) dm (- m2 m1))
16083 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16084 (concat t1 "+" (number-to-string dh)
16085 (and (/= 0 dm) (format ":%02d" dm)))))))
16087 (defun org-time-stamp-inactive (&optional arg)
16088 "Insert an inactive time stamp.
16090 An inactive time stamp is enclosed in square brackets instead of angle
16091 brackets. It is inactive in the sense that it does not trigger agenda entries,
16092 does not link to the calendar and cannot be changed with the S-cursor keys.
16093 So these are more for recording a certain time/date.
16095 If the user specifies a time like HH:MM or if this command is called with
16096 at least one prefix argument, the time stamp contains the date and the time.
16097 Otherwise, only the date is included.
16099 When called with two universal prefix arguments, insert an active time stamp
16100 with the current time without prompting the user."
16101 (interactive "P")
16102 (org-time-stamp arg 'inactive))
16104 (defvar org-date-ovl (make-overlay 1 1))
16105 (overlay-put org-date-ovl 'face 'org-date-selected)
16106 (delete-overlay org-date-ovl)
16108 (defvar org-ans1) ; dynamically scoped parameter
16109 (defvar org-ans2) ; dynamically scoped parameter
16111 (defvar org-plain-time-of-day-regexp) ; defined below
16113 (defvar org-overriding-default-time nil) ; dynamically scoped
16114 (defvar org-read-date-overlay nil)
16115 (defvar org-dcst nil) ; dynamically scoped
16116 (defvar org-read-date-history nil)
16117 (defvar org-read-date-final-answer nil)
16118 (defvar org-read-date-analyze-futurep nil)
16119 (defvar org-read-date-analyze-forced-year nil)
16120 (defvar org-read-date-inactive)
16122 (defvar org-read-date-minibuffer-local-map
16123 (let* ((map (make-sparse-keymap)))
16124 (set-keymap-parent map minibuffer-local-map)
16125 (org-defkey map (kbd ".")
16126 (lambda () (interactive)
16127 ;; Are we at the beginning of the prompt?
16128 (if (looking-back "^[^:]+: "
16129 (let ((inhibit-field-text-motion t))
16130 (line-beginning-position)))
16131 (org-eval-in-calendar '(calendar-goto-today))
16132 (insert "."))))
16133 (org-defkey map (kbd "C-.")
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-goto-today))))
16136 (org-defkey map (kbd "M-S-<left>")
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-backward-month 1))))
16139 (org-defkey map (kbd "ESC S-<left>")
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-backward-month 1))))
16142 (org-defkey map (kbd "M-S-<right>")
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-forward-month 1))))
16145 (org-defkey map (kbd "ESC S-<right>")
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-forward-month 1))))
16148 (org-defkey map (kbd "M-S-<up>")
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(calendar-backward-year 1))))
16151 (org-defkey map (kbd "ESC S-<up>")
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-backward-year 1))))
16154 (org-defkey map (kbd "M-S-<down>")
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(calendar-forward-year 1))))
16157 (org-defkey map (kbd "ESC S-<down>")
16158 (lambda () (interactive)
16159 (org-eval-in-calendar '(calendar-forward-year 1))))
16160 (org-defkey map (kbd "S-<up>")
16161 (lambda () (interactive)
16162 (org-eval-in-calendar '(calendar-backward-week 1))))
16163 (org-defkey map (kbd "S-<down>")
16164 (lambda () (interactive)
16165 (org-eval-in-calendar '(calendar-forward-week 1))))
16166 (org-defkey map (kbd "S-<left>")
16167 (lambda () (interactive)
16168 (org-eval-in-calendar '(calendar-backward-day 1))))
16169 (org-defkey map (kbd "S-<right>")
16170 (lambda () (interactive)
16171 (org-eval-in-calendar '(calendar-forward-day 1))))
16172 (org-defkey map (kbd "!")
16173 (lambda () (interactive)
16174 (org-eval-in-calendar '(diary-view-entries))
16175 (message "")))
16176 (org-defkey map (kbd ">")
16177 (lambda () (interactive)
16178 (org-eval-in-calendar '(calendar-scroll-left 1))))
16179 (org-defkey map (kbd "<")
16180 (lambda () (interactive)
16181 (org-eval-in-calendar '(calendar-scroll-right 1))))
16182 (org-defkey map (kbd "C-v")
16183 (lambda () (interactive)
16184 (org-eval-in-calendar
16185 '(calendar-scroll-left-three-months 1))))
16186 (org-defkey map (kbd "M-v")
16187 (lambda () (interactive)
16188 (org-eval-in-calendar
16189 '(calendar-scroll-right-three-months 1))))
16190 map)
16191 "Keymap for minibuffer commands when using `org-read-date'.")
16193 (defvar org-def)
16194 (defvar org-defdecode)
16195 (defvar org-with-time)
16197 (defvar calendar-setup) ; Dynamically scoped.
16198 (defun org-read-date (&optional with-time to-time from-string prompt
16199 default-time default-input inactive)
16200 "Read a date, possibly a time, and make things smooth for the user.
16201 The prompt will suggest to enter an ISO date, but you can also enter anything
16202 which will at least partially be understood by `parse-time-string'.
16203 Unrecognized parts of the date will default to the current day, month, year,
16204 hour and minute. If this command is called to replace a timestamp at point,
16205 or to enter the second timestamp of a range, the default time is taken
16206 from the existing stamp. Furthermore, the command prefers the future,
16207 so if you are giving a date where the year is not given, and the day-month
16208 combination is already past in the current year, it will assume you
16209 mean next year. For details, see the manual. A few examples:
16211 3-2-5 --> 2003-02-05
16212 feb 15 --> currentyear-02-15
16213 2/15 --> currentyear-02-15
16214 sep 12 9 --> 2009-09-12
16215 12:45 --> today 12:45
16216 22 sept 0:34 --> currentyear-09-22 0:34
16217 12 --> currentyear-currentmonth-12
16218 Fri --> nearest Friday after today
16219 -Tue --> last Tuesday
16220 etc.
16222 Furthermore you can specify a relative date by giving, as the *first* thing
16223 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16224 change in days weeks, months, years.
16225 With a single plus or minus, the date is relative to today. With a double
16226 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16227 +4d --> four days from today
16228 +4 --> same as above
16229 +2w --> two weeks from today
16230 ++5 --> five days from default date
16232 The function understands only English month and weekday abbreviations.
16234 While prompting, a calendar is popped up - you can also select the
16235 date with the mouse (button 1). The calendar shows a period of three
16236 months. To scroll it to other months, use the keys `>' and `<'.
16237 If you don't like the calendar, turn it off with
16238 (setq org-read-date-popup-calendar nil)
16240 With optional argument TO-TIME, the date will immediately be converted
16241 to an internal time.
16242 With an optional argument WITH-TIME, the prompt will suggest to
16243 also insert a time. Note that when WITH-TIME is not set, you can
16244 still enter a time, and this function will inform the calling routine
16245 about this change. The calling routine may then choose to change the
16246 format used to insert the time stamp into the buffer to include the time.
16247 With optional argument FROM-STRING, read from this string instead from
16248 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16249 the time/date that is used for everything that is not specified by the
16250 user."
16251 (require 'parse-time)
16252 (let* ((org-with-time with-time)
16253 (org-time-stamp-rounding-minutes
16254 (if (equal org-with-time '(16))
16255 '(0 0)
16256 org-time-stamp-rounding-minutes))
16257 (org-dcst org-display-custom-times)
16258 (ct (org-current-time))
16259 (org-def (or org-overriding-default-time default-time ct))
16260 (org-defdecode (decode-time org-def))
16261 (cur-frame (selected-frame))
16262 (mouse-autoselect-window nil) ; Don't let the mouse jump
16263 (calendar-setup
16264 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16265 (calendar-move-hook nil)
16266 (calendar-view-diary-initially-flag nil)
16267 (calendar-view-holidays-initially-flag nil)
16268 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16269 ;; Rationalize `org-def' and `org-defdecode', if required.
16270 (when (< (nth 2 org-defdecode) org-extend-today-until)
16271 (setf (nth 2 org-defdecode) -1)
16272 (setf (nth 1 org-defdecode) 59)
16273 (setq org-def (apply #'encode-time org-defdecode))
16274 (setq org-defdecode (decode-time org-def)))
16275 (let* ((timestr (format-time-string
16276 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16277 org-def))
16278 (prompt (concat (if prompt (concat prompt " ") "")
16279 (format "Date+time [%s]: " timestr))))
16280 (cond
16281 (from-string (setq ans from-string))
16282 (org-read-date-popup-calendar
16283 (save-excursion
16284 (save-window-excursion
16285 (calendar)
16286 (when (eq calendar-setup 'calendar-only)
16287 (setq cal-frame
16288 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16289 (select-frame cal-frame))
16290 (org-eval-in-calendar '(setq cursor-type nil) t)
16291 (unwind-protect
16292 (progn
16293 (calendar-forward-day (- (time-to-days org-def)
16294 (calendar-absolute-from-gregorian
16295 (calendar-current-date))))
16296 (org-eval-in-calendar nil t)
16297 (let* ((old-map (current-local-map))
16298 (map (copy-keymap calendar-mode-map))
16299 (minibuffer-local-map
16300 (copy-keymap org-read-date-minibuffer-local-map)))
16301 (org-defkey map (kbd "RET") 'org-calendar-select)
16302 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16303 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16304 (unwind-protect
16305 (progn
16306 (use-local-map map)
16307 (setq org-read-date-inactive inactive)
16308 (add-hook 'post-command-hook 'org-read-date-display)
16309 (setq org-ans0
16310 (read-string prompt
16311 default-input
16312 'org-read-date-history
16313 nil))
16314 ;; org-ans0: from prompt
16315 ;; org-ans1: from mouse click
16316 ;; org-ans2: from calendar motion
16317 (setq ans
16318 (concat org-ans0 " " (or org-ans1 org-ans2))))
16319 (remove-hook 'post-command-hook 'org-read-date-display)
16320 (use-local-map old-map)
16321 (when org-read-date-overlay
16322 (delete-overlay org-read-date-overlay)
16323 (setq org-read-date-overlay nil)))))
16324 (bury-buffer "*Calendar*")
16325 (when cal-frame
16326 (delete-frame cal-frame)
16327 (select-frame-set-input-focus cur-frame))))))
16329 (t ; Naked prompt only
16330 (unwind-protect
16331 (setq ans (read-string prompt default-input
16332 'org-read-date-history timestr))
16333 (when org-read-date-overlay
16334 (delete-overlay org-read-date-overlay)
16335 (setq org-read-date-overlay nil))))))
16337 (setq final (org-read-date-analyze ans org-def org-defdecode))
16339 (when org-read-date-analyze-forced-year
16340 (message "Year was forced into %s"
16341 (if org-read-date-force-compatible-dates
16342 "compatible range (1970-2037)"
16343 "range representable on this machine"))
16344 (ding))
16346 ;; One round trip to get rid of 34th of August and stuff like that....
16347 (setq final (decode-time (apply 'encode-time final)))
16349 (setq org-read-date-final-answer ans)
16351 (if to-time
16352 (apply 'encode-time final)
16353 (if (and (boundp 'org-time-was-given) org-time-was-given)
16354 (format "%04d-%02d-%02d %02d:%02d"
16355 (nth 5 final) (nth 4 final) (nth 3 final)
16356 (nth 2 final) (nth 1 final))
16357 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16359 (defun org-read-date-display ()
16360 "Display the current date prompt interpretation in the minibuffer."
16361 (when org-read-date-display-live
16362 (when org-read-date-overlay
16363 (delete-overlay org-read-date-overlay))
16364 (when (minibufferp (current-buffer))
16365 (save-excursion
16366 (end-of-line 1)
16367 (while (not (equal (buffer-substring
16368 (max (point-min) (- (point) 4)) (point))
16369 " "))
16370 (insert " ")))
16371 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16372 " " (or org-ans1 org-ans2)))
16373 (org-end-time-was-given nil)
16374 (f (org-read-date-analyze ans org-def org-defdecode))
16375 (fmts (if org-dcst
16376 org-time-stamp-custom-formats
16377 org-time-stamp-formats))
16378 (fmt (if (or org-with-time
16379 (and (boundp 'org-time-was-given) org-time-was-given))
16380 (cdr fmts)
16381 (car fmts)))
16382 (txt (format-time-string fmt (apply 'encode-time f)))
16383 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16384 (txt (concat "=> " txt)))
16385 (when (and org-end-time-was-given
16386 (string-match org-plain-time-of-day-regexp txt))
16387 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16388 org-end-time-was-given
16389 (substring txt (match-end 0)))))
16390 (when org-read-date-analyze-futurep
16391 (setq txt (concat txt " (=>F)")))
16392 (setq org-read-date-overlay
16393 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16394 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16396 (defun org-read-date-analyze (ans def defdecode)
16397 "Analyze the combined answer of the date prompt."
16398 ;; FIXME: cleanup and comment
16399 ;; Pass `current-time' result to `decode-time' (instead of calling
16400 ;; without arguments) so that only `current-time' has to be
16401 ;; overridden in tests.
16402 (let ((org-def def)
16403 (org-defdecode defdecode)
16404 (nowdecode (decode-time (current-time)))
16405 delta deltan deltaw deltadef year month day
16406 hour minute second wday pm h2 m2 tl wday1
16407 iso-year iso-weekday iso-week iso-date futurep kill-year)
16408 (setq org-read-date-analyze-futurep nil
16409 org-read-date-analyze-forced-year nil)
16410 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16411 (setq ans "+0"))
16413 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16414 (setq ans (replace-match "" t t ans)
16415 deltan (car delta)
16416 deltaw (nth 1 delta)
16417 deltadef (nth 2 delta)))
16419 ;; Check if there is an iso week date in there. If yes, store the
16420 ;; info and postpone interpreting it until the rest of the parsing
16421 ;; is done.
16422 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16423 (setq iso-year (when (match-end 1)
16424 (org-small-year-to-year
16425 (string-to-number (match-string 1 ans))))
16426 iso-weekday (when (match-end 3)
16427 (string-to-number (match-string 3 ans)))
16428 iso-week (string-to-number (match-string 2 ans)))
16429 (setq ans (replace-match "" t t ans)))
16431 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16432 (when (string-match
16433 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16434 (setq year (if (match-end 2)
16435 (string-to-number (match-string 2 ans))
16436 (progn (setq kill-year t)
16437 (string-to-number (format-time-string "%Y"))))
16438 month (string-to-number (match-string 3 ans))
16439 day (string-to-number (match-string 4 ans)))
16440 (setq year (org-small-year-to-year year))
16441 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16442 t nil ans)))
16444 ;; Help matching dotted european dates
16445 (when (string-match
16446 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16447 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16448 (setq kill-year t)
16449 (string-to-number (format-time-string "%Y")))
16450 day (string-to-number (match-string 1 ans))
16451 month (string-to-number (match-string 2 ans))
16452 ans (replace-match (format "%04d-%02d-%02d" year month day)
16453 t nil ans)))
16455 ;; Help matching american dates, like 5/30 or 5/30/7
16456 (when (string-match
16457 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16458 (setq year (if (match-end 4)
16459 (string-to-number (match-string 4 ans))
16460 (progn (setq kill-year t)
16461 (string-to-number (format-time-string "%Y"))))
16462 month (string-to-number (match-string 1 ans))
16463 day (string-to-number (match-string 2 ans)))
16464 (setq year (org-small-year-to-year year))
16465 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16466 t nil ans)))
16467 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16468 ;; If there is a time with am/pm, and *no* time without it, we convert
16469 ;; so that matching will be successful.
16470 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16471 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16472 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16473 (setq hour (string-to-number (match-string 1 ans))
16474 minute (if (match-end 3)
16475 (string-to-number (match-string 3 ans))
16477 pm (equal ?p
16478 (string-to-char (downcase (match-string 4 ans)))))
16479 (if (and (= hour 12) (not pm))
16480 (setq hour 0)
16481 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16482 (setq ans (replace-match (format "%02d:%02d" hour minute)
16483 t t ans))))
16485 ;; Check if a time range is given as a duration
16486 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16487 (setq hour (string-to-number (match-string 1 ans))
16488 h2 (+ hour (string-to-number (match-string 3 ans)))
16489 minute (string-to-number (match-string 2 ans))
16490 m2 (+ minute (if (match-end 5) (string-to-number
16491 (match-string 5 ans))0)))
16492 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16493 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16494 t t ans)))
16496 ;; Check if there is a time range
16497 (when (boundp 'org-end-time-was-given)
16498 (setq org-time-was-given nil)
16499 (when (and (string-match org-plain-time-of-day-regexp ans)
16500 (match-end 8))
16501 (setq org-end-time-was-given (match-string 8 ans))
16502 (setq ans (concat (substring ans 0 (match-beginning 7))
16503 (substring ans (match-end 7))))))
16505 (setq tl (parse-time-string ans)
16506 day (or (nth 3 tl) (nth 3 org-defdecode))
16507 month
16508 (cond ((nth 4 tl))
16509 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16510 ;; Day was specified. Make sure DAY+MONTH
16511 ;; combination happens in the future.
16512 ((nth 3 tl)
16513 (setq futurep t)
16514 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16515 (nth 4 nowdecode)))
16516 (t (nth 4 org-defdecode)))
16517 year
16518 (cond ((and (not kill-year) (nth 5 tl)))
16519 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16520 ;; Month was guessed in the future and is at least
16521 ;; equal to NOWDECODE's. Fix year accordingly.
16522 (futurep
16523 (if (or (> month (nth 4 nowdecode))
16524 (>= day (nth 3 nowdecode)))
16525 (nth 5 nowdecode)
16526 (1+ (nth 5 nowdecode))))
16527 ;; Month was specified. Make sure MONTH+YEAR
16528 ;; combination happens in the future.
16529 ((nth 4 tl)
16530 (setq futurep t)
16531 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16532 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16533 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16534 (t (nth 5 nowdecode))))
16535 (t (nth 5 org-defdecode)))
16536 hour (or (nth 2 tl) (nth 2 org-defdecode))
16537 minute (or (nth 1 tl) (nth 1 org-defdecode))
16538 second (or (nth 0 tl) 0)
16539 wday (nth 6 tl))
16541 (when (and (eq org-read-date-prefer-future 'time)
16542 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16543 (equal day (nth 3 nowdecode))
16544 (equal month (nth 4 nowdecode))
16545 (equal year (nth 5 nowdecode))
16546 (nth 2 tl)
16547 (or (< (nth 2 tl) (nth 2 nowdecode))
16548 (and (= (nth 2 tl) (nth 2 nowdecode))
16549 (nth 1 tl)
16550 (< (nth 1 tl) (nth 1 nowdecode)))))
16551 (setq day (1+ day)
16552 futurep t))
16554 ;; Special date definitions below
16555 (cond
16556 (iso-week
16557 ;; There was an iso week
16558 (require 'cal-iso)
16559 (setq futurep nil)
16560 (setq year (or iso-year year)
16561 day (or iso-weekday wday 1)
16562 wday nil ; to make sure that the trigger below does not match
16563 iso-date (calendar-gregorian-from-absolute
16564 (calendar-iso-to-absolute
16565 (list iso-week day year))))
16566 ; FIXME: Should we also push ISO weeks into the future?
16567 ; (when (and org-read-date-prefer-future
16568 ; (not iso-year)
16569 ; (< (calendar-absolute-from-gregorian iso-date)
16570 ; (time-to-days (current-time))))
16571 ; (setq year (1+ year)
16572 ; iso-date (calendar-gregorian-from-absolute
16573 ; (calendar-iso-to-absolute
16574 ; (list iso-week day year)))))
16575 (setq month (car iso-date)
16576 year (nth 2 iso-date)
16577 day (nth 1 iso-date)))
16578 (deltan
16579 (setq futurep nil)
16580 (unless deltadef
16581 ;; Pass `current-time' result to `decode-time' (instead of
16582 ;; calling without arguments) so that only `current-time' has
16583 ;; to be overridden in tests.
16584 (let ((now (decode-time (current-time))))
16585 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16586 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16587 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16588 ((equal deltaw "m") (setq month (+ month deltan)))
16589 ((equal deltaw "y") (setq year (+ year deltan)))))
16590 ((and wday (not (nth 3 tl)))
16591 ;; Weekday was given, but no day, so pick that day in the week
16592 ;; on or after the derived date.
16593 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16594 (unless (equal wday wday1)
16595 (setq day (+ day (% (- wday wday1 -7) 7))))))
16596 (when (and (boundp 'org-time-was-given)
16597 (nth 2 tl))
16598 (setq org-time-was-given t))
16599 (when (< year 100) (setq year (+ 2000 year)))
16600 ;; Check of the date is representable
16601 (if org-read-date-force-compatible-dates
16602 (progn
16603 (when (< year 1970)
16604 (setq year 1970 org-read-date-analyze-forced-year t))
16605 (when (> year 2037)
16606 (setq year 2037 org-read-date-analyze-forced-year t)))
16607 (condition-case nil
16608 (ignore (encode-time second minute hour day month year))
16609 (error
16610 (setq year (nth 5 org-defdecode))
16611 (setq org-read-date-analyze-forced-year t))))
16612 (setq org-read-date-analyze-futurep futurep)
16613 (list second minute hour day month year)))
16615 (defvar parse-time-weekdays)
16616 (defun org-read-date-get-relative (s today default)
16617 "Check string S for special relative date string.
16618 TODAY and DEFAULT are internal times, for today and for a default.
16619 Return shift list (N what def-flag)
16620 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16621 N is the number of WHATs to shift.
16622 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16623 the DEFAULT date rather than TODAY."
16624 (require 'parse-time)
16625 (when (and
16626 (string-match
16627 (concat
16628 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16629 "\\([0-9]+\\)?"
16630 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16631 "\\([ \t]\\|$\\)") s)
16632 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16633 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16634 (string-to-char (substring (match-string 1 s) -1))
16635 ?+))
16636 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16637 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16638 (what (if (match-end 3) (match-string 3 s) "d"))
16639 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16640 (date (if rel default today))
16641 (wday (nth 6 (decode-time date)))
16642 delta)
16643 (if wday1
16644 (progn
16645 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16646 (when (= delta 0) (setq delta 7))
16647 (when (= dir ?-)
16648 (setq delta (- delta 7))
16649 (when (= delta 0) (setq delta -7)))
16650 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16651 (list delta "d" rel))
16652 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16654 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16655 "Turn a user-specified date into the internal representation.
16656 The internal representation needed by the calendar is (month day year).
16657 This is a wrapper to handle the brain-dead convention in calendar that
16658 user function argument order change dependent on argument order."
16659 (pcase calendar-date-style
16660 (`american (list arg1 arg2 arg3))
16661 (`european (list arg2 arg1 arg3))
16662 (`iso (list arg2 arg3 arg1))))
16664 (defun org-eval-in-calendar (form &optional keepdate)
16665 "Eval FORM in the calendar window and return to current window.
16666 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16667 (let ((sf (selected-frame))
16668 (sw (selected-window)))
16669 (select-window (get-buffer-window "*Calendar*" t))
16670 (eval form)
16671 (when (and (not keepdate) (calendar-cursor-to-date))
16672 (let* ((date (calendar-cursor-to-date))
16673 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16674 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16675 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16676 (select-window sw)
16677 (select-frame-set-input-focus sf)))
16679 (defun org-calendar-select ()
16680 "Return to `org-read-date' with the date currently selected.
16681 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16682 (interactive)
16683 (when (calendar-cursor-to-date)
16684 (let* ((date (calendar-cursor-to-date))
16685 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16686 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16687 (when (active-minibuffer-window) (exit-minibuffer))))
16689 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16690 "Insert a date stamp for the date given by the internal TIME.
16691 See `format-time-string' for the format of TIME.
16692 WITH-HM means use the stamp format that includes the time of the day.
16693 INACTIVE means use square brackets instead of angular ones, so that the
16694 stamp will not contribute to the agenda.
16695 PRE and POST are optional strings to be inserted before and after the
16696 stamp.
16697 The command returns the inserted time stamp."
16698 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16699 stamp)
16700 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16701 (insert-before-markers (or pre ""))
16702 (when (listp extra)
16703 (setq extra (car extra))
16704 (if (and (stringp extra)
16705 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16706 (setq extra (format "-%02d:%02d"
16707 (string-to-number (match-string 1 extra))
16708 (string-to-number (match-string 2 extra))))
16709 (setq extra nil)))
16710 (when extra
16711 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16712 (insert-before-markers (setq stamp (format-time-string fmt time)))
16713 (insert-before-markers (or post ""))
16714 (setq org-last-inserted-timestamp stamp)))
16716 (defun org-toggle-time-stamp-overlays ()
16717 "Toggle the use of custom time stamp formats."
16718 (interactive)
16719 (setq org-display-custom-times (not org-display-custom-times))
16720 (unless org-display-custom-times
16721 (let ((p (point-min)) (bmp (buffer-modified-p)))
16722 (while (setq p (next-single-property-change p 'display))
16723 (when (and (get-text-property p 'display)
16724 (eq (get-text-property p 'face) 'org-date))
16725 (remove-text-properties
16726 p (setq p (next-single-property-change p 'display))
16727 '(display t))))
16728 (set-buffer-modified-p bmp)))
16729 (org-restart-font-lock)
16730 (setq org-table-may-need-update t)
16731 (if org-display-custom-times
16732 (message "Time stamps are overlaid with custom format")
16733 (message "Time stamp overlays removed")))
16735 (defun org-display-custom-time (beg end)
16736 "Overlay modified time stamp format over timestamp between BEG and END."
16737 (let* ((ts (buffer-substring beg end))
16738 t1 with-hm tf time str (off 0))
16739 (save-match-data
16740 (setq t1 (org-parse-time-string ts t))
16741 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16742 (setq off (- (match-end 0) (match-beginning 0)))))
16743 (setq end (- end off))
16744 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16745 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16746 time (org-fix-decoded-time t1)
16747 str (org-add-props
16748 (format-time-string
16749 (substring tf 1 -1) (apply 'encode-time time))
16750 nil 'mouse-face 'highlight))
16751 (put-text-property beg end 'display str)))
16753 (defun org-fix-decoded-time (time)
16754 "Set 0 instead of nil for the first 6 elements of time.
16755 Don't touch the rest."
16756 (let ((n 0))
16757 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16759 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16760 "Difference between TIMESTAMP-STRING and now in days.
16761 If SECONDS is non-nil, return the difference in seconds."
16762 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16763 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16764 (funcall fdiff (current-time)))))
16766 (defun org-deadline-close-p (timestamp-string &optional ndays)
16767 "Is the time in TIMESTAMP-STRING close to the current date?"
16768 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16769 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16770 (not (org-entry-is-done-p))))
16772 (defun org-get-wdays (ts &optional delay zero-delay)
16773 "Get the deadline lead time appropriate for timestring TS.
16774 When DELAY is non-nil, get the delay time for scheduled items
16775 instead of the deadline lead time. When ZERO-DELAY is non-nil
16776 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16777 don't try to find the delay cookie in the scheduled timestamp."
16778 (let ((tv (if delay org-scheduled-delay-days
16779 org-deadline-warning-days)))
16780 (cond
16781 ((or (and delay (< tv 0))
16782 (and delay zero-delay (<= tv 0))
16783 (and (not delay) (<= tv 0)))
16784 ;; Enforce this value no matter what
16785 (- tv))
16786 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16787 ;; lead time is specified.
16788 (floor (* (string-to-number (match-string 1 ts))
16789 (cdr (assoc (match-string 2 ts)
16790 '(("d" . 1) ("w" . 7)
16791 ("m" . 30.4) ("y" . 365.25)
16792 ("h" . 0.041667)))))))
16793 ;; go for the default.
16794 (t tv))))
16796 (defun org-calendar-select-mouse (ev)
16797 "Return to `org-read-date' with the date currently selected.
16798 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16799 (interactive "e")
16800 (mouse-set-point ev)
16801 (when (calendar-cursor-to-date)
16802 (let* ((date (calendar-cursor-to-date))
16803 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16804 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16805 (when (active-minibuffer-window) (exit-minibuffer))))
16807 (defun org-check-deadlines (ndays)
16808 "Check if there are any deadlines due or past due.
16809 A deadline is considered due if it happens within `org-deadline-warning-days'
16810 days from today's date. If the deadline appears in an entry marked DONE,
16811 it is not shown. A numeric prefix argument NDAYS can be used to test that
16812 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16813 are shown."
16814 (interactive "P")
16815 (let* ((org-warn-days
16816 (cond
16817 ((equal ndays '(4)) 100000)
16818 (ndays (prefix-numeric-value ndays))
16819 (t (abs org-deadline-warning-days))))
16820 (case-fold-search nil)
16821 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16822 (callback
16823 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16824 (message "%d deadlines past-due or due within %d days"
16825 (org-occur regexp nil callback)
16826 org-warn-days)))
16828 (defsubst org-re-timestamp (type)
16829 "Return a regexp for timestamp TYPE.
16830 Allowed values for TYPE are:
16832 all: all timestamps
16833 active: only active timestamps (<...>)
16834 inactive: only inactive timestamps ([...])
16835 scheduled: only scheduled timestamps
16836 deadline: only deadline timestamps
16837 closed: only closed time-stamps
16839 When TYPE is nil, fall back on returning a regexp that matches
16840 both scheduled and deadline timestamps."
16841 (cl-case type
16842 (all org-ts-regexp-both)
16843 (active org-ts-regexp)
16844 (inactive org-ts-regexp-inactive)
16845 (scheduled org-scheduled-time-regexp)
16846 (deadline org-deadline-time-regexp)
16847 (closed org-closed-time-regexp)
16848 (otherwise
16849 (concat "\\<"
16850 (regexp-opt (list org-deadline-string org-scheduled-string))
16851 " *<\\([^>]+\\)>"))))
16853 (defun org-check-before-date (d)
16854 "Check if there are deadlines or scheduled entries before date D."
16855 (interactive (list (org-read-date)))
16856 (let* ((case-fold-search nil)
16857 (regexp (org-re-timestamp org-ts-type))
16858 (ts-type org-ts-type)
16859 (callback
16860 (lambda ()
16861 (let ((match (match-string 1)))
16862 (and (if (memq ts-type '(active inactive all))
16863 (eq (org-element-type (save-excursion
16864 (backward-char)
16865 (org-element-context)))
16866 'timestamp)
16867 (org-at-planning-p))
16868 (time-less-p
16869 (org-time-string-to-time match)
16870 (org-time-string-to-time d)))))))
16871 (message "%d entries before %s"
16872 (org-occur regexp nil callback)
16873 d)))
16875 (defun org-check-after-date (d)
16876 "Check if there are deadlines or scheduled entries after date D."
16877 (interactive (list (org-read-date)))
16878 (let* ((case-fold-search nil)
16879 (regexp (org-re-timestamp org-ts-type))
16880 (ts-type org-ts-type)
16881 (callback
16882 (lambda ()
16883 (let ((match (match-string 1)))
16884 (and (if (memq ts-type '(active inactive all))
16885 (eq (org-element-type (save-excursion
16886 (backward-char)
16887 (org-element-context)))
16888 'timestamp)
16889 (org-at-planning-p))
16890 (not (time-less-p
16891 (org-time-string-to-time match)
16892 (org-time-string-to-time d))))))))
16893 (message "%d entries after %s"
16894 (org-occur regexp nil callback)
16895 d)))
16897 (defun org-check-dates-range (start-date end-date)
16898 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16899 (interactive (list (org-read-date nil nil nil "Range starts")
16900 (org-read-date nil nil nil "Range end")))
16901 (let ((case-fold-search nil)
16902 (regexp (org-re-timestamp org-ts-type))
16903 (callback
16904 (let ((type org-ts-type))
16905 (lambda ()
16906 (let ((match (match-string 1)))
16907 (and
16908 (if (memq type '(active inactive all))
16909 (eq (org-element-type (save-excursion
16910 (backward-char)
16911 (org-element-context)))
16912 'timestamp)
16913 (org-at-planning-p))
16914 (not (time-less-p
16915 (org-time-string-to-time match)
16916 (org-time-string-to-time start-date)))
16917 (time-less-p
16918 (org-time-string-to-time match)
16919 (org-time-string-to-time end-date))))))))
16920 (message "%d entries between %s and %s"
16921 (org-occur regexp nil callback) start-date end-date)))
16923 (defun org-evaluate-time-range (&optional to-buffer)
16924 "Evaluate a time range by computing the difference between start and end.
16925 Normally the result is just printed in the echo area, but with prefix arg
16926 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16927 If the time range is actually in a table, the result is inserted into the
16928 next column.
16929 For time difference computation, a year is assumed to be exactly 365
16930 days in order to avoid rounding problems."
16931 (interactive "P")
16933 (org-clock-update-time-maybe)
16934 (save-excursion
16935 (unless (org-at-date-range-p t)
16936 (goto-char (point-at-bol))
16937 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16938 (unless (org-at-date-range-p t)
16939 (user-error "Not at a time-stamp range, and none found in current line")))
16940 (let* ((ts1 (match-string 1))
16941 (ts2 (match-string 2))
16942 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16943 (match-end (match-end 0))
16944 (time1 (org-time-string-to-time ts1))
16945 (time2 (org-time-string-to-time ts2))
16946 (t1 (float-time time1))
16947 (t2 (float-time time2))
16948 (diff (abs (- t2 t1)))
16949 (negative (< (- t2 t1) 0))
16950 ;; (ys (floor (* 365 24 60 60)))
16951 (ds (* 24 60 60))
16952 (hs (* 60 60))
16953 (fy "%dy %dd %02d:%02d")
16954 (fy1 "%dy %dd")
16955 (fd "%dd %02d:%02d")
16956 (fd1 "%dd")
16957 (fh "%02d:%02d")
16958 y d h m align)
16959 (if havetime
16960 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16962 d (floor (/ diff ds)) diff (mod diff ds)
16963 h (floor (/ diff hs)) diff (mod diff hs)
16964 m (floor (/ diff 60)))
16965 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16967 d (floor (+ (/ diff ds) 0.5))
16968 h 0 m 0))
16969 (if (not to-buffer)
16970 (message "%s" (org-make-tdiff-string y d h m))
16971 (if (org-at-table-p)
16972 (progn
16973 (goto-char match-end)
16974 (setq align t)
16975 (and (looking-at " *|") (goto-char (match-end 0))))
16976 (goto-char match-end))
16977 (when (looking-at
16978 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16979 (replace-match ""))
16980 (when negative (insert " -"))
16981 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16982 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16983 (insert " " (format fh h m))))
16984 (when align (org-table-align))
16985 (message "Time difference inserted")))))
16987 (defun org-make-tdiff-string (y d h m)
16988 (let ((fmt "")
16989 (l nil))
16990 (when (> y 0)
16991 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16992 (push y l))
16993 (when (> d 0)
16994 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16995 (push d l))
16996 (when (> h 0)
16997 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16998 (push h l))
16999 (when (> m 0)
17000 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17001 (push m l))
17002 (apply 'format fmt (nreverse l))))
17004 (defun org-time-string-to-time (s)
17005 "Convert timestamp string S into internal time."
17006 (apply #'encode-time (org-parse-time-string s)))
17008 (defun org-time-string-to-seconds (s)
17009 "Convert a timestamp string S into a number of seconds."
17010 (float-time (org-time-string-to-time s)))
17012 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17014 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17015 "Convert time stamp S to an absolute day number.
17017 If DAYNR in non-nil, and there is a specifier for a cyclic time
17018 stamp, get the closest date to DAYNR. If PREFER is
17019 `past' (respectively `future') return a date past (respectively
17020 after) or equal to DAYNR.
17022 POS is the location of time stamp S, as a buffer position in
17023 BUFFER.
17025 Diary sexp timestamps are matched against DAYNR, when non-nil.
17026 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17027 signaled."
17028 (cond
17029 ((string-match "\\`%%\\((.*)\\)" s)
17030 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17031 ;; only able to match individual dates. If it fails, raise an
17032 ;; error.
17033 (if (and daynr
17034 (org-diary-sexp-entry
17035 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17036 daynr
17037 (signal 'org-diary-sexp-no-match (list s))))
17038 (daynr (org-closest-date s daynr prefer))
17039 (t (time-to-days
17040 (condition-case errdata
17041 (apply #'encode-time (org-parse-time-string s))
17042 (error (error "Bad timestamp `%s'%s\nError was: %s"
17044 (if (not (and buffer pos)) ""
17045 (format-message " at %d in buffer `%s'" pos buffer))
17046 (cdr errdata))))))))
17048 (defun org-days-to-iso-week (days)
17049 "Return the iso week number."
17050 (require 'cal-iso)
17051 (car (calendar-iso-from-absolute days)))
17053 (defun org-small-year-to-year (year)
17054 "Convert 2-digit years into 4-digit years.
17055 YEAR is expanded into one of the 30 next years, if possible, or
17056 into a past one. Any year larger than 99 is returned unchanged."
17057 (if (>= year 100) year
17058 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17059 (century (/ current 100))
17060 (offset (- year (% current 100))))
17061 (cond ((> offset 30) (+ (* (1- century) 100) year))
17062 ((> offset -70) (+ (* century 100) year))
17063 (t (+ (* (1+ century) 100) year))))))
17065 (defun org-time-from-absolute (d)
17066 "Return the time corresponding to date D.
17067 D may be an absolute day number, or a calendar-type list (month day year)."
17068 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17069 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17071 (defvar org-agenda-current-date)
17072 (defun org-calendar-holiday ()
17073 "List of holidays, for Diary display in Org mode."
17074 (require 'holidays)
17075 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17076 (and hl (mapconcat #'identity hl "; "))))
17078 (defun org-diary-sexp-entry (sexp entry d)
17079 "Process a SEXP diary ENTRY for date D."
17080 (require 'diary-lib)
17081 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17082 ;; dynamically.
17083 (let* ((sexp `(let ((entry ,entry)
17084 (date ',d))
17085 ,(car (read-from-string sexp))))
17086 (result (if calendar-debug-sexp (eval sexp)
17087 (condition-case nil
17088 (eval sexp)
17089 (error
17090 (beep)
17091 (message "Bad sexp at line %d in %s: %s"
17092 (org-current-line)
17093 (buffer-file-name) sexp)
17094 (sleep-for 2))))))
17095 (cond ((stringp result) (split-string result "; "))
17096 ((and (consp result)
17097 (not (consp (cdr result)))
17098 (stringp (cdr result))) (cdr result))
17099 ((and (consp result)
17100 (stringp (car result))) result)
17101 (result entry))))
17103 (defun org-diary-to-ical-string (frombuf)
17104 "Get iCalendar entries from diary entries in buffer FROMBUF.
17105 This uses the icalendar.el library."
17106 (let* ((tmpdir temporary-file-directory)
17107 (tmpfile (make-temp-name
17108 (expand-file-name "orgics" tmpdir)))
17109 buf rtn b e)
17110 (with-current-buffer frombuf
17111 (icalendar-export-region (point-min) (point-max) tmpfile)
17112 (setq buf (find-buffer-visiting tmpfile))
17113 (set-buffer buf)
17114 (goto-char (point-min))
17115 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17116 (setq b (match-beginning 0)))
17117 (goto-char (point-max))
17118 (when (re-search-backward "^END:VEVENT" nil t)
17119 (setq e (match-end 0)))
17120 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17121 (kill-buffer buf)
17122 (delete-file tmpfile)
17123 rtn))
17125 (defun org-closest-date (start current prefer)
17126 "Return closest date to CURRENT starting from START.
17128 CURRENT and START are both time stamps.
17130 When PREFER is `past', return a date that is either CURRENT or
17131 past. When PREFER is `future', return a date that is either
17132 CURRENT or future.
17134 Only time stamps with a repeater are modified. Any other time
17135 stamp stay unchanged. In any case, return value is an absolute
17136 day number."
17137 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17138 ;; No repeater. Do not shift time stamp.
17139 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17140 (let ((value (string-to-number (match-string 1 start)))
17141 (type (match-string 2 start)))
17142 (if (= 0 value)
17143 ;; Repeater with a 0-value is considered as void.
17144 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17145 (let* ((base (org-date-to-gregorian start))
17146 (target (org-date-to-gregorian current))
17147 (sday (calendar-absolute-from-gregorian base))
17148 (cday (calendar-absolute-from-gregorian target))
17149 n1 n2)
17150 ;; If START is already past CURRENT, just return START.
17151 (if (<= cday sday) sday
17152 ;; Compute closest date before (N1) and closest date past
17153 ;; (N2) CURRENT.
17154 (pcase type
17155 ("h"
17156 (let ((missing-hours
17157 (mod (+ (- (* 24 (- cday sday))
17158 (nth 2 (org-parse-time-string start)))
17159 org-extend-today-until)
17160 value)))
17161 (setf n1 (if (= missing-hours 0) cday
17162 (- cday (1+ (/ missing-hours 24)))))
17163 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17164 ((or "d" "w")
17165 (let ((value (if (equal type "w") (* 7 value) value)))
17166 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17167 (setf n2 (+ n1 value))))
17168 ("m"
17169 (let* ((add-months
17170 (lambda (d n)
17171 ;; Add N months to gregorian date D, i.e.,
17172 ;; a list (MONTH DAY YEAR). Return a valid
17173 ;; gregorian date.
17174 (let ((m (+ (nth 0 d) n)))
17175 (list (mod m 12)
17176 (nth 1 d)
17177 (+ (/ m 12) (nth 2 d))))))
17178 (months ; Complete months to TARGET.
17179 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17180 (- (nth 0 target) (nth 0 base))
17181 ;; If START's day is greater than
17182 ;; TARGET's, remove incomplete month.
17183 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17184 value)
17185 value))
17186 (before (funcall add-months base months)))
17187 (setf n1 (calendar-absolute-from-gregorian before))
17188 (setf n2
17189 (calendar-absolute-from-gregorian
17190 (funcall add-months before value)))))
17192 (let* ((d (nth 1 base))
17193 (m (nth 0 base))
17194 (y (nth 2 base))
17195 (years ; Complete years to TARGET.
17196 (* (/ (- (nth 2 target)
17198 ;; If START's month and day are
17199 ;; greater than TARGET's, remove
17200 ;; incomplete year.
17201 (if (or (> (nth 0 target) m)
17202 (and (= (nth 0 target) m)
17203 (> (nth 1 target) d)))
17206 value)
17207 value))
17208 (before (list m d (+ y years))))
17209 (setf n1 (calendar-absolute-from-gregorian before))
17210 (setf n2 (calendar-absolute-from-gregorian
17211 (list m d (+ (nth 2 before) value)))))))
17212 ;; Handle PREFER parameter, if any.
17213 (cond
17214 ((eq prefer 'past) (if (= cday n2) n2 n1))
17215 ((eq prefer 'future) (if (= cday n1) n1 n2))
17216 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17218 (defun org-date-to-gregorian (d)
17219 "Turn any specification of date D into a Gregorian date for the calendar."
17220 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17221 ((and (listp d) (= (length d) 3)) d)
17222 ((stringp d)
17223 (let ((d (org-parse-time-string d)))
17224 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17225 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17227 (defun org-timestamp-up (&optional arg)
17228 "Increase the date item at the cursor by one.
17229 If the cursor is on the year, change the year. If it is on the month,
17230 the day or the time, change that. If the cursor is on the enclosing
17231 bracket, change the timestamp type.
17232 With prefix ARG, change by that many units."
17233 (interactive "p")
17234 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17236 (defun org-timestamp-down (&optional arg)
17237 "Decrease the date item at the cursor by one.
17238 If the cursor is on the year, change the year. If it is on the month,
17239 the day or the time, change that. If the cursor is on the enclosing
17240 bracket, change the timestamp type.
17241 With prefix ARG, change by that many units."
17242 (interactive "p")
17243 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17245 (defun org-timestamp-up-day (&optional arg)
17246 "Increase the date in the time stamp by one day.
17247 With prefix ARG, change that many days."
17248 (interactive "p")
17249 (if (and (not (org-at-timestamp-p 'lax))
17250 (org-at-heading-p))
17251 (org-todo 'up)
17252 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17254 (defun org-timestamp-down-day (&optional arg)
17255 "Decrease the date in the time stamp by one day.
17256 With prefix ARG, change that many days."
17257 (interactive "p")
17258 (if (and (not (org-at-timestamp-p 'lax))
17259 (org-at-heading-p))
17260 (org-todo 'down)
17261 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17263 (defun org-at-timestamp-p (&optional extended)
17264 "Non-nil if point is inside a timestamp.
17266 By default, the function only consider syntactically valid active
17267 timestamps. However, the caller may have a broader definition
17268 for timestamps. As a consequence, optional argument EXTENDED can
17269 be set to the following values
17271 `inactive'
17273 Include also syntactically valid inactive timestamps.
17275 `agenda'
17277 Include timestamps allowed in Agenda, i.e., those in
17278 properties drawers, planning lines and clock lines.
17280 `lax'
17282 Ignore context. The function matches any part of the
17283 document looking like a timestamp. This includes comments,
17284 example blocks...
17286 For backward-compatibility with Org 9.0, every other non-nil
17287 value is equivalent to `inactive'.
17289 When at a timestamp, return the position of the point as a symbol
17290 among `bracket', `after', `year', `month', `hour', `minute',
17291 `day' or a number of character from the last know part of the
17292 time stamp.
17294 When matching, the match groups are the following:
17295 group 1: year
17296 group 2: month
17297 group 3: day number
17298 group 4: day name
17299 group 5: hours, if any
17300 group 6: minutes, if any"
17301 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17302 (pos (point))
17303 (match?
17304 (let ((boundaries (org-in-regexp regexp)))
17305 (save-match-data
17306 (cond ((null boundaries) nil)
17307 ((eq extended 'lax) t)
17309 (or (and (eq extended 'agenda)
17310 (or (org-at-planning-p)
17311 (org-at-property-p)
17312 (and (bound-and-true-p
17313 org-agenda-include-inactive-timestamps)
17314 (org-at-clock-log-p))))
17315 (eq 'timestamp
17316 (save-excursion
17317 (when (= pos (cdr boundaries)) (forward-char -1))
17318 (org-element-type (org-element-context)))))))))))
17319 (cond
17320 ((not match?) nil)
17321 ((= pos (match-beginning 0)) 'bracket)
17322 ;; Distinguish location right before the closing bracket from
17323 ;; right after it.
17324 ((= pos (1- (match-end 0))) 'bracket)
17325 ((= pos (match-end 0)) 'after)
17326 ((org-pos-in-match-range pos 2) 'year)
17327 ((org-pos-in-match-range pos 3) 'month)
17328 ((org-pos-in-match-range pos 7) 'hour)
17329 ((org-pos-in-match-range pos 8) 'minute)
17330 ((or (org-pos-in-match-range pos 4)
17331 (org-pos-in-match-range pos 5)) 'day)
17332 ((and (> pos (or (match-end 8) (match-end 5)))
17333 (< pos (match-end 0)))
17334 (- pos (or (match-end 8) (match-end 5))))
17335 (t 'day))))
17337 (defun org-toggle-timestamp-type ()
17338 "Toggle the type (<active> or [inactive]) of a time stamp."
17339 (interactive)
17340 (when (org-at-timestamp-p 'lax)
17341 (let ((beg (match-beginning 0)) (end (match-end 0))
17342 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17343 (save-excursion
17344 (goto-char beg)
17345 (while (re-search-forward "[][<>]" end t)
17346 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17347 t t)))
17348 (message "Timestamp is now %sactive"
17349 (if (equal (char-after beg) ?<) "" "in")))))
17351 (defun org-at-clock-log-p ()
17352 "Non-nil if point is on a clock log line."
17353 (and (org-match-line org-clock-line-re)
17354 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17356 (defvar org-clock-history) ; defined in org-clock.el
17357 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17358 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17359 "Change the date in the time stamp at point.
17360 The date will be changed by N times WHAT. WHAT can be `day', `month',
17361 `year', `minute', `second'. If WHAT is not given, the cursor position
17362 in the timestamp determines what will be changed.
17363 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17364 (let ((origin (point))
17365 (timestamp? (org-at-timestamp-p 'lax))
17366 origin-cat
17367 with-hm inactive
17368 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17369 extra rem
17370 ts time time0 fixnext clrgx)
17371 (unless timestamp? (user-error "Not at a timestamp"))
17372 (if (and (not what) (eq timestamp? 'bracket))
17373 (org-toggle-timestamp-type)
17374 ;; Point isn't on brackets. Remember the part of the time-stamp
17375 ;; the point was in. Indeed, size of time-stamps may change,
17376 ;; but point must be kept in the same category nonetheless.
17377 (setq origin-cat timestamp?)
17378 (when (and (not what) (not (eq timestamp? 'day))
17379 org-display-custom-times
17380 (get-text-property (point) 'display)
17381 (not (get-text-property (1- (point)) 'display)))
17382 (setq timestamp? 'day))
17383 (setq timestamp? (or what timestamp?)
17384 inactive (= (char-after (match-beginning 0)) ?\[)
17385 ts (match-string 0))
17386 (replace-match "")
17387 (when (string-match
17388 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17390 (setq extra (match-string 1 ts))
17391 (when suppress-tmp-delay
17392 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17393 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17394 (setq with-hm t))
17395 (setq time0 (org-parse-time-string ts))
17396 (when (and updown
17397 (eq timestamp? 'minute)
17398 (not current-prefix-arg))
17399 ;; This looks like s-up and s-down. Change by one rounding step.
17400 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17401 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17402 (setcar (cdr time0) (+ (nth 1 time0)
17403 (if (> n 0) (- rem) (- dm rem))))))
17404 (setq time
17405 (apply #'encode-time
17406 (or (car time0) 0)
17407 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17408 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17409 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17410 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17411 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17412 (nthcdr 6 time0)))
17413 (when (and (memq timestamp? '(hour minute))
17414 extra
17415 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17416 (setq extra (org-modify-ts-extra
17417 extra
17418 (if (eq timestamp? 'hour) 2 5)
17419 n dm)))
17420 (when (integerp timestamp?)
17421 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17422 (when (eq what 'calendar)
17423 (let ((cal-date (org-get-date-from-calendar)))
17424 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17425 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17426 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17427 (setcar time0 (or (car time0) 0))
17428 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17429 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17430 (setq time (apply 'encode-time time0))))
17431 ;; Insert the new time-stamp, and ensure point stays in the same
17432 ;; category as before (i.e. not after the last position in that
17433 ;; category).
17434 (let ((pos (point)))
17435 ;; Stay before inserted string. `save-excursion' is of no use.
17436 (setq org-last-changed-timestamp
17437 (org-insert-time-stamp time with-hm inactive nil nil extra))
17438 (goto-char pos))
17439 (save-match-data
17440 (looking-at org-ts-regexp3)
17441 (goto-char
17442 (pcase origin-cat
17443 ;; `day' category ends before `hour' if any, or at the end
17444 ;; of the day name.
17445 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17446 (`hour (min (match-end 7) origin))
17447 (`minute (min (1- (match-end 8)) origin))
17448 ((pred integerp) (min (1- (match-end 0)) origin))
17449 ;; Point was right after the time-stamp. However, the
17450 ;; time-stamp length might have changed, so refer to
17451 ;; (match-end 0) instead.
17452 (`after (match-end 0))
17453 ;; `year' and `month' have both fixed size: point couldn't
17454 ;; have moved into another part.
17455 (_ origin))))
17456 ;; Update clock if on a CLOCK line.
17457 (org-clock-update-time-maybe)
17458 ;; Maybe adjust the closest clock in `org-clock-history'
17459 (when org-clock-adjust-closest
17460 (if (not (and (org-at-clock-log-p)
17461 (< 1 (length (delq nil (mapcar 'marker-position
17462 org-clock-history))))))
17463 (message "No clock to adjust")
17464 (cond ((save-excursion ; fix previous clock?
17465 (re-search-backward org-ts-regexp0 nil t)
17466 (looking-back (concat org-clock-string " \\[")
17467 (line-beginning-position)))
17468 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17469 ((save-excursion ; fix next clock?
17470 (re-search-backward org-ts-regexp0 nil t)
17471 (looking-at (concat org-ts-regexp0 "\\] =>")))
17472 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17473 (save-window-excursion
17474 ;; Find closest clock to point, adjust the previous/next one in history
17475 (let* ((p (save-excursion (org-back-to-heading t)))
17476 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17477 (clfixnth
17478 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17479 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17480 (if (not clfixpos)
17481 (message "No clock to adjust")
17482 (save-excursion
17483 (org-goto-marker-or-bmk clfixpos)
17484 (org-show-subtree)
17485 (when (re-search-forward clrgx nil t)
17486 (goto-char (match-beginning 1))
17487 (let (org-clock-adjust-closest)
17488 (org-timestamp-change n timestamp? updown))
17489 (message "Clock adjusted in %s for heading: %s"
17490 (file-name-nondirectory (buffer-file-name))
17491 (org-get-heading t t)))))))))
17492 ;; Try to recenter the calendar window, if any.
17493 (when (and org-calendar-follow-timestamp-change
17494 (get-buffer-window "*Calendar*" t)
17495 (memq timestamp? '(day month year)))
17496 (org-recenter-calendar (time-to-days time))))))
17498 (defun org-modify-ts-extra (s pos n dm)
17499 "Change the different parts of the lead-time and repeat fields in timestamp."
17500 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17501 ng h m new rem)
17502 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17503 (cond
17504 ((or (org-pos-in-match-range pos 2)
17505 (org-pos-in-match-range pos 3))
17506 (setq m (string-to-number (match-string 3 s))
17507 h (string-to-number (match-string 2 s)))
17508 (if (org-pos-in-match-range pos 2)
17509 (setq h (+ h n))
17510 (setq n (* dm (with-no-warnings (cl-signum n))))
17511 (unless (= 0 (setq rem (% m dm)))
17512 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17513 (setq m (+ m n)))
17514 (when (< m 0) (setq m (+ m 60) h (1- h)))
17515 (when (> m 59) (setq m (- m 60) h (1+ h)))
17516 (setq h (mod h 24))
17517 (setq ng 1 new (format "-%02d:%02d" h m)))
17518 ((org-pos-in-match-range pos 6)
17519 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17520 ((org-pos-in-match-range pos 5)
17521 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17523 ((org-pos-in-match-range pos 9)
17524 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17525 ((org-pos-in-match-range pos 8)
17526 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17528 (when ng
17529 (setq s (concat
17530 (substring s 0 (match-beginning ng))
17532 (substring s (match-end ng))))))
17535 (defun org-recenter-calendar (d)
17536 "If the calendar is visible, recenter it to date D."
17537 (let ((cwin (get-buffer-window "*Calendar*" t)))
17538 (when cwin
17539 (let ((calendar-move-hook nil))
17540 (with-selected-window cwin
17541 (calendar-goto-date
17542 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17544 (defun org-goto-calendar (&optional arg)
17545 "Go to the Emacs calendar at the current date.
17546 If there is a time stamp in the current line, go to that date.
17547 A prefix ARG can be used to force the current date."
17548 (interactive "P")
17549 (let ((calendar-move-hook nil)
17550 (calendar-view-holidays-initially-flag nil)
17551 (calendar-view-diary-initially-flag nil)
17552 diff)
17553 (when (or (org-at-timestamp-p 'lax)
17554 (org-match-line (concat ".*" org-ts-regexp)))
17555 (let ((d1 (time-to-days (current-time)))
17556 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17557 (setq diff (- d2 d1))))
17558 (calendar)
17559 (calendar-goto-today)
17560 (when (and diff (not arg)) (calendar-forward-day diff))))
17562 (defun org-get-date-from-calendar ()
17563 "Return a list (month day year) of date at point in calendar."
17564 (with-current-buffer "*Calendar*"
17565 (save-match-data
17566 (calendar-cursor-to-date))))
17568 (defun org-date-from-calendar ()
17569 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17570 If there is already a time stamp at the cursor position, update it."
17571 (interactive)
17572 (if (org-at-timestamp-p 'lax)
17573 (org-timestamp-change 0 'calendar)
17574 (let ((cal-date (org-get-date-from-calendar)))
17575 (org-insert-time-stamp
17576 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17578 (defcustom org-image-actual-width t
17579 "Should we use the actual width of images when inlining them?
17581 When set to t, always use the image width.
17583 When set to a number, use imagemagick (when available) to set
17584 the image's width to this value.
17586 When set to a number in a list, try to get the width from any
17587 #+ATTR.* keyword if it matches a width specification like
17589 #+ATTR_HTML: :width 300px
17591 and fall back on that number if none is found.
17593 When set to nil, try to get the width from an #+ATTR.* keyword
17594 and fall back on the original width if none is found.
17596 This requires Emacs >= 24.1, build with imagemagick support."
17597 :group 'org-appearance
17598 :version "24.4"
17599 :package-version '(Org . "8.0")
17600 :type '(choice
17601 (const :tag "Use the image width" t)
17602 (integer :tag "Use a number of pixels")
17603 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17604 (const :tag "Use #+ATTR* or don't resize" nil)))
17606 (defcustom org-agenda-inhibit-startup nil
17607 "Inhibit startup when preparing agenda buffers.
17608 When this variable is t, the initialization of the Org agenda
17609 buffers is inhibited: e.g. the visibility state is not set, the
17610 tables are not re-aligned, etc."
17611 :type 'boolean
17612 :version "24.3"
17613 :group 'org-agenda)
17615 (defcustom org-agenda-ignore-properties nil
17616 "Avoid updating text properties when building the agenda.
17617 Properties are used to prepare buffers for effort estimates,
17618 appointments, statistics and subtree-local categories.
17619 If you don't use these in the agenda, you can add them to this
17620 list and agenda building will be a bit faster.
17621 The value is a list, with zero or more of the symbols `effort', `appt',
17622 `stats' or `category'."
17623 :type '(set :greedy t
17624 (const effort)
17625 (const appt)
17626 (const stats)
17627 (const category))
17628 :version "26.1"
17629 :package-version '(Org . "8.3")
17630 :group 'org-agenda)
17632 ;;;; Files
17634 (defun org-save-all-org-buffers ()
17635 "Save all Org buffers without user confirmation."
17636 (interactive)
17637 (message "Saving all Org buffers...")
17638 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17639 (when (featurep 'org-id) (org-id-locations-save))
17640 (message "Saving all Org buffers... done"))
17642 (defun org-revert-all-org-buffers ()
17643 "Revert all Org buffers.
17644 Prompt for confirmation when there are unsaved changes.
17645 Be sure you know what you are doing before letting this function
17646 overwrite your changes.
17648 This function is useful in a setup where one tracks Org files
17649 with a version control system, to revert on one machine after pulling
17650 changes from another. I believe the procedure must be like this:
17652 1. M-x org-save-all-org-buffers
17653 2. Pull changes from the other machine, resolve conflicts
17654 3. M-x org-revert-all-org-buffers"
17655 (interactive)
17656 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17657 (user-error "Abort"))
17658 (save-excursion
17659 (save-window-excursion
17660 (dolist (b (buffer-list))
17661 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17662 (with-current-buffer b buffer-file-name))
17663 (pop-to-buffer-same-window b)
17664 (revert-buffer t 'no-confirm)))
17665 (when (and (featurep 'org-id) org-id-track-globally)
17666 (org-id-locations-load)))))
17668 ;;;; Agenda files
17670 ;;;###autoload
17671 (defun org-switchb (&optional arg)
17672 "Switch between Org buffers.
17674 With `\\[universal-argument]' prefix, restrict available buffers to files.
17676 With `\\[universal-argument] \\[universal-argument]' \
17677 prefix, restrict available buffers to agenda files."
17678 (interactive "P")
17679 (let ((blist (org-buffer-list
17680 (cond ((equal arg '(4)) 'files)
17681 ((equal arg '(16)) 'agenda)))))
17682 (pop-to-buffer-same-window
17683 (completing-read "Org buffer: "
17684 (mapcar #'list (mapcar #'buffer-name blist))
17685 nil t))))
17687 (defun org-buffer-list (&optional predicate exclude-tmp)
17688 "Return a list of Org buffers.
17689 PREDICATE can be `export', `files' or `agenda'.
17691 export restrict the list to Export buffers.
17692 files restrict the list to buffers visiting Org files.
17693 agenda restrict the list to buffers visiting agenda files.
17695 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17696 (let* ((bfn nil)
17697 (agenda-files (and (eq predicate 'agenda)
17698 (mapcar 'file-truename (org-agenda-files t))))
17699 (filter
17700 (cond
17701 ((eq predicate 'files)
17702 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17703 ((eq predicate 'export)
17704 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17705 ((eq predicate 'agenda)
17706 (lambda (b)
17707 (with-current-buffer b
17708 (and (derived-mode-p 'org-mode)
17709 (setq bfn (buffer-file-name b))
17710 (member (file-truename bfn) agenda-files)))))
17711 (t (lambda (b) (with-current-buffer b
17712 (or (derived-mode-p 'org-mode)
17713 (string-match "\\*Org .*Export"
17714 (buffer-name b)))))))))
17715 (delq nil
17716 (mapcar
17717 (lambda(b)
17718 (if (and (funcall filter b)
17719 (or (not exclude-tmp)
17720 (not (string-match "tmp" (buffer-name b)))))
17722 nil))
17723 (buffer-list)))))
17725 (defun org-agenda-files (&optional unrestricted archives)
17726 "Get the list of agenda files.
17727 Optional UNRESTRICTED means return the full list even if a restriction
17728 is currently in place.
17729 When ARCHIVES is t, include all archive files that are really being
17730 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17731 `org-agenda-archives-mode' is t."
17732 (let ((files
17733 (cond
17734 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17735 ((stringp org-agenda-files) (org-read-agenda-file-list))
17736 ((listp org-agenda-files) org-agenda-files)
17737 (t (error "Invalid value of `org-agenda-files'")))))
17738 (setq files (apply 'append
17739 (mapcar (lambda (f)
17740 (if (file-directory-p f)
17741 (directory-files
17742 f t org-agenda-file-regexp)
17743 (list f)))
17744 files)))
17745 (when org-agenda-skip-unavailable-files
17746 (setq files (delq nil
17747 (mapcar (function
17748 (lambda (file)
17749 (and (file-readable-p file) file)))
17750 files))))
17751 (when (or (eq archives t)
17752 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17753 (setq files (org-add-archive-files files)))
17754 files))
17756 (defun org-agenda-file-p (&optional file)
17757 "Return non-nil, if FILE is an agenda file.
17758 If FILE is omitted, use the file associated with the current
17759 buffer."
17760 (let ((fname (or file (buffer-file-name))))
17761 (and fname
17762 (member (file-truename fname)
17763 (mapcar #'file-truename (org-agenda-files t))))))
17765 (defun org-edit-agenda-file-list ()
17766 "Edit the list of agenda files.
17767 Depending on setup, this either uses customize to edit the variable
17768 `org-agenda-files', or it visits the file that is holding the list. In the
17769 latter case, the buffer is set up in a way that saving it automatically kills
17770 the buffer and restores the previous window configuration."
17771 (interactive)
17772 (if (stringp org-agenda-files)
17773 (let ((cw (current-window-configuration)))
17774 (find-file org-agenda-files)
17775 (setq-local org-window-configuration cw)
17776 (add-hook 'after-save-hook
17777 (lambda ()
17778 (set-window-configuration
17779 (prog1 org-window-configuration
17780 (kill-buffer (current-buffer))))
17781 (org-install-agenda-files-menu)
17782 (message "New agenda file list installed"))
17783 nil 'local)
17784 (message "%s" (substitute-command-keys
17785 "Edit list and finish with \\[save-buffer]")))
17786 (customize-variable 'org-agenda-files)))
17788 (defun org-store-new-agenda-file-list (list)
17789 "Set new value for the agenda file list and save it correctly."
17790 (if (stringp org-agenda-files)
17791 (let ((fe (org-read-agenda-file-list t)) b u)
17792 (while (setq b (find-buffer-visiting org-agenda-files))
17793 (kill-buffer b))
17794 (with-temp-file org-agenda-files
17795 (insert
17796 (mapconcat
17797 (lambda (f) ;; Keep un-expanded entries.
17798 (if (setq u (assoc f fe))
17799 (cdr u)
17801 list "\n")
17802 "\n")))
17803 (let ((org-mode-hook nil) (org-inhibit-startup t)
17804 (org-insert-mode-line-in-empty-file nil))
17805 (setq org-agenda-files list)
17806 (customize-save-variable 'org-agenda-files org-agenda-files))))
17808 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17809 "Read the list of agenda files from a file.
17810 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17811 filenames, used by `org-store-new-agenda-file-list' to write back
17812 un-expanded file names."
17813 (when (file-directory-p org-agenda-files)
17814 (error "`org-agenda-files' cannot be a single directory"))
17815 (when (stringp org-agenda-files)
17816 (with-temp-buffer
17817 (insert-file-contents org-agenda-files)
17818 (mapcar
17819 (lambda (f)
17820 (let ((e (expand-file-name (substitute-in-file-name f)
17821 org-directory)))
17822 (if pair-with-expansion
17823 (cons e f)
17824 e)))
17825 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17827 ;;;###autoload
17828 (defun org-cycle-agenda-files ()
17829 "Cycle through the files in `org-agenda-files'.
17830 If the current buffer visits an agenda file, find the next one in the list.
17831 If the current buffer does not, find the first agenda file."
17832 (interactive)
17833 (let* ((fs (or (org-agenda-files t)
17834 (user-error "No agenda files")))
17835 (files (copy-sequence fs))
17836 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17837 file)
17838 (when tcf
17839 (while (and (setq file (pop files))
17840 (not (equal (file-truename file) tcf)))))
17841 (find-file (car (or files fs)))
17842 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17844 (defun org-agenda-file-to-front (&optional to-end)
17845 "Move/add the current file to the top of the agenda file list.
17846 If the file is not present in the list, it is added to the front. If it is
17847 present, it is moved there. With optional argument TO-END, add/move to the
17848 end of the list."
17849 (interactive "P")
17850 (let ((org-agenda-skip-unavailable-files nil)
17851 (file-alist (mapcar (lambda (x)
17852 (cons (file-truename x) x))
17853 (org-agenda-files t)))
17854 (ctf (file-truename
17855 (or buffer-file-name
17856 (user-error "Please save the current buffer to a file"))))
17857 x had)
17858 (setq x (assoc ctf file-alist) had x)
17860 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17861 (if to-end
17862 (setq file-alist (append (delq x file-alist) (list x)))
17863 (setq file-alist (cons x (delq x file-alist))))
17864 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17865 (org-install-agenda-files-menu)
17866 (message "File %s to %s of agenda file list"
17867 (if had "moved" "added") (if to-end "end" "front"))))
17869 (defun org-remove-file (&optional file)
17870 "Remove current file from the list of files in variable `org-agenda-files'.
17871 These are the files which are being checked for agenda entries.
17872 Optional argument FILE means use this file instead of the current."
17873 (interactive)
17874 (let* ((org-agenda-skip-unavailable-files nil)
17875 (file (or file buffer-file-name
17876 (user-error "Current buffer does not visit a file")))
17877 (true-file (file-truename file))
17878 (afile (abbreviate-file-name file))
17879 (files (delq nil (mapcar
17880 (lambda (x)
17881 (unless (equal true-file
17882 (file-truename x))
17884 (org-agenda-files t)))))
17885 (if (not (= (length files) (length (org-agenda-files t))))
17886 (progn
17887 (org-store-new-agenda-file-list files)
17888 (org-install-agenda-files-menu)
17889 (message "Removed from Org Agenda list: %s" afile))
17890 (message "File was not in list: %s (not removed)" afile))))
17892 (defun org-file-menu-entry (file)
17893 (vector file (list 'find-file file) t))
17895 (defun org-check-agenda-file (file)
17896 "Make sure FILE exists. If not, ask user what to do."
17897 (unless (file-exists-p file)
17898 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17899 (abbreviate-file-name file))
17900 (let ((r (downcase (read-char-exclusive))))
17901 (cond
17902 ((equal r ?r)
17903 (org-remove-file file)
17904 (throw 'nextfile t))
17905 (t (user-error "Abort"))))))
17907 (defun org-get-agenda-file-buffer (file)
17908 "Get an agenda buffer visiting FILE.
17909 If the buffer needs to be created, add it to the list of buffers
17910 which might be released later."
17911 (let ((buf (org-find-base-buffer-visiting file)))
17912 (if buf
17913 buf ; just return it
17914 ;; Make a new buffer and remember it
17915 (setq buf (find-file-noselect file))
17916 (when buf (push buf org-agenda-new-buffers))
17917 buf)))
17919 (defun org-release-buffers (blist)
17920 "Release all buffers in list, asking the user for confirmation when needed.
17921 When a buffer is unmodified, it is just killed. When modified, it is saved
17922 \(if the user agrees) and then killed."
17923 (let (file)
17924 (dolist (buf blist)
17925 (setq file (buffer-file-name buf))
17926 (when (and (buffer-modified-p buf)
17927 file
17928 (y-or-n-p (format "Save file %s? " file)))
17929 (with-current-buffer buf (save-buffer)))
17930 (kill-buffer buf))))
17932 (defun org-agenda-prepare-buffers (files)
17933 "Create buffers for all agenda files, protect archived trees and comments."
17934 (interactive)
17935 (let ((pa '(:org-archived t))
17936 (pc '(:org-comment t))
17937 (pall '(:org-archived t :org-comment t))
17938 (inhibit-read-only t)
17939 (org-inhibit-startup org-agenda-inhibit-startup)
17940 (rea (org-make-tag-string (list org-archive-tag)))
17941 re pos)
17942 (setq org-tag-alist-for-agenda nil
17943 org-tag-groups-alist-for-agenda nil)
17944 (save-excursion
17945 (save-restriction
17946 (dolist (file files)
17947 (catch 'nextfile
17948 (if (bufferp file)
17949 (set-buffer file)
17950 (org-check-agenda-file file)
17951 (set-buffer (org-get-agenda-file-buffer file)))
17952 (widen)
17953 (org-set-regexps-and-options 'tags-only)
17954 (setq pos (point))
17955 (or (memq 'category org-agenda-ignore-properties)
17956 (org-refresh-category-properties))
17957 (or (memq 'stats org-agenda-ignore-properties)
17958 (org-refresh-stats-properties))
17959 (or (memq 'effort org-agenda-ignore-properties)
17960 (org-refresh-effort-properties))
17961 (or (memq 'appt org-agenda-ignore-properties)
17962 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17963 (setq org-todo-keywords-for-agenda
17964 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17965 (setq org-done-keywords-for-agenda
17966 (append org-done-keywords-for-agenda org-done-keywords))
17967 (setq org-todo-keyword-alist-for-agenda
17968 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17969 (setq org-tag-alist-for-agenda
17970 (org--tag-add-to-alist
17971 org-tag-alist-for-agenda
17972 org-current-tag-alist))
17973 ;; Merge current file's tag groups into global
17974 ;; `org-tag-groups-alist-for-agenda'.
17975 (when org-group-tags
17976 (dolist (alist org-tag-groups-alist)
17977 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17978 (if old
17979 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17980 (push alist org-tag-groups-alist-for-agenda)))))
17981 (with-silent-modifications
17982 (save-excursion
17983 (remove-text-properties (point-min) (point-max) pall)
17984 (when org-agenda-skip-archived-trees
17985 (goto-char (point-min))
17986 (while (re-search-forward rea nil t)
17987 (when (org-at-heading-p t)
17988 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17989 (goto-char (point-min))
17990 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17991 (while (re-search-forward re nil t)
17992 (when (save-match-data (org-in-commented-heading-p t))
17993 (add-text-properties
17994 (match-beginning 0) (org-end-of-subtree t) pc)))))
17995 (goto-char pos)))))
17996 (setq org-todo-keywords-for-agenda
17997 (org-uniquify org-todo-keywords-for-agenda))
17998 (setq org-todo-keyword-alist-for-agenda
17999 (org-uniquify org-todo-keyword-alist-for-agenda))))
18002 ;;;; CDLaTeX minor mode
18004 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18005 "Keymap for the minor `org-cdlatex-mode'.")
18007 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
18008 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
18009 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
18010 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
18011 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
18013 (defvar org-cdlatex-texmathp-advice-is-done nil
18014 "Flag remembering if we have applied the advice to texmathp already.")
18016 (define-minor-mode org-cdlatex-mode
18017 "Toggle the minor `org-cdlatex-mode'.
18018 This mode supports entering LaTeX environment and math in LaTeX fragments
18019 in Org mode.
18020 \\{org-cdlatex-mode-map}"
18021 nil " OCDL" nil
18022 (when org-cdlatex-mode
18023 (require 'cdlatex)
18024 (run-hooks 'cdlatex-mode-hook)
18025 (cdlatex-compute-tables))
18026 (unless org-cdlatex-texmathp-advice-is-done
18027 (setq org-cdlatex-texmathp-advice-is-done t)
18028 (defadvice texmathp (around org-math-always-on activate)
18029 "Always return t in Org buffers.
18030 This is because we want to insert math symbols without dollars even outside
18031 the LaTeX math segments. If Org mode thinks that point is actually inside
18032 an embedded LaTeX fragment, let `texmathp' do its job.
18033 `\\[org-cdlatex-mode-map]'"
18034 (interactive)
18035 (let (p)
18036 (cond
18037 ((not (derived-mode-p 'org-mode)) ad-do-it)
18038 ((eq this-command 'cdlatex-math-symbol)
18039 (setq ad-return-value t
18040 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18042 (let ((p (org-inside-LaTeX-fragment-p)))
18043 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18044 (setq ad-return-value t
18045 texmathp-why '("Org mode embedded math" . 0))
18046 (when p ad-do-it)))))))))
18048 (defun turn-on-org-cdlatex ()
18049 "Unconditionally turn on `org-cdlatex-mode'."
18050 (org-cdlatex-mode 1))
18052 (defun org-try-cdlatex-tab ()
18053 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18054 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18055 - inside a LaTeX fragment, or
18056 - after the first word in a line, where an abbreviation expansion could
18057 insert a LaTeX environment."
18058 (when org-cdlatex-mode
18059 (cond
18060 ;; Before any word on the line: No expansion possible.
18061 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18062 ;; Just after first word on the line: Expand it. Make sure it
18063 ;; cannot happen on headlines, though.
18064 ((save-excursion
18065 (skip-chars-backward "a-zA-Z0-9*")
18066 (skip-chars-backward " \t")
18067 (and (bolp) (not (org-at-heading-p))))
18068 (cdlatex-tab) t)
18069 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18071 (defun org-cdlatex-underscore-caret (&optional _arg)
18072 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18073 Revert to the normal definition outside of these fragments."
18074 (interactive "P")
18075 (if (org-inside-LaTeX-fragment-p)
18076 (call-interactively 'cdlatex-sub-superscript)
18077 (let (org-cdlatex-mode)
18078 (call-interactively (key-binding (vector last-input-event))))))
18080 (defun org-cdlatex-math-modify (&optional _arg)
18081 "Execute `cdlatex-math-modify' in LaTeX fragments.
18082 Revert to the normal definition outside of these fragments."
18083 (interactive "P")
18084 (if (org-inside-LaTeX-fragment-p)
18085 (call-interactively 'cdlatex-math-modify)
18086 (let (org-cdlatex-mode)
18087 (call-interactively (key-binding (vector last-input-event))))))
18089 (defun org-cdlatex-environment-indent (&optional environment item)
18090 "Execute `cdlatex-environment' and indent the inserted environment.
18092 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18094 The inserted environment is indented to current indentation
18095 unless point is at the beginning of the line, in which the
18096 environment remains unintended."
18097 (interactive)
18098 ;; cdlatex-environment always return nil. Therefore, capture output
18099 ;; first and determine if an environment was selected.
18100 (let* ((beg (point-marker))
18101 (end (copy-marker (point) t))
18102 (inserted (progn
18103 (ignore-errors (cdlatex-environment environment item))
18104 (< beg end)))
18105 ;; Figure out how many lines to move forward after the
18106 ;; environment has been inserted.
18107 (lines (when inserted
18108 (save-excursion
18109 (- (cl-loop while (< beg (point))
18110 with x = 0
18111 do (forward-line -1)
18112 (cl-incf x)
18113 finally return x)
18114 (if (progn (goto-char beg)
18115 (and (progn (skip-chars-forward " \t") (eolp))
18116 (progn (skip-chars-backward " \t") (bolp))))
18117 1 0)))))
18118 (env (org-trim (delete-and-extract-region beg end))))
18119 (when inserted
18120 ;; Get indentation of next line unless at column 0.
18121 (let ((ind (if (bolp) 0
18122 (save-excursion
18123 (org-return-indent)
18124 (prog1 (current-indentation)
18125 (when (progn (skip-chars-forward " \t") (eolp))
18126 (delete-region beg (point)))))))
18127 (bol (progn (skip-chars-backward " \t") (bolp))))
18128 ;; Insert a newline before environment unless at column zero
18129 ;; to "escape" the current line. Insert a newline if
18130 ;; something is one the same line as \end{ENVIRONMENT}.
18131 (insert
18132 (concat (unless bol "\n") env
18133 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18134 (unless (zerop ind)
18135 (save-excursion
18136 (goto-char beg)
18137 (while (< (point) end)
18138 (unless (eolp) (indent-line-to ind))
18139 (forward-line))))
18140 (goto-char beg)
18141 (forward-line lines)
18142 (indent-line-to ind)))
18143 (set-marker beg nil)
18144 (set-marker end nil)))
18147 ;;;; LaTeX fragments
18149 (defun org-inside-LaTeX-fragment-p ()
18150 "Test if point is inside a LaTeX fragment.
18151 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18152 sequence appearing also before point.
18153 Even though the matchers for math are configurable, this function assumes
18154 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18155 delimiters are skipped when they have been removed by customization.
18156 The return value is nil, or a cons cell with the delimiter and the
18157 position of this delimiter.
18159 This function does a reasonably good job, but can locally be fooled by
18160 for example currency specifications. For example it will assume being in
18161 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18162 fragments that are properly closed, but during editing, we have to live
18163 with the uncertainty caused by missing closing delimiters. This function
18164 looks only before point, not after."
18165 (catch 'exit
18166 (let ((pos (point))
18167 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18168 (lim (save-excursion (org-backward-paragraph) (point)))
18169 dd-on str (start 0) m re)
18170 (goto-char pos)
18171 (when dodollar
18172 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18173 re (nth 1 (assoc "$" org-latex-regexps)))
18174 (while (string-match re str start)
18175 (cond
18176 ((= (match-end 0) (length str))
18177 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18178 ((= (match-end 0) (- (length str) 5))
18179 (throw 'exit nil))
18180 (t (setq start (match-end 0))))))
18181 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18182 (goto-char pos)
18183 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18184 (and (match-beginning 2) (throw 'exit nil))
18185 ;; count $$
18186 (while (re-search-backward "\\$\\$" lim t)
18187 (setq dd-on (not dd-on)))
18188 (goto-char pos)
18189 (when dd-on (cons "$$" m))))))
18191 (defun org-inside-latex-macro-p ()
18192 "Is point inside a LaTeX macro or its arguments?"
18193 (save-match-data
18194 (org-in-regexp
18195 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18197 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18198 "Build an overlay between BEG and END using IMAGE file.
18199 Argument IMAGETYPE is the extension of the displayed image,
18200 as a string. It defaults to \"png\"."
18201 (let ((ov (make-overlay beg end))
18202 (imagetype (or (intern imagetype) 'png)))
18203 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18204 (overlay-put ov 'evaporate t)
18205 (overlay-put ov
18206 'modification-hooks
18207 (list (lambda (o _flag _beg _end &optional _l)
18208 (delete-overlay o))))
18209 (overlay-put ov
18210 'display
18211 (list 'image :type imagetype :file image :ascent 'center))))
18213 (defun org--list-latex-overlays (&optional beg end)
18214 "List all Org LaTeX overlays in current buffer.
18215 Limit to overlays between BEG and END when those are provided."
18216 (cl-remove-if-not
18217 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18218 (overlays-in (or beg (point-min)) (or end (point-max)))))
18220 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18221 "Remove all overlays with LaTeX fragment images in current buffer.
18222 When optional arguments BEG and END are non-nil, remove all
18223 overlays between them instead. Return a non-nil value when some
18224 overlays were removed, nil otherwise."
18225 (let ((overlays (org--list-latex-overlays beg end)))
18226 (mapc #'delete-overlay overlays)
18227 overlays))
18229 (defun org-toggle-latex-fragment (&optional arg)
18230 "Preview the LaTeX fragment at point, or all locally or globally.
18232 If the cursor is on a LaTeX fragment, create the image and overlay
18233 it over the source code, if there is none. Remove it otherwise.
18234 If there is no fragment at point, display all fragments in the
18235 current section.
18237 With prefix ARG, preview or clear image for all fragments in the
18238 current subtree or in the whole buffer when used before the first
18239 headline. With a prefix ARG `\\[universal-argument] \
18240 \\[universal-argument]' preview or clear images
18241 for all fragments in the buffer."
18242 (interactive "P")
18243 (when (display-graphic-p)
18244 (catch 'exit
18245 (save-excursion
18246 (let (beg end msg)
18247 (cond
18248 ((or (equal arg '(16))
18249 (and (equal arg '(4))
18250 (org-with-limited-levels (org-before-first-heading-p))))
18251 (if (org-remove-latex-fragment-image-overlays)
18252 (progn (message "LaTeX fragments images removed from buffer")
18253 (throw 'exit nil))
18254 (setq msg "Creating images for buffer...")))
18255 ((equal arg '(4))
18256 (org-with-limited-levels (org-back-to-heading t))
18257 (setq beg (point))
18258 (setq end (progn (org-end-of-subtree t) (point)))
18259 (if (org-remove-latex-fragment-image-overlays beg end)
18260 (progn
18261 (message "LaTeX fragment images removed from subtree")
18262 (throw 'exit nil))
18263 (setq msg "Creating images for subtree...")))
18264 ((let ((datum (org-element-context)))
18265 (when (memq (org-element-type datum)
18266 '(latex-environment latex-fragment))
18267 (setq beg (org-element-property :begin datum))
18268 (setq end (org-element-property :end datum))
18269 (if (org-remove-latex-fragment-image-overlays beg end)
18270 (progn (message "LaTeX fragment image removed")
18271 (throw 'exit nil))
18272 (setq msg "Creating image...")))))
18274 (org-with-limited-levels
18275 (setq beg (if (org-at-heading-p) (line-beginning-position)
18276 (outline-previous-heading)
18277 (point)))
18278 (setq end (progn (outline-next-heading) (point)))
18279 (if (org-remove-latex-fragment-image-overlays beg end)
18280 (progn
18281 (message "LaTeX fragment images removed from section")
18282 (throw 'exit nil))
18283 (setq msg "Creating images for section...")))))
18284 (let ((file (buffer-file-name (buffer-base-buffer))))
18285 (org-format-latex
18286 (concat org-preview-latex-image-directory "org-ltximg")
18287 beg end
18288 ;; Emacs cannot overlay images from remote hosts. Create
18289 ;; it in `temporary-file-directory' instead.
18290 (if (or (not file) (file-remote-p file))
18291 temporary-file-directory
18292 default-directory)
18293 'overlays msg 'forbuffer org-preview-latex-default-process))
18294 (message (concat msg "done")))))))
18296 (defun org-format-latex
18297 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18298 "Replace LaTeX fragments with links to an image.
18300 The function takes care of creating the replacement image.
18302 Only consider fragments between BEG and END when those are
18303 provided.
18305 When optional argument OVERLAYS is non-nil, display the image on
18306 top of the fragment instead of replacing it.
18308 PROCESSING-TYPE is the conversion method to use, as a symbol.
18310 Some of the options can be changed using the variable
18311 `org-format-latex-options', which see."
18312 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18313 (unless (eq processing-type 'verbatim)
18314 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18315 (cnt 0)
18316 checkdir-flag)
18317 (goto-char (or beg (point-min)))
18318 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18319 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18320 (overlay-recenter (or end (point-max))))
18321 (while (re-search-forward math-regexp end t)
18322 (unless (and overlays
18323 (eq (get-char-property (point) 'org-overlay-type)
18324 'org-latex-overlay))
18325 (let* ((context (org-element-context))
18326 (type (org-element-type context)))
18327 (when (memq type '(latex-environment latex-fragment))
18328 (let ((block-type (eq type 'latex-environment))
18329 (value (org-element-property :value context))
18330 (beg (org-element-property :begin context))
18331 (end (save-excursion
18332 (goto-char (org-element-property :end context))
18333 (skip-chars-backward " \r\t\n")
18334 (point))))
18335 (cond
18336 ((eq processing-type 'mathjax)
18337 ;; Prepare for MathJax processing.
18338 (if (not (string-match "\\`\\$\\$?" value))
18339 (goto-char end)
18340 (delete-region beg end)
18341 (if (string= (match-string 0 value) "$$")
18342 (insert "\\[" (substring value 2 -2) "\\]")
18343 (insert "\\(" (substring value 1 -1) "\\)"))))
18344 ((assq processing-type org-preview-latex-process-alist)
18345 ;; Process to an image.
18346 (cl-incf cnt)
18347 (goto-char beg)
18348 (let* ((processing-info
18349 (cdr (assq processing-type org-preview-latex-process-alist)))
18350 (face (face-at-point))
18351 ;; Get the colors from the face at point.
18353 (let ((color (plist-get org-format-latex-options
18354 :foreground)))
18355 (if (and forbuffer (eq color 'auto))
18356 (face-attribute face :foreground nil 'default)
18357 color)))
18359 (let ((color (plist-get org-format-latex-options
18360 :background)))
18361 (if (and forbuffer (eq color 'auto))
18362 (face-attribute face :background nil 'default)
18363 color)))
18364 (hash (sha1 (prin1-to-string
18365 (list org-format-latex-header
18366 org-latex-default-packages-alist
18367 org-latex-packages-alist
18368 org-format-latex-options
18369 forbuffer value fg bg))))
18370 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18371 (absprefix (expand-file-name prefix dir))
18372 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18373 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18374 (sep (and block-type "\n\n"))
18375 (link (concat sep "[[file:" linkfile "]]" sep))
18376 (options
18377 (org-combine-plists
18378 org-format-latex-options
18379 `(:foreground ,fg :background ,bg))))
18380 (when msg (message msg cnt))
18381 (unless checkdir-flag ; Ensure the directory exists.
18382 (setq checkdir-flag t)
18383 (let ((todir (file-name-directory absprefix)))
18384 (unless (file-directory-p todir)
18385 (make-directory todir t))))
18386 (unless (file-exists-p movefile)
18387 (org-create-formula-image
18388 value movefile options forbuffer processing-type))
18389 (if overlays
18390 (progn
18391 (dolist (o (overlays-in beg end))
18392 (when (eq (overlay-get o 'org-overlay-type)
18393 'org-latex-overlay)
18394 (delete-overlay o)))
18395 (org--format-latex-make-overlay beg end movefile imagetype)
18396 (goto-char end))
18397 (delete-region beg end)
18398 (insert
18399 (org-add-props link
18400 (list 'org-latex-src
18401 (replace-regexp-in-string "\"" "" value)
18402 'org-latex-src-embed-type
18403 (if block-type 'paragraph 'character)))))))
18404 ((eq processing-type 'mathml)
18405 ;; Process to MathML.
18406 (unless (org-format-latex-mathml-available-p)
18407 (user-error "LaTeX to MathML converter not configured"))
18408 (cl-incf cnt)
18409 (when msg (message msg cnt))
18410 (goto-char beg)
18411 (delete-region beg end)
18412 (insert (org-format-latex-as-mathml
18413 value block-type prefix dir)))
18415 (error "Unknown conversion process %s for LaTeX fragments"
18416 processing-type)))))))))))
18418 (defun org-create-math-formula (latex-frag &optional mathml-file)
18419 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18420 Use `org-latex-to-mathml-convert-command'. If the conversion is
18421 sucessful, return the portion between \"<math...> </math>\"
18422 elements otherwise return nil. When MATHML-FILE is specified,
18423 write the results in to that file. When invoked as an
18424 interactive command, prompt for LATEX-FRAG, with initial value
18425 set to the current active region and echo the results for user
18426 inspection."
18427 (interactive (list (let ((frag (when (org-region-active-p)
18428 (buffer-substring-no-properties
18429 (region-beginning) (region-end)))))
18430 (read-string "LaTeX Fragment: " frag nil frag))))
18431 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18432 (let* ((tmp-in-file
18433 (let ((file (file-relative-name
18434 (make-temp-name (expand-file-name "ltxmathml-in")))))
18435 (write-region latex-frag nil file)
18436 file))
18437 (tmp-out-file (file-relative-name
18438 (make-temp-name (expand-file-name "ltxmathml-out"))))
18439 (cmd (format-spec
18440 org-latex-to-mathml-convert-command
18441 `((?j . ,(and org-latex-to-mathml-jar-file
18442 (shell-quote-argument
18443 (expand-file-name
18444 org-latex-to-mathml-jar-file))))
18445 (?I . ,(shell-quote-argument tmp-in-file))
18446 (?i . ,latex-frag)
18447 (?o . ,(shell-quote-argument tmp-out-file)))))
18448 mathml shell-command-output)
18449 (when (called-interactively-p 'any)
18450 (unless (org-format-latex-mathml-available-p)
18451 (user-error "LaTeX to MathML converter not configured")))
18452 (message "Running %s" cmd)
18453 (setq shell-command-output (shell-command-to-string cmd))
18454 (setq mathml
18455 (when (file-readable-p tmp-out-file)
18456 (with-current-buffer (find-file-noselect tmp-out-file t)
18457 (goto-char (point-min))
18458 (when (re-search-forward
18459 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18460 (regexp-quote
18461 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18462 nil t)
18463 (prog1 (match-string 0) (kill-buffer))))))
18464 (cond
18465 (mathml
18466 (setq mathml
18467 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18468 (when mathml-file
18469 (write-region mathml nil mathml-file))
18470 (when (called-interactively-p 'any)
18471 (message mathml)))
18472 ((message "LaTeX to MathML conversion failed")
18473 (message shell-command-output)))
18474 (delete-file tmp-in-file)
18475 (when (file-exists-p tmp-out-file)
18476 (delete-file tmp-out-file))
18477 mathml))
18479 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18480 prefix &optional dir)
18481 "Use `org-create-math-formula' but check local cache first."
18482 (let* ((absprefix (expand-file-name prefix dir))
18483 (print-length nil) (print-level nil)
18484 (formula-id (concat
18485 "formula-"
18486 (sha1
18487 (prin1-to-string
18488 (list latex-frag
18489 org-latex-to-mathml-convert-command)))))
18490 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18491 (formula-cache-dir (file-name-directory formula-cache)))
18493 (unless (file-directory-p formula-cache-dir)
18494 (make-directory formula-cache-dir t))
18496 (unless (file-exists-p formula-cache)
18497 (org-create-math-formula latex-frag formula-cache))
18499 (if (file-exists-p formula-cache)
18500 ;; Successful conversion. Return the link to MathML file.
18501 (org-add-props
18502 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18503 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18504 'org-latex-src-embed-type (if latex-frag-type
18505 'paragraph 'character)))
18506 ;; Failed conversion. Return the LaTeX fragment verbatim
18507 latex-frag)))
18509 (defun org--get-display-dpi ()
18510 "Get the DPI of the display.
18511 The function assumes that the display has the same pixel width in
18512 the horizontal and vertical directions."
18513 (if (display-graphic-p)
18514 (round (/ (display-pixel-height)
18515 (/ (display-mm-height) 25.4)))
18516 (error "Attempt to calculate the dpi of a non-graphic display")))
18518 (defun org-create-formula-image
18519 (string tofile options buffer &optional processing-type)
18520 "Create an image from LaTeX source using external processes.
18522 The LaTeX STRING is saved to a temporary LaTeX file, then
18523 converted to an image file by process PROCESSING-TYPE defined in
18524 `org-preview-latex-process-alist'. A nil value defaults to
18525 `org-preview-latex-default-process'.
18527 The generated image file is eventually moved to TOFILE.
18529 The OPTIONS argument controls the size, foreground color and
18530 background color of the generated image.
18532 When BUFFER non-nil, this function is used for LaTeX previewing.
18533 Otherwise, it is used to deal with LaTeX snippets showed in
18534 a HTML file."
18535 (let* ((processing-type (or processing-type
18536 org-preview-latex-default-process))
18537 (processing-info
18538 (cdr (assq processing-type org-preview-latex-process-alist)))
18539 (programs (plist-get processing-info :programs))
18540 (error-message (or (plist-get processing-info :message) ""))
18541 (use-xcolor (plist-get processing-info :use-xcolor))
18542 (image-input-type (plist-get processing-info :image-input-type))
18543 (image-output-type (plist-get processing-info :image-output-type))
18544 (post-clean (or (plist-get processing-info :post-clean)
18545 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18546 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18547 (latex-header
18548 (or (plist-get processing-info :latex-header)
18549 (org-latex-make-preamble
18550 (org-export-get-environment (org-export-get-backend 'latex))
18551 org-format-latex-header
18552 'snippet)))
18553 (latex-compiler (plist-get processing-info :latex-compiler))
18554 (image-converter (plist-get processing-info :image-converter))
18555 (tmpdir temporary-file-directory)
18556 (texfilebase (make-temp-name
18557 (expand-file-name "orgtex" tmpdir)))
18558 (texfile (concat texfilebase ".tex"))
18559 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18560 '(1.0 . 1.0)))
18561 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18562 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18563 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18564 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18565 "Black"))
18566 (bg (or (plist-get options (if buffer :background :html-background))
18567 "Transparent"))
18568 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18569 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18570 (dolist (program programs)
18571 (org-check-external-command program error-message))
18572 (if use-xcolor
18573 (progn (if (eq fg 'default)
18574 (setq fg (org-latex-color :foreground))
18575 (setq fg (org-latex-color-format fg)))
18576 (if (eq bg 'default)
18577 (setq bg (org-latex-color :background))
18578 (setq bg (org-latex-color-format
18579 (if (string= bg "Transparent") "white" bg))))
18580 (with-temp-file texfile
18581 (insert latex-header)
18582 (insert "\n\\begin{document}\n"
18583 "\\definecolor{fg}{rgb}{" fg "}\n"
18584 "\\definecolor{bg}{rgb}{" bg "}\n"
18585 "\n\\pagecolor{bg}\n"
18586 "\n{\\color{fg}\n"
18587 string
18588 "\n}\n"
18589 "\n\\end{document}\n")))
18590 (if (eq fg 'default)
18591 (setq fg (org-dvipng-color :foreground))
18592 (unless (string= fg "Transparent")
18593 (setq fg (org-dvipng-color-format fg))))
18594 (if (eq bg 'default)
18595 (setq bg (org-dvipng-color :background))
18596 (unless (string= bg "Transparent")
18597 (setq bg (org-dvipng-color-format bg))))
18598 (with-temp-file texfile
18599 (insert latex-header)
18600 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18602 (let* ((err-msg (format "Please adjust `%s' part of \
18603 `org-preview-latex-process-alist'."
18604 processing-type))
18605 (image-input-file
18606 (org-compile-file
18607 texfile latex-compiler image-input-type err-msg log-buf))
18608 (image-output-file
18609 (org-compile-file
18610 image-input-file image-converter image-output-type err-msg log-buf
18611 `((?F . ,(shell-quote-argument fg))
18612 (?B . ,(shell-quote-argument bg))
18613 (?D . ,(shell-quote-argument (format "%s" dpi)))
18614 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18615 (copy-file image-output-file tofile 'replace)
18616 (dolist (e post-clean)
18617 (when (file-exists-p (concat texfilebase e))
18618 (delete-file (concat texfilebase e))))
18619 image-output-file)))
18621 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18622 "Fill a LaTeX header template TPL.
18623 In the template, the following place holders will be recognized:
18625 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18626 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18627 [PACKAGES] \\usepackage statements for PKG
18628 [NO-PACKAGES] do not include PKG
18629 [EXTRA] the string EXTRA
18630 [NO-EXTRA] do not include EXTRA
18632 For backward compatibility, if both the positive and the negative place
18633 holder is missing, the positive one (without the \"NO-\") will be
18634 assumed to be present at the end of the template.
18635 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18636 EXTRA is a string.
18637 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18638 (let (rpl (end ""))
18639 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18640 (setq rpl (if (or (match-end 1) (not def-pkg))
18641 "" (org-latex-packages-to-string def-pkg snippets-p t))
18642 tpl (replace-match rpl t t tpl))
18643 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18645 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18646 (setq rpl (if (or (match-end 1) (not pkg))
18647 "" (org-latex-packages-to-string pkg snippets-p t))
18648 tpl (replace-match rpl t t tpl))
18649 (when pkg (setq end
18650 (concat end "\n"
18651 (org-latex-packages-to-string pkg snippets-p)))))
18653 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18654 (setq rpl (if (or (match-end 1) (not extra))
18655 "" (concat extra "\n"))
18656 tpl (replace-match rpl t t tpl))
18657 (when (and extra (string-match "\\S-" extra))
18658 (setq end (concat end "\n" extra))))
18660 (if (string-match "\\S-" end)
18661 (concat tpl "\n" end)
18662 tpl)))
18664 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18665 "Turn an alist of packages into a string with the \\usepackage macros."
18666 (setq pkg (mapconcat (lambda(p)
18667 (cond
18668 ((stringp p) p)
18669 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18670 (format "%% Package %s omitted" (cadr p)))
18671 ((equal "" (car p))
18672 (format "\\usepackage{%s}" (cadr p)))
18674 (format "\\usepackage[%s]{%s}"
18675 (car p) (cadr p)))))
18677 "\n"))
18678 (if newline (concat pkg "\n") pkg))
18680 (defun org-dvipng-color (attr)
18681 "Return a RGB color specification for dvipng."
18682 (org-dvipng-color-format (face-attribute 'default attr nil)))
18684 (defun org-dvipng-color-format (color-name)
18685 "Convert COLOR-NAME to a RGB color value for dvipng."
18686 (apply #'format "rgb %s %s %s"
18687 (mapcar 'org-normalize-color
18688 (color-values color-name))))
18690 (defun org-latex-color (attr)
18691 "Return a RGB color for the LaTeX color package."
18692 (org-latex-color-format (face-attribute 'default attr nil)))
18694 (defun org-latex-color-format (color-name)
18695 "Convert COLOR-NAME to a RGB color value."
18696 (apply #'format "%s,%s,%s"
18697 (mapcar 'org-normalize-color
18698 (color-values color-name))))
18700 (defun org-normalize-color (value)
18701 "Return string to be used as color value for an RGB component."
18702 (format "%g" (/ value 65535.0)))
18705 ;; Image display
18707 (defvar-local org-inline-image-overlays nil)
18709 (defun org-toggle-inline-images (&optional include-linked)
18710 "Toggle the display of inline images.
18711 INCLUDE-LINKED is passed to `org-display-inline-images'."
18712 (interactive "P")
18713 (if org-inline-image-overlays
18714 (progn
18715 (org-remove-inline-images)
18716 (when (called-interactively-p 'interactive)
18717 (message "Inline image display turned off")))
18718 (org-display-inline-images include-linked)
18719 (when (called-interactively-p 'interactive)
18720 (message (if org-inline-image-overlays
18721 (format "%d images displayed inline"
18722 (length org-inline-image-overlays))
18723 "No images to display inline")))))
18725 (defun org-redisplay-inline-images ()
18726 "Refresh the display of inline images."
18727 (interactive)
18728 (if (not org-inline-image-overlays)
18729 (org-toggle-inline-images)
18730 (org-toggle-inline-images)
18731 (org-toggle-inline-images)))
18733 (defun org-display-inline-images (&optional include-linked refresh beg end)
18734 "Display inline images.
18736 An inline image is a link which follows either of these
18737 conventions:
18739 1. Its path is a file with an extension matching return value
18740 from `image-file-name-regexp' and it has no contents.
18742 2. Its description consists in a single link of the previous
18743 type.
18745 When optional argument INCLUDE-LINKED is non-nil, also links with
18746 a text description part will be inlined. This can be nice for
18747 a quick look at those images, but it does not reflect what
18748 exported files will look like.
18750 When optional argument REFRESH is non-nil, refresh existing
18751 images between BEG and END. This will create new image displays
18752 only if necessary. BEG and END default to the buffer
18753 boundaries."
18754 (interactive "P")
18755 (when (display-graphic-p)
18756 (unless refresh
18757 (org-remove-inline-images)
18758 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18759 (org-with-wide-buffer
18760 (goto-char (or beg (point-min)))
18761 (let* ((case-fold-search t)
18762 (file-extension-re (image-file-name-regexp))
18763 (link-abbrevs (mapcar #'car
18764 (append org-link-abbrev-alist-local
18765 org-link-abbrev-alist)))
18766 ;; Check absolute, relative file names and explicit
18767 ;; "file:" links. Also check link abbreviations since
18768 ;; some might expand to "file" links.
18769 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18770 (if (not link-abbrevs) ""
18771 (format "\\|\\(?:%s:\\)"
18772 (regexp-opt link-abbrevs))))))
18773 (while (re-search-forward file-types-re end t)
18774 (let ((link (save-match-data (org-element-context))))
18775 ;; Check if we're at an inline image, i.e., an image file
18776 ;; link without a description (unless INCLUDE-LINKED is
18777 ;; non-nil).
18778 (when (and (equal "file" (org-element-property :type link))
18779 (or include-linked
18780 (null (org-element-contents link)))
18781 (string-match-p file-extension-re
18782 (org-element-property :path link)))
18783 (let ((file (expand-file-name
18784 (org-link-unescape
18785 (org-element-property :path link)))))
18786 (when (file-exists-p file)
18787 (let ((width
18788 ;; Apply `org-image-actual-width' specifications.
18789 (cond
18790 ((not (image-type-available-p 'imagemagick)) nil)
18791 ((eq org-image-actual-width t) nil)
18792 ((listp org-image-actual-width)
18794 ;; First try to find a width among
18795 ;; attributes associated to the paragraph
18796 ;; containing link.
18797 (let ((paragraph
18798 (let ((e link))
18799 (while (and (setq e (org-element-property
18800 :parent e))
18801 (not (eq (org-element-type e)
18802 'paragraph))))
18803 e)))
18804 (when paragraph
18805 (save-excursion
18806 (goto-char (org-element-property :begin paragraph))
18807 (when
18808 (re-search-forward
18809 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18810 (org-element-property
18811 :post-affiliated paragraph)
18813 (string-to-number (match-string 1))))))
18814 ;; Otherwise, fall-back to provided number.
18815 (car org-image-actual-width)))
18816 ((numberp org-image-actual-width)
18817 org-image-actual-width)))
18818 (old (get-char-property-and-overlay
18819 (org-element-property :begin link)
18820 'org-image-overlay)))
18821 (if (and (car-safe old) refresh)
18822 (image-refresh (overlay-get (cdr old) 'display))
18823 (let ((image (create-image file
18824 (and width 'imagemagick)
18826 :width width)))
18827 (when image
18828 (let ((ov (make-overlay
18829 (org-element-property :begin link)
18830 (progn
18831 (goto-char
18832 (org-element-property :end link))
18833 (skip-chars-backward " \t")
18834 (point)))))
18835 (overlay-put ov 'display image)
18836 (overlay-put ov 'face 'default)
18837 (overlay-put ov 'org-image-overlay t)
18838 (overlay-put
18839 ov 'modification-hooks
18840 (list 'org-display-inline-remove-overlay))
18841 (push ov org-inline-image-overlays)))))))))))))))
18843 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18844 "Remove inline-display overlay if a corresponding region is modified."
18845 (let ((inhibit-modification-hooks t))
18846 (when (and ov after)
18847 (delete ov org-inline-image-overlays)
18848 (delete-overlay ov))))
18850 (defun org-remove-inline-images ()
18851 "Remove inline display of images."
18852 (interactive)
18853 (mapc #'delete-overlay org-inline-image-overlays)
18854 (setq org-inline-image-overlays nil))
18857 ;;; Key bindings
18859 (defun org-remap (map &rest commands)
18860 "In MAP, remap the functions given in COMMANDS.
18861 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18862 (let (new old)
18863 (while commands
18864 (setq old (pop commands) new (pop commands))
18865 (org-defkey map (vector 'remap old) new))))
18867 ;;;; Outline functions that can be remapped in Org
18868 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18869 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18870 (define-key org-mode-map [remap outline-forward-same-level]
18871 #'org-forward-heading-same-level)
18872 (define-key org-mode-map [remap outline-backward-same-level]
18873 #'org-backward-heading-same-level)
18874 (define-key org-mode-map [remap outline-show-branches]
18875 #'org-kill-note-or-show-branches)
18876 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18877 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18878 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18879 (define-key org-mode-map [remap outline-next-visible-heading]
18880 #'org-next-visible-heading)
18881 (define-key org-mode-map [remap outline-previous-visible-heading]
18882 #'org-previous-visible-heading)
18883 (define-key org-mode-map [remap show-children] #'org-show-children)
18885 ;;;; Make `C-c C-x' a prefix key
18886 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18888 ;;;; TAB key with modifiers
18889 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18890 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18891 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18892 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18893 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18895 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18896 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18897 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18899 ;;;; RET key with modifiers
18900 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18901 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18902 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18903 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18904 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18906 ;;;; Cursor keys with modifiers
18907 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18908 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18909 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18910 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18911 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18912 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18913 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18915 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18916 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18917 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18918 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18919 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18920 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18921 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18922 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18923 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18924 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18926 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18927 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18928 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18929 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18931 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18932 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18933 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18934 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18936 ;;;; Babel keys
18937 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18938 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18939 (define-key org-babel-map key def))
18941 ;;;; Extra keys for TTY access.
18943 ;; We only set them when really needed because otherwise the
18944 ;; menus don't show the simple keys
18946 (when (or org-use-extra-keys (not window-system))
18947 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18948 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18949 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18950 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18951 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18952 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18953 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18954 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18955 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18956 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18957 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18958 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18959 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18960 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18961 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18962 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18963 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18964 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18965 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18966 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18967 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18969 ;;;; Narrow map
18970 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18971 (org-defkey narrow-map "b" #'org-narrow-to-block)
18972 (org-defkey narrow-map "e" #'org-narrow-to-element)
18974 ;;;; Remap usual Emacs bindings
18975 (org-remap org-mode-map
18976 'self-insert-command 'org-self-insert-command
18977 'delete-char 'org-delete-char
18978 'delete-backward-char 'org-delete-backward-char
18979 'kill-line 'org-kill-line
18980 'open-line 'org-open-line
18981 'yank 'org-yank
18982 'comment-dwim 'org-comment-dwim
18983 'move-beginning-of-line 'org-beginning-of-line
18984 'move-end-of-line 'org-end-of-line
18985 'forward-paragraph 'org-forward-paragraph
18986 'backward-paragraph 'org-backward-paragraph
18987 'backward-sentence 'org-backward-sentence
18988 'forward-sentence 'org-forward-sentence
18989 'fill-paragraph 'org-fill-paragraph
18990 'delete-indentation 'org-delete-indentation
18991 'transpose-words 'org-transpose-words)
18993 ;;;; All the other keys
18994 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18995 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18996 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18997 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18998 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18999 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
19000 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
19001 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
19002 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
19003 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
19004 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
19005 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
19006 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
19007 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
19008 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
19009 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
19010 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
19011 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
19012 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
19013 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
19014 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
19015 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
19016 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
19017 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
19018 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
19019 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
19020 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
19021 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
19022 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
19023 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
19024 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
19025 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
19026 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
19027 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
19028 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
19029 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
19030 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
19031 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
19032 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
19033 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
19034 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
19035 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
19036 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19037 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19038 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19039 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19040 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19041 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19042 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19043 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19044 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19045 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19046 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19047 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19048 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19049 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19050 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19051 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19052 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19053 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19054 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19055 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19056 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19057 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19058 (org-defkey org-mode-map (kbd "RET") #'org-return)
19059 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19060 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19061 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19062 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19063 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19064 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19065 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19066 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19067 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19068 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19069 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19070 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19071 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19072 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19073 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19074 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19075 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19076 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19077 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19078 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19079 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19080 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19081 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19082 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19083 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19084 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19085 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19086 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19087 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19088 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19089 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19090 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19091 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19092 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19093 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19094 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19095 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19096 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19097 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19098 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19099 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19100 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19101 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19102 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19103 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19104 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19105 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19106 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19107 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19108 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19109 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19110 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19111 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19112 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19113 (org-defkey org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19114 (org-defkey org-mode-map (kbd "C-c C-x !") #'org-reload)
19115 (org-defkey org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19116 (org-defkey org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19117 (org-defkey org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19118 (org-defkey org-mode-map (kbd "C-c C-x I") #'org-info-find-node)
19121 ;;; Speed commands
19123 (defconst org-speed-commands-default
19125 ("Outline Navigation")
19126 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19127 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19128 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19129 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19130 ("F" . org-next-block)
19131 ("B" . org-previous-block)
19132 ("u" . (org-speed-move-safe 'outline-up-heading))
19133 ("j" . org-goto)
19134 ("g" . (org-refile t))
19135 ("Outline Visibility")
19136 ("c" . org-cycle)
19137 ("C" . org-shifttab)
19138 (" " . org-display-outline-path)
19139 ("s" . org-toggle-narrow-to-subtree)
19140 ("k" . org-cut-subtree)
19141 ("=" . org-columns)
19142 ("Outline Structure Editing")
19143 ("U" . org-metaup)
19144 ("D" . org-metadown)
19145 ("r" . org-metaright)
19146 ("l" . org-metaleft)
19147 ("R" . org-shiftmetaright)
19148 ("L" . org-shiftmetaleft)
19149 ("i" . (progn (forward-char 1) (call-interactively
19150 'org-insert-heading-respect-content)))
19151 ("^" . org-sort)
19152 ("w" . org-refile)
19153 ("a" . org-archive-subtree-default-with-confirmation)
19154 ("@" . org-mark-subtree)
19155 ("#" . org-toggle-comment)
19156 ("Clock Commands")
19157 ("I" . org-clock-in)
19158 ("O" . org-clock-out)
19159 ("Meta Data Editing")
19160 ("t" . org-todo)
19161 ("," . (org-priority))
19162 ("0" . (org-priority ?\ ))
19163 ("1" . (org-priority ?A))
19164 ("2" . (org-priority ?B))
19165 ("3" . (org-priority ?C))
19166 (":" . org-set-tags-command)
19167 ("e" . org-set-effort)
19168 ("E" . org-inc-effort)
19169 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19170 (org-entry-put (point) "APPT_WARNTIME" m)))
19171 ("Agenda Views etc")
19172 ("v" . org-agenda)
19173 ("/" . org-sparse-tree)
19174 ("Misc")
19175 ("o" . org-open-at-point)
19176 ("?" . org-speed-command-help)
19177 ("<" . (org-agenda-set-restriction-lock 'subtree))
19178 (">" . (org-agenda-remove-restriction-lock))
19180 "The default speed commands.")
19182 (defun org-print-speed-command (e)
19183 (if (> (length (car e)) 1)
19184 (progn
19185 (princ "\n")
19186 (princ (car e))
19187 (princ "\n")
19188 (princ (make-string (length (car e)) ?-))
19189 (princ "\n"))
19190 (princ (car e))
19191 (princ " ")
19192 (if (symbolp (cdr e))
19193 (princ (symbol-name (cdr e)))
19194 (prin1 (cdr e)))
19195 (princ "\n")))
19197 (defun org-speed-command-help ()
19198 "Show the available speed commands."
19199 (interactive)
19200 (if (not org-use-speed-commands)
19201 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19202 (with-output-to-temp-buffer "*Help*"
19203 (princ "User-defined Speed commands\n===========================\n")
19204 (mapc #'org-print-speed-command org-speed-commands-user)
19205 (princ "\n")
19206 (princ "Built-in Speed commands\n=======================\n")
19207 (mapc #'org-print-speed-command org-speed-commands-default))
19208 (with-current-buffer "*Help*"
19209 (setq truncate-lines t))))
19211 (defun org-speed-move-safe (cmd)
19212 "Execute CMD, but make sure that the cursor always ends up in a headline.
19213 If not, return to the original position and throw an error."
19214 (interactive)
19215 (let ((pos (point)))
19216 (call-interactively cmd)
19217 (unless (and (bolp) (org-at-heading-p))
19218 (goto-char pos)
19219 (error "Boundary reached while executing %s" cmd))))
19221 (defvar org-self-insert-command-undo-counter 0)
19223 (defvar org-table-auto-blank-field) ; defined in org-table.el
19224 (defvar org-speed-command nil)
19226 (defun org-speed-command-activate (keys)
19227 "Hook for activating single-letter speed commands.
19228 `org-speed-commands-default' specifies a minimal command set.
19229 Use `org-speed-commands-user' for further customization."
19230 (when (or (and (bolp) (looking-at org-outline-regexp))
19231 (and (functionp org-use-speed-commands)
19232 (funcall org-use-speed-commands)))
19233 (cdr (assoc keys (append org-speed-commands-user
19234 org-speed-commands-default)))))
19236 (defun org-babel-speed-command-activate (keys)
19237 "Hook for activating single-letter code block commands."
19238 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19239 (cdr (assoc keys org-babel-key-bindings))))
19241 (defcustom org-speed-command-hook
19242 '(org-speed-command-activate org-babel-speed-command-activate)
19243 "Hook for activating speed commands at strategic locations.
19244 Hook functions are called in sequence until a valid handler is
19245 found.
19247 Each hook takes a single argument, a user-pressed command key
19248 which is also a `self-insert-command' from the global map.
19250 Within the hook, examine the cursor position and the command key
19251 and return nil or a valid handler as appropriate. Handler could
19252 be one of an interactive command, a function, or a form.
19254 Set `org-use-speed-commands' to non-nil value to enable this
19255 hook. The default setting is `org-speed-command-activate'."
19256 :group 'org-structure
19257 :version "24.1"
19258 :type 'hook)
19260 (defun org-self-insert-command (N)
19261 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19262 If the cursor is in a table looking at whitespace, the whitespace is
19263 overwritten, and the table is not marked as requiring realignment."
19264 (interactive "p")
19265 (org-check-before-invisible-edit 'insert)
19266 (cond
19267 ((and org-use-speed-commands
19268 (let ((kv (this-command-keys-vector)))
19269 (setq org-speed-command
19270 (run-hook-with-args-until-success
19271 'org-speed-command-hook
19272 (make-string 1 (aref kv (1- (length kv))))))))
19273 (cond
19274 ((commandp org-speed-command)
19275 (setq this-command org-speed-command)
19276 (call-interactively org-speed-command))
19277 ((functionp org-speed-command)
19278 (funcall org-speed-command))
19279 ((and org-speed-command (listp org-speed-command))
19280 (eval org-speed-command))
19281 (t (let (org-use-speed-commands)
19282 (call-interactively 'org-self-insert-command)))))
19283 ((and
19284 (= N 1)
19285 (not (org-region-active-p))
19286 (org-at-table-p)
19287 (progn
19288 ;; Check if we blank the field, and if that triggers align.
19289 (and (featurep 'org-table)
19290 org-table-auto-blank-field
19291 (memq last-command
19292 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19293 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19294 ;; Got extra space, this field does not determine
19295 ;; column width.
19296 (let (org-table-may-need-update) (org-table-blank-field))
19297 ;; No extra space, this field may determine column
19298 ;; width.
19299 (org-table-blank-field)))
19301 (looking-at "[^|\n]* |"))
19302 ;; There is room for insertion without re-aligning the table.
19303 (self-insert-command N)
19304 (org-table-with-shrunk-field
19305 (save-excursion
19306 (skip-chars-forward "^|")
19307 ;; Do not delete last space, which is
19308 ;; `org-table-separator-space', but the regular space before
19309 ;; it.
19310 (delete-region (- (point) 2) (1- (point))))))
19312 (setq org-table-may-need-update t)
19313 (self-insert-command N)
19314 (org-fix-tags-on-the-fly)
19315 (when org-self-insert-cluster-for-undo
19316 (if (not (eq last-command 'org-self-insert-command))
19317 (setq org-self-insert-command-undo-counter 1)
19318 (if (>= org-self-insert-command-undo-counter 20)
19319 (setq org-self-insert-command-undo-counter 1)
19320 (and (> org-self-insert-command-undo-counter 0)
19321 buffer-undo-list (listp buffer-undo-list)
19322 (not (cadr buffer-undo-list)) ; remove nil entry
19323 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19324 (setq org-self-insert-command-undo-counter
19325 (1+ org-self-insert-command-undo-counter))))))))
19327 (defun org-check-before-invisible-edit (kind)
19328 "Check is editing if kind KIND would be dangerous with invisible text around.
19329 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19330 ;; First, try to get out of here as quickly as possible, to reduce overhead
19331 (when (and org-catch-invisible-edits
19332 (or (not (boundp 'visible-mode)) (not visible-mode))
19333 (or (get-char-property (point) 'invisible)
19334 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19335 ;; OK, we need to take a closer look. Do not consider
19336 ;; invisibility obtained through text properties (e.g., link
19337 ;; fontification), as it cannot be toggled.
19338 (let* ((invisible-at-point
19339 (pcase (get-char-property-and-overlay (point) 'invisible)
19340 (`(,_ . ,(and (pred overlayp) o)) o)))
19341 ;; Assume that point cannot land in the middle of an
19342 ;; overlay, or between two overlays.
19343 (invisible-before-point
19344 (and (not invisible-at-point)
19345 (not (bobp))
19346 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19347 (`(,_ . ,(and (pred overlayp) o)) o))))
19348 (border-and-ok-direction
19350 ;; Check if we are acting predictably before invisible
19351 ;; text.
19352 (and invisible-at-point
19353 (memq kind '(insert delete-backward)))
19354 ;; Check if we are acting predictably after invisible text
19355 ;; This works not well, and I have turned it off. It seems
19356 ;; better to always show and stop after invisible text.
19357 ;; (and (not invisible-at-point) invisible-before-point
19358 ;; (memq kind '(insert delete)))
19360 (when (or invisible-at-point invisible-before-point)
19361 (when (eq org-catch-invisible-edits 'error)
19362 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19363 (if (and org-custom-properties-overlays
19364 (y-or-n-p "Display invisible properties in this buffer? "))
19365 (org-toggle-custom-properties-visibility)
19366 ;; Make the area visible
19367 (save-excursion
19368 (when invisible-before-point
19369 (goto-char
19370 (previous-single-char-property-change (point) 'invisible)))
19371 ;; Remove whatever overlay is currently making yet-to-be
19372 ;; edited text invisible. Also remove nested invisibility
19373 ;; related overlays.
19374 (delete-overlay (or invisible-at-point invisible-before-point))
19375 (let ((origin (if invisible-at-point (point) (1- (point)))))
19376 (while (pcase (get-char-property-and-overlay origin 'invisible)
19377 (`(,_ . ,(and (pred overlayp) o))
19378 (delete-overlay o)
19379 t)))))
19380 (cond
19381 ((eq org-catch-invisible-edits 'show)
19382 ;; That's it, we do the edit after showing
19383 (message
19384 "Unfolding invisible region around point before editing")
19385 (sit-for 1))
19386 ((and (eq org-catch-invisible-edits 'smart)
19387 border-and-ok-direction)
19388 (message "Unfolding invisible region around point before editing"))
19390 ;; Don't do the edit, make the user repeat it in full visibility
19391 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19393 (defun org-fix-tags-on-the-fly ()
19394 "Align tags in headline at point.
19395 Unlike `org-align-tags', this function does nothing if point is
19396 either not currently on a tagged headline or on a tag."
19397 (when (and (org-match-line org-tag-line-re)
19398 (< (point) (match-beginning 1)))
19399 (org-align-tags)))
19401 (defun org-delete-backward-char (N)
19402 "Like `delete-backward-char', insert whitespace at field end in tables.
19403 When deleting backwards, in tables this function will insert whitespace in
19404 front of the next \"|\" separator, to keep the table aligned. The table will
19405 still be marked for re-alignment if the field did fill the entire column,
19406 because, in this case the deletion might narrow the column."
19407 (interactive "p")
19408 (save-match-data
19409 (org-check-before-invisible-edit 'delete-backward)
19410 (if (and (= N 1)
19411 (not overwrite-mode)
19412 (not (org-region-active-p))
19413 (not (eq (char-before) ?|))
19414 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19415 (looking-at-p ".*?|")
19416 (org-at-table-p))
19417 (progn (forward-char -1) (org-delete-char 1))
19418 (backward-delete-char N)
19419 (org-fix-tags-on-the-fly))))
19421 (defun org-delete-char (N)
19422 "Like `delete-char', but insert whitespace at field end in tables.
19423 When deleting characters, in tables this function will insert whitespace in
19424 front of the next \"|\" separator, to keep the table aligned. The table will
19425 still be marked for re-alignment if the field did fill the entire column,
19426 because, in this case the deletion might narrow the column."
19427 (interactive "p")
19428 (save-match-data
19429 (org-check-before-invisible-edit 'delete)
19430 (cond
19431 ((or (/= N 1)
19432 (eq (char-after) ?|)
19433 (save-excursion (skip-chars-backward " \t") (bolp))
19434 (not (org-at-table-p)))
19435 (delete-char N)
19436 (org-fix-tags-on-the-fly))
19437 ((looking-at ".\\(.*?\\)|")
19438 (let* ((update? org-table-may-need-update)
19439 (noalign (looking-at-p ".*? |")))
19440 (delete-char 1)
19441 (org-table-with-shrunk-field
19442 (save-excursion
19443 ;; Last space is `org-table-separator-space', so insert
19444 ;; a regular one before it instead.
19445 (goto-char (- (match-end 0) 2))
19446 (insert " ")))
19447 ;; If there were two spaces at the end, this field does not
19448 ;; determine the width of the column.
19449 (when noalign (setq org-table-may-need-update update?))))
19451 (delete-char N)))))
19453 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19454 (put 'org-self-insert-command 'delete-selection
19455 (lambda ()
19456 (not (run-hook-with-args-until-success
19457 'self-insert-uses-region-functions))))
19458 (put 'orgtbl-self-insert-command 'delete-selection
19459 (lambda ()
19460 (not (run-hook-with-args-until-success
19461 'self-insert-uses-region-functions))))
19462 (put 'org-delete-char 'delete-selection 'supersede)
19463 (put 'org-delete-backward-char 'delete-selection 'supersede)
19464 (put 'org-yank 'delete-selection 'yank)
19466 ;; Make `flyspell-mode' delay after some commands
19467 (put 'org-self-insert-command 'flyspell-delayed t)
19468 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19469 (put 'org-delete-char 'flyspell-delayed t)
19470 (put 'org-delete-backward-char 'flyspell-delayed t)
19472 ;; Make pabbrev-mode expand after Org mode commands
19473 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19474 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19476 (defun org-transpose-words ()
19477 "Transpose words for Org.
19478 This uses the `org-mode-transpose-word-syntax-table' syntax
19479 table, which interprets characters in `org-emphasis-alist' as
19480 word constituents."
19481 (interactive)
19482 (with-syntax-table org-mode-transpose-word-syntax-table
19483 (call-interactively 'transpose-words)))
19485 (defvar org-ctrl-c-ctrl-c-hook nil
19486 "Hook for functions attaching themselves to `C-c C-c'.
19488 This can be used to add additional functionality to the C-c C-c
19489 key which executes context-dependent commands. This hook is run
19490 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19491 run after the last test.
19493 Each function will be called with no arguments. The function
19494 must check if the context is appropriate for it to act. If yes,
19495 it should do its thing and then return a non-nil value. If the
19496 context is wrong, just do nothing and return nil.")
19498 (defvar org-ctrl-c-ctrl-c-final-hook nil
19499 "Hook for functions attaching themselves to `C-c C-c'.
19501 This can be used to add additional functionality to the C-c C-c
19502 key which executes context-dependent commands. This hook is run
19503 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19504 before the first test.
19506 Each function will be called with no arguments. The function
19507 must check if the context is appropriate for it to act. If yes,
19508 it should do its thing and then return a non-nil value. If the
19509 context is wrong, just do nothing and return nil.")
19511 (defvar org-tab-first-hook nil
19512 "Hook for functions to attach themselves to TAB.
19513 See `org-ctrl-c-ctrl-c-hook' for more information.
19514 This hook runs as the first action when TAB is pressed, even before
19515 `org-cycle' messes around with the `outline-regexp' to cater for
19516 inline tasks and plain list item folding.
19517 If any function in this hook returns t, any other actions that
19518 would have been caused by TAB (such as table field motion or visibility
19519 cycling) will not occur.")
19521 (defvar org-tab-after-check-for-table-hook nil
19522 "Hook for functions to attach themselves to TAB.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.
19524 This hook runs after it has been established that the cursor is not in a
19525 table, but before checking if the cursor is in a headline or if global cycling
19526 should be done.
19527 If any function in this hook returns t, not other actions like visibility
19528 cycling will be done.")
19530 (defvar org-tab-after-check-for-cycling-hook nil
19531 "Hook for functions to attach themselves to TAB.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.
19533 This hook runs after it has been established that not table field motion and
19534 not visibility should be done because of current context. This is probably
19535 the place where a package like yasnippets can hook in.")
19537 (defvar org-tab-before-tab-emulation-hook nil
19538 "Hook for functions to attach themselves to TAB.
19539 See `org-ctrl-c-ctrl-c-hook' for more information.
19540 This hook runs after every other options for TAB have been exhausted, but
19541 before indentation and \t insertion takes place.")
19543 (defvar org-metaleft-hook nil
19544 "Hook for functions attaching themselves to `M-left'.
19545 See `org-ctrl-c-ctrl-c-hook' for more information.")
19546 (defvar org-metaright-hook nil
19547 "Hook for functions attaching themselves to `M-right'.
19548 See `org-ctrl-c-ctrl-c-hook' for more information.")
19549 (defvar org-metaup-hook nil
19550 "Hook for functions attaching themselves to `M-up'.
19551 See `org-ctrl-c-ctrl-c-hook' for more information.")
19552 (defvar org-metadown-hook nil
19553 "Hook for functions attaching themselves to `M-down'.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defvar org-shiftmetaleft-hook nil
19556 "Hook for functions attaching themselves to `M-S-left'.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19558 (defvar org-shiftmetaright-hook nil
19559 "Hook for functions attaching themselves to `M-S-right'.
19560 See `org-ctrl-c-ctrl-c-hook' for more information.")
19561 (defvar org-shiftmetaup-hook nil
19562 "Hook for functions attaching themselves to `M-S-up'.
19563 See `org-ctrl-c-ctrl-c-hook' for more information.")
19564 (defvar org-shiftmetadown-hook nil
19565 "Hook for functions attaching themselves to `M-S-down'.
19566 See `org-ctrl-c-ctrl-c-hook' for more information.")
19567 (defvar org-metareturn-hook nil
19568 "Hook for functions attaching themselves to `M-RET'.
19569 See `org-ctrl-c-ctrl-c-hook' for more information.")
19570 (defvar org-shiftup-hook nil
19571 "Hook for functions attaching themselves to `S-up'.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.")
19573 (defvar org-shiftup-final-hook nil
19574 "Hook for functions attaching themselves to `S-up'.
19575 This one runs after all other options except shift-select have been excluded.
19576 See `org-ctrl-c-ctrl-c-hook' for more information.")
19577 (defvar org-shiftdown-hook nil
19578 "Hook for functions attaching themselves to `S-down'.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.")
19580 (defvar org-shiftdown-final-hook nil
19581 "Hook for functions attaching themselves to `S-down'.
19582 This one runs after all other options except shift-select have been excluded.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.")
19584 (defvar org-shiftleft-hook nil
19585 "Hook for functions attaching themselves to `S-left'.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.")
19587 (defvar org-shiftleft-final-hook nil
19588 "Hook for functions attaching themselves to `S-left'.
19589 This one runs after all other options except shift-select have been excluded.
19590 See `org-ctrl-c-ctrl-c-hook' for more information.")
19591 (defvar org-shiftright-hook nil
19592 "Hook for functions attaching themselves to `S-right'.
19593 See `org-ctrl-c-ctrl-c-hook' for more information.")
19594 (defvar org-shiftright-final-hook nil
19595 "Hook for functions attaching themselves to `S-right'.
19596 This one runs after all other options except shift-select have been excluded.
19597 See `org-ctrl-c-ctrl-c-hook' for more information.")
19599 (defun org-modifier-cursor-error ()
19600 "Throw an error, a modified cursor command was applied in wrong context."
19601 (user-error "This command is active in special context like tables, headlines or items"))
19603 (defun org-shiftselect-error ()
19604 "Throw an error because Shift-Cursor command was applied in wrong context."
19605 (if (and (boundp 'shift-select-mode) shift-select-mode)
19606 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19607 (user-error "This command works only in special context like headlines or timestamps")))
19609 (defun org-call-for-shift-select (cmd)
19610 (let ((this-command-keys-shift-translated t))
19611 (call-interactively cmd)))
19613 (defun org-shifttab (&optional arg)
19614 "Global visibility cycling or move to previous table field.
19615 Call `org-table-previous-field' within a table.
19616 When ARG is nil, cycle globally through visibility states.
19617 When ARG is a numeric prefix, show contents of this level."
19618 (interactive "P")
19619 (cond
19620 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19621 ((integerp arg)
19622 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19623 (message "Content view to level: %d" arg)
19624 (org-content (prefix-numeric-value arg2))
19625 (org-cycle-show-empty-lines t)
19626 (setq org-cycle-global-status 'overview)))
19627 (t (call-interactively 'org-global-cycle))))
19629 (defun org-shiftmetaleft ()
19630 "Promote subtree or delete table column.
19631 Calls `org-promote-subtree', `org-outdent-item-tree', or
19632 `org-table-delete-column', depending on context. See the
19633 individual commands for more information."
19634 (interactive)
19635 (cond
19636 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19637 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19638 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19639 ((if (not (org-region-active-p)) (org-at-item-p)
19640 (save-excursion (goto-char (region-beginning))
19641 (org-at-item-p)))
19642 (call-interactively 'org-outdent-item-tree))
19643 (t (org-modifier-cursor-error))))
19645 (defun org-shiftmetaright ()
19646 "Demote subtree or insert table column.
19647 Calls `org-demote-subtree', `org-indent-item-tree', or
19648 `org-table-insert-column', depending on context. See the
19649 individual commands for more information."
19650 (interactive)
19651 (cond
19652 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19653 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19654 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19655 ((if (not (org-region-active-p)) (org-at-item-p)
19656 (save-excursion (goto-char (region-beginning))
19657 (org-at-item-p)))
19658 (call-interactively 'org-indent-item-tree))
19659 (t (org-modifier-cursor-error))))
19661 (defun org-shiftmetaup (&optional _arg)
19662 "Drag the line at point up.
19663 In a table, kill the current row.
19664 On a clock timestamp, update the value of the timestamp like `S-<up>'
19665 but also adjust the previous clocked item in the clock history.
19666 Everywhere else, drag the line at point up."
19667 (interactive "P")
19668 (cond
19669 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19670 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19671 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19672 (call-interactively 'org-timestamp-up)))
19673 (t (call-interactively 'org-drag-line-backward))))
19675 (defun org-shiftmetadown (&optional _arg)
19676 "Drag the line at point down.
19677 In a table, insert an empty row at the current line.
19678 On a clock timestamp, update the value of the timestamp like `S-<down>'
19679 but also adjust the previous clocked item in the clock history.
19680 Everywhere else, drag the line at point down."
19681 (interactive "P")
19682 (cond
19683 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19684 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19685 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19686 (call-interactively 'org-timestamp-down)))
19687 (t (call-interactively 'org-drag-line-forward))))
19689 (defsubst org-hidden-tree-error ()
19690 (user-error
19691 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19693 (defun org-metaleft (&optional _arg)
19694 "Promote heading, list item at point or move table column left.
19696 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19697 depending on context. With no specific context, calls the Emacs
19698 default `backward-word'. See the individual commands for more
19699 information.
19701 This function runs the hook `org-metaleft-hook' as a first step,
19702 and returns at first non-nil value."
19703 (interactive "P")
19704 (cond
19705 ((run-hook-with-args-until-success 'org-metaleft-hook))
19706 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19707 ((org-with-limited-levels
19708 (or (org-at-heading-p)
19709 (and (org-region-active-p)
19710 (save-excursion
19711 (goto-char (region-beginning))
19712 (org-at-heading-p)))))
19713 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19714 (call-interactively 'org-do-promote))
19715 ;; At an inline task.
19716 ((org-at-heading-p)
19717 (call-interactively 'org-inlinetask-promote))
19718 ((or (org-at-item-p)
19719 (and (org-region-active-p)
19720 (save-excursion
19721 (goto-char (region-beginning))
19722 (org-at-item-p))))
19723 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19724 (call-interactively 'org-outdent-item))
19725 (t (call-interactively 'backward-word))))
19727 (defun org-metaright (&optional _arg)
19728 "Demote heading, list item at point or move table column right.
19730 In front of a drawer or a block keyword, indent it correctly.
19732 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19733 `org-indent-drawer' or `org-indent-block' depending on context.
19734 With no specific context, calls the Emacs default `forward-word'.
19735 See the individual commands for more information.
19737 This function runs the hook `org-metaright-hook' as a first step,
19738 and returns at first non-nil value."
19739 (interactive "P")
19740 (cond
19741 ((run-hook-with-args-until-success 'org-metaright-hook))
19742 ((org-at-table-p) (call-interactively 'org-table-move-column))
19743 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19744 ((org-at-block-p) (call-interactively 'org-indent-block))
19745 ((org-with-limited-levels
19746 (or (org-at-heading-p)
19747 (and (org-region-active-p)
19748 (save-excursion
19749 (goto-char (region-beginning))
19750 (org-at-heading-p)))))
19751 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19752 (call-interactively 'org-do-demote))
19753 ;; At an inline task.
19754 ((org-at-heading-p)
19755 (call-interactively 'org-inlinetask-demote))
19756 ((or (org-at-item-p)
19757 (and (org-region-active-p)
19758 (save-excursion
19759 (goto-char (region-beginning))
19760 (org-at-item-p))))
19761 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19762 (call-interactively 'org-indent-item))
19763 (t (call-interactively 'forward-word))))
19765 (defun org-check-for-hidden (what)
19766 "Check if there are hidden headlines/items in the current visual line.
19767 WHAT can be either `headlines' or `items'. If the current line is
19768 an outline or item heading and it has a folded subtree below it,
19769 this function returns t, nil otherwise."
19770 (let ((re (cond
19771 ((eq what 'headlines) org-outline-regexp-bol)
19772 ((eq what 'items) (org-item-beginning-re))
19773 (t (error "This should not happen"))))
19774 beg end)
19775 (save-excursion
19776 (catch 'exit
19777 (unless (org-region-active-p)
19778 (setq beg (point-at-bol))
19779 (beginning-of-line 2)
19780 (while (and (not (eobp)) ;; this is like `next-line'
19781 (get-char-property (1- (point)) 'invisible))
19782 (beginning-of-line 2))
19783 (setq end (point))
19784 (goto-char beg)
19785 (goto-char (point-at-eol))
19786 (setq end (max end (point)))
19787 (while (re-search-forward re end t)
19788 (when (get-char-property (match-beginning 0) 'invisible)
19789 (throw 'exit t))))
19790 nil))))
19792 (defun org-metaup (&optional _arg)
19793 "Move subtree up or move table row up.
19794 Calls `org-move-subtree-up' or `org-table-move-row' or
19795 `org-move-item-up', depending on context. See the individual commands
19796 for more information."
19797 (interactive "P")
19798 (cond
19799 ((run-hook-with-args-until-success 'org-metaup-hook))
19800 ((org-region-active-p)
19801 (let* ((a (save-excursion
19802 (goto-char (min (region-beginning) (region-end)))
19803 (line-beginning-position)))
19804 (b (save-excursion
19805 (goto-char (max (region-beginning) (region-end)))
19806 (if (bolp) (1- (point)) (line-end-position))))
19807 (c (save-excursion
19808 (goto-char a)
19809 (move-beginning-of-line 0)
19810 (point)))
19811 (d (save-excursion
19812 (goto-char a)
19813 (move-end-of-line 0)
19814 (point))))
19815 (transpose-regions a b c d)
19816 (goto-char c)))
19817 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19818 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19819 ((org-at-item-p) (call-interactively 'org-move-item-up))
19820 (t (org-drag-element-backward))))
19822 (defun org-metadown (&optional _arg)
19823 "Move subtree down or move table row down.
19824 Calls `org-move-subtree-down' or `org-table-move-row' or
19825 `org-move-item-down', depending on context. See the individual
19826 commands for more information."
19827 (interactive "P")
19828 (cond
19829 ((run-hook-with-args-until-success 'org-metadown-hook))
19830 ((org-region-active-p)
19831 (let* ((a (save-excursion
19832 (goto-char (min (region-beginning) (region-end)))
19833 (line-beginning-position)))
19834 (b (save-excursion
19835 (goto-char (max (region-beginning) (region-end)))
19836 (if (bolp) (1- (point)) (line-end-position))))
19837 (c (save-excursion
19838 (goto-char b)
19839 (move-beginning-of-line (if (bolp) 1 2))
19840 (point)))
19841 (d (save-excursion
19842 (goto-char b)
19843 (move-end-of-line (if (bolp) 1 2))
19844 (point))))
19845 (transpose-regions a b c d)
19846 (goto-char d)))
19847 ((org-at-table-p) (call-interactively 'org-table-move-row))
19848 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19849 ((org-at-item-p) (call-interactively 'org-move-item-down))
19850 (t (org-drag-element-forward))))
19852 (defun org-shiftup (&optional arg)
19853 "Increase item in timestamp or increase priority of current headline.
19854 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19855 depending on context. See the individual commands for more information."
19856 (interactive "P")
19857 (cond
19858 ((run-hook-with-args-until-success 'org-shiftup-hook))
19859 ((and org-support-shift-select (org-region-active-p))
19860 (org-call-for-shift-select 'previous-line))
19861 ((org-at-timestamp-p 'lax)
19862 (call-interactively (if org-edit-timestamp-down-means-later
19863 'org-timestamp-down 'org-timestamp-up)))
19864 ((and (not (eq org-support-shift-select 'always))
19865 org-enable-priority-commands
19866 (org-at-heading-p))
19867 (call-interactively 'org-priority-up))
19868 ((and (not org-support-shift-select) (org-at-item-p))
19869 (call-interactively 'org-previous-item))
19870 ((org-clocktable-try-shift 'up arg))
19871 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19872 (org-support-shift-select
19873 (org-call-for-shift-select 'previous-line))
19874 (t (org-shiftselect-error))))
19876 (defun org-shiftdown (&optional arg)
19877 "Decrease item in timestamp or decrease priority of current headline.
19878 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19879 depending on context. See the individual commands for more information."
19880 (interactive "P")
19881 (cond
19882 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19883 ((and org-support-shift-select (org-region-active-p))
19884 (org-call-for-shift-select 'next-line))
19885 ((org-at-timestamp-p 'lax)
19886 (call-interactively (if org-edit-timestamp-down-means-later
19887 'org-timestamp-up 'org-timestamp-down)))
19888 ((and (not (eq org-support-shift-select 'always))
19889 org-enable-priority-commands
19890 (org-at-heading-p))
19891 (call-interactively 'org-priority-down))
19892 ((and (not org-support-shift-select) (org-at-item-p))
19893 (call-interactively 'org-next-item))
19894 ((org-clocktable-try-shift 'down arg))
19895 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19896 (org-support-shift-select
19897 (org-call-for-shift-select 'next-line))
19898 (t (org-shiftselect-error))))
19900 (defun org-shiftright (&optional arg)
19901 "Cycle the thing at point or in the current line, depending on context.
19902 Depending on context, this does one of the following:
19904 - switch a timestamp at point one day into the future
19905 - on a headline, switch to the next TODO keyword.
19906 - on an item, switch entire list to the next bullet type
19907 - on a property line, switch to the next allowed value
19908 - on a clocktable definition line, move time block into the future"
19909 (interactive "P")
19910 (cond
19911 ((run-hook-with-args-until-success 'org-shiftright-hook))
19912 ((and org-support-shift-select (org-region-active-p))
19913 (org-call-for-shift-select 'forward-char))
19914 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19915 ((and (not (eq org-support-shift-select 'always))
19916 (org-at-heading-p))
19917 (let ((org-inhibit-logging
19918 (not org-treat-S-cursor-todo-selection-as-state-change))
19919 (org-inhibit-blocking
19920 (not org-treat-S-cursor-todo-selection-as-state-change)))
19921 (org-call-with-arg 'org-todo 'right)))
19922 ((or (and org-support-shift-select
19923 (not (eq org-support-shift-select 'always))
19924 (org-at-item-bullet-p))
19925 (and (not org-support-shift-select) (org-at-item-p)))
19926 (org-call-with-arg 'org-cycle-list-bullet nil))
19927 ((and (not (eq org-support-shift-select 'always))
19928 (org-at-property-p))
19929 (call-interactively 'org-property-next-allowed-value))
19930 ((org-clocktable-try-shift 'right arg))
19931 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19932 (org-support-shift-select
19933 (org-call-for-shift-select 'forward-char))
19934 (t (org-shiftselect-error))))
19936 (defun org-shiftleft (&optional arg)
19937 "Cycle the thing at point or in the current line, depending on context.
19938 Depending on context, this does one of the following:
19940 - switch a timestamp at point one day into the past
19941 - on a headline, switch to the previous TODO keyword.
19942 - on an item, switch entire list to the previous bullet type
19943 - on a property line, switch to the previous allowed value
19944 - on a clocktable definition line, move time block into the past"
19945 (interactive "P")
19946 (cond
19947 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19948 ((and org-support-shift-select (org-region-active-p))
19949 (org-call-for-shift-select 'backward-char))
19950 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19951 ((and (not (eq org-support-shift-select 'always))
19952 (org-at-heading-p))
19953 (let ((org-inhibit-logging
19954 (not org-treat-S-cursor-todo-selection-as-state-change))
19955 (org-inhibit-blocking
19956 (not org-treat-S-cursor-todo-selection-as-state-change)))
19957 (org-call-with-arg 'org-todo 'left)))
19958 ((or (and org-support-shift-select
19959 (not (eq org-support-shift-select 'always))
19960 (org-at-item-bullet-p))
19961 (and (not org-support-shift-select) (org-at-item-p)))
19962 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19963 ((and (not (eq org-support-shift-select 'always))
19964 (org-at-property-p))
19965 (call-interactively 'org-property-previous-allowed-value))
19966 ((org-clocktable-try-shift 'left arg))
19967 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19968 (org-support-shift-select
19969 (org-call-for-shift-select 'backward-char))
19970 (t (org-shiftselect-error))))
19972 (defun org-shiftcontrolright ()
19973 "Switch to next TODO set."
19974 (interactive)
19975 (cond
19976 ((and org-support-shift-select (org-region-active-p))
19977 (org-call-for-shift-select 'forward-word))
19978 ((and (not (eq org-support-shift-select 'always))
19979 (org-at-heading-p))
19980 (org-call-with-arg 'org-todo 'nextset))
19981 (org-support-shift-select
19982 (org-call-for-shift-select 'forward-word))
19983 (t (org-shiftselect-error))))
19985 (defun org-shiftcontrolleft ()
19986 "Switch to previous TODO set."
19987 (interactive)
19988 (cond
19989 ((and org-support-shift-select (org-region-active-p))
19990 (org-call-for-shift-select 'backward-word))
19991 ((and (not (eq org-support-shift-select 'always))
19992 (org-at-heading-p))
19993 (org-call-with-arg 'org-todo 'previousset))
19994 (org-support-shift-select
19995 (org-call-for-shift-select 'backward-word))
19996 (t (org-shiftselect-error))))
19998 (defun org-shiftcontrolup (&optional n)
19999 "Change timestamps synchronously up in CLOCK log lines.
20000 Optional argument N tells to change by that many units."
20001 (interactive "P")
20002 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20003 (let (org-support-shift-select)
20004 (org-clock-timestamps-up n))
20005 (user-error "Not at a clock log")))
20007 (defun org-shiftcontroldown (&optional n)
20008 "Change timestamps synchronously down in CLOCK log lines.
20009 Optional argument N tells to change by that many units."
20010 (interactive "P")
20011 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20012 (let (org-support-shift-select)
20013 (org-clock-timestamps-down n))
20014 (user-error "Not at a clock log")))
20016 (defun org-increase-number-at-point (&optional inc)
20017 "Increment the number at point.
20018 With an optional prefix numeric argument INC, increment using
20019 this numeric value."
20020 (interactive "p")
20021 (if (not (number-at-point))
20022 (user-error "Not on a number")
20023 (unless inc (setq inc 1))
20024 (let ((pos (point))
20025 (beg (skip-chars-backward "-+^/*0-9eE."))
20026 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20027 (setq nap (buffer-substring-no-properties
20028 (+ pos beg) (+ pos beg end)))
20029 (delete-region (+ pos beg) (+ pos beg end))
20030 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20031 (when (org-at-table-p)
20032 (org-table-align)
20033 (org-table-end-of-field 1))))
20035 (defun org-decrease-number-at-point (&optional inc)
20036 "Decrement the number at point.
20037 With an optional prefix numeric argument INC, decrement using
20038 this numeric value."
20039 (interactive "p")
20040 (org-increase-number-at-point (- (or inc 1))))
20042 (defun org-ctrl-c-ret ()
20043 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20044 (interactive)
20045 (cond
20046 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20047 (t (call-interactively 'org-insert-heading))))
20049 (defun org-find-visible ()
20050 (let ((s (point)))
20051 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20052 (get-char-property s 'invisible)))
20054 (defun org-find-invisible ()
20055 (let ((s (point)))
20056 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20057 (not (get-char-property s 'invisible))))
20060 (defun org-copy-visible (beg end)
20061 "Copy the visible parts of the region."
20062 (interactive "r")
20063 (let ((result ""))
20064 (while (/= beg end)
20065 (when (get-char-property beg 'invisible)
20066 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20067 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20068 (setq result (concat result (buffer-substring beg next)))
20069 (setq beg next)))
20070 (setq deactivate-mark t)
20071 (kill-new result)
20072 (message "Visible strings have been copied to the kill ring.")))
20074 (defun org-copy-special ()
20075 "Copy region in table or copy current subtree.
20076 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20077 context. See the individual commands for more information."
20078 (interactive)
20079 (call-interactively
20080 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20082 (defun org-cut-special ()
20083 "Cut region in table or cut current subtree.
20084 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20085 context. See the individual commands for more information."
20086 (interactive)
20087 (call-interactively
20088 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20090 (defun org-paste-special (arg)
20091 "Paste rectangular region into table, or past subtree relative to level.
20092 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20093 See the individual commands for more information."
20094 (interactive "P")
20095 (if (org-at-table-p)
20096 (org-table-paste-rectangle)
20097 (org-paste-subtree arg)))
20099 (defun org-edit-special (&optional arg)
20100 "Call a special editor for the element at point.
20101 When at a table, call the formula editor with `org-table-edit-formulas'.
20102 When in a source code block, call `org-edit-src-code'.
20103 When in a fixed-width region, call `org-edit-fixed-width-region'.
20104 When in an export block, call `org-edit-export-block'.
20105 When in a LaTeX environment, call `org-edit-latex-environment'.
20106 When at an #+INCLUDE keyword, visit the included file.
20107 When at a footnote reference, call `org-edit-footnote-reference'.
20108 When at a planning line call, `org-deadline' and/or `org-schedule'.
20109 When at an active timestamp, call `org-time-stamp'.
20110 When at an inactive timestamp, call `org-time-stamp-inactive'.
20111 On a link, call `ffap' to visit the link at point.
20112 Otherwise, return a user error."
20113 (interactive "P")
20114 (let ((element (org-element-at-point)))
20115 (barf-if-buffer-read-only)
20116 (pcase (org-element-type element)
20117 (`src-block
20118 (if (not arg) (org-edit-src-code)
20119 (let* ((info (org-babel-get-src-block-info))
20120 (lang (nth 0 info))
20121 (params (nth 2 info))
20122 (session (cdr (assq :session params))))
20123 (if (not session) (org-edit-src-code)
20124 ;; At a src-block with a session and function called with
20125 ;; an ARG: switch to the buffer related to the inferior
20126 ;; process.
20127 (switch-to-buffer
20128 (funcall (intern (concat "org-babel-prep-session:" lang))
20129 session params))))))
20130 (`keyword
20131 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20132 (org-open-link-from-string
20133 (format "[[%s]]"
20134 (expand-file-name
20135 (let ((value (org-element-property :value element)))
20136 (cond ((org-file-url-p value)
20137 (user-error "The file is specified as a URL, cannot be edited"))
20138 ((not (org-string-nw-p value))
20139 (user-error "No file to edit"))
20140 ((string-match "\\`\"\\(.*?\\)\"" value)
20141 (match-string 1 value))
20142 ((string-match "\\`[^ \t\"]\\S-*" value)
20143 (match-string 0 value))
20144 (t (user-error "No valid file specified")))))))
20145 (user-error "No special environment to edit here")))
20146 (`table
20147 (if (eq (org-element-property :type element) 'table.el)
20148 (org-edit-table.el)
20149 (call-interactively 'org-table-edit-formulas)))
20150 ;; Only Org tables contain `table-row' type elements.
20151 (`table-row (call-interactively 'org-table-edit-formulas))
20152 (`example-block (org-edit-src-code))
20153 (`export-block (org-edit-export-block))
20154 (`fixed-width (org-edit-fixed-width-region))
20155 (`latex-environment (org-edit-latex-environment))
20156 (`planning
20157 (let ((proplist (cadr element)))
20158 (mapc #'call-interactively
20159 (remq nil
20160 (list
20161 (when (plist-get proplist :deadline) #'org-deadline)
20162 (when (plist-get proplist :scheduled) #'org-schedule))))))
20164 ;; No notable element at point. Though, we may be at a link or
20165 ;; a footnote reference, which are objects. Thus, scan deeper.
20166 (let ((context (org-element-context element)))
20167 (pcase (org-element-type context)
20168 (`footnote-reference (org-edit-footnote-reference))
20169 (`inline-src-block (org-edit-inline-src-code))
20170 (`timestamp (if (eq 'inactive (org-element-property :type context))
20171 (call-interactively #'org-time-stamp-inactive)
20172 (call-interactively #'org-time-stamp)))
20173 (`link (call-interactively #'ffap))
20174 (_ (user-error "No special environment to edit here"))))))))
20176 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20177 (defun org-ctrl-c-ctrl-c (&optional arg)
20178 "Set tags in headline, or update according to changed information at point.
20180 This command does many different things, depending on context:
20182 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20183 this is what we do.
20185 - If the cursor is on a statistics cookie, update it.
20187 - If the cursor is in a headline, prompt for tags and insert them
20188 into the current line, aligned to `org-tags-column'. When called
20189 with prefix arg, realign all tags in the current buffer.
20191 - If the cursor is in one of the special #+KEYWORD lines, this
20192 triggers scanning the buffer for these lines and updating the
20193 information.
20195 - If the cursor is inside a table, realign the table. This command
20196 works even if the automatic table editor has been turned off.
20198 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20199 the entire table.
20201 - If the cursor is at a footnote reference or definition, jump to
20202 the corresponding definition or references, respectively.
20204 - If the cursor is a the beginning of a dynamic block, update it.
20206 - If the current buffer is a capture buffer, close note and file it.
20208 - If the cursor is on a <<<target>>>, update radio targets and
20209 corresponding links in this buffer.
20211 - If the cursor is on a numbered item in a plain list, renumber the
20212 ordered list.
20214 - If the cursor is on a checkbox, toggle it.
20216 - If the cursor is on a code block, evaluate it. The variable
20217 `org-confirm-babel-evaluate' can be used to control prompting
20218 before code block evaluation, by default every code block
20219 evaluation requires confirmation. Code block evaluation can be
20220 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20221 (interactive "P")
20222 (cond
20223 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20224 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20225 (org-remove-occur-highlights)
20226 (message "Temporary highlights/overlays removed from current buffer"))
20227 ((and (local-variable-p 'org-finish-function)
20228 (fboundp org-finish-function))
20229 (funcall org-finish-function))
20230 ((org-babel-hash-at-point))
20231 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20233 (let* ((context
20234 (org-element-lineage
20235 (org-element-context)
20236 ;; Limit to supported contexts.
20237 '(babel-call clock dynamic-block footnote-definition
20238 footnote-reference inline-babel-call inline-src-block
20239 inlinetask item keyword node-property paragraph
20240 plain-list planning property-drawer radio-target
20241 src-block statistics-cookie table table-cell table-row
20242 timestamp)
20244 (type (org-element-type context)))
20245 ;; For convenience: at the first line of a paragraph on the same
20246 ;; line as an item, apply function on that item instead.
20247 (when (eq type 'paragraph)
20248 (let ((parent (org-element-property :parent context)))
20249 (when (and (eq (org-element-type parent) 'item)
20250 (= (line-beginning-position)
20251 (org-element-property :begin parent)))
20252 (setq context parent)
20253 (setq type 'item))))
20254 ;; Act according to type of element or object at point.
20256 ;; Do nothing on a blank line, except if it is contained in
20257 ;; a source block. Hence, we first check if point is in such
20258 ;; a block and then if it is at a blank line.
20259 (pcase type
20260 ((or `inline-src-block `src-block)
20261 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20262 (org-babel-eval-wipe-error-buffer)
20263 (org-babel-execute-src-block
20264 current-prefix-arg (org-babel-get-src-block-info nil context))))
20265 ((guard (org-match-line "[ \t]*$"))
20266 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20267 (user-error
20268 (substitute-command-keys
20269 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20270 ((or `babel-call `inline-babel-call)
20271 (let ((info (org-babel-lob-get-info context)))
20272 (when info (org-babel-execute-src-block nil info))))
20273 (`clock (org-clock-update-time-maybe))
20274 (`dynamic-block
20275 (save-excursion
20276 (goto-char (org-element-property :post-affiliated context))
20277 (org-update-dblock)))
20278 (`footnote-definition
20279 (goto-char (org-element-property :post-affiliated context))
20280 (call-interactively 'org-footnote-action))
20281 (`footnote-reference (call-interactively #'org-footnote-action))
20282 ((or `headline `inlinetask)
20283 (save-excursion (goto-char (org-element-property :begin context))
20284 (call-interactively #'org-set-tags-command)))
20285 (`item
20286 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20287 ;; unconditionally, whereas `C-u' will toggle its presence.
20288 ;; Without a universal argument, if the item has a checkbox,
20289 ;; toggle it. Otherwise repair the list.
20290 (let* ((box (org-element-property :checkbox context))
20291 (struct (org-element-property :structure context))
20292 (old-struct (copy-tree struct))
20293 (parents (org-list-parents-alist struct))
20294 (prevs (org-list-prevs-alist struct))
20295 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20296 (org-list-set-checkbox
20297 (org-element-property :begin context) struct
20298 (cond ((equal arg '(16)) "[-]")
20299 ((and (not box) (equal arg '(4))) "[ ]")
20300 ((or (not box) (equal arg '(4))) nil)
20301 ((eq box 'on) "[ ]")
20302 (t "[X]")))
20303 ;; Mimic `org-list-write-struct' but with grabbing a return
20304 ;; value from `org-list-struct-fix-box'.
20305 (org-list-struct-fix-ind struct parents 2)
20306 (org-list-struct-fix-item-end struct)
20307 (org-list-struct-fix-bul struct prevs)
20308 (org-list-struct-fix-ind struct parents)
20309 (let ((block-item
20310 (org-list-struct-fix-box struct parents prevs orderedp)))
20311 (if (and box (equal struct old-struct))
20312 (if (equal arg '(16))
20313 (message "Checkboxes already reset")
20314 (user-error "Cannot toggle this checkbox: %s"
20315 (if (eq box 'on)
20316 "all subitems checked"
20317 "unchecked subitems")))
20318 (org-list-struct-apply-struct struct old-struct)
20319 (org-update-checkbox-count-maybe))
20320 (when block-item
20321 (message "Checkboxes were removed due to empty box at line %d"
20322 (org-current-line block-item))))))
20323 (`keyword
20324 (let ((org-inhibit-startup-visibility-stuff t)
20325 (org-startup-align-all-tables nil))
20326 (when (boundp 'org-table-coordinate-overlays)
20327 (mapc #'delete-overlay org-table-coordinate-overlays)
20328 (setq org-table-coordinate-overlays nil))
20329 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20330 (message "Local setup has been refreshed"))
20331 (`plain-list
20332 ;; At a plain list, with a double C-u argument, set
20333 ;; checkboxes of each item to "[-]", whereas a single one
20334 ;; will toggle their presence according to the state of the
20335 ;; first item in the list. Without an argument, repair the
20336 ;; list.
20337 (let* ((begin (org-element-property :contents-begin context))
20338 (struct (org-element-property :structure context))
20339 (old-struct (copy-tree struct))
20340 (first-box (save-excursion
20341 (goto-char begin)
20342 (looking-at org-list-full-item-re)
20343 (match-string-no-properties 3)))
20344 (new-box (cond ((equal arg '(16)) "[-]")
20345 ((equal arg '(4)) (unless first-box "[ ]"))
20346 ((equal first-box "[X]") "[ ]")
20347 (t "[X]"))))
20348 (cond
20349 (arg
20350 (dolist (pos
20351 (org-list-get-all-items
20352 begin struct (org-list-prevs-alist struct)))
20353 (org-list-set-checkbox pos struct new-box)))
20354 ((and first-box (eq (point) begin))
20355 ;; For convenience, when point is at bol on the first
20356 ;; item of the list and no argument is provided, simply
20357 ;; toggle checkbox of that item, if any.
20358 (org-list-set-checkbox begin struct new-box)))
20359 (when (equal
20360 (org-list-write-struct
20361 struct (org-list-parents-alist struct) old-struct)
20362 old-struct)
20363 (message "Cannot update this checkbox"))
20364 (org-update-checkbox-count-maybe)))
20365 ((or `property-drawer `node-property)
20366 (call-interactively #'org-property-action))
20367 (`radio-target
20368 (call-interactively #'org-update-radio-target-regexp))
20369 (`statistics-cookie
20370 (call-interactively #'org-update-statistics-cookies))
20371 ((or `table `table-cell `table-row)
20372 ;; At a table, recalculate every field and align it. Also
20373 ;; send the table if necessary. If the table has
20374 ;; a `table.el' type, just give up. At a table row or cell,
20375 ;; maybe recalculate line but always align table.
20376 (if (eq (org-element-property :type context) 'table.el)
20377 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20378 Use `\\[org-edit-special]' to edit table.el tables"))
20379 (if (or (eq type 'table)
20380 ;; Check if point is at a TBLFM line.
20381 (and (eq type 'table-row)
20382 (= (point) (org-element-property :end context))))
20383 (save-excursion
20384 (if (org-at-TBLFM-p)
20385 (progn (require 'org-table)
20386 (org-table-calc-current-TBLFM))
20387 (goto-char (org-element-property :contents-begin context))
20388 (org-call-with-arg 'org-table-recalculate (or arg t))
20389 (orgtbl-send-table 'maybe)))
20390 (org-table-maybe-eval-formula)
20391 (cond (arg (call-interactively #'org-table-recalculate))
20392 ((org-table-maybe-recalculate-line))
20393 (t (org-table-align))))))
20394 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20395 (org-timestamp-change 0 'day))
20396 ((and `nil (guard (org-at-heading-p)))
20397 ;; When point is on an unsupported object type, we can miss
20398 ;; the fact that it also is at a heading. Handle it here.
20399 (call-interactively #'org-set-tags-command))
20400 ((guard
20401 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20403 (user-error
20404 (substitute-command-keys
20405 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20407 (defun org-mode-restart ()
20408 (interactive)
20409 (let ((indent-status (bound-and-true-p org-indent-mode)))
20410 (funcall major-mode)
20411 (hack-local-variables)
20412 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20413 (org-indent-mode -1))
20414 (org-reset-file-cache))
20415 (message "%s restarted" major-mode))
20417 (defun org-kill-note-or-show-branches ()
20418 "Abort storing current note, or call `outline-show-branches'."
20419 (interactive)
20420 (if (not org-finish-function)
20421 (save-excursion
20422 (save-restriction
20423 (org-narrow-to-subtree)
20424 (org-flag-subtree t)
20425 (call-interactively 'outline-show-branches)
20426 (org-hide-archived-subtrees (point-min) (point-max))))
20427 (let ((org-note-abort t))
20428 (funcall org-finish-function))))
20430 (defun org-delete-indentation (&optional arg)
20431 "Join current line to previous and fix whitespace at join.
20433 If previous line is a headline add to headline title. Otherwise
20434 the function calls `delete-indentation'.
20436 With a non-nil optional argument, join it to the following one."
20437 (interactive "*P")
20438 (if (save-excursion
20439 (beginning-of-line (if arg 1 0))
20440 (let ((case-fold-search nil))
20441 (looking-at org-complex-heading-regexp)))
20442 ;; At headline.
20443 (let ((tags-column (when (match-beginning 5)
20444 (save-excursion (goto-char (match-beginning 5))
20445 (current-column))))
20446 (string (concat " " (progn (when arg (forward-line 1))
20447 (org-trim (delete-and-extract-region
20448 (line-beginning-position)
20449 (line-end-position)))))))
20450 (unless (bobp) (delete-region (point) (1- (point))))
20451 (goto-char (or (match-end 4)
20452 (match-beginning 5)
20453 (match-end 0)))
20454 (skip-chars-backward " \t")
20455 (save-excursion (insert string))
20456 ;; Adjust alignment of tags.
20457 (cond
20458 ((not tags-column)) ;no tags
20459 (org-auto-align-tags (org-align-tags))
20460 (t (org--align-tags-here tags-column)))) ;preserve tags column
20461 (delete-indentation arg)))
20463 (defun org-open-line (n)
20464 "Insert a new row in tables, call `open-line' elsewhere.
20465 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20466 As a special case, when a document starts with a table, allow to
20467 call `open-line' on the very first character."
20468 (interactive "*p")
20469 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20470 (org-table-insert-row)
20471 (open-line n)))
20473 (defun org-return (&optional indent)
20474 "Goto next table row or insert a newline.
20476 Calls `org-table-next-row' or `newline', depending on context.
20478 When optional INDENT argument is non-nil, call
20479 `newline-and-indent' instead of `newline'.
20481 When `org-return-follows-link' is non-nil and point is on
20482 a timestamp or a link, call `org-open-at-point'. However, it
20483 will not happen if point is in a table or on a \"dead\"
20484 object (e.g., within a comment). In these case, you need to use
20485 `org-open-at-point' directly."
20486 (interactive)
20487 (let ((context (if org-return-follows-link (org-element-context)
20488 (org-element-at-point))))
20489 (cond
20490 ;; In a table, call `org-table-next-row'. However, before first
20491 ;; column or after last one, split the table.
20492 ((or (and (eq (org-element-type context) 'table)
20493 (>= (point) (org-element-property :contents-begin context))
20494 (< (point) (org-element-property :contents-end context)))
20495 (org-element-lineage context '(table-row table-cell) t))
20496 (if (or (looking-at-p "[ \t]*$")
20497 (save-excursion (skip-chars-backward " \t") (bolp)))
20498 (insert "\n")
20499 (org-table-justify-field-maybe)
20500 (call-interactively #'org-table-next-row)))
20501 ;; On a link or a timestamp, call `org-open-at-point' if
20502 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20503 ;; locations, e.g., in a comment, as `org-open-at-point'.
20504 ((and org-return-follows-link
20505 (or (and (eq 'link (org-element-type context))
20506 ;; Ensure point is not on the white spaces after
20507 ;; the link.
20508 (let ((origin (point)))
20509 (org-with-point-at (org-element-property :end context)
20510 (skip-chars-backward " \t")
20511 (> (point) origin))))
20512 (org-in-regexp org-ts-regexp-both nil t)
20513 (org-in-regexp org-tsr-regexp-both nil t)
20514 (org-in-regexp org-any-link-re nil t)))
20515 (call-interactively #'org-open-at-point))
20516 ;; Insert newline in heading, but preserve tags.
20517 ((and (not (bolp))
20518 (save-excursion (beginning-of-line)
20519 (let ((case-fold-search nil))
20520 (looking-at org-complex-heading-regexp))))
20521 ;; At headline. Split line. However, if point is on keyword,
20522 ;; priority cookie or tags, do not break any of them: add
20523 ;; a newline after the headline instead.
20524 (let ((tags-column (and (match-beginning 5)
20525 (save-excursion (goto-char (match-beginning 5))
20526 (current-column))))
20527 (string
20528 (when (and (match-end 4) (org-point-in-group (point) 4))
20529 (delete-and-extract-region (point) (match-end 4)))))
20530 ;; Adjust tag alignment.
20531 (cond
20532 ((not (and tags-column string)))
20533 (org-auto-align-tags (org-align-tags))
20534 (t (org--align-tags-here tags-column))) ;preserve tags column
20535 (end-of-line)
20536 (org-show-entry)
20537 (if indent (newline-and-indent) (newline))
20538 (when string (save-excursion (insert (org-trim string))))))
20539 ;; In a list, make sure indenting keeps trailing text within.
20540 ((and indent
20541 (not (eolp))
20542 (org-element-lineage context '(item)))
20543 (let ((trailing-data
20544 (delete-and-extract-region (point) (line-end-position))))
20545 (newline-and-indent)
20546 (save-excursion (insert trailing-data))))
20548 ;; Do not auto-fill when point is in an Org property drawer.
20549 (let ((auto-fill-function (and (not (org-at-property-p))
20550 auto-fill-function)))
20551 (if indent
20552 (newline-and-indent)
20553 (newline)))))))
20555 (defun org-return-indent ()
20556 "Goto next table row or insert a newline and indent.
20557 Calls `org-table-next-row' or `newline-and-indent', depending on
20558 context. See the individual commands for more information."
20559 (interactive)
20560 (org-return t))
20562 (defun org-ctrl-c-tab (&optional _arg)
20563 "Toggle columns width in a table, or show children.
20564 Call `org-table-toggle-column-width' if point is in a table.
20565 Otherwise, call `org-show-children'."
20566 (interactive "p")
20567 (call-interactively
20568 (if (org-at-table-p) #'org-table-toggle-column-width
20569 #'org-show-children)))
20571 (defun org-ctrl-c-star ()
20572 "Compute table, or change heading status of lines.
20573 Calls `org-table-recalculate' or `org-toggle-heading',
20574 depending on context."
20575 (interactive)
20576 (cond
20577 ((org-at-table-p)
20578 (call-interactively 'org-table-recalculate))
20580 ;; Convert all lines in region to list items
20581 (call-interactively 'org-toggle-heading))))
20583 (defun org-ctrl-c-minus ()
20584 "Insert separator line in table or modify bullet status of line.
20585 Also turns a plain line or a region of lines into list items.
20586 Calls `org-table-insert-hline', `org-toggle-item', or
20587 `org-cycle-list-bullet', depending on context."
20588 (interactive)
20589 (cond
20590 ((org-at-table-p)
20591 (call-interactively 'org-table-insert-hline))
20592 ((org-region-active-p)
20593 (call-interactively 'org-toggle-item))
20594 ((org-in-item-p)
20595 (call-interactively 'org-cycle-list-bullet))
20597 (call-interactively 'org-toggle-item))))
20599 (defun org-toggle-heading (&optional nstars)
20600 "Convert headings to normal text, or items or text to headings.
20601 If there is no active region, only convert the current line.
20603 With a `\\[universal-argument]' prefix, convert the whole list at
20604 point into heading.
20606 In a region:
20608 - If the first non blank line is a headline, remove the stars
20609 from all headlines in the region.
20611 - If it is a normal line, turn each and every normal line (i.e.,
20612 not an heading or an item) in the region into headings. If you
20613 want to convert only the first line of this region, use one
20614 universal prefix argument.
20616 - If it is a plain list item, turn all plain list items into headings.
20618 When converting a line into a heading, the number of stars is chosen
20619 such that the lines become children of the current entry. However,
20620 when a numeric prefix argument is given, its value determines the
20621 number of stars to add."
20622 (interactive "P")
20623 (let ((skip-blanks
20624 (function
20625 ;; Return beginning of first non-blank line, starting from
20626 ;; line at POS.
20627 (lambda (pos)
20628 (save-excursion
20629 (goto-char pos)
20630 (while (org-at-comment-p) (forward-line))
20631 (skip-chars-forward " \r\t\n")
20632 (point-at-bol)))))
20633 beg end toggled)
20634 ;; Determine boundaries of changes. If a universal prefix has
20635 ;; been given, put the list in a region. If region ends at a bol,
20636 ;; do not consider the last line to be in the region.
20638 (when (and current-prefix-arg (org-at-item-p))
20639 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20640 (org-mark-element))
20642 (if (org-region-active-p)
20643 (setq beg (funcall skip-blanks (region-beginning))
20644 end (copy-marker (save-excursion
20645 (goto-char (region-end))
20646 (if (bolp) (point) (point-at-eol)))))
20647 (setq beg (funcall skip-blanks (point-at-bol))
20648 end (copy-marker (point-at-eol))))
20649 ;; Ensure inline tasks don't count as headings.
20650 (org-with-limited-levels
20651 (save-excursion
20652 (goto-char beg)
20653 (cond
20654 ;; Case 1. Started at an heading: de-star headings.
20655 ((org-at-heading-p)
20656 (while (< (point) end)
20657 (when (org-at-heading-p t)
20658 (looking-at org-outline-regexp) (replace-match "")
20659 (setq toggled t))
20660 (forward-line)))
20661 ;; Case 2. Started at an item: change items into headlines.
20662 ;; One star will be added by `org-list-to-subtree'.
20663 ((org-at-item-p)
20664 (while (< (point) end)
20665 (when (org-at-item-p)
20666 ;; Pay attention to cases when region ends before list.
20667 (let* ((struct (org-list-struct))
20668 (list-end
20669 (min (org-list-get-bottom-point struct) (1+ end))))
20670 (save-restriction
20671 (narrow-to-region (point) list-end)
20672 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20673 (setq toggled t))
20674 (forward-line)))
20675 ;; Case 3. Started at normal text: make every line an heading,
20676 ;; skipping headlines and items.
20677 (t (let* ((stars
20678 (make-string
20679 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20680 (add-stars
20681 (cond (nstars "") ; stars from prefix only
20682 ((equal stars "") "*") ; before first heading
20683 (org-odd-levels-only "**") ; inside heading, odd
20684 (t "*"))) ; inside heading, oddeven
20685 (rpl (concat stars add-stars " "))
20686 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20687 (while (< (point) (if (equal nstars '(4)) lend end))
20688 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20689 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20690 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20691 (forward-line)))))))
20692 (unless toggled (message "Cannot toggle heading from here"))))
20694 (defun org-meta-return (&optional arg)
20695 "Insert a new heading or wrap a region in a table.
20696 Calls `org-insert-heading', `org-insert-item' or
20697 `org-table-wrap-region', depending on context. When called with
20698 an argument, unconditionally call `org-insert-heading'."
20699 (interactive "P")
20700 (org-check-before-invisible-edit 'insert)
20701 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20702 (call-interactively (cond (arg #'org-insert-heading)
20703 ((org-at-table-p) #'org-table-wrap-region)
20704 ((org-in-item-p) #'org-insert-item)
20705 (t #'org-insert-heading)))))
20707 ;;; Menu entries
20709 (defsubst org-in-subtree-not-table-p ()
20710 "Are we in a subtree and not in a table?"
20711 (and (not (org-before-first-heading-p))
20712 (not (org-at-table-p))))
20714 ;; Define the Org mode menus
20715 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20716 '("Tbl"
20717 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20718 ["Next Field" org-cycle (org-at-table-p)]
20719 ["Previous Field" org-shifttab (org-at-table-p)]
20720 ["Next Row" org-return (org-at-table-p)]
20721 "--"
20722 ["Blank Field" org-table-blank-field (org-at-table-p)]
20723 ["Edit Field" org-table-edit-field (org-at-table-p)]
20724 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20725 "--"
20726 ("Column"
20727 ["Move Column Left" org-metaleft (org-at-table-p)]
20728 ["Move Column Right" org-metaright (org-at-table-p)]
20729 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20730 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20731 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20732 ("Row"
20733 ["Move Row Up" org-metaup (org-at-table-p)]
20734 ["Move Row Down" org-metadown (org-at-table-p)]
20735 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20736 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20737 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20738 "--"
20739 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20740 ("Rectangle"
20741 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20742 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20743 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20744 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20745 "--"
20746 ("Calculate"
20747 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20748 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20749 ["Edit Formulas" org-edit-special (org-at-table-p)]
20750 "--"
20751 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20752 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20753 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20754 "--"
20755 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20756 "--"
20757 ["Sum Column/Rectangle" org-table-sum
20758 (or (org-at-table-p) (org-region-active-p))]
20759 ["Which Column?" org-table-current-column (org-at-table-p)])
20760 ["Debug Formulas"
20761 org-table-toggle-formula-debugger
20762 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20763 ["Show Col/Row Numbers"
20764 org-table-toggle-coordinate-overlays
20765 :style toggle
20766 :selected (bound-and-true-p org-table-overlay-coordinates)]
20767 "--"
20768 ["Create" org-table-create (not (org-at-table-p))]
20769 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20770 ["Import from File" org-table-import (not (org-at-table-p))]
20771 ["Export to File" org-table-export (org-at-table-p)]
20772 "--"
20773 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20774 "--"
20775 ("Plot"
20776 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20777 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20779 (easy-menu-define org-org-menu org-mode-map "Org menu"
20780 '("Org"
20781 ("Show/Hide"
20782 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20783 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20784 ["Sparse Tree..." org-sparse-tree t]
20785 ["Reveal Context" org-reveal t]
20786 ["Show All" org-show-all t]
20787 "--"
20788 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20789 "--"
20790 ["New Heading" org-insert-heading t]
20791 ("Navigate Headings"
20792 ["Up" outline-up-heading t]
20793 ["Next" outline-next-visible-heading t]
20794 ["Previous" outline-previous-visible-heading t]
20795 ["Next Same Level" outline-forward-same-level t]
20796 ["Previous Same Level" outline-backward-same-level t]
20797 "--"
20798 ["Jump" org-goto t])
20799 ("Edit Structure"
20800 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20801 "--"
20802 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20803 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20804 "--"
20805 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20806 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20807 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20808 "--"
20809 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20810 "--"
20811 ["Copy visible text" org-copy-visible t]
20812 "--"
20813 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20814 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20815 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20816 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20817 "--"
20818 ["Sort Region/Children" org-sort t]
20819 "--"
20820 ["Convert to odd levels" org-convert-to-odd-levels t]
20821 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20822 ("Editing"
20823 ["Emphasis..." org-emphasize t]
20824 ["Edit Source Example" org-edit-special t]
20825 "--"
20826 ["Footnote new/jump" org-footnote-action t]
20827 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20828 ("Archive"
20829 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20830 "--"
20831 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20832 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20833 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20835 "--"
20836 ("Hyperlinks"
20837 ["Store Link (Global)" org-store-link t]
20838 ["Find existing link to here" org-occur-link-in-agenda-files t]
20839 ["Insert Link" org-insert-link t]
20840 ["Follow Link" org-open-at-point t]
20841 "--"
20842 ["Next link" org-next-link t]
20843 ["Previous link" org-previous-link t]
20844 "--"
20845 ["Descriptive Links"
20846 org-toggle-link-display
20847 :style radio
20848 :selected org-descriptive-links
20850 ["Literal Links"
20851 org-toggle-link-display
20852 :style radio
20853 :selected (not org-descriptive-links)])
20854 "--"
20855 ("TODO Lists"
20856 ["TODO/DONE/-" org-todo t]
20857 ("Select keyword"
20858 ["Next keyword" org-shiftright (org-at-heading-p)]
20859 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20860 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20861 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20862 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20863 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20864 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20865 "--"
20866 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20867 :selected org-enforce-todo-dependencies :style toggle :active t]
20868 "Settings for tree at point"
20869 ["Do Children sequentially" org-toggle-ordered-property :style radio
20870 :selected (org-entry-get nil "ORDERED")
20871 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20872 ["Do Children parallel" org-toggle-ordered-property :style radio
20873 :selected (not (org-entry-get nil "ORDERED"))
20874 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20875 "--"
20876 ["Set Priority" org-priority t]
20877 ["Priority Up" org-shiftup t]
20878 ["Priority Down" org-shiftdown t]
20879 "--"
20880 ["Get news from all feeds" org-feed-update-all t]
20881 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20882 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20883 ("TAGS and Properties"
20884 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20885 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20886 "--"
20887 ["Set property" org-set-property (not (org-before-first-heading-p))]
20888 ["Column view of properties" org-columns t]
20889 ["Insert Column View DBlock" org-columns-insert-dblock t])
20890 ("Dates and Scheduling"
20891 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20892 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20893 ("Change Date"
20894 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20895 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20896 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20897 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20898 ["Compute Time Range" org-evaluate-time-range t]
20899 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20900 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20901 "--"
20902 ["Custom time format" org-toggle-time-stamp-overlays
20903 :style radio :selected org-display-custom-times]
20904 "--"
20905 ["Goto Calendar" org-goto-calendar t]
20906 ["Date from Calendar" org-date-from-calendar t]
20907 "--"
20908 ["Start/Restart Timer" org-timer-start t]
20909 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20910 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20911 ["Insert Timer String" org-timer t]
20912 ["Insert Timer Item" org-timer-item t])
20913 ("Logging work"
20914 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20915 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20916 ["Clock out" org-clock-out t]
20917 ["Clock cancel" org-clock-cancel t]
20918 "--"
20919 ["Mark as default task" org-clock-mark-default-task t]
20920 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20921 ["Goto running clock" org-clock-goto t]
20922 "--"
20923 ["Display times" org-clock-display t]
20924 ["Create clock table" org-clock-report t]
20925 "--"
20926 ["Record DONE time"
20927 (progn (setq org-log-done (not org-log-done))
20928 (message "Switching to %s will %s record a timestamp"
20929 (car org-done-keywords)
20930 (if org-log-done "automatically" "not")))
20931 :style toggle :selected org-log-done])
20932 "--"
20933 ["Agenda Command..." org-agenda t]
20934 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20935 ("File List for Agenda")
20936 ("Special views current file"
20937 ["TODO Tree" org-show-todo-tree t]
20938 ["Check Deadlines" org-check-deadlines t]
20939 ["Tags/Property tree" org-match-sparse-tree t])
20940 "--"
20941 ["Export/Publish..." org-export-dispatch t]
20942 ("LaTeX"
20943 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20944 :style toggle :selected org-cdlatex-mode]
20945 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20946 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20947 ["Modify math symbol" org-cdlatex-math-modify
20948 (org-inside-LaTeX-fragment-p)]
20949 ["Insert citation" org-reftex-citation t])
20950 "--"
20951 ("MobileOrg"
20952 ["Push Files and Views" org-mobile-push t]
20953 ["Get Captured and Flagged" org-mobile-pull t]
20954 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20955 "--"
20956 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20957 "--"
20958 ("Documentation"
20959 ["Show Version" org-version t]
20960 ["Info Documentation" org-info t]
20961 ["Browse Org News" org-browse-news t])
20962 ("Customize"
20963 ["Browse Org Group" org-customize t]
20964 "--"
20965 ["Expand This Menu" org-create-customize-menu
20966 (fboundp 'customize-menu-create)])
20967 ["Send bug report" org-submit-bug-report t]
20968 "--"
20969 ("Refresh/Reload"
20970 ["Refresh setup current buffer" org-mode-restart t]
20971 ["Reload Org (after update)" org-reload t]
20972 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
20974 (defun org-info (&optional node)
20975 "Read documentation for Org in the info system.
20976 With optional NODE, go directly to that node."
20977 (interactive)
20978 (info (format "(org)%s" (or node ""))))
20980 (defun org-browse-news ()
20981 "Browse the news for the latest major release."
20982 (interactive)
20983 (browse-url "https://orgmode.org/Changes.html"))
20985 ;;;###autoload
20986 (defun org-submit-bug-report ()
20987 "Submit a bug report on Org via mail.
20989 Don't hesitate to report any problems or inaccurate documentation.
20991 If you don't have setup sending mail from (X)Emacs, please copy the
20992 output buffer into your mail program, as it gives us important
20993 information about your Org version and configuration."
20994 (interactive)
20995 (require 'reporter)
20996 (defvar reporter-prompt-for-summary-p)
20997 (org-load-modules-maybe)
20998 (org-require-autoloaded-modules)
20999 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21000 (reporter-submit-bug-report
21001 "emacs-orgmode@gnu.org"
21002 (org-version nil 'full)
21003 (let (list)
21004 (save-window-excursion
21005 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21006 (delete-other-windows)
21007 (erase-buffer)
21008 (insert "You are about to submit a bug report to the Org mailing list.
21010 We would like to add your full Org and Outline configuration to the
21011 bug report. This greatly simplifies the work of the maintainer and
21012 other experts on the mailing list.
21014 HOWEVER, some variables you have customized may contain private
21015 information. The names of customers, colleagues, or friends, might
21016 appear in the form of file names, tags, todo states, or search strings.
21017 If you answer yes to the prompt, you might want to check and remove
21018 such private information before sending the email.")
21019 (add-text-properties (point-min) (point-max) '(face org-warning))
21020 (when (yes-or-no-p "Include your Org configuration ")
21021 (mapatoms
21022 (lambda (v)
21023 (and (boundp v)
21024 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21025 (or (and (symbol-value v)
21026 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21027 (and
21028 (get v 'custom-type) (get v 'standard-value)
21029 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21030 (push v list)))))
21031 (kill-buffer (get-buffer "*Warn about privacy*"))
21032 list))
21033 nil nil
21034 "Remember to cover the basics, that is, what you expected to happen and
21035 what in fact did happen. You don't know how to make a good report? See
21037 https://orgmode.org/manual/Feedback.html#Feedback
21039 Your bug report will be posted to the Org mailing list.
21040 ------------------------------------------------------------------------")
21041 (save-excursion
21042 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21043 (replace-match "\\1Bug: \\3 [\\2]")))))
21046 (defun org-install-agenda-files-menu ()
21047 (let ((bl (buffer-list)))
21048 (save-excursion
21049 (while bl
21050 (set-buffer (pop bl))
21051 (when (derived-mode-p 'org-mode) (setq bl nil)))
21052 (when (derived-mode-p 'org-mode)
21053 (easy-menu-change
21054 '("Org") "File List for Agenda"
21055 (append
21056 (list
21057 ["Edit File List" (org-edit-agenda-file-list) t]
21058 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21059 ["Remove Current File from List" org-remove-file t]
21060 ["Cycle through agenda files" org-cycle-agenda-files t]
21061 ["Occur in all agenda files" org-occur-in-agenda-files t]
21062 "--")
21063 (mapcar 'org-file-menu-entry
21064 ;; Prevent initialization from failing.
21065 (ignore-errors (org-agenda-files t)))))))))
21067 ;;;; Documentation
21069 (defun org-require-autoloaded-modules ()
21070 (interactive)
21071 (mapc #'require
21072 '(org-agenda org-archive org-attach org-clock org-colview org-id
21073 org-table org-timer)))
21075 ;;;###autoload
21076 (defun org-reload (&optional uncompiled)
21077 "Reload all Org Lisp files.
21078 With prefix arg UNCOMPILED, load the uncompiled versions."
21079 (interactive "P")
21080 (require 'loadhist)
21081 (let* ((org-dir (org-find-library-dir "org"))
21082 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21083 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21084 (remove-re (format "\\`%s\\'"
21085 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21086 (feats (delete-dups
21087 (mapcar 'file-name-sans-extension
21088 (mapcar 'file-name-nondirectory
21089 (delq nil
21090 (mapcar 'feature-file
21091 features))))))
21092 (lfeat (append
21093 (sort
21094 (setq feats
21095 (delq nil (mapcar
21096 (lambda (f)
21097 (if (and (string-match feature-re f)
21098 (not (string-match remove-re f)))
21099 f nil))
21100 feats)))
21101 'string-lessp)
21102 (list "org-version" "org")))
21103 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21104 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21105 load-uncore load-misses)
21106 (setq load-misses
21107 (delq 't
21108 (mapcar (lambda (f)
21109 (or (org-load-noerror-mustsuffix (concat org-dir f))
21110 (and (string= org-dir contrib-dir)
21111 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21112 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21113 (add-to-list 'load-uncore f 'append)
21116 lfeat)))
21117 (when load-uncore
21118 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21119 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21120 (if load-misses
21121 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21122 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21123 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21125 ;;;###autoload
21126 (defun org-customize ()
21127 "Call the customize function with org as argument."
21128 (interactive)
21129 (org-load-modules-maybe)
21130 (org-require-autoloaded-modules)
21131 (customize-browse 'org))
21133 (defun org-create-customize-menu ()
21134 "Create a full customization menu for Org mode, insert it into the menu."
21135 (interactive)
21136 (org-load-modules-maybe)
21137 (org-require-autoloaded-modules)
21138 (if (fboundp 'customize-menu-create)
21139 (progn
21140 (easy-menu-change
21141 '("Org") "Customize"
21142 `(["Browse Org group" org-customize t]
21143 "--"
21144 ,(customize-menu-create 'org)
21145 ["Set" Custom-set t]
21146 ["Save" Custom-save t]
21147 ["Reset to Current" Custom-reset-current t]
21148 ["Reset to Saved" Custom-reset-saved t]
21149 ["Reset to Standard Settings" Custom-reset-standard t]))
21150 (message "\"Org\"-menu now contains full customization menu"))
21151 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21153 ;;;; Miscellaneous stuff
21155 ;;; Generally useful functions
21157 (defun org-link-display-format (s)
21158 "Replace links in string S with their description.
21159 If there is no description, use the link target."
21160 (save-match-data
21161 (replace-regexp-in-string
21162 org-bracket-link-analytic-regexp
21163 (lambda (m)
21164 (if (match-end 5) (match-string 5 m)
21165 (concat (match-string 1 m) (match-string 3 m))))
21166 s nil t)))
21168 (defun org-toggle-link-display ()
21169 "Toggle the literal or descriptive display of links."
21170 (interactive)
21171 (if org-descriptive-links
21172 (remove-from-invisibility-spec '(org-link))
21173 (add-to-invisibility-spec '(org-link)))
21174 (org-restart-font-lock)
21175 (setq org-descriptive-links (not org-descriptive-links)))
21177 (defun org-in-clocktable-p ()
21178 "Check if the cursor is in a clocktable."
21179 (let ((pos (point)) start)
21180 (save-excursion
21181 (end-of-line 1)
21182 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21183 (setq start (match-beginning 0))
21184 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21185 (>= (match-end 0) pos)
21186 start))))
21188 (defun org-in-verbatim-emphasis ()
21189 (save-match-data
21190 (and (org-in-regexp org-verbatim-re 2)
21191 (>= (point) (match-beginning 3))
21192 (<= (point) (match-end 4)))))
21194 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21195 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21196 (if (and marker (marker-buffer marker)
21197 (buffer-live-p (marker-buffer marker)))
21198 (progn
21199 (pop-to-buffer-same-window (marker-buffer marker))
21200 (when (or (> marker (point-max)) (< marker (point-min)))
21201 (widen))
21202 (goto-char marker)
21203 (org-show-context 'org-goto))
21204 (if bookmark
21205 (bookmark-jump bookmark)
21206 (error "Cannot find location"))))
21208 (defun org-quote-csv-field (s)
21209 "Quote field for inclusion in CSV material."
21210 (if (string-match "[\",]" s)
21211 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21214 (defun org-force-self-insert (N)
21215 "Needed to enforce self-insert under remapping."
21216 (interactive "p")
21217 (self-insert-command N))
21219 (defun org-fill-template (template alist)
21220 "Find each %key of ALIST in TEMPLATE and replace it."
21221 (let ((case-fold-search nil))
21222 (dolist (entry (sort (copy-sequence alist)
21223 (lambda (a b) (< (length (car a)) (length (car b))))))
21224 (setq template
21225 (replace-regexp-in-string
21226 (concat "%" (regexp-quote (car entry)))
21227 (or (cdr entry) "") template t t)))
21228 template))
21230 (defun org-quote-vert (s)
21231 "Replace \"|\" with \"\\vert\"."
21232 (while (string-match "|" s)
21233 (setq s (replace-match "\\vert" t t s)))
21236 (defun org-uuidgen-p (s)
21237 "Is S an ID created by UUIDGEN?"
21238 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21240 (defun org-in-src-block-p (&optional inside)
21241 "Whether point is in a code source block.
21242 When INSIDE is non-nil, don't consider we are within a source
21243 block when point is at #+BEGIN_SRC or #+END_SRC."
21244 (let ((case-fold-search t))
21245 (or (and (eq (get-char-property (point) 'src-block) t))
21246 (and (not inside)
21247 (save-match-data
21248 (save-excursion
21249 (beginning-of-line)
21250 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21252 (defun org-context ()
21253 "Return a list of contexts of the current cursor position.
21254 If several contexts apply, all are returned.
21255 Each context entry is a list with a symbol naming the context, and
21256 two positions indicating start and end of the context. Possible
21257 contexts are:
21259 :headline anywhere in a headline
21260 :headline-stars on the leading stars in a headline
21261 :todo-keyword on a TODO keyword (including DONE) in a headline
21262 :tags on the TAGS in a headline
21263 :priority on the priority cookie in a headline
21264 :item on the first line of a plain list item
21265 :item-bullet on the bullet/number of a plain list item
21266 :checkbox on the checkbox in a plain list item
21267 :table in an Org table
21268 :table-special on a special filed in a table
21269 :table-table in a table.el table
21270 :clocktable in a clocktable
21271 :src-block in a source block
21272 :link on a hyperlink
21273 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21274 :target on a <<target>>
21275 :radio-target on a <<<radio-target>>>
21276 :latex-fragment on a LaTeX fragment
21277 :latex-preview on a LaTeX fragment with overlaid preview image
21279 This function expects the position to be visible because it uses font-lock
21280 faces as a help to recognize the following contexts: :table-special, :link,
21281 and :keyword."
21282 (let* ((f (get-text-property (point) 'face))
21283 (faces (if (listp f) f (list f)))
21284 (case-fold-search t)
21285 (p (point)) clist o)
21286 ;; First the large context
21287 (cond
21288 ((org-at-heading-p t)
21289 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21290 (when (progn
21291 (beginning-of-line 1)
21292 (looking-at org-todo-line-tags-regexp))
21293 (push (org-point-in-group p 1 :headline-stars) clist)
21294 (push (org-point-in-group p 2 :todo-keyword) clist)
21295 (push (org-point-in-group p 4 :tags) clist))
21296 (goto-char p)
21297 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21298 (when (looking-at "\\[#[A-Z0-9]\\]")
21299 (push (org-point-in-group p 0 :priority) clist)))
21301 ((org-at-item-p)
21302 (push (org-point-in-group p 2 :item-bullet) clist)
21303 (push (list :item (point-at-bol)
21304 (save-excursion (org-end-of-item) (point)))
21305 clist)
21306 (and (org-at-item-checkbox-p)
21307 (push (org-point-in-group p 0 :checkbox) clist)))
21309 ((org-at-table-p)
21310 (push (list :table (org-table-begin) (org-table-end)) clist)
21311 (when (memq 'org-formula faces)
21312 (push (list :table-special
21313 (previous-single-property-change p 'face)
21314 (next-single-property-change p 'face)) clist)))
21315 ((org-at-table-p 'any)
21316 (push (list :table-table) clist)))
21317 (goto-char p)
21319 (let ((case-fold-search t))
21320 ;; New the "medium" contexts: clocktables, source blocks
21321 (cond ((org-in-clocktable-p)
21322 (push (list :clocktable
21323 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21324 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21325 (match-beginning 1))
21326 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21327 (match-end 0))) clist))
21328 ((org-in-src-block-p)
21329 (push (list :src-block
21330 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21331 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21332 (match-beginning 1))
21333 (and (search-forward "#+END_SRC" nil t)
21334 (match-beginning 0))) clist))))
21335 (goto-char p)
21337 ;; Now the small context
21338 (cond
21339 ((org-at-timestamp-p)
21340 (push (org-point-in-group p 0 :timestamp) clist))
21341 ((memq 'org-link faces)
21342 (push (list :link
21343 (previous-single-property-change p 'face)
21344 (next-single-property-change p 'face)) clist))
21345 ((memq 'org-special-keyword faces)
21346 (push (list :keyword
21347 (previous-single-property-change p 'face)
21348 (next-single-property-change p 'face)) clist))
21349 ((org-at-target-p)
21350 (push (org-point-in-group p 0 :target) clist)
21351 (goto-char (1- (match-beginning 0)))
21352 (when (looking-at org-radio-target-regexp)
21353 (push (org-point-in-group p 0 :radio-target) clist))
21354 (goto-char p))
21355 ((setq o (cl-some
21356 (lambda (o)
21357 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21359 (overlays-at (point))))
21360 (push (list :latex-fragment
21361 (overlay-start o) (overlay-end o)) clist)
21362 (push (list :latex-preview
21363 (overlay-start o) (overlay-end o)) clist))
21364 ((org-inside-LaTeX-fragment-p)
21365 ;; FIXME: positions wrong.
21366 (push (list :latex-fragment (point) (point)) clist)))
21368 (setq clist (nreverse (delq nil clist)))
21369 clist))
21371 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21372 "Non-nil when point is between matches of START-RE and END-RE.
21374 Also return a non-nil value when point is on one of the matches.
21376 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21377 buffer positions. Default values are the positions of headlines
21378 surrounding the point.
21380 The functions returns a cons cell whose car (resp. cdr) is the
21381 position before START-RE (resp. after END-RE)."
21382 (save-match-data
21383 (let ((pos (point))
21384 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21385 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21386 beg end)
21387 (save-excursion
21388 ;; Point is on a block when on START-RE or if START-RE can be
21389 ;; found before it...
21390 (and (or (org-in-regexp start-re)
21391 (re-search-backward start-re limit-up t))
21392 (setq beg (match-beginning 0))
21393 ;; ... and END-RE after it...
21394 (goto-char (match-end 0))
21395 (re-search-forward end-re limit-down t)
21396 (> (setq end (match-end 0)) pos)
21397 ;; ... without another START-RE in-between.
21398 (goto-char (match-beginning 0))
21399 (not (re-search-backward start-re (1+ beg) t))
21400 ;; Return value.
21401 (cons beg end))))))
21403 (defun org-in-block-p (names)
21404 "Non-nil when point belongs to a block whose name belongs to NAMES.
21406 NAMES is a list of strings containing names of blocks.
21408 Return first block name matched, or nil. Beware that in case of
21409 nested blocks, the returned name may not belong to the closest
21410 block from point."
21411 (save-match-data
21412 (catch 'exit
21413 (let ((case-fold-search t)
21414 (lim-up (save-excursion (outline-previous-heading)))
21415 (lim-down (save-excursion (outline-next-heading))))
21416 (dolist (name names)
21417 (let ((n (regexp-quote name)))
21418 (when (org-between-regexps-p
21419 (concat "^[ \t]*#\\+begin_" n)
21420 (concat "^[ \t]*#\\+end_" n)
21421 lim-up lim-down)
21422 (throw 'exit n)))))
21423 nil)))
21425 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21426 "Call `multi-occur' with buffers for all agenda files."
21427 (interactive "sOrg-files matching: ")
21428 (let* ((files (org-agenda-files))
21429 (tnames (mapcar #'file-truename files))
21430 (extra org-agenda-text-search-extra-files))
21431 (when (eq (car extra) 'agenda-archives)
21432 (setq extra (cdr extra))
21433 (setq files (org-add-archive-files files)))
21434 (dolist (f extra)
21435 (unless (member (file-truename f) tnames)
21436 (unless (member f files) (setq files (append files (list f))))
21437 (setq tnames (append tnames (list (file-truename f))))))
21438 (multi-occur
21439 (mapcar (lambda (x)
21440 (with-current-buffer
21441 ;; FIXME: Why not just (find-file-noselect x)?
21442 ;; Is it to avoid the "revert buffer" prompt?
21443 (or (get-file-buffer x) (find-file-noselect x))
21444 (widen)
21445 (current-buffer)))
21446 files)
21447 regexp)))
21449 (add-hook 'occur-mode-find-occurrence-hook
21450 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21452 (defun org-occur-link-in-agenda-files ()
21453 "Create a link and search for it in the agendas.
21454 The link is not stored in `org-stored-links', it is just created
21455 for the search purpose."
21456 (interactive)
21457 (let ((link (condition-case nil
21458 (org-store-link nil)
21459 (error "Unable to create a link to here"))))
21460 (org-occur-in-agenda-files (regexp-quote link))))
21462 (defun org-back-over-empty-lines ()
21463 "Move backwards over whitespace, to the beginning of the first empty line.
21464 Returns the number of empty lines passed."
21465 (let ((pos (point)))
21466 (if (cdr (assq 'heading org-blank-before-new-entry))
21467 (skip-chars-backward " \t\n\r")
21468 (unless (eobp)
21469 (forward-line -1)))
21470 (beginning-of-line 2)
21471 (goto-char (min (point) pos))
21472 (count-lines (point) pos)))
21474 (defun org-replace-escapes (string table)
21475 "Replace %-escapes in STRING with values in TABLE.
21476 TABLE is an association list with keys like \"%a\" and string values.
21477 The sequences in STRING may contain normal field width and padding information,
21478 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21479 so values can contain further %-escapes if they are define later in TABLE."
21480 (let ((tbl (copy-alist table))
21481 (case-fold-search nil)
21482 (pchg 0)
21483 re rpl)
21484 (dolist (e tbl)
21485 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21486 (when (and (cdr e) (string-match re (cdr e)))
21487 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21488 (safe "SREF"))
21489 (add-text-properties 0 3 (list 'sref sref) safe)
21490 (setcdr e (replace-match safe t t (cdr e)))))
21491 (while (string-match re string)
21492 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21493 (cdr e)))
21494 (setq string (replace-match rpl t t string))))
21495 (while (setq pchg (next-property-change pchg string))
21496 (let ((sref (get-text-property pchg 'sref string)))
21497 (when (and sref (string-match "SREF" string pchg))
21498 (setq string (replace-match sref t t string)))))
21499 string))
21501 ;;; TODO: Only called once, from ox-odt which should probably use
21502 ;;; org-export-inline-image-p or something.
21503 (defun org-file-image-p (file)
21504 "Return non-nil if FILE is an image."
21505 (save-match-data
21506 (string-match (image-file-name-regexp) file)))
21508 (defun org-get-cursor-date (&optional with-time)
21509 "Return the date at cursor in as a time.
21510 This works in the calendar and in the agenda, anywhere else it just
21511 returns the current time.
21512 If WITH-TIME is non-nil, returns the time of the event at point (in
21513 the agenda) or the current time of the day."
21514 (let (date day defd tp hod mod)
21515 (when with-time
21516 (setq tp (get-text-property (point) 'time))
21517 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21518 (setq hod (string-to-number (match-string 1 tp))
21519 mod (string-to-number (match-string 2 tp))))
21520 (or tp (let ((now (decode-time)))
21521 (setq hod (nth 2 now)
21522 mod (nth 1 now)))))
21523 (cond
21524 ((eq major-mode 'calendar-mode)
21525 (setq date (calendar-cursor-to-date)
21526 defd (encode-time 0 (or mod 0) (or hod 0)
21527 (nth 1 date) (nth 0 date) (nth 2 date))))
21528 ((eq major-mode 'org-agenda-mode)
21529 (setq day (get-text-property (point) 'day))
21530 (when day
21531 (setq date (calendar-gregorian-from-absolute day)
21532 defd (encode-time 0 (or mod 0) (or hod 0)
21533 (nth 1 date) (nth 0 date) (nth 2 date))))))
21534 (or defd (current-time))))
21536 (defun org-mark-subtree (&optional up)
21537 "Mark the current subtree.
21538 This puts point at the start of the current subtree, and mark at
21539 the end. If a numeric prefix UP is given, move up into the
21540 hierarchy of headlines by UP levels before marking the subtree."
21541 (interactive "P")
21542 (org-with-limited-levels
21543 (cond ((org-at-heading-p) (beginning-of-line))
21544 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21545 (t (outline-previous-visible-heading 1))))
21546 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21547 (if (called-interactively-p 'any)
21548 (call-interactively 'org-mark-element)
21549 (org-mark-element)))
21551 ;;; Indentation
21553 (defvar org-element-greater-elements)
21554 (defun org--get-expected-indentation (element contentsp)
21555 "Expected indentation column for current line, according to ELEMENT.
21556 ELEMENT is an element containing point. CONTENTSP is non-nil
21557 when indentation is to be computed according to contents of
21558 ELEMENT."
21559 (let ((type (org-element-type element))
21560 (start (org-element-property :begin element))
21561 (post-affiliated (org-element-property :post-affiliated element)))
21562 (org-with-wide-buffer
21563 (cond
21564 (contentsp
21565 (cl-case type
21566 ((diary-sexp footnote-definition) 0)
21567 ((headline inlinetask nil)
21568 (if (not org-adapt-indentation) 0
21569 (let ((level (org-current-level)))
21570 (if level (1+ level) 0))))
21571 ((item plain-list) (org-list-item-body-column post-affiliated))
21573 (goto-char start)
21574 (current-indentation))))
21575 ((memq type '(headline inlinetask nil))
21576 (if (org-match-line "[ \t]*$")
21577 (org--get-expected-indentation element t)
21579 ((memq type '(diary-sexp footnote-definition)) 0)
21580 ;; First paragraph of a footnote definition or an item.
21581 ;; Indent like parent.
21582 ((< (line-beginning-position) start)
21583 (org--get-expected-indentation
21584 (org-element-property :parent element) t))
21585 ;; At first line: indent according to previous sibling, if any,
21586 ;; ignoring footnote definitions and inline tasks, or parent's
21587 ;; contents.
21588 ((= (line-beginning-position) start)
21589 (catch 'exit
21590 (while t
21591 (if (= (point-min) start) (throw 'exit 0)
21592 (goto-char (1- start))
21593 (let* ((previous (org-element-at-point))
21594 (parent previous))
21595 (while (and parent (<= (org-element-property :end parent) start))
21596 (setq previous parent
21597 parent (org-element-property :parent parent)))
21598 (cond
21599 ((not previous) (throw 'exit 0))
21600 ((> (org-element-property :end previous) start)
21601 (throw 'exit (org--get-expected-indentation previous t)))
21602 ((memq (org-element-type previous)
21603 '(footnote-definition inlinetask))
21604 (setq start (org-element-property :begin previous)))
21605 (t (goto-char (org-element-property :begin previous))
21606 (throw 'exit
21607 (if (bolp) (current-indentation)
21608 ;; At first paragraph in an item or
21609 ;; a footnote definition.
21610 (org--get-expected-indentation
21611 (org-element-property :parent previous) t))))))))))
21612 ;; Otherwise, move to the first non-blank line above.
21614 (beginning-of-line)
21615 (let ((pos (point)))
21616 (skip-chars-backward " \r\t\n")
21617 (cond
21618 ;; Two blank lines end a footnote definition or a plain
21619 ;; list. When we indent an empty line after them, the
21620 ;; containing list or footnote definition is over, so it
21621 ;; qualifies as a previous sibling. Therefore, we indent
21622 ;; like its first line.
21623 ((and (memq type '(footnote-definition plain-list))
21624 (> (count-lines (point) pos) 2))
21625 (goto-char start)
21626 (current-indentation))
21627 ;; Line above is the first one of a paragraph at the
21628 ;; beginning of an item or a footnote definition. Indent
21629 ;; like parent.
21630 ((< (line-beginning-position) start)
21631 (org--get-expected-indentation
21632 (org-element-property :parent element) t))
21633 ;; Line above is the beginning of an element, i.e., point
21634 ;; was originally on the blank lines between element's start
21635 ;; and contents.
21636 ((= (line-beginning-position) post-affiliated)
21637 (org--get-expected-indentation element t))
21638 ;; POS is after contents in a greater element. Indent like
21639 ;; the beginning of the element.
21640 ((and (memq type org-element-greater-elements)
21641 (let ((cend (org-element-property :contents-end element)))
21642 (and cend (<= cend pos))))
21643 ;; As a special case, if point is at the end of a footnote
21644 ;; definition or an item, indent like the very last element
21645 ;; within. If that last element is an item, indent like
21646 ;; its contents.
21647 (if (memq type '(footnote-definition item plain-list))
21648 (let ((last (org-element-at-point)))
21649 (goto-char pos)
21650 (org--get-expected-indentation
21651 last (eq (org-element-type last) 'item)))
21652 (goto-char start)
21653 (current-indentation)))
21654 ;; In any other case, indent like the current line.
21655 (t (current-indentation)))))))))
21657 (defun org--align-node-property ()
21658 "Align node property at point.
21659 Alignment is done according to `org-property-format', which see."
21660 (when (save-excursion
21661 (beginning-of-line)
21662 (looking-at org-property-re))
21663 (replace-match
21664 (concat (match-string 4)
21665 (org-trim
21666 (format org-property-format (match-string 1) (match-string 3))))
21667 t t)))
21669 (defun org-indent-line ()
21670 "Indent line depending on context.
21672 Indentation is done according to the following rules:
21674 - Footnote definitions, diary sexps, headlines and inline tasks
21675 have to start at column 0.
21677 - On the very first line of an element, consider, in order, the
21678 next rules until one matches:
21680 1. If there's a sibling element before, ignoring footnote
21681 definitions and inline tasks, indent like its first line.
21683 2. If element has a parent, indent like its contents. More
21684 precisely, if parent is an item, indent after the
21685 description part, if any, or the bullet (see
21686 `org-list-description-max-indent'). Else, indent like
21687 parent's first line.
21689 3. Otherwise, indent relatively to current level, if
21690 `org-adapt-indentation' is non-nil, or to left margin.
21692 - On a blank line at the end of an element, indent according to
21693 the type of the element. More precisely
21695 1. If element is a plain list, an item, or a footnote
21696 definition, indent like the very last element within.
21698 2. If element is a paragraph, indent like its last non blank
21699 line.
21701 3. Otherwise, indent like its very first line.
21703 - In the code part of a source block, use language major mode
21704 to indent current line if `org-src-tab-acts-natively' is
21705 non-nil. If it is nil, do nothing.
21707 - Otherwise, indent like the first non-blank line above.
21709 The function doesn't indent an item as it could break the whole
21710 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21711 `\\[org-shiftmetaright]'.
21713 Also align node properties according to `org-property-format'."
21714 (interactive)
21715 (cond
21716 ((org-at-heading-p) 'noindent)
21718 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21719 (type (org-element-type element)))
21720 (cond ((and (memq type '(plain-list item))
21721 (= (line-beginning-position)
21722 (org-element-property :post-affiliated element)))
21723 'noindent)
21724 ((and (eq type 'latex-environment)
21725 (>= (point) (org-element-property :post-affiliated element))
21726 (< (point) (org-with-wide-buffer
21727 (goto-char (org-element-property :end element))
21728 (skip-chars-backward " \r\t\n")
21729 (line-beginning-position 2))))
21730 'noindent)
21731 ((and (eq type 'src-block)
21732 org-src-tab-acts-natively
21733 (> (line-beginning-position)
21734 (org-element-property :post-affiliated element))
21735 (< (line-beginning-position)
21736 (org-with-wide-buffer
21737 (goto-char (org-element-property :end element))
21738 (skip-chars-backward " \r\t\n")
21739 (line-beginning-position))))
21740 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21742 (let ((column (org--get-expected-indentation element nil)))
21743 ;; Preserve current column.
21744 (if (<= (current-column) (current-indentation))
21745 (indent-line-to column)
21746 (save-excursion (indent-line-to column))))
21747 ;; Align node property. Also preserve current column.
21748 (when (eq type 'node-property)
21749 (let ((column (current-column)))
21750 (org--align-node-property)
21751 (org-move-to-column column)))))))))
21753 (defun org-indent-region (start end)
21754 "Indent each non-blank line in the region.
21755 Called from a program, START and END specify the region to
21756 indent. The function will not indent contents of example blocks,
21757 verse blocks and export blocks as leading white spaces are
21758 assumed to be significant there."
21759 (interactive "r")
21760 (save-excursion
21761 (goto-char start)
21762 (skip-chars-forward " \r\t\n")
21763 (unless (eobp) (beginning-of-line))
21764 (let ((indent-to
21765 (lambda (ind pos)
21766 ;; Set IND as indentation for all lines between point and
21767 ;; POS. Blank lines are ignored. Leave point after POS
21768 ;; once done.
21769 (let ((limit (copy-marker pos)))
21770 (while (< (point) limit)
21771 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21772 (forward-line))
21773 (set-marker limit nil))))
21774 (end (copy-marker end)))
21775 (while (< (point) end)
21776 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21777 (let* ((element (org-element-at-point))
21778 (type (org-element-type element))
21779 (element-end (copy-marker (org-element-property :end element)))
21780 (ind (org--get-expected-indentation element nil)))
21781 (cond
21782 ;; Element indented as a single block. Example blocks
21783 ;; preserving indentation are a special case since the
21784 ;; "contents" must not be indented whereas the block
21785 ;; boundaries can.
21786 ((or (memq type '(export-block latex-environment))
21787 (and (eq type 'example-block)
21788 (not
21789 (or org-src-preserve-indentation
21790 (org-element-property :preserve-indent element)))))
21791 (let ((offset (- ind (current-indentation))))
21792 (unless (zerop offset)
21793 (indent-rigidly (org-element-property :begin element)
21794 (org-element-property :end element)
21795 offset)))
21796 (goto-char element-end))
21797 ;; Elements indented line wise. Be sure to exclude
21798 ;; example blocks (preserving indentation) and source
21799 ;; blocks from this category as they are treated
21800 ;; specially later.
21801 ((or (memq type '(paragraph table table-row))
21802 (not (or (org-element-property :contents-begin element)
21803 (memq type '(example-block src-block)))))
21804 (when (eq type 'node-property)
21805 (org--align-node-property)
21806 (beginning-of-line))
21807 (funcall indent-to ind (min element-end end)))
21808 ;; Elements consisting of three parts: before the
21809 ;; contents, the contents, and after the contents. The
21810 ;; contents are treated specially, according to the
21811 ;; element type, or not indented at all. Other parts are
21812 ;; indented as a single block.
21814 (let* ((post (copy-marker
21815 (org-element-property :post-affiliated element)))
21816 (cbeg
21817 (copy-marker
21818 (cond
21819 ((not (org-element-property :contents-begin element))
21820 ;; Fake contents for source blocks.
21821 (org-with-wide-buffer
21822 (goto-char post)
21823 (line-beginning-position 2)))
21824 ((memq type '(footnote-definition item plain-list))
21825 ;; Contents in these elements could start on
21826 ;; the same line as the beginning of the
21827 ;; element. Make sure we start indenting
21828 ;; from the second line.
21829 (org-with-wide-buffer
21830 (goto-char post)
21831 (end-of-line)
21832 (skip-chars-forward " \r\t\n")
21833 (if (eobp) (point) (line-beginning-position))))
21834 (t (org-element-property :contents-begin element)))))
21835 (cend (copy-marker
21836 (or (org-element-property :contents-end element)
21837 ;; Fake contents for source blocks.
21838 (org-with-wide-buffer
21839 (goto-char element-end)
21840 (skip-chars-backward " \r\t\n")
21841 (line-beginning-position)))
21842 t)))
21843 ;; Do not change items indentation individually as it
21844 ;; might break the list as a whole. On the other
21845 ;; hand, when at a plain list, indent it as a whole.
21846 (cond ((eq type 'plain-list)
21847 (let ((offset (- ind (current-indentation))))
21848 (unless (zerop offset)
21849 (indent-rigidly (org-element-property :begin element)
21850 (org-element-property :end element)
21851 offset))
21852 (goto-char cbeg)))
21853 ((eq type 'item) (goto-char cbeg))
21854 (t (funcall indent-to ind (min cbeg end))))
21855 (when (< (point) end)
21856 (cl-case type
21857 ((example-block verse-block))
21858 (src-block
21859 ;; In a source block, indent source code
21860 ;; according to language major mode, but only if
21861 ;; `org-src-tab-acts-natively' is non-nil.
21862 (when (and (< (point) end) org-src-tab-acts-natively)
21863 (ignore-errors
21864 (org-babel-do-in-edit-buffer
21865 (indent-region (point-min) (point-max))))))
21866 (t (org-indent-region (point) (min cend end))))
21867 (goto-char (min cend end))
21868 (when (< (point) end)
21869 (funcall indent-to ind (min element-end end))))
21870 (set-marker post nil)
21871 (set-marker cbeg nil)
21872 (set-marker cend nil))))
21873 (set-marker element-end nil))))
21874 (set-marker end nil))))
21876 (defun org-indent-drawer ()
21877 "Indent the drawer at point."
21878 (interactive)
21879 (unless (save-excursion
21880 (beginning-of-line)
21881 (looking-at-p org-drawer-regexp))
21882 (user-error "Not at a drawer"))
21883 (let ((element (org-element-at-point)))
21884 (unless (memq (org-element-type element) '(drawer property-drawer))
21885 (user-error "Not at a drawer"))
21886 (org-with-wide-buffer
21887 (org-indent-region (org-element-property :begin element)
21888 (org-element-property :end element))))
21889 (message "Drawer at point indented"))
21891 (defun org-indent-block ()
21892 "Indent the block at point."
21893 (interactive)
21894 (unless (save-excursion
21895 (beginning-of-line)
21896 (let ((case-fold-search t))
21897 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21898 (user-error "Not at a block"))
21899 (let ((element (org-element-at-point)))
21900 (unless (memq (org-element-type element)
21901 '(comment-block center-block dynamic-block example-block
21902 export-block quote-block special-block
21903 src-block verse-block))
21904 (user-error "Not at a block"))
21905 (org-with-wide-buffer
21906 (org-indent-region (org-element-property :begin element)
21907 (org-element-property :end element))))
21908 (message "Block at point indented"))
21911 ;;; Filling
21913 ;; We use our own fill-paragraph and auto-fill functions.
21915 ;; `org-fill-paragraph' relies on adaptive filling and context
21916 ;; checking. Appropriate `fill-prefix' is computed with
21917 ;; `org-adaptive-fill-function'.
21919 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21920 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21921 ;; `org-adaptive-fill-function' value. Internally,
21922 ;; `org-comment-line-break-function' breaks the line.
21924 ;; `org-setup-filling' installs filling and auto-filling related
21925 ;; variables during `org-mode' initialization.
21927 (defun org-setup-filling ()
21928 (require 'org-element)
21929 ;; Prevent auto-fill from inserting unwanted new items.
21930 (when (boundp 'fill-nobreak-predicate)
21931 (setq-local
21932 fill-nobreak-predicate
21933 (org-uniquify
21934 (append fill-nobreak-predicate
21935 '(org-fill-line-break-nobreak-p
21936 org-fill-n-macro-as-item-nobreak-p
21937 org-fill-paragraph-with-timestamp-nobreak-p)))))
21938 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21939 (setq-local paragraph-start paragraph-ending)
21940 (setq-local paragraph-separate paragraph-ending))
21941 (setq-local fill-paragraph-function 'org-fill-paragraph)
21942 (setq-local auto-fill-inhibit-regexp nil)
21943 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21944 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21945 (setq-local comment-line-break-function 'org-comment-line-break-function))
21947 (defun org-fill-line-break-nobreak-p ()
21948 "Non-nil when a new line at point would create an Org line break."
21949 (save-excursion
21950 (skip-chars-backward "[ \t]")
21951 (skip-chars-backward "\\\\")
21952 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21954 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21955 "Non-nil when a new line at point would split a timestamp."
21956 (and (org-at-timestamp-p 'lax)
21957 (not (looking-at org-ts-regexp-both))))
21959 (defun org-fill-n-macro-as-item-nobreak-p ()
21960 "Non-nil when a new line at point would create a new list."
21961 ;; During export, a "n" macro followed by a dot or a closing
21962 ;; parenthesis can end up being parsed as a new list item.
21963 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21965 (defvar orgtbl-line-start-regexp) ; From org-table.el
21966 (defun org-adaptive-fill-function ()
21967 "Compute a fill prefix for the current line.
21968 Return fill prefix, as a string, or nil if current line isn't
21969 meant to be filled. For convenience, if `adaptive-fill-regexp'
21970 matches in paragraphs or comments, use it."
21971 (org-with-wide-buffer
21972 (unless (org-at-heading-p)
21973 (let* ((p (line-beginning-position))
21974 (element (save-excursion
21975 (beginning-of-line)
21976 (org-element-at-point)))
21977 (type (org-element-type element))
21978 (post-affiliated (org-element-property :post-affiliated element)))
21979 (unless (< p post-affiliated)
21980 (cl-case type
21981 (comment
21982 (save-excursion
21983 (beginning-of-line)
21984 (looking-at "[ \t]*")
21985 (concat (match-string 0) "# ")))
21986 (footnote-definition "")
21987 ((item plain-list)
21988 (make-string (org-list-item-body-column post-affiliated) ?\s))
21989 (paragraph
21990 ;; Fill prefix is usually the same as the current line,
21991 ;; unless the paragraph is at the beginning of an item.
21992 (let ((parent (org-element-property :parent element)))
21993 (save-excursion
21994 (beginning-of-line)
21995 (cond ((eq (org-element-type parent) 'item)
21996 (make-string (org-list-item-body-column
21997 (org-element-property :begin parent))
21998 ?\s))
21999 ((and adaptive-fill-regexp
22000 ;; Locally disable
22001 ;; `adaptive-fill-function' to let
22002 ;; `fill-context-prefix' handle
22003 ;; `adaptive-fill-regexp' variable.
22004 (let (adaptive-fill-function)
22005 (fill-context-prefix
22006 post-affiliated
22007 (org-element-property :end element)))))
22008 ((looking-at "[ \t]+") (match-string 0))
22009 (t "")))))
22010 (comment-block
22011 ;; Only fill contents if P is within block boundaries.
22012 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22013 (forward-line)
22014 (point)))
22015 (cend (save-excursion
22016 (goto-char (org-element-property :end element))
22017 (skip-chars-backward " \r\t\n")
22018 (line-beginning-position))))
22019 (when (and (>= p cbeg) (< p cend))
22020 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22021 (match-string 0)
22022 ""))))))))))
22024 (defun org-fill-element (&optional justify)
22025 "Fill element at point, when applicable.
22027 This function only applies to comment blocks, comments, example
22028 blocks and paragraphs. Also, as a special case, re-align table
22029 when point is at one.
22031 If JUSTIFY is non-nil (interactively, with prefix argument),
22032 justify as well. If `sentence-end-double-space' is non-nil, then
22033 period followed by one space does not end a sentence, so don't
22034 break a line there. The variable `fill-column' controls the
22035 width for filling.
22037 For convenience, when point is at a plain list, an item or
22038 a footnote definition, try to fill the first paragraph within."
22039 (with-syntax-table org-mode-transpose-word-syntax-table
22040 ;; Move to end of line in order to get the first paragraph within
22041 ;; a plain list or a footnote definition.
22042 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22043 ;; First check if point is in a blank line at the beginning of
22044 ;; the buffer. In that case, ignore filling.
22045 (cl-case (org-element-type element)
22046 ;; Use major mode filling function is source blocks.
22047 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22048 ;; Align Org tables, leave table.el tables as-is.
22049 (table-row (org-table-align) t)
22050 (table
22051 (when (eq (org-element-property :type element) 'org)
22052 (save-excursion
22053 (goto-char (org-element-property :post-affiliated element))
22054 (org-table-align)))
22056 (paragraph
22057 ;; Paragraphs may contain `line-break' type objects.
22058 (let ((beg (max (point-min)
22059 (org-element-property :contents-begin element)))
22060 (end (min (point-max)
22061 (org-element-property :contents-end element))))
22062 ;; Do nothing if point is at an affiliated keyword.
22063 (if (< (line-end-position) beg) t
22064 ;; Fill paragraph, taking line breaks into account.
22065 (save-excursion
22066 (goto-char beg)
22067 (let ((cuts (list beg)))
22068 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22069 (when (eq 'line-break
22070 (org-element-type
22071 (save-excursion (backward-char)
22072 (org-element-context))))
22073 (push (point) cuts)))
22074 (dolist (c (delq end cuts))
22075 (fill-region-as-paragraph c end justify)
22076 (setq end c))))
22077 t)))
22078 ;; Contents of `comment-block' type elements should be
22079 ;; filled as plain text, but only if point is within block
22080 ;; markers.
22081 (comment-block
22082 (let* ((case-fold-search t)
22083 (beg (save-excursion
22084 (goto-char (org-element-property :begin element))
22085 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22086 (forward-line)
22087 (point)))
22088 (end (save-excursion
22089 (goto-char (org-element-property :end element))
22090 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22091 (line-beginning-position))))
22092 (if (or (< (point) beg) (> (point) end)) t
22093 (fill-region-as-paragraph
22094 (save-excursion (end-of-line)
22095 (re-search-backward "^[ \t]*$" beg 'move)
22096 (line-beginning-position))
22097 (save-excursion (beginning-of-line)
22098 (re-search-forward "^[ \t]*$" end 'move)
22099 (line-beginning-position))
22100 justify))))
22101 ;; Fill comments.
22102 (comment
22103 (let ((begin (org-element-property :post-affiliated element))
22104 (end (org-element-property :end element)))
22105 (when (and (>= (point) begin) (<= (point) end))
22106 (let ((begin (save-excursion
22107 (end-of-line)
22108 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22109 (progn (forward-line) (point))
22110 begin)))
22111 (end (save-excursion
22112 (end-of-line)
22113 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22114 (1- (line-beginning-position))
22115 (skip-chars-backward " \r\t\n")
22116 (line-end-position)))))
22117 ;; Do not fill comments when at a blank line.
22118 (when (> end begin)
22119 (let ((fill-prefix
22120 (save-excursion
22121 (beginning-of-line)
22122 (looking-at "[ \t]*#")
22123 (let ((comment-prefix (match-string 0)))
22124 (goto-char (match-end 0))
22125 (if (looking-at adaptive-fill-regexp)
22126 (concat comment-prefix (match-string 0))
22127 (concat comment-prefix " "))))))
22128 (save-excursion
22129 (fill-region-as-paragraph begin end justify))))))
22131 ;; Ignore every other element.
22132 (otherwise t)))))
22134 (defun org-fill-paragraph (&optional justify region)
22135 "Fill element at point, when applicable.
22137 This function only applies to comment blocks, comments, example
22138 blocks and paragraphs. Also, as a special case, re-align table
22139 when point is at one.
22141 For convenience, when point is at a plain list, an item or
22142 a footnote definition, try to fill the first paragraph within.
22144 If JUSTIFY is non-nil (interactively, with prefix argument),
22145 justify as well. If `sentence-end-double-space' is non-nil, then
22146 period followed by one space does not end a sentence, so don't
22147 break a line there. The variable `fill-column' controls the
22148 width for filling.
22150 The REGION argument is non-nil if called interactively; in that
22151 case, if Transient Mark mode is enabled and the mark is active,
22152 fill each of the elements in the active region, instead of just
22153 filling the current element."
22154 (interactive (progn
22155 (barf-if-buffer-read-only)
22156 (list (when current-prefix-arg 'full) t)))
22157 (cond
22158 ((and region transient-mark-mode mark-active
22159 (not (eq (region-beginning) (region-end))))
22160 (let ((origin (point-marker))
22161 (start (region-beginning)))
22162 (unwind-protect
22163 (progn
22164 (goto-char (region-end))
22165 (while (> (point) start)
22166 (org-backward-paragraph)
22167 (org-fill-element justify)))
22168 (goto-char origin)
22169 (set-marker origin nil))))
22170 (t (org-fill-element justify))))
22172 (defun org-auto-fill-function ()
22173 "Auto-fill function."
22174 ;; Check if auto-filling is meaningful.
22175 (let ((fc (current-fill-column)))
22176 (when (and fc (> (current-column) fc))
22177 (let* ((fill-prefix (org-adaptive-fill-function))
22178 ;; Enforce empty fill prefix, if required. Otherwise, it
22179 ;; will be computed again.
22180 (adaptive-fill-mode (not (equal fill-prefix ""))))
22181 (when fill-prefix (do-auto-fill))))))
22183 (defun org-comment-line-break-function (&optional soft)
22184 "Break line at point and indent, continuing comment if within one.
22185 The inserted newline is marked hard if variable
22186 `use-hard-newlines' is true, unless optional argument SOFT is
22187 non-nil."
22188 (if soft (insert-and-inherit ?\n) (newline 1))
22189 (save-excursion (forward-char -1) (delete-horizontal-space))
22190 (delete-horizontal-space)
22191 (indent-to-left-margin)
22192 (insert-before-markers-and-inherit fill-prefix))
22195 ;;; Fixed Width Areas
22197 (defun org-toggle-fixed-width ()
22198 "Toggle fixed-width markup.
22200 Add or remove fixed-width markup on current line, whenever it
22201 makes sense. Return an error otherwise.
22203 If a region is active and if it contains only fixed-width areas
22204 or blank lines, remove all fixed-width markup in it. If the
22205 region contains anything else, convert all non-fixed-width lines
22206 to fixed-width ones.
22208 Blank lines at the end of the region are ignored unless the
22209 region only contains such lines."
22210 (interactive)
22211 (if (not (org-region-active-p))
22212 ;; No region:
22214 ;; Remove fixed width marker only in a fixed-with element.
22216 ;; Add fixed width maker in paragraphs, in blank lines after
22217 ;; elements or at the beginning of a headline or an inlinetask,
22218 ;; and before any one-line elements (e.g., a clock).
22219 (progn
22220 (beginning-of-line)
22221 (let* ((element (org-element-at-point))
22222 (type (org-element-type element)))
22223 (cond
22224 ((and (eq type 'fixed-width)
22225 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22226 (replace-match
22227 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22228 ((and (memq type '(babel-call clock comment diary-sexp headline
22229 horizontal-rule keyword paragraph
22230 planning))
22231 (<= (org-element-property :post-affiliated element) (point)))
22232 (skip-chars-forward " \t")
22233 (insert ": "))
22234 ((and (looking-at-p "[ \t]*$")
22235 (or (eq type 'inlinetask)
22236 (save-excursion
22237 (skip-chars-forward " \r\t\n")
22238 (<= (org-element-property :end element) (point)))))
22239 (delete-region (point) (line-end-position))
22240 (org-indent-line)
22241 (insert ": "))
22242 (t (user-error "Cannot insert a fixed-width line here")))))
22243 ;; Region active.
22244 (let* ((begin (save-excursion
22245 (goto-char (region-beginning))
22246 (line-beginning-position)))
22247 (end (copy-marker
22248 (save-excursion
22249 (goto-char (region-end))
22250 (unless (eolp) (beginning-of-line))
22251 (if (save-excursion (re-search-backward "\\S-" begin t))
22252 (progn (skip-chars-backward " \r\t\n") (point))
22253 (point)))))
22254 (all-fixed-width-p
22255 (catch 'not-all-p
22256 (save-excursion
22257 (goto-char begin)
22258 (skip-chars-forward " \r\t\n")
22259 (when (eobp) (throw 'not-all-p nil))
22260 (while (< (point) end)
22261 (let ((element (org-element-at-point)))
22262 (if (eq (org-element-type element) 'fixed-width)
22263 (goto-char (org-element-property :end element))
22264 (throw 'not-all-p nil))))
22265 t))))
22266 (if all-fixed-width-p
22267 (save-excursion
22268 (goto-char begin)
22269 (while (< (point) end)
22270 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22271 (replace-match
22272 "" nil nil nil
22273 (if (= (line-end-position) (match-end 0)) 0 1)))
22274 (forward-line)))
22275 (let ((min-ind (point-max)))
22276 ;; Find minimum indentation across all lines.
22277 (save-excursion
22278 (goto-char begin)
22279 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22280 (setq min-ind 0)
22281 (catch 'zerop
22282 (while (< (point) end)
22283 (unless (looking-at-p "[ \t]*$")
22284 (let ((ind (current-indentation)))
22285 (setq min-ind (min min-ind ind))
22286 (when (zerop ind) (throw 'zerop t))))
22287 (forward-line)))))
22288 ;; Loop over all lines and add fixed-width markup everywhere
22289 ;; but in fixed-width lines.
22290 (save-excursion
22291 (goto-char begin)
22292 (while (< (point) end)
22293 (cond
22294 ((org-at-heading-p)
22295 (insert ": ")
22296 (forward-line)
22297 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22298 (insert ":")
22299 (forward-line)))
22300 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22301 (let* ((element (org-element-at-point))
22302 (element-end (org-element-property :end element)))
22303 (if (eq (org-element-type element) 'fixed-width)
22304 (progn (goto-char element-end)
22305 (skip-chars-backward " \r\t\n")
22306 (forward-line))
22307 (let ((limit (min end element-end)))
22308 (while (< (point) limit)
22309 (org-move-to-column min-ind t)
22310 (insert ": ")
22311 (forward-line))))))
22313 (org-move-to-column min-ind t)
22314 (insert ": ")
22315 (forward-line)))))))
22316 (set-marker end nil))))
22319 ;;; Blocks
22321 (defun org-block-map (function &optional start end)
22322 "Call FUNCTION at the head of all source blocks in the current buffer.
22323 Optional arguments START and END can be used to limit the range."
22324 (let ((start (or start (point-min)))
22325 (end (or end (point-max))))
22326 (save-excursion
22327 (goto-char start)
22328 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22329 (save-excursion
22330 (save-match-data
22331 (goto-char (match-beginning 0))
22332 (funcall function)))))))
22334 (defun org-next-block (arg &optional backward block-regexp)
22335 "Jump to the next block.
22337 With a prefix argument ARG, jump forward ARG many blocks.
22339 When BACKWARD is non-nil, jump to the previous block.
22341 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22342 Match data is set according to this regexp when the function
22343 returns.
22345 Return point at beginning of the opening line of found block.
22346 Throw an error if no block is found."
22347 (interactive "p")
22348 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22349 (case-fold-search t)
22350 (search-fn (if backward #'re-search-backward #'re-search-forward))
22351 (count (or arg 1))
22352 (origin (point))
22353 last-element)
22354 (if backward (beginning-of-line) (end-of-line))
22355 (while (and (> count 0) (funcall search-fn re nil t))
22356 (let ((element (save-excursion
22357 (goto-char (match-beginning 0))
22358 (save-match-data (org-element-at-point)))))
22359 (when (and (memq (org-element-type element)
22360 '(center-block comment-block dynamic-block
22361 example-block export-block quote-block
22362 special-block src-block verse-block))
22363 (<= (match-beginning 0)
22364 (org-element-property :post-affiliated element)))
22365 (setq last-element element)
22366 (cl-decf count))))
22367 (if (= count 0)
22368 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22369 (save-match-data (org-show-context)))
22370 (goto-char origin)
22371 (user-error "No %s code blocks" (if backward "previous" "further")))))
22373 (defun org-previous-block (arg &optional block-regexp)
22374 "Jump to the previous block.
22375 With a prefix argument ARG, jump backward ARG many source blocks.
22376 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22377 (interactive "p")
22378 (org-next-block arg t block-regexp))
22381 ;;; Comments
22383 ;; Org comments syntax is quite complex. It requires the entire line
22384 ;; to be just a comment. Also, even with the right syntax at the
22385 ;; beginning of line, some elements (e.g., verse-block or
22386 ;; example-block) don't accept comments. Usual Emacs comment commands
22387 ;; cannot cope with those requirements. Therefore, Org replaces them.
22389 ;; Org still relies on `comment-dwim', but cannot trust
22390 ;; `comment-only-p'. So, `comment-region-function' and
22391 ;; `uncomment-region-function' both point
22392 ;; to`org-comment-or-uncomment-region'. Eventually,
22393 ;; `org-insert-comment' takes care of insertion of comments at the
22394 ;; beginning of line.
22396 ;; `org-setup-comments-handling' install comments related variables
22397 ;; during `org-mode' initialization.
22399 (defun org-setup-comments-handling ()
22400 (interactive)
22401 (setq-local comment-use-syntax nil)
22402 (setq-local comment-start "# ")
22403 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22404 (setq-local comment-insert-comment-function 'org-insert-comment)
22405 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22406 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22408 (defun org-insert-comment ()
22409 "Insert an empty comment above current line.
22410 If the line is empty, insert comment at its beginning. When
22411 point is within a source block, comment according to the related
22412 major mode."
22413 (if (let ((element (org-element-at-point)))
22414 (and (eq (org-element-type element) 'src-block)
22415 (< (save-excursion
22416 (goto-char (org-element-property :post-affiliated element))
22417 (line-end-position))
22418 (point))
22419 (> (save-excursion
22420 (goto-char (org-element-property :end element))
22421 (skip-chars-backward " \r\t\n")
22422 (line-beginning-position))
22423 (point))))
22424 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22425 (beginning-of-line)
22426 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22427 (open-line 1))
22428 (org-indent-line)
22429 (insert "# ")))
22431 (defvar comment-empty-lines) ; From newcomment.el.
22432 (defun org-comment-or-uncomment-region (beg end &rest _)
22433 "Comment or uncomment each non-blank line in the region.
22434 Uncomment each non-blank line between BEG and END if it only
22435 contains commented lines. Otherwise, comment them. If region is
22436 strictly within a source block, use appropriate comment syntax."
22437 (if (let ((element (org-element-at-point)))
22438 (and (eq (org-element-type element) 'src-block)
22439 (< (save-excursion
22440 (goto-char (org-element-property :post-affiliated element))
22441 (line-end-position))
22442 beg)
22443 (>= (save-excursion
22444 (goto-char (org-element-property :end element))
22445 (skip-chars-backward " \r\t\n")
22446 (line-beginning-position))
22447 end)))
22448 ;; Translate region boundaries for the Org buffer to the source
22449 ;; buffer.
22450 (let ((offset (- end beg)))
22451 (save-excursion
22452 (goto-char beg)
22453 (org-babel-do-in-edit-buffer
22454 (comment-or-uncomment-region (point) (+ offset (point))))))
22455 (save-restriction
22456 ;; Restrict region
22457 (narrow-to-region (save-excursion (goto-char beg)
22458 (skip-chars-forward " \r\t\n" end)
22459 (line-beginning-position))
22460 (save-excursion (goto-char end)
22461 (skip-chars-backward " \r\t\n" beg)
22462 (line-end-position)))
22463 (let ((uncommentp
22464 ;; UNCOMMENTP is non-nil when every non blank line between
22465 ;; BEG and END is a comment.
22466 (save-excursion
22467 (goto-char (point-min))
22468 (while (and (not (eobp))
22469 (let ((element (org-element-at-point)))
22470 (and (eq (org-element-type element) 'comment)
22471 (goto-char (min (point-max)
22472 (org-element-property
22473 :end element)))))))
22474 (eobp))))
22475 (if uncommentp
22476 ;; Only blank lines and comments in region: uncomment it.
22477 (save-excursion
22478 (goto-char (point-min))
22479 (while (not (eobp))
22480 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22481 (replace-match "" nil nil nil 1))
22482 (forward-line)))
22483 ;; Comment each line in region.
22484 (let ((min-indent (point-max)))
22485 ;; First find the minimum indentation across all lines.
22486 (save-excursion
22487 (goto-char (point-min))
22488 (while (and (not (eobp)) (not (zerop min-indent)))
22489 (unless (looking-at "[ \t]*$")
22490 (setq min-indent (min min-indent (current-indentation))))
22491 (forward-line)))
22492 ;; Then loop over all lines.
22493 (save-excursion
22494 (goto-char (point-min))
22495 (while (not (eobp))
22496 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22497 ;; Don't get fooled by invisible text (e.g. link path)
22498 ;; when moving to column MIN-INDENT.
22499 (let ((buffer-invisibility-spec nil))
22500 (org-move-to-column min-indent t))
22501 (insert comment-start))
22502 (forward-line)))))))))
22504 (defun org-comment-dwim (_arg)
22505 "Call the comment command you mean.
22506 Call `org-toggle-comment' if on a heading, otherwise call
22507 `comment-dwim', within a source edit buffer if needed."
22508 (interactive "*P")
22509 (cond ((org-at-heading-p)
22510 (call-interactively #'org-toggle-comment))
22511 ((org-in-src-block-p)
22512 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22513 (t (call-interactively #'comment-dwim))))
22516 ;;; Timestamps API
22518 ;; This section contains tools to operate on, or create, timestamp
22519 ;; objects, as returned by, e.g. `org-element-context'.
22521 (defun org-timestamp-from-string (s)
22522 "Convert Org timestamp S, as a string, into a timestamp object.
22523 Return nil if S is not a valid timestamp string."
22524 (when (org-string-nw-p s)
22525 (with-temp-buffer
22526 (save-excursion (insert s))
22527 (org-element-timestamp-parser))))
22529 (defun org-timestamp-from-time (time &optional with-time inactive)
22530 "Convert a time value into a timestamp object.
22532 TIME is an Emacs internal time representation, as returned, e.g.,
22533 by `current-time'.
22535 When optional argument WITH-TIME is non-nil, return a timestamp
22536 object with a time part, i.e., with hours and minutes.
22538 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22539 return an active timestamp."
22540 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22541 (org-element-create 'timestamp
22542 (list :type (if inactive 'inactive 'active)
22543 :year-start year
22544 :month-start month
22545 :day-start day
22546 :hour-start (and with-time hour)
22547 :minute-start (and with-time minute)))))
22549 (defun org-timestamp-to-time (timestamp &optional end)
22550 "Convert TIMESTAMP object into an Emacs internal time value.
22551 Use end of date range or time range when END is non-nil.
22552 Otherwise, use its start."
22553 (apply #'encode-time
22554 (cons 0
22555 (mapcar
22556 (lambda (prop) (or (org-element-property prop timestamp) 0))
22557 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22558 '(:minute-start :hour-start :day-start :month-start
22559 :year-start))))))
22561 (defun org-timestamp-has-time-p (timestamp)
22562 "Non-nil when TIMESTAMP has a time specified."
22563 (org-element-property :hour-start timestamp))
22565 (defun org-timestamp-format (timestamp format &optional end utc)
22566 "Format a TIMESTAMP object into a string.
22568 FORMAT is a format specifier to be passed to
22569 `format-time-string'.
22571 When optional argument END is non-nil, use end of date-range or
22572 time-range, if possible.
22574 When optional argument UTC is non-nil, time is be expressed as
22575 Universal Time."
22576 (format-time-string format (org-timestamp-to-time timestamp end)
22577 (and utc t)))
22579 (defun org-timestamp-split-range (timestamp &optional end)
22580 "Extract a TIMESTAMP object from a date or time range.
22582 END, when non-nil, means extract the end of the range.
22583 Otherwise, extract its start.
22585 Return a new timestamp object."
22586 (let ((type (org-element-property :type timestamp)))
22587 (if (memq type '(active inactive diary)) timestamp
22588 (let ((split-ts (org-element-copy timestamp)))
22589 ;; Set new type.
22590 (org-element-put-property
22591 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22592 ;; Copy start properties over end properties if END is
22593 ;; non-nil. Otherwise, copy end properties over `start' ones.
22594 (let ((p-alist '((:minute-start . :minute-end)
22595 (:hour-start . :hour-end)
22596 (:day-start . :day-end)
22597 (:month-start . :month-end)
22598 (:year-start . :year-end))))
22599 (dolist (p-cell p-alist)
22600 (org-element-put-property
22601 split-ts
22602 (funcall (if end #'car #'cdr) p-cell)
22603 (org-element-property
22604 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22605 ;; Eventually refresh `:raw-value'.
22606 (org-element-put-property split-ts :raw-value nil)
22607 (org-element-put-property
22608 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22610 (defun org-timestamp-translate (timestamp &optional boundary)
22611 "Translate TIMESTAMP object to custom format.
22613 Format string is defined in `org-time-stamp-custom-formats',
22614 which see.
22616 When optional argument BOUNDARY is non-nil, it is either the
22617 symbol `start' or `end'. In this case, only translate the
22618 starting or ending part of TIMESTAMP if it is a date or time
22619 range. Otherwise, translate both parts.
22621 Return timestamp as-is if `org-display-custom-times' is nil or if
22622 it has a `diary' type."
22623 (let ((type (org-element-property :type timestamp)))
22624 (if (or (not org-display-custom-times) (eq type 'diary))
22625 (org-element-interpret-data timestamp)
22626 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22627 org-time-stamp-custom-formats)))
22628 (if (and (not boundary) (memq type '(active-range inactive-range)))
22629 (concat (org-timestamp-format timestamp fmt)
22630 "--"
22631 (org-timestamp-format timestamp fmt t))
22632 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22634 ;;; Other stuff
22636 (defvar reftex-docstruct-symbol)
22637 (defvar org--rds)
22639 (defun org-reftex-citation ()
22640 "Use reftex-citation to insert a citation into the buffer.
22641 This looks for a line like
22643 #+BIBLIOGRAPHY: foo plain option:-d
22645 and derives from it that foo.bib is the bibliography file relevant
22646 for this document. It then installs the necessary environment for RefTeX
22647 to work in this buffer and calls `reftex-citation' to insert a citation
22648 into the buffer.
22650 Export of such citations to both LaTeX and HTML is handled by the contributed
22651 package ox-bibtex by Taru Karttunen."
22652 (interactive)
22653 (let ((reftex-docstruct-symbol 'org--rds)
22654 org--rds bib)
22655 (org-with-wide-buffer
22656 (let ((case-fold-search t)
22657 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22658 (if (not (save-excursion
22659 (or (re-search-forward re nil t)
22660 (re-search-backward re nil t))))
22661 (user-error "No bibliography defined in file")
22662 (setq bib (concat (match-string 1) ".bib")
22663 org--rds (list (list 'bib bib))))))
22664 (call-interactively 'reftex-citation)))
22666 ;;;; Functions extending outline functionality
22668 (defun org-beginning-of-line (&optional n)
22669 "Go to the beginning of the current visible line.
22671 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22672 symbol `reversed', on the first attempt move to where the
22673 headline text starts, and only move to beginning of line when the
22674 cursor is already before the start of the text of the headline.
22676 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22677 start of the text on the second attempt.
22679 With argument N not nil or 1, move forward N - 1 lines first."
22680 (interactive "^p")
22681 (let ((origin (point))
22682 (special (pcase org-special-ctrl-a/e
22683 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22684 deactivate-mark)
22685 ;; First move to a visible line.
22686 (if (bound-and-true-p visual-line-mode)
22687 (beginning-of-visual-line n)
22688 (move-beginning-of-line n)
22689 ;; `move-beginning-of-line' may leave point after invisible
22690 ;; characters if line starts with such of these (e.g., with
22691 ;; a link at column 0). Really move to the beginning of the
22692 ;; current visible line.
22693 (beginning-of-line))
22694 (cond
22695 ;; No special behavior. Point is already at the beginning of
22696 ;; a line, logical or visual.
22697 ((not special))
22698 ;; `beginning-of-visual-line' left point before logical beginning
22699 ;; of line: point is at the beginning of a visual line. Bail
22700 ;; out.
22701 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22702 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22703 ;; At a headline, special position is before the title, but
22704 ;; after any TODO keyword or priority cookie.
22705 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22706 (line-end-position)))
22707 (bol (point)))
22708 (if (eq special 'reversed)
22709 (when (and (= origin bol) (eq last-command this-command))
22710 (goto-char refpos))
22711 (when (or (> origin refpos) (= origin bol))
22712 (goto-char refpos)))))
22713 ((and (looking-at org-list-full-item-re)
22714 (memq (org-element-type (save-match-data (org-element-at-point)))
22715 '(item plain-list)))
22716 ;; Set special position at first white space character after
22717 ;; bullet, and check-box, if any.
22718 (let ((after-bullet
22719 (let ((box (match-end 3)))
22720 (cond ((not box) (match-end 1))
22721 ((eq (char-after box) ?\s) (1+ box))
22722 (t box)))))
22723 (if (eq special 'reversed)
22724 (when (and (= (point) origin) (eq last-command this-command))
22725 (goto-char after-bullet))
22726 (when (or (> origin after-bullet) (= (point) origin))
22727 (goto-char after-bullet)))))
22728 ;; No special context. Point is already at beginning of line.
22729 (t nil))))
22731 (defun org-end-of-line (&optional n)
22732 "Go to the end of the line, but before ellipsis, if any.
22734 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22735 symbol `reversed', ignore tags on the first attempt, and only
22736 move to after the tags when the cursor is already beyond the end
22737 of the headline.
22739 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22740 on the second attempt.
22742 With argument N not nil or 1, move forward N - 1 lines first."
22743 (interactive "^p")
22744 (let ((origin (point))
22745 (special (pcase org-special-ctrl-a/e
22746 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22747 deactivate-mark)
22748 ;; First move to a visible line.
22749 (if (bound-and-true-p visual-line-mode)
22750 (beginning-of-visual-line n)
22751 (move-beginning-of-line n))
22752 (cond
22753 ;; At a headline, with tags.
22754 ((and special
22755 (save-excursion
22756 (beginning-of-line)
22757 (let ((case-fold-search nil))
22758 (looking-at org-complex-heading-regexp)))
22759 (match-end 5))
22760 (let ((tags (save-excursion
22761 (goto-char (match-beginning 5))
22762 (skip-chars-backward " \t")
22763 (point)))
22764 (visual-end (and (bound-and-true-p visual-line-mode)
22765 (save-excursion
22766 (end-of-visual-line)
22767 (point)))))
22768 ;; If `end-of-visual-line' brings us before end of line or
22769 ;; even tags, i.e., the headline spans over multiple visual
22770 ;; lines, move there.
22771 (cond ((and visual-end
22772 (< visual-end tags)
22773 (<= origin visual-end))
22774 (goto-char visual-end))
22775 ((eq special 'reversed)
22776 (if (and (= origin (line-end-position))
22777 (eq this-command last-command))
22778 (goto-char tags)
22779 (end-of-line)))
22781 (if (or (< origin tags) (= origin (line-end-position)))
22782 (goto-char tags)
22783 (end-of-line))))))
22784 ((bound-and-true-p visual-line-mode)
22785 (let ((bol (line-beginning-position)))
22786 (end-of-visual-line)
22787 ;; If `end-of-visual-line' gets us past the ellipsis at the
22788 ;; end of a line, backtrack and use `end-of-line' instead.
22789 (when (/= bol (line-beginning-position))
22790 (goto-char bol)
22791 (end-of-line))))
22792 (t (end-of-line)))))
22794 (defun org-backward-sentence (&optional _arg)
22795 "Go to beginning of sentence, or beginning of table field.
22796 This will call `backward-sentence' or `org-table-beginning-of-field',
22797 depending on context."
22798 (interactive)
22799 (let* ((element (org-element-at-point))
22800 (contents-begin (org-element-property :contents-begin element))
22801 (table (org-element-lineage element '(table) t)))
22802 (if (and table
22803 (> (point) contents-begin)
22804 (<= (point) (org-element-property :contents-end table)))
22805 (call-interactively #'org-table-beginning-of-field)
22806 (save-restriction
22807 (when (and contents-begin
22808 (< (point-min) contents-begin)
22809 (> (point) contents-begin))
22810 (narrow-to-region contents-begin
22811 (org-element-property :contents-end element)))
22812 (call-interactively #'backward-sentence)))))
22814 (defun org-forward-sentence (&optional _arg)
22815 "Go to end of sentence, or end of table field.
22816 This will call `forward-sentence' or `org-table-end-of-field',
22817 depending on context."
22818 (interactive)
22819 (if (and (org-at-heading-p)
22820 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22821 (save-restriction
22822 (narrow-to-region (line-beginning-position) (line-end-position))
22823 (call-interactively #'forward-sentence))
22824 (let* ((element (org-element-at-point))
22825 (contents-end (org-element-property :contents-end element))
22826 (table (org-element-lineage element '(table) t)))
22827 (if (and table
22828 (>= (point) (org-element-property :contents-begin table))
22829 (< (point) contents-end))
22830 (call-interactively #'org-table-end-of-field)
22831 (save-restriction
22832 (when (and contents-end
22833 (> (point-max) contents-end)
22834 ;; Skip blank lines between elements.
22835 (< (org-element-property :end element)
22836 (save-excursion (goto-char contents-end)
22837 (skip-chars-forward " \r\t\n"))))
22838 (narrow-to-region (org-element-property :contents-begin element)
22839 contents-end))
22840 ;; End of heading is considered as the end of a sentence.
22841 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22842 (call-interactively #'forward-sentence)))))))
22844 (defun org-kill-line (&optional _arg)
22845 "Kill line, to tags or end of line."
22846 (interactive)
22847 (cond
22848 ((or (not org-special-ctrl-k)
22849 (bolp)
22850 (not (org-at-heading-p)))
22851 (when (and (get-char-property (line-end-position) 'invisible)
22852 org-ctrl-k-protect-subtree
22853 (or (eq org-ctrl-k-protect-subtree 'error)
22854 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22855 (user-error
22856 (substitute-command-keys
22857 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22858 (call-interactively
22859 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22860 ((org-match-line org-tag-line-re)
22861 (let ((end (save-excursion
22862 (goto-char (match-beginning 1))
22863 (skip-chars-backward " \t")
22864 (point))))
22865 (if (<= end (point)) ;on tags part
22866 (kill-region (point) (line-end-position))
22867 (kill-region (point) end)))
22868 (org-align-tags))
22869 (t (kill-region (point) (line-end-position)))))
22871 (defun org-yank (&optional arg)
22872 "Yank. If the kill is a subtree, treat it specially.
22873 This command will look at the current kill and check if is a single
22874 subtree, or a series of subtrees[1]. If it passes the test, and if the
22875 cursor is at the beginning of a line or after the stars of a currently
22876 empty headline, then the yank is handled specially. How exactly depends
22877 on the value of the following variables.
22879 `org-yank-folded-subtrees'
22880 By default, this variable is non-nil, which results in
22881 subtree(s) being folded after insertion, except if doing so
22882 would swallow text after the yanked text.
22884 `org-yank-adjusted-subtrees'
22885 When non-nil (the default value is nil), the subtree will be
22886 promoted or demoted in order to fit into the local outline tree
22887 structure, which means that the level will be adjusted so that it
22888 becomes the smaller one of the two *visible* surrounding headings.
22890 Any prefix to this command will cause `yank' to be called directly with
22891 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22892 will just
22893 plainly yank the text as it is.
22895 \[1] The test checks if the first non-white line is a heading
22896 and if there are no other headings with fewer stars."
22897 (interactive "P")
22898 (org-yank-generic 'yank arg))
22900 (defun org-yank-generic (command arg)
22901 "Perform some yank-like command.
22903 This function implements the behavior described in the `org-yank'
22904 documentation. However, it has been generalized to work for any
22905 interactive command with similar behavior."
22907 ;; pretend to be command COMMAND
22908 (setq this-command command)
22910 (if arg
22911 (call-interactively command)
22913 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22914 (and (org-kill-is-subtree-p)
22915 (or (bolp)
22916 (and (looking-at "[ \t]*$")
22917 (string-match
22918 "\\`\\*+\\'"
22919 (buffer-substring (point-at-bol) (point)))))))
22920 swallowp)
22921 (cond
22922 ((and subtreep org-yank-folded-subtrees)
22923 (let ((beg (point))
22924 end)
22925 (if (and subtreep org-yank-adjusted-subtrees)
22926 (org-paste-subtree nil nil 'for-yank)
22927 (call-interactively command))
22929 (setq end (point))
22930 (goto-char beg)
22931 (when (and (bolp) subtreep
22932 (not (setq swallowp
22933 (org-yank-folding-would-swallow-text beg end))))
22934 (org-with-limited-levels
22935 (or (looking-at org-outline-regexp)
22936 (re-search-forward org-outline-regexp-bol end t))
22937 (while (and (< (point) end) (looking-at org-outline-regexp))
22938 (outline-hide-subtree)
22939 (org-cycle-show-empty-lines 'folded)
22940 (condition-case nil
22941 (outline-forward-same-level 1)
22942 (error (goto-char end))))))
22943 (when swallowp
22944 (message
22945 "Inserted text not folded because that would swallow text"))
22947 (goto-char end)
22948 (skip-chars-forward " \t\n\r")
22949 (beginning-of-line 1)
22950 (push-mark beg 'nomsg)))
22951 ((and subtreep org-yank-adjusted-subtrees)
22952 (let ((beg (point-at-bol)))
22953 (org-paste-subtree nil nil 'for-yank)
22954 (push-mark beg 'nomsg)))
22956 (call-interactively command))))))
22958 (defun org-yank-folding-would-swallow-text (beg end)
22959 "Would hide-subtree at BEG swallow any text after END?"
22960 (let (level)
22961 (org-with-limited-levels
22962 (save-excursion
22963 (goto-char beg)
22964 (when (or (looking-at org-outline-regexp)
22965 (re-search-forward org-outline-regexp-bol end t))
22966 (setq level (org-outline-level)))
22967 (goto-char end)
22968 (skip-chars-forward " \t\r\n\v\f")
22969 (not (or (eobp)
22970 (and (bolp) (looking-at-p org-outline-regexp)
22971 (<= (org-outline-level) level))))))))
22973 (defun org-back-to-heading (&optional invisible-ok)
22974 "Call `outline-back-to-heading', but provide a better error message."
22975 (condition-case nil
22976 (outline-back-to-heading invisible-ok)
22977 (error (error "Before first headline at position %d in buffer %s"
22978 (point) (current-buffer)))))
22980 (defun org-before-first-heading-p ()
22981 "Before first heading?"
22982 (org-with-limited-levels
22983 (save-excursion
22984 (end-of-line)
22985 (null (re-search-backward org-outline-regexp-bol nil t)))))
22987 (defun org-at-heading-p (&optional _)
22988 "Non-nil when on a headline."
22989 (outline-on-heading-p t))
22991 (defun org-in-commented-heading-p (&optional no-inheritance)
22992 "Non-nil if point is under a commented heading.
22993 This function also checks ancestors of the current headline,
22994 unless optional argument NO-INHERITANCE is non-nil."
22995 (cond
22996 ((org-before-first-heading-p) nil)
22997 ((let ((headline (nth 4 (org-heading-components))))
22998 (and headline
22999 (let ((case-fold-search nil))
23000 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23001 headline)))))
23002 (no-inheritance nil)
23004 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23006 (defun org-at-comment-p nil
23007 "Is cursor in a commented line?"
23008 (save-excursion
23009 (save-match-data
23010 (beginning-of-line)
23011 (looking-at "^[ \t]*# "))))
23013 (defun org-at-drawer-p nil
23014 "Is cursor at a drawer keyword?"
23015 (save-excursion
23016 (move-beginning-of-line 1)
23017 (looking-at org-drawer-regexp)))
23019 (defun org-at-block-p nil
23020 "Is cursor at a block keyword?"
23021 (save-excursion
23022 (move-beginning-of-line 1)
23023 (looking-at org-block-regexp)))
23025 (defun org-point-at-end-of-empty-headline ()
23026 "If point is at the end of an empty headline, return t, else nil.
23027 If the heading only contains a TODO keyword, it is still still considered
23028 empty."
23029 (let ((case-fold-search nil))
23030 (and (looking-at "[ \t]*$")
23031 org-todo-line-regexp
23032 (save-excursion
23033 (beginning-of-line)
23034 (looking-at org-todo-line-regexp)
23035 (string= (match-string 3) "")))))
23037 (defun org-at-heading-or-item-p ()
23038 (or (org-at-heading-p) (org-at-item-p)))
23040 (defun org-at-target-p ()
23041 (or (org-in-regexp org-radio-target-regexp)
23042 (org-in-regexp org-target-regexp)))
23044 (defun org-up-heading-all (arg)
23045 "Move to the heading line of which the present line is a subheading.
23046 This function considers both visible and invisible heading lines.
23047 With argument, move up ARG levels."
23048 (outline-up-heading arg t))
23050 (defun org-up-heading-safe ()
23051 "Move to the heading line of which the present line is a subheading.
23052 This version will not throw an error. It will return the level of the
23053 headline found, or nil if no higher level is found.
23055 Also, this function will be a lot faster than `outline-up-heading',
23056 because it relies on stars being the outline starters. This can really
23057 make a significant difference in outlines with very many siblings."
23058 (when (ignore-errors (org-back-to-heading t))
23059 (let ((level-up (1- (funcall outline-level))))
23060 (and (> level-up 0)
23061 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23062 (funcall outline-level)))))
23064 (defun org-first-sibling-p ()
23065 "Is this heading the first child of its parents?"
23066 (interactive)
23067 (let ((re org-outline-regexp-bol)
23068 level l)
23069 (unless (org-at-heading-p t)
23070 (user-error "Not at a heading"))
23071 (setq level (funcall outline-level))
23072 (save-excursion
23073 (if (not (re-search-backward re nil t))
23075 (setq l (funcall outline-level))
23076 (< l level)))))
23078 (defun org-goto-sibling (&optional previous)
23079 "Goto the next sibling, even if it is invisible.
23080 When PREVIOUS is set, go to the previous sibling instead. Returns t
23081 when a sibling was found. When none is found, return nil and don't
23082 move point."
23083 (let ((fun (if previous 're-search-backward 're-search-forward))
23084 (pos (point))
23085 (re org-outline-regexp-bol)
23086 level l)
23087 (when (ignore-errors (org-back-to-heading t))
23088 (setq level (funcall outline-level))
23089 (catch 'exit
23090 (or previous (forward-char 1))
23091 (while (funcall fun re nil t)
23092 (setq l (funcall outline-level))
23093 (when (< l level) (goto-char pos) (throw 'exit nil))
23094 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23095 (goto-char pos)
23096 nil))))
23098 (defun org-show-siblings ()
23099 "Show all siblings of the current headline."
23100 (save-excursion
23101 (while (org-goto-sibling) (org-flag-heading nil)))
23102 (save-excursion
23103 (while (org-goto-sibling 'previous)
23104 (org-flag-heading nil))))
23106 (defun org-goto-first-child ()
23107 "Goto the first child, even if it is invisible.
23108 Return t when a child was found. Otherwise don't move point and
23109 return nil."
23110 (let (level (pos (point)) (re org-outline-regexp-bol))
23111 (when (ignore-errors (org-back-to-heading t))
23112 (setq level (outline-level))
23113 (forward-char 1)
23114 (if (and (re-search-forward re nil t) (> (outline-level) level))
23115 (progn (goto-char (match-beginning 0)) t)
23116 (goto-char pos) nil))))
23118 (defun org-show-hidden-entry ()
23119 "Show an entry where even the heading is hidden."
23120 (save-excursion
23121 (org-show-entry)))
23123 (defun org-flag-heading (flag &optional entry)
23124 "Flag the current heading. FLAG non-nil means make invisible.
23125 When ENTRY is non-nil, show the entire entry."
23126 (save-excursion
23127 (org-back-to-heading t)
23128 ;; Check if we should show the entire entry
23129 (if (not entry)
23130 (org-flag-region
23131 (line-end-position 0) (line-end-position) flag 'outline)
23132 (org-show-entry)
23133 (save-excursion
23134 (and (outline-next-heading)
23135 (org-flag-heading nil))))))
23137 (defun org-get-next-sibling ()
23138 "Move to next heading of the same level, and return point.
23139 If there is no such heading, return nil.
23140 This is like outline-next-sibling, but invisible headings are ok."
23141 (let ((level (funcall outline-level)))
23142 (outline-next-heading)
23143 (while (and (not (eobp)) (> (funcall outline-level) level))
23144 (outline-next-heading))
23145 (unless (or (eobp) (< (funcall outline-level) level))
23146 (point))))
23148 (defun org-get-last-sibling ()
23149 "Move to previous heading of the same level, and return point.
23150 If there is no such heading, return nil."
23151 (let ((opoint (point))
23152 (level (funcall outline-level)))
23153 (outline-previous-heading)
23154 (when (and (/= (point) opoint) (outline-on-heading-p t))
23155 (while (and (> (funcall outline-level) level)
23156 (not (bobp)))
23157 (outline-previous-heading))
23158 (unless (< (funcall outline-level) level)
23159 (point)))))
23161 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23162 "Goto to the end of a subtree."
23163 ;; This contains an exact copy of the original function, but it uses
23164 ;; `org-back-to-heading', to make it work also in invisible
23165 ;; trees. And is uses an invisible-ok argument.
23166 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23167 ;; Furthermore, when used inside Org, finding the end of a large subtree
23168 ;; with many children and grandchildren etc, this can be much faster
23169 ;; than the outline version.
23170 (org-back-to-heading invisible-ok)
23171 (let ((first t)
23172 (level (funcall outline-level)))
23173 (if (and (derived-mode-p 'org-mode) (< level 1000))
23174 ;; A true heading (not a plain list item), in Org
23175 ;; This means we can easily find the end by looking
23176 ;; only for the right number of stars. Using a regexp to do
23177 ;; this is so much faster than using a Lisp loop.
23178 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23179 (forward-char 1)
23180 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23181 ;; something else, do it the slow way
23182 (while (and (not (eobp))
23183 (or first (> (funcall outline-level) level)))
23184 (setq first nil)
23185 (outline-next-heading)))
23186 (unless to-heading
23187 (when (memq (preceding-char) '(?\n ?\^M))
23188 ;; Go to end of line before heading
23189 (forward-char -1)
23190 (when (memq (preceding-char) '(?\n ?\^M))
23191 ;; leave blank line before heading
23192 (forward-char -1)))))
23193 (point))
23195 (defun org-end-of-meta-data (&optional full)
23196 "Skip planning line and properties drawer in current entry.
23197 When optional argument FULL is non-nil, also skip empty lines,
23198 clocking lines and regular drawers at the beginning of the
23199 entry."
23200 (org-back-to-heading t)
23201 (forward-line)
23202 (when (looking-at-p org-planning-line-re) (forward-line))
23203 (when (looking-at org-property-drawer-re)
23204 (goto-char (match-end 0))
23205 (forward-line))
23206 (when (and full (not (org-at-heading-p)))
23207 (catch 'exit
23208 (let ((end (save-excursion (outline-next-heading) (point)))
23209 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23210 (while (not (eobp))
23211 (cond ((looking-at-p org-drawer-regexp)
23212 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23213 (forward-line)
23214 (throw 'exit t)))
23215 ((looking-at-p re) (forward-line))
23216 (t (throw 'exit t))))))))
23218 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23219 "Move forward to the ARG'th subheading at same level as this one.
23220 Stop at the first and last subheadings of a superior heading.
23221 Normally this only looks at visible headings, but when INVISIBLE-OK is
23222 non-nil it will also look at invisible ones."
23223 (interactive "p")
23224 (let ((backward? (and arg (< arg 0))))
23225 (if (org-before-first-heading-p)
23226 (if backward? (goto-char (point-min)) (outline-next-heading))
23227 (org-back-to-heading invisible-ok)
23228 (unless backward? (end-of-line)) ;do not match current headline
23229 (let ((level (- (match-end 0) (match-beginning 0) 1))
23230 (f (if backward? #'re-search-backward #'re-search-forward))
23231 (count (if arg (abs arg) 1))
23232 (result (point)))
23233 (while (and (> count 0)
23234 (funcall f org-outline-regexp-bol nil 'move))
23235 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23236 (cond ((< l level) (setq count 0))
23237 ((and (= l level)
23238 (or invisible-ok
23239 (not (org-invisible-p
23240 (line-beginning-position)))))
23241 (cl-decf count)
23242 (when (= l level) (setq result (point)))))))
23243 (goto-char result))
23244 (beginning-of-line))))
23246 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23247 "Move backward to the ARG'th subheading at same level as this one.
23248 Stop at the first and last subheadings of a superior heading."
23249 (interactive "p")
23250 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23252 (defun org-next-visible-heading (arg)
23253 "Move to the next visible heading.
23255 This function wraps `outline-next-visible-heading' with
23256 `org-with-limited-levels' in order to skip over inline tasks and
23257 respect customization of `org-odd-levels-only'."
23258 (interactive "p")
23259 (org-with-limited-levels
23260 (outline-next-visible-heading arg)))
23262 (defun org-previous-visible-heading (arg)
23263 "Move to the previous visible heading.
23265 This function wraps `outline-previous-visible-heading' with
23266 `org-with-limited-levels' in order to skip over inline tasks and
23267 respect customization of `org-odd-levels-only'."
23268 (interactive "p")
23269 (org-with-limited-levels
23270 (outline-previous-visible-heading arg)))
23272 (defun org-forward-paragraph ()
23273 "Move forward to beginning of next paragraph or equivalent.
23275 The function moves point to the beginning of the next visible
23276 structural element, which can be a paragraph, a table, a list
23277 item, etc. It also provides some special moves for convenience:
23279 - On an affiliated keyword, jump to the beginning of the
23280 relative element.
23281 - On an item or a footnote definition, move to the second
23282 element inside, if any.
23283 - On a table or a property drawer, jump after it.
23284 - On a verse or source block, stop after blank lines."
23285 (interactive)
23286 (unless (eobp)
23287 (let* ((deactivate-mark nil)
23288 (element (org-element-at-point))
23289 (type (org-element-type element))
23290 (post-affiliated (org-element-property :post-affiliated element))
23291 (contents-begin (org-element-property :contents-begin element))
23292 (contents-end (org-element-property :contents-end element))
23293 (end (let ((end (org-element-property :end element)) (parent element))
23294 (while (and (setq parent (org-element-property :parent parent))
23295 (= (org-element-property :contents-end parent) end))
23296 (setq end (org-element-property :end parent)))
23297 end)))
23298 (cond ((not element)
23299 (skip-chars-forward " \r\t\n")
23300 (or (eobp) (beginning-of-line)))
23301 ;; On affiliated keywords, move to element's beginning.
23302 ((< (point) post-affiliated)
23303 (goto-char post-affiliated))
23304 ;; At a table row, move to the end of the table. Similarly,
23305 ;; at a node property, move to the end of the property
23306 ;; drawer.
23307 ((memq type '(node-property table-row))
23308 (goto-char (org-element-property
23309 :end (org-element-property :parent element))))
23310 ((memq type '(property-drawer table)) (goto-char end))
23311 ;; Consider blank lines as separators in verse and source
23312 ;; blocks to ease editing.
23313 ((memq type '(src-block verse-block))
23314 (when (eq type 'src-block)
23315 (setq contents-end
23316 (save-excursion (goto-char end)
23317 (skip-chars-backward " \r\t\n")
23318 (line-beginning-position))))
23319 (beginning-of-line)
23320 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23321 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23322 (goto-char end)
23323 (skip-chars-forward " \r\t\n")
23324 (if (= (point) contents-end) (goto-char end)
23325 (beginning-of-line))))
23326 ;; With no contents, just skip element.
23327 ((not contents-begin) (goto-char end))
23328 ;; If contents are invisible, skip the element altogether.
23329 ((org-invisible-p (line-end-position))
23330 (cl-case type
23331 (headline
23332 (org-with-limited-levels (outline-next-visible-heading 1)))
23333 ;; At a plain list, make sure we move to the next item
23334 ;; instead of skipping the whole list.
23335 (plain-list (forward-char)
23336 (org-forward-paragraph))
23337 (otherwise (goto-char end))))
23338 ((>= (point) contents-end) (goto-char end))
23339 ((>= (point) contents-begin)
23340 ;; This can only happen on paragraphs and plain lists.
23341 (cl-case type
23342 (paragraph (goto-char end))
23343 ;; At a plain list, try to move to second element in
23344 ;; first item, if possible.
23345 (plain-list (end-of-line)
23346 (org-forward-paragraph))))
23347 ;; When contents start on the middle of a line (e.g. in
23348 ;; items and footnote definitions), try to reach first
23349 ;; element starting after current line.
23350 ((> (line-end-position) contents-begin)
23351 (end-of-line)
23352 (org-forward-paragraph))
23353 (t (goto-char contents-begin))))))
23355 (defun org-backward-paragraph ()
23356 "Move backward to start of previous paragraph or equivalent.
23358 The function moves point to the beginning of the current
23359 structural element, which can be a paragraph, a table, a list
23360 item, etc., or to the beginning of the previous visible one if
23361 point is already there. It also provides some special moves for
23362 convenience:
23364 - On an affiliated keyword, jump to the first one.
23365 - On a table or a property drawer, move to its beginning.
23366 - On comment, example, export, src and verse blocks, stop
23367 before blank lines."
23368 (interactive)
23369 (unless (bobp)
23370 (let* ((deactivate-mark nil)
23371 (element (org-element-at-point))
23372 (type (org-element-type element))
23373 (contents-end (org-element-property :contents-end element))
23374 (post-affiliated (org-element-property :post-affiliated element))
23375 (begin (org-element-property :begin element))
23376 (special? ;blocks handled specially
23377 (memq type '(comment-block example-block export-block src-block
23378 verse-block)))
23379 (contents-begin
23380 (if special?
23381 ;; These types have no proper contents. Fake line
23382 ;; below the block opening line as contents beginning.
23383 (save-excursion (goto-char begin) (line-beginning-position 2))
23384 (org-element-property :contents-begin element))))
23385 (cond
23386 ((not element) (goto-char (point-min)))
23387 ((= (point) begin)
23388 (backward-char)
23389 (org-backward-paragraph))
23390 ((<= (point) post-affiliated) (goto-char begin))
23391 ;; Special behavior: on a table or a property drawer, move to
23392 ;; its beginning.
23393 ((memq type '(node-property table-row))
23394 (goto-char (org-element-property
23395 :post-affiliated (org-element-property :parent element))))
23396 (special?
23397 (if (<= (point) contents-begin) (goto-char post-affiliated)
23398 ;; Inside a verse block, see blank lines as paragraph
23399 ;; separators.
23400 (let ((origin (point)))
23401 (skip-chars-backward " \r\t\n" contents-begin)
23402 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23403 (skip-chars-forward " \r\t\n" origin)
23404 (if (= (point) origin) (goto-char contents-begin)
23405 (beginning-of-line))))))
23406 ((eq type 'paragraph) (goto-char contents-begin)
23407 ;; When at first paragraph in an item or a footnote definition,
23408 ;; move directly to beginning of line.
23409 (let ((parent-contents
23410 (org-element-property
23411 :contents-begin (org-element-property :parent element))))
23412 (when (and parent-contents (= parent-contents contents-begin))
23413 (beginning-of-line))))
23414 ;; At the end of a greater element, move to the beginning of
23415 ;; the last element within.
23416 ((and contents-end (>= (point) contents-end))
23417 (goto-char (1- contents-end))
23418 (org-backward-paragraph))
23419 (t (goto-char (or post-affiliated begin))))
23420 ;; Ensure we never leave point invisible.
23421 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23423 (defun org-forward-element ()
23424 "Move forward by one element.
23425 Move to the next element at the same level, when possible."
23426 (interactive)
23427 (cond ((eobp) (user-error "Cannot move further down"))
23428 ((org-with-limited-levels (org-at-heading-p))
23429 (let ((origin (point)))
23430 (goto-char (org-end-of-subtree nil t))
23431 (unless (org-with-limited-levels (org-at-heading-p))
23432 (goto-char origin)
23433 (user-error "Cannot move further down"))))
23435 (let* ((elem (org-element-at-point))
23436 (end (org-element-property :end elem))
23437 (parent (org-element-property :parent elem)))
23438 (cond ((and parent (= (org-element-property :contents-end parent) end))
23439 (goto-char (org-element-property :end parent)))
23440 ((integer-or-marker-p end) (goto-char end))
23441 (t (message "No element at point")))))))
23443 (defun org-backward-element ()
23444 "Move backward by one element.
23445 Move to the previous element at the same level, when possible."
23446 (interactive)
23447 (cond ((bobp) (user-error "Cannot move further up"))
23448 ((org-with-limited-levels (org-at-heading-p))
23449 ;; At a headline, move to the previous one, if any, or stay
23450 ;; here.
23451 (let ((origin (point)))
23452 (org-with-limited-levels (org-backward-heading-same-level 1))
23453 ;; When current headline has no sibling above, move to its
23454 ;; parent.
23455 (when (= (point) origin)
23456 (or (org-with-limited-levels (org-up-heading-safe))
23457 (progn (goto-char origin)
23458 (user-error "Cannot move further up"))))))
23460 (let* ((elem (org-element-at-point))
23461 (beg (org-element-property :begin elem)))
23462 (cond
23463 ;; Move to beginning of current element if point isn't
23464 ;; there already.
23465 ((null beg) (message "No element at point"))
23466 ((/= (point) beg) (goto-char beg))
23467 (t (goto-char beg)
23468 (skip-chars-backward " \r\t\n")
23469 (unless (bobp)
23470 (let ((prev (org-element-at-point)))
23471 (goto-char (org-element-property :begin prev))
23472 (while (and (setq prev (org-element-property :parent prev))
23473 (<= (org-element-property :end prev) beg))
23474 (goto-char (org-element-property :begin prev)))))))))))
23476 (defun org-up-element ()
23477 "Move to upper element."
23478 (interactive)
23479 (if (org-with-limited-levels (org-at-heading-p))
23480 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23481 (let* ((elem (org-element-at-point))
23482 (parent (org-element-property :parent elem)))
23483 (if parent (goto-char (org-element-property :begin parent))
23484 (if (org-with-limited-levels (org-before-first-heading-p))
23485 (user-error "No surrounding element")
23486 (org-with-limited-levels (org-back-to-heading)))))))
23488 (defun org-down-element ()
23489 "Move to inner element."
23490 (interactive)
23491 (let ((element (org-element-at-point)))
23492 (cond
23493 ((memq (org-element-type element) '(plain-list table))
23494 (goto-char (org-element-property :contents-begin element))
23495 (forward-char))
23496 ((memq (org-element-type element) org-element-greater-elements)
23497 ;; If contents are hidden, first disclose them.
23498 (when (org-invisible-p (line-end-position)) (org-cycle))
23499 (goto-char (or (org-element-property :contents-begin element)
23500 (user-error "No content for this element"))))
23501 (t (user-error "No inner element")))))
23503 (defun org-drag-element-backward ()
23504 "Move backward element at point."
23505 (interactive)
23506 (let ((elem (or (org-element-at-point)
23507 (user-error "No element at point"))))
23508 (if (eq (org-element-type elem) 'headline)
23509 ;; Preserve point when moving a whole tree, even if point was
23510 ;; on blank lines below the headline.
23511 (let ((offset (skip-chars-backward " \t\n")))
23512 (unwind-protect (org-move-subtree-up)
23513 (forward-char (- offset))))
23514 (let ((prev-elem
23515 (save-excursion
23516 (goto-char (org-element-property :begin elem))
23517 (skip-chars-backward " \r\t\n")
23518 (unless (bobp)
23519 (let* ((beg (org-element-property :begin elem))
23520 (prev (org-element-at-point))
23521 (up prev))
23522 (while (and (setq up (org-element-property :parent up))
23523 (<= (org-element-property :end up) beg))
23524 (setq prev up))
23525 prev)))))
23526 ;; Error out if no previous element or previous element is
23527 ;; a parent of the current one.
23528 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23529 (user-error "Cannot drag element backward")
23530 (let ((pos (point)))
23531 (org-element-swap-A-B prev-elem elem)
23532 (goto-char (+ (org-element-property :begin prev-elem)
23533 (- pos (org-element-property :begin elem))))))))))
23535 (defun org-drag-element-forward ()
23536 "Move forward element at point."
23537 (interactive)
23538 (let* ((pos (point))
23539 (elem (or (org-element-at-point)
23540 (user-error "No element at point"))))
23541 (when (= (point-max) (org-element-property :end elem))
23542 (user-error "Cannot drag element forward"))
23543 (goto-char (org-element-property :end elem))
23544 (let ((next-elem (org-element-at-point)))
23545 (when (or (org-element-nested-p elem next-elem)
23546 (and (eq (org-element-type next-elem) 'headline)
23547 (not (eq (org-element-type elem) 'headline))))
23548 (goto-char pos)
23549 (user-error "Cannot drag element forward"))
23550 ;; Compute new position of point: it's shifted by NEXT-ELEM
23551 ;; body's length (without final blanks) and by the length of
23552 ;; blanks between ELEM and NEXT-ELEM.
23553 (let ((size-next (- (save-excursion
23554 (goto-char (org-element-property :end next-elem))
23555 (skip-chars-backward " \r\t\n")
23556 (forward-line)
23557 ;; Small correction if buffer doesn't end
23558 ;; with a newline character.
23559 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23560 (org-element-property :begin next-elem)))
23561 (size-blank (- (org-element-property :end elem)
23562 (save-excursion
23563 (goto-char (org-element-property :end elem))
23564 (skip-chars-backward " \r\t\n")
23565 (forward-line)
23566 (point)))))
23567 (org-element-swap-A-B elem next-elem)
23568 (goto-char (+ pos size-next size-blank))))))
23570 (defun org-drag-line-forward (arg)
23571 "Drag the line at point ARG lines forward."
23572 (interactive "p")
23573 (dotimes (_ (abs arg))
23574 (let ((c (current-column)))
23575 (if (< 0 arg)
23576 (progn
23577 (beginning-of-line 2)
23578 (transpose-lines 1)
23579 (beginning-of-line 0))
23580 (transpose-lines 1)
23581 (beginning-of-line -1))
23582 (org-move-to-column c))))
23584 (defun org-drag-line-backward (arg)
23585 "Drag the line at point ARG lines backward."
23586 (interactive "p")
23587 (org-drag-line-forward (- arg)))
23589 (defun org-mark-element ()
23590 "Put point at beginning of this element, mark at end.
23592 Interactively, if this command is repeated or (in Transient Mark
23593 mode) if the mark is active, it marks the next element after the
23594 ones already marked."
23595 (interactive)
23596 (let (deactivate-mark)
23597 (if (and (called-interactively-p 'any)
23598 (or (and (eq last-command this-command) (mark t))
23599 (and transient-mark-mode mark-active)))
23600 (set-mark
23601 (save-excursion
23602 (goto-char (mark))
23603 (goto-char (org-element-property :end (org-element-at-point)))))
23604 (let ((element (org-element-at-point)))
23605 (end-of-line)
23606 (push-mark (org-element-property :end element) t t)
23607 (goto-char (org-element-property :begin element))))))
23609 (defun org-narrow-to-element ()
23610 "Narrow buffer to current element."
23611 (interactive)
23612 (let ((elem (org-element-at-point)))
23613 (cond
23614 ((eq (car elem) 'headline)
23615 (narrow-to-region
23616 (org-element-property :begin elem)
23617 (org-element-property :end elem)))
23618 ((memq (car elem) org-element-greater-elements)
23619 (narrow-to-region
23620 (org-element-property :contents-begin elem)
23621 (org-element-property :contents-end elem)))
23623 (narrow-to-region
23624 (org-element-property :begin elem)
23625 (org-element-property :end elem))))))
23627 (defun org-transpose-element ()
23628 "Transpose current and previous elements, keeping blank lines between.
23629 Point is moved after both elements."
23630 (interactive)
23631 (org-skip-whitespace)
23632 (let ((end (org-element-property :end (org-element-at-point))))
23633 (org-drag-element-backward)
23634 (goto-char end)))
23636 (defun org-unindent-buffer ()
23637 "Un-indent the visible part of the buffer.
23638 Relative indentation (between items, inside blocks, etc.) isn't
23639 modified."
23640 (interactive)
23641 (unless (eq major-mode 'org-mode)
23642 (user-error "Cannot un-indent a buffer not in Org mode"))
23643 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23644 (unindent-tree
23645 (lambda (contents)
23646 (dolist (element (reverse contents))
23647 (if (memq (org-element-type element) '(headline section))
23648 (funcall unindent-tree (org-element-contents element))
23649 (save-excursion
23650 (save-restriction
23651 (narrow-to-region
23652 (org-element-property :begin element)
23653 (org-element-property :end element))
23654 (org-do-remove-indentation))))))))
23655 (funcall unindent-tree (org-element-contents parse-tree))))
23657 (defun org-make-options-regexp (kwds &optional extra)
23658 "Make a regular expression for keyword lines.
23659 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23660 when non-nil, is a regexp matching keywords names."
23661 (concat "^[ \t]*#\\+\\("
23662 (regexp-opt kwds)
23663 (and extra (concat (and kwds "\\|") extra))
23664 "\\):[ \t]*\\(.*\\)"))
23667 ;;; Conveniently switch to Info nodes
23669 (defun org-info-find-node (&optional nodename)
23670 "Find Info documentation NODENAME or Org documentation according context.
23671 Started from `gnus-info-find-node'."
23672 (interactive)
23673 (Info-goto-node
23674 (or nodename
23675 (let ((default-org-info-node "(org) Top"))
23676 (cond
23677 ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
23678 ((eq 'org-mode major-mode)
23679 (let* ((context (org-element-at-point))
23680 (element-info-nodes ; compare to `org-element-all-elements'.
23681 `((babel-call . "(org) Evaluating Code Blocks")
23682 (center-block . "(org) Paragraphs")
23683 (clock . ,default-org-info-node)
23684 (comment . "(org) Comment Lines")
23685 (comment-block . "(org) Comment Lines")
23686 (diary-sexp . ,default-org-info-node)
23687 (drawer . "(org) Drawers")
23688 (dynamic-block . "(org) Dynamic Blocks")
23689 (example-block . "(org) Literal Examples")
23690 (export-block . "(org) ASCII/Latin-1/UTF-8 export")
23691 (fixed-width . ,default-org-info-node)
23692 (footnote-definition . "(org) Creating Footnotes")
23693 (headline . "(org) Document Structure")
23694 (horizontal-rule . "(org) Built-in Table Editor")
23695 (inlinetask . ,default-org-info-node)
23696 (item . "(org) Plain Lists")
23697 (keyword . "(org) Per-file keywords")
23698 (latex-environment . "(org) LaTeX Export")
23699 (node-property . "(org) Properties and Columns")
23700 (paragraph . "(org) Paragraphs")
23701 (plain-list . "(org) Plain Lists")
23702 (planning . "(org) Deadlines and Scheduling")
23703 (property-drawer . "(org) Properties and Columns")
23704 (quote-block . "(org) Paragraphs")
23705 (section . ,default-org-info-node)
23706 (special-block . ,default-org-info-node)
23707 (src-block . "(org) Working with Source Code")
23708 (table . "(org) Tables")
23709 (table-row . "(org) Tables")
23710 (verse-block . "(org) Paragraphs"))))
23711 (or (cdr (assoc (car context) element-info-nodes))
23712 default-org-info-node)))
23713 (t default-org-info-node))))))
23716 ;;; Finish up
23718 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23719 (lambda () (add-hook 'change-major-mode-hook
23720 'org-show-all 'append 'local)))
23722 (provide 'org)
23724 (run-hooks 'org-load-hook)
23726 ;;; org.el ends here