test files: use cl- prefixed functions, and require cl-lib
[org-mode/org-tableheadings.git] / lisp / org.el
blob2cfe4669748526ff2e4fd069432af04442724e80
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.1.13
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 isearch-no-upper-case-p "isearch" (string regexp-flag))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
119 (declare-function org-archive-subtree "org-archive" (&optional find-done))
120 (declare-function org-archive-subtree-default "org-archive" ())
121 (declare-function org-archive-to-archive-sibling "org-archive" ())
122 (declare-function org-attach "org-attach" ())
123 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
124 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
125 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
126 (declare-function org-clock-cancel "org-clock" ())
127 (declare-function org-clock-display "org-clock" (&optional arg))
128 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
129 (declare-function org-clock-goto "org-clock" (&optional select))
130 (declare-function org-clock-in "org-clock" (&optional select start-time))
131 (declare-function org-clock-in-last "org-clock" (&optional arg))
132 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
133 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
134 (declare-function org-clock-report "org-clock" (&optional arg))
135 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
136 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
137 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
138 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
139 (declare-function org-clock-update-time-maybe "org-clock" ())
140 (declare-function org-clocking-buffer "org-clock" ())
141 (declare-function org-clocktable-shift "org-clock" (dir n))
142 (declare-function org-columns-insert-dblock "org-colview" ())
143 (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
144 (declare-function org-element-at-point "org-element" ())
145 (declare-function org-element-cache-refresh "org-element" (pos))
146 (declare-function org-element-cache-reset "org-element" (&optional all))
147 (declare-function org-element-contents "org-element" (element))
148 (declare-function org-element-context "org-element" (&optional element))
149 (declare-function org-element-copy "org-element" (datum))
150 (declare-function org-element-create "org-element" (type &optional props &rest children))
151 (declare-function org-element-interpret-data "org-element" (data))
152 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
153 (declare-function org-element-link-parser "org-element" ())
154 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
155 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
156 (declare-function org-element-property "org-element" (property element))
157 (declare-function org-element-put-property "org-element" (element property value))
158 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
159 (declare-function org-element-timestamp-parser "org-element" ())
160 (declare-function org-element-type "org-element" (element))
161 (declare-function org-element-update-syntax "org-element" ())
162 (declare-function org-export-dispatch "ox" (&optional arg))
163 (declare-function org-export-get-backend "ox" (name))
164 (declare-function org-export-get-backend "ox" (name))
165 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
166 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
167 (declare-function org-feed-goto-inbox "org-feed" (feed))
168 (declare-function org-feed-update-all "org-feed" ())
169 (declare-function org-goto "org-goto" (&optional alternative-interface))
170 (declare-function org-goto "org-goto" (&optional alternative-interface))
171 (declare-function org-id-find-id-file "org-id" (id))
172 (declare-function org-id-get-create "org-id" (&optional force))
173 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
174 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
175 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
176 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
177 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
178 (declare-function org-plot/gnuplot "org-plot" (&optional params))
179 (declare-function org-table--shrunk-field "org-table" ()) ;; For `org-table-with-shrunk-field'.
180 (declare-function org-table-align "org-table" ())
181 (declare-function org-table-begin "org-table" (&optional table-type))
182 (declare-function org-table-beginning-of-field "org-table" (&optional n))
183 (declare-function org-table-blank-field "org-table" ())
184 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
185 (declare-function org-table-copy-down "org-table" (N))
186 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
187 (declare-function org-table-create-or-convert-from-region "org-table" (arg))
188 (declare-function org-table-create-with-table.el "org-table" ())
189 (declare-function org-table-cut-region "org-table" (beg end))
190 (declare-function org-table-edit-field "org-table" (arg))
191 (declare-function org-table-end "org-table" (&optional table-type))
192 (declare-function org-table-end-of-field "org-table" (&optional n))
193 (declare-function org-table-eval-formula "org-table" (&optional arg equation suppress-align suppress-const suppress-store suppress-analysis))
194 (declare-function org-table-field-info "org-table" (arg))
195 (declare-function org-table-insert-row "org-table" (&optional arg))
196 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
197 (declare-function org-table-maybe-eval-formula "org-table" ())
198 (declare-function org-table-maybe-recalculate-line "org-table" ())
199 (declare-function org-table-next-row "org-table" ())
200 (declare-function org-table-paste-rectangle "org-table" ())
201 (declare-function org-table-recalculate "org-table" (&optional all noalign))
202 (declare-function org-table-rotate-recalc-marks "org-table" (&optional newchar))
203 (declare-function org-table-shrink "org-table" (&optional begin end))
204 (declare-function org-table-sort-lines "org-table" (&optional with-case sorting-type getkey-func compare-func interactive?))
205 (declare-function org-table-sum "org-table" (&optional beg end nlast))
206 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
207 (declare-function org-table-toggle-coordinate-overlays "org-table" ())
208 (declare-function org-table-toggle-formula-debugger "org-table" ())
209 (declare-function org-table-wrap-region "org-table" (arg))
210 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
211 (declare-function org-timer "org-timer" (&optional restart no-insert))
212 (declare-function org-timer-item "org-timer" (&optional arg))
213 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
214 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
215 (declare-function org-timer-set-timer "org-timer" (&optional opt))
216 (declare-function org-timer-start "org-timer" (&optional offset))
217 (declare-function org-timer-stop "org-timer" ())
218 (declare-function org-timer-stop "org-timer" ())
219 (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
220 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
221 (declare-function orgtbl-mode "org-table" (&optional arg))
223 (defvar ffap-url-regexp)
224 (defvar org-element-paragraph-separate)
225 (defvar org-indent-indentation-per-level)
227 ;; load languages based on value of `org-babel-load-languages'
228 (defvar org-babel-load-languages)
230 ;;;###autoload
231 (defun org-babel-do-load-languages (sym value)
232 "Load the languages defined in `org-babel-load-languages'."
233 (set-default sym value)
234 (dolist (pair org-babel-load-languages)
235 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
236 (if active
237 (require (intern (concat "ob-" lang)))
238 (fmakunbound
239 (intern (concat "org-babel-execute:" lang)))
240 (fmakunbound
241 (intern (concat "org-babel-expand-body:" lang)))))))
243 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
244 ;;;###autoload
245 (defun org-babel-load-file (file &optional compile)
246 "Load Emacs Lisp source code blocks in the Org FILE.
247 This function exports the source code using `org-babel-tangle'
248 and then loads the resulting file using `load-file'. With prefix
249 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
250 file to byte-code before it is loaded."
251 (interactive "fFile to load: \nP")
252 (let* ((age (lambda (file)
253 (float-time
254 (time-subtract (current-time)
255 (nth 5 (or (file-attributes (file-truename file))
256 (file-attributes file)))))))
257 (base-name (file-name-sans-extension file))
258 (exported-file (concat base-name ".el")))
259 ;; tangle if the Org file is newer than the elisp file
260 (unless (and (file-exists-p exported-file)
261 (> (funcall age file) (funcall age exported-file)))
262 ;; Tangle-file traversal returns reversed list of tangled files
263 ;; and we want to evaluate the first target.
264 (setq exported-file
265 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
266 (message "%s %s"
267 (if compile
268 (progn (byte-compile-file exported-file 'load)
269 "Compiled and loaded")
270 (progn (load-file exported-file) "Loaded"))
271 exported-file)))
273 (defcustom org-babel-load-languages '((emacs-lisp . t))
274 "Languages which can be evaluated in Org buffers.
275 \\<org-mode-map>
276 This list can be used to load support for any of the languages
277 below. Each language will depend on a different set of system
278 executables and/or Emacs modes.
280 When a language is \"loaded\", code blocks in that language can
281 be evaluated with `org-babel-execute-src-block', which is bound
282 by default to \\[org-ctrl-c-ctrl-c].
284 The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
285 remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
286 default, only Emacs Lisp is loaded, since it has no specific
287 requirement."
288 :group 'org-babel
289 :set 'org-babel-do-load-languages
290 :version "24.1"
291 :type '(alist :tag "Babel Languages"
292 :key-type
293 (choice
294 (const :tag "Awk" awk)
295 (const :tag "C" C)
296 (const :tag "R" R)
297 (const :tag "Asymptote" asymptote)
298 (const :tag "Calc" calc)
299 (const :tag "Clojure" clojure)
300 (const :tag "CSS" css)
301 (const :tag "Ditaa" ditaa)
302 (const :tag "Dot" dot)
303 (const :tag "Ebnf2ps" ebnf2ps)
304 (const :tag "Emacs Lisp" emacs-lisp)
305 (const :tag "Forth" forth)
306 (const :tag "Fortran" fortran)
307 (const :tag "Gnuplot" gnuplot)
308 (const :tag "Haskell" haskell)
309 (const :tag "hledger" hledger)
310 (const :tag "IO" io)
311 (const :tag "J" J)
312 (const :tag "Java" java)
313 (const :tag "Javascript" js)
314 (const :tag "LaTeX" latex)
315 (const :tag "Ledger" ledger)
316 (const :tag "Lilypond" lilypond)
317 (const :tag "Lisp" lisp)
318 (const :tag "Makefile" makefile)
319 (const :tag "Maxima" maxima)
320 (const :tag "Matlab" matlab)
321 (const :tag "Mscgen" mscgen)
322 (const :tag "Ocaml" ocaml)
323 (const :tag "Octave" octave)
324 (const :tag "Org" org)
325 (const :tag "Perl" perl)
326 (const :tag "Pico Lisp" picolisp)
327 (const :tag "PlantUML" plantuml)
328 (const :tag "Python" python)
329 (const :tag "Ruby" ruby)
330 (const :tag "Sass" sass)
331 (const :tag "Scala" scala)
332 (const :tag "Scheme" scheme)
333 (const :tag "Screen" screen)
334 (const :tag "Shell Script" shell)
335 (const :tag "Shen" shen)
336 (const :tag "Sql" sql)
337 (const :tag "Sqlite" sqlite)
338 (const :tag "Stan" stan)
339 (const :tag "Vala" vala))
340 :value-type (boolean :tag "Activate" :value t)))
342 ;;;; Customization variables
343 (defcustom org-clone-delete-id nil
344 "Remove ID property of clones of a subtree.
345 When non-nil, clones of a subtree don't inherit the ID property.
346 Otherwise they inherit the ID property with a new unique
347 identifier."
348 :type 'boolean
349 :version "24.1"
350 :group 'org-id)
352 ;;; Version
353 (org-check-version)
355 ;;;###autoload
356 (defun org-version (&optional here full message)
357 "Show the Org version.
358 Interactively, or when MESSAGE is non-nil, show it in echo area.
359 With prefix argument, or when HERE is non-nil, insert it at point.
360 In non-interactive uses, a reduced version string is output unless
361 FULL is given."
362 (interactive (list current-prefix-arg t (not current-prefix-arg)))
363 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
364 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
365 (load-suffixes (list ".el"))
366 (org-install-dir
367 (ignore-errors (org-find-library-dir "org-loaddefs"))))
368 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
369 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
370 (let* ((load-suffixes save-load-suffixes)
371 (release (org-release))
372 (git-version (org-git-version))
373 (version (format "Org mode version %s (%s @ %s)"
374 release
375 git-version
376 (if org-install-dir
377 (if (string= org-dir org-install-dir)
378 org-install-dir
379 (concat "mixed installation! "
380 org-install-dir
381 " and "
382 org-dir))
383 "org-loaddefs.el can not be found!")))
384 (version1 (if full version release)))
385 (when here (insert version1))
386 (when message (message "%s" version1))
387 version1)))
389 (defconst org-version (org-version))
392 ;;; Syntax Constants
394 ;;;; Block
396 (defconst org-block-regexp
397 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
398 "Regular expression for hiding blocks.")
400 (defconst org-dblock-start-re
401 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
402 "Matches the start line of a dynamic block, with parameters.")
404 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
405 "Matches the end of a dynamic block.")
407 ;;;; Clock and Planning
409 (defconst org-clock-string "CLOCK:"
410 "String used as prefix for timestamps clocking work hours on an item.")
412 (defvar org-closed-string "CLOSED:"
413 "String used as the prefix for timestamps logging closing a TODO entry.")
415 (defvar org-deadline-string "DEADLINE:"
416 "String to mark deadline entries.
417 \\<org-mode-map>
418 A deadline is this string, followed by a time stamp. It must be
419 a word, terminated by a colon. You can insert a schedule keyword
420 and a timestamp with `\\[org-deadline]'.")
422 (defvar org-scheduled-string "SCHEDULED:"
423 "String to mark scheduled TODO entries.
424 \\<org-mode-map>
425 A schedule is this string, followed by a time stamp. It must be
426 a word, terminated by a colon. You can insert a schedule keyword
427 and a timestamp with `\\[org-schedule]'.")
429 (defconst org-ds-keyword-length
430 (+ 2
431 (apply #'max
432 (mapcar #'length
433 (list org-deadline-string org-scheduled-string
434 org-clock-string org-closed-string))))
435 "Maximum length of the DEADLINE and SCHEDULED keywords.")
437 (defconst org-planning-line-re
438 (concat "^[ \t]*"
439 (regexp-opt
440 (list org-closed-string org-deadline-string org-scheduled-string)
442 "Matches a line with planning info.
443 Matched keyword is in group 1.")
445 (defconst org-clock-line-re
446 (concat "^[ \t]*" org-clock-string)
447 "Matches a line with clock info.")
449 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
450 "Matches the DEADLINE keyword.")
452 (defconst org-deadline-time-regexp
453 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
454 "Matches the DEADLINE keyword together with a time stamp.")
456 (defconst org-deadline-time-hour-regexp
457 (concat "\\<" org-deadline-string
458 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
459 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
461 (defconst org-deadline-line-regexp
462 (concat "\\<\\(" org-deadline-string "\\).*")
463 "Matches the DEADLINE keyword and the rest of the line.")
465 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
466 "Matches the SCHEDULED keyword.")
468 (defconst org-scheduled-time-regexp
469 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
470 "Matches the SCHEDULED keyword together with a time stamp.")
472 (defconst org-scheduled-time-hour-regexp
473 (concat "\\<" org-scheduled-string
474 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
475 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
477 (defconst org-closed-time-regexp
478 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
479 "Matches the CLOSED keyword together with a time stamp.")
481 (defconst org-keyword-time-regexp
482 (concat "\\<"
483 (regexp-opt
484 (list org-scheduled-string org-deadline-string org-closed-string
485 org-clock-string)
487 " *[[<]\\([^]>]+\\)[]>]")
488 "Matches any of the 4 keywords, together with the time stamp.")
490 (defconst org-keyword-time-not-clock-regexp
491 (concat
492 "\\<"
493 (regexp-opt
494 (list org-scheduled-string org-deadline-string org-closed-string) t)
495 " *[[<]\\([^]>]+\\)[]>]")
496 "Matches any of the 3 keywords, together with the time stamp.")
498 (defconst org-maybe-keyword-time-regexp
499 (concat "\\(\\<"
500 (regexp-opt
501 (list org-scheduled-string org-deadline-string org-closed-string
502 org-clock-string)
504 "\\)?"
505 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
506 "\\|"
507 "<%%([^\r\n>]*>\\)")
508 "Matches a timestamp, possibly preceded by a keyword.")
510 (defconst org-all-time-keywords
511 (mapcar (lambda (w) (substring w 0 -1))
512 (list org-scheduled-string org-deadline-string
513 org-clock-string org-closed-string))
514 "List of time keywords.")
516 ;;;; Drawer
518 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
519 "Matches first or last line of a hidden block.
520 Group 1 contains drawer's name or \"END\".")
522 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
523 "Regular expression matching the first line of a property drawer.")
525 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
526 "Regular expression matching the last line of a property drawer.")
528 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
529 "Regular expression matching the first line of a clock drawer.")
531 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
532 "Regular expression matching the last line of a clock drawer.")
534 (defconst org-property-drawer-re
535 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
536 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
537 "[ \t]*:END:[ \t]*$")
538 "Matches an entire property drawer.")
540 (defconst org-clock-drawer-re
541 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
542 org-clock-drawer-end-re "\\)\n?")
543 "Matches an entire clock drawer.")
545 ;;;; Headline
547 (defconst org-heading-keyword-regexp-format
548 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
549 "Printf format for a regexp matching a headline with some keyword.
550 This regexp will match the headline of any node which has the
551 exact keyword that is put into the format. The keyword isn't in
552 any group by default, but the stars and the body are.")
554 (defconst org-heading-keyword-maybe-regexp-format
555 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
556 "Printf format for a regexp matching a headline, possibly with some keyword.
557 This regexp can match any headline with the specified keyword, or
558 without a keyword. The keyword isn't in any group by default,
559 but the stars and the body are.")
561 (defconst org-archive-tag "ARCHIVE"
562 "The tag that marks a subtree as archived.
563 An archived subtree does not open during visibility cycling, and does
564 not contribute to the agenda listings.")
566 (defconst org-tag-re "[[:alnum:]_@#%]+"
567 "Regexp matching a single tag.")
569 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
570 "Regexp matching the tag group at the end of a line, with leading spaces.
571 Tags are stored in match group 1. Match group 2 stores the tags
572 without the enclosing colons.")
574 (defconst org-tag-line-re
575 "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
576 "Regexp matching tags in a headline.
577 Tags are stored in match group 1. Match group 2 stores the tags
578 without the enclosing colons.")
580 (eval-and-compile
581 (defconst org-comment-string "COMMENT"
582 "Entries starting with this keyword will never be exported.
583 \\<org-mode-map>
584 An entry can be toggled between COMMENT and normal with
585 `\\[org-toggle-comment]'."))
588 ;;;; LaTeX Environments and Fragments
590 (defconst org-latex-regexps
591 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
592 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
593 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
594 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
595 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
596 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
597 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
598 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
599 "Regular expressions for matching embedded LaTeX.")
601 ;;;; Node Property
603 (defconst org-effort-property "Effort"
604 "The property that is being used to keep track of effort estimates.
605 Effort estimates given in this property need to have the format H:MM.")
607 ;;;; Table
609 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
610 "Detect an org-type or table-type table.")
612 (defconst org-table-line-regexp "^[ \t]*|"
613 "Detect an org-type table line.")
615 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
616 "Detect an org-type table line.")
618 (defconst org-table-hline-regexp "^[ \t]*|-"
619 "Detect an org-type table hline.")
621 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
622 "Detect a table-type table hline.")
624 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
625 "Detect the first line outside a table when searching from within it.
626 This works for both table types.")
628 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
629 "Detect a #+TBLFM line.")
631 ;;;; Timestamp
633 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
634 "Regular expression for fast time stamp matching.")
636 (defconst org-ts-regexp-inactive
637 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
638 "Regular expression for fast inactive time stamp matching.")
640 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
641 "Regular expression for fast time stamp matching.")
643 (defconst org-ts-regexp0
644 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
645 "Regular expression matching time strings for analysis.
646 This one does not require the space after the date, so it can be used
647 on a string that terminates immediately after the date.")
649 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
650 "Regular expression matching time strings for analysis.")
652 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
653 "Regular expression matching time stamps, with groups.")
655 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
656 "Regular expression matching time stamps (also [..]), with groups.")
658 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
659 "Regular expression matching a time stamp range.")
661 (defconst org-tr-regexp-both
662 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
663 "Regular expression matching a time stamp range.")
665 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
666 org-ts-regexp "\\)?")
667 "Regular expression matching a time stamp or time stamp range.")
669 (defconst org-tsr-regexp-both
670 (concat org-ts-regexp-both "\\(--?-?"
671 org-ts-regexp-both "\\)?")
672 "Regular expression matching a time stamp or time stamp range.
673 The time stamps may be either active or inactive.")
675 (defconst org-repeat-re
676 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
677 "Regular expression for specifying repeated events.
678 After a match, group 1 contains the repeat expression.")
680 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
681 "Formats for `format-time-string' which are used for time stamps.")
684 ;;; The custom variables
686 (defgroup org nil
687 "Outline-based notes management and organizer."
688 :tag "Org"
689 :group 'outlines
690 :group 'calendar)
692 (defcustom org-mode-hook nil
693 "Mode hook for Org mode, run after the mode was turned on."
694 :group 'org
695 :type 'hook)
697 (defcustom org-load-hook nil
698 "Hook that is run after org.el has been loaded."
699 :group 'org
700 :type 'hook)
702 (defcustom org-log-buffer-setup-hook nil
703 "Hook that is run after an Org log buffer is created."
704 :group 'org
705 :version "24.1"
706 :type 'hook)
708 (defvar org-modules) ; defined below
709 (defvar org-modules-loaded nil
710 "Have the modules been loaded already?")
712 (defun org-load-modules-maybe (&optional force)
713 "Load all extensions listed in `org-modules'."
714 (when (or force (not org-modules-loaded))
715 (dolist (ext org-modules)
716 (condition-case nil (require ext)
717 (error (message "Problems while trying to load feature `%s'" ext))))
718 (setq org-modules-loaded t)))
720 (defun org-set-modules (var value)
721 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
722 (set var value)
723 (when (featurep 'org)
724 (org-load-modules-maybe 'force)
725 (org-element-cache-reset 'all)))
727 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail org-eww)
728 "Modules that should always be loaded together with org.el.
730 If a description starts with <C>, the file is not part of Emacs
731 and loading it will require that you have downloaded and properly
732 installed the Org mode distribution.
734 You can also use this system to load external packages (i.e. neither Org
735 core modules, nor modules from the CONTRIB directory). Just add symbols
736 to the end of the list. If the package is called org-xyz.el, then you need
737 to add the symbol `xyz', and the package must have a call to:
739 (provide \\='org-xyz)
741 For export specific modules, see also `org-export-backends'."
742 :group 'org
743 :set 'org-set-modules
744 :version "26.1"
745 :package-version '(Org . "9.2")
746 :type
747 '(set :greedy t
748 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
749 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
750 (const :tag " crypt: Encryption of subtrees" org-crypt)
751 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
752 (const :tag " docview: Links to doc-view buffers" org-docview)
753 (const :tag " eww: Store link to url of eww" org-eww)
754 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
755 (const :tag " habit: Track your consistency with habits" org-habit)
756 (const :tag " id: Global IDs for identifying entries" org-id)
757 (const :tag " info: Links to Info nodes" org-info)
758 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
759 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
760 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
761 (const :tag " mouse: Additional mouse support" org-mouse)
762 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
763 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
764 (const :tag " tempo: Fast completion for structures" org-tempo)
765 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
766 (const :tag " eshell: Support for links to working directories in eshell" org-eshell)
768 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
769 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
770 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
771 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
772 (const :tag "C collector: Collect properties into tables" org-collector)
773 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
774 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
775 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
776 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
777 (const :tag "C eval: Include command output as text" org-eval)
778 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
779 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
780 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
781 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
782 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
783 (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
784 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
785 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
786 (const :tag "C man: Support for links to manpages in Org mode" org-man)
787 (const :tag "C mew: Links to Mew folders/messages" org-mew)
788 (const :tag "C notify: Notifications for Org-mode" org-notify)
789 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
790 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
791 (const :tag "C registry: A registry for Org links" org-registry)
792 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
793 (const :tag "C screenshot: Take and manage screenshots in Org-mode files" org-screenshot)
794 (const :tag "C secretary: Team management with Org" org-secretary)
795 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
796 (const :tag "C toc: Table of contents for Org buffer" org-toc)
797 (const :tag "C track: Keep up with Org mode development" org-track)
798 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
799 (const :tag "C vm: Links to VM folders/messages" org-vm)
800 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
801 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
802 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
804 (defvar org-export-registered-backends) ; From ox.el.
805 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
806 (declare-function org-export-backend-name "ox" (backend) t)
807 (defcustom org-export-backends '(ascii html icalendar latex odt)
808 "List of export back-ends that should be always available.
810 If a description starts with <C>, the file is not part of Emacs
811 and loading it will require that you have downloaded and properly
812 installed the Org mode distribution.
814 Unlike to `org-modules', libraries in this list will not be
815 loaded along with Org, but only once the export framework is
816 needed.
818 This variable needs to be set before org.el is loaded. If you
819 need to make a change while Emacs is running, use the customize
820 interface or run the following code, where VAL stands for the new
821 value of the variable, after updating it:
823 (progn
824 (setq org-export-registered-backends
825 (cl-remove-if-not
826 (lambda (backend)
827 (let ((name (org-export-backend-name backend)))
828 (or (memq name val)
829 (catch \\='parentp
830 (dolist (b val)
831 (and (org-export-derived-backend-p b name)
832 (throw \\='parentp t)))))))
833 org-export-registered-backends))
834 (let ((new-list (mapcar #\\='org-export-backend-name
835 org-export-registered-backends)))
836 (dolist (backend val)
837 (cond
838 ((not (load (format \"ox-%s\" backend) t t))
839 (message \"Problems while trying to load export back-end \\=`%s\\='\"
840 backend))
841 ((not (memq backend new-list)) (push backend new-list))))
842 (set-default \\='org-export-backends new-list)))
844 Adding a back-end to this list will also pull the back-end it
845 depends on, if any."
846 :group 'org
847 :group 'org-export
848 :version "26.1"
849 :package-version '(Org . "9.0")
850 :initialize 'custom-initialize-set
851 :set (lambda (var val)
852 (if (not (featurep 'ox)) (set-default var val)
853 ;; Any back-end not required anymore (not present in VAL and not
854 ;; a parent of any back-end in the new value) is removed from the
855 ;; list of registered back-ends.
856 (setq org-export-registered-backends
857 (cl-remove-if-not
858 (lambda (backend)
859 (let ((name (org-export-backend-name backend)))
860 (or (memq name val)
861 (catch 'parentp
862 (dolist (b val)
863 (and (org-export-derived-backend-p b name)
864 (throw 'parentp t)))))))
865 org-export-registered-backends))
866 ;; Now build NEW-LIST of both new back-ends and required
867 ;; parents.
868 (let ((new-list (mapcar #'org-export-backend-name
869 org-export-registered-backends)))
870 (dolist (backend val)
871 (cond
872 ((not (load (format "ox-%s" backend) t t))
873 (message "Problems while trying to load export back-end `%s'"
874 backend))
875 ((not (memq backend new-list)) (push backend new-list))))
876 ;; Set VAR to that list with fixed dependencies.
877 (set-default var new-list))))
878 :type '(set :greedy t
879 (const :tag " ascii Export buffer to ASCII format" ascii)
880 (const :tag " beamer Export buffer to Beamer presentation" beamer)
881 (const :tag " html Export buffer to HTML format" html)
882 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
883 (const :tag " latex Export buffer to LaTeX format" latex)
884 (const :tag " man Export buffer to MAN format" man)
885 (const :tag " md Export buffer to Markdown format" md)
886 (const :tag " odt Export buffer to ODT format" odt)
887 (const :tag " org Export buffer to Org format" org)
888 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
889 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
890 (const :tag "C deck Export buffer to deck.js presentations" deck)
891 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
892 (const :tag "C groff Export buffer to Groff format" groff)
893 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
894 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
895 (const :tag "C s5 Export buffer to s5 presentations" s5)
896 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
898 (eval-after-load 'ox
899 '(dolist (backend org-export-backends)
900 (condition-case nil (require (intern (format "ox-%s" backend)))
901 (error (message "Problems while trying to load export back-end `%s'"
902 backend)))))
904 (defcustom org-support-shift-select nil
905 "Non-nil means make shift-cursor commands select text when possible.
906 \\<org-mode-map>\
908 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
909 start selecting a region, or enlarge regions started in this way.
910 In Org mode, in special contexts, these same keys are used for
911 other purposes, important enough to compete with shift selection.
912 Org tries to balance these needs by supporting `shift-select-mode'
913 outside these special contexts, under control of this variable.
915 The default of this variable is nil, to avoid confusing behavior. Shifted
916 cursor keys will then execute Org commands in the following contexts:
917 - on a headline, changing TODO state (left/right) and priority (up/down)
918 - on a time stamp, changing the time
919 - in a plain list item, changing the bullet type
920 - in a property definition line, switching between allowed values
921 - in the BEGIN line of a clock table (changing the time block).
922 Outside these contexts, the commands will throw an error.
924 When this variable is t and the cursor is not in a special
925 context, Org mode will support shift-selection for making and
926 enlarging regions. To make this more effective, the bullet
927 cycling will no longer happen anywhere in an item line, but only
928 if the cursor is exactly on the bullet.
930 If you set this variable to the symbol `always', then the keys
931 will not be special in headlines, property lines, and item lines,
932 to make shift selection work there as well. If this is what you
933 want, you can use the following alternative commands:
934 `\\[org-todo]' and `\\[org-priority]' \
935 to change TODO state and priority,
936 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
937 can be used to switch TODO sets,
938 `\\[org-ctrl-c-minus]' to cycle item bullet types,
939 and properties can be edited by hand or in column view.
941 However, when the cursor is on a timestamp, shift-cursor commands
942 will still edit the time stamp - this is just too good to give up."
943 :group 'org
944 :type '(choice
945 (const :tag "Never" nil)
946 (const :tag "When outside special context" t)
947 (const :tag "Everywhere except timestamps" always)))
949 (defcustom org-loop-over-headlines-in-active-region nil
950 "Shall some commands act upon headlines in the active region?
952 When set to t, some commands will be performed in all headlines
953 within the active region.
955 When set to `start-level', some commands will be performed in all
956 headlines within the active region, provided that these headlines
957 are of the same level than the first one.
959 When set to a string, those commands will be performed on the
960 matching headlines within the active region. Such string must be
961 a tags/property/todo match as it is used in the agenda tags view.
963 The list of commands is: `org-schedule', `org-deadline',
964 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
965 `org-archive-to-archive-sibling'. The archiving commands skip
966 already archived entries."
967 :type '(choice (const :tag "Don't loop" nil)
968 (const :tag "All headlines in active region" t)
969 (const :tag "In active region, headlines at the same level than the first one" start-level)
970 (string :tag "Tags/Property/Todo matcher"))
971 :version "24.1"
972 :group 'org-todo
973 :group 'org-archive)
975 (defcustom org-startup-folded t
976 "Non-nil means entering Org mode will switch to OVERVIEW.
978 This can also be configured on a per-file basis by adding one of
979 the following lines anywhere in the buffer:
981 #+STARTUP: fold (or `overview', this is equivalent)
982 #+STARTUP: nofold (or `showall', this is equivalent)
983 #+STARTUP: content
984 #+STARTUP: showeverything
986 Set `org-agenda-inhibit-startup' to a non-nil value if you want
987 to ignore this option when Org opens agenda files for the first
988 time."
989 :group 'org-startup
990 :type '(choice
991 (const :tag "nofold: show all" nil)
992 (const :tag "fold: overview" t)
993 (const :tag "content: all headlines" content)
994 (const :tag "show everything, even drawers" showeverything)))
996 (defcustom org-startup-truncated t
997 "Non-nil means entering Org mode will set `truncate-lines'.
998 This is useful since some lines containing links can be very long and
999 uninteresting. Also tables look terrible when wrapped.
1001 The variable `org-startup-truncated' allows to configure
1002 truncation for Org mode different to the other modes that use the
1003 variable `truncate-lines' and as a shortcut instead of putting
1004 the variable `truncate-lines' into the `org-mode-hook'. If one
1005 wants to configure truncation for Org mode not statically but
1006 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
1007 the variable `truncate-lines' has to be used because in such a
1008 case it is too late to set the variable `org-startup-truncated'."
1009 :group 'org-startup
1010 :type 'boolean)
1012 (defcustom org-startup-indented nil
1013 "Non-nil means turn on `org-indent-mode' on startup.
1014 This can also be configured on a per-file basis by adding one of
1015 the following lines anywhere in the buffer:
1017 #+STARTUP: indent
1018 #+STARTUP: noindent"
1019 :group 'org-structure
1020 :type '(choice
1021 (const :tag "Not" nil)
1022 (const :tag "Globally (slow on startup in large files)" t)))
1024 (defcustom org-use-sub-superscripts t
1025 "Non-nil means interpret \"_\" and \"^\" for display.
1027 If you want to control how Org exports those characters, see
1028 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
1029 used to be an alias for `org-export-with-sub-superscripts' in
1030 Org <8.0, it is not anymore.
1032 When this option is turned on, you can use TeX-like syntax for
1033 sub- and superscripts within the buffer. Several characters after
1034 \"_\" or \"^\" will be considered as a single item - so grouping
1035 with {} is normally not needed. For example, the following things
1036 will be parsed as single sub- or superscripts:
1038 10^24 or 10^tau several digits will be considered 1 item.
1039 10^-12 or 10^-tau a leading sign with digits or a word
1040 x^2-y^3 will be read as x^2 - y^3, because items are
1041 terminated by almost any nonword/nondigit char.
1042 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1044 Still, ambiguity is possible. So when in doubt, use {} to enclose
1045 the sub/superscript. If you set this variable to the symbol `{}',
1046 the braces are *required* in order to trigger interpretations as
1047 sub/superscript. This can be helpful in documents that need \"_\"
1048 frequently in plain text."
1049 :group 'org-startup
1050 :version "24.4"
1051 :package-version '(Org . "8.0")
1052 :type '(choice
1053 (const :tag "Always interpret" t)
1054 (const :tag "Only with braces" {})
1055 (const :tag "Never interpret" nil)))
1057 (defcustom org-startup-with-beamer-mode nil
1058 "Non-nil means turn on `org-beamer-mode' on startup.
1059 This can also be configured on a per-file basis by adding one of
1060 the following lines anywhere in the buffer:
1062 #+STARTUP: beamer"
1063 :group 'org-startup
1064 :version "24.1"
1065 :type 'boolean)
1067 (defcustom org-startup-align-all-tables nil
1068 "Non-nil means align all tables when visiting a file.
1069 This can also be configured on a per-file basis by adding one of
1070 the following lines anywhere in the buffer:
1071 #+STARTUP: align
1072 #+STARTUP: noalign"
1073 :group 'org-startup
1074 :type 'boolean)
1076 (defcustom org-startup-shrink-all-tables nil
1077 "Non-nil means shrink all table columns with a width cookie.
1078 This can also be configured on a per-file basis by adding one of
1079 the following lines anywhere in the buffer:
1080 #+STARTUP: shrink"
1081 :group 'org-startup
1082 :type 'boolean
1083 :version "27.1"
1084 :package-version '(Org . "9.2")
1085 :safe #'booleanp)
1087 (defcustom org-startup-with-inline-images nil
1088 "Non-nil means show inline images when loading a new Org file.
1089 This can also be configured on a per-file basis by adding one of
1090 the following lines anywhere in the buffer:
1091 #+STARTUP: inlineimages
1092 #+STARTUP: noinlineimages"
1093 :group 'org-startup
1094 :version "24.1"
1095 :type 'boolean)
1097 (defcustom org-startup-with-latex-preview nil
1098 "Non-nil means preview LaTeX fragments when loading a new Org file.
1100 This can also be configured on a per-file basis by adding one of
1101 the following lines anywhere in the buffer:
1102 #+STARTUP: latexpreview
1103 #+STARTUP: nolatexpreview"
1104 :group 'org-startup
1105 :version "24.4"
1106 :package-version '(Org . "8.0")
1107 :type 'boolean)
1109 (defcustom org-insert-mode-line-in-empty-file nil
1110 "Non-nil means insert the first line setting Org mode in empty files.
1111 When the function `org-mode' is called interactively in an empty file, this
1112 normally means that the file name does not automatically trigger Org mode.
1113 To ensure that the file will always be in Org mode in the future, a
1114 line enforcing Org mode will be inserted into the buffer, if this option
1115 has been set."
1116 :group 'org-startup
1117 :type 'boolean)
1119 (defcustom org-replace-disputed-keys nil
1120 "Non-nil means use alternative key bindings for some keys.
1122 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1123 These keys are also used by other packages like Shift Select mode,
1124 CUA mode or Windmove. If you want to use Org mode together with
1125 one of these other modes, or more generally if you would like to
1126 move some Org mode commands to other keys, set this variable and
1127 configure the keys with the variable `org-disputed-keys'.
1129 This option is only relevant at load-time of Org mode, and must be set
1130 *before* org.el is loaded. Changing it requires a restart of Emacs to
1131 become effective."
1132 :group 'org-startup
1133 :type 'boolean)
1135 (defcustom org-use-extra-keys nil
1136 "Non-nil means use extra key sequence definitions for certain commands.
1137 This happens automatically if `window-system' is nil. This
1138 variable lets you do the same manually. You must set it before
1139 loading Org."
1140 :group 'org-startup
1141 :type 'boolean)
1143 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1145 (defcustom org-disputed-keys
1146 '(([(shift up)] . [(meta p)])
1147 ([(shift down)] . [(meta n)])
1148 ([(shift left)] . [(meta -)])
1149 ([(shift right)] . [(meta +)])
1150 ([(control shift right)] . [(meta shift +)])
1151 ([(control shift left)] . [(meta shift -)]))
1152 "Keys for which Org mode and other modes compete.
1153 This is an alist, cars are the default keys, second element specifies
1154 the alternative to use when `org-replace-disputed-keys' is t.
1156 Keys can be specified in any syntax supported by `define-key'.
1157 The value of this option takes effect only at Org mode startup,
1158 therefore you'll have to restart Emacs to apply it after changing."
1159 :group 'org-startup
1160 :type 'alist)
1162 (defun org-key (key)
1163 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1164 Or return the original if not disputed."
1165 (when org-replace-disputed-keys
1166 (let* ((nkey (key-description key))
1167 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1168 org-disputed-keys)))
1169 (setq key (if x (cdr x) key))))
1170 key)
1172 (defun org-defkey (keymap key def)
1173 "Define a key, possibly translated, as returned by `org-key'."
1174 (define-key keymap (org-key key) def))
1176 (defcustom org-ellipsis nil
1177 "The ellipsis to use in the Org mode outline.
1179 When nil, just use the standard three dots. When a non-empty string,
1180 use that string instead.
1182 The change affects only Org mode (which will then use its own display table).
1183 Changing this requires executing `\\[org-mode]' in a buffer to become
1184 effective."
1185 :group 'org-startup
1186 :type '(choice (const :tag "Default" nil)
1187 (string :tag "String" :value "...#"))
1188 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1190 (defvar org-display-table nil
1191 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1193 (defgroup org-keywords nil
1194 "Keywords in Org mode."
1195 :tag "Org Keywords"
1196 :group 'org)
1198 (defcustom org-closed-keep-when-no-todo nil
1199 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1200 :group 'org-todo
1201 :group 'org-keywords
1202 :version "24.4"
1203 :package-version '(Org . "8.0")
1204 :type 'boolean)
1206 (defgroup org-structure nil
1207 "Options concerning the general structure of Org files."
1208 :tag "Org Structure"
1209 :group 'org)
1211 (defgroup org-reveal-location nil
1212 "Options about how to make context of a location visible."
1213 :tag "Org Reveal Location"
1214 :group 'org-structure)
1216 (defcustom org-show-context-detail '((agenda . local)
1217 (bookmark-jump . lineage)
1218 (isearch . lineage)
1219 (default . ancestors))
1220 "Alist between context and visibility span when revealing a location.
1222 \\<org-mode-map>Some actions may move point into invisible
1223 locations. As a consequence, Org always expose a neighborhood
1224 around point. How much is shown depends on the initial action,
1225 or context. Valid contexts are
1227 agenda when exposing an entry from the agenda
1228 org-goto when using the command `org-goto' (`\\[org-goto]')
1229 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1230 tags-tree when constructing a sparse tree based on tags matches
1231 link-search when exposing search matches associated with a link
1232 mark-goto when exposing the jump goal of a mark
1233 bookmark-jump when exposing a bookmark location
1234 isearch when exiting from an incremental search
1235 default default for all contexts not set explicitly
1237 Allowed visibility spans are
1239 minimal show current headline; if point is not on headline,
1240 also show entry
1242 local show current headline, entry and next headline
1244 ancestors show current headline and its direct ancestors; if
1245 point is not on headline, also show entry
1247 lineage show current headline, its direct ancestors and all
1248 their children; if point is not on headline, also show
1249 entry and first child
1251 tree show current headline, its direct ancestors and all
1252 their children; if point is not on headline, also show
1253 entry and all children
1255 canonical show current headline, its direct ancestors along with
1256 their entries and children; if point is not located on
1257 the headline, also show current entry and all children
1259 As special cases, a nil or t value means show all contexts in
1260 `minimal' or `canonical' view, respectively.
1262 Some views can make displayed information very compact, but also
1263 make it harder to edit the location of the match. In such
1264 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1265 more context."
1266 :group 'org-reveal-location
1267 :version "26.1"
1268 :package-version '(Org . "9.0")
1269 :type '(choice
1270 (const :tag "Canonical" t)
1271 (const :tag "Minimal" nil)
1272 (repeat :greedy t :tag "Individual contexts"
1273 (cons
1274 (choice :tag "Context"
1275 (const agenda)
1276 (const org-goto)
1277 (const occur-tree)
1278 (const tags-tree)
1279 (const link-search)
1280 (const mark-goto)
1281 (const bookmark-jump)
1282 (const isearch)
1283 (const default))
1284 (choice :tag "Detail level"
1285 (const minimal)
1286 (const local)
1287 (const ancestors)
1288 (const lineage)
1289 (const tree)
1290 (const canonical))))))
1292 (defcustom org-indirect-buffer-display 'other-window
1293 "How should indirect tree buffers be displayed?
1295 This applies to indirect buffers created with the commands
1296 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1298 Valid values are:
1299 current-window Display in the current window
1300 other-window Just display in another window.
1301 dedicated-frame Create one new frame, and re-use it each time.
1302 new-frame Make a new frame each time. Note that in this case
1303 previously-made indirect buffers are kept, and you need to
1304 kill these buffers yourself."
1305 :group 'org-structure
1306 :group 'org-agenda-windows
1307 :type '(choice
1308 (const :tag "In current window" current-window)
1309 (const :tag "In current frame, other window" other-window)
1310 (const :tag "Each time a new frame" new-frame)
1311 (const :tag "One dedicated frame" dedicated-frame)))
1313 (defcustom org-use-speed-commands nil
1314 "Non-nil means activate single letter commands at beginning of a headline.
1315 This may also be a function to test for appropriate locations where speed
1316 commands should be active.
1318 For example, to activate speed commands when the point is on any
1319 star at the beginning of the headline, you can do this:
1321 (setq org-use-speed-commands
1322 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1323 :group 'org-structure
1324 :type '(choice
1325 (const :tag "Never" nil)
1326 (const :tag "At beginning of headline stars" t)
1327 (function)))
1329 (defcustom org-speed-commands-user nil
1330 "Alist of additional speed commands.
1331 This list will be checked before `org-speed-commands-default'
1332 when the variable `org-use-speed-commands' is non-nil
1333 and when the cursor is at the beginning of a headline.
1334 The car of each entry is a string with a single letter, which must
1335 be assigned to `self-insert-command' in the global map.
1336 The cdr is either a command to be called interactively, a function
1337 to be called, or a form to be evaluated.
1338 An entry that is just a list with a single string will be interpreted
1339 as a descriptive headline that will be added when listing the speed
1340 commands in the Help buffer using the `?' speed command."
1341 :group 'org-structure
1342 :type '(repeat :value ("k" . ignore)
1343 (choice :value ("k" . ignore)
1344 (list :tag "Descriptive Headline" (string :tag "Headline"))
1345 (cons :tag "Letter and Command"
1346 (string :tag "Command letter")
1347 (choice
1348 (function)
1349 (sexp))))))
1351 (defcustom org-bookmark-names-plist
1352 '(:last-capture "org-capture-last-stored"
1353 :last-refile "org-refile-last-stored"
1354 :last-capture-marker "org-capture-last-stored-marker")
1355 "Names for bookmarks automatically set by some Org commands.
1356 This can provide strings as names for a number of bookmarks Org sets
1357 automatically. The following keys are currently implemented:
1358 :last-capture
1359 :last-capture-marker
1360 :last-refile
1361 When a key does not show up in the property list, the corresponding bookmark
1362 is not set."
1363 :group 'org-structure
1364 :type 'plist)
1366 (defgroup org-cycle nil
1367 "Options concerning visibility cycling in Org mode."
1368 :tag "Org Cycle"
1369 :group 'org-structure)
1371 (defcustom org-cycle-skip-children-state-if-no-children t
1372 "Non-nil means skip CHILDREN state in entries that don't have any."
1373 :group 'org-cycle
1374 :type 'boolean)
1376 (defcustom org-cycle-max-level nil
1377 "Maximum level which should still be subject to visibility cycling.
1378 Levels higher than this will, for cycling, be treated as text, not a headline.
1379 When `org-odd-levels-only' is set, a value of N in this variable actually
1380 means 2N-1 stars as the limiting headline.
1381 When nil, cycle all levels.
1382 Note that the limiting level of cycling is also influenced by
1383 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1384 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1385 than its value."
1386 :group 'org-cycle
1387 :type '(choice
1388 (const :tag "No limit" nil)
1389 (integer :tag "Maximum level")))
1391 (defcustom org-hide-block-startup nil
1392 "Non-nil means entering Org mode will fold all blocks.
1393 This can also be set in on a per-file basis with
1395 #+STARTUP: hideblocks
1396 #+STARTUP: showblocks"
1397 :group 'org-startup
1398 :group 'org-cycle
1399 :type 'boolean)
1401 (defcustom org-cycle-global-at-bob nil
1402 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1404 This makes it possible to do global cycling without having to use `S-TAB'
1405 or `\\[universal-argument] TAB'. For this special case to work, the first \
1406 line of the buffer
1407 must not be a headline -- it may be empty or some other text.
1409 When used in this way, `org-cycle-hook' is disabled temporarily to make
1410 sure the cursor stays at the beginning of the buffer.
1412 When this option is nil, don't do anything special at the beginning of
1413 the buffer."
1414 :group 'org-cycle
1415 :type 'boolean)
1417 (defcustom org-cycle-level-after-item/entry-creation t
1418 "Non-nil means cycle entry level or item indentation in new empty entries.
1420 When the cursor is at the end of an empty headline, i.e., with only stars
1421 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1422 and then all possible ancestor states, before returning to the original state.
1423 This makes data entry extremely fast: M-RET to create a new headline,
1424 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1426 When the cursor is at the end of an empty plain list item, one TAB will
1427 make it a subitem, two or more tabs will back up to make this an item
1428 higher up in the item hierarchy."
1429 :group 'org-cycle
1430 :type 'boolean)
1432 (defcustom org-cycle-emulate-tab t
1433 "Where should `org-cycle' emulate TAB.
1434 nil Never
1435 white Only in completely white lines
1436 whitestart Only at the beginning of lines, before the first non-white char
1437 t Everywhere except in headlines
1438 exc-hl-bol Everywhere except at the start of a headline
1439 If TAB is used in a place where it does not emulate TAB, the current subtree
1440 visibility is cycled."
1441 :group 'org-cycle
1442 :type '(choice (const :tag "Never" nil)
1443 (const :tag "Only in completely white lines" white)
1444 (const :tag "Before first char in a line" whitestart)
1445 (const :tag "Everywhere except in headlines" t)
1446 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1448 (defcustom org-cycle-separator-lines 2
1449 "Number of empty lines needed to keep an empty line between collapsed trees.
1450 If you leave an empty line between the end of a subtree and the following
1451 headline, this empty line is hidden when the subtree is folded.
1452 Org mode will leave (exactly) one empty line visible if the number of
1453 empty lines is equal or larger to the number given in this variable.
1454 So the default 2 means at least 2 empty lines after the end of a subtree
1455 are needed to produce free space between a collapsed subtree and the
1456 following headline.
1458 If the number is negative, and the number of empty lines is at least -N,
1459 all empty lines are shown.
1461 Special case: when 0, never leave empty lines in collapsed view."
1462 :group 'org-cycle
1463 :type 'integer)
1464 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1466 (defcustom org-pre-cycle-hook nil
1467 "Hook that is run before visibility cycling is happening.
1468 The function(s) in this hook must accept a single argument which indicates
1469 the new state that will be set right after running this hook. The
1470 argument is a symbol. Before a global state change, it can have the values
1471 `overview', `content', or `all'. Before a local state change, it can have
1472 the values `folded', `children', or `subtree'."
1473 :group 'org-cycle
1474 :type 'hook)
1476 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1477 org-cycle-show-empty-lines
1478 org-optimize-window-after-visibility-change)
1479 "Hook that is run after `org-cycle' has changed the buffer visibility.
1480 The function(s) in this hook must accept a single argument which indicates
1481 the new state that was set by the most recent `org-cycle' command. The
1482 argument is a symbol. After a global state change, it can have the values
1483 `overview', `contents', or `all'. After a local state change, it can have
1484 the values `folded', `children', or `subtree'."
1485 :group 'org-cycle
1486 :type 'hook
1487 :version "26.1"
1488 :package-version '(Org . "8.3"))
1490 (defgroup org-edit-structure nil
1491 "Options concerning structure editing in Org mode."
1492 :tag "Org Edit Structure"
1493 :group 'org-structure)
1495 (defcustom org-odd-levels-only nil
1496 "Non-nil means skip even levels and only use odd levels for the outline.
1497 This has the effect that two stars are being added/taken away in
1498 promotion/demotion commands. It also influences how levels are
1499 handled by the exporters.
1500 Changing it requires restart of `font-lock-mode' to become effective
1501 for fontification also in regions already fontified.
1502 You may also set this on a per-file basis by adding one of the following
1503 lines to the buffer:
1505 #+STARTUP: odd
1506 #+STARTUP: oddeven"
1507 :group 'org-edit-structure
1508 :group 'org-appearance
1509 :type 'boolean)
1511 (defcustom org-adapt-indentation t
1512 "Non-nil means adapt indentation to outline node level.
1514 When this variable is set, Org assumes that you write outlines by
1515 indenting text in each node to align with the headline (after the
1516 stars). The following issues are influenced by this variable:
1518 - The indentation is increased by one space in a demotion
1519 command, and decreased by one in a promotion command. However,
1520 in the latter case, if shifting some line in the entry body
1521 would alter document structure (e.g., insert a new headline),
1522 indentation is not changed at all.
1524 - Property drawers and planning information is inserted indented
1525 when this variable is set. When nil, they will not be indented.
1527 - TAB indents a line relative to current level. The lines below
1528 a headline will be indented when this variable is set.
1530 Note that this is all about true indentation, by adding and
1531 removing space characters. See also \"org-indent.el\" which does
1532 level-dependent indentation in a virtual way, i.e. at display
1533 time in Emacs."
1534 :group 'org-edit-structure
1535 :type 'boolean
1536 :safe #'booleanp)
1538 (defcustom org-special-ctrl-a/e nil
1539 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1541 When t, `C-a' will bring back the cursor to the beginning of the
1542 headline text, i.e. after the stars and after a possible TODO
1543 keyword. In an item, this will be the position after bullet and
1544 check-box, if any. When the cursor is already at that position,
1545 another `C-a' will bring it to the beginning of the line.
1547 `C-e' will jump to the end of the headline, ignoring the presence
1548 of tags in the headline. A second `C-e' will then jump to the
1549 true end of the line, after any tags. This also means that, when
1550 this variable is non-nil, `C-e' also will never jump beyond the
1551 end of the heading of a folded section, i.e. not after the
1552 ellipses.
1554 When set to the symbol `reversed', the first `C-a' or `C-e' works
1555 normally, going to the true line boundary first. Only a directly
1556 following, identical keypress will bring the cursor to the
1557 special positions.
1559 This may also be a cons cell where the behavior for `C-a' and
1560 `C-e' is set separately."
1561 :group 'org-edit-structure
1562 :type '(choice
1563 (const :tag "off" nil)
1564 (const :tag "on: after stars/bullet and before tags first" t)
1565 (const :tag "reversed: true line boundary first" reversed)
1566 (cons :tag "Set C-a and C-e separately"
1567 (choice :tag "Special C-a"
1568 (const :tag "off" nil)
1569 (const :tag "on: after stars/bullet first" t)
1570 (const :tag "reversed: before stars/bullet first" reversed))
1571 (choice :tag "Special C-e"
1572 (const :tag "off" nil)
1573 (const :tag "on: before tags first" t)
1574 (const :tag "reversed: after tags first" reversed)))))
1575 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1577 (defcustom org-special-ctrl-k nil
1578 "Non-nil means `C-k' will behave specially in headlines.
1579 When nil, `C-k' will call the default `kill-line' command.
1580 When t, the following will happen while the cursor is in the headline:
1582 - When the cursor is at the beginning of a headline, kill the entire
1583 line and possible the folded subtree below the line.
1584 - When in the middle of the headline text, kill the headline up to the tags.
1585 - When after the headline text, kill the tags."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-ctrl-k-protect-subtree nil
1590 "Non-nil means, do not delete a hidden subtree with C-k.
1591 When set to the symbol `error', simply throw an error when C-k is
1592 used to kill (part-of) a headline that has hidden text behind it.
1593 Any other non-nil value will result in a query to the user, if it is
1594 OK to kill that hidden subtree. When nil, kill without remorse."
1595 :group 'org-edit-structure
1596 :version "24.1"
1597 :type '(choice
1598 (const :tag "Do not protect hidden subtrees" nil)
1599 (const :tag "Protect hidden subtrees with a security query" t)
1600 (const :tag "Never kill a hidden subtree with C-k" error)))
1602 (defcustom org-special-ctrl-o t
1603 "Non-nil means, make `C-o' insert a row in tables."
1604 :group 'org-edit-structure
1605 :type 'boolean)
1607 (defcustom org-catch-invisible-edits nil
1608 "Check if in invisible region before inserting or deleting a character.
1609 Valid values are:
1611 nil Do not check, so just do invisible edits.
1612 error Throw an error and do nothing.
1613 show Make point visible, and do the requested edit.
1614 show-and-error Make point visible, then throw an error and abort the edit.
1615 smart Make point visible, and do insertion/deletion if it is
1616 adjacent to visible text and the change feels predictable.
1617 Never delete a previously invisible character or add in the
1618 middle or right after an invisible region. Basically, this
1619 allows insertion and backward-delete right before ellipses.
1620 FIXME: maybe in this case we should not even show?"
1621 :group 'org-edit-structure
1622 :version "24.1"
1623 :type '(choice
1624 (const :tag "Do not check" nil)
1625 (const :tag "Throw error when trying to edit" error)
1626 (const :tag "Unhide, but do not do the edit" show-and-error)
1627 (const :tag "Show invisible part and do the edit" show)
1628 (const :tag "Be smart and do the right thing" smart)))
1630 (defcustom org-yank-folded-subtrees t
1631 "Non-nil means when yanking subtrees, fold them.
1632 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1633 it starts with a heading and all other headings in it are either children
1634 or siblings, then fold all the subtrees. However, do this only if no
1635 text after the yank would be swallowed into a folded tree by this action."
1636 :group 'org-edit-structure
1637 :type 'boolean)
1639 (defcustom org-yank-adjusted-subtrees nil
1640 "Non-nil means when yanking subtrees, adjust the level.
1641 With this setting, `org-paste-subtree' is used to insert the subtree, see
1642 this function for details."
1643 :group 'org-edit-structure
1644 :type 'boolean)
1646 (defcustom org-M-RET-may-split-line '((default . t))
1647 "Non-nil means M-RET will split the line at the cursor position.
1648 When nil, it will go to the end of the line before making a
1649 new line.
1650 You may also set this option in a different way for different
1651 contexts. Valid contexts are:
1653 headline when creating a new headline
1654 item when creating a new item
1655 table in a table field
1656 default the value to be used for all contexts not explicitly
1657 customized"
1658 :group 'org-structure
1659 :group 'org-table
1660 :type '(choice
1661 (const :tag "Always" t)
1662 (const :tag "Never" nil)
1663 (repeat :greedy t :tag "Individual contexts"
1664 (cons
1665 (choice :tag "Context"
1666 (const headline)
1667 (const item)
1668 (const table)
1669 (const default))
1670 (boolean)))))
1673 (defcustom org-insert-heading-respect-content nil
1674 "Non-nil means insert new headings after the current subtree.
1675 \\<org-mode-map>
1676 When nil, the new heading is created directly after the current line.
1677 The commands `\\[org-insert-heading-respect-content]' and \
1678 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1679 for the duration of the command."
1680 :group 'org-structure
1681 :type 'boolean)
1683 (defcustom org-blank-before-new-entry '((heading . auto)
1684 (plain-list-item . auto))
1685 "Should `org-insert-heading' leave a blank line before new heading/item?
1686 The value is an alist, with `heading' and `plain-list-item' as CAR,
1687 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1688 which case Org will look at the surrounding headings/items and try to
1689 make an intelligent decision whether to insert a blank line or not."
1690 :group 'org-edit-structure
1691 :type '(list
1692 (cons (const heading)
1693 (choice (const :tag "Never" nil)
1694 (const :tag "Always" t)
1695 (const :tag "Auto" auto)))
1696 (cons (const plain-list-item)
1697 (choice (const :tag "Never" nil)
1698 (const :tag "Always" t)
1699 (const :tag "Auto" auto)))))
1701 (defcustom org-insert-heading-hook nil
1702 "Hook being run after inserting a new heading."
1703 :group 'org-edit-structure
1704 :type 'hook)
1706 (defcustom org-enable-fixed-width-editor t
1707 "Non-nil means lines starting with \":\" are treated as fixed-width.
1708 This currently only means they are never auto-wrapped.
1709 When nil, such lines will be treated like ordinary lines."
1710 :group 'org-edit-structure
1711 :type 'boolean)
1713 (defgroup org-sparse-trees nil
1714 "Options concerning sparse trees in Org mode."
1715 :tag "Org Sparse Trees"
1716 :group 'org-structure)
1718 (defcustom org-highlight-sparse-tree-matches t
1719 "Non-nil means highlight all matches that define a sparse tree.
1720 The highlights will automatically disappear the next time the buffer is
1721 changed by an edit command."
1722 :group 'org-sparse-trees
1723 :type 'boolean)
1725 (defcustom org-remove-highlights-with-change t
1726 "Non-nil means any change to the buffer will remove temporary highlights.
1727 \\<org-mode-map>\
1728 Such highlights are created by `org-occur' and `org-clock-display'.
1729 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1730 to get rid of the highlights.
1731 The highlights created by `org-toggle-latex-fragment' always need
1732 `\\[org-toggle-latex-fragment]' to be removed."
1733 :group 'org-sparse-trees
1734 :group 'org-time
1735 :type 'boolean)
1737 (defcustom org-occur-case-fold-search t
1738 "Non-nil means `org-occur' should be case-insensitive.
1739 If set to `smart' the search will be case-insensitive only if it
1740 doesn't specify any upper case character."
1741 :group 'org-sparse-trees
1742 :version "26.1"
1743 :type '(choice
1744 (const :tag "Case-sensitive" nil)
1745 (const :tag "Case-insensitive" t)
1746 (const :tag "Case-insensitive for lower case searches only" smart)))
1748 (defcustom org-occur-hook '(org-first-headline-recenter)
1749 "Hook that is run after `org-occur' has constructed a sparse tree.
1750 This can be used to recenter the window to show as much of the structure
1751 as possible."
1752 :group 'org-sparse-trees
1753 :type 'hook)
1755 (defgroup org-table nil
1756 "Options concerning tables in Org mode."
1757 :tag "Org Table"
1758 :group 'org)
1760 (defcustom org-self-insert-cluster-for-undo nil
1761 "Non-nil means cluster self-insert commands for undo when possible.
1762 If this is set, then, like in the Emacs command loop, 20 consecutive
1763 characters will be undone together.
1764 This is configurable, because there is some impact on typing performance."
1765 :group 'org-table
1766 :type 'boolean)
1768 (defcustom org-table-tab-recognizes-table.el t
1769 "Non-nil means TAB will automatically notice a table.el table.
1770 When it sees such a table, it moves point into it and - if necessary -
1771 calls `table-recognize-table'."
1772 :group 'org-table-editing
1773 :type 'boolean)
1775 (defgroup org-link nil
1776 "Options concerning links in Org mode."
1777 :tag "Org Link"
1778 :group 'org)
1780 (defvar-local org-link-abbrev-alist-local nil
1781 "Buffer-local version of `org-link-abbrev-alist', which see.
1782 The value of this is taken from the #+LINK lines.")
1784 (defcustom org-link-parameters
1785 '(("doi" :follow org--open-doi-link)
1786 ("elisp" :follow org--open-elisp-link)
1787 ("file" :complete org-file-complete-link)
1788 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1789 ("help" :follow org--open-help-link)
1790 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1791 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1792 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1793 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1794 ("shell" :follow org--open-shell-link))
1795 "An alist of properties that defines all the links in Org mode.
1796 The key in each association is a string of the link type.
1797 Subsequent optional elements make up a p-list of link properties.
1799 :follow - A function that takes the link path as an argument.
1801 :export - A function that takes the link path, description and
1802 export-backend as arguments.
1804 :store - A function responsible for storing the link. See the
1805 function `org-store-link-functions'.
1807 :complete - A function that inserts a link with completion. The
1808 function takes one optional prefix arg.
1810 :face - A face for the link, or a function that returns a face.
1811 The function takes one argument which is the link path. The
1812 default face is `org-link'.
1814 :mouse-face - The mouse-face. The default is `highlight'.
1816 :display - `full' will not fold the link in descriptive
1817 display. Default is `org-link'.
1819 :help-echo - A string or function that takes (window object position)
1820 as arguments and returns a string.
1822 :keymap - A keymap that is active on the link. The default is
1823 `org-mouse-map'.
1825 :htmlize-link - A function for the htmlize-link. Defaults
1826 to (list :uri \"type:path\")
1828 :activate-func - A function to run at the end of font-lock
1829 activation. The function must accept (link-start link-end path bracketp)
1830 as arguments."
1831 :group 'org-link
1832 :type '(alist :tag "Link display parameters"
1833 :value-type plist)
1834 :version "26.1"
1835 :package-version '(Org . "9.1"))
1837 (defun org-link-get-parameter (type key)
1838 "Get TYPE link property for KEY.
1839 TYPE is a string and KEY is a plist keyword."
1840 (plist-get
1841 (cdr (assoc type org-link-parameters))
1842 key))
1844 (defun org-link-set-parameters (type &rest parameters)
1845 "Set link TYPE properties to PARAMETERS.
1846 PARAMETERS should be :key val pairs."
1847 (let ((data (assoc type org-link-parameters)))
1848 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1849 (push (cons type parameters) org-link-parameters)
1850 (org-make-link-regexps)
1851 (org-element-update-syntax))))
1853 (defun org-link-types ()
1854 "Return a list of known link types."
1855 (mapcar #'car org-link-parameters))
1857 (defcustom org-link-abbrev-alist nil
1858 "Alist of link abbreviations.
1859 The car of each element is a string, to be replaced at the start of a link.
1860 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1861 links in Org buffers can have an optional tag after a double colon, e.g.,
1863 [[linkkey:tag][description]]
1865 The `linkkey' must be a single word, starting with a letter, followed
1866 by letters, numbers, `-' or `_'.
1868 If REPLACE is a string, the tag will simply be appended to create the link.
1869 If the string contains \"%s\", the tag will be inserted there. If the string
1870 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1871 at that point (see the function `url-hexify-string'). If the string contains
1872 the specifier \"%(my-function)\", then the custom function `my-function' will
1873 be invoked: this function takes the tag as its only argument and must return
1874 a string.
1876 REPLACE may also be a function that will be called with the tag as the
1877 only argument to create the link, which should be returned as a string.
1879 See the manual for examples."
1880 :group 'org-link
1881 :type '(repeat
1882 (cons
1883 (string :tag "Protocol")
1884 (choice
1885 (string :tag "Format")
1886 (function)))))
1888 (defcustom org-descriptive-links t
1889 "Non-nil means Org will display descriptive links.
1890 E.g. [[https://orgmode.org][Org website]] will be displayed as
1891 \"Org Website\", hiding the link itself and just displaying its
1892 description. When set to nil, Org will display the full links
1893 literally.
1895 You can interactively set the value of this variable by calling
1896 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1897 :group 'org-link
1898 :type 'boolean)
1900 (defcustom org-link-file-path-type 'adaptive
1901 "How the path name in file links should be stored.
1902 Valid values are:
1904 relative Relative to the current directory, i.e. the directory of the file
1905 into which the link is being inserted.
1906 absolute Absolute path, if possible with ~ for home directory.
1907 noabbrev Absolute path, no abbreviation of home directory.
1908 adaptive Use relative path for files in the current directory and sub-
1909 directories of it. For other files, use an absolute path."
1910 :group 'org-link
1911 :type '(choice
1912 (const relative)
1913 (const absolute)
1914 (const noabbrev)
1915 (const adaptive)))
1917 (defvaralias 'org-activate-links 'org-highlight-links)
1918 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1919 "Types of links that should be highlighted in Org files.
1921 This is a list of symbols, each one of them leading to the
1922 highlighting of a certain link type.
1924 You can still open links that are not highlighted.
1926 In principle, it does not hurt to turn on highlighting for all
1927 link types. There may be a small gain when turning off unused
1928 link types. The types are:
1930 bracket The recommended [[link][description]] or [[link]] links with hiding.
1931 angle Links in angular brackets that may contain whitespace like
1932 <bbdb:Carsten Dominik>.
1933 plain Plain links in normal text, no whitespace, like http://google.com.
1934 radio Text that is matched by a radio target, see manual for details.
1935 tag Tag settings in a headline (link to tag search).
1936 date Time stamps (link to calendar).
1937 footnote Footnote labels.
1939 If you set this variable during an Emacs session, use `org-mode-restart'
1940 in the Org buffer so that the change takes effect."
1941 :group 'org-link
1942 :group 'org-appearance
1943 :type '(set :greedy t
1944 (const :tag "Double bracket links" bracket)
1945 (const :tag "Angular bracket links" angle)
1946 (const :tag "Plain text links" plain)
1947 (const :tag "Radio target matches" radio)
1948 (const :tag "Tags" tag)
1949 (const :tag "Timestamps" date)
1950 (const :tag "Footnotes" footnote)))
1952 (defcustom org-make-link-description-function nil
1953 "Function to use for generating link descriptions from links.
1954 This function must take two parameters: the first one is the
1955 link, the second one is the description generated by
1956 `org-insert-link'. The function should return the description to
1957 use."
1958 :group 'org-link
1959 :type '(choice (const nil) (function)))
1961 (defgroup org-link-store nil
1962 "Options concerning storing links in Org mode."
1963 :tag "Org Store Link"
1964 :group 'org-link)
1966 (defcustom org-url-hexify-p t
1967 "When non-nil, hexify URL when creating a link."
1968 :type 'boolean
1969 :version "24.3"
1970 :group 'org-link-store)
1972 (defcustom org-email-link-description-format "Email %c: %.30s"
1973 "Format of the description part of a link to an email or usenet message.
1974 The following %-escapes will be replaced by corresponding information:
1976 %F full \"From\" field
1977 %f name, taken from \"From\" field, address if no name
1978 %T full \"To\" field
1979 %t first name in \"To\" field, address if no name
1980 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1981 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1982 %s subject
1983 %d date
1984 %m message-id.
1986 You may use normal field width specification between the % and the letter.
1987 This is for example useful to limit the length of the subject.
1989 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1990 :group 'org-link-store
1991 :type 'string)
1993 (defcustom org-from-is-user-regexp
1994 (let (r1 r2)
1995 (when (and user-mail-address (not (string= user-mail-address "")))
1996 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1997 (when (and user-full-name (not (string= user-full-name "")))
1998 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1999 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2000 "Regexp matched against the \"From:\" header of an email or usenet message.
2001 It should match if the message is from the user him/herself."
2002 :group 'org-link-store
2003 :type 'regexp)
2005 (defcustom org-context-in-file-links t
2006 "Non-nil means file links from `org-store-link' contain context.
2007 \\<org-mode-map>
2008 A search string will be added to the file name with :: as separator
2009 and used to find the context when the link is activated by the command
2010 `org-open-at-point'. When this option is t, the entire active region
2011 will be placed in the search string of the file link. If set to a
2012 positive integer, only the first n lines of context will be stored.
2014 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2015 \\[org-store-link]')
2016 negates this setting for the duration of the command."
2017 :group 'org-link-store
2018 :type '(choice boolean integer))
2020 (defcustom org-keep-stored-link-after-insertion nil
2021 "Non-nil means keep link in list for entire session.
2022 \\<org-mode-map>
2023 The command `org-store-link' adds a link pointing to the current
2024 location to an internal list. These links accumulate during a session.
2025 The command `org-insert-link' can be used to insert links into any
2026 Org file (offering completion for all stored links).
2028 When this option is nil, every link which has been inserted once using
2029 `\\[org-insert-link]' will be removed from the list, to make completing the \
2030 unused
2031 links more efficient."
2032 :group 'org-link-store
2033 :type 'boolean)
2035 (defgroup org-link-follow nil
2036 "Options concerning following links in Org mode."
2037 :tag "Org Follow Link"
2038 :group 'org-link)
2040 (defcustom org-link-translation-function nil
2041 "Function to translate links with different syntax to Org syntax.
2042 This can be used to translate links created for example by the Planner
2043 or emacs-wiki packages to Org syntax.
2044 The function must accept two parameters, a TYPE containing the link
2045 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2046 which is everything after the link protocol. It should return a cons
2047 with possibly modified values of type and path.
2048 Org contains a function for this, so if you set this variable to
2049 `org-translate-link-from-planner', you should be able follow many
2050 links created by planner."
2051 :group 'org-link-follow
2052 :type '(choice (const nil) (function)))
2054 (defcustom org-follow-link-hook nil
2055 "Hook that is run after a link has been followed."
2056 :group 'org-link-follow
2057 :type 'hook)
2059 (defcustom org-tab-follows-link nil
2060 "Non-nil means on links TAB will follow the link.
2061 Needs to be set before org.el is loaded.
2062 This really should not be used, it does not make sense, and the
2063 implementation is bad."
2064 :group 'org-link-follow
2065 :type 'boolean)
2067 (defcustom org-return-follows-link nil
2068 "Non-nil means on links RET will follow the link.
2069 In tables, the special behavior of RET has precedence."
2070 :group 'org-link-follow
2071 :type 'boolean)
2073 (defcustom org-mouse-1-follows-link
2074 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2075 "Non-nil means mouse-1 on a link will follow the link.
2076 A longer mouse click will still set point. Needs to be set
2077 before org.el is loaded."
2078 :group 'org-link-follow
2079 :version "26.1"
2080 :package-version '(Org . "8.3")
2081 :type '(choice
2082 (const :tag "A double click follows the link" double)
2083 (const :tag "Unconditionally follow the link with mouse-1" t)
2084 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2086 (defcustom org-mark-ring-length 4
2087 "Number of different positions to be recorded in the ring.
2088 Changing this requires a restart of Emacs to work correctly."
2089 :group 'org-link-follow
2090 :type 'integer)
2092 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2093 "Non-nil means internal fuzzy links can only match headlines.
2095 When nil, the a fuzzy link may point to a target or a named
2096 construct in the document. When set to the special value
2097 `query-to-create', offer to create a new headline when none
2098 matched.
2100 Spaces and statistics cookies are ignored during heading searches."
2101 :group 'org-link-follow
2102 :version "24.1"
2103 :type '(choice
2104 (const :tag "Use fuzzy text search" nil)
2105 (const :tag "Match only exact headline" t)
2106 (const :tag "Match exact headline or query to create it"
2107 query-to-create))
2108 :safe #'symbolp)
2110 (defcustom org-link-frame-setup
2111 '((vm . vm-visit-folder-other-frame)
2112 (vm-imap . vm-visit-imap-folder-other-frame)
2113 (gnus . org-gnus-no-new-news)
2114 (file . find-file-other-window)
2115 (wl . wl-other-frame))
2116 "Setup the frame configuration for following links.
2117 When following a link with Emacs, it may often be useful to display
2118 this link in another window or frame. This variable can be used to
2119 set this up for the different types of links.
2120 For VM, use any of
2121 `vm-visit-folder'
2122 `vm-visit-folder-other-window'
2123 `vm-visit-folder-other-frame'
2124 For Gnus, use any of
2125 `gnus'
2126 `gnus-other-frame'
2127 `org-gnus-no-new-news'
2128 For FILE, use any of
2129 `find-file'
2130 `find-file-other-window'
2131 `find-file-other-frame'
2132 For Wanderlust use any of
2133 `wl'
2134 `wl-other-frame'
2135 For the calendar, use the variable `calendar-setup'.
2136 For BBDB, it is currently only possible to display the matches in
2137 another window."
2138 :group 'org-link-follow
2139 :type '(list
2140 (cons (const vm)
2141 (choice
2142 (const vm-visit-folder)
2143 (const vm-visit-folder-other-window)
2144 (const vm-visit-folder-other-frame)))
2145 (cons (const vm-imap)
2146 (choice
2147 (const vm-visit-imap-folder)
2148 (const vm-visit-imap-folder-other-window)
2149 (const vm-visit-imap-folder-other-frame)))
2150 (cons (const gnus)
2151 (choice
2152 (const gnus)
2153 (const gnus-other-frame)
2154 (const org-gnus-no-new-news)))
2155 (cons (const file)
2156 (choice
2157 (const find-file)
2158 (const find-file-other-window)
2159 (const find-file-other-frame)))
2160 (cons (const wl)
2161 (choice
2162 (const wl)
2163 (const wl-other-frame)))))
2165 (defcustom org-display-internal-link-with-indirect-buffer nil
2166 "Non-nil means use indirect buffer to display infile links.
2167 Activating internal links (from one location in a file to another location
2168 in the same file) normally just jumps to the location. When the link is
2169 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2170 is displayed in
2171 another window. When this option is set, the other window actually displays
2172 an indirect buffer clone of the current buffer, to avoid any visibility
2173 changes to the current buffer."
2174 :group 'org-link-follow
2175 :type 'boolean)
2177 (defcustom org-open-non-existing-files nil
2178 "Non-nil means `org-open-file' will open non-existing files.
2179 When nil, an error will be generated.
2180 This variable applies only to external applications because they
2181 might choke on non-existing files. If the link is to a file that
2182 will be opened in Emacs, the variable is ignored."
2183 :group 'org-link-follow
2184 :type 'boolean)
2186 (defcustom org-open-directory-means-index-dot-org nil
2187 "Non-nil means a link to a directory really means to index.org.
2188 When nil, following a directory link will run dired or open a finder/explorer
2189 window on that directory."
2190 :group 'org-link-follow
2191 :type 'boolean)
2193 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2194 "Non-nil means ask for confirmation before executing shell links.
2195 Shell links can be dangerous: just think about a link
2197 [[shell:rm -rf ~/*][Google Search]]
2199 This link would show up in your Org document as \"Google Search\",
2200 but really it would remove your entire home directory.
2201 Therefore we advise against setting this variable to nil.
2202 Just change it to `y-or-n-p' if you want to confirm with a
2203 single keystroke rather than having to type \"yes\"."
2204 :group 'org-link-follow
2205 :type '(choice
2206 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2207 (const :tag "with y-or-n (faster)" y-or-n-p)
2208 (const :tag "no confirmation (dangerous)" nil)))
2209 (put 'org-confirm-shell-link-function
2210 'safe-local-variable
2211 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2213 (defcustom org-confirm-shell-link-not-regexp ""
2214 "A regexp to skip confirmation for shell links."
2215 :group 'org-link-follow
2216 :version "24.1"
2217 :type 'regexp)
2219 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2220 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2221 Elisp links can be dangerous: just think about a link
2223 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2225 This link would show up in your Org document as \"Google Search\",
2226 but really it would remove your entire home directory.
2227 Therefore we advise against setting this variable to nil.
2228 Just change it to `y-or-n-p' if you want to confirm with a
2229 single keystroke rather than having to type \"yes\"."
2230 :group 'org-link-follow
2231 :type '(choice
2232 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2233 (const :tag "with y-or-n (faster)" y-or-n-p)
2234 (const :tag "no confirmation (dangerous)" nil)))
2235 (put 'org-confirm-shell-link-function
2236 'safe-local-variable
2237 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2239 (defcustom org-confirm-elisp-link-not-regexp ""
2240 "A regexp to skip confirmation for Elisp links."
2241 :group 'org-link-follow
2242 :version "24.1"
2243 :type 'regexp)
2245 (defconst org-file-apps-defaults-gnu
2246 '((remote . emacs)
2247 (system . mailcap)
2248 (t . mailcap))
2249 "Default file applications on a UNIX or GNU/Linux system.
2250 See `org-file-apps'.")
2252 (defconst org-file-apps-defaults-macosx
2253 '((remote . emacs)
2254 (system . "open %s")
2255 ("ps.gz" . "gv %s")
2256 ("eps.gz" . "gv %s")
2257 ("dvi" . "xdvi %s")
2258 ("fig" . "xfig %s")
2259 (t . "open %s"))
2260 "Default file applications on a macOS system.
2261 The system \"open\" is known as a default, but we use X11 applications
2262 for some files for which the OS does not have a good default.
2263 See `org-file-apps'.")
2265 (defconst org-file-apps-defaults-windowsnt
2266 (list '(remote . emacs)
2267 (cons 'system (lambda (file _path)
2268 (with-no-warnings (w32-shell-execute "open" file))))
2269 (cons t (lambda (file _path)
2270 (with-no-warnings (w32-shell-execute "open" file)))))
2271 "Default file applications on a Windows NT system.
2272 The system \"open\" is used for most files.
2273 See `org-file-apps'.")
2275 (defcustom org-file-apps
2276 '((auto-mode . emacs)
2277 ("\\.mm\\'" . default)
2278 ("\\.x?html?\\'" . default)
2279 ("\\.pdf\\'" . default))
2280 "External applications for opening `file:path' items in a document.
2281 \\<org-mode-map>\
2283 Org mode uses system defaults for different file types, but
2284 you can use this variable to set the application for a given file
2285 extension. The entries in this list are cons cells where the car identifies
2286 files and the cdr the corresponding command.
2288 Possible values for the file identifier are:
2290 \"string\" A string as a file identifier can be interpreted in different
2291 ways, depending on its contents:
2293 - Alphanumeric characters only:
2294 Match links with this file extension.
2295 Example: (\"pdf\" . \"evince %s\")
2296 to open PDFs with evince.
2298 - Regular expression: Match links where the
2299 filename matches the regexp. If you want to
2300 use groups here, use shy groups.
2302 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2303 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2304 to open *.html and *.xhtml with firefox.
2306 - Regular expression which contains (non-shy) groups:
2307 Match links where the whole link, including \"::\", and
2308 anything after that, matches the regexp.
2309 In a custom command string, %1, %2, etc. are replaced with
2310 the parts of the link that were matched by the groups.
2311 For backwards compatibility, if a command string is given
2312 that does not use any of the group matches, this case is
2313 handled identically to the second one (i.e. match against
2314 file name only).
2315 In a custom function, you can access the group matches with
2316 (match-string n link).
2318 Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
2319 \"evince -p %1 %s\")
2320 to open [[file:document.pdf::5]] with evince at page 5.
2322 `directory' Matches a directory
2323 `remote' Matches a remote file, accessible through tramp or efs.
2324 Remote files most likely should be visited through Emacs
2325 because external applications cannot handle such paths.
2326 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2327 so all files Emacs knows how to handle. Using this with
2328 command `emacs' will open most files in Emacs. Beware that this
2329 will also open html files inside Emacs, unless you add
2330 (\"html\" . default) to the list as well.
2331 `system' The system command to open files, like `open' on Windows
2332 and macOS, and mailcap under GNU/Linux. This is the command
2333 that will be selected if you call `org-open-at-point' with a
2334 double prefix argument (`\\[universal-argument] \
2335 \\[universal-argument] \\[org-open-at-point]').
2336 t Default for files not matched by any of the other options.
2338 Possible values for the command are:
2340 `emacs' The file will be visited by the current Emacs process.
2341 `default' Use the default application for this file type, which is the
2342 association for t in the list, most likely in the system-specific
2343 part. This can be used to overrule an unwanted setting in the
2344 system-specific variable.
2345 `system' Use the system command for opening files, like \"open\".
2346 This command is specified by the entry whose car is `system'.
2347 Most likely, the system-specific version of this variable
2348 does define this command, but you can overrule/replace it
2349 here.
2350 `mailcap' Use command specified in the mailcaps.
2351 string A command to be executed by a shell; %s will be replaced
2352 by the path to the file.
2353 function A Lisp function, which will be called with two arguments:
2354 the file path and the original link string, without the
2355 \"file:\" prefix.
2357 For more examples, see the system specific constants
2358 `org-file-apps-defaults-macosx'
2359 `org-file-apps-defaults-windowsnt'
2360 `org-file-apps-defaults-gnu'."
2361 :group 'org-link-follow
2362 :type '(repeat
2363 (cons (choice :value ""
2364 (string :tag "Extension")
2365 (const :tag "System command to open files" system)
2366 (const :tag "Default for unrecognized files" t)
2367 (const :tag "Remote file" remote)
2368 (const :tag "Links to a directory" directory)
2369 (const :tag "Any files that have Emacs modes"
2370 auto-mode))
2371 (choice :value ""
2372 (const :tag "Visit with Emacs" emacs)
2373 (const :tag "Use default" default)
2374 (const :tag "Use the system command" system)
2375 (string :tag "Command")
2376 (function :tag "Function")))))
2378 (defcustom org-doi-server-url "http://dx.doi.org/"
2379 "The URL of the DOI server."
2380 :type 'string
2381 :version "24.3"
2382 :group 'org-link-follow)
2384 (defgroup org-refile nil
2385 "Options concerning refiling entries in Org mode."
2386 :tag "Org Refile"
2387 :group 'org)
2389 (defcustom org-directory "~/org"
2390 "Directory with Org files.
2391 This is just a default location to look for Org files. There is no need
2392 at all to put your files into this directory. It is used in the
2393 following situations:
2395 1. When a capture template specifies a target file that is not an
2396 absolute path. The path will then be interpreted relative to
2397 `org-directory'
2398 2. When the value of variable `org-agenda-files' is a single file, any
2399 relative paths in this file will be taken as relative to
2400 `org-directory'."
2401 :group 'org-refile
2402 :group 'org-capture
2403 :type 'directory)
2405 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2406 "Default target for storing notes.
2407 Used as a fall back file for org-capture.el, for templates that
2408 do not specify a target file."
2409 :group 'org-refile
2410 :group 'org-capture
2411 :type 'file)
2413 (defcustom org-reverse-note-order nil
2414 "Non-nil means store new notes at the beginning of a file or entry.
2415 When nil, new notes will be filed to the end of a file or entry.
2416 This can also be a list with cons cells of regular expressions that
2417 are matched against file names, and values."
2418 :group 'org-capture
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Reverse always" t)
2422 (const :tag "Reverse never" nil)
2423 (repeat :tag "By file name regexp"
2424 (cons regexp boolean))))
2426 (defcustom org-log-refile nil
2427 "Information to record when a task is refiled.
2429 Possible values are:
2431 nil Don't add anything
2432 time Add a time stamp to the task
2433 note Prompt for a note and add it with template `org-log-note-headings'
2435 This option can also be set with on a per-file-basis with
2437 #+STARTUP: nologrefile
2438 #+STARTUP: logrefile
2439 #+STARTUP: lognoterefile
2441 You can have local logging settings for a subtree by setting the LOGGING
2442 property to one or more of these keywords.
2444 When bulk-refiling from the agenda, the value `note' is forbidden and
2445 will temporarily be changed to `time'."
2446 :group 'org-refile
2447 :group 'org-progress
2448 :version "24.1"
2449 :type '(choice
2450 (const :tag "No logging" nil)
2451 (const :tag "Record timestamp" time)
2452 (const :tag "Record timestamp with note." note)))
2454 (defcustom org-refile-targets nil
2455 "Targets for refiling entries with `\\[org-refile]'.
2456 This is a list of cons cells. Each cell contains:
2457 - a specification of the files to be considered, either a list of files,
2458 or a symbol whose function or variable value will be used to retrieve
2459 a file name or a list of file names. If you use `org-agenda-files' for
2460 that, all agenda files will be scanned for targets. Nil means consider
2461 headings in the current buffer.
2462 - A specification of how to find candidate refile targets. This may be
2463 any of:
2464 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2465 This tag has to be present in all target headlines, inheritance will
2466 not be considered.
2467 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2468 todo keyword.
2469 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2470 headlines that are refiling targets.
2471 - a cons cell (:level . N). Any headline of level N is considered a target.
2472 Note that, when `org-odd-levels-only' is set, level corresponds to
2473 order in hierarchy, not to the number of stars.
2474 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2475 Note that, when `org-odd-levels-only' is set, level corresponds to
2476 order in hierarchy, not to the number of stars.
2478 Each element of this list generates a set of possible targets.
2479 The union of these sets is presented (with completion) to
2480 the user by `org-refile'.
2482 You can set the variable `org-refile-target-verify-function' to a function
2483 to verify each headline found by the simple criteria above.
2485 When this variable is nil, all top-level headlines in the current buffer
2486 are used, equivalent to the value `((nil . (:level . 1))'."
2487 :group 'org-refile
2488 :type '(repeat
2489 (cons
2490 (choice :value org-agenda-files
2491 (const :tag "All agenda files" org-agenda-files)
2492 (const :tag "Current buffer" nil)
2493 (function) (variable) (file))
2494 (choice :tag "Identify target headline by"
2495 (cons :tag "Specific tag" (const :value :tag) (string))
2496 (cons :tag "TODO keyword" (const :value :todo) (string))
2497 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2498 (cons :tag "Level number" (const :value :level) (integer))
2499 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2501 (defcustom org-refile-target-verify-function nil
2502 "Function to verify if the headline at point should be a refile target.
2503 The function will be called without arguments, with point at the
2504 beginning of the headline. It should return t and leave point
2505 where it is if the headline is a valid target for refiling.
2507 If the target should not be selected, the function must return nil.
2508 In addition to this, it may move point to a place from where the search
2509 should be continued. For example, the function may decide that the entire
2510 subtree of the current entry should be excluded and move point to the end
2511 of the subtree."
2512 :group 'org-refile
2513 :type '(choice
2514 (const nil)
2515 (function)))
2517 (defcustom org-refile-use-cache nil
2518 "Non-nil means cache refile targets to speed up the process.
2519 \\<org-mode-map>\
2520 The cache for a particular file will be updated automatically when
2521 the buffer has been killed, or when any of the marker used for flagging
2522 refile targets no longer points at a live buffer.
2523 If you have added new entries to a buffer that might themselves be targets,
2524 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2525 if you find that easier, \
2526 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2527 \\[org-refile]'."
2528 :group 'org-refile
2529 :version "24.1"
2530 :type 'boolean)
2532 (defcustom org-refile-use-outline-path nil
2533 "Non-nil means provide refile targets as paths.
2534 So a level 3 headline will be available as level1/level2/level3.
2536 When the value is `file', also include the file name (without directory)
2537 into the path. In this case, you can also stop the completion after
2538 the file name, to get entries inserted as top level in the file.
2540 When `full-file-path', include the full file path.
2542 When `buffer-name', use the buffer name."
2543 :group 'org-refile
2544 :type '(choice
2545 (const :tag "Not" nil)
2546 (const :tag "Yes" t)
2547 (const :tag "Start with file name" file)
2548 (const :tag "Start with full file path" full-file-path)
2549 (const :tag "Start with buffer name" buffer-name)))
2551 (defcustom org-outline-path-complete-in-steps t
2552 "Non-nil means complete the outline path in hierarchical steps.
2553 When Org uses the refile interface to select an outline path (see
2554 `org-refile-use-outline-path'), the completion of the path can be
2555 done in a single go, or it can be done in steps down the headline
2556 hierarchy. Going in steps is probably the best if you do not use
2557 a special completion package like `ido' or `icicles'. However,
2558 when using these packages, going in one step can be very fast,
2559 while still showing the whole path to the entry."
2560 :group 'org-refile
2561 :type 'boolean)
2563 (defcustom org-refile-allow-creating-parent-nodes nil
2564 "Non-nil means allow the creation of new nodes as refile targets.
2565 New nodes are then created by adding \"/new node name\" to the completion
2566 of an existing node. When the value of this variable is `confirm',
2567 new node creation must be confirmed by the user (recommended).
2568 When nil, the completion must match an existing entry.
2570 Note that, if the new heading is not seen by the criteria
2571 listed in `org-refile-targets', multiple instances of the same
2572 heading would be created by trying again to file under the new
2573 heading."
2574 :group 'org-refile
2575 :type '(choice
2576 (const :tag "Never" nil)
2577 (const :tag "Always" t)
2578 (const :tag "Prompt for confirmation" confirm)))
2580 (defcustom org-refile-active-region-within-subtree nil
2581 "Non-nil means also refile active region within a subtree.
2583 By default `org-refile' doesn't allow refiling regions if they
2584 don't contain a set of subtrees, but it might be convenient to
2585 do so sometimes: in that case, the first line of the region is
2586 converted to a headline before refiling."
2587 :group 'org-refile
2588 :version "24.1"
2589 :type 'boolean)
2591 (defgroup org-todo nil
2592 "Options concerning TODO items in Org mode."
2593 :tag "Org TODO"
2594 :group 'org)
2596 (defgroup org-progress nil
2597 "Options concerning Progress logging in Org mode."
2598 :tag "Org Progress"
2599 :group 'org-time)
2601 (defvar org-todo-interpretation-widgets
2602 '((:tag "Sequence (cycling hits every state)" sequence)
2603 (:tag "Type (cycling directly to DONE)" type))
2604 "The available interpretation symbols for customizing `org-todo-keywords'.
2605 Interested libraries should add to this list.")
2607 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2608 "List of TODO entry keyword sequences and their interpretation.
2609 \\<org-mode-map>This is a list of sequences.
2611 Each sequence starts with a symbol, either `sequence' or `type',
2612 indicating if the keywords should be interpreted as a sequence of
2613 action steps, or as different types of TODO items. The first
2614 keywords are states requiring action - these states will select a headline
2615 for inclusion into the global TODO list Org produces. If one of the
2616 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2617 signify that no further action is necessary. If \"|\" is not found,
2618 the last keyword is treated as the only DONE state of the sequence.
2620 The command `\\[org-todo]' cycles an entry through these states, and one
2621 additional state where no keyword is present. For details about this
2622 cycling, see the manual.
2624 TODO keywords and interpretation can also be set on a per-file basis with
2625 the special #+SEQ_TODO and #+TYP_TODO lines.
2627 Each keyword can optionally specify a character for fast state selection
2628 \(in combination with the variable `org-use-fast-todo-selection')
2629 and specifiers for state change logging, using the same syntax that
2630 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2631 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2632 indicates to record a time stamp each time this state is selected.
2634 Each keyword may also specify if a timestamp or a note should be
2635 recorded when entering or leaving the state, by adding additional
2636 characters in the parenthesis after the keyword. This looks like this:
2637 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2638 record only the time of the state change. With X and Y being either
2639 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2640 Y when leaving the state if and only if the *target* state does not
2641 define X. You may omit any of the fast-selection key or X or /Y,
2642 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2644 For backward compatibility, this variable may also be just a list
2645 of keywords. In this case the interpretation (sequence or type) will be
2646 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2647 :group 'org-todo
2648 :group 'org-keywords
2649 :type '(choice
2650 (repeat :tag "Old syntax, just keywords"
2651 (string :tag "Keyword"))
2652 (repeat :tag "New syntax"
2653 (cons
2654 (choice
2655 :tag "Interpretation"
2656 ;;Quick and dirty way to see
2657 ;;`org-todo-interpretations'. This takes the
2658 ;;place of item arguments
2659 :convert-widget
2660 (lambda (widget)
2661 (widget-put widget
2662 :args (mapcar
2663 (lambda (x)
2664 (widget-convert
2665 (cons 'const x)))
2666 org-todo-interpretation-widgets))
2667 widget))
2668 (repeat
2669 (string :tag "Keyword"))))))
2671 (defvar-local org-todo-keywords-1 nil
2672 "All TODO and DONE keywords active in a buffer.")
2673 (defvar org-todo-keywords-for-agenda nil)
2674 (defvar org-done-keywords-for-agenda nil)
2675 (defvar org-todo-keyword-alist-for-agenda nil)
2676 (defvar org-tag-alist-for-agenda nil
2677 "Alist of all tags from all agenda files.")
2678 (defvar org-tag-groups-alist-for-agenda nil
2679 "Alist of all groups tags from all current agenda files.")
2680 (defvar-local org-tag-groups-alist nil)
2681 (defvar org-agenda-contributing-files nil)
2682 (defvar-local org-current-tag-alist nil
2683 "Alist of all tag groups in current buffer.
2684 This variable takes into consideration `org-tag-alist',
2685 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2686 (defvar-local org-not-done-keywords nil)
2687 (defvar-local org-done-keywords nil)
2688 (defvar-local org-todo-heads nil)
2689 (defvar-local org-todo-sets nil)
2690 (defvar-local org-todo-log-states nil)
2691 (defvar-local org-todo-kwd-alist nil)
2692 (defvar-local org-todo-key-alist nil)
2693 (defvar-local org-todo-key-trigger nil)
2695 (defcustom org-todo-interpretation 'sequence
2696 "Controls how TODO keywords are interpreted.
2697 This variable is in principle obsolete and is only used for
2698 backward compatibility, if the interpretation of todo keywords is
2699 not given already in `org-todo-keywords'. See that variable for
2700 more information."
2701 :group 'org-todo
2702 :group 'org-keywords
2703 :type '(choice (const sequence)
2704 (const type)))
2706 (defcustom org-use-fast-todo-selection t
2707 "\\<org-mode-map>\
2708 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2709 This variable describes if and under what circumstances the cycling
2710 mechanism for TODO keywords will be replaced by a single-key, direct
2711 selection scheme.
2713 When nil, fast selection is never used.
2715 When the symbol `prefix', it will be used when `org-todo' is called
2716 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2717 in an Org buffer, and
2718 `\\[universal-argument] t' in an agenda buffer.
2720 When t, fast selection is used by default. In this case, the prefix
2721 argument forces cycling instead.
2723 In all cases, the special interface is only used if access keys have
2724 actually been assigned by the user, i.e. if keywords in the configuration
2725 are followed by a letter in parenthesis, like TODO(t)."
2726 :group 'org-todo
2727 :type '(choice
2728 (const :tag "Never" nil)
2729 (const :tag "By default" t)
2730 (const :tag "Only with C-u C-c C-t" prefix)))
2732 (defcustom org-provide-todo-statistics t
2733 "Non-nil means update todo statistics after insert and toggle.
2734 ALL-HEADLINES means update todo statistics by including headlines
2735 with no TODO keyword as well, counting them as not done.
2736 A list of TODO keywords means the same, but skip keywords that are
2737 not in this list.
2738 When set to a list of two lists, the first list contains keywords
2739 to consider as TODO keywords, the second list contains keywords
2740 to consider as DONE keywords.
2742 When this is set, todo statistics is updated in the parent of the
2743 current entry each time a todo state is changed."
2744 :group 'org-todo
2745 :type '(choice
2746 (const :tag "Yes, only for TODO entries" t)
2747 (const :tag "Yes, including all entries" all-headlines)
2748 (repeat :tag "Yes, for TODOs in this list"
2749 (string :tag "TODO keyword"))
2750 (list :tag "Yes, for TODOs and DONEs in these lists"
2751 (repeat (string :tag "TODO keyword"))
2752 (repeat (string :tag "DONE keyword")))
2753 (other :tag "No TODO statistics" nil)))
2755 (defcustom org-hierarchical-todo-statistics t
2756 "Non-nil means TODO statistics covers just direct children.
2757 When nil, all entries in the subtree are considered.
2758 This has only an effect if `org-provide-todo-statistics' is set.
2759 To set this to nil for only a single subtree, use a COOKIE_DATA
2760 property and include the word \"recursive\" into the value."
2761 :group 'org-todo
2762 :type 'boolean)
2764 (defcustom org-after-todo-state-change-hook nil
2765 "Hook which is run after the state of a TODO item was changed.
2766 The new state (a string with a TODO keyword, or nil) is available in the
2767 Lisp variable `org-state'."
2768 :group 'org-todo
2769 :type 'hook)
2771 (defvar org-blocker-hook nil
2772 "Hook for functions that are allowed to block a state change.
2774 Functions in this hook should not modify the buffer.
2775 Each function gets as its single argument a property list,
2776 see `org-trigger-hook' for more information about this list.
2778 If any of the functions in this hook returns nil, the state change
2779 is blocked.")
2781 (defvar org-trigger-hook nil
2782 "Hook for functions that are triggered by a state change.
2784 Each function gets as its single argument a property list with at
2785 least the following elements:
2787 (:type type-of-change :position pos-at-entry-start
2788 :from old-state :to new-state)
2790 Depending on the type, more properties may be present.
2792 This mechanism is currently implemented for:
2794 TODO state changes
2795 ------------------
2796 :type todo-state-change
2797 :from previous state (keyword as a string), or nil, or a symbol
2798 `todo' or `done', to indicate the general type of state.
2799 :to new state, like in :from")
2801 (defcustom org-enforce-todo-dependencies nil
2802 "Non-nil means undone TODO entries will block switching the parent to DONE.
2803 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2804 be blocked if any prior sibling is not yet done.
2805 Finally, if the parent is blocked because of ordered siblings of its own,
2806 the child will also be blocked."
2807 :set (lambda (var val)
2808 (set var val)
2809 (if val
2810 (add-hook 'org-blocker-hook
2811 'org-block-todo-from-children-or-siblings-or-parent)
2812 (remove-hook 'org-blocker-hook
2813 'org-block-todo-from-children-or-siblings-or-parent)))
2814 :group 'org-todo
2815 :type 'boolean)
2817 (defcustom org-enforce-todo-checkbox-dependencies nil
2818 "Non-nil means unchecked boxes will block switching the parent to DONE.
2819 When this is nil, checkboxes have no influence on switching TODO states.
2820 When non-nil, you first need to check off all check boxes before the TODO
2821 entry can be switched to DONE.
2822 This variable needs to be set before org.el is loaded, and you need to
2823 restart Emacs after a change to make the change effective. The only way
2824 to change is while Emacs is running is through the customize interface."
2825 :set (lambda (var val)
2826 (set var val)
2827 (if val
2828 (add-hook 'org-blocker-hook
2829 'org-block-todo-from-checkboxes)
2830 (remove-hook 'org-blocker-hook
2831 'org-block-todo-from-checkboxes)))
2832 :group 'org-todo
2833 :type 'boolean)
2835 (defcustom org-treat-insert-todo-heading-as-state-change nil
2836 "Non-nil means inserting a TODO heading is treated as state change.
2837 So when the command `\\[org-insert-todo-heading]' is used, state change
2838 logging will apply if appropriate. When nil, the new TODO item will
2839 be inserted directly, and no logging will take place."
2840 :group 'org-todo
2841 :type 'boolean)
2843 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2844 "Non-nil means switching TODO states with S-cursor counts as state change.
2845 This is the default behavior. However, setting this to nil allows a
2846 convenient way to select a TODO state and bypass any logging associated
2847 with that."
2848 :group 'org-todo
2849 :type 'boolean)
2851 (defcustom org-todo-state-tags-triggers nil
2852 "Tag changes that should be triggered by TODO state changes.
2853 This is a list. Each entry is
2855 (state-change (tag . flag) .......)
2857 State-change can be a string with a state, and empty string to indicate the
2858 state that has no TODO keyword, or it can be one of the symbols `todo'
2859 or `done', meaning any not-done or done state, respectively."
2860 :group 'org-todo
2861 :group 'org-tags
2862 :type '(repeat
2863 (cons (choice :tag "When changing to"
2864 (const :tag "Not-done state" todo)
2865 (const :tag "Done state" done)
2866 (string :tag "State"))
2867 (repeat
2868 (cons :tag "Tag action"
2869 (string :tag "Tag")
2870 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2872 (defcustom org-log-done nil
2873 "Information to record when a task moves to the DONE state.
2875 Possible values are:
2877 nil Don't add anything, just change the keyword
2878 time Add a time stamp to the task
2879 note Prompt for a note and add it with template `org-log-note-headings'
2881 This option can also be set with on a per-file-basis with
2883 #+STARTUP: nologdone
2884 #+STARTUP: logdone
2885 #+STARTUP: lognotedone
2887 You can have local logging settings for a subtree by setting the LOGGING
2888 property to one or more of these keywords."
2889 :group 'org-todo
2890 :group 'org-progress
2891 :type '(choice
2892 (const :tag "No logging" nil)
2893 (const :tag "Record CLOSED timestamp" time)
2894 (const :tag "Record CLOSED timestamp with note." note)))
2896 ;; Normalize old uses of org-log-done.
2897 (cond
2898 ((eq org-log-done t) (setq org-log-done 'time))
2899 ((and (listp org-log-done) (memq 'done org-log-done))
2900 (setq org-log-done 'note)))
2902 (defcustom org-log-reschedule nil
2903 "Information to record when the scheduling date of a tasks is modified.
2905 Possible values are:
2907 nil Don't add anything, just change the date
2908 time Add a time stamp to the task
2909 note Prompt for a note and add it with template `org-log-note-headings'
2911 This option can also be set with on a per-file-basis with
2913 #+STARTUP: nologreschedule
2914 #+STARTUP: logreschedule
2915 #+STARTUP: lognotereschedule"
2916 :group 'org-todo
2917 :group 'org-progress
2918 :type '(choice
2919 (const :tag "No logging" nil)
2920 (const :tag "Record timestamp" time)
2921 (const :tag "Record timestamp with note." note)))
2923 (defcustom org-log-redeadline nil
2924 "Information to record when the deadline date of a tasks is modified.
2926 Possible values are:
2928 nil Don't add anything, just change the date
2929 time Add a time stamp to the task
2930 note Prompt for a note and add it with template `org-log-note-headings'
2932 This option can also be set with on a per-file-basis with
2934 #+STARTUP: nologredeadline
2935 #+STARTUP: logredeadline
2936 #+STARTUP: lognoteredeadline
2938 You can have local logging settings for a subtree by setting the LOGGING
2939 property to one or more of these keywords."
2940 :group 'org-todo
2941 :group 'org-progress
2942 :type '(choice
2943 (const :tag "No logging" nil)
2944 (const :tag "Record timestamp" time)
2945 (const :tag "Record timestamp with note." note)))
2947 (defcustom org-log-note-clock-out nil
2948 "Non-nil means record a note when clocking out of an item.
2949 This can also be configured on a per-file basis by adding one of
2950 the following lines anywhere in the buffer:
2952 #+STARTUP: lognoteclock-out
2953 #+STARTUP: nolognoteclock-out"
2954 :group 'org-todo
2955 :group 'org-progress
2956 :type 'boolean)
2958 (defcustom org-log-done-with-time t
2959 "Non-nil means the CLOSED time stamp will contain date and time.
2960 When nil, only the date will be recorded."
2961 :group 'org-progress
2962 :type 'boolean)
2964 (defcustom org-log-note-headings
2965 '((done . "CLOSING NOTE %t")
2966 (state . "State %-12s from %-12S %t")
2967 (note . "Note taken on %t")
2968 (reschedule . "Rescheduled from %S on %t")
2969 (delschedule . "Not scheduled, was %S on %t")
2970 (redeadline . "New deadline from %S on %t")
2971 (deldeadline . "Removed deadline, was %S on %t")
2972 (refile . "Refiled on %t")
2973 (clock-out . ""))
2974 "Headings for notes added to entries.
2976 The value is an alist, with the car being a symbol indicating the
2977 note context, and the cdr is the heading to be used. The heading
2978 may also be the empty string. The following placeholders can be
2979 used:
2981 %t a time stamp.
2982 %T an active time stamp instead the default inactive one
2983 %d a short-format time stamp.
2984 %D an active short-format time stamp.
2985 %s the new TODO state or time stamp (inactive), in double quotes.
2986 %S the old TODO state or time stamp (inactive), in double quotes.
2987 %u the user name.
2988 %U full user name.
2990 In fact, it is not a good idea to change the `state' entry,
2991 because Agenda Log mode depends on the format of these entries."
2992 :group 'org-todo
2993 :group 'org-progress
2994 :type '(list :greedy t
2995 (cons (const :tag "Heading when closing an item" done) string)
2996 (cons (const :tag
2997 "Heading when changing todo state (todo sequence only)"
2998 state) string)
2999 (cons (const :tag "Heading when just taking a note" note) string)
3000 (cons (const :tag "Heading when rescheduling" reschedule) string)
3001 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3002 (cons (const :tag "Heading when changing deadline" redeadline) string)
3003 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3004 (cons (const :tag "Heading when refiling" refile) string)
3005 (cons (const :tag "Heading when clocking out" clock-out) string)))
3007 (unless (assq 'note org-log-note-headings)
3008 (push '(note . "%t") org-log-note-headings))
3010 (defcustom org-log-into-drawer nil
3011 "Non-nil means insert state change notes and time stamps into a drawer.
3012 When nil, state changes notes will be inserted after the headline and
3013 any scheduling and clock lines, but not inside a drawer.
3015 The value of this variable should be the name of the drawer to use.
3016 LOGBOOK is proposed as the default drawer for this purpose, you can
3017 also set this to a string to define the drawer of your choice.
3019 A value of t is also allowed, representing \"LOGBOOK\".
3021 A value of t or nil can also be set with on a per-file-basis with
3023 #+STARTUP: logdrawer
3024 #+STARTUP: nologdrawer
3026 If this variable is set, `org-log-state-notes-insert-after-drawers'
3027 will be ignored.
3029 You can set the property LOG_INTO_DRAWER to overrule this setting for
3030 a subtree.
3032 Do not check directly this variable in a Lisp program. Call
3033 function `org-log-into-drawer' instead."
3034 :group 'org-todo
3035 :group 'org-progress
3036 :type '(choice
3037 (const :tag "Not into a drawer" nil)
3038 (const :tag "LOGBOOK" t)
3039 (string :tag "Other")))
3041 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3043 (defun org-log-into-drawer ()
3044 "Name of the log drawer, as a string, or nil.
3045 This is the value of `org-log-into-drawer'. However, if the
3046 current entry has or inherits a LOG_INTO_DRAWER property, it will
3047 be used instead of the default value."
3048 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3049 (cond ((equal p "nil") nil)
3050 ((equal p "t") "LOGBOOK")
3051 ((stringp p) p)
3052 (p "LOGBOOK")
3053 ((stringp org-log-into-drawer) org-log-into-drawer)
3054 (org-log-into-drawer "LOGBOOK"))))
3056 (defcustom org-log-state-notes-insert-after-drawers nil
3057 "Non-nil means insert state change notes after any drawers in entry.
3058 Only the drawers that *immediately* follow the headline and the
3059 deadline/scheduled line are skipped.
3060 When nil, insert notes right after the heading and perhaps the line
3061 with deadline/scheduling if present.
3063 This variable will have no effect if `org-log-into-drawer' is
3064 set."
3065 :group 'org-todo
3066 :group 'org-progress
3067 :type 'boolean)
3069 (defcustom org-log-states-order-reversed t
3070 "Non-nil means the latest state note will be directly after heading.
3071 When nil, the state change notes will be ordered according to time.
3073 This option can also be set with on a per-file-basis with
3075 #+STARTUP: logstatesreversed
3076 #+STARTUP: nologstatesreversed"
3077 :group 'org-todo
3078 :group 'org-progress
3079 :type 'boolean)
3081 (defcustom org-todo-repeat-to-state nil
3082 "The TODO state to which a repeater should return the repeating task.
3083 By default this is the first task of a TODO sequence or the
3084 previous state of a TYPE_TODO set. But you can specify to use
3085 the previous state in a TODO sequence or a string.
3087 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3088 entry, which has precedence over this option."
3089 :group 'org-todo
3090 :version "24.1"
3091 :type '(choice (const :tag "Use the previous TODO state" t)
3092 (const :tag "Use the head of the TODO sequence" nil)
3093 (string :tag "Use a specific TODO state")))
3095 (defcustom org-log-repeat 'time
3096 "Non-nil means record moving through the DONE state when triggering repeat.
3097 An auto-repeating task is immediately switched back to TODO when
3098 marked DONE. If you are not logging state changes (by adding \"@\"
3099 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3100 record a closing note, there will be no record of the task moving
3101 through DONE. This variable forces taking a note anyway.
3103 nil Don't force a record
3104 time Record a time stamp
3105 note Prompt for a note and add it with template `org-log-note-headings'
3107 This option can also be set with on a per-file-basis with
3109 #+STARTUP: nologrepeat
3110 #+STARTUP: logrepeat
3111 #+STARTUP: lognoterepeat
3113 You can have local logging settings for a subtree by setting the LOGGING
3114 property to one or more of these keywords."
3115 :group 'org-todo
3116 :group 'org-progress
3117 :type '(choice
3118 (const :tag "Don't force a record" nil)
3119 (const :tag "Force recording the DONE state" time)
3120 (const :tag "Force recording a note with the DONE state" note)))
3123 (defgroup org-priorities nil
3124 "Priorities in Org mode."
3125 :tag "Org Priorities"
3126 :group 'org-todo)
3128 (defcustom org-enable-priority-commands t
3129 "Non-nil means priority commands are active.
3130 When nil, these commands will be disabled, so that you never accidentally
3131 set a priority."
3132 :group 'org-priorities
3133 :type 'boolean)
3135 (defcustom org-highest-priority ?A
3136 "The highest priority of TODO items. A character like ?A, ?B etc.
3137 Must have a smaller ASCII number than `org-lowest-priority'."
3138 :group 'org-priorities
3139 :type 'character)
3141 (defcustom org-lowest-priority ?C
3142 "The lowest priority of TODO items. A character like ?A, ?B etc.
3143 Must have a larger ASCII number than `org-highest-priority'."
3144 :group 'org-priorities
3145 :type 'character)
3147 (defcustom org-default-priority ?B
3148 "The default priority of TODO items.
3149 This is the priority an item gets if no explicit priority is given.
3150 When starting to cycle on an empty priority the first step in the cycle
3151 depends on `org-priority-start-cycle-with-default'. The resulting first
3152 step priority must not exceed the range from `org-highest-priority' to
3153 `org-lowest-priority' which means that `org-default-priority' has to be
3154 in this range exclusive or inclusive the range boundaries. Else the
3155 first step refuses to set the default and the second will fall back
3156 to (depending on the command used) the highest or lowest priority."
3157 :group 'org-priorities
3158 :type 'character)
3160 (defcustom org-priority-start-cycle-with-default t
3161 "Non-nil means start with default priority when starting to cycle.
3162 When this is nil, the first step in the cycle will be (depending on the
3163 command used) one higher or lower than the default priority.
3164 See also `org-default-priority'."
3165 :group 'org-priorities
3166 :type 'boolean)
3168 (defcustom org-get-priority-function nil
3169 "Function to extract the priority from a string.
3170 The string is normally the headline. If this is nil Org computes the
3171 priority from the priority cookie like [#A] in the headline. It returns
3172 an integer, increasing by 1000 for each priority level.
3173 The user can set a different function here, which should take a string
3174 as an argument and return the numeric priority."
3175 :group 'org-priorities
3176 :version "24.1"
3177 :type '(choice
3178 (const nil)
3179 (function)))
3181 (defgroup org-time nil
3182 "Options concerning time stamps and deadlines in Org mode."
3183 :tag "Org Time"
3184 :group 'org)
3186 (defcustom org-time-stamp-rounding-minutes '(0 5)
3187 "Number of minutes to round time stamps to.
3188 \\<org-mode-map>\
3189 These are two values, the first applies when first creating a time stamp.
3190 The second applies when changing it with the commands `S-up' and `S-down'.
3191 When changing the time stamp, this means that it will change in steps
3192 of N minutes, as given by the second value.
3194 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3195 numbers should be factors of 60, so for example 5, 10, 15.
3197 When this is larger than 1, you can still force an exact time stamp by using
3198 a double prefix argument to a time stamp command like \
3199 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3200 and by using a prefix arg to `S-up/down' to specify the exact number
3201 of minutes to shift."
3202 :group 'org-time
3203 :get (lambda (var) ; Make sure both elements are there
3204 (if (integerp (default-value var))
3205 (list (default-value var) 5)
3206 (default-value var)))
3207 :type '(list
3208 (integer :tag "when inserting times")
3209 (integer :tag "when modifying times")))
3211 ;; Normalize old customizations of this variable.
3212 (when (integerp org-time-stamp-rounding-minutes)
3213 (setq org-time-stamp-rounding-minutes
3214 (list org-time-stamp-rounding-minutes
3215 org-time-stamp-rounding-minutes)))
3217 (defcustom org-display-custom-times nil
3218 "Non-nil means overlay custom formats over all time stamps.
3219 The formats are defined through the variable `org-time-stamp-custom-formats'.
3220 To turn this on on a per-file basis, insert anywhere in the file:
3221 #+STARTUP: customtime"
3222 :group 'org-time
3223 :set 'set-default
3224 :type 'sexp)
3225 (make-variable-buffer-local 'org-display-custom-times)
3227 (defcustom org-time-stamp-custom-formats
3228 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3229 "Custom formats for time stamps. See `format-time-string' for the syntax.
3230 These are overlaid over the default ISO format if the variable
3231 `org-display-custom-times' is set. Time like %H:%M should be at the
3232 end of the second format. The custom formats are also honored by export
3233 commands, if custom time display is turned on at the time of export."
3234 :group 'org-time
3235 :type 'sexp)
3237 (defun org-time-stamp-format (&optional long inactive)
3238 "Get the right format for a time string."
3239 (let ((f (if long (cdr org-time-stamp-formats)
3240 (car org-time-stamp-formats))))
3241 (if inactive
3242 (concat "[" (substring f 1 -1) "]")
3243 f)))
3245 (defcustom org-deadline-warning-days 14
3246 "Number of days before expiration during which a deadline becomes active.
3247 This variable governs the display in sparse trees and in the agenda.
3248 When 0 or negative, it means use this number (the absolute value of it)
3249 even if a deadline has a different individual lead time specified.
3251 Custom commands can set this variable in the options section."
3252 :group 'org-time
3253 :group 'org-agenda-daily/weekly
3254 :type 'integer)
3256 (defcustom org-scheduled-delay-days 0
3257 "Number of days before a scheduled item becomes active.
3258 This variable governs the display in sparse trees and in the agenda.
3259 The default value (i.e. 0) means: don't delay scheduled item.
3260 When negative, it means use this number (the absolute value of it)
3261 even if a scheduled item has a different individual delay time
3262 specified.
3264 Custom commands can set this variable in the options section."
3265 :group 'org-time
3266 :group 'org-agenda-daily/weekly
3267 :version "24.4"
3268 :package-version '(Org . "8.0")
3269 :type 'integer)
3271 (defcustom org-read-date-prefer-future t
3272 "Non-nil means assume future for incomplete date input from user.
3273 This affects the following situations:
3274 1. The user gives a month but not a year.
3275 For example, if it is April and you enter \"feb 2\", this will be read
3276 as Feb 2, *next* year. \"May 5\", however, will be this year.
3277 2. The user gives a day, but no month.
3278 For example, if today is the 15th, and you enter \"3\", Org will read
3279 this as the third of *next* month. However, if you enter \"17\",
3280 it will be considered as *this* month.
3282 If you set this variable to the symbol `time', then also the following
3283 will work:
3285 3. If the user gives a time.
3286 If the time is before now, it will be interpreted as tomorrow.
3288 Currently none of this works for ISO week specifications.
3290 When this option is nil, the current day, month and year will always be
3291 used as defaults.
3293 See also `org-agenda-jump-prefer-future'."
3294 :group 'org-time
3295 :type '(choice
3296 (const :tag "Never" nil)
3297 (const :tag "Check month and day" t)
3298 (const :tag "Check month, day, and time" time)))
3300 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3301 "Should the agenda jump command prefer the future for incomplete dates?
3302 The default is to do the same as configured in `org-read-date-prefer-future'.
3303 But you can also set a deviating value here.
3304 This may t or nil, or the symbol `org-read-date-prefer-future'."
3305 :group 'org-agenda
3306 :group 'org-time
3307 :version "24.1"
3308 :type '(choice
3309 (const :tag "Use org-read-date-prefer-future"
3310 org-read-date-prefer-future)
3311 (const :tag "Never" nil)
3312 (const :tag "Always" t)))
3314 (defcustom org-read-date-force-compatible-dates t
3315 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3317 Depending on the system Emacs is running on, certain dates cannot
3318 be represented with the type used internally to represent time.
3319 Dates between 1970-1-1 and 2038-1-1 can always be represented
3320 correctly. Some systems allow for earlier dates, some for later,
3321 some for both. One way to find out it to insert any date into an
3322 Org buffer, putting the cursor on the year and hitting S-up and
3323 S-down to test the range.
3325 When this variable is set to t, the date/time prompt will not let
3326 you specify dates outside the 1970-2037 range, so it is certain that
3327 these dates will work in whatever version of Emacs you are
3328 running, and also that you can move a file from one Emacs implementation
3329 to another. WHenever Org is forcing the year for you, it will display
3330 a message and beep.
3332 When this variable is nil, Org will check if the date is
3333 representable in the specific Emacs implementation you are using.
3334 If not, it will force a year, usually the current year, and beep
3335 to remind you. Currently this setting is not recommended because
3336 the likelihood that you will open your Org files in an Emacs that
3337 has limited date range is not negligible.
3339 A workaround for this problem is to use diary sexp dates for time
3340 stamps outside of this range."
3341 :group 'org-time
3342 :version "24.1"
3343 :type 'boolean)
3345 (defcustom org-read-date-display-live t
3346 "Non-nil means display current interpretation of date prompt live.
3347 This display will be in an overlay, in the minibuffer."
3348 :group 'org-time
3349 :type 'boolean)
3351 (defcustom org-read-date-popup-calendar t
3352 "Non-nil means pop up a calendar when prompting for a date.
3353 In the calendar, the date can be selected with mouse-1. However, the
3354 minibuffer will also be active, and you can simply enter the date as well.
3355 When nil, only the minibuffer will be available."
3356 :group 'org-time
3357 :type 'boolean)
3358 (defvaralias 'org-popup-calendar-for-date-prompt
3359 'org-read-date-popup-calendar)
3361 (defcustom org-extend-today-until 0
3362 "The hour when your day really ends. Must be an integer.
3363 This has influence for the following applications:
3364 - When switching the agenda to \"today\". It it is still earlier than
3365 the time given here, the day recognized as TODAY is actually yesterday.
3366 - When a date is read from the user and it is still before the time given
3367 here, the current date and time will be assumed to be yesterday, 23:59.
3368 Also, timestamps inserted in capture templates follow this rule.
3370 IMPORTANT: This is a feature whose implementation is and likely will
3371 remain incomplete. Really, it is only here because past midnight seems to
3372 be the favorite working time of John Wiegley :-)"
3373 :group 'org-time
3374 :type 'integer)
3376 (defcustom org-use-effective-time nil
3377 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3378 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3379 \"effective time\" of any timestamps between midnight and 8am will be
3380 23:59 of the previous day."
3381 :group 'org-time
3382 :version "24.1"
3383 :type 'boolean)
3385 (defcustom org-use-last-clock-out-time-as-effective-time nil
3386 "When non-nil, use the last clock out time for `org-todo'.
3387 Note that this option has precedence over the combined use of
3388 `org-use-effective-time' and `org-extend-today-until'."
3389 :group 'org-time
3390 :version "24.4"
3391 :package-version '(Org . "8.0")
3392 :type 'boolean)
3394 (defcustom org-edit-timestamp-down-means-later nil
3395 "Non-nil means S-down will increase the time in a time stamp.
3396 When nil, S-up will increase."
3397 :group 'org-time
3398 :type 'boolean)
3400 (defcustom org-calendar-follow-timestamp-change t
3401 "Non-nil means make the calendar window follow timestamp changes.
3402 When a timestamp is modified and the calendar window is visible, it will be
3403 moved to the new date."
3404 :group 'org-time
3405 :type 'boolean)
3407 (defgroup org-tags nil
3408 "Options concerning tags in Org mode."
3409 :tag "Org Tags"
3410 :group 'org)
3412 (defcustom org-tag-alist nil
3413 "Default tags available in Org files.
3415 The value of this variable is an alist. Associations either:
3417 (TAG)
3418 (TAG . SELECT)
3419 (SPECIAL)
3421 where TAG is a tag as a string, SELECT is character, used to
3422 select that tag through the fast tag selection interface, and
3423 SPECIAL is one of the following keywords: `:startgroup',
3424 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3425 `:newline'. These keywords are used to define a hierarchy of
3426 tags. See manual for details.
3428 When this variable is nil, Org mode bases tag input on what is
3429 already in the buffer. The value can be overridden locally by
3430 using a TAGS keyword, e.g.,
3432 #+TAGS: tag1 tag2
3434 See also `org-tag-persistent-alist' to sidestep this behavior."
3435 :group 'org-tags
3436 :type '(repeat
3437 (choice
3438 (cons :tag "Tag with key"
3439 (string :tag "Tag name")
3440 (character :tag "Access char"))
3441 (list :tag "Tag" (string :tag "Tag name"))
3442 (const :tag "Start radio group" (:startgroup))
3443 (const :tag "Start tag group, non distinct" (:startgrouptag))
3444 (const :tag "Group tags delimiter" (:grouptags))
3445 (const :tag "End radio group" (:endgroup))
3446 (const :tag "End tag group, non distinct" (:endgrouptag))
3447 (const :tag "New line" (:newline)))))
3449 (defcustom org-tag-persistent-alist nil
3450 "Tags always available in Org files.
3452 The value of this variable is an alist. Associations either:
3454 (TAG)
3455 (TAG . SELECT)
3456 (SPECIAL)
3458 where TAG is a tag as a string, SELECT is a character, used to
3459 select that tag through the fast tag selection interface, and
3460 SPECIAL is one of the following keywords: `:startgroup',
3461 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3462 `:newline'. These keywords are used to define a hierarchy of
3463 tags. See manual for details.
3465 Unlike to `org-tag-alist', tags defined in this variable do not
3466 depend on a local TAGS keyword. Instead, to disable these tags
3467 on a per-file basis, insert anywhere in the file:
3469 #+STARTUP: noptag"
3470 :group 'org-tags
3471 :type '(repeat
3472 (choice
3473 (cons :tag "Tag with key"
3474 (string :tag "Tag name")
3475 (character :tag "Access char"))
3476 (list :tag "Tag" (string :tag "Tag name"))
3477 (const :tag "Start radio group" (:startgroup))
3478 (const :tag "Start tag group, non distinct" (:startgrouptag))
3479 (const :tag "Group tags delimiter" (:grouptags))
3480 (const :tag "End radio group" (:endgroup))
3481 (const :tag "End tag group, non distinct" (:endgrouptag))
3482 (const :tag "New line" (:newline)))))
3484 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3485 "If non-nil, always offer completion for all tags of all agenda files.
3486 Instead of customizing this variable directly, you might want to
3487 set it locally for capture buffers, because there no list of
3488 tags in that file can be created dynamically (there are none).
3490 (add-hook \\='org-capture-mode-hook
3491 (lambda ()
3492 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3493 :group 'org-tags
3494 :version "24.1"
3495 :type 'boolean)
3497 (defvar org-file-tags nil
3498 "List of tags that can be inherited by all entries in the file.
3499 The tags will be inherited if the variable `org-use-tag-inheritance'
3500 says they should be.
3501 This variable is populated from #+FILETAGS lines.")
3503 (defcustom org-use-fast-tag-selection 'auto
3504 "Non-nil means use fast tag selection scheme.
3505 This is a special interface to select and deselect tags with single keys.
3506 When nil, fast selection is never used.
3507 When the symbol `auto', fast selection is used if and only if selection
3508 characters for tags have been configured, either through the variable
3509 `org-tag-alist' or through a #+TAGS line in the buffer.
3510 When t, fast selection is always used and selection keys are assigned
3511 automatically if necessary."
3512 :group 'org-tags
3513 :type '(choice
3514 (const :tag "Always" t)
3515 (const :tag "Never" nil)
3516 (const :tag "When selection characters are configured" auto)))
3518 (defcustom org-fast-tag-selection-single-key nil
3519 "Non-nil means fast tag selection exits after first change.
3520 When nil, you have to press RET to exit it.
3521 During fast tag selection, you can toggle this flag with `C-c'.
3522 This variable can also have the value `expert'. In this case, the window
3523 displaying the tags menu is not even shown, until you press C-c again."
3524 :group 'org-tags
3525 :type '(choice
3526 (const :tag "No" nil)
3527 (const :tag "Yes" t)
3528 (const :tag "Expert" expert)))
3530 (defvar org-fast-tag-selection-include-todo nil
3531 "Non-nil means fast tags selection interface will also offer TODO states.
3532 This is an undocumented feature, you should not rely on it.")
3534 (defcustom org-tags-column -77
3535 "The column to which tags should be indented in a headline.
3536 If this number is positive, it specifies the column. If it is negative,
3537 it means that the tags should be flushright to that column. For example,
3538 -80 works well for a normal 80 character screen.
3539 When 0, place tags directly after headline text, with only one space in
3540 between."
3541 :group 'org-tags
3542 :type 'integer)
3544 (defcustom org-auto-align-tags t
3545 "Non-nil keeps tags aligned when modifying headlines.
3546 Some operations (i.e. demoting) change the length of a headline and
3547 therefore shift the tags around. With this option turned on, after
3548 each such operation the tags are again aligned to `org-tags-column'."
3549 :group 'org-tags
3550 :type 'boolean)
3552 (defcustom org-use-tag-inheritance t
3553 "Non-nil means tags in levels apply also for sublevels.
3554 When nil, only the tags directly given in a specific line apply there.
3555 This may also be a list of tags that should be inherited, or a regexp that
3556 matches tags that should be inherited. Additional control is possible
3557 with the variable `org-tags-exclude-from-inheritance' which gives an
3558 explicit list of tags to be excluded from inheritance, even if the value of
3559 `org-use-tag-inheritance' would select it for inheritance.
3561 If this option is t, a match early-on in a tree can lead to a large
3562 number of matches in the subtree when constructing the agenda or creating
3563 a sparse tree. If you only want to see the first match in a tree during
3564 a search, check out the variable `org-tags-match-list-sublevels'."
3565 :group 'org-tags
3566 :type '(choice
3567 (const :tag "Not" nil)
3568 (const :tag "Always" t)
3569 (repeat :tag "Specific tags" (string :tag "Tag"))
3570 (regexp :tag "Tags matched by regexp")))
3572 (defcustom org-tags-exclude-from-inheritance nil
3573 "List of tags that should never be inherited.
3574 This is a way to exclude a few tags from inheritance. For way to do
3575 the opposite, to actively allow inheritance for selected tags,
3576 see the variable `org-use-tag-inheritance'."
3577 :group 'org-tags
3578 :type '(repeat (string :tag "Tag")))
3580 (defun org-tag-inherit-p (tag)
3581 "Check if TAG is one that should be inherited."
3582 (cond
3583 ((member tag org-tags-exclude-from-inheritance) nil)
3584 ((eq org-use-tag-inheritance t) t)
3585 ((not org-use-tag-inheritance) nil)
3586 ((stringp org-use-tag-inheritance)
3587 (string-match org-use-tag-inheritance tag))
3588 ((listp org-use-tag-inheritance)
3589 (member tag org-use-tag-inheritance))
3590 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3592 (defcustom org-tags-match-list-sublevels t
3593 "Non-nil means list also sublevels of headlines matching a search.
3594 This variable applies to tags/property searches, and also to stuck
3595 projects because this search is based on a tags match as well.
3597 When set to the symbol `indented', sublevels are indented with
3598 leading dots.
3600 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3601 the sublevels of a headline matching a tag search often also match
3602 the same search. Listing all of them can create very long lists.
3603 Setting this variable to nil causes subtrees of a match to be skipped.
3605 This variable is semi-obsolete and probably should always be true. It
3606 is better to limit inheritance to certain tags using the variables
3607 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3608 :group 'org-tags
3609 :type '(choice
3610 (const :tag "No, don't list them" nil)
3611 (const :tag "Yes, do list them" t)
3612 (const :tag "List them, indented with leading dots" indented)))
3614 (defcustom org-tags-sort-function nil
3615 "When set, tags are sorted using this function as a comparator."
3616 :group 'org-tags
3617 :type '(choice
3618 (const :tag "No sorting" nil)
3619 (const :tag "Alphabetical" org-string-collate-lessp)
3620 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3621 (function :tag "Custom function" nil)))
3623 (defvar org-tags-history nil
3624 "History of minibuffer reads for tags.")
3625 (defvar org-last-tags-completion-table nil
3626 "The last used completion table for tags.")
3627 (defvar org-after-tags-change-hook nil
3628 "Hook that is run after the tags in a line have changed.")
3630 (defgroup org-properties nil
3631 "Options concerning properties in Org mode."
3632 :tag "Org Properties"
3633 :group 'org)
3635 (defcustom org-property-format "%-10s %s"
3636 "How property key/value pairs should be formatted by `indent-line'.
3637 When `indent-line' hits a property definition, it will format the line
3638 according to this format, mainly to make sure that the values are
3639 lined-up with respect to each other."
3640 :group 'org-properties
3641 :type 'string)
3643 (defcustom org-properties-postprocess-alist nil
3644 "Alist of properties and functions to adjust inserted values.
3645 Elements of this alist must be of the form
3647 ([string] [function])
3649 where [string] must be a property name and [function] must be a
3650 lambda expression: this lambda expression must take one argument,
3651 the value to adjust, and return the new value as a string.
3653 For example, this element will allow the property \"Remaining\"
3654 to be updated wrt the relation between the \"Effort\" property
3655 and the clock summary:
3657 ((\"Remaining\" (lambda(value)
3658 (let ((clocksum (org-clock-sum-current-item))
3659 (effort (org-duration-to-minutes
3660 (org-entry-get (point) \"Effort\"))))
3661 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3662 :group 'org-properties
3663 :version "24.1"
3664 :type '(alist :key-type (string :tag "Property")
3665 :value-type (function :tag "Function")))
3667 (defcustom org-use-property-inheritance nil
3668 "Non-nil means properties apply also for sublevels.
3670 This setting is chiefly used during property searches. Turning it on can
3671 cause significant overhead when doing a search, which is why it is not
3672 on by default.
3674 When nil, only the properties directly given in the current entry count.
3675 When t, every property is inherited. The value may also be a list of
3676 properties that should have inheritance, or a regular expression matching
3677 properties that should be inherited.
3679 However, note that some special properties use inheritance under special
3680 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3681 and the properties ending in \"_ALL\" when they are used as descriptor
3682 for valid values of a property.
3684 Note for programmers:
3685 When querying an entry with `org-entry-get', you can control if inheritance
3686 should be used. By default, `org-entry-get' looks only at the local
3687 properties. You can request inheritance by setting the inherit argument
3688 to t (to force inheritance) or to `selective' (to respect the setting
3689 in this variable)."
3690 :group 'org-properties
3691 :type '(choice
3692 (const :tag "Not" nil)
3693 (const :tag "Always" t)
3694 (repeat :tag "Specific properties" (string :tag "Property"))
3695 (regexp :tag "Properties matched by regexp")))
3697 (defun org-property-inherit-p (property)
3698 "Return a non-nil value if PROPERTY should be inherited."
3699 (cond
3700 ((eq org-use-property-inheritance t) t)
3701 ((not org-use-property-inheritance) nil)
3702 ((stringp org-use-property-inheritance)
3703 (string-match org-use-property-inheritance property))
3704 ((listp org-use-property-inheritance)
3705 (member-ignore-case property org-use-property-inheritance))
3706 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3708 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3709 "The default column format, if no other format has been defined.
3710 This variable can be set on the per-file basis by inserting a line
3712 #+COLUMNS: %25ITEM ....."
3713 :group 'org-properties
3714 :type 'string)
3716 (defcustom org-columns-ellipses ".."
3717 "The ellipses to be used when a field in column view is truncated.
3718 When this is the empty string, as many characters as possible are shown,
3719 but then there will be no visual indication that the field has been truncated.
3720 When this is a string of length N, the last N characters of a truncated
3721 field are replaced by this string. If the column is narrower than the
3722 ellipses string, only part of the ellipses string will be shown."
3723 :group 'org-properties
3724 :type 'string)
3726 (defconst org-global-properties-fixed
3727 '(("VISIBILITY_ALL" . "folded children content all")
3728 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3729 "List of property/value pairs that can be inherited by any entry.
3731 These are fixed values, for the preset properties. The user variable
3732 that can be used to add to this list is `org-global-properties'.
3734 The entries in this list are cons cells where the car is a property
3735 name and cdr is a string with the value. If the value represents
3736 multiple items like an \"_ALL\" property, separate the items by
3737 spaces.")
3739 (defcustom org-global-properties nil
3740 "List of property/value pairs that can be inherited by any entry.
3742 This list will be combined with the constant `org-global-properties-fixed'.
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.
3747 You can set buffer-local values for the same purpose in the variable
3748 `org-file-properties' this by adding lines like
3750 #+PROPERTY: NAME VALUE"
3751 :group 'org-properties
3752 :type '(repeat
3753 (cons (string :tag "Property")
3754 (string :tag "Value"))))
3756 (defvar-local org-file-properties nil
3757 "List of property/value pairs that can be inherited by any entry.
3758 Valid for the current buffer.
3759 This variable is populated from #+PROPERTY lines.")
3761 (defgroup org-agenda nil
3762 "Options concerning agenda views in Org mode."
3763 :tag "Org Agenda"
3764 :group 'org)
3766 (defvar-local org-category nil
3767 "Variable used by Org files to set a category for agenda display.
3768 Such files should use a file variable to set it, for example
3770 # -*- mode: org; org-category: \"ELisp\"
3772 or contain a special line
3774 #+CATEGORY: ELisp
3776 If the file does not specify a category, then file's base name
3777 is used instead.")
3778 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3780 (defcustom org-agenda-files nil
3781 "The files to be used for agenda display.
3783 If an entry is a directory, all files in that directory that are matched
3784 by `org-agenda-file-regexp' will be part of the file list.
3786 If the value of the variable is not a list but a single file name, then
3787 the list of agenda files is actually stored and maintained in that file,
3788 one agenda file per line. In this file paths can be given relative to
3789 `org-directory'. Tilde expansion and environment variable substitution
3790 are also made.
3792 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3793 and removed with `\\[org-remove-file]'."
3794 :group 'org-agenda
3795 :type '(choice
3796 (repeat :tag "List of files and directories" file)
3797 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3799 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3800 "Regular expression to match files for `org-agenda-files'.
3801 If any element in the list in that variable contains a directory instead
3802 of a normal file, all files in that directory that are matched by this
3803 regular expression will be included."
3804 :group 'org-agenda
3805 :type 'regexp)
3807 (defcustom org-agenda-text-search-extra-files nil
3808 "List of extra files to be searched by text search commands.
3809 These files will be searched in addition to the agenda files by the
3810 commands `org-search-view' (`\\[org-agenda] s') \
3811 and `org-occur-in-agenda-files'.
3812 Note that these files will only be searched for text search commands,
3813 not for the other agenda views like todo lists, tag searches or the weekly
3814 agenda. This variable is intended to list notes and possibly archive files
3815 that should also be searched by these two commands.
3816 In fact, if the first element in the list is the symbol `agenda-archives',
3817 then all archive files of all agenda files will be added to the search
3818 scope."
3819 :group 'org-agenda
3820 :type '(set :greedy t
3821 (const :tag "Agenda Archives" agenda-archives)
3822 (repeat :inline t (file))))
3824 (defvaralias 'org-agenda-multi-occur-extra-files
3825 'org-agenda-text-search-extra-files)
3827 (defcustom org-agenda-skip-unavailable-files nil
3828 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3829 A nil value means to remove them, after a query, from the list."
3830 :group 'org-agenda
3831 :type 'boolean)
3833 (defcustom org-agenda-diary-file 'diary-file
3834 "File to which to add new entries with the `i' key in agenda and calendar.
3835 When this is the symbol `diary-file', the functionality in the Emacs
3836 calendar will be used to add entries to the `diary-file'. But when this
3837 points to a file, `org-agenda-diary-entry' will be used instead."
3838 :group 'org-agenda
3839 :type '(choice
3840 (const :tag "The standard Emacs diary file" diary-file)
3841 (file :tag "Special Org file diary entries")))
3843 (defgroup org-latex nil
3844 "Options for embedding LaTeX code into Org mode."
3845 :tag "Org LaTeX"
3846 :group 'org)
3848 (defcustom org-format-latex-options
3849 '(:foreground default :background default :scale 1.0
3850 :html-foreground "Black" :html-background "Transparent"
3851 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3852 "Options for creating images from LaTeX fragments.
3853 This is a property list with the following properties:
3854 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3855 `default' means use the foreground of the default face.
3856 `auto' means use the foreground from the text face.
3857 :background the background color, or \"Transparent\".
3858 `default' means use the background of the default face.
3859 `auto' means use the background from the text face.
3860 :scale a scaling factor for the size of the images, to get more pixels
3861 :html-foreground, :html-background, :html-scale
3862 the same numbers for HTML export.
3863 :matchers a list indicating which matchers should be used to
3864 find LaTeX fragments. Valid members of this list are:
3865 \"begin\" find environments
3866 \"$1\" find single characters surrounded by $.$
3867 \"$\" find math expressions surrounded by $...$
3868 \"$$\" find math expressions surrounded by $$....$$
3869 \"\\(\" find math expressions surrounded by \\(...\\)
3870 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3871 :group 'org-latex
3872 :type 'plist)
3874 (defcustom org-format-latex-signal-error t
3875 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3876 When nil, just push out a message."
3877 :group 'org-latex
3878 :version "24.1"
3879 :type 'boolean)
3881 (defcustom org-latex-to-mathml-jar-file nil
3882 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3883 Use this to specify additional executable file say a jar file.
3885 When using MathToWeb as the converter, specify the full-path to
3886 your mathtoweb.jar file."
3887 :group 'org-latex
3888 :version "24.1"
3889 :type '(choice
3890 (const :tag "None" nil)
3891 (file :tag "JAR file" :must-match t)))
3893 (defcustom org-latex-to-mathml-convert-command nil
3894 "Command to convert LaTeX fragments to MathML.
3895 Replace format-specifiers in the command as noted below and use
3896 `shell-command' to convert LaTeX to MathML.
3897 %j: Executable file in fully expanded form as specified by
3898 `org-latex-to-mathml-jar-file'.
3899 %I: Input LaTeX file in fully expanded form.
3900 %i: The latex fragment to be converted.
3901 %o: Output MathML file.
3903 This command is used by `org-create-math-formula'.
3905 When using MathToWeb as the converter, set this option to
3906 \"java -jar %j -unicode -force -df %o %I\".
3908 When using LaTeXML set this option to
3909 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3910 :group 'org-latex
3911 :version "24.1"
3912 :type '(choice
3913 (const :tag "None" nil)
3914 (string :tag "\nShell command")))
3916 (defcustom org-preview-latex-default-process 'dvipng
3917 "The default process to convert LaTeX fragments to image files.
3918 All available processes and theirs documents can be found in
3919 `org-preview-latex-process-alist', which see."
3920 :group 'org-latex
3921 :version "26.1"
3922 :package-version '(Org . "9.0")
3923 :type 'symbol)
3925 (defcustom org-preview-latex-process-alist
3926 '((dvipng
3927 :programs ("latex" "dvipng")
3928 :description "dvi > png"
3929 :message "you need to install the programs: latex and dvipng."
3930 :image-input-type "dvi"
3931 :image-output-type "png"
3932 :image-size-adjust (1.0 . 1.0)
3933 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3934 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3935 (dvisvgm
3936 :programs ("latex" "dvisvgm")
3937 :description "dvi > svg"
3938 :message "you need to install the programs: latex and dvisvgm."
3939 :use-xcolor t
3940 :image-input-type "dvi"
3941 :image-output-type "svg"
3942 :image-size-adjust (1.7 . 1.5)
3943 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3944 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3945 (imagemagick
3946 :programs ("latex" "convert")
3947 :description "pdf > png"
3948 :message "you need to install the programs: latex and imagemagick."
3949 :use-xcolor t
3950 :image-input-type "pdf"
3951 :image-output-type "png"
3952 :image-size-adjust (1.0 . 1.0)
3953 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3954 :image-converter
3955 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3956 "Definitions of external processes for LaTeX previewing.
3957 Org mode can use some external commands to generate TeX snippet's images for
3958 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3959 `org-create-formula-image' how to call them.
3961 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3962 PROPERTIES accepts the following attributes:
3964 :programs list of strings, required programs.
3965 :description string, describe the process.
3966 :message string, message it when required programs cannot be found.
3967 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3968 :image-output-type string, output file type of image converter (e.g., \"png\").
3969 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3970 deal with background and foreground color of image.
3971 Otherwise, dvipng style background and foreground color
3972 format are generated. You may then refer to them in
3973 command options with \"%F\" and \"%B\".
3974 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3975 image size showed in buffer and the cdr element is for
3976 HTML file. This option is only useful for process
3977 developers, users should use variable
3978 `org-format-latex-options' instead.
3979 :post-clean list of strings, files matched are to be cleaned up once
3980 the image is generated. When nil, the files with \".dvi\",
3981 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3982 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3983 be cleaned up.
3984 :latex-header list of strings, the LaTeX header of the snippet file.
3985 When nil, the fallback value is used instead, which is
3986 controlled by `org-format-latex-header',
3987 `org-latex-default-packages-alist' and
3988 `org-latex-packages-alist', which see.
3989 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3990 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
3991 replaced with values defined below.
3992 :image-converter list of image converter commands strings. Each of them is
3993 given to the shell and supports any of the following
3994 place-holders defined below.
3996 Place-holders used by `:image-converter' and `:latex-compiler':
3998 %f input file name
3999 %b base name of input file
4000 %o base directory of input file
4001 %O absolute output file name
4003 Place-holders only used by `:image-converter':
4005 %F foreground of image
4006 %B background of image
4007 %D dpi, which is used to adjust image size by some processing commands.
4008 %S the image size scale ratio, which is used to adjust image size by some
4009 processing commands."
4010 :group 'org-latex
4011 :version "26.1"
4012 :package-version '(Org . "9.0")
4013 :type '(alist :tag "LaTeX to image backends"
4014 :value-type (plist)))
4016 (defcustom org-preview-latex-image-directory "ltximg/"
4017 "Path to store latex preview images.
4018 A relative path here creates many directories relative to the
4019 processed Org files paths. An absolute path puts all preview
4020 images at the same place."
4021 :group 'org-latex
4022 :version "26.1"
4023 :package-version '(Org . "9.0")
4024 :type 'string)
4026 (defun org-format-latex-mathml-available-p ()
4027 "Return t if `org-latex-to-mathml-convert-command' is usable."
4028 (save-match-data
4029 (when (and (boundp 'org-latex-to-mathml-convert-command)
4030 org-latex-to-mathml-convert-command)
4031 (let ((executable (car (split-string
4032 org-latex-to-mathml-convert-command))))
4033 (when (executable-find executable)
4034 (if (string-match
4035 "%j" org-latex-to-mathml-convert-command)
4036 (file-readable-p org-latex-to-mathml-jar-file)
4037 t))))))
4039 (defcustom org-format-latex-header "\\documentclass{article}
4040 \\usepackage[usenames]{color}
4041 \[PACKAGES]
4042 \[DEFAULT-PACKAGES]
4043 \\pagestyle{empty} % do not remove
4044 % The settings below are copied from fullpage.sty
4045 \\setlength{\\textwidth}{\\paperwidth}
4046 \\addtolength{\\textwidth}{-3cm}
4047 \\setlength{\\oddsidemargin}{1.5cm}
4048 \\addtolength{\\oddsidemargin}{-2.54cm}
4049 \\setlength{\\evensidemargin}{\\oddsidemargin}
4050 \\setlength{\\textheight}{\\paperheight}
4051 \\addtolength{\\textheight}{-\\headheight}
4052 \\addtolength{\\textheight}{-\\headsep}
4053 \\addtolength{\\textheight}{-\\footskip}
4054 \\addtolength{\\textheight}{-3cm}
4055 \\setlength{\\topmargin}{1.5cm}
4056 \\addtolength{\\topmargin}{-2.54cm}"
4057 "The document header used for processing LaTeX fragments.
4058 It is imperative that this header make sure that no page number
4059 appears on the page. The package defined in the variables
4060 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4061 will either replace the placeholder \"[PACKAGES]\" in this
4062 header, or they will be appended."
4063 :group 'org-latex
4064 :type 'string)
4066 (defun org-set-packages-alist (var val)
4067 "Set the packages alist and make sure it has 3 elements per entry."
4068 (set var (mapcar (lambda (x)
4069 (if (and (consp x) (= (length x) 2))
4070 (list (car x) (nth 1 x) t)
4072 val)))
4074 (defun org-get-packages-alist (var)
4075 "Get the packages alist and make sure it has 3 elements per entry."
4076 (mapcar (lambda (x)
4077 (if (and (consp x) (= (length x) 2))
4078 (list (car x) (nth 1 x) t)
4080 (default-value var)))
4082 (defcustom org-latex-default-packages-alist
4083 '(("AUTO" "inputenc" t ("pdflatex"))
4084 ("T1" "fontenc" t ("pdflatex"))
4085 ("" "graphicx" t)
4086 ("" "grffile" t)
4087 ("" "longtable" nil)
4088 ("" "wrapfig" nil)
4089 ("" "rotating" nil)
4090 ("normalem" "ulem" t)
4091 ("" "amsmath" t)
4092 ("" "textcomp" t)
4093 ("" "amssymb" t)
4094 ("" "capt-of" nil)
4095 ("" "hyperref" nil))
4096 "Alist of default packages to be inserted in the header.
4098 Change this only if one of the packages here causes an
4099 incompatibility with another package you are using.
4101 The packages in this list are needed by one part or another of
4102 Org mode to function properly:
4104 - inputenc, fontenc: for basic font and character selection
4105 - graphicx: for including images
4106 - grffile: allow periods and spaces in graphics file names
4107 - longtable: For multipage tables
4108 - wrapfig: for figure placement
4109 - rotating: for sideways figures and tables
4110 - ulem: for underline and strike-through
4111 - amsmath: for subscript and superscript and math environments
4112 - textcomp, amssymb: for various symbols used
4113 for interpreting the entities in `org-entities'. You can skip
4114 some of these packages if you don't use any of their symbols.
4115 - capt-of: for captions outside of floats
4116 - hyperref: for cross references
4118 Therefore you should not modify this variable unless you know
4119 what you are doing. The one reason to change it anyway is that
4120 you might be loading some other package that conflicts with one
4121 of the default packages. Each element is either a cell or
4122 a string.
4124 A cell is of the format
4126 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4128 If SNIPPET-FLAG is non-nil, the package also needs to be included
4129 when compiling LaTeX snippets into images for inclusion into
4130 non-LaTeX output. COMPILERS is a list of compilers that should
4131 include the package, see `org-latex-compiler'. If the document
4132 compiler is not in the list, and the list is non-nil, the package
4133 will not be inserted in the final document.
4135 A string will be inserted as-is in the header of the document."
4136 :group 'org-latex
4137 :group 'org-export-latex
4138 :set 'org-set-packages-alist
4139 :get 'org-get-packages-alist
4140 :version "26.1"
4141 :package-version '(Org . "8.3")
4142 :type '(repeat
4143 (choice
4144 (list :tag "options/package pair"
4145 (string :tag "options")
4146 (string :tag "package")
4147 (boolean :tag "Snippet")
4148 (choice
4149 (const :tag "For all compilers" nil)
4150 (repeat :tag "Allowed compiler" string)))
4151 (string :tag "A line of LaTeX"))))
4153 (defcustom org-latex-packages-alist nil
4154 "Alist of packages to be inserted in every LaTeX header.
4156 These will be inserted after `org-latex-default-packages-alist'.
4157 Each element is either a cell or a string.
4159 A cell is of the format:
4161 (\"options\" \"package\" SNIPPET-FLAG)
4163 SNIPPET-FLAG, when non-nil, indicates that this package is also
4164 needed when turning LaTeX snippets into images for inclusion into
4165 non-LaTeX output.
4167 A string will be inserted as-is in the header of the document.
4169 Make sure that you only list packages here which:
4171 - you want in every file;
4172 - do not conflict with the setup in `org-format-latex-header';
4173 - do not conflict with the default packages in
4174 `org-latex-default-packages-alist'."
4175 :group 'org-latex
4176 :group 'org-export-latex
4177 :set 'org-set-packages-alist
4178 :get 'org-get-packages-alist
4179 :type '(repeat
4180 (choice
4181 (list :tag "options/package pair"
4182 (string :tag "options")
4183 (string :tag "package")
4184 (boolean :tag "Snippet"))
4185 (string :tag "A line of LaTeX"))))
4187 (defgroup org-appearance nil
4188 "Settings for Org mode appearance."
4189 :tag "Org Appearance"
4190 :group 'org)
4192 (defcustom org-level-color-stars-only nil
4193 "Non-nil means fontify only the stars in each headline.
4194 When nil, the entire headline is fontified.
4195 Changing it requires restart of `font-lock-mode' to become effective
4196 also in regions already fontified."
4197 :group 'org-appearance
4198 :type 'boolean)
4200 (defcustom org-hide-leading-stars nil
4201 "Non-nil means hide the first N-1 stars in a headline.
4202 This works by using the face `org-hide' for these stars. This
4203 face is white for a light background, and black for a dark
4204 background. You may have to customize the face `org-hide' to
4205 make this work.
4206 Changing it requires restart of `font-lock-mode' to become effective
4207 also in regions already fontified.
4208 You may also set this on a per-file basis by adding one of the following
4209 lines to the buffer:
4211 #+STARTUP: hidestars
4212 #+STARTUP: showstars"
4213 :group 'org-appearance
4214 :type 'boolean)
4216 (defcustom org-hidden-keywords nil
4217 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4218 For example, a value \\='(title) for this list makes the document's title
4219 appear in the buffer without the initial \"#+TITLE:\" part."
4220 :group 'org-appearance
4221 :version "24.1"
4222 :type '(set (const :tag "#+AUTHOR" author)
4223 (const :tag "#+DATE" date)
4224 (const :tag "#+EMAIL" email)
4225 (const :tag "#+TITLE" title)))
4227 (defcustom org-custom-properties nil
4228 "List of properties (as strings) with a special meaning.
4229 The default use of these custom properties is to let the user
4230 hide them with `org-toggle-custom-properties-visibility'."
4231 :group 'org-properties
4232 :group 'org-appearance
4233 :version "24.3"
4234 :type '(repeat (string :tag "Property Name")))
4236 (defcustom org-fontify-done-headline nil
4237 "Non-nil means change the face of a headline if it is marked DONE.
4238 Normally, only the TODO/DONE keyword indicates the state of a headline.
4239 When this is non-nil, the headline after the keyword is set to the
4240 `org-headline-done' as an additional indication."
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-fontify-emphasized-text t
4245 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4246 Changing this variable requires a restart of Emacs to take effect."
4247 :group 'org-appearance
4248 :type 'boolean)
4250 (defcustom org-fontify-whole-heading-line nil
4251 "Non-nil means fontify the whole line for headings.
4252 This is useful when setting a background color for the
4253 org-level-* faces."
4254 :group 'org-appearance
4255 :type 'boolean)
4257 (defcustom org-highlight-latex-and-related nil
4258 "Non-nil means highlight LaTeX related syntax in the buffer.
4259 When non nil, the value should be a list containing any of the
4260 following symbols:
4261 `latex' Highlight LaTeX snippets and environments.
4262 `script' Highlight subscript and superscript.
4263 `entities' Highlight entities."
4264 :group 'org-appearance
4265 :version "24.4"
4266 :package-version '(Org . "8.0")
4267 :type '(choice
4268 (const :tag "No highlighting" nil)
4269 (set :greedy t :tag "Highlight"
4270 (const :tag "LaTeX snippets and environments" latex)
4271 (const :tag "Subscript and superscript" script)
4272 (const :tag "Entities" entities))))
4274 (defcustom org-hide-emphasis-markers nil
4275 "Non-nil mean font-lock should hide the emphasis marker characters."
4276 :group 'org-appearance
4277 :type 'boolean
4278 :safe #'booleanp)
4280 (defcustom org-hide-macro-markers nil
4281 "Non-nil mean font-lock should hide the brackets marking macro calls."
4282 :group 'org-appearance
4283 :type 'boolean)
4285 (defcustom org-pretty-entities nil
4286 "Non-nil means show entities as UTF8 characters.
4287 When nil, the \\name form remains in the buffer."
4288 :group 'org-appearance
4289 :version "24.1"
4290 :type 'boolean)
4292 (defcustom org-pretty-entities-include-sub-superscripts t
4293 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4294 :group 'org-appearance
4295 :version "24.1"
4296 :type 'boolean)
4298 (defvar org-emph-re nil
4299 "Regular expression for matching emphasis.
4300 After a match, the match groups contain these elements:
4301 0 The match of the full regular expression, including the characters
4302 before and after the proper match
4303 1 The character before the proper match, or empty at beginning of line
4304 2 The proper match, including the leading and trailing markers
4305 3 The leading marker like * or /, indicating the type of highlighting
4306 4 The text between the emphasis markers, not including the markers
4307 5 The character after the match, empty at the end of a line")
4309 (defvar org-verbatim-re nil
4310 "Regular expression for matching verbatim text.")
4312 (defvar org-emphasis-regexp-components) ; defined just below
4313 (defvar org-emphasis-alist) ; defined just below
4314 (defun org-set-emph-re (var val)
4315 "Set variable and compute the emphasis regular expression."
4316 (set var val)
4317 (when (and (boundp 'org-emphasis-alist)
4318 (boundp 'org-emphasis-regexp-components)
4319 org-emphasis-alist org-emphasis-regexp-components)
4320 (pcase-let*
4321 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4322 (body (if (<= nl 0) body
4323 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4324 (template
4325 (format (concat "\\([%s]\\|^\\)" ;before markers
4326 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4327 "\\([%s]\\|$\\)") ;after markers
4328 pre border border body border post)))
4329 (setq org-emph-re (format template "*/_+"))
4330 (setq org-verbatim-re (format template "=~")))))
4332 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4333 ;; set this option proved cumbersome. See this message/thread:
4334 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4335 (defvar org-emphasis-regexp-components
4336 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4337 "Components used to build the regular expression for emphasis.
4338 This is a list with five entries. Terminology: In an emphasis string
4339 like \" *strong word* \", we call the initial space PREMATCH, the final
4340 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4341 and \"trong wor\" is the body. The different components in this variable
4342 specify what is allowed/forbidden in each part:
4344 pre Chars allowed as prematch. Beginning of line will be allowed too.
4345 post Chars allowed as postmatch. End of line will be allowed too.
4346 border The chars *forbidden* as border characters.
4347 body-regexp A regexp like \".\" to match a body character. Don't use
4348 non-shy groups here, and don't allow newline here.
4349 newline The maximum number of newlines allowed in an emphasis exp.
4351 You need to reload Org or to restart Emacs after setting this.")
4353 (defcustom org-emphasis-alist
4354 '(("*" bold)
4355 ("/" italic)
4356 ("_" underline)
4357 ("=" org-verbatim verbatim)
4358 ("~" org-code verbatim)
4359 ("+" (:strike-through t)))
4360 "Alist of characters and faces to emphasize text.
4361 Text starting and ending with a special character will be emphasized,
4362 for example *bold*, _underlined_ and /italic/. This variable sets the
4363 marker characters and the face to be used by font-lock for highlighting
4364 in Org buffers.
4366 You need to reload Org or to restart Emacs after customizing this."
4367 :group 'org-appearance
4368 :set 'org-set-emph-re
4369 :version "24.4"
4370 :package-version '(Org . "8.0")
4371 :type '(repeat
4372 (list
4373 (string :tag "Marker character")
4374 (choice
4375 (face :tag "Font-lock-face")
4376 (plist :tag "Face property list"))
4377 (option (const verbatim)))))
4379 (defvar org-protecting-blocks '("src" "example" "export")
4380 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4381 This is needed for font-lock setup.")
4383 ;;; Functions and variables from their packages
4384 ;; Declared here to avoid compiler warnings
4385 (defvar mark-active)
4387 ;; Various packages
4388 (declare-function calc-eval "calc" (str &optional separator &rest args))
4389 (declare-function calendar-forward-day "cal-move" (arg))
4390 (declare-function calendar-goto-date "cal-move" (date))
4391 (declare-function calendar-goto-today "cal-move" ())
4392 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4393 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4394 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4395 (declare-function cdlatex-tab "ext:cdlatex" ())
4396 (declare-function dired-get-filename
4397 "dired"
4398 (&optional localp no-error-if-not-filep))
4399 (declare-function iswitchb-read-buffer
4400 "iswitchb"
4401 (prompt &optional
4402 default require-match _predicate start matches-set))
4403 (declare-function org-agenda-change-all-lines
4404 "org-agenda"
4405 (newhead hdmarker &optional fixface just-this))
4406 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4407 "org-agenda"
4408 (&optional end))
4409 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4410 (declare-function org-agenda-format-item
4411 "org-agenda"
4412 (extra txt &optional level category tags dotime
4413 remove-re habitp))
4414 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4415 (declare-function org-agenda-save-markers-for-cut-and-paste
4416 "org-agenda"
4417 (beg end))
4418 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4419 (declare-function org-agenda-skip "org-agenda" ())
4420 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4421 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4422 (declare-function org-indent-mode "org-indent" (&optional arg))
4423 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4424 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4425 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4426 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4427 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4428 (declare-function parse-time-string "parse-time" (string))
4430 (defvar align-mode-rules-list)
4431 (defvar calc-embedded-close-formula)
4432 (defvar calc-embedded-open-formula)
4433 (defvar calc-embedded-open-mode)
4434 (defvar font-lock-unfontify-region-function)
4435 (defvar iswitchb-temp-buflist)
4436 (defvar org-agenda-tags-todo-honor-ignore-options)
4437 (defvar remember-data-file)
4438 (defvar texmathp-why)
4440 ;;;###autoload
4441 (defun turn-on-orgtbl ()
4442 "Unconditionally turn on `orgtbl-mode'."
4443 (require 'org-table)
4444 (orgtbl-mode 1))
4446 (defun org-at-table-p (&optional table-type)
4447 "Non-nil if the cursor is inside an Org table.
4448 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4449 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4450 (or (not (derived-mode-p 'org-mode))
4451 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4452 (and e (or table-type
4453 (eq 'org (org-element-property :type e))))))))
4455 (defun org-at-table.el-p ()
4456 "Non-nil when point is at a table.el table."
4457 (and (org-match-line "[ \t]*[|+]")
4458 (let ((element (org-element-at-point)))
4459 (and (eq (org-element-type element) 'table)
4460 (eq (org-element-property :type element) 'table.el)))))
4462 (defun org-at-table-hline-p ()
4463 "Non-nil when point is inside a hline in a table.
4464 Assume point is already in a table."
4465 (org-match-line org-table-hline-regexp))
4467 (defun org-table-map-tables (function &optional quietly)
4468 "Apply FUNCTION to the start of all tables in the buffer."
4469 (org-with-wide-buffer
4470 (goto-char (point-min))
4471 (while (re-search-forward org-table-any-line-regexp nil t)
4472 (unless quietly
4473 (message "Mapping tables: %d%%"
4474 (floor (* 100.0 (point)) (buffer-size))))
4475 (beginning-of-line 1)
4476 (when (and (looking-at org-table-line-regexp)
4477 ;; Exclude tables in src/example/verbatim/clocktable blocks
4478 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4479 (save-excursion (funcall function))
4480 (or (looking-at org-table-line-regexp)
4481 (forward-char 1)))
4482 (re-search-forward org-table-any-border-regexp nil 1)))
4483 (unless quietly (message "Mapping tables: done")))
4485 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4486 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
4487 (declare-function org-resolve-clocks "org-clock"
4488 (&optional also-non-dangling-p prompt last-valid))
4490 (defun org-at-TBLFM-p (&optional pos)
4491 "Non-nil when point (or POS) is in #+TBLFM line."
4492 (save-excursion
4493 (goto-char (or pos (point)))
4494 (beginning-of-line)
4495 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4496 (eq (org-element-type (org-element-at-point)) 'table))))
4498 (defvar org-clock-start-time)
4499 (defvar org-clock-marker (make-marker)
4500 "Marker recording the last clock-in.")
4501 (defvar org-clock-hd-marker (make-marker)
4502 "Marker recording the last clock-in, but the headline position.")
4503 (defvar org-clock-heading ""
4504 "The heading of the current clock entry.")
4505 (defun org-clock-is-active ()
4506 "Return the buffer where the clock is currently running.
4507 Return nil if no clock is running."
4508 (marker-buffer org-clock-marker))
4510 (defun org-check-running-clock ()
4511 "Check if the current buffer contains the running clock.
4512 If yes, offer to stop it and to save the buffer with the changes."
4513 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4514 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4515 (buffer-name))))
4516 (org-clock-out)
4517 (when (y-or-n-p "Save changed buffer?")
4518 (save-buffer))))
4520 (defun org-clocktable-try-shift (dir n)
4521 "Check if this line starts a clock table, if yes, shift the time block."
4522 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4523 (org-clocktable-shift dir n)))
4525 ;;;###autoload
4526 (defun org-clock-persistence-insinuate ()
4527 "Set up hooks for clock persistence."
4528 (require 'org-clock)
4529 (add-hook 'org-mode-hook 'org-clock-load)
4530 (add-hook 'kill-emacs-hook 'org-clock-save))
4532 (defgroup org-archive nil
4533 "Options concerning archiving in Org mode."
4534 :tag "Org Archive"
4535 :group 'org-structure)
4537 (defcustom org-archive-location "%s_archive::"
4538 "The location where subtrees should be archived.
4540 The value of this variable is a string, consisting of two parts,
4541 separated by a double-colon. The first part is a filename and
4542 the second part is a headline.
4544 When the filename is omitted, archiving happens in the same file.
4545 %s in the filename will be replaced by the current file
4546 name (without the directory part). Archiving to a different file
4547 is useful to keep archived entries from contributing to the
4548 Org Agenda.
4550 The archived entries will be filed as subtrees of the specified
4551 headline. When the headline is omitted, the subtrees are simply
4552 filed away at the end of the file, as top-level entries. Also in
4553 the heading you can use %s to represent the file name, this can be
4554 useful when using the same archive for a number of different files.
4556 Here are a few examples:
4557 \"%s_archive::\"
4558 If the current file is Projects.org, archive in file
4559 Projects.org_archive, as top-level trees. This is the default.
4561 \"::* Archived Tasks\"
4562 Archive in the current file, under the top-level headline
4563 \"* Archived Tasks\".
4565 \"~/org/archive.org::\"
4566 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4568 \"~/org/archive.org::* From %s\"
4569 Archive in file ~/org/archive.org (absolute path), under headlines
4570 \"From FILENAME\" where file name is the current file name.
4572 \"~/org/datetree.org::datetree/* Finished Tasks\"
4573 The \"datetree/\" string is special, signifying to archive
4574 items to the datetree. Items are placed in either the CLOSED
4575 date of the item, or the current date if there is no CLOSED date.
4576 The heading will be a subentry to the current date. There doesn't
4577 need to be a heading, but there always needs to be a slash after
4578 datetree. For example, to store archived items directly in the
4579 datetree, use \"~/org/datetree.org::datetree/\".
4581 \"basement::** Finished Tasks\"
4582 Archive in file ./basement (relative path), as level 3 trees
4583 below the level 2 heading \"** Finished Tasks\".
4585 You may set this option on a per-file basis by adding to the buffer a
4586 line like
4588 #+ARCHIVE: basement::** Finished Tasks
4590 You may also define it locally for a subtree by setting an ARCHIVE property
4591 in the entry. If such a property is found in an entry, or anywhere up
4592 the hierarchy, it will be used."
4593 :group 'org-archive
4594 :type 'string)
4596 (defcustom org-agenda-skip-archived-trees t
4597 "Non-nil means the agenda will skip any items located in archived trees.
4598 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4599 variable is no longer recommended, you should leave it at the value t.
4600 Instead, use the key `v' to cycle the archives-mode in the agenda."
4601 :group 'org-archive
4602 :group 'org-agenda-skip
4603 :type 'boolean)
4605 (defcustom org-columns-skip-archived-trees t
4606 "Non-nil means ignore archived trees when creating column view."
4607 :group 'org-archive
4608 :group 'org-properties
4609 :type 'boolean)
4611 (defcustom org-cycle-open-archived-trees nil
4612 "Non-nil means `org-cycle' will open archived trees.
4613 An archived tree is a tree marked with the tag ARCHIVE.
4614 When nil, archived trees will stay folded. You can still open them with
4615 normal outline commands like `show-all', but not with the cycling commands."
4616 :group 'org-archive
4617 :group 'org-cycle
4618 :type 'boolean)
4620 (defcustom org-sparse-tree-open-archived-trees nil
4621 "Non-nil means sparse tree construction shows matches in archived trees.
4622 When nil, matches in these trees are highlighted, but the trees are kept in
4623 collapsed state."
4624 :group 'org-archive
4625 :group 'org-sparse-trees
4626 :type 'boolean)
4628 (defcustom org-sparse-tree-default-date-type nil
4629 "The default date type when building a sparse tree.
4630 When this is nil, a date is a scheduled or a deadline timestamp.
4631 Otherwise, these types are allowed:
4633 all: all timestamps
4634 active: only active timestamps (<...>)
4635 inactive: only inactive timestamps ([...])
4636 scheduled: only scheduled timestamps
4637 deadline: only deadline timestamps"
4638 :type '(choice (const :tag "Scheduled or deadline" nil)
4639 (const :tag "All timestamps" all)
4640 (const :tag "Only active timestamps" active)
4641 (const :tag "Only inactive timestamps" inactive)
4642 (const :tag "Only scheduled timestamps" scheduled)
4643 (const :tag "Only deadline timestamps" deadline)
4644 (const :tag "Only closed timestamps" closed))
4645 :version "26.1"
4646 :package-version '(Org . "8.3")
4647 :group 'org-sparse-trees)
4649 (defun org-cycle-hide-archived-subtrees (state)
4650 "Re-hide all archived subtrees after a visibility state change.
4651 STATE should be one of the symbols listed in the docstring of
4652 `org-cycle-hook'."
4653 (when (and (not org-cycle-open-archived-trees)
4654 (not (memq state '(overview folded))))
4655 (save-excursion
4656 (let* ((globalp (memq state '(contents all)))
4657 (beg (if globalp (point-min) (point)))
4658 (end (if globalp (point-max) (org-end-of-subtree t))))
4659 (org-hide-archived-subtrees beg end)
4660 (goto-char beg)
4661 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4662 (message "%s" (substitute-command-keys
4663 "Subtree is archived and stays closed. Use \
4664 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4666 (defun org-force-cycle-archived ()
4667 "Cycle subtree even if it is archived."
4668 (interactive)
4669 (setq this-command 'org-cycle)
4670 (let ((org-cycle-open-archived-trees t))
4671 (call-interactively 'org-cycle)))
4673 (defun org-hide-archived-subtrees (beg end)
4674 "Re-hide all archived subtrees after a visibility state change."
4675 (org-with-wide-buffer
4676 (let ((case-fold-search nil)
4677 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4678 (goto-char beg)
4679 ;; Include headline point is currently on.
4680 (beginning-of-line)
4681 (while (and (< (point) end) (re-search-forward re end t))
4682 (when (member org-archive-tag (org-get-tags nil t))
4683 (org-flag-subtree t)
4684 (org-end-of-subtree t))))))
4686 (defun org-flag-subtree (flag)
4687 (save-excursion
4688 (org-back-to-heading t)
4689 (org-flag-region (line-end-position)
4690 (progn (org-end-of-subtree t) (point))
4691 flag
4692 'outline)))
4694 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4696 ;; Declare Column View Code
4698 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4699 (declare-function org-columns-compute "org-colview" (property))
4701 ;; Declare ID code
4703 (declare-function org-id-store-link "org-id")
4704 (declare-function org-id-locations-load "org-id")
4705 (declare-function org-id-locations-save "org-id")
4706 (defvar org-id-track-globally)
4708 ;;; Variables for pre-computed regular expressions, all buffer local
4710 (defvar-local org-todo-regexp nil
4711 "Matches any of the TODO state keywords.
4712 Since TODO keywords are case-sensitive, `case-fold-search' is
4713 expected to be bound to nil when matching against this regexp.")
4715 (defvar-local org-not-done-regexp nil
4716 "Matches any of the TODO state keywords except the last one.
4717 Since TODO keywords are case-sensitive, `case-fold-search' is
4718 expected to be bound to nil when matching against this regexp.")
4720 (defvar-local org-not-done-heading-regexp nil
4721 "Matches a TODO headline that is not done.
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-todo-line-regexp nil
4726 "Matches a headline and puts TODO state into group 2 if present.
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-complex-heading-regexp nil
4731 "Matches a headline and puts everything into groups:
4733 group 1: Stars
4734 group 2: The TODO keyword, maybe
4735 group 3: Priority cookie
4736 group 4: True headline
4737 group 5: Tags
4739 Since TODO keywords are case-sensitive, `case-fold-search' is
4740 expected to be bound to nil when matching against this regexp.")
4742 (defvar-local org-complex-heading-regexp-format nil
4743 "Printf format to make regexp to match an exact headline.
4744 This regexp will match the headline of any node which has the
4745 exact headline text that is put into the format, but may have any
4746 TODO state, priority and tags.")
4748 (defvar-local org-todo-line-tags-regexp nil
4749 "Matches a headline and puts TODO state into group 2 if present.
4750 Also put tags into group 4 if tags are present.")
4752 (defconst org-plain-time-of-day-regexp
4753 (concat
4754 "\\(\\<[012]?[0-9]"
4755 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4756 "\\(--?"
4757 "\\(\\<[012]?[0-9]"
4758 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4759 "\\)?")
4760 "Regular expression to match a plain time or time range.
4761 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4762 groups carry important information:
4763 0 the full match
4764 1 the first time, range or not
4765 8 the second time, if it is a range.")
4767 (defconst org-plain-time-extension-regexp
4768 (concat
4769 "\\(\\<[012]?[0-9]"
4770 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4771 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4772 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4773 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4774 groups carry important information:
4775 0 the full match
4776 7 hours of duration
4777 9 minutes of duration")
4779 (defconst org-stamp-time-of-day-regexp
4780 (concat
4781 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4782 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4783 "\\(--?"
4784 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4785 "Regular expression to match a timestamp time or time range.
4786 After a match, the following groups carry important information:
4787 0 the full match
4788 1 date plus weekday, for back referencing to make sure both times are on the same day
4789 2 the first time, range or not
4790 4 the second time, if it is a range.")
4792 (defconst org-startup-options
4793 '(("fold" org-startup-folded t)
4794 ("overview" org-startup-folded t)
4795 ("nofold" org-startup-folded nil)
4796 ("showall" org-startup-folded nil)
4797 ("showeverything" org-startup-folded showeverything)
4798 ("content" org-startup-folded content)
4799 ("indent" org-startup-indented t)
4800 ("noindent" org-startup-indented nil)
4801 ("hidestars" org-hide-leading-stars t)
4802 ("showstars" org-hide-leading-stars nil)
4803 ("odd" org-odd-levels-only t)
4804 ("oddeven" org-odd-levels-only nil)
4805 ("align" org-startup-align-all-tables t)
4806 ("noalign" org-startup-align-all-tables nil)
4807 ("shrink" org-startup-shrink-all-tables t)
4808 ("inlineimages" org-startup-with-inline-images t)
4809 ("noinlineimages" org-startup-with-inline-images nil)
4810 ("latexpreview" org-startup-with-latex-preview t)
4811 ("nolatexpreview" org-startup-with-latex-preview nil)
4812 ("customtime" org-display-custom-times t)
4813 ("logdone" org-log-done time)
4814 ("lognotedone" org-log-done note)
4815 ("nologdone" org-log-done nil)
4816 ("lognoteclock-out" org-log-note-clock-out t)
4817 ("nolognoteclock-out" org-log-note-clock-out nil)
4818 ("logrepeat" org-log-repeat state)
4819 ("lognoterepeat" org-log-repeat note)
4820 ("logdrawer" org-log-into-drawer t)
4821 ("nologdrawer" org-log-into-drawer nil)
4822 ("logstatesreversed" org-log-states-order-reversed t)
4823 ("nologstatesreversed" org-log-states-order-reversed nil)
4824 ("nologrepeat" org-log-repeat nil)
4825 ("logreschedule" org-log-reschedule time)
4826 ("lognotereschedule" org-log-reschedule note)
4827 ("nologreschedule" org-log-reschedule nil)
4828 ("logredeadline" org-log-redeadline time)
4829 ("lognoteredeadline" org-log-redeadline note)
4830 ("nologredeadline" org-log-redeadline nil)
4831 ("logrefile" org-log-refile time)
4832 ("lognoterefile" org-log-refile note)
4833 ("nologrefile" org-log-refile nil)
4834 ("fninline" org-footnote-define-inline t)
4835 ("nofninline" org-footnote-define-inline nil)
4836 ("fnlocal" org-footnote-section nil)
4837 ("fnauto" org-footnote-auto-label t)
4838 ("fnprompt" org-footnote-auto-label nil)
4839 ("fnconfirm" org-footnote-auto-label confirm)
4840 ("fnplain" org-footnote-auto-label plain)
4841 ("fnadjust" org-footnote-auto-adjust t)
4842 ("nofnadjust" org-footnote-auto-adjust nil)
4843 ("constcgs" constants-unit-system cgs)
4844 ("constSI" constants-unit-system SI)
4845 ("noptag" org-tag-persistent-alist nil)
4846 ("hideblocks" org-hide-block-startup t)
4847 ("nohideblocks" org-hide-block-startup nil)
4848 ("beamer" org-startup-with-beamer-mode t)
4849 ("entitiespretty" org-pretty-entities t)
4850 ("entitiesplain" org-pretty-entities nil))
4851 "Variable associated with STARTUP options for Org.
4852 Each element is a list of three items: the startup options (as written
4853 in the #+STARTUP line), the corresponding variable, and the value to set
4854 this variable to if the option is found. An optional forth element PUSH
4855 means to push this value onto the list in the variable.")
4857 (defcustom org-group-tags t
4858 "When non-nil (the default), use group tags.
4859 This can be turned on/off through `org-toggle-tags-groups'."
4860 :group 'org-tags
4861 :group 'org-startup
4862 :type 'boolean)
4864 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4866 (defun org-toggle-tags-groups ()
4867 "Toggle support for group tags.
4868 Support for group tags is controlled by the option
4869 `org-group-tags', which is non-nil by default."
4870 (interactive)
4871 (setq org-group-tags (not org-group-tags))
4872 (cond ((and (derived-mode-p 'org-agenda-mode)
4873 org-group-tags)
4874 (org-agenda-redo))
4875 ((derived-mode-p 'org-mode)
4876 (let ((org-inhibit-startup t)) (org-mode))))
4877 (message "Groups tags support has been turned %s"
4878 (if org-group-tags "on" "off")))
4880 (defun org--tag-add-to-alist (alist1 alist2)
4881 "Merge tags from ALIST1 into ALIST2.
4883 Duplicates tags outside a group are removed. Keywords and order
4884 are preserved.
4886 The function assumes ALIST1 and ALIST2 are proper tag alists.
4887 See `org-tag-alist' for their structure."
4888 (cond
4889 ((null alist2) alist1)
4890 ((null alist1) alist2)
4892 (let ((to-add nil)
4893 (group-flag nil))
4894 (dolist (tag-pair alist1)
4895 (pcase tag-pair
4896 (`(,(or :startgrouptag :startgroup))
4897 (setq group-flag t)
4898 (push tag-pair to-add))
4899 (`(,(or :endgrouptag :endgroup))
4900 (setq group-flag nil)
4901 (push tag-pair to-add))
4902 (`(,(or :grouptags :newline))
4903 (push tag-pair to-add))
4904 (`(,tag . ,_)
4905 ;; Remove duplicates from ALIST1, unless they are in
4906 ;; a group. Indeed, it makes sense to have a tag appear in
4907 ;; multiple groups.
4908 (when (or group-flag (not (assoc tag alist2)))
4909 (push tag-pair to-add)))
4910 (_ (error "Invalid association in tag alist: %S" tag-pair))))
4911 ;; Preserve order of ALIST1.
4912 (append (nreverse to-add) alist2)))))
4914 (defun org-set-regexps-and-options (&optional tags-only)
4915 "Precompute regular expressions used in the current buffer.
4916 When optional argument TAGS-ONLY is non-nil, only compute tags
4917 related expressions."
4918 (when (derived-mode-p 'org-mode)
4919 (let ((alist (org--setup-collect-keywords
4920 (org-make-options-regexp
4921 (append '("FILETAGS" "TAGS" "SETUPFILE")
4922 (and (not tags-only)
4923 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4924 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4925 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4926 ;; Startup options. Get this early since it does change
4927 ;; behavior for other options (e.g., tags).
4928 (let ((startup (cdr (assq 'startup alist))))
4929 (dolist (option startup)
4930 (let ((entry (assoc-string option org-startup-options t)))
4931 (when entry
4932 (let ((var (nth 1 entry))
4933 (val (nth 2 entry)))
4934 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4935 (unless (listp (symbol-value var))
4936 (set (make-local-variable var) nil))
4937 (add-to-list var val)))))))
4938 (setq-local org-file-tags
4939 (mapcar #'org-add-prop-inherited
4940 (cdr (assq 'filetags alist))))
4941 (setq org-current-tag-alist
4942 (org--tag-add-to-alist
4943 org-tag-persistent-alist
4944 (let ((tags (cdr (assq 'tags alist))))
4945 (if tags (org-tag-string-to-alist tags)
4946 org-tag-alist))))
4947 (setq org-tag-groups-alist
4948 (org-tag-alist-to-groups org-current-tag-alist))
4949 (unless tags-only
4950 ;; File properties.
4951 (setq-local org-file-properties (cdr (assq 'property alist)))
4952 ;; Archive location.
4953 (let ((archive (cdr (assq 'archive alist))))
4954 (when archive (setq-local org-archive-location archive)))
4955 ;; Category.
4956 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4957 (when cat
4958 (setq-local org-category (intern cat))
4959 (setq-local org-file-properties
4960 (org--update-property-plist
4961 "CATEGORY" cat org-file-properties))))
4962 ;; Columns.
4963 (let ((column (cdr (assq 'columns alist))))
4964 (when column (setq-local org-columns-default-format column)))
4965 ;; Constants.
4966 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4967 ;; Link abbreviations.
4968 (let ((links (cdr (assq 'link alist))))
4969 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4970 ;; Priorities.
4971 (let ((priorities (cdr (assq 'priorities alist))))
4972 (when priorities
4973 (setq-local org-highest-priority (nth 0 priorities))
4974 (setq-local org-lowest-priority (nth 1 priorities))
4975 (setq-local org-default-priority (nth 2 priorities))))
4976 ;; Scripts.
4977 (let ((scripts (assq 'scripts alist)))
4978 (when scripts
4979 (setq-local org-use-sub-superscripts (cdr scripts))))
4980 ;; TODO keywords.
4981 (setq-local org-todo-kwd-alist nil)
4982 (setq-local org-todo-key-alist nil)
4983 (setq-local org-todo-key-trigger nil)
4984 (setq-local org-todo-keywords-1 nil)
4985 (setq-local org-done-keywords nil)
4986 (setq-local org-todo-heads nil)
4987 (setq-local org-todo-sets nil)
4988 (setq-local org-todo-log-states nil)
4989 (let ((todo-sequences
4990 (or (nreverse (cdr (assq 'todo alist)))
4991 (let ((d (default-value 'org-todo-keywords)))
4992 (if (not (stringp (car d))) d
4993 ;; XXX: Backward compatibility code.
4994 (list (cons org-todo-interpretation d)))))))
4995 (dolist (sequence todo-sequences)
4996 (let* ((sequence (or (run-hook-with-args-until-success
4997 'org-todo-setup-filter-hook sequence)
4998 sequence))
4999 (sequence-type (car sequence))
5000 (keywords (cdr sequence))
5001 (sep (member "|" keywords))
5002 names alist)
5003 (dolist (k (remove "|" keywords))
5004 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5006 (error "Invalid TODO keyword %s" k))
5007 (let ((name (match-string 1 k))
5008 (key (match-string 2 k))
5009 (log (org-extract-log-state-settings k)))
5010 (push name names)
5011 (push (cons name (and key (string-to-char key))) alist)
5012 (when log (push log org-todo-log-states))))
5013 (let* ((names (nreverse names))
5014 (done (if sep (org-remove-keyword-keys (cdr sep))
5015 (last names)))
5016 (head (car names))
5017 (tail (list sequence-type head (car done) (org-last done))))
5018 (add-to-list 'org-todo-heads head 'append)
5019 (push names org-todo-sets)
5020 (setq org-done-keywords (append org-done-keywords done nil))
5021 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5022 (setq org-todo-key-alist
5023 (append org-todo-key-alist
5024 (and alist
5025 (append '((:startgroup))
5026 (nreverse alist)
5027 '((:endgroup))))))
5028 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5029 (setq org-todo-sets (nreverse org-todo-sets)
5030 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5031 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5032 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5033 ;; Compute the regular expressions and other local variables.
5034 ;; Using `org-outline-regexp-bol' would complicate them much,
5035 ;; because of the fixed white space at the end of that string.
5036 (unless org-done-keywords
5037 (setq org-done-keywords
5038 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5039 (setq org-not-done-keywords
5040 (org-delete-all org-done-keywords
5041 (copy-sequence org-todo-keywords-1))
5042 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5043 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5044 org-not-done-heading-regexp
5045 (format org-heading-keyword-regexp-format org-not-done-regexp)
5046 org-todo-line-regexp
5047 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5048 org-complex-heading-regexp
5049 (concat "^\\(\\*+\\)"
5050 "\\(?: +" org-todo-regexp "\\)?"
5051 "\\(?: +\\(\\[#.\\]\\)\\)?"
5052 "\\(?: +\\(.*?\\)\\)??"
5053 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5054 "[ \t]*$")
5055 org-complex-heading-regexp-format
5056 (concat "^\\(\\*+\\)"
5057 "\\(?: +" org-todo-regexp "\\)?"
5058 "\\(?: +\\(\\[#.\\]\\)\\)?"
5059 "\\(?: +"
5060 ;; Stats cookies can be stuck to body.
5061 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5062 "\\(%s\\)"
5063 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5064 "\\)"
5065 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5066 "[ \t]*$")
5067 org-todo-line-tags-regexp
5068 (concat "^\\(\\*+\\)"
5069 "\\(?: +" org-todo-regexp "\\)?"
5070 "\\(?: +\\(.*?\\)\\)??"
5071 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5072 "[ \t]*$"))
5073 (org-compute-latex-and-related-regexp)))))
5075 (defun org--setup-collect-keywords (regexp &optional files alist)
5076 "Return setup keywords values as an alist.
5078 REGEXP matches a subset of setup keywords. FILES is a list of
5079 file names already visited. It is used to avoid circular setup
5080 files. ALIST, when non-nil, is the alist computed so far.
5082 Return value contains the following keys: `archive', `category',
5083 `columns', `constants', `filetags', `link', `priorities',
5084 `property', `scripts', `startup', `tags' and `todo'."
5085 (org-with-wide-buffer
5086 (goto-char (point-min))
5087 (let ((case-fold-search t))
5088 (while (re-search-forward regexp nil t)
5089 (let ((element (org-element-at-point)))
5090 (when (eq (org-element-type element) 'keyword)
5091 (let ((key (org-element-property :key element))
5092 (value (org-element-property :value element)))
5093 (cond
5094 ((equal key "ARCHIVE")
5095 (when (org-string-nw-p value)
5096 (push (cons 'archive value) alist)))
5097 ((equal key "CATEGORY") (push (cons 'category value) alist))
5098 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5099 ((equal key "CONSTANTS")
5100 (let* ((constants (assq 'constants alist))
5101 (store (cdr constants)))
5102 (dolist (pair (split-string value))
5103 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5104 pair)
5105 (let* ((name (match-string 1 pair))
5106 (value (match-string 2 pair))
5107 (old (assoc name store)))
5108 (if old (setcdr old value)
5109 (push (cons name value) store)))))
5110 (if constants (setcdr constants store)
5111 (push (cons 'constants store) alist))))
5112 ((equal key "FILETAGS")
5113 (when (org-string-nw-p value)
5114 (let ((old (assq 'filetags alist))
5115 (new (apply #'nconc
5116 (mapcar (lambda (x) (org-split-string x ":"))
5117 (split-string value)))))
5118 (if old (setcdr old (append new (cdr old)))
5119 (push (cons 'filetags new) alist)))))
5120 ((equal key "LINK")
5121 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5122 (let ((links (assq 'link alist))
5123 (pair (cons (match-string-no-properties 1 value)
5124 (match-string-no-properties 2 value))))
5125 (if links (push pair (cdr links))
5126 (push (list 'link pair) alist)))))
5127 ((equal key "OPTIONS")
5128 (when (and (org-string-nw-p value)
5129 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5130 (push (cons 'scripts (read (match-string 1 value))) alist)))
5131 ((equal key "PRIORITIES")
5132 (push (cons 'priorities
5133 (let ((prio (split-string value)))
5134 (if (< (length prio) 3) '(?A ?C ?B)
5135 (mapcar #'string-to-char prio))))
5136 alist))
5137 ((equal key "PROPERTY")
5138 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5139 (let* ((property (assq 'property alist))
5140 (value (org--update-property-plist
5141 (match-string-no-properties 1 value)
5142 (match-string-no-properties 2 value)
5143 (cdr property))))
5144 (if property (setcdr property value)
5145 (push (cons 'property value) alist)))))
5146 ((equal key "STARTUP")
5147 (let ((startup (assq 'startup alist)))
5148 (if startup
5149 (setcdr startup
5150 (append (cdr startup) (split-string value)))
5151 (push (cons 'startup (split-string value)) alist))))
5152 ((equal key "TAGS")
5153 (let ((tag-cell (assq 'tags alist)))
5154 (if tag-cell
5155 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5156 (push (cons 'tags value) alist))))
5157 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5158 (let ((todo (assq 'todo alist))
5159 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5160 (split-string value))))
5161 (if todo (push value (cdr todo))
5162 (push (list 'todo value) alist))))
5163 ((equal key "SETUPFILE")
5164 (unless buffer-read-only ; Do not check in Gnus messages.
5165 (let ((f (and (org-string-nw-p value)
5166 (expand-file-name
5167 (org-unbracket-string "\"" "\"" value)))))
5168 (when (and f (file-readable-p f) (not (member f files)))
5169 (with-temp-buffer
5170 (setq default-directory (file-name-directory f))
5171 (insert-file-contents f)
5172 (setq alist
5173 ;; Fake Org mode to benefit from cache
5174 ;; without recurring needlessly.
5175 (let ((major-mode 'org-mode))
5176 (org--setup-collect-keywords
5177 regexp (cons f files) alist)))))))))))))))
5178 alist)
5180 (defun org-tag-string-to-alist (s)
5181 "Return tag alist associated to string S.
5182 S is a value for TAGS keyword or produced with
5183 `org-tag-alist-to-string'. Return value is an alist suitable for
5184 `org-tag-alist' or `org-tag-persistent-alist'."
5185 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5186 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5187 "\\(?:(\\(.\\))\\)?\\'"))
5188 alist group-flag)
5189 (dolist (tokens lines (cdr (nreverse alist)))
5190 (push '(:newline) alist)
5191 (while tokens
5192 (let ((token (pop tokens)))
5193 (pcase token
5194 ("{"
5195 (push '(:startgroup) alist)
5196 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5197 ("}"
5198 (push '(:endgroup) alist)
5199 (setq group-flag nil))
5200 ("["
5201 (push '(:startgrouptag) alist)
5202 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5203 ("]"
5204 (push '(:endgrouptag) alist)
5205 (setq group-flag nil))
5206 (":"
5207 (push '(:grouptags) alist))
5208 ((guard (string-match tag-re token))
5209 (let ((tag (match-string 1 token))
5210 (key (and (match-beginning 2)
5211 (string-to-char (match-string 2 token)))))
5212 ;; Push all tags in groups, no matter if they already
5213 ;; appear somewhere else in the list.
5214 (when (or group-flag (not (assoc tag alist)))
5215 (push (cons tag key) alist))))))))))
5217 (defun org-tag-alist-to-string (alist &optional skip-key)
5218 "Return tag string associated to ALIST.
5220 ALIST is an alist, as defined in `org-tag-alist' or
5221 `org-tag-persistent-alist', or produced with
5222 `org-tag-string-to-alist'.
5224 Return value is a string suitable as a value for \"TAGS\"
5225 keyword.
5227 When optional argument SKIP-KEY is non-nil, skip selection keys
5228 next to tags."
5229 (mapconcat (lambda (token)
5230 (pcase token
5231 (`(:startgroup) "{")
5232 (`(:endgroup) "}")
5233 (`(:startgrouptag) "[")
5234 (`(:endgrouptag) "]")
5235 (`(:grouptags) ":")
5236 (`(:newline) "\\n")
5237 ((and
5238 (guard (not skip-key))
5239 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5240 (format "%s(%c)" tag key))
5241 (`(,(and tag (pred stringp)) . ,_) tag)
5242 (_ (user-error "Invalid tag token: %S" token))))
5243 alist
5244 " "))
5246 (defun org-tag-alist-to-groups (alist)
5247 "Return group alist from tag ALIST.
5248 ALIST is an alist, as defined in `org-tag-alist' or
5249 `org-tag-persistent-alist', or produced with
5250 `org-tag-string-to-alist'. Return value is an alist following
5251 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5252 a string, summarizing TAGS, as a list of strings."
5253 (let (groups group-status current-group)
5254 (dolist (token alist (nreverse groups))
5255 (pcase token
5256 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5257 (`(,(or :endgroup :endgrouptag))
5258 (when (eq group-status 'append)
5259 (push (nreverse current-group) groups))
5260 (setq group-status nil current-group nil))
5261 (`(:grouptags) (setq group-status 'append))
5262 ((and `(,tag . ,_) (guard group-status))
5263 (if (eq group-status 'append) (push tag current-group)
5264 (setq current-group (list tag))))
5265 (_ nil)))))
5267 (defvar org--file-cache (make-hash-table :test #'equal)
5268 "Hash table to store contents of files referenced via a URL.
5269 This is the cache of file URLs read using `org-file-contents'.")
5271 (defun org-reset-file-cache ()
5272 "Reset the cache of files downloaded by `org-file-contents'."
5273 (clrhash org--file-cache))
5275 (defun org-file-url-p (file)
5276 "Non-nil if FILE is a URL."
5277 (require 'ffap)
5278 (string-match-p ffap-url-regexp file))
5280 (defun org-file-contents (file &optional noerror nocache)
5281 "Return the contents of FILE, as a string.
5283 FILE can be a file name or URL.
5285 If FILE is a URL, download the contents. If the URL contents are
5286 already cached in the `org--file-cache' hash table, the download step
5287 is skipped.
5289 If NOERROR is non-nil, ignore the error when unable to read the FILE
5290 from file or URL.
5292 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5293 is available. This option applies only if FILE is a URL."
5294 (let* ((is-url (org-file-url-p file))
5295 (cache (and is-url
5296 (not nocache)
5297 (gethash file org--file-cache))))
5298 (cond
5299 (cache)
5300 (is-url
5301 (with-current-buffer (url-retrieve-synchronously file)
5302 (goto-char (point-min))
5303 ;; Move point to after the url-retrieve header.
5304 (search-forward "\n\n" nil :move)
5305 ;; Search for the success code only in the url-retrieve header.
5306 (if (save-excursion
5307 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5308 ;; Update the cache `org--file-cache' and return contents.
5309 (puthash file
5310 (buffer-substring-no-properties (point) (point-max))
5311 org--file-cache)
5312 (funcall (if noerror #'message #'user-error)
5313 "Unable to fetch file from %S"
5314 file))))
5316 (with-temp-buffer
5317 (condition-case nil
5318 (progn
5319 (insert-file-contents file)
5320 (buffer-string))
5321 (file-error
5322 (funcall (if noerror #'message #'user-error)
5323 "Unable to read file %S"
5324 file))))))))
5326 (defun org-extract-log-state-settings (x)
5327 "Extract the log state setting from a TODO keyword string.
5328 This will extract info from a string like \"WAIT(w@/!)\"."
5329 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5330 (let ((kw (match-string 1 x))
5331 (log1 (and (match-end 3) (match-string 3 x)))
5332 (log2 (and (match-end 4) (match-string 4 x))))
5333 (and (or log1 log2)
5334 (list kw
5335 (and log1 (if (equal log1 "!") 'time 'note))
5336 (and log2 (if (equal log2 "!") 'time 'note)))))))
5338 (defun org-remove-keyword-keys (list)
5339 "Remove a pair of parenthesis at the end of each string in LIST."
5340 (mapcar (lambda (x)
5341 (if (string-match "(.*)$" x)
5342 (substring x 0 (match-beginning 0))
5344 list))
5346 (defun org-assign-fast-keys (alist)
5347 "Assign fast keys to a keyword-key alist.
5348 Respect keys that are already there."
5349 (let (new e (alt ?0))
5350 (while (setq e (pop alist))
5351 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5352 (cdr e)) ;; Key already assigned.
5353 (push e new)
5354 (let ((clist (string-to-list (downcase (car e))))
5355 (used (append new alist)))
5356 (when (= (car clist) ?@)
5357 (pop clist))
5358 (while (and clist (rassoc (car clist) used))
5359 (pop clist))
5360 (unless clist
5361 (while (rassoc alt used)
5362 (cl-incf alt)))
5363 (push (cons (car e) (or (car clist) alt)) new))))
5364 (nreverse new)))
5366 ;;; Some variables used in various places
5368 (defvar org-window-configuration nil
5369 "Used in various places to store a window configuration.")
5370 (defvar org-selected-window nil
5371 "Used in various places to store a window configuration.")
5372 (defvar org-finish-function nil
5373 "Function to be called when `C-c C-c' is used.
5374 This is for getting out of special buffers like capture.")
5375 (defvar org-last-state)
5377 ;; Defined somewhere in this file, but used before definition.
5378 (defvar org-entities) ;; defined in org-entities.el
5379 (defvar org-struct-menu)
5380 (defvar org-org-menu)
5381 (defvar org-tbl-menu)
5383 ;;;; Define the Org mode
5385 ;; We use a before-change function to check if a table might need
5386 ;; an update.
5387 (defvar org-table-may-need-update t
5388 "Indicates that a table might need an update.
5389 This variable is set by `org-before-change-function'.
5390 `org-table-align' sets it back to nil.")
5391 (defun org-before-change-function (_beg _end)
5392 "Every change indicates that a table might need an update."
5393 (setq org-table-may-need-update t))
5394 (defvar org-mode-map)
5395 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5396 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5397 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5398 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5399 (defvar org-table-buffer-is-an nil)
5401 (defvar bidi-paragraph-direction)
5402 (defvar buffer-face-mode-face)
5404 (require 'outline)
5406 ;; Other stuff we need.
5407 (require 'time-date)
5408 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5409 (require 'easymenu)
5410 (autoload 'easy-menu-add "easymenu")
5411 (require 'overlay)
5413 ;; (require 'org-macs) moved higher up in the file before it is first used
5414 (require 'org-entities)
5415 ;; (require 'org-compat) moved higher up in the file before it is first used
5416 (require 'org-faces)
5417 (require 'org-list)
5418 (require 'org-pcomplete)
5419 (require 'org-src)
5420 (require 'org-footnote)
5421 (require 'org-macro)
5423 ;; babel
5424 (require 'ob)
5426 ;;;###autoload
5427 (define-derived-mode org-mode outline-mode "Org"
5428 "Outline-based notes management and organizer, alias
5429 \"Carsten's outline-mode for keeping track of everything.\"
5431 Org mode develops organizational tasks around a NOTES file which
5432 contains information about projects as plain text. Org mode is
5433 implemented on top of Outline mode, which is ideal to keep the content
5434 of large files well structured. It supports ToDo items, deadlines and
5435 time stamps, which magically appear in the diary listing of the Emacs
5436 calendar. Tables are easily created with a built-in table editor.
5437 Plain text URL-like links connect to websites, emails (VM), Usenet
5438 messages (Gnus), BBDB entries, and any files related to the project.
5439 For printing and sharing of notes, an Org file (or a part of it)
5440 can be exported as a structured ASCII or HTML file.
5442 The following commands are available:
5444 \\{org-mode-map}"
5446 ;; Get rid of Outline menus, they are not needed
5447 ;; Need to do this here because define-derived-mode sets up
5448 ;; the keymap so late. Still, it is a waste to call this each time
5449 ;; we switch another buffer into Org mode.
5450 (define-key org-mode-map [menu-bar headings] 'undefined)
5451 (define-key org-mode-map [menu-bar hide] 'undefined)
5452 (define-key org-mode-map [menu-bar show] 'undefined)
5454 (org-load-modules-maybe)
5455 (org-install-agenda-files-menu)
5456 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5457 (add-to-invisibility-spec '(org-hide-block . t))
5458 (add-to-invisibility-spec '(org-hide-drawer . t))
5459 (setq-local outline-regexp org-outline-regexp)
5460 (setq-local outline-level 'org-outline-level)
5461 (setq bidi-paragraph-direction 'left-to-right)
5462 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5463 (unless org-display-table
5464 (setq org-display-table (make-display-table)))
5465 (set-display-table-slot
5466 org-display-table 4
5467 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5468 org-ellipsis)))
5469 (setq buffer-display-table org-display-table))
5470 (org-set-regexps-and-options)
5471 (org-set-font-lock-defaults)
5472 (when (and org-tag-faces (not org-tags-special-faces-re))
5473 ;; tag faces set outside customize.... force initialization.
5474 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5475 ;; Calc embedded
5476 (setq-local calc-embedded-open-mode "# ")
5477 ;; Modify a few syntax entries
5478 (modify-syntax-entry ?\" "\"")
5479 (modify-syntax-entry ?\\ "_")
5480 (modify-syntax-entry ?~ "_")
5481 (modify-syntax-entry ?< "(>")
5482 (modify-syntax-entry ?> ")<")
5483 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5484 ;; Activate before-change-function
5485 (setq-local org-table-may-need-update t)
5486 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5487 ;; Check for running clock before killing a buffer
5488 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5489 ;; Initialize macros templates.
5490 (org-macro-initialize-templates)
5491 ;; Initialize radio targets.
5492 (org-update-radio-target-regexp)
5493 ;; Indentation.
5494 (setq-local indent-line-function 'org-indent-line)
5495 (setq-local indent-region-function 'org-indent-region)
5496 ;; Filling and auto-filling.
5497 (org-setup-filling)
5498 ;; Comments.
5499 (org-setup-comments-handling)
5500 ;; Initialize cache.
5501 (org-element-cache-reset)
5502 ;; Beginning/end of defun
5503 (setq-local beginning-of-defun-function 'org-backward-element)
5504 (setq-local end-of-defun-function
5505 (lambda ()
5506 (if (not (org-at-heading-p))
5507 (org-forward-element)
5508 (org-forward-element)
5509 (forward-char -1))))
5510 ;; Next error for sparse trees
5511 (setq-local next-error-function 'org-occur-next-match)
5512 ;; Make sure dependence stuff works reliably, even for users who set it
5513 ;; too late :-(
5514 (if org-enforce-todo-dependencies
5515 (add-hook 'org-blocker-hook
5516 'org-block-todo-from-children-or-siblings-or-parent)
5517 (remove-hook 'org-blocker-hook
5518 'org-block-todo-from-children-or-siblings-or-parent))
5519 (if org-enforce-todo-checkbox-dependencies
5520 (add-hook 'org-blocker-hook
5521 'org-block-todo-from-checkboxes)
5522 (remove-hook 'org-blocker-hook
5523 'org-block-todo-from-checkboxes))
5525 ;; Align options lines
5526 (setq-local
5527 align-mode-rules-list
5528 '((org-in-buffer-settings
5529 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5530 (modes . '(org-mode)))))
5532 ;; Imenu
5533 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5535 ;; Make isearch reveal context
5536 (setq-local outline-isearch-open-invisible-function
5537 (lambda (&rest _) (org-show-context 'isearch)))
5539 ;; Setup the pcomplete hooks
5540 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5541 (setq-local pcomplete-command-name-function 'org-command-at-point)
5542 (setq-local pcomplete-default-completion-function 'ignore)
5543 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5544 (setq-local pcomplete-termination-string "")
5545 (setq-local buffer-face-mode-face 'org-default)
5547 ;; If empty file that did not turn on Org mode automatically, make
5548 ;; it to.
5549 (when (and org-insert-mode-line-in-empty-file
5550 (called-interactively-p 'any)
5551 (= (point-min) (point-max)))
5552 (insert "# -*- mode: org -*-\n\n"))
5553 (unless org-inhibit-startup
5554 (org-unmodified
5555 (when org-startup-with-beamer-mode (org-beamer-mode))
5556 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5557 (org-table-map-tables
5558 (cond ((and org-startup-align-all-tables
5559 org-startup-shrink-all-tables)
5560 (lambda () (org-table-align) (org-table-shrink)))
5561 (org-startup-align-all-tables #'org-table-align)
5562 (t #'org-table-shrink))
5564 (when org-startup-with-inline-images (org-display-inline-images))
5565 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5566 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5567 (when org-startup-truncated (setq truncate-lines t))
5568 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5569 (org-refresh-effort-properties)))
5570 ;; Try to set `org-hide' face correctly.
5571 (let ((foreground (org-find-invisible-foreground)))
5572 (when foreground
5573 (set-face-foreground 'org-hide foreground))))
5575 ;; Update `customize-package-emacs-version-alist'
5576 (add-to-list 'customize-package-emacs-version-alist
5577 '(Org ("8.0" . "24.4")
5578 ("8.1" . "24.4")
5579 ("8.2" . "24.4")
5580 ("8.2.7" . "24.4")
5581 ("8.3" . "26.1")
5582 ("9.0" . "26.1")
5583 ("9.1" . "26.1")
5584 ("9.2" . "27.1")))
5586 (defvar org-mode-transpose-word-syntax-table
5587 (let ((st (make-syntax-table text-mode-syntax-table)))
5588 (dolist (c org-emphasis-alist st)
5589 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5591 (when (fboundp 'abbrev-table-put)
5592 (abbrev-table-put org-mode-abbrev-table
5593 :parents (list text-mode-abbrev-table)))
5595 (defun org-find-invisible-foreground ()
5596 (let ((candidates (remove
5597 "unspecified-bg"
5598 (nconc
5599 (list (face-background 'default)
5600 (face-background 'org-default))
5601 (mapcar
5602 (lambda (alist)
5603 (when (boundp alist)
5604 (cdr (assq 'background-color (symbol-value alist)))))
5605 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5606 (list (face-foreground 'org-hide))))))
5607 (car (remove nil candidates))))
5609 (defun org-current-time (&optional rounding-minutes past)
5610 "Current time, possibly rounded to ROUNDING-MINUTES.
5611 When ROUNDING-MINUTES is not an integer, fall back on the car of
5612 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5613 the rounding returns a past time."
5614 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5615 (car org-time-stamp-rounding-minutes)))
5616 (time (decode-time)) res)
5617 (if (< r 1)
5618 (current-time)
5619 (setq res
5620 (apply 'encode-time
5621 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5622 (nthcdr 2 time))))
5623 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5624 (seconds-to-time (- (float-time res) (* r 60)))
5625 res))))
5627 (defun org-today ()
5628 "Return today date, considering `org-extend-today-until'."
5629 (time-to-days
5630 (time-subtract (current-time)
5631 (list 0 (* 3600 org-extend-today-until) 0))))
5633 ;;;; Font-Lock stuff, including the activators
5635 (defvar org-mouse-map (make-sparse-keymap))
5636 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5637 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5638 (when org-mouse-1-follows-link
5639 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5640 (when org-tab-follows-link
5641 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5642 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5644 (require 'font-lock)
5646 (defconst org-non-link-chars "]\t\n\r<>")
5647 (defvar org-link-types-re nil
5648 "Matches a link that has a url-like prefix like \"http:\"")
5649 (defvar org-link-re-with-space nil
5650 "Matches a link with spaces, optional angular brackets around it.")
5651 (defvar org-link-re-with-space2 nil
5652 "Matches a link with spaces, optional angular brackets around it.")
5653 (defvar org-link-re-with-space3 nil
5654 "Matches a link with spaces, only for internal part in bracket links.")
5655 (defvar org-angle-link-re nil
5656 "Matches link with angular brackets, spaces are allowed.")
5657 (defvar org-plain-link-re nil
5658 "Matches plain link, without spaces.")
5659 (defvar org-bracket-link-regexp nil
5660 "Matches a link in double brackets.")
5661 (defvar org-bracket-link-analytic-regexp nil
5662 "Regular expression used to analyze links.
5663 Here is what the match groups contain after a match:
5664 1: http:
5665 2: http
5666 3: path
5667 4: [desc]
5668 5: desc")
5669 (defvar org-bracket-link-analytic-regexp++ nil
5670 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5671 (defvar org-any-link-re nil
5672 "Regular expression matching any link.")
5674 (defconst org-match-sexp-depth 3
5675 "Number of stacked braces for sub/superscript matching.")
5677 (defun org-create-multibrace-regexp (left right n)
5678 "Create a regular expression which will match a balanced sexp.
5679 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5680 as single character strings.
5681 The regexp returned will match the entire expression including the
5682 delimiters. It will also define a single group which contains the
5683 match except for the outermost delimiters. The maximum depth of
5684 stacked delimiters is N. Escaping delimiters is not possible."
5685 (let* ((nothing (concat "[^" left right "]*?"))
5686 (or "\\|")
5687 (re nothing)
5688 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5689 (while (> n 1)
5690 (setq n (1- n)
5691 re (concat re or next)
5692 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5693 (concat left "\\(" re "\\)" right)))
5695 (defconst org-match-substring-regexp
5696 (concat
5697 "\\(\\S-\\)\\([_^]\\)\\("
5698 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5699 "\\|"
5700 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5701 "\\|"
5702 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5703 "The regular expression matching a sub- or superscript.")
5705 (defconst org-match-substring-with-braces-regexp
5706 (concat
5707 "\\(\\S-\\)\\([_^]\\)"
5708 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5709 "The regular expression matching a sub- or superscript, forcing braces.")
5711 (defun org-make-link-regexps ()
5712 "Update the link regular expressions.
5713 This should be called after the variable `org-link-parameters' has changed."
5714 (let ((types-re (regexp-opt (org-link-types) t)))
5715 (setq org-link-types-re
5716 (concat "\\`" types-re ":")
5717 org-link-re-with-space
5718 (concat "<?" types-re ":"
5719 "\\([^" org-non-link-chars " ]"
5720 "[^" org-non-link-chars "]*"
5721 "[^" org-non-link-chars " ]\\)>?")
5722 org-link-re-with-space2
5723 (concat "<?" types-re ":"
5724 "\\([^" org-non-link-chars " ]"
5725 "[^\t\n\r]*"
5726 "[^" org-non-link-chars " ]\\)>?")
5727 org-link-re-with-space3
5728 (concat "<?" types-re ":"
5729 "\\([^" org-non-link-chars " ]"
5730 "[^\t\n\r]*\\)")
5731 org-angle-link-re
5732 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5733 types-re)
5734 org-plain-link-re
5735 (concat
5736 "\\<" types-re ":"
5737 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5738 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5739 org-bracket-link-regexp
5740 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5741 org-bracket-link-analytic-regexp
5742 (concat
5743 "\\[\\["
5744 "\\(" types-re ":\\)?"
5745 "\\([^]]+\\)"
5746 "\\]"
5747 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5748 "\\]")
5749 org-bracket-link-analytic-regexp++
5750 (concat
5751 "\\[\\["
5752 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5753 "\\([^]]+\\)"
5754 "\\]"
5755 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5756 "\\]")
5757 org-any-link-re
5758 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5759 org-angle-link-re "\\)\\|\\("
5760 org-plain-link-re "\\)"))))
5762 (org-make-link-regexps)
5764 (defvar org-emph-face nil)
5766 (defun org-do-emphasis-faces (limit)
5767 "Run through the buffer and emphasize strings."
5768 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5769 (car org-emphasis-regexp-components))))
5770 (catch :exit
5771 (while (re-search-forward quick-re limit t)
5772 (let* ((marker (match-string 2))
5773 (verbatim? (member marker '("~" "="))))
5774 (when (save-excursion
5775 (goto-char (match-beginning 0))
5776 (and
5777 ;; Do not match table hlines.
5778 (not (and (equal marker "+")
5779 (org-match-line
5780 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5781 ;; Do not match headline stars. Do not consider
5782 ;; stars of a headline as closing marker for bold
5783 ;; markup either.
5784 (not (and (equal marker "*")
5785 (save-excursion
5786 (forward-char)
5787 (skip-chars-backward "*")
5788 (looking-at-p org-outline-regexp-bol))))
5789 ;; Match full emphasis markup regexp.
5790 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5791 ;; Do not span over paragraph boundaries.
5792 (not (string-match-p org-element-paragraph-separate
5793 (match-string 2)))
5794 ;; Do not span over cells in table rows.
5795 (not (and (save-match-data (org-match-line "[ \t]*|"))
5796 (string-match-p "|" (match-string 4))))))
5797 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5798 (font-lock-prepend-text-property
5799 (match-beginning 2) (match-end 2) 'face face)
5800 (when verbatim?
5801 (org-remove-flyspell-overlays-in
5802 (match-beginning 0) (match-end 0)))
5803 (add-text-properties (match-beginning 2) (match-end 2)
5804 '(font-lock-multiline t org-emphasis t))
5805 (when org-hide-emphasis-markers
5806 (add-text-properties (match-end 4) (match-beginning 5)
5807 '(invisible org-link))
5808 (add-text-properties (match-beginning 3) (match-end 3)
5809 '(invisible org-link)))
5810 (throw :exit t))))))))
5812 (defun org-emphasize (&optional char)
5813 "Insert or change an emphasis, i.e. a font like bold or italic.
5814 If there is an active region, change that region to a new emphasis.
5815 If there is no region, just insert the marker characters and position
5816 the cursor between them.
5817 CHAR should be the marker character. If it is a space, it means to
5818 remove the emphasis of the selected region.
5819 If CHAR is not given (for example in an interactive call) it will be
5820 prompted for."
5821 (interactive)
5822 (let ((erc org-emphasis-regexp-components)
5823 (string "") beg end move s)
5824 (if (org-region-active-p)
5825 (setq beg (region-beginning)
5826 end (region-end)
5827 string (buffer-substring beg end))
5828 (setq move t))
5830 (unless char
5831 (message "Emphasis marker or tag: [%s]"
5832 (mapconcat #'car org-emphasis-alist ""))
5833 (setq char (read-char-exclusive)))
5834 (if (equal char ?\s)
5835 (setq s ""
5836 move nil)
5837 (unless (assoc (char-to-string char) org-emphasis-alist)
5838 (user-error "No such emphasis marker: \"%c\"" char))
5839 (setq s (char-to-string char)))
5840 (while (and (> (length string) 1)
5841 (equal (substring string 0 1) (substring string -1))
5842 (assoc (substring string 0 1) org-emphasis-alist))
5843 (setq string (substring string 1 -1)))
5844 (setq string (concat s string s))
5845 (when beg (delete-region beg end))
5846 (unless (or (bolp)
5847 (string-match (concat "[" (nth 0 erc) "\n]")
5848 (char-to-string (char-before (point)))))
5849 (insert " "))
5850 (unless (or (eobp)
5851 (string-match (concat "[" (nth 1 erc) "\n]")
5852 (char-to-string (char-after (point)))))
5853 (insert " ") (backward-char 1))
5854 (insert string)
5855 (and move (backward-char 1))))
5857 (defconst org-nonsticky-props
5858 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5860 (defsubst org-rear-nonsticky-at (pos)
5861 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5863 (defun org-activate-links (limit)
5864 "Add link properties to links.
5865 This includes angle, plain, and bracket links."
5866 (catch :exit
5867 (while (re-search-forward org-any-link-re limit t)
5868 (let* ((start (match-beginning 0))
5869 (end (match-end 0))
5870 (style (cond ((eq ?< (char-after start)) 'angle)
5871 ((eq ?\[ (char-after (1+ start))) 'bracket)
5872 (t 'plain))))
5873 (when (and (memq style org-highlight-links)
5874 ;; Do not confuse plain links with tags.
5875 (not (and (eq style 'plain)
5876 (let ((face (get-text-property
5877 (max (1- start) (point-min)) 'face)))
5878 (if (consp face) (memq 'org-tag face)
5879 (eq 'org-tag face))))))
5880 (let* ((link-object (save-excursion
5881 (goto-char start)
5882 (save-match-data (org-element-link-parser))))
5883 (link (org-element-property :raw-link link-object))
5884 (type (org-element-property :type link-object))
5885 (path (org-element-property :path link-object))
5886 (properties ;for link's visible part
5887 (list
5888 'face (pcase (org-link-get-parameter type :face)
5889 ((and (pred functionp) face) (funcall face path))
5890 ((and (pred facep) face) face)
5891 ((and (pred consp) face) face) ;anonymous
5892 (_ 'org-link))
5893 'mouse-face (or (org-link-get-parameter type :mouse-face)
5894 'highlight)
5895 'keymap (or (org-link-get-parameter type :keymap)
5896 org-mouse-map)
5897 'help-echo (pcase (org-link-get-parameter type :help-echo)
5898 ((and (pred stringp) echo) echo)
5899 ((and (pred functionp) echo) echo)
5900 (_ (concat "LINK: " link)))
5901 'htmlize-link (pcase (org-link-get-parameter type
5902 :htmlize-link)
5903 ((and (pred functionp) f) (funcall f))
5904 (_ `(:uri ,link)))
5905 'font-lock-multiline t)))
5906 (org-remove-flyspell-overlays-in start end)
5907 (org-rear-nonsticky-at end)
5908 (if (not (eq 'bracket style))
5909 (add-text-properties start end properties)
5910 ;; Handle invisible parts in bracket links.
5911 (remove-text-properties start end '(invisible nil))
5912 (let ((hidden
5913 (append `(invisible
5914 ,(or (org-link-get-parameter type :display)
5915 'org-link))
5916 properties))
5917 (visible-start (or (match-beginning 4) (match-beginning 2)))
5918 (visible-end (or (match-end 4) (match-end 2))))
5919 (add-text-properties start visible-start hidden)
5920 (add-text-properties visible-start visible-end properties)
5921 (add-text-properties visible-end end hidden)
5922 (org-rear-nonsticky-at visible-start)
5923 (org-rear-nonsticky-at visible-end)))
5924 (let ((f (org-link-get-parameter type :activate-func)))
5925 (when (functionp f)
5926 (funcall f start end path (eq style 'bracket))))
5927 (throw :exit t))))) ;signal success
5928 nil))
5930 (defun org-activate-code (limit)
5931 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5932 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5933 (remove-text-properties (match-beginning 0) (match-end 0)
5934 '(display t invisible t intangible t))
5937 (defcustom org-src-fontify-natively t
5938 "When non-nil, fontify code in code blocks.
5939 See also the `org-block' face."
5940 :type 'boolean
5941 :version "26.1"
5942 :package-version '(Org . "8.3")
5943 :group 'org-appearance
5944 :group 'org-babel)
5946 (defcustom org-allow-promoting-top-level-subtree nil
5947 "When non-nil, allow promoting a top level subtree.
5948 The leading star of the top level headline will be replaced
5949 by a #."
5950 :type 'boolean
5951 :version "24.1"
5952 :group 'org-appearance)
5954 (defun org-fontify-meta-lines-and-blocks (limit)
5955 (condition-case nil
5956 (org-fontify-meta-lines-and-blocks-1 limit)
5957 (error (message "Org mode fontification error in %S at %d"
5958 (current-buffer)
5959 (line-number-at-pos)))))
5961 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5962 "Fontify #+ lines and blocks."
5963 (let ((case-fold-search t))
5964 (when (re-search-forward
5965 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5966 limit t)
5967 (let ((beg (match-beginning 0))
5968 (block-start (match-end 0))
5969 (block-end nil)
5970 (lang (match-string 7))
5971 (beg1 (line-beginning-position 2))
5972 (dc1 (downcase (match-string 2)))
5973 (dc3 (downcase (match-string 3)))
5974 end end1 quoting block-type)
5975 (cond
5976 ((and (match-end 4) (equal dc3 "+begin"))
5977 ;; Truly a block
5978 (setq block-type (downcase (match-string 5))
5979 quoting (member block-type org-protecting-blocks))
5980 (when (re-search-forward
5981 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5982 nil t) ;; on purpose, we look further than LIMIT
5983 (setq end (min (point-max) (match-end 0))
5984 end1 (min (point-max) (1- (match-beginning 0))))
5985 (setq block-end (match-beginning 0))
5986 (when quoting
5987 (org-remove-flyspell-overlays-in beg1 end1)
5988 (remove-text-properties beg end
5989 '(display t invisible t intangible t)))
5990 (add-text-properties
5991 beg end '(font-lock-fontified t font-lock-multiline t))
5992 (add-text-properties beg beg1 '(face org-meta-line))
5993 (org-remove-flyspell-overlays-in beg beg1)
5994 (add-text-properties ; For end_src
5995 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5996 (org-remove-flyspell-overlays-in end1 end)
5997 (cond
5998 ((and lang (not (string= lang "")) org-src-fontify-natively)
5999 (org-src-font-lock-fontify-block lang block-start block-end)
6000 (add-text-properties beg1 block-end '(src-block t)))
6001 (quoting
6002 (add-text-properties beg1 (min (point-max) (1+ end1))
6003 (list 'face
6004 (list :inherit
6005 (let ((face-name
6006 (intern (format "org-block-%s" lang))))
6007 (append (and (facep face-name) (list face-name))
6008 '(org-block))))))) ; end of source block
6009 ((not org-fontify-quote-and-verse-blocks))
6010 ((string= block-type "quote")
6011 (add-face-text-property
6012 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6013 ((string= block-type "verse")
6014 (add-face-text-property
6015 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6016 (add-text-properties beg beg1 '(face org-block-begin-line))
6017 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6018 '(face org-block-end-line))
6020 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6021 (org-remove-flyspell-overlays-in
6022 (match-beginning 0)
6023 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6024 (add-text-properties
6025 beg (match-end 3)
6026 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6027 '(font-lock-fontified t invisible t)
6028 '(font-lock-fontified t face org-document-info-keyword)))
6029 (add-text-properties
6030 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6031 (if (string-equal dc1 "+title:")
6032 '(font-lock-fontified t face org-document-title)
6033 '(font-lock-fontified t face org-document-info))))
6034 ((string-prefix-p "+caption" dc1)
6035 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6036 (remove-text-properties (match-beginning 0) (match-end 0)
6037 '(display t invisible t intangible t))
6038 ;; Handle short captions.
6039 (save-excursion
6040 (beginning-of-line)
6041 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6042 (add-text-properties (line-beginning-position) (match-end 1)
6043 '(font-lock-fontified t face org-meta-line))
6044 (add-text-properties (match-end 0) (line-end-position)
6045 '(font-lock-fontified t face org-block))
6047 ((member dc3 '(" " ""))
6048 (org-remove-flyspell-overlays-in beg (match-end 0))
6049 (add-text-properties
6050 beg (match-end 0)
6051 '(font-lock-fontified t face font-lock-comment-face)))
6052 (t ;; just any other in-buffer setting, but not indented
6053 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6054 (remove-text-properties (match-beginning 0) (match-end 0)
6055 '(display t invisible t intangible t))
6056 (add-text-properties beg (match-end 0)
6057 '(font-lock-fontified t face org-meta-line))
6058 t))))))
6060 (defun org-fontify-drawers (limit)
6061 "Fontify drawers."
6062 (when (re-search-forward org-drawer-regexp limit t)
6063 (add-text-properties
6064 (match-beginning 0) (match-end 0)
6065 '(font-lock-fontified t face org-special-keyword))
6066 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6069 (defun org-fontify-macros (limit)
6070 "Fontify macros."
6071 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6072 (let ((begin (match-beginning 0))
6073 (opening-end (match-beginning 1)))
6074 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6075 (match-string 1))
6076 (let ((end (match-end 1))
6077 (closing-start (match-beginning 1)))
6078 (add-text-properties
6079 begin end
6080 '(font-lock-multiline t font-lock-fontified t face org-macro))
6081 (org-remove-flyspell-overlays-in begin end)
6082 (when org-hide-macro-markers
6083 (add-text-properties begin opening-end '(invisible t))
6084 (add-text-properties closing-start end '(invisible t)))
6085 t)))))
6087 (defun org-activate-footnote-links (limit)
6088 "Add text properties for footnotes."
6089 (let ((fn (org-footnote-next-reference-or-definition limit)))
6090 (when fn
6091 (let* ((beg (nth 1 fn))
6092 (end (nth 2 fn))
6093 (label (car fn))
6094 (referencep (/= (line-beginning-position) beg)))
6095 (when (and referencep (nth 3 fn))
6096 (save-excursion
6097 (goto-char beg)
6098 (search-forward (or label "fn:"))
6099 (org-remove-flyspell-overlays-in beg (match-end 0))))
6100 (add-text-properties beg end
6101 (list 'mouse-face 'highlight
6102 'keymap org-mouse-map
6103 'help-echo
6104 (if referencep "Footnote reference"
6105 "Footnote definition")
6106 'font-lock-fontified t
6107 'font-lock-multiline t
6108 'face 'org-footnote))))))
6110 (defun org-activate-dates (limit)
6111 "Add text properties for dates."
6112 (when (and (re-search-forward org-tsr-regexp-both limit t)
6113 (not (equal (char-before (match-beginning 0)) 91)))
6114 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6115 (add-text-properties (match-beginning 0) (match-end 0)
6116 (list 'mouse-face 'highlight
6117 'keymap org-mouse-map))
6118 (org-rear-nonsticky-at (match-end 0))
6119 (when org-display-custom-times
6120 ;; If it's a date range, activate custom time for second date.
6121 (when (match-end 3)
6122 (org-display-custom-time (match-beginning 3) (match-end 3)))
6123 (org-display-custom-time (match-beginning 1) (match-end 1)))
6126 (defvar-local org-target-link-regexp nil
6127 "Regular expression matching radio targets in plain text.")
6129 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6130 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6131 border border border))
6132 "Regular expression matching a link target.")
6134 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6135 "Regular expression matching a radio target.")
6137 (defconst org-any-target-regexp
6138 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6139 "Regular expression matching any target.")
6141 (defun org-activate-target-links (limit)
6142 "Add text properties for target matches."
6143 (when org-target-link-regexp
6144 (let ((case-fold-search t))
6145 (when (re-search-forward org-target-link-regexp limit t)
6146 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6147 (add-text-properties (match-beginning 1) (match-end 1)
6148 (list 'mouse-face 'highlight
6149 'keymap org-mouse-map
6150 'help-echo "Radio target link"
6151 'org-linked-text t))
6152 (org-rear-nonsticky-at (match-end 1))
6153 t))))
6155 (defun org-update-radio-target-regexp ()
6156 "Find all radio targets in this file and update the regular expression.
6157 Also refresh fontification if needed."
6158 (interactive)
6159 (let ((old-regexp org-target-link-regexp)
6160 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6161 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6162 (targets
6163 (org-with-wide-buffer
6164 (goto-char (point-min))
6165 (let (rtn)
6166 (while (re-search-forward org-radio-target-regexp nil t)
6167 ;; Make sure point is really within the object.
6168 (backward-char)
6169 (let ((obj (org-element-context)))
6170 (when (eq (org-element-type obj) 'radio-target)
6171 (cl-pushnew (org-element-property :value obj) rtn
6172 :test #'equal))))
6173 rtn))))
6174 (setq org-target-link-regexp
6175 (and targets
6176 (concat before-re
6177 (mapconcat
6178 (lambda (x)
6179 (replace-regexp-in-string
6180 " +" "\\s-+" (regexp-quote x) t t))
6181 targets
6182 "\\|")
6183 after-re)))
6184 (unless (equal old-regexp org-target-link-regexp)
6185 ;; Clean-up cache.
6186 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6187 ((not org-target-link-regexp) old-regexp)
6189 (concat before-re
6190 (mapconcat
6191 (lambda (re)
6192 (substring re (length before-re)
6193 (- (length after-re))))
6194 (list old-regexp org-target-link-regexp)
6195 "\\|")
6196 after-re)))))
6197 (org-with-wide-buffer
6198 (goto-char (point-min))
6199 (while (re-search-forward regexp nil t)
6200 (org-element-cache-refresh (match-beginning 1)))))
6201 ;; Re fontify buffer.
6202 (when (memq 'radio org-highlight-links)
6203 (org-restart-font-lock)))))
6205 (defvar org-latex-and-related-regexp nil
6206 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6208 (defun org-compute-latex-and-related-regexp ()
6209 "Compute regular expression for LaTeX, entities and sub/superscript.
6210 Result depends on variable `org-highlight-latex-and-related'."
6211 (setq-local
6212 org-latex-and-related-regexp
6213 (let* ((re-sub
6214 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6215 ((eq org-use-sub-superscripts '{})
6216 (list org-match-substring-with-braces-regexp))
6217 (org-use-sub-superscripts (list org-match-substring-regexp))))
6218 (re-latex
6219 (when (memq 'latex org-highlight-latex-and-related)
6220 (let ((matchers (plist-get org-format-latex-options :matchers)))
6221 (delq nil
6222 (mapcar (lambda (x)
6223 (and (member (car x) matchers) (nth 1 x)))
6224 org-latex-regexps)))))
6225 (re-entities
6226 (when (memq 'entities org-highlight-latex-and-related)
6227 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6228 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6230 (defun org-do-latex-and-related (limit)
6231 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6232 LIMIT bounds the search for syntax to highlight. Stop at first
6233 highlighted object, if any. Return t if some highlighting was
6234 done, nil otherwise."
6235 (when (org-string-nw-p org-latex-and-related-regexp)
6236 (catch 'found
6237 (while (re-search-forward org-latex-and-related-regexp limit t)
6238 (unless
6239 (cl-some
6240 (lambda (f)
6241 (memq f '(org-code org-verbatim underline org-special-keyword)))
6242 (save-excursion
6243 (goto-char (1+ (match-beginning 0)))
6244 (face-at-point nil t)))
6245 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6246 '(?_ ?^))
6248 0)))
6249 (font-lock-prepend-text-property
6250 (+ offset (match-beginning 0)) (match-end 0)
6251 'face 'org-latex-and-related)
6252 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6253 '(font-lock-multiline t)))
6254 (throw 'found t)))
6255 nil)))
6257 (defun org-restart-font-lock ()
6258 "Restart `font-lock-mode', to force refontification."
6259 (when (and (boundp 'font-lock-mode) font-lock-mode)
6260 (font-lock-mode -1)
6261 (font-lock-mode 1)))
6263 (defun org-activate-tags (limit)
6264 (when (re-search-forward org-tag-line-re limit t)
6265 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6266 (add-text-properties (match-beginning 1) (match-end 1)
6267 (list 'mouse-face 'highlight
6268 'keymap org-mouse-map))
6269 (org-rear-nonsticky-at (match-end 1))
6272 (defun org-outline-level ()
6273 "Compute the outline level of the heading at point.
6275 If this is called at a normal headline, the level is the number
6276 of stars. Use `org-reduced-level' to remove the effect of
6277 `org-odd-levels'. Unlike to `org-current-level', this function
6278 takes into consideration inlinetasks."
6279 (org-with-wide-buffer
6280 (end-of-line)
6281 (if (re-search-backward org-outline-regexp-bol nil t)
6282 (1- (- (match-end 0) (match-beginning 0)))
6283 0)))
6285 (defvar org-font-lock-keywords nil)
6287 (defsubst org-re-property (property &optional literal allow-null value)
6288 "Return a regexp matching a PROPERTY line.
6290 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6291 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6292 non-nil, match properties even without a value.
6294 Match group 3 is set to the value when it exists. If there is no
6295 value and ALLOW-NULL is non-nil, it is set to the empty string.
6297 With optional argument VALUE, match only property lines with
6298 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6299 unless LITERAL is non-nil."
6300 (concat
6301 "^\\(?4:[ \t]*\\)"
6302 (format "\\(?1::\\(?2:%s\\):\\)"
6303 (if literal property (regexp-quote property)))
6304 (cond (value
6305 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6306 (if literal value (regexp-quote value))))
6307 (allow-null
6308 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6310 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6312 (defconst org-property-re
6313 (org-re-property "\\S-+" 'literal t)
6314 "Regular expression matching a property line.
6315 There are four matching groups:
6316 1: :PROPKEY: including the leading and trailing colon,
6317 2: PROPKEY without the leading and trailing colon,
6318 3: PROPVAL without leading or trailing spaces,
6319 4: the indentation of the current line,
6320 5: trailing whitespace.")
6322 (defvar org-font-lock-hook nil
6323 "Functions to be called for special font lock stuff.")
6325 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6327 (defvar org-font-lock-set-keywords-hook nil
6328 "Functions that can manipulate `org-font-lock-extra-keywords'.
6329 This is called after `org-font-lock-extra-keywords' is defined, but before
6330 it is installed to be used by font lock. This can be useful if something
6331 needs to be inserted at a specific position in the font-lock sequence.")
6333 (defun org-font-lock-hook (limit)
6334 "Run `org-font-lock-hook' within LIMIT."
6335 (run-hook-with-args 'org-font-lock-hook limit))
6337 (defun org-set-font-lock-defaults ()
6338 "Set font lock defaults for the current buffer."
6339 (let* ((em org-fontify-emphasized-text)
6340 (lk org-highlight-links)
6341 (org-font-lock-extra-keywords
6342 (list
6343 ;; Call the hook
6344 '(org-font-lock-hook)
6345 ;; Headlines
6346 `(,(if org-fontify-whole-heading-line
6347 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6348 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6349 (1 (org-get-level-face 1))
6350 (2 (org-get-level-face 2))
6351 (3 (org-get-level-face 3)))
6352 ;; Table lines
6353 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6354 (1 'org-table t))
6355 ;; Table internals
6356 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6357 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6358 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6359 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6360 ;; Drawers
6361 '(org-fontify-drawers)
6362 ;; Properties
6363 (list org-property-re
6364 '(1 'org-special-keyword t)
6365 '(3 'org-property-value t))
6366 ;; Link related fontification.
6367 '(org-activate-links)
6368 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6369 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6370 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6371 (when (memq 'footnote lk) '(org-activate-footnote-links))
6372 ;; Targets.
6373 (list org-any-target-regexp '(0 'org-target t))
6374 ;; Diary sexps.
6375 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6376 ;; Macro
6377 '(org-fontify-macros)
6378 ;; TODO keyword
6379 (list (format org-heading-keyword-regexp-format
6380 org-todo-regexp)
6381 '(2 (org-get-todo-face 2) t))
6382 ;; DONE
6383 (if org-fontify-done-headline
6384 (list (format org-heading-keyword-regexp-format
6385 (concat
6386 "\\(?:"
6387 (mapconcat 'regexp-quote org-done-keywords "\\|")
6388 "\\)"))
6389 '(2 'org-headline-done t))
6390 nil)
6391 ;; Priorities
6392 '(org-font-lock-add-priority-faces)
6393 ;; Tags
6394 '(org-font-lock-add-tag-faces)
6395 ;; Tags groups
6396 (when (and org-group-tags org-tag-groups-alist)
6397 (list (concat org-outline-regexp-bol ".+\\(:"
6398 (regexp-opt (mapcar 'car org-tag-groups-alist))
6399 ":\\).*$")
6400 '(1 'org-tag-group prepend)))
6401 ;; Special keywords
6402 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6403 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6404 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6405 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6406 ;; Emphasis
6407 (when em '(org-do-emphasis-faces))
6408 ;; Checkboxes
6409 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6410 1 'org-checkbox prepend)
6411 (when (cdr (assq 'checkbox org-list-automatic-rules))
6412 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6413 (0 (org-get-checkbox-statistics-face) t)))
6414 ;; Description list items
6415 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6416 1 'org-list-dt prepend)
6417 ;; ARCHIVEd headings
6418 (list (concat
6419 org-outline-regexp-bol
6420 "\\(.*:" org-archive-tag ":.*\\)")
6421 '(1 'org-archived prepend))
6422 ;; Specials
6423 '(org-do-latex-and-related)
6424 '(org-fontify-entities)
6425 '(org-raise-scripts)
6426 ;; Code
6427 '(org-activate-code (1 'org-code t))
6428 ;; COMMENT
6429 (list (format
6430 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6431 org-todo-regexp
6432 org-comment-string)
6433 '(9 'org-special-keyword t))
6434 ;; Blocks and meta lines
6435 '(org-fontify-meta-lines-and-blocks))))
6436 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6437 (run-hooks 'org-font-lock-set-keywords-hook)
6438 ;; Now set the full font-lock-keywords
6439 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6440 (setq-local font-lock-defaults
6441 '(org-font-lock-keywords t nil nil backward-paragraph))
6442 (kill-local-variable 'font-lock-keywords)
6443 nil))
6445 (defun org-toggle-pretty-entities ()
6446 "Toggle the composition display of entities as UTF8 characters."
6447 (interactive)
6448 (setq-local org-pretty-entities (not org-pretty-entities))
6449 (org-restart-font-lock)
6450 (if org-pretty-entities
6451 (message "Entities are now displayed as UTF8 characters")
6452 (save-restriction
6453 (widen)
6454 (decompose-region (point-min) (point-max))
6455 (message "Entities are now displayed as plain text"))))
6457 (defvar-local org-custom-properties-overlays nil
6458 "List of overlays used for custom properties.")
6460 (defun org-toggle-custom-properties-visibility ()
6461 "Display or hide properties in `org-custom-properties'."
6462 (interactive)
6463 (if org-custom-properties-overlays
6464 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6465 (setq org-custom-properties-overlays nil))
6466 (when org-custom-properties
6467 (org-with-wide-buffer
6468 (goto-char (point-min))
6469 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6470 (while (re-search-forward regexp nil t)
6471 (let ((end (cdr (save-match-data (org-get-property-block)))))
6472 (when (and end (< (point) end))
6473 ;; Hide first custom property in current drawer.
6474 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6475 (overlay-put o 'invisible t)
6476 (overlay-put o 'org-custom-property t)
6477 (push o org-custom-properties-overlays))
6478 ;; Hide additional custom properties in the same drawer.
6479 (while (re-search-forward regexp end t)
6480 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6481 (overlay-put o 'invisible t)
6482 (overlay-put o 'org-custom-property t)
6483 (push o org-custom-properties-overlays)))))
6484 ;; Each entry is limited to a single property drawer.
6485 (outline-next-heading)))))))
6487 (defun org-fontify-entities (limit)
6488 "Find an entity to fontify."
6489 (let (ee)
6490 (when org-pretty-entities
6491 (catch 'match
6492 ;; "\_ "-family is left out on purpose. Only the first one,
6493 ;; i.e., "\_ ", could be fontified anyway, and it would be
6494 ;; confusing when adding a second white space character.
6495 (while (re-search-forward
6496 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6497 limit t)
6498 (when (and (not (org-at-comment-p))
6499 (setq ee (org-entity-get (match-string 1)))
6500 (= (length (nth 6 ee)) 1))
6501 (let* ((end (if (equal (match-string 2) "{}")
6502 (match-end 2)
6503 (match-end 1))))
6504 (add-text-properties
6505 (match-beginning 0) end
6506 (list 'font-lock-fontified t))
6507 (compose-region (match-beginning 0) end
6508 (nth 6 ee) nil)
6509 (backward-char 1)
6510 (throw 'match t))))
6511 nil))))
6513 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6514 "Fontify string S like in Org mode."
6515 (with-temp-buffer
6516 (insert s)
6517 (let ((org-odd-levels-only odd-levels))
6518 (org-mode)
6519 (org-font-lock-ensure)
6520 (buffer-string))))
6522 (defvar org-m nil)
6523 (defvar org-l nil)
6524 (defvar org-f nil)
6525 (defun org-get-level-face (n)
6526 "Get the right face for match N in font-lock matching of headlines."
6527 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6528 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6529 (if org-cycle-level-faces
6530 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6531 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6532 (cond
6533 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6534 ((eq n 2) org-f)
6535 (t (unless org-level-color-stars-only org-f))))
6537 (defun org-face-from-face-or-color (context inherit face-or-color)
6538 "Create a face list that inherits INHERIT, but sets the foreground color.
6539 When FACE-OR-COLOR is not a string, just return it."
6540 (if (stringp face-or-color)
6541 (list :inherit inherit
6542 (cdr (assoc context org-faces-easy-properties))
6543 face-or-color)
6544 face-or-color))
6546 (defun org-get-todo-face (kwd)
6547 "Get the right face for a TODO keyword KWD.
6548 If KWD is a number, get the corresponding match group."
6549 (when (numberp kwd) (setq kwd (match-string kwd)))
6550 (or (org-face-from-face-or-color
6551 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6552 (and (member kwd org-done-keywords) 'org-done)
6553 'org-todo))
6555 (defun org-get-priority-face (priority)
6556 "Get the right face for PRIORITY.
6557 PRIORITY is a character."
6558 (or (org-face-from-face-or-color
6559 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6560 'org-priority))
6562 (defun org-get-tag-face (tag)
6563 "Get the right face for TAG.
6564 If TAG is a number, get the corresponding match group."
6565 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6566 (or (org-face-from-face-or-color
6567 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6568 'org-tag)))
6570 (defun org-font-lock-add-priority-faces (limit)
6571 "Add the special priority faces."
6572 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6573 (add-text-properties
6574 (match-beginning 1) (match-end 1)
6575 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6576 'font-lock-fontified t))))
6578 (defun org-font-lock-add-tag-faces (limit)
6579 "Add the special tag faces."
6580 (when (and org-tag-faces org-tags-special-faces-re)
6581 (while (re-search-forward org-tags-special-faces-re limit t)
6582 (add-text-properties (match-beginning 1) (match-end 1)
6583 (list 'face (org-get-tag-face 1)
6584 'font-lock-fontified t))
6585 (backward-char 1))))
6587 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6588 "Remove fontification and activation overlays from links."
6589 (font-lock-default-unfontify-region beg end)
6590 (let* ((buffer-undo-list t)
6591 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6592 (inhibit-modification-hooks t)
6593 deactivate-mark buffer-file-name buffer-file-truename)
6594 (decompose-region beg end)
6595 (remove-text-properties beg end
6596 '(mouse-face t keymap t org-linked-text t
6597 invisible t intangible t
6598 org-emphasis t))
6599 (org-remove-font-lock-display-properties beg end)))
6601 (defconst org-script-display '(((raise -0.3) (height 0.7))
6602 ((raise 0.3) (height 0.7))
6603 ((raise -0.5))
6604 ((raise 0.5)))
6605 "Display properties for showing superscripts and subscripts.")
6607 (defun org-remove-font-lock-display-properties (beg end)
6608 "Remove specific display properties that have been added by font lock.
6609 The will remove the raise properties that are used to show superscripts
6610 and subscripts."
6611 (let (next prop)
6612 (while (< beg end)
6613 (setq next (next-single-property-change beg 'display nil end)
6614 prop (get-text-property beg 'display))
6615 (when (member prop org-script-display)
6616 (put-text-property beg next 'display nil))
6617 (setq beg next))))
6619 (defun org-raise-scripts (limit)
6620 "Add raise properties to sub/superscripts."
6621 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6622 (re-search-forward
6623 (if (eq org-use-sub-superscripts t)
6624 org-match-substring-regexp
6625 org-match-substring-with-braces-regexp)
6626 limit t))
6627 (let* ((pos (point)) table-p comment-p
6628 (mpos (match-beginning 3))
6629 (emph-p (get-text-property mpos 'org-emphasis))
6630 (link-p (get-text-property mpos 'mouse-face))
6631 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6632 (goto-char (point-at-bol))
6633 (setq table-p (looking-at-p org-table-dataline-regexp)
6634 comment-p (looking-at-p "^[ \t]*#[ +]"))
6635 (goto-char pos)
6636 ;; Handle a_b^c
6637 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6638 (unless (or comment-p emph-p link-p keyw-p)
6639 (put-text-property (match-beginning 3) (match-end 0)
6640 'display
6641 (if (equal (char-after (match-beginning 2)) ?^)
6642 (nth (if table-p 3 1) org-script-display)
6643 (nth (if table-p 2 0) org-script-display)))
6644 (add-text-properties (match-beginning 2) (match-end 2)
6645 (list 'invisible t))
6646 (when (and (eq (char-after (match-beginning 3)) ?{)
6647 (eq (char-before (match-end 3)) ?}))
6648 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6649 (list 'invisible t))
6650 (add-text-properties (1- (match-end 3)) (match-end 3)
6651 (list 'invisible t))))
6652 t)))
6654 (defun org-remove-empty-overlays-at (pos)
6655 "Remove outline overlays that do not contain non-white stuff."
6656 (dolist (o (overlays-at pos))
6657 (and (eq 'outline (overlay-get o 'invisible))
6658 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6659 (overlay-end o))))
6660 (delete-overlay o))))
6662 (defun org-show-empty-lines-in-parent ()
6663 "Move to the parent and re-show empty lines before visible headlines."
6664 (save-excursion
6665 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6666 (org-cycle-show-empty-lines context))))
6668 (defun org-files-list ()
6669 "Return `org-agenda-files' list, plus all open Org files.
6670 This is useful for operations that need to scan all of a user's
6671 open and agenda-wise Org files."
6672 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6673 (dolist (buf (buffer-list))
6674 (with-current-buffer buf
6675 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6676 (cl-pushnew (expand-file-name (buffer-file-name)) files
6677 :test #'equal))))
6678 files))
6680 (defsubst org-entry-beginning-position ()
6681 "Return the beginning position of the current entry."
6682 (save-excursion (org-back-to-heading t) (point)))
6684 (defsubst org-entry-end-position ()
6685 "Return the end position of the current entry."
6686 (save-excursion (outline-next-heading) (point)))
6688 (defun org-subtree-end-visible-p ()
6689 "Is the end of the current subtree visible?"
6690 (pos-visible-in-window-p
6691 (save-excursion (org-end-of-subtree t) (point))))
6693 (defun org-first-headline-recenter ()
6694 "Move cursor to the first headline and recenter the headline."
6695 (let ((window (get-buffer-window)))
6696 (when window
6697 (goto-char (point-min))
6698 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6699 (set-window-start window (line-beginning-position))))))
6702 ;;; Visibility (headlines, blocks, drawers)
6704 ;;;; Headlines visibility
6706 (defun org-show-entry ()
6707 "Show the body directly following this heading.
6708 Show the heading too, if it is currently invisible."
6709 (interactive)
6710 (save-excursion
6711 (ignore-errors
6712 (org-back-to-heading t)
6713 (org-flag-region
6714 (line-end-position 0)
6715 (save-excursion
6716 (if (re-search-forward
6717 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6718 (match-beginning 1)
6719 (point-max)))
6721 'outline))))
6723 (defun org-show-children (&optional level)
6724 "Show all direct subheadings of this heading.
6725 Prefix arg LEVEL is how many levels below the current level
6726 should be shown. Default is enough to cause the following
6727 heading to appear."
6728 (interactive "p")
6729 (save-excursion
6730 (org-back-to-heading t)
6731 (let* ((current-level (funcall outline-level))
6732 (max-level (org-get-valid-level
6733 current-level
6734 (if level (prefix-numeric-value level) 1)))
6735 (end (save-excursion (org-end-of-subtree t t)))
6736 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6737 (past-first-child nil)
6738 ;; Make sure to skip inlinetasks.
6739 (re (format regexp-fmt
6740 current-level
6741 (cond
6742 ((not (featurep 'org-inlinetask)) "")
6743 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6745 (t (1- org-inlinetask-min-level))))))
6746 ;; Display parent heading.
6747 (org-flag-heading nil)
6748 (forward-line)
6749 ;; Display children. First child may be deeper than expected
6750 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6751 ;; MAX-LEVEL accordingly.
6752 (while (re-search-forward re end t)
6753 (unless past-first-child
6754 (setq re (format regexp-fmt
6755 current-level
6756 (max (funcall outline-level) max-level)))
6757 (setq past-first-child t))
6758 (org-flag-heading nil)))))
6760 (defun org-show-subtree ()
6761 "Show everything after this heading at deeper levels."
6762 (interactive)
6763 (org-flag-region
6764 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6766 ;;;; Blocks visibility
6768 (defun org-hide-block-toggle-maybe ()
6769 "Toggle visibility of block at point.
6770 Unlike to `org-hide-block-toggle', this function does not throw
6771 an error. Return a non-nil value when toggling is successful."
6772 (interactive)
6773 (ignore-errors (org-hide-block-toggle)))
6775 (defun org-hide-block-toggle (&optional force)
6776 "Toggle the visibility of the current block.
6777 When optional argument FORCE is `off', make block visible. If it
6778 is non-nil, hide it unconditionally. Throw an error when not at
6779 a block. Return a non-nil value when toggling is successful."
6780 (interactive)
6781 (let ((element (org-element-at-point)))
6782 (unless (memq (org-element-type element)
6783 '(center-block comment-block dynamic-block example-block
6784 export-block quote-block special-block
6785 src-block verse-block))
6786 (user-error "Not at a block"))
6787 (let* ((post (org-element-property :post-affiliated element))
6788 (start (save-excursion
6789 (goto-char post)
6790 (line-end-position)))
6791 (end (save-excursion
6792 (goto-char (org-element-property :end element))
6793 (skip-chars-backward " \t\n")
6794 (line-end-position))))
6795 ;; Do nothing when not before or at the block opening line or at
6796 ;; the block closing line.
6797 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6798 (cond ((eq force 'off)
6799 (org-flag-region start end nil 'org-hide-block))
6800 (force
6801 (org-flag-region start end t 'org-hide-block))
6802 ((eq (get-char-property start 'invisible) 'org-hide-block)
6803 (org-flag-region start end nil 'org-hide-block))
6805 (org-flag-region start end t 'org-hide-block)))
6806 ;; When the block is hidden away, make sure point is left in
6807 ;; a visible part of the buffer.
6808 (when (invisible-p (max (1- (point)) (point-min)))
6809 (goto-char post))
6810 ;; Signal success.
6811 t))))
6813 (defun org-hide-block-toggle-all ()
6814 "Toggle the visibility of all blocks in the current buffer."
6815 (org-block-map 'org-hide-block-toggle))
6817 (defun org-hide-block-all ()
6818 "Fold all blocks in the current buffer."
6819 (interactive)
6820 (org-show-all '(blocks))
6821 (org-block-map 'org-hide-block-toggle-maybe))
6823 ;;;; Drawers visibility
6825 (defun org-cycle-hide-drawers (state &optional exceptions)
6826 "Re-hide all drawers after a visibility state change.
6827 STATE should be one of the symbols listed in the docstring of
6828 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6829 a list of strings specifying which drawers should not be hidden."
6830 (when (and (derived-mode-p 'org-mode)
6831 (not (memq state '(overview folded contents))))
6832 (save-excursion
6833 (let* ((globalp (eq state 'all))
6834 (beg (if globalp (point-min) (point)))
6835 (end (if globalp (point-max)
6836 (if (eq state 'children)
6837 (save-excursion (outline-next-heading) (point))
6838 (org-end-of-subtree t)))))
6839 (goto-char beg)
6840 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6841 (unless (member-ignore-case (match-string 1) exceptions)
6842 (let ((drawer (org-element-at-point)))
6843 (when (memq (org-element-type drawer) '(drawer property-drawer))
6844 (org-flag-drawer t drawer)
6845 ;; Make sure to skip drawer entirely or we might flag
6846 ;; it another time when matching its ending line with
6847 ;; `org-drawer-regexp'.
6848 (goto-char (org-element-property :end drawer))))))))))
6850 (defun org-flag-drawer (flag &optional element)
6851 "When FLAG is non-nil, hide the drawer we are at.
6852 Otherwise make it visible. When optional argument ELEMENT is
6853 a parsed drawer, as returned by `org-element-at-point', hide or
6854 show that drawer instead."
6855 (let ((drawer (or element
6856 (and (save-excursion
6857 (beginning-of-line)
6858 (looking-at-p org-drawer-regexp))
6859 (org-element-at-point)))))
6860 (when (memq (org-element-type drawer) '(drawer property-drawer))
6861 (let ((post (org-element-property :post-affiliated drawer)))
6862 (org-flag-region
6863 (save-excursion (goto-char post) (line-end-position))
6864 (save-excursion (goto-char (org-element-property :end drawer))
6865 (skip-chars-backward " \t\n")
6866 (line-end-position))
6867 flag 'org-hide-drawer)
6868 ;; When the drawer is hidden away, make sure point lies in
6869 ;; a visible part of the buffer.
6870 (when (invisible-p (max (1- (point)) (point-min)))
6871 (goto-char post))))))
6873 ;;;; Visibility cycling
6875 (defvar-local org-cycle-global-status nil)
6876 (put 'org-cycle-global-status 'org-state t)
6877 (defvar-local org-cycle-subtree-status nil)
6878 (put 'org-cycle-subtree-status 'org-state t)
6880 (defun org-show-all (&optional types)
6881 "Show all contents in the visible part of the buffer.
6882 By default, the function expands headings, blocks and drawers.
6883 When optional argument TYPE is a list of symbols among `blocks',
6884 `drawers' and `headings', to only expand one specific type."
6885 (dolist (type (or types '(blocks drawers headings)))
6886 (org-flag-region (point-min) (point-max) nil
6887 (pcase type
6888 (`blocks 'org-hide-block)
6889 (`drawers 'org-hide-drawer)
6890 (`headings 'outline)
6891 (_ (error "Invalid type: %S" type))))))
6893 ;;;###autoload
6894 (defun org-cycle (&optional arg)
6895 "TAB-action and visibility cycling for Org mode.
6897 This is the command invoked in Org mode by the `TAB' key. Its main
6898 purpose is outline visibility cycling, but it also invokes other actions
6899 in special contexts.
6901 When this function is called with a `\\[universal-argument]' prefix, rotate \
6902 the entire
6903 buffer through 3 states (global cycling)
6904 1. OVERVIEW: Show only top-level headlines.
6905 2. CONTENTS: Show all headlines of all levels, but no body text.
6906 3. SHOW ALL: Show everything.
6908 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6909 switch to the startup visibility,
6910 determined by the variable `org-startup-folded', and by any VISIBILITY
6911 properties in the buffer.
6913 With a `\\[universal-argument] \\[universal-argument] \
6914 \\[universal-argument]' prefix argument, show the entire buffer, including
6915 any drawers.
6917 When inside a table, re-align the table and move to the next field.
6919 When point is at the beginning of a headline, rotate the subtree started
6920 by this line through 3 different states (local cycling)
6921 1. FOLDED: Only the main headline is shown.
6922 2. CHILDREN: The main headline and the direct children are shown.
6923 From this state, you can move to one of the children
6924 and zoom in further.
6925 3. SUBTREE: Show the entire subtree, including body text.
6926 If there is no subtree, switch directly from CHILDREN to FOLDED.
6928 When point is at the beginning of an empty headline and the variable
6929 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6930 of the headline by demoting and promoting it to likely levels. This
6931 speeds up creation document structure by pressing `TAB' once or several
6932 times right after creating a new headline.
6934 When there is a numeric prefix, go up to a heading with level ARG, do
6935 a `show-subtree' and return to the previous cursor position. If ARG
6936 is negative, go up that many levels.
6938 When point is not at the beginning of a headline, execute the global
6939 binding for `TAB', which is re-indenting the line. See the option
6940 `org-cycle-emulate-tab' for details.
6942 As a special case, if point is at the beginning of the buffer and there is
6943 no headline in line 1, this function will act as if called with prefix arg
6944 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6945 prefix arg, but only
6946 if the variable `org-cycle-global-at-bob' is t."
6947 (interactive "P")
6948 (org-load-modules-maybe)
6949 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6950 (and org-cycle-level-after-item/entry-creation
6951 (or (org-cycle-level)
6952 (org-cycle-item-indentation))))
6953 (let* ((limit-level
6954 (or org-cycle-max-level
6955 (and (boundp 'org-inlinetask-min-level)
6956 org-inlinetask-min-level
6957 (1- org-inlinetask-min-level))))
6958 (nstars (and limit-level
6959 (if org-odd-levels-only
6960 (and limit-level (1- (* limit-level 2)))
6961 limit-level)))
6962 (org-outline-regexp
6963 (if (not (derived-mode-p 'org-mode))
6964 outline-regexp
6965 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6966 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6967 (not (looking-at org-outline-regexp))))
6968 (org-cycle-hook
6969 (if bob-special
6970 (delq 'org-optimize-window-after-visibility-change
6971 (copy-sequence org-cycle-hook))
6972 org-cycle-hook))
6973 (pos (point)))
6975 (cond
6977 ((equal arg '(16))
6978 (setq last-command 'dummy)
6979 (org-set-startup-visibility)
6980 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6982 ((equal arg '(64))
6983 (org-show-all)
6984 (org-unlogged-message "Entire buffer visible, including drawers"))
6986 ((equal arg '(4)) (org-cycle-internal-global))
6988 ;; Try hiding block at point.
6989 ((org-hide-block-toggle-maybe))
6991 ;; Try cdlatex TAB completion
6992 ((org-try-cdlatex-tab))
6994 ;; Table: enter it or move to the next field.
6995 ((org-at-table-p 'any)
6996 (if (org-at-table.el-p)
6997 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6998 Use `\\[org-edit-special]' to edit table.el tables"))
6999 (if arg (org-table-edit-field t)
7000 (org-table-justify-field-maybe)
7001 (call-interactively 'org-table-next-field))))
7003 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
7005 ;; Global cycling: delegate to `org-cycle-internal-global'.
7006 (bob-special (org-cycle-internal-global))
7008 ;; Drawers: delegate to `org-flag-drawer'.
7009 ((save-excursion
7010 (beginning-of-line 1)
7011 (looking-at org-drawer-regexp))
7012 (org-flag-drawer ; toggle block visibility
7013 (not (get-char-property (match-end 0) 'invisible))))
7015 ;; Show-subtree, ARG levels up from here.
7016 ((integerp arg)
7017 (save-excursion
7018 (org-back-to-heading)
7019 (outline-up-heading (if (< arg 0) (- arg)
7020 (- (funcall outline-level) arg)))
7021 (org-show-subtree)))
7023 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
7024 ((and (featurep 'org-inlinetask)
7025 (org-inlinetask-at-task-p)
7026 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7027 (org-inlinetask-toggle-visibility))
7029 ;; At an item/headline: delegate to `org-cycle-internal-local'.
7030 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
7031 (save-excursion (move-beginning-of-line 1)
7032 (looking-at org-outline-regexp)))
7033 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7034 (org-cycle-internal-local))
7036 ;; From there: TAB emulation and template completion.
7037 (buffer-read-only (org-back-to-heading))
7039 ((run-hook-with-args-until-success
7040 'org-tab-after-check-for-cycling-hook))
7042 ((run-hook-with-args-until-success
7043 'org-tab-before-tab-emulation-hook))
7045 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7046 (or (not (bolp))
7047 (not (looking-at org-outline-regexp))))
7048 (call-interactively (global-key-binding "\t")))
7050 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7051 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7052 (or (and (eq org-cycle-emulate-tab 'white)
7053 (= (match-end 0) (point-at-eol)))
7054 (and (eq org-cycle-emulate-tab 'whitestart)
7055 (>= (match-end 0) pos))))
7057 (eq org-cycle-emulate-tab t))
7058 (call-interactively (global-key-binding "\t")))
7060 (t (save-excursion
7061 (org-back-to-heading)
7062 (org-cycle)))))))
7064 (defun org-cycle-internal-global ()
7065 "Do the global cycling action."
7066 ;; Hack to avoid display of messages for .org attachments in Gnus
7067 (let ((ga (string-match "\\*fontification" (buffer-name))))
7068 (cond
7069 ((and (eq last-command this-command)
7070 (eq org-cycle-global-status 'overview))
7071 ;; We just created the overview - now do table of contents
7072 ;; This can be slow in very large buffers, so indicate action
7073 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7074 (unless ga (org-unlogged-message "CONTENTS..."))
7075 (org-content)
7076 (unless ga (org-unlogged-message "CONTENTS...done"))
7077 (setq org-cycle-global-status 'contents)
7078 (run-hook-with-args 'org-cycle-hook 'contents))
7080 ((and (eq last-command this-command)
7081 (eq org-cycle-global-status 'contents))
7082 ;; We just showed the table of contents - now show everything
7083 (run-hook-with-args 'org-pre-cycle-hook 'all)
7084 (org-show-all '(headings blocks))
7085 (unless ga (org-unlogged-message "SHOW ALL"))
7086 (setq org-cycle-global-status 'all)
7087 (run-hook-with-args 'org-cycle-hook 'all))
7090 ;; Default action: go to overview
7091 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7092 (org-overview)
7093 (unless ga (org-unlogged-message "OVERVIEW"))
7094 (setq org-cycle-global-status 'overview)
7095 (run-hook-with-args 'org-cycle-hook 'overview)))))
7097 (defvar org-called-with-limited-levels nil
7098 "Non-nil when `org-with-limited-levels' is currently active.")
7100 (defun org-cycle-internal-local ()
7101 "Do the local cycling action."
7102 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7103 ;; First, determine end of headline (EOH), end of subtree or item
7104 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7105 (save-excursion
7106 (if (org-at-item-p)
7107 (progn
7108 (beginning-of-line)
7109 (setq struct (org-list-struct))
7110 (setq eoh (point-at-eol))
7111 (setq eos (org-list-get-item-end-before-blank (point) struct))
7112 (setq has-children (org-list-has-child-p (point) struct)))
7113 (org-back-to-heading)
7114 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7115 (setq eos (save-excursion (org-end-of-subtree t t)
7116 (when (bolp) (backward-char)) (point)))
7117 (setq has-children
7118 (or (save-excursion
7119 (let ((level (funcall outline-level)))
7120 (outline-next-heading)
7121 (and (org-at-heading-p t)
7122 (> (funcall outline-level) level))))
7123 (save-excursion
7124 (org-list-search-forward (org-item-beginning-re) eos t)))))
7125 ;; Determine end invisible part of buffer (EOL)
7126 (beginning-of-line 2)
7127 (while (and (not (eobp)) ;This is like `next-line'.
7128 (get-char-property (1- (point)) 'invisible))
7129 (goto-char (next-single-char-property-change (point) 'invisible))
7130 (and (eolp) (beginning-of-line 2)))
7131 (setq eol (point)))
7132 ;; Find out what to do next and set `this-command'
7133 (cond
7134 ((= eos eoh)
7135 ;; Nothing is hidden behind this heading
7136 (unless (org-before-first-heading-p)
7137 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7138 (org-unlogged-message "EMPTY ENTRY")
7139 (setq org-cycle-subtree-status nil)
7140 (save-excursion
7141 (goto-char eos)
7142 (outline-next-heading)
7143 (when (org-invisible-p) (org-flag-heading nil))))
7144 ((and (or (>= eol eos)
7145 (not (string-match "\\S-" (buffer-substring eol eos))))
7146 (or has-children
7147 (not (setq children-skipped
7148 org-cycle-skip-children-state-if-no-children))))
7149 ;; Entire subtree is hidden in one line: children view
7150 (unless (org-before-first-heading-p)
7151 (run-hook-with-args 'org-pre-cycle-hook 'children))
7152 (if (org-at-item-p)
7153 (org-list-set-item-visibility (point-at-bol) struct 'children)
7154 (org-show-entry)
7155 (org-with-limited-levels (org-show-children))
7156 (org-show-set-visibility 'canonical)
7157 ;; Fold every list in subtree to top-level items.
7158 (when (eq org-cycle-include-plain-lists 'integrate)
7159 (save-excursion
7160 (org-back-to-heading)
7161 (while (org-list-search-forward (org-item-beginning-re) eos t)
7162 (beginning-of-line 1)
7163 (let* ((struct (org-list-struct))
7164 (prevs (org-list-prevs-alist struct))
7165 (end (org-list-get-bottom-point struct)))
7166 (dolist (e (org-list-get-all-items (point) struct prevs))
7167 (org-list-set-item-visibility e struct 'folded))
7168 (goto-char (if (< end eos) end eos)))))))
7169 (org-unlogged-message "CHILDREN")
7170 (save-excursion
7171 (goto-char eos)
7172 (outline-next-heading)
7173 (when (org-invisible-p) (org-flag-heading nil)))
7174 (setq org-cycle-subtree-status 'children)
7175 (unless (org-before-first-heading-p)
7176 (run-hook-with-args 'org-cycle-hook 'children)))
7177 ((or children-skipped
7178 (and (eq last-command this-command)
7179 (eq org-cycle-subtree-status 'children)))
7180 ;; We just showed the children, or no children are there,
7181 ;; now show everything.
7182 (unless (org-before-first-heading-p)
7183 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7184 (org-flag-region eoh eos nil 'outline)
7185 (org-unlogged-message
7186 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7187 (setq org-cycle-subtree-status 'subtree)
7188 (unless (org-before-first-heading-p)
7189 (run-hook-with-args 'org-cycle-hook 'subtree)))
7191 ;; Default action: hide the subtree.
7192 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7193 (org-flag-region eoh eos t 'outline)
7194 (org-unlogged-message "FOLDED")
7195 (setq org-cycle-subtree-status 'folded)
7196 (unless (org-before-first-heading-p)
7197 (run-hook-with-args 'org-cycle-hook 'folded))))))
7199 ;;;###autoload
7200 (defun org-global-cycle (&optional arg)
7201 "Cycle the global visibility. For details see `org-cycle'.
7202 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7203 With a numeric prefix, show all headlines up to that level."
7204 (interactive "P")
7205 (let ((org-cycle-include-plain-lists
7206 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7207 (cond
7208 ((integerp arg)
7209 (org-show-all '(headings blocks))
7210 (outline-hide-sublevels arg)
7211 (setq org-cycle-global-status 'contents))
7212 ((equal arg '(4))
7213 (org-set-startup-visibility)
7214 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7216 (org-cycle '(4))))))
7218 (defun org-set-startup-visibility ()
7219 "Set the visibility required by startup options and properties."
7220 (cond
7221 ((eq org-startup-folded t)
7222 (org-overview))
7223 ((eq org-startup-folded 'content)
7224 (org-content))
7225 ((or (eq org-startup-folded 'showeverything)
7226 (eq org-startup-folded nil))
7227 (org-show-all)))
7228 (unless (eq org-startup-folded 'showeverything)
7229 (when org-hide-block-startup (org-hide-block-all))
7230 (org-set-visibility-according-to-property)
7231 (org-cycle-hide-archived-subtrees 'all)
7232 (org-cycle-hide-drawers 'all)
7233 (org-cycle-show-empty-lines t)))
7235 (defun org-set-visibility-according-to-property ()
7236 "Switch subtree visibilities according to :VISIBILITY: property."
7237 (interactive)
7238 (org-with-wide-buffer
7239 (goto-char (point-min))
7240 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7241 (if (not (org-at-property-p)) (outline-next-heading)
7242 (let ((state (match-string 3)))
7243 (save-excursion
7244 (org-back-to-heading t)
7245 (outline-hide-subtree)
7246 (org-reveal)
7247 (cond
7248 ((equal state "folded")
7249 (outline-hide-subtree))
7250 ((equal state "children")
7251 (org-show-hidden-entry)
7252 (org-show-children))
7253 ((equal state "content")
7254 (save-excursion
7255 (save-restriction
7256 (org-narrow-to-subtree)
7257 (org-content))))
7258 ((member state '("all" "showall"))
7259 (outline-show-subtree)))))))))
7261 (defun org-overview ()
7262 "Switch to overview mode, showing only top-level headlines.
7263 This shows all headlines with a level equal or greater than the level
7264 of the first headline in the buffer. This is important, because if the
7265 first headline is not level one, then (hide-sublevels 1) gives confusing
7266 results."
7267 (interactive)
7268 (save-excursion
7269 (let ((level
7270 (save-excursion
7271 (goto-char (point-min))
7272 (when (re-search-forward org-outline-regexp-bol nil t)
7273 (goto-char (match-beginning 0))
7274 (funcall outline-level)))))
7275 (and level (outline-hide-sublevels level)))))
7277 (defun org-content (&optional arg)
7278 "Show all headlines in the buffer, like a table of contents.
7279 With numerical argument N, show content up to level N."
7280 (interactive "P")
7281 (org-overview)
7282 (save-excursion
7283 ;; Visit all headings and show their offspring
7284 (and (integerp arg) (org-overview))
7285 (goto-char (point-max))
7286 (catch 'exit
7287 (while (and (progn (condition-case nil
7288 (outline-previous-visible-heading 1)
7289 (error (goto-char (point-min))))
7291 (looking-at org-outline-regexp))
7292 (if (integerp arg)
7293 (org-show-children (1- arg))
7294 (outline-show-branches))
7295 (when (bobp) (throw 'exit nil))))))
7297 (defun org-optimize-window-after-visibility-change (state)
7298 "Adjust the window after a change in outline visibility.
7299 This function is the default value of the hook `org-cycle-hook'."
7300 (when (get-buffer-window (current-buffer))
7301 (cond
7302 ((eq state 'content) nil)
7303 ((eq state 'all) nil)
7304 ((eq state 'folded) nil)
7305 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7306 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7308 (defun org-clean-visibility-after-subtree-move ()
7309 "Fix visibility issues after moving a subtree."
7310 ;; First, find a reasonable region to look at:
7311 ;; Start two siblings above, end three below
7312 (let* ((beg (save-excursion
7313 (and (org-get-last-sibling)
7314 (org-get-last-sibling))
7315 (point)))
7316 (end (save-excursion
7317 (and (org-get-next-sibling)
7318 (org-get-next-sibling)
7319 (org-get-next-sibling))
7320 (if (org-at-heading-p)
7321 (point-at-eol)
7322 (point))))
7323 (level (looking-at "\\*+"))
7324 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7325 (save-excursion
7326 (save-restriction
7327 (narrow-to-region beg end)
7328 (when re
7329 ;; Properly fold already folded siblings
7330 (goto-char (point-min))
7331 (while (re-search-forward re nil t)
7332 (when (and (not (org-invisible-p))
7333 (org-invisible-p (line-end-position)))
7334 (outline-hide-entry))))
7335 (org-cycle-hide-drawers 'all)
7336 (org-cycle-show-empty-lines 'overview)))))
7338 (defun org-cycle-show-empty-lines (state)
7339 "Show empty lines above all visible headlines.
7340 The region to be covered depends on STATE when called through
7341 `org-cycle-hook'. Lisp program can use t for STATE to get the
7342 entire buffer covered. Note that an empty line is only shown if there
7343 are at least `org-cycle-separator-lines' empty lines before the headline."
7344 (when (/= org-cycle-separator-lines 0)
7345 (save-excursion
7346 (let* ((n (abs org-cycle-separator-lines))
7347 (re (cond
7348 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7349 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7350 (t (let ((ns (number-to-string (- n 2))))
7351 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7352 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7353 beg end)
7354 (cond
7355 ((memq state '(overview contents t))
7356 (setq beg (point-min) end (point-max)))
7357 ((memq state '(children folded))
7358 (setq beg (point)
7359 end (progn (org-end-of-subtree t t)
7360 (line-beginning-position 2)))))
7361 (when beg
7362 (goto-char beg)
7363 (while (re-search-forward re end t)
7364 (unless (get-char-property (match-end 1) 'invisible)
7365 (let ((e (match-end 1))
7366 (b (if (>= org-cycle-separator-lines 0)
7367 (match-beginning 1)
7368 (save-excursion
7369 (goto-char (match-beginning 0))
7370 (skip-chars-backward " \t\n")
7371 (line-end-position)))))
7372 (org-flag-region b e nil 'outline))))))))
7373 ;; Never hide empty lines at the end of the file.
7374 (save-excursion
7375 (goto-char (point-max))
7376 (outline-previous-heading)
7377 (outline-end-of-heading)
7378 (when (and (looking-at "[ \t\n]+")
7379 (= (match-end 0) (point-max)))
7380 (org-flag-region (point) (match-end 0) nil 'outline))))
7382 ;;;; Reveal point location
7384 (defun org-show-context (&optional key)
7385 "Make sure point and context are visible.
7386 Optional argument KEY, when non-nil, is a symbol. See
7387 `org-show-context-detail' for allowed values and how much is to
7388 be shown."
7389 (org-show-set-visibility
7390 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7391 ((cdr (assq key org-show-context-detail)))
7392 (t (cdr (assq 'default org-show-context-detail))))))
7394 (defun org-show-set-visibility (detail)
7395 "Set visibility around point according to DETAIL.
7396 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7397 `tree', `canonical' or t. See `org-show-context-detail' for more
7398 information."
7399 ;; Show current heading and possibly its entry, following headline
7400 ;; or all children.
7401 (if (and (org-at-heading-p) (not (eq detail 'local)))
7402 (org-flag-heading nil)
7403 (org-show-entry)
7404 ;; If point is hidden within a drawer or a block, make sure to
7405 ;; expose it.
7406 (dolist (o (overlays-at (point)))
7407 (when (memq (overlay-get o 'invisible)
7408 '(org-hide-block org-hide-drawer outline))
7409 (delete-overlay o)))
7410 (unless (org-before-first-heading-p)
7411 (org-with-limited-levels
7412 (cl-case detail
7413 ((tree canonical t) (org-show-children))
7414 ((nil minimal ancestors))
7415 (t (save-excursion
7416 (outline-next-heading)
7417 (org-flag-heading nil)))))))
7418 ;; Show all siblings.
7419 (when (eq detail 'lineage) (org-show-siblings))
7420 ;; Show ancestors, possibly with their children.
7421 (when (memq detail '(ancestors lineage tree canonical t))
7422 (save-excursion
7423 (while (org-up-heading-safe)
7424 (org-flag-heading nil)
7425 (when (memq detail '(canonical t)) (org-show-entry))
7426 (when (memq detail '(tree canonical t)) (org-show-children))))))
7428 (defvar org-reveal-start-hook nil
7429 "Hook run before revealing a location.")
7431 (defun org-reveal (&optional siblings)
7432 "Show current entry, hierarchy above it, and the following headline.
7434 This can be used to show a consistent set of context around
7435 locations exposed with `org-show-context'.
7437 With optional argument SIBLINGS, on each level of the hierarchy all
7438 siblings are shown. This repairs the tree structure to what it would
7439 look like when opened with hierarchical calls to `org-cycle'.
7441 With a \\[universal-argument] \\[universal-argument] prefix, \
7442 go to the parent and show the entire tree."
7443 (interactive "P")
7444 (run-hooks 'org-reveal-start-hook)
7445 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7446 ((equal siblings '(16))
7447 (save-excursion
7448 (when (org-up-heading-safe)
7449 (org-show-subtree)
7450 (run-hook-with-args 'org-cycle-hook 'subtree))))
7451 (t (org-show-set-visibility 'lineage))))
7454 ;;; Indirect buffer display of subtrees
7456 (defvar org-indirect-dedicated-frame nil
7457 "This is the frame being used for indirect tree display.")
7458 (defvar org-last-indirect-buffer nil)
7460 (defun org-tree-to-indirect-buffer (&optional arg)
7461 "Create indirect buffer and narrow it to current subtree.
7463 With a numerical prefix ARG, go up to this level and then take that tree.
7464 If ARG is negative, go up that many levels.
7466 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7467 indirect buffer previously made with this command, to avoid proliferation of
7468 indirect buffers. However, when you call the command with a \
7469 `\\[universal-argument]' prefix, or
7470 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7471 so that you can work with several indirect buffers at the same time. If
7472 `org-indirect-buffer-display' is `dedicated-frame', the \
7473 `\\[universal-argument]' prefix also
7474 requests that a new frame be made for the new buffer, so that the dedicated
7475 frame is not changed."
7476 (interactive "P")
7477 (let ((cbuf (current-buffer))
7478 (cwin (selected-window))
7479 (pos (point))
7480 beg end level heading ibuf)
7481 (save-excursion
7482 (org-back-to-heading t)
7483 (when (numberp arg)
7484 (setq level (org-outline-level))
7485 (when (< arg 0) (setq arg (+ level arg)))
7486 (while (> (setq level (org-outline-level)) arg)
7487 (org-up-heading-safe)))
7488 (setq beg (point)
7489 heading (org-get-heading 'no-tags))
7490 (org-end-of-subtree t t)
7491 (when (org-at-heading-p) (backward-char 1))
7492 (setq end (point)))
7493 (when (and (buffer-live-p org-last-indirect-buffer)
7494 (not (eq org-indirect-buffer-display 'new-frame))
7495 (not arg))
7496 (kill-buffer org-last-indirect-buffer))
7497 (setq ibuf (org-get-indirect-buffer cbuf heading)
7498 org-last-indirect-buffer ibuf)
7499 (cond
7500 ((or (eq org-indirect-buffer-display 'new-frame)
7501 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7502 (select-frame (make-frame))
7503 (delete-other-windows)
7504 (pop-to-buffer-same-window ibuf)
7505 (org-set-frame-title heading))
7506 ((eq org-indirect-buffer-display 'dedicated-frame)
7507 (raise-frame
7508 (select-frame (or (and org-indirect-dedicated-frame
7509 (frame-live-p org-indirect-dedicated-frame)
7510 org-indirect-dedicated-frame)
7511 (setq org-indirect-dedicated-frame (make-frame)))))
7512 (delete-other-windows)
7513 (pop-to-buffer-same-window ibuf)
7514 (org-set-frame-title (concat "Indirect: " heading)))
7515 ((eq org-indirect-buffer-display 'current-window)
7516 (pop-to-buffer-same-window ibuf))
7517 ((eq org-indirect-buffer-display 'other-window)
7518 (pop-to-buffer ibuf))
7519 (t (error "Invalid value")))
7520 (narrow-to-region beg end)
7521 (org-show-all '(headings blocks))
7522 (goto-char pos)
7523 (run-hook-with-args 'org-cycle-hook 'all)
7524 (and (window-live-p cwin) (select-window cwin))))
7526 (defun org-get-indirect-buffer (&optional buffer heading)
7527 (setq buffer (or buffer (current-buffer)))
7528 (let ((n 1) (base (buffer-name buffer)) bname)
7529 (while (buffer-live-p
7530 (get-buffer
7531 (setq bname
7532 (concat base "-"
7533 (if heading (concat heading "-" (number-to-string n))
7534 (number-to-string n))))))
7535 (setq n (1+ n)))
7536 (condition-case nil
7537 (make-indirect-buffer buffer bname 'clone)
7538 (error (make-indirect-buffer buffer bname)))))
7540 (defun org-set-frame-title (title)
7541 "Set the title of the current frame to the string TITLE."
7542 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7544 ;;;; Structure editing
7546 ;;; Inserting headlines
7548 (defun org--line-empty-p (n)
7549 "Is the Nth next line empty?
7551 Counts the current line as N = 1 and the previous line as N = 0;
7552 see `beginning-of-line'."
7553 (save-excursion
7554 (and (not (bobp))
7555 (or (beginning-of-line n) t)
7556 (save-match-data
7557 (looking-at "[ \t]*$")))))
7559 (defun org-previous-line-empty-p ()
7560 "Is the previous line a blank line?
7561 When NEXT is non-nil, check the next line instead."
7562 (org--line-empty-p 0))
7564 (defun org-next-line-empty-p ()
7565 "Is the previous line a blank line?
7566 When NEXT is non-nil, check the next line instead."
7567 (org--line-empty-p 2))
7569 (defun org--blank-before-heading-p (&optional parent)
7570 "Non-nil when an empty line should precede a new heading here.
7571 When optional argument PARENT is non-nil, consider parent
7572 headline instead of current one."
7573 (pcase (assq 'heading org-blank-before-new-entry)
7574 (`(heading . auto)
7575 (save-excursion
7576 (org-with-limited-levels
7577 (unless (and (org-before-first-heading-p)
7578 (not (outline-next-heading)))
7579 (org-back-to-heading t)
7580 (when parent (org-up-heading-safe))
7581 (cond ((not (bobp))
7582 (org-previous-line-empty-p))
7583 ((outline-next-heading)
7584 (org-previous-line-empty-p))
7585 ;; Ignore trailing spaces on last buffer line.
7586 ((progn (skip-chars-backward " \t") (bolp))
7587 (org-previous-line-empty-p))
7588 (t nil))))))
7589 (`(heading . ,value) value)
7590 (_ nil)))
7592 (defun org-insert-heading (&optional arg invisible-ok top)
7593 "Insert a new heading or an item with the same depth at point.
7595 If point is at the beginning of a heading, insert a new heading
7596 or a new headline above the current one. When at the beginning
7597 of a regular line of text, turn it into a heading.
7599 If point is in the middle of a line, split it and create a new
7600 headline with the text in the current line after point (see
7601 `org-M-RET-may-split-line' on how to modify this behavior). As
7602 a special case, on a headline, splitting can only happen on the
7603 title itself. E.g., this excludes breaking stars or tags.
7605 With a `\\[universal-argument]' prefix, set \
7606 `org-insert-heading-respect-content' to
7607 a non-nil value for the duration of the command. This forces the
7608 insertion of a heading after the current subtree, independently
7609 on the location of point.
7611 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7612 insert the heading at the end of the tree
7613 above the current heading. For example, if point is within a
7614 2nd-level heading, then it will insert a 2nd-level heading at
7615 the end of the 1st-level parent subtree.
7617 When INVISIBLE-OK is set, stop at invisible headlines when going
7618 back. This is important for non-interactive uses of the
7619 command.
7621 When optional argument TOP is non-nil, insert a level 1 heading,
7622 unconditionally."
7623 (interactive "P")
7624 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7625 (level (org-current-level))
7626 (stars (make-string (if (and level (not top)) level 1) ?*)))
7627 (cond
7628 ((or org-insert-heading-respect-content
7629 (member arg '((4) (16)))
7630 (and (not invisible-ok)
7631 (invisible-p (max (1- (point)) (point-min)))))
7632 ;; Position point at the location of insertion.
7633 (if (not level) ;before first headline
7634 (org-with-limited-levels (outline-next-heading))
7635 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7636 ;; is nil.
7637 (org-with-limited-levels (org-back-to-heading invisible-ok))
7638 (cond ((equal arg '(16))
7639 (org-up-heading-safe)
7640 (org-end-of-subtree t t))
7642 (org-end-of-subtree t t))))
7643 (unless (bolp) (insert "\n")) ;ensure final newline
7644 (unless (and blank? (org-previous-line-empty-p))
7645 (org-N-empty-lines-before-current (if blank? 1 0)))
7646 (insert stars " \n")
7647 (forward-char -1))
7648 ;; At a headline...
7649 ((org-at-heading-p)
7650 (cond ((bolp)
7651 (when blank? (save-excursion (insert "\n")))
7652 (save-excursion (insert stars " \n"))
7653 (unless (and blank? (org-previous-line-empty-p))
7654 (org-N-empty-lines-before-current (if blank? 1 0)))
7655 (end-of-line))
7656 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7657 (org-match-line org-complex-heading-regexp)
7658 (org-pos-in-match-range (point) 4))
7659 ;; Grab the text that should moved to the new headline.
7660 ;; Preserve tags.
7661 (let ((split (delete-and-extract-region (point) (match-end 4))))
7662 (if (looking-at "[ \t]*$") (replace-match "")
7663 (org-align-tags))
7664 (end-of-line)
7665 (when blank? (insert "\n"))
7666 (insert "\n" stars " ")
7667 (when (org-string-nw-p split) (insert split))
7668 (when (eobp) (save-excursion (insert "\n")))))
7670 (end-of-line)
7671 (when blank? (insert "\n"))
7672 (insert "\n" stars " ")
7673 (when (eobp) (save-excursion (insert "\n"))))))
7674 ;; On regular text, turn line into a headline or split, if
7675 ;; appropriate.
7676 ((bolp)
7677 (insert stars " ")
7678 (unless (and blank? (org-previous-line-empty-p))
7679 (org-N-empty-lines-before-current (if blank? 1 0))))
7681 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7682 (end-of-line))
7683 (insert "\n" stars " ")
7684 (unless (and blank? (org-previous-line-empty-p))
7685 (org-N-empty-lines-before-current (if blank? 1 0))))))
7686 (run-hooks 'org-insert-heading-hook))
7688 (defun org-N-empty-lines-before-current (n)
7689 "Make the number of empty lines before current exactly N.
7690 So this will delete or add empty lines."
7691 (let ((column (current-column)))
7692 (beginning-of-line)
7693 (unless (bobp)
7694 (let ((start (save-excursion
7695 (skip-chars-backward " \r\t\n")
7696 (line-end-position))))
7697 (delete-region start (line-end-position 0))))
7698 (insert (make-string n ?\n))
7699 (move-to-column column)))
7701 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7702 "Return the heading of the current entry, without the stars.
7703 When NO-TAGS is non-nil, don't include tags.
7704 When NO-TODO is non-nil, don't include TODO keywords.
7705 When NO-PRIORITY is non-nil, don't include priority cookie.
7706 When NO-COMMENT is non-nil, don't include COMMENT string."
7707 (save-excursion
7708 (org-back-to-heading t)
7709 (let ((case-fold-search nil))
7710 (looking-at org-complex-heading-regexp)
7711 (let ((todo (and (not no-todo) (match-string 2)))
7712 (priority (and (not no-priority) (match-string 3)))
7713 (headline (pcase (match-string 4)
7714 (`nil "")
7715 ((and (guard no-comment) h)
7716 (replace-regexp-in-string
7717 (eval-when-compile
7718 (format "\\`%s[ \t]+" org-comment-string))
7719 "" h))
7720 (h h)))
7721 (tags (and (not no-tags) (match-string 5))))
7722 (mapconcat #'identity
7723 (delq nil (list todo priority headline tags))
7724 " ")))))
7726 (defun org-heading-components ()
7727 "Return the components of the current heading.
7728 This is a list with the following elements:
7729 - the level as an integer
7730 - the reduced level, different if `org-odd-levels-only' is set.
7731 - the TODO keyword, or nil
7732 - the priority character, like ?A, or nil if no priority is given
7733 - the headline text itself, or the tags string if no headline text
7734 - the tags string, or nil."
7735 (save-excursion
7736 (org-back-to-heading t)
7737 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7738 (list (length (match-string 1))
7739 (org-reduced-level (length (match-string 1)))
7740 (match-string-no-properties 2)
7741 (and (match-end 3) (aref (match-string 3) 2))
7742 (match-string-no-properties 4)
7743 (match-string-no-properties 5)))))
7745 (defun org-get-entry ()
7746 "Get the entry text, after heading, entire subtree."
7747 (save-excursion
7748 (org-back-to-heading t)
7749 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7751 (defun org-edit-headline (&optional heading)
7752 "Edit the current headline.
7753 Set it to HEADING when provided."
7754 (interactive)
7755 (org-with-wide-buffer
7756 (org-back-to-heading t)
7757 (let ((case-fold-search nil))
7758 (when (looking-at org-complex-heading-regexp)
7759 (let* ((old (match-string-no-properties 4))
7760 (new (save-match-data
7761 (org-trim (or heading (read-string "Edit: " old))))))
7762 (unless (equal old new)
7763 (if old (replace-match new t t nil 4)
7764 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7765 (insert " " new))
7766 (org-align-tags)
7767 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7769 (defun org-insert-heading-after-current ()
7770 "Insert a new heading with same level as current, after current subtree."
7771 (interactive)
7772 (org-back-to-heading)
7773 (org-insert-heading)
7774 (org-move-subtree-down)
7775 (end-of-line 1))
7777 (defun org-insert-heading-respect-content (&optional invisible-ok)
7778 "Insert heading with `org-insert-heading-respect-content' set to t."
7779 (interactive)
7780 (org-insert-heading '(4) invisible-ok))
7782 (defun org-insert-todo-heading-respect-content (&optional force-state)
7783 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7784 (interactive)
7785 (org-insert-todo-heading force-state '(4)))
7787 (defun org-insert-todo-heading (arg &optional force-heading)
7788 "Insert a new heading with the same level and TODO state as current heading.
7790 If the heading has no TODO state, or if the state is DONE, use
7791 the first state (TODO by default). Also with one prefix arg,
7792 force first state. With two prefix args, force inserting at the
7793 end of the parent subtree.
7795 When called at a plain list item, insert a new item with an
7796 unchecked check box."
7797 (interactive "P")
7798 (when (or force-heading (not (org-insert-item 'checkbox)))
7799 (org-insert-heading (or (and (equal arg '(16)) '(16))
7800 force-heading))
7801 (save-excursion
7802 (org-forward-heading-same-level -1)
7803 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7804 (let* ((new-mark-x
7805 (if (or (equal arg '(4))
7806 (not (match-beginning 2))
7807 (member (match-string 2) org-done-keywords))
7808 (car org-todo-keywords-1)
7809 (match-string 2)))
7810 (new-mark
7812 (run-hook-with-args-until-success
7813 'org-todo-get-default-hook new-mark-x nil)
7814 new-mark-x)))
7815 (beginning-of-line 1)
7816 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7817 (if org-treat-insert-todo-heading-as-state-change
7818 (org-todo new-mark)
7819 (insert new-mark " "))))
7820 (when org-provide-todo-statistics
7821 (org-update-parent-todo-statistics))))
7823 (defun org-insert-subheading (arg)
7824 "Insert a new subheading and demote it.
7825 Works for outline headings and for plain lists alike."
7826 (interactive "P")
7827 (org-insert-heading arg)
7828 (cond
7829 ((org-at-heading-p) (org-do-demote))
7830 ((org-at-item-p) (org-indent-item))))
7832 (defun org-insert-todo-subheading (arg)
7833 "Insert a new subheading with TODO keyword or checkbox and demote it.
7834 Works for outline headings and for plain lists alike."
7835 (interactive "P")
7836 (org-insert-todo-heading arg)
7837 (cond
7838 ((org-at-heading-p) (org-do-demote))
7839 ((org-at-item-p) (org-indent-item))))
7841 ;;; Promotion and Demotion
7843 (defvar org-after-demote-entry-hook nil
7844 "Hook run after an entry has been demoted.
7845 The cursor will be at the beginning of the entry.
7846 When a subtree is being demoted, the hook will be called for each node.")
7848 (defvar org-after-promote-entry-hook nil
7849 "Hook run after an entry has been promoted.
7850 The cursor will be at the beginning of the entry.
7851 When a subtree is being promoted, the hook will be called for each node.")
7853 (defun org-promote-subtree ()
7854 "Promote the entire subtree.
7855 See also `org-promote'."
7856 (interactive)
7857 (save-excursion
7858 (org-with-limited-levels (org-map-tree 'org-promote)))
7859 (org-fix-position-after-promote))
7861 (defun org-demote-subtree ()
7862 "Demote the entire subtree.
7863 See `org-demote' and `org-promote'."
7864 (interactive)
7865 (save-excursion
7866 (org-with-limited-levels (org-map-tree 'org-demote)))
7867 (org-fix-position-after-promote))
7869 (defun org-do-promote ()
7870 "Promote the current heading higher up the tree.
7871 If the region is active in `transient-mark-mode', promote all
7872 headings in the region."
7873 (interactive)
7874 (save-excursion
7875 (if (org-region-active-p)
7876 (org-map-region 'org-promote (region-beginning) (region-end))
7877 (org-promote)))
7878 (org-fix-position-after-promote))
7880 (defun org-do-demote ()
7881 "Demote the current heading lower down the tree.
7882 If the region is active in `transient-mark-mode', demote all
7883 headings in the region."
7884 (interactive)
7885 (save-excursion
7886 (if (org-region-active-p)
7887 (org-map-region 'org-demote (region-beginning) (region-end))
7888 (org-demote)))
7889 (org-fix-position-after-promote))
7891 (defun org-fix-position-after-promote ()
7892 "Fix cursor position and indentation after demoting/promoting."
7893 (let ((pos (point)))
7894 (when (save-excursion
7895 (beginning-of-line)
7896 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7897 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7898 (cond ((eobp) (insert " "))
7899 ((eolp) (insert " "))
7900 ((equal (char-after) ?\s) (forward-char 1))))))
7902 (defun org-current-level ()
7903 "Return the level of the current entry, or nil if before the first headline.
7904 The level is the number of stars at the beginning of the
7905 headline. Use `org-reduced-level' to remove the effect of
7906 `org-odd-levels'. Unlike to `org-outline-level', this function
7907 ignores inlinetasks."
7908 (let ((level (org-with-limited-levels (org-outline-level))))
7909 (and (> level 0) level)))
7911 (defun org-get-previous-line-level ()
7912 "Return the outline depth of the last headline before the current line.
7913 Returns 0 for the first headline in the buffer, and nil if before the
7914 first headline."
7915 (and (org-current-level)
7916 (or (and (/= (line-beginning-position) (point-min))
7917 (save-excursion (beginning-of-line 0) (org-current-level)))
7918 0)))
7920 (defun org-reduced-level (l)
7921 "Compute the effective level of a heading.
7922 This takes into account the setting of `org-odd-levels-only'."
7923 (cond
7924 ((zerop l) 0)
7925 (org-odd-levels-only (1+ (floor (/ l 2))))
7926 (t l)))
7928 (defun org-level-increment ()
7929 "Return the number of stars that will be added or removed at a
7930 time to headlines when structure editing, based on the value of
7931 `org-odd-levels-only'."
7932 (if org-odd-levels-only 2 1))
7934 (defun org-get-valid-level (level &optional change)
7935 "Rectify a level change under the influence of `org-odd-levels-only'.
7936 LEVEL is a current level, CHANGE is by how much the level should
7937 be modified. Even if CHANGE is nil, LEVEL may be returned
7938 modified because even level numbers will become the next higher
7939 odd number. Returns values greater than 0."
7940 (if org-odd-levels-only
7941 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7942 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7943 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7944 (max 1 (+ level (or change 0)))))
7946 (defun org-promote ()
7947 "Promote the current heading higher up the tree."
7948 (org-with-wide-buffer
7949 (org-back-to-heading t)
7950 (let* ((after-change-functions (remq 'flyspell-after-change-function
7951 after-change-functions))
7952 (level (save-match-data (funcall outline-level)))
7953 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7954 (diff (abs (- level (length up-head) -1))))
7955 (cond
7956 ((and (= level 1) org-allow-promoting-top-level-subtree)
7957 (replace-match "# " nil t))
7958 ((= level 1)
7959 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7960 (t (replace-match up-head nil t)))
7961 (unless (= level 1)
7962 (when org-auto-align-tags (org-align-tags))
7963 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7964 (run-hooks 'org-after-promote-entry-hook))))
7966 (defun org-demote ()
7967 "Demote the current heading lower down the tree."
7968 (org-with-wide-buffer
7969 (org-back-to-heading t)
7970 (let* ((after-change-functions (remq 'flyspell-after-change-function
7971 after-change-functions))
7972 (level (save-match-data (funcall outline-level)))
7973 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7974 (diff (abs (- level (length down-head) -1))))
7975 (replace-match down-head nil t)
7976 (when org-auto-align-tags (org-align-tags))
7977 (when org-adapt-indentation (org-fixup-indentation diff))
7978 (run-hooks 'org-after-demote-entry-hook))))
7980 (defun org-cycle-level ()
7981 "Cycle the level of an empty headline through possible states.
7982 This goes first to child, then to parent, level, then up the hierarchy.
7983 After top level, it switches back to sibling level."
7984 (interactive)
7985 (let ((org-adapt-indentation nil))
7986 (when (org-point-at-end-of-empty-headline)
7987 (setq this-command 'org-cycle-level) ; Only needed for caching
7988 (let ((cur-level (org-current-level))
7989 (prev-level (org-get-previous-line-level)))
7990 (cond
7991 ;; If first headline in file, promote to top-level.
7992 ((= prev-level 0)
7993 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
7994 do (org-do-promote)))
7995 ;; If same level as prev, demote one.
7996 ((= prev-level cur-level)
7997 (org-do-demote))
7998 ;; If parent is top-level, promote to top level if not already.
7999 ((= prev-level 1)
8000 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8001 do (org-do-promote)))
8002 ;; If top-level, return to prev-level.
8003 ((= cur-level 1)
8004 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8005 do (org-do-demote)))
8006 ;; If less than prev-level, promote one.
8007 ((< cur-level prev-level)
8008 (org-do-promote))
8009 ;; If deeper than prev-level, promote until higher than
8010 ;; prev-level.
8011 ((> cur-level prev-level)
8012 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8013 do (org-do-promote))))
8014 t))))
8016 (defun org-map-tree (fun)
8017 "Call FUN for every heading underneath the current one."
8018 (org-back-to-heading t)
8019 (let ((level (funcall outline-level)))
8020 (save-excursion
8021 (funcall fun)
8022 (while (and (progn
8023 (outline-next-heading)
8024 (> (funcall outline-level) level))
8025 (not (eobp)))
8026 (funcall fun)))))
8028 (defun org-map-region (fun beg end)
8029 "Call FUN for every heading between BEG and END."
8030 (let ((org-ignore-region t))
8031 (save-excursion
8032 (setq end (copy-marker end))
8033 (goto-char beg)
8034 (when (and (re-search-forward org-outline-regexp-bol nil t)
8035 (< (point) end))
8036 (funcall fun))
8037 (while (and (progn
8038 (outline-next-heading)
8039 (< (point) end))
8040 (not (eobp)))
8041 (funcall fun)))))
8043 (defun org-fixup-indentation (diff)
8044 "Change the indentation in the current entry by DIFF.
8046 DIFF is an integer. Indentation is done according to the
8047 following rules:
8049 - Planning information and property drawers are always indented
8050 according to the new level of the headline;
8052 - Footnote definitions and their contents are ignored;
8054 - Inlinetasks' boundaries are not shifted;
8056 - Empty lines are ignored;
8058 - Other lines' indentation are shifted by DIFF columns, unless
8059 it would introduce a structural change in the document, in
8060 which case no shifting is done at all.
8062 Assume point is at a heading or an inlinetask beginning."
8063 (org-with-wide-buffer
8064 (narrow-to-region (line-beginning-position)
8065 (save-excursion
8066 (if (org-with-limited-levels (org-at-heading-p))
8067 (org-with-limited-levels (outline-next-heading))
8068 (org-inlinetask-goto-end))
8069 (point)))
8070 (forward-line)
8071 ;; Indent properly planning info and property drawer.
8072 (when (looking-at-p org-planning-line-re)
8073 (org-indent-line)
8074 (forward-line))
8075 (when (looking-at org-property-drawer-re)
8076 (goto-char (match-end 0))
8077 (forward-line)
8078 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8079 (catch 'no-shift
8080 (when (zerop diff) (throw 'no-shift nil))
8081 ;; If DIFF is negative, first check if a shift is possible at all
8082 ;; (e.g., it doesn't break structure). This can only happen if
8083 ;; some contents are not properly indented.
8084 (let ((case-fold-search t))
8085 (when (< diff 0)
8086 (let ((diff (- diff))
8087 (forbidden-re (concat org-outline-regexp
8088 "\\|"
8089 (substring org-footnote-definition-re 1))))
8090 (save-excursion
8091 (while (not (eobp))
8092 (cond
8093 ((looking-at-p "[ \t]*$") (forward-line))
8094 ((and (looking-at-p org-footnote-definition-re)
8095 (let ((e (org-element-at-point)))
8096 (and (eq (org-element-type e) 'footnote-definition)
8097 (goto-char (org-element-property :end e))))))
8098 ((looking-at-p org-outline-regexp) (forward-line))
8099 ;; Give up if shifting would move before column 0 or
8100 ;; if it would introduce a headline or a footnote
8101 ;; definition.
8103 (skip-chars-forward " \t")
8104 (let ((ind (current-column)))
8105 (when (or (< ind diff)
8106 (and (= ind diff) (looking-at-p forbidden-re)))
8107 (throw 'no-shift nil)))
8108 ;; Ignore contents of example blocks and source
8109 ;; blocks if their indentation is meant to be
8110 ;; preserved. Jump to block's closing line.
8111 (beginning-of-line)
8112 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8113 (let ((e (org-element-at-point)))
8114 (and (memq (org-element-type e)
8115 '(example-block src-block))
8116 (or org-src-preserve-indentation
8117 (org-element-property :preserve-indent e))
8118 (goto-char (org-element-property :end e))
8119 (progn (skip-chars-backward " \r\t\n")
8120 (beginning-of-line)
8121 t))))
8122 (forward-line))))))))
8123 ;; Shift lines but footnote definitions, inlinetasks boundaries
8124 ;; by DIFF. Also skip contents of source or example blocks
8125 ;; when indentation is meant to be preserved.
8126 (while (not (eobp))
8127 (cond
8128 ((and (looking-at-p org-footnote-definition-re)
8129 (let ((e (org-element-at-point)))
8130 (and (eq (org-element-type e) 'footnote-definition)
8131 (goto-char (org-element-property :end e))))))
8132 ((looking-at-p org-outline-regexp) (forward-line))
8133 ((looking-at-p "[ \t]*$") (forward-line))
8135 (indent-line-to (+ (current-indentation) diff))
8136 (beginning-of-line)
8137 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8138 (let ((e (org-element-at-point)))
8139 (and (memq (org-element-type e)
8140 '(example-block src-block))
8141 (or org-src-preserve-indentation
8142 (org-element-property :preserve-indent e))
8143 (goto-char (org-element-property :end e))
8144 (progn (skip-chars-backward " \r\t\n")
8145 (beginning-of-line)
8146 t))))
8147 (forward-line)))))))))
8149 (defun org-convert-to-odd-levels ()
8150 "Convert an Org file with all levels allowed to one with odd levels.
8151 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8152 level 5 etc."
8153 (interactive)
8154 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8155 (let ((outline-level 'org-outline-level)
8156 (org-odd-levels-only nil) n)
8157 (save-excursion
8158 (goto-char (point-min))
8159 (while (re-search-forward "^\\*\\*+ " nil t)
8160 (setq n (- (length (match-string 0)) 2))
8161 (while (>= (setq n (1- n)) 0)
8162 (org-demote))
8163 (end-of-line 1))))))
8165 (defun org-convert-to-oddeven-levels ()
8166 "Convert an Org file with only odd levels to one with odd/even levels.
8167 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8168 file contains a section with an even level, conversion would
8169 destroy the structure of the file. An error is signaled in this
8170 case."
8171 (interactive)
8172 (goto-char (point-min))
8173 ;; First check if there are no even levels
8174 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8175 (org-show-set-visibility 'canonical)
8176 (error "Not all levels are odd in this file. Conversion not possible"))
8177 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8178 (let ((outline-regexp org-outline-regexp)
8179 (outline-level 'org-outline-level)
8180 (org-odd-levels-only nil) n)
8181 (save-excursion
8182 (goto-char (point-min))
8183 (while (re-search-forward "^\\*\\*+ " nil t)
8184 (setq n (/ (1- (length (match-string 0))) 2))
8185 (while (>= (setq n (1- n)) 0)
8186 (org-promote))
8187 (end-of-line 1))))))
8189 (defun org-tr-level (n)
8190 "Make N odd if required."
8191 (if org-odd-levels-only (1+ (/ n 2)) n))
8193 ;;; Vertical tree motion, cutting and pasting of subtrees
8195 (defun org-move-subtree-up (&optional arg)
8196 "Move the current subtree up past ARG headlines of the same level."
8197 (interactive "p")
8198 (org-move-subtree-down (- (prefix-numeric-value arg))))
8200 (defun org-move-subtree-down (&optional arg)
8201 "Move the current subtree down past ARG headlines of the same level."
8202 (interactive "p")
8203 (setq arg (prefix-numeric-value arg))
8204 (org-preserve-local-variables
8205 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8206 'org-get-last-sibling))
8207 (ins-point (make-marker))
8208 (cnt (abs arg))
8209 (col (current-column))
8210 beg end txt folded)
8211 ;; Select the tree
8212 (org-back-to-heading)
8213 (setq beg (point))
8214 (save-match-data
8215 (save-excursion (outline-end-of-heading)
8216 (setq folded (org-invisible-p)))
8217 (progn (org-end-of-subtree nil t)
8218 (unless (eobp) (backward-char))))
8219 (outline-next-heading)
8220 (setq end (point))
8221 (goto-char beg)
8222 ;; Find insertion point, with error handling
8223 (while (> cnt 0)
8224 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8225 (goto-char beg)
8226 (user-error "Cannot move past superior level or buffer limit"))
8227 (setq cnt (1- cnt)))
8228 (when (> arg 0)
8229 ;; Moving forward - still need to move over subtree
8230 (org-end-of-subtree t t)
8231 (save-excursion
8232 (org-back-over-empty-lines)
8233 (or (bolp) (newline))))
8234 (move-marker ins-point (point))
8235 (setq txt (buffer-substring beg end))
8236 (org-save-markers-in-region beg end)
8237 (delete-region beg end)
8238 (org-remove-empty-overlays-at beg)
8239 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8240 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8241 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8242 (let ((bbb (point)))
8243 (insert-before-markers txt)
8244 (org-reinstall-markers-in-region bbb)
8245 (move-marker ins-point bbb))
8246 (or (bolp) (insert "\n"))
8247 (goto-char ins-point)
8248 (org-skip-whitespace)
8249 (move-marker ins-point nil)
8250 (if folded
8251 (outline-hide-subtree)
8252 (org-show-entry)
8253 (org-show-children))
8254 (org-clean-visibility-after-subtree-move)
8255 ;; move back to the initial column we were at
8256 (move-to-column col))))
8258 (defvar org-subtree-clip ""
8259 "Clipboard for cut and paste of subtrees.
8260 This is actually only a copy of the kill, because we use the normal kill
8261 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8263 (defvar org-subtree-clip-folded nil
8264 "Was the last copied subtree folded?
8265 This is used to fold the tree back after pasting.")
8267 (defun org-cut-subtree (&optional n)
8268 "Cut the current subtree into the clipboard.
8269 With prefix arg N, cut this many sequential subtrees.
8270 This is a short-hand for marking the subtree and then cutting it."
8271 (interactive "p")
8272 (org-copy-subtree n 'cut))
8274 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8275 "Copy the current subtree into the clipboard.
8276 With prefix arg N, copy this many sequential subtrees.
8277 This is a short-hand for marking the subtree and then copying it.
8278 If CUT is non-nil, actually cut the subtree.
8279 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8280 of some markers in the region, even if CUT is non-nil. This is
8281 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8282 (interactive "p")
8283 (org-preserve-local-variables
8284 (let (beg end folded (beg0 (point)))
8285 (if (called-interactively-p 'any)
8286 (org-back-to-heading nil) ; take what looks like a subtree
8287 (org-back-to-heading t)) ; take what is really there
8288 (setq beg (point))
8289 (skip-chars-forward " \t\r\n")
8290 (save-match-data
8291 (if nosubtrees
8292 (outline-next-heading)
8293 (save-excursion (outline-end-of-heading)
8294 (setq folded (org-invisible-p)))
8295 (ignore-errors (org-forward-heading-same-level (1- n) t))
8296 (org-end-of-subtree t t)))
8297 ;; Include the end of an inlinetask
8298 (when (and (featurep 'org-inlinetask)
8299 (looking-at-p (concat (org-inlinetask-outline-regexp)
8300 "END[ \t]*$")))
8301 (end-of-line))
8302 (setq end (point))
8303 (goto-char beg0)
8304 (when (> end beg)
8305 (setq org-subtree-clip-folded folded)
8306 (when (or cut force-store-markers)
8307 (org-save-markers-in-region beg end))
8308 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8309 (setq org-subtree-clip (current-kill 0))
8310 (message "%s: Subtree(s) with %d characters"
8311 (if cut "Cut" "Copied")
8312 (length org-subtree-clip))))))
8314 (defun org-paste-subtree (&optional level tree for-yank remove)
8315 "Paste the clipboard as a subtree, with modification of headline level.
8317 The entire subtree is promoted or demoted in order to match a new headline
8318 level.
8320 If the cursor is at the beginning of a headline, the same level as
8321 that headline is used to paste the tree.
8323 If not, the new level is derived from the *visible* headings
8324 before and after the insertion point, and taken to be the inferior headline
8325 level of the two. So if the previous visible heading is level 3 and the
8326 next is level 4 (or vice versa), level 4 will be used for insertion.
8327 This makes sure that the subtree remains an independent subtree and does
8328 not swallow low level entries.
8330 You can also force a different level, either by using a numeric prefix
8331 argument, or by inserting the heading marker by hand. For example, if the
8332 cursor is after \"*****\", then the tree will be shifted to level 5.
8334 If optional TREE is given, use this text instead of the kill ring.
8336 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8337 move back over whitespace before inserting, and move point to the end of
8338 the inserted text when done.
8340 When REMOVE is non-nil, remove the subtree from the clipboard."
8341 (interactive "P")
8342 (setq tree (or tree (and kill-ring (current-kill 0))))
8343 (unless (org-kill-is-subtree-p tree)
8344 (user-error
8345 (substitute-command-keys
8346 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8347 (org-with-limited-levels
8348 (let* ((visp (not (org-invisible-p)))
8349 (txt tree)
8350 (old-level (if (string-match org-outline-regexp-bol txt)
8351 (- (match-end 0) (match-beginning 0) 1)
8352 -1))
8353 (force-level
8354 (cond
8355 (level (prefix-numeric-value level))
8356 ;; When point is right after the stars in an otherwise
8357 ;; empty headline, use stars as the forced level.
8358 ((and (looking-at-p "[ \t]*$")
8359 (string-match-p "^\\*+ *"
8360 (buffer-substring (line-beginning-position)
8361 (point))))
8362 (org-outline-level))
8363 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8364 (previous-level
8365 (save-excursion
8366 (org-previous-visible-heading 1)
8367 (if (org-at-heading-p) (org-outline-level) 1)))
8368 (next-level
8369 (save-excursion
8370 (if (org-at-heading-p) (org-outline-level)
8371 (org-next-visible-heading 1)
8372 (if (org-at-heading-p) (org-outline-level) 1))))
8373 (new-level (or force-level (max previous-level next-level)))
8374 (shift (if (or (= old-level -1)
8375 (= new-level -1)
8376 (= old-level new-level))
8378 (- new-level old-level)))
8379 (delta (if (> shift 0) -1 1))
8380 (func (if (> shift 0) #'org-demote #'org-promote))
8381 (org-odd-levels-only nil)
8382 beg end newend)
8383 ;; Remove the forced level indicator.
8384 (when (and force-level (not level))
8385 (delete-region (line-beginning-position) (point)))
8386 ;; Paste before the next visible heading or at end of buffer,
8387 ;; unless point is at the beginning of a headline.
8388 (unless (and (bolp) (org-at-heading-p))
8389 (org-next-visible-heading 1)
8390 (unless (bolp) (insert "\n")))
8391 (setq beg (point))
8392 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8393 (insert-before-markers txt)
8394 (unless (string-suffix-p "\n" txt) (insert "\n"))
8395 (setq newend (point))
8396 (org-reinstall-markers-in-region beg)
8397 (setq end (point))
8398 (goto-char beg)
8399 (skip-chars-forward " \t\n\r")
8400 (setq beg (point))
8401 (when (and (org-invisible-p) visp)
8402 (save-excursion (outline-show-heading)))
8403 ;; Shift if necessary.
8404 (unless (= shift 0)
8405 (save-restriction
8406 (narrow-to-region beg end)
8407 (while (not (= shift 0))
8408 (org-map-region func (point-min) (point-max))
8409 (setq shift (+ delta shift)))
8410 (goto-char (point-min))
8411 (setq newend (point-max))))
8412 (when (or for-yank (called-interactively-p 'interactive))
8413 (message "Clipboard pasted as level %d subtree" new-level))
8414 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8415 kill-ring
8416 (equal org-subtree-clip (current-kill 0))
8417 org-subtree-clip-folded)
8418 ;; The tree was folded before it was killed/copied
8419 (outline-hide-subtree))
8420 (when for-yank (goto-char newend))
8421 (when remove (pop kill-ring)))))
8423 (defun org-kill-is-subtree-p (&optional txt)
8424 "Check if the current kill is an outline subtree, or a set of trees.
8425 Returns nil if kill does not start with a headline, or if the first
8426 headline level is not the largest headline level in the tree.
8427 So this will actually accept several entries of equal levels as well,
8428 which is OK for `org-paste-subtree'.
8429 If optional TXT is given, check this string instead of the current kill."
8430 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8431 (re (org-get-limited-outline-regexp))
8432 (^re (concat "^" re))
8433 (start-level (and kill
8434 (string-match
8435 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8436 kill)
8437 (- (match-end 2) (match-beginning 2) 1)))
8438 (start (1+ (or (match-beginning 2) -1))))
8439 (if (not start-level)
8440 (progn
8441 nil) ;; does not even start with a heading
8442 (catch 'exit
8443 (while (setq start (string-match ^re kill (1+ start)))
8444 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8445 (throw 'exit nil)))
8446 t))))
8448 (defvar org-markers-to-move nil
8449 "Markers that should be moved with a cut-and-paste operation.
8450 Those markers are stored together with their positions relative to
8451 the start of the region.")
8453 (defun org-save-markers-in-region (beg end)
8454 "Check markers in region.
8455 If these markers are between BEG and END, record their position relative
8456 to BEG, so that after moving the block of text, we can put the markers back
8457 into place.
8458 This function gets called just before an entry or tree gets cut from the
8459 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8460 called immediately, to move the markers with the entries."
8461 (setq org-markers-to-move nil)
8462 (when (featurep 'org-clock)
8463 (org-clock-save-markers-for-cut-and-paste beg end))
8464 (when (featurep 'org-agenda)
8465 (org-agenda-save-markers-for-cut-and-paste beg end)))
8467 (defun org-check-and-save-marker (marker beg end)
8468 "Check if MARKER is between BEG and END.
8469 If yes, remember the marker and the distance to BEG."
8470 (when (and (marker-buffer marker)
8471 (equal (marker-buffer marker) (current-buffer))
8472 (>= marker beg) (< marker end))
8473 (push (cons marker (- marker beg)) org-markers-to-move)))
8475 (defun org-reinstall-markers-in-region (beg)
8476 "Move all remembered markers to their position relative to BEG."
8477 (dolist (x org-markers-to-move)
8478 (move-marker (car x) (+ beg (cdr x))))
8479 (setq org-markers-to-move nil))
8481 (defun org-narrow-to-subtree ()
8482 "Narrow buffer to the current subtree."
8483 (interactive)
8484 (save-excursion
8485 (save-match-data
8486 (org-with-limited-levels
8487 (narrow-to-region
8488 (progn (org-back-to-heading t) (point))
8489 (progn (org-end-of-subtree t t)
8490 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8491 (point)))))))
8493 (defun org-toggle-narrow-to-subtree ()
8494 "Narrow to the subtree at point or widen a narrowed buffer."
8495 (interactive)
8496 (if (buffer-narrowed-p)
8497 (widen)
8498 (org-narrow-to-subtree)))
8500 (defun org-narrow-to-block ()
8501 "Narrow buffer to the current block."
8502 (interactive)
8503 (let* ((case-fold-search t)
8504 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8505 "^[ \t]*#\\+end_.*")))
8506 (if blockp
8507 (narrow-to-region (car blockp) (cdr blockp))
8508 (user-error "Not in a block"))))
8510 (defun org-clone-subtree-with-time-shift (n &optional shift)
8511 "Clone the task (subtree) at point N times.
8512 The clones will be inserted as siblings.
8514 In interactive use, the user will be prompted for the number of
8515 clones to be produced. If the entry has a timestamp, the user
8516 will also be prompted for a time shift, which may be a repeater
8517 as used in time stamps, for example `+3d'. To disable this,
8518 you can call the function with a universal prefix argument.
8520 When a valid repeater is given and the entry contains any time
8521 stamps, the clones will become a sequence in time, with time
8522 stamps in the subtree shifted for each clone produced. If SHIFT
8523 is nil or the empty string, time stamps will be left alone. The
8524 ID property of the original subtree is removed.
8526 In each clone, all the CLOCK entries will be removed. This
8527 prevents Org from considering that the clocked times overlap.
8529 If the original subtree did contain time stamps with a repeater,
8530 the following will happen:
8531 - the repeater will be removed in each clone
8532 - an additional clone will be produced, with the current, unshifted
8533 date(s) in the entry.
8534 - the original entry will be placed *after* all the clones, with
8535 repeater intact.
8536 - the start days in the repeater in the original entry will be shifted
8537 to past the last clone.
8538 In this way you can spell out a number of instances of a repeating task,
8539 and still retain the repeater to cover future instances of the task.
8541 As described above, N+1 clones are produced when the original
8542 subtree has a repeater. Setting N to 0, then, can be used to
8543 remove the repeater from a subtree and create a shifted clone
8544 with the original repeater."
8545 (interactive "nNumber of clones to produce: ")
8546 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8547 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8548 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8549 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8550 (shift
8551 (or shift
8552 (if (and (not (equal current-prefix-arg '(4)))
8553 (save-excursion
8554 (goto-char beg)
8555 (re-search-forward org-ts-regexp-both end-of-tree t)))
8556 (read-from-minibuffer
8557 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8558 ""))) ;No time shift
8559 (doshift
8560 (and (org-string-nw-p shift)
8561 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8562 shift)
8563 (user-error "Invalid shift specification %s" shift)))))
8564 (goto-char end-of-tree)
8565 (unless (bolp) (insert "\n"))
8566 (let* ((end (point))
8567 (template (buffer-substring beg end))
8568 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8569 (shift-what (pcase (and doshift (match-string 2 shift))
8570 (`nil nil)
8571 ("d" 'day)
8572 ("w" (setq shift-n (* 7 shift-n)) 'day)
8573 ("m" 'month)
8574 ("y" 'year)
8575 (_ (error "Unsupported time unit"))))
8576 (nmin 1)
8577 (nmax n)
8578 (n-no-remove -1)
8579 (idprop (org-entry-get nil "ID")))
8580 (when (and doshift
8581 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8582 template))
8583 (delete-region beg end)
8584 (setq end beg)
8585 (setq nmin 0)
8586 (setq nmax (1+ nmax))
8587 (setq n-no-remove nmax))
8588 (goto-char end)
8589 (cl-loop for n from nmin to nmax do
8590 (insert
8591 ;; Prepare clone.
8592 (with-temp-buffer
8593 (insert template)
8594 (org-mode)
8595 (goto-char (point-min))
8596 (org-show-subtree)
8597 (and idprop (if org-clone-delete-id
8598 (org-entry-delete nil "ID")
8599 (org-id-get-create t)))
8600 (unless (= n 0)
8601 (while (re-search-forward org-clock-line-re nil t)
8602 (delete-region (line-beginning-position)
8603 (line-beginning-position 2)))
8604 (goto-char (point-min))
8605 (while (re-search-forward org-drawer-regexp nil t)
8606 (org-remove-empty-drawer-at (point))))
8607 (goto-char (point-min))
8608 (when doshift
8609 (while (re-search-forward org-ts-regexp-both nil t)
8610 (org-timestamp-change (* n shift-n) shift-what))
8611 (unless (= n n-no-remove)
8612 (goto-char (point-min))
8613 (while (re-search-forward org-ts-regexp nil t)
8614 (save-excursion
8615 (goto-char (match-beginning 0))
8616 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8617 (delete-region (match-beginning 1) (match-end 1)))))))
8618 (buffer-string)))))
8619 (goto-char beg)))
8621 ;;; Outline Sorting
8623 (defun org-sort (&optional with-case)
8624 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8625 Optional argument WITH-CASE means sort case-sensitively."
8626 (interactive "P")
8627 (org-call-with-arg
8628 (cond ((org-at-table-p) #'org-table-sort-lines)
8629 ((org-at-item-p) #'org-sort-list)
8630 (t #'org-sort-entries))
8631 with-case))
8633 (defun org-sort-remove-invisible (s)
8634 "Remove invisible part of links and emphasis markers from string S."
8635 (remove-text-properties 0 (length s) org-rm-props s)
8636 (replace-regexp-in-string
8637 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8638 (replace-regexp-in-string
8639 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8640 (org-link-display-format s)
8641 t t) t t))
8643 (defvar org-priority-regexp) ; defined later in the file
8645 (defvar org-after-sorting-entries-or-items-hook nil
8646 "Hook that is run after a bunch of entries or items have been sorted.
8647 When children are sorted, the cursor is in the parent line when this
8648 hook gets called. When a region or a plain list is sorted, the cursor
8649 will be in the first entry of the sorted region/list.")
8651 (defun org-sort-entries
8652 (&optional with-case sorting-type getkey-func compare-func property
8653 interactive?)
8654 "Sort entries on a certain level of an outline tree.
8655 If there is an active region, the entries in the region are sorted.
8656 Else, if the cursor is before the first entry, sort the top-level items.
8657 Else, the children of the entry at point are sorted.
8659 Sorting can be alphabetically, numerically, by date/time as given by
8660 a time stamp, by a property, by priority order, or by a custom function.
8662 The command prompts for the sorting type unless it has been given to the
8663 function through the SORTING-TYPE argument, which needs to be a character,
8664 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8665 the precise meaning of each character:
8667 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8668 c By creation time, which is assumed to be the first inactive time stamp
8669 at the beginning of a line.
8670 d By deadline date/time.
8671 k By clocking time.
8672 n Numerically, by converting the beginning of the entry/item to a number.
8673 o By order of TODO keywords.
8674 p By priority according to the cookie.
8675 r By the value of a property.
8676 s By scheduled date/time.
8677 t By date/time, either the first active time stamp in the entry, or, if
8678 none exist, by the first inactive one.
8680 Capital letters will reverse the sort order.
8682 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8683 called with point at the beginning of the record. It must return a
8684 value that is compatible with COMPARE-FUNC, the function used to
8685 compare entries.
8687 Comparing entries ignores case by default. However, with an optional argument
8688 WITH-CASE, the sorting considers case as well.
8690 Sorting is done against the visible part of the headlines, it ignores hidden
8691 links.
8693 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8695 A non-nil value for INTERACTIVE? is used to signal that this
8696 function is being called interactively."
8697 (interactive (list current-prefix-arg nil nil nil nil t))
8698 (let ((case-func (if with-case 'identity 'downcase))
8699 start beg end stars re re2
8700 txt what tmp)
8701 ;; Find beginning and end of region to sort
8702 (cond
8703 ((org-region-active-p)
8704 ;; we will sort the region
8705 (setq end (region-end)
8706 what "region")
8707 (goto-char (region-beginning))
8708 (unless (org-at-heading-p) (outline-next-heading))
8709 (setq start (point)))
8710 ((or (org-at-heading-p)
8711 (ignore-errors (progn (org-back-to-heading) t)))
8712 ;; we will sort the children of the current headline
8713 (org-back-to-heading)
8714 (setq start (point)
8715 end (progn (org-end-of-subtree t t)
8716 (or (bolp) (insert "\n"))
8717 (when (>= (org-back-over-empty-lines) 1)
8718 (forward-line 1))
8719 (point))
8720 what "children")
8721 (goto-char start)
8722 (outline-show-subtree)
8723 (outline-next-heading))
8725 ;; we will sort the top-level entries in this file
8726 (goto-char (point-min))
8727 (or (org-at-heading-p) (outline-next-heading))
8728 (setq start (point))
8729 (goto-char (point-max))
8730 (beginning-of-line 1)
8731 (when (looking-at ".*?\\S-")
8732 ;; File ends in a non-white line
8733 (end-of-line 1)
8734 (insert "\n"))
8735 (setq end (point-max))
8736 (setq what "top-level")
8737 (goto-char start)
8738 (org-show-all '(headings blocks))))
8740 (setq beg (point))
8741 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8743 (looking-at "\\(\\*+\\)")
8744 (setq stars (match-string 1)
8745 re (concat "^" (regexp-quote stars) " +")
8746 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8747 txt (buffer-substring beg end))
8748 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8749 (when (and (not (equal stars "*")) (string-match re2 txt))
8750 (user-error "Region to sort contains a level above the first entry"))
8752 (unless sorting-type
8753 (message
8754 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8755 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8756 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8757 what)
8758 (setq sorting-type (read-char-exclusive)))
8760 (unless getkey-func
8761 (and (= (downcase sorting-type) ?f)
8762 (setq getkey-func
8763 (or (and interactive?
8764 (org-read-function
8765 "Function for extracting keys: "))
8766 (error "Missing key extractor")))))
8768 (and (= (downcase sorting-type) ?r)
8769 (not property)
8770 (setq property
8771 (completing-read "Property: "
8772 (mapcar #'list (org-buffer-property-keys t))
8773 nil t)))
8775 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8776 (message "Sorting entries...")
8778 (save-restriction
8779 (narrow-to-region start end)
8780 (let ((restore-clock?
8781 ;; The clock marker is lost when using `sort-subr'; mark
8782 ;; the clock with temporary `:org-clock-marker-backup'
8783 ;; text property.
8784 (when (and (eq (org-clock-is-active) (current-buffer))
8785 (<= start (marker-position org-clock-marker))
8786 (>= end (marker-position org-clock-marker)))
8787 (with-silent-modifications
8788 (put-text-property (1- org-clock-marker) org-clock-marker
8789 :org-clock-marker-backup t))
8791 (dcst (downcase sorting-type))
8792 (case-fold-search nil)
8793 (now (current-time)))
8794 (org-preserve-local-variables
8795 (sort-subr
8796 (/= dcst sorting-type)
8797 ;; This function moves to the beginning character of the
8798 ;; "record" to be sorted.
8799 (lambda nil
8800 (if (re-search-forward re nil t)
8801 (goto-char (match-beginning 0))
8802 (goto-char (point-max))))
8803 ;; This function moves to the last character of the "record" being
8804 ;; sorted.
8805 (lambda nil
8806 (save-match-data
8807 (condition-case nil
8808 (outline-forward-same-level 1)
8809 (error
8810 (goto-char (point-max))))))
8811 ;; This function returns the value that gets sorted against.
8812 (lambda ()
8813 (cond
8814 ((= dcst ?n)
8815 (string-to-number
8816 (org-sort-remove-invisible (org-get-heading t t t t))))
8817 ((= dcst ?a)
8818 (funcall case-func
8819 (org-sort-remove-invisible (org-get-heading t t t t))))
8820 ((= dcst ?k)
8821 (or (get-text-property (point) :org-clock-minutes) 0))
8822 ((= dcst ?t)
8823 (let ((end (save-excursion (outline-next-heading) (point))))
8824 (if (or (re-search-forward org-ts-regexp end t)
8825 (re-search-forward org-ts-regexp-both end t))
8826 (org-time-string-to-seconds (match-string 0))
8827 (float-time now))))
8828 ((= dcst ?c)
8829 (let ((end (save-excursion (outline-next-heading) (point))))
8830 (if (re-search-forward
8831 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8832 end t)
8833 (org-time-string-to-seconds (match-string 0))
8834 (float-time now))))
8835 ((= dcst ?s)
8836 (let ((end (save-excursion (outline-next-heading) (point))))
8837 (if (re-search-forward org-scheduled-time-regexp end t)
8838 (org-time-string-to-seconds (match-string 1))
8839 (float-time now))))
8840 ((= dcst ?d)
8841 (let ((end (save-excursion (outline-next-heading) (point))))
8842 (if (re-search-forward org-deadline-time-regexp end t)
8843 (org-time-string-to-seconds (match-string 1))
8844 (float-time now))))
8845 ((= dcst ?p)
8846 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8847 (string-to-char (match-string 2))
8848 org-default-priority))
8849 ((= dcst ?r)
8850 (or (org-entry-get nil property) ""))
8851 ((= dcst ?o)
8852 (when (looking-at org-complex-heading-regexp)
8853 (let* ((m (match-string 2))
8854 (s (if (member m org-done-keywords) '- '+)))
8855 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8856 ((= dcst ?f)
8857 (if getkey-func
8858 (progn
8859 (setq tmp (funcall getkey-func))
8860 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8861 tmp)
8862 (error "Invalid key function `%s'" getkey-func)))
8863 (t (error "Invalid sorting type `%c'" sorting-type))))
8865 (cond
8866 ((= dcst ?a) 'org-string-collate-lessp)
8867 ((= dcst ?f)
8868 (or compare-func
8869 (and interactive?
8870 (org-read-function
8871 (concat "Function for comparing keys "
8872 "(empty for default `sort-subr' predicate): ")
8873 'allow-empty))))
8874 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8875 (when restore-clock?
8876 (move-marker org-clock-marker
8877 (1+ (next-single-property-change
8878 start :org-clock-marker-backup)))
8879 (remove-text-properties (1- org-clock-marker) org-clock-marker
8880 '(:org-clock-marker-backup t)))))
8881 (run-hooks 'org-after-sorting-entries-or-items-hook)
8882 (message "Sorting entries...done")))
8884 (defun org-contextualize-keys (alist contexts)
8885 "Return valid elements in ALIST depending on CONTEXTS.
8887 `org-agenda-custom-commands' or `org-capture-templates' are the
8888 values used for ALIST, and `org-agenda-custom-commands-contexts'
8889 or `org-capture-templates-contexts' are the associated contexts
8890 definitions."
8891 (let ((contexts
8892 ;; normalize contexts
8893 (mapcar
8894 (lambda(c) (cond ((listp (cadr c))
8895 (list (car c) (car c) (nth 1 c)))
8896 ((string= "" (cadr c))
8897 (list (car c) (car c) (nth 2 c)))
8898 (t c)))
8899 contexts))
8900 (a alist) r s)
8901 ;; loop over all commands or templates
8902 (dolist (c a)
8903 (let (vrules repl)
8904 (cond
8905 ((not (assoc (car c) contexts))
8906 (push c r))
8907 ((and (assoc (car c) contexts)
8908 (setq vrules (org-contextualize-validate-key
8909 (car c) contexts)))
8910 (mapc (lambda (vr)
8911 (unless (equal (car vr) (cadr vr))
8912 (setq repl vr)))
8913 vrules)
8914 (if (not repl) (push c r)
8915 (push (cadr repl) s)
8916 (push
8917 (cons (car c)
8918 (cdr (or (assoc (cadr repl) alist)
8919 (error "Undefined key `%s' as contextual replacement for `%s'"
8920 (cadr repl) (car c)))))
8921 r))))))
8922 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8923 (delq
8925 (delete-dups
8926 (mapcar (lambda (x)
8927 (let ((tpl (car x)))
8928 (unless (delq
8930 (mapcar (lambda (y)
8931 (equal y tpl))
8933 x)))
8934 (reverse r))))))
8936 (defun org-contextualize-validate-key (key contexts)
8937 "Check CONTEXTS for agenda or capture KEY."
8938 (let (res)
8939 (dolist (r contexts)
8940 (dolist (rr (car (last r)))
8941 (when
8942 (and (equal key (car r))
8943 (if (functionp rr) (funcall rr)
8944 (or (and (eq (car rr) 'in-file)
8945 (buffer-file-name)
8946 (string-match (cdr rr) (buffer-file-name)))
8947 (and (eq (car rr) 'in-mode)
8948 (string-match (cdr rr) (symbol-name major-mode)))
8949 (and (eq (car rr) 'in-buffer)
8950 (string-match (cdr rr) (buffer-name)))
8951 (when (and (eq (car rr) 'not-in-file)
8952 (buffer-file-name))
8953 (not (string-match (cdr rr) (buffer-file-name))))
8954 (when (eq (car rr) 'not-in-mode)
8955 (not (string-match (cdr rr) (symbol-name major-mode))))
8956 (when (eq (car rr) 'not-in-buffer)
8957 (not (string-match (cdr rr) (buffer-name)))))))
8958 (push r res))))
8959 (delete-dups (delq nil res))))
8961 ;; Defined to provide a value for defcustom, since there is no
8962 ;; string-collate-greaterp in Emacs.
8963 (defun org-string-collate-greaterp (s1 s2)
8964 "Return non-nil if S1 is greater than S2 in collation order."
8965 (not (org-string-collate-lessp s1 s2)))
8967 ;;;###autoload
8968 (defun org-run-like-in-org-mode (cmd)
8969 "Run a command, pretending that the current buffer is in Org mode.
8970 This will temporarily bind local variables that are typically bound in
8971 Org mode to the values they have in Org mode, and then interactively
8972 call CMD."
8973 (org-load-modules-maybe)
8974 (let (binds)
8975 (dolist (var (org-get-local-variables))
8976 (when (or (not (boundp (car var)))
8977 (eq (symbol-value (car var))
8978 (default-value (car var))))
8979 (push (list (car var) `(quote ,(cadr var))) binds)))
8980 (eval `(let ,binds
8981 (call-interactively (quote ,cmd))))))
8983 (defun org-get-category (&optional pos force-refresh)
8984 "Get the category applying to position POS."
8985 (save-match-data
8986 (when force-refresh (org-refresh-category-properties))
8987 (let ((pos (or pos (point))))
8988 (or (get-text-property pos 'org-category)
8989 (progn (org-refresh-category-properties)
8990 (get-text-property pos 'org-category))))))
8992 ;;; Refresh properties
8994 (defun org-refresh-properties (dprop tprop)
8995 "Refresh buffer text properties.
8996 DPROP is the drawer property and TPROP is either the
8997 corresponding text property to set, or an alist with each element
8998 being a text property (as a symbol) and a function to apply to
8999 the value of the drawer property."
9000 (let* ((case-fold-search t)
9001 (inhibit-read-only t)
9002 (inherit? (org-property-inherit-p dprop))
9003 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9004 (global (and inherit? (org--property-global-value dprop nil))))
9005 (with-silent-modifications
9006 (org-with-point-at 1
9007 ;; Set global values (e.g., values defined through
9008 ;; "#+PROPERTY:" keywords) to the whole buffer.
9009 (when global (put-text-property (point-min) (point-max) tprop global))
9010 ;; Set local values.
9011 (while (re-search-forward property-re nil t)
9012 (when (org-at-property-p)
9013 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9014 (outline-next-heading))))))
9016 (defun org-refresh-property (tprop p &optional inherit)
9017 "Refresh the buffer text property TPROP from the drawer property P.
9018 The refresh happens only for the current headline, or the whole
9019 sub-tree if optional argument INHERIT is non-nil."
9020 (unless (org-before-first-heading-p)
9021 (save-excursion
9022 (org-back-to-heading t)
9023 (let ((start (point))
9024 (end (save-excursion
9025 (if inherit (org-end-of-subtree t t)
9026 (or (outline-next-heading) (point-max))))))
9027 (if (symbolp tprop)
9028 ;; TPROP is a text property symbol.
9029 (put-text-property start end tprop p)
9030 ;; TPROP is an alist with (property . function) elements.
9031 (pcase-dolist (`(,prop . ,f) tprop)
9032 (put-text-property start end prop (funcall f p))))))))
9034 (defun org-refresh-category-properties ()
9035 "Refresh category text properties in the buffer."
9036 (let ((case-fold-search t)
9037 (inhibit-read-only t)
9038 (default-category
9039 (cond ((null org-category)
9040 (if buffer-file-name
9041 (file-name-sans-extension
9042 (file-name-nondirectory buffer-file-name))
9043 "???"))
9044 ((symbolp org-category) (symbol-name org-category))
9045 (t org-category))))
9046 (with-silent-modifications
9047 (org-with-wide-buffer
9048 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9049 ;; This is the default category for the buffer. If none is
9050 ;; found, fall-back to `org-category' or buffer file name.
9051 (put-text-property
9052 (point-min) (point-max)
9053 'org-category
9054 (catch 'buffer-category
9055 (goto-char (point-max))
9056 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9057 (let ((element (org-element-at-point)))
9058 (when (eq (org-element-type element) 'keyword)
9059 (throw 'buffer-category
9060 (org-element-property :value element)))))
9061 default-category))
9062 ;; Set sub-tree specific categories.
9063 (goto-char (point-min))
9064 (let ((regexp (org-re-property "CATEGORY")))
9065 (while (re-search-forward regexp nil t)
9066 (let ((value (match-string-no-properties 3)))
9067 (when (org-at-property-p)
9068 (put-text-property
9069 (save-excursion (org-back-to-heading t) (point))
9070 (save-excursion (org-end-of-subtree t t) (point))
9071 'org-category
9072 value)))))))))
9074 (defun org-refresh-stats-properties ()
9075 "Refresh stats text properties in the buffer."
9076 (with-silent-modifications
9077 (org-with-point-at 1
9078 (let ((regexp (concat org-outline-regexp-bol
9079 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9080 (while (re-search-forward regexp nil t)
9081 (let* ((numerator (string-to-number (match-string 1)))
9082 (denominator (and (match-end 2)
9083 (string-to-number (match-string 2))))
9084 (stats (cond ((not denominator) numerator) ;percent
9085 ((= denominator 0) 0)
9086 (t (/ (* numerator 100) denominator)))))
9087 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9088 'org-stats stats)))))))
9090 (defun org-refresh-effort-properties ()
9091 "Refresh effort properties"
9092 (org-refresh-properties
9093 org-effort-property
9094 '((effort . identity)
9095 (effort-minutes . org-duration-to-minutes))))
9097 ;;;; Link Stuff
9099 ;;; Link abbreviations
9101 (defun org-link-expand-abbrev (link)
9102 "Apply replacements as defined in `org-link-abbrev-alist'."
9103 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9104 (let* ((key (match-string 1 link))
9105 (as (or (assoc key org-link-abbrev-alist-local)
9106 (assoc key org-link-abbrev-alist)))
9107 (tag (and (match-end 2) (match-string 3 link)))
9108 rpl)
9109 (if (not as)
9110 link
9111 (setq rpl (cdr as))
9112 (cond
9113 ((symbolp rpl) (funcall rpl tag))
9114 ((string-match "%(\\([^)]+\\))" rpl)
9115 (replace-match
9116 (save-match-data
9117 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9118 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9119 ((string-match "%h" rpl)
9120 (replace-match (url-hexify-string (or tag "")) t t rpl))
9121 (t (concat rpl tag)))))
9122 link))
9124 ;;; Storing and inserting links
9126 (defvar org-insert-link-history nil
9127 "Minibuffer history for links inserted with `org-insert-link'.")
9129 (defvar org-stored-links nil
9130 "Contains the links stored with `org-store-link'.")
9132 (defvar org-store-link-plist nil
9133 "Plist with info about the most recently link created with `org-store-link'.")
9135 (defun org-store-link-functions ()
9136 "Return a list of functions that are called to create and store a link.
9137 The functions defined in the :store property of
9138 `org-link-parameters'.
9140 Each function will be called in turn until one returns a non-nil
9141 value. Each function should check if it is responsible for
9142 creating this link (for example by looking at the major mode).
9143 If not, it must exit and return nil. If yes, it should return
9144 a non-nil value after calling `org-store-link-props' with a list
9145 of properties and values. Special properties are:
9147 :type The link prefix, like \"http\". This must be given.
9148 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9149 This is obligatory as well.
9150 :description Optional default description for the second pair
9151 of brackets in an Org mode link. The user can still change
9152 this when inserting this link into an Org mode buffer.
9154 In addition to these, any additional properties can be specified
9155 and then used in capture templates."
9156 (cl-loop for link in org-link-parameters
9157 with store-func
9158 do (setq store-func (org-link-get-parameter (car link) :store))
9159 if store-func
9160 collect store-func))
9162 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9163 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9165 ;;;###autoload
9166 (defun org-store-link (arg &optional interactive?)
9167 "Store an org-link to the current location.
9168 \\<org-mode-map>
9169 This link is added to `org-stored-links' and can later be inserted
9170 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9172 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9173 A single
9174 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9175 `org-gnus-prefer-web-links' for links to Usenet articles.
9177 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9178 skipping storing functions that are not
9179 part of Org core.
9181 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9182 prefix ARG forces storing a link for each line in the
9183 active region.
9185 Assume the function is called interactively if INTERACTIVE? is
9186 non-nil."
9187 (interactive "P\np")
9188 (org-load-modules-maybe)
9189 (if (and (equal arg '(64)) (org-region-active-p))
9190 (save-excursion
9191 (let ((end (region-end)))
9192 (goto-char (region-beginning))
9193 (set-mark (point))
9194 (while (< (point-at-eol) end)
9195 (move-end-of-line 1) (activate-mark)
9196 (let (current-prefix-arg)
9197 (call-interactively 'org-store-link))
9198 (move-beginning-of-line 2)
9199 (set-mark (point)))))
9200 (setq org-store-link-plist nil)
9201 (let (link cpltxt desc description search txt custom-id agenda-link)
9202 (cond
9203 ;; Store a link using an external link type, if any function is
9204 ;; available. If more than one can generate a link from current
9205 ;; location, ask which one to use.
9206 ((and (not (equal arg '(16)))
9207 (let ((results-alist nil))
9208 (dolist (f (org-store-link-functions))
9209 (when (funcall f)
9210 ;; XXX: return value is not link's plist, so we
9211 ;; store the new value before it is modified. It
9212 ;; would be cleaner to ask store link functions to
9213 ;; return the plist instead.
9214 (push (cons f (copy-sequence org-store-link-plist))
9215 results-alist)))
9216 (pcase results-alist
9217 (`nil nil)
9218 (`((,_ . ,_)) t) ;single choice: nothing to do
9219 (`((,name . ,_) . ,_)
9220 ;; Reinstate link plist associated to the chosen
9221 ;; function.
9222 (apply #'org-store-link-props
9223 (cdr (assoc-string
9224 (completing-read
9225 "Which function for creating the link? "
9226 (mapcar #'car results-alist)
9227 nil t (symbol-name name))
9228 results-alist)))
9229 t))))
9230 (setq link (plist-get org-store-link-plist :link))
9231 (setq desc (or (plist-get org-store-link-plist :description)
9232 link)))
9234 ;; Store a link from a source code buffer.
9235 ((org-src-edit-buffer-p)
9236 (let ((coderef-format (org-src-coderef-format)))
9237 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9238 (setq link (format "(%s)" (match-string-no-properties 3))))
9239 (interactive?
9240 (let ((label (read-string "Code line label: ")))
9241 (end-of-line)
9242 (setq link (format coderef-format label))
9243 (let ((gc (- 79 (length link))))
9244 (if (< (current-column) gc)
9245 (org-move-to-column gc t)
9246 (insert " ")))
9247 (insert link)
9248 (setq link (concat "(" label ")"))
9249 (setq desc nil)))
9250 (t (setq link nil)))))
9252 ;; We are in the agenda, link to referenced location
9253 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9254 (let ((m (or (get-text-property (point) 'org-hd-marker)
9255 (get-text-property (point) 'org-marker))))
9256 (when m
9257 (org-with-point-at m
9258 (setq agenda-link (org-store-link nil interactive?))))))
9260 ((eq major-mode 'calendar-mode)
9261 (let ((cd (calendar-cursor-to-date)))
9262 (setq link
9263 (format-time-string
9264 (car org-time-stamp-formats)
9265 (apply 'encode-time
9266 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9267 nil nil nil))))
9268 (org-store-link-props :type "calendar" :date cd)))
9270 ((eq major-mode 'help-mode)
9271 (setq link (concat "help:" (save-excursion
9272 (goto-char (point-min))
9273 (looking-at "^[^ ]+")
9274 (match-string 0))))
9275 (org-store-link-props :type "help"))
9277 ((eq major-mode 'w3-mode)
9278 (setq cpltxt (if (and (buffer-name)
9279 (not (string-match "Untitled" (buffer-name))))
9280 (buffer-name)
9281 (url-view-url t))
9282 link (url-view-url t))
9283 (org-store-link-props :type "w3" :url (url-view-url t)))
9285 ((eq major-mode 'image-mode)
9286 (setq cpltxt (concat "file:"
9287 (abbreviate-file-name buffer-file-name))
9288 link cpltxt)
9289 (org-store-link-props :type "image" :file buffer-file-name))
9291 ;; In dired, store a link to the file of the current line
9292 ((derived-mode-p 'dired-mode)
9293 (let ((file (dired-get-filename nil t)))
9294 (setq file (if file
9295 (abbreviate-file-name
9296 (expand-file-name (dired-get-filename nil t)))
9297 ;; otherwise, no file so use current directory.
9298 default-directory))
9299 (setq cpltxt (concat "file:" file)
9300 link cpltxt)))
9302 ((setq search (run-hook-with-args-until-success
9303 'org-create-file-search-functions))
9304 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9305 "::" search))
9306 (setq cpltxt (or description link)))
9308 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9309 (org-with-limited-levels
9310 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9311 (cond
9312 ;; Store a link using the target at point
9313 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9314 (setq cpltxt
9315 (concat "file:"
9316 (abbreviate-file-name
9317 (buffer-file-name (buffer-base-buffer)))
9318 "::" (match-string 1))
9319 link cpltxt))
9320 ((and (featurep 'org-id)
9321 (or (eq org-id-link-to-org-use-id t)
9322 (and interactive?
9323 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9324 (and (eq org-id-link-to-org-use-id
9325 'create-if-interactive-and-no-custom-id)
9326 (not custom-id))))
9327 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9328 ;; Store a link using the ID at point
9329 (setq link (condition-case nil
9330 (prog1 (org-id-store-link)
9331 (setq desc (or (plist-get org-store-link-plist
9332 :description)
9333 "")))
9334 (error
9335 ;; Probably before first headline, link only to file
9336 (concat "file:"
9337 (abbreviate-file-name
9338 (buffer-file-name (buffer-base-buffer))))))))
9340 ;; Just link to current headline
9341 (setq cpltxt (concat "file:"
9342 (abbreviate-file-name
9343 (buffer-file-name (buffer-base-buffer)))))
9344 ;; Add a context search string
9345 (when (org-xor org-context-in-file-links
9346 (equal arg '(4)))
9347 (let* ((element (org-element-at-point))
9348 (name (org-element-property :name element)))
9349 (setq txt (cond
9350 ((org-at-heading-p) nil)
9351 (name)
9352 ((org-region-active-p)
9353 (buffer-substring (region-beginning) (region-end)))))
9354 (when (or (null txt) (string-match "\\S-" txt))
9355 (setq cpltxt
9356 (concat cpltxt "::"
9357 (condition-case nil
9358 (org-make-org-heading-search-string txt)
9359 (error "")))
9360 desc (or name
9361 (nth 4 (ignore-errors (org-heading-components)))
9362 "NONE")))))
9363 (when (string-match "::\\'" cpltxt)
9364 (setq cpltxt (substring cpltxt 0 -2)))
9365 (setq link cpltxt)))))
9367 ((buffer-file-name (buffer-base-buffer))
9368 ;; Just link to this file here.
9369 (setq cpltxt (concat "file:"
9370 (abbreviate-file-name
9371 (buffer-file-name (buffer-base-buffer)))))
9372 ;; Add a context string.
9373 (when (org-xor org-context-in-file-links
9374 (equal arg '(4)))
9375 (setq txt (if (org-region-active-p)
9376 (buffer-substring (region-beginning) (region-end))
9377 (buffer-substring (point-at-bol) (point-at-eol))))
9378 ;; Only use search option if there is some text.
9379 (when (string-match "\\S-" txt)
9380 (setq cpltxt
9381 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9382 desc "NONE")))
9383 (setq link cpltxt))
9385 (interactive?
9386 (user-error "No method for storing a link from this buffer"))
9388 (t (setq link nil)))
9390 ;; We're done setting link and desc, clean up
9391 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9392 (setq link (or link cpltxt)
9393 desc (or desc cpltxt))
9394 (cond ((not desc))
9395 ((equal desc "NONE") (setq desc nil))
9396 (t (setq desc
9397 (replace-regexp-in-string
9398 org-bracket-link-analytic-regexp
9399 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9400 desc))))
9401 ;; Return the link
9402 (if (not (and interactive? link))
9403 (or agenda-link (and link (org-make-link-string link desc)))
9404 (push (list link desc) org-stored-links)
9405 (message "Stored: %s" (or desc link))
9406 (when custom-id
9407 (setq link (concat "file:" (abbreviate-file-name
9408 (buffer-file-name)) "::#" custom-id))
9409 (push (list link desc) org-stored-links))
9410 (car org-stored-links)))))
9412 (defun org-store-link-props (&rest plist)
9413 "Store link properties.
9414 The properties are pre-processed by extracting names, addresses
9415 and dates."
9416 (let ((x (plist-get plist :from)))
9417 (when x
9418 (let ((adr (mail-extract-address-components x)))
9419 (setq plist (plist-put plist :fromname (car adr)))
9420 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9421 (let ((x (plist-get plist :to)))
9422 (when x
9423 (let ((adr (mail-extract-address-components x)))
9424 (setq plist (plist-put plist :toname (car adr)))
9425 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9426 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9427 (when x
9428 (setq plist (plist-put plist :date-timestamp
9429 (format-time-string
9430 (org-time-stamp-format t) x)))
9431 (setq plist (plist-put plist :date-timestamp-inactive
9432 (format-time-string
9433 (org-time-stamp-format t t) x)))))
9434 (let ((from (plist-get plist :from))
9435 (to (plist-get plist :to)))
9436 (when (and from to org-from-is-user-regexp)
9437 (setq plist
9438 (plist-put plist :fromto
9439 (if (string-match org-from-is-user-regexp from)
9440 (concat "to %t")
9441 (concat "from %f"))))))
9442 (setq org-store-link-plist plist))
9444 (defun org-add-link-props (&rest plist)
9445 "Add these properties to the link property list."
9446 (let (key value)
9447 (while plist
9448 (setq key (pop plist) value (pop plist))
9449 (setq org-store-link-plist
9450 (plist-put org-store-link-plist key value)))))
9452 (defun org-email-link-description (&optional fmt)
9453 "Return the description part of an email link.
9454 This takes information from `org-store-link-plist' and formats it
9455 according to FMT (default from `org-email-link-description-format')."
9456 (setq fmt (or fmt org-email-link-description-format))
9457 (let* ((p org-store-link-plist)
9458 (to (plist-get p :toaddress))
9459 (from (plist-get p :fromaddress))
9460 (table
9461 (list
9462 (cons "%c" (plist-get p :fromto))
9463 (cons "%F" (plist-get p :from))
9464 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9465 (cons "%T" (plist-get p :to))
9466 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9467 (cons "%s" (plist-get p :subject))
9468 (cons "%d" (plist-get p :date))
9469 (cons "%m" (plist-get p :message-id)))))
9470 (when (string-match "%c" fmt)
9471 ;; Check if the user wrote this message
9472 (if (and org-from-is-user-regexp from to
9473 (save-match-data (string-match org-from-is-user-regexp from)))
9474 (setq fmt (replace-match "to %t" t t fmt))
9475 (setq fmt (replace-match "from %f" t t fmt))))
9476 (org-replace-escapes fmt table)))
9478 (defun org-make-org-heading-search-string (&optional string)
9479 "Make search string for the current headline or STRING."
9480 (let ((s (or string
9481 (and (derived-mode-p 'org-mode)
9482 (save-excursion
9483 (org-back-to-heading t)
9484 (org-element-property :raw-value (org-element-at-point))))))
9485 (lines org-context-in-file-links))
9486 (unless string (setq s (concat "*" s))) ;Add * for headlines
9487 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9488 (when (and string (integerp lines) (> lines 0))
9489 (let ((slines (org-split-string s "\n")))
9490 (when (< lines (length slines))
9491 (setq s (mapconcat
9492 'identity
9493 (reverse (nthcdr (- (length slines) lines)
9494 (reverse slines))) "\n")))))
9495 (mapconcat #'identity (split-string s) " ")))
9497 (defconst org-link-escape-chars
9498 ;;%20 %5B %5D %25
9499 '(?\s ?\[ ?\] ?%)
9500 "List of characters that should be escaped in a link when stored to Org.
9501 This is the list that is used for internal purposes.")
9503 (defun org-make-link-string (link &optional description)
9504 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9505 (unless (org-string-nw-p link) (error "Empty link"))
9506 (let ((uri (cond ((string-match org-link-types-re link)
9507 (concat (match-string 1 link)
9508 (org-link-escape (substring link (match-end 1)))))
9509 ((or (file-name-absolute-p link)
9510 (string-match-p "\\`\\.\\.?/" link))
9511 (org-link-escape link))
9512 ;; For readability, do not encode space characters
9513 ;; in fuzzy links.
9514 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9515 (description
9516 (and (org-string-nw-p description)
9517 ;; Remove brackets from description, as they are fatal.
9518 (replace-regexp-in-string
9519 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9520 (org-trim description)))))
9521 (format "[[%s]%s]"
9523 (if description (format "[%s]" description) ""))))
9525 (defun org-link-escape (text &optional table merge)
9526 "Return percent escaped representation of TEXT.
9527 TEXT is a string with the text to escape.
9528 Optional argument TABLE is a list with characters that should be
9529 escaped. When nil, `org-link-escape-chars' is used.
9530 If optional argument MERGE is set, merge TABLE into
9531 `org-link-escape-chars'."
9532 (let ((characters-to-encode
9533 (cond ((null table) org-link-escape-chars)
9534 (merge (append org-link-escape-chars table))
9535 (t table))))
9536 (mapconcat
9537 (lambda (c)
9538 (if (or (memq c characters-to-encode)
9539 (and org-url-hexify-p (or (< c 32) (> c 126))))
9540 (mapconcat (lambda (e) (format "%%%.2X" e))
9541 (or (encode-coding-char c 'utf-8)
9542 (error "Unable to percent escape character: %c" c))
9544 (char-to-string c)))
9545 text "")))
9547 (defun org-link-unescape (str)
9548 "Unhex hexified Unicode parts in string STR.
9549 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9550 reciprocal of `org-link-escape', which see."
9551 (if (org-string-nw-p str)
9552 (replace-regexp-in-string
9553 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9554 str))
9556 (defun org-link-unescape-compound (hex)
9557 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9558 Note: this function also decodes single byte encodings like
9559 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9560 (save-match-data
9561 (let* ((bytes (cdr (split-string hex "%")))
9562 (ret "")
9563 (eat 0)
9564 (sum 0))
9565 (while bytes
9566 (let* ((val (string-to-number (pop bytes) 16))
9567 (shift-xor
9568 (if (= 0 eat)
9569 (cond
9570 ((>= val 252) (cons 6 252))
9571 ((>= val 248) (cons 5 248))
9572 ((>= val 240) (cons 4 240))
9573 ((>= val 224) (cons 3 224))
9574 ((>= val 192) (cons 2 192))
9575 (t (cons 0 0)))
9576 (cons 6 128))))
9577 (when (>= val 192) (setq eat (car shift-xor)))
9578 (setq val (logxor val (cdr shift-xor)))
9579 (setq sum (+ (lsh sum (car shift-xor)) val))
9580 (when (> eat 0) (setq eat (- eat 1)))
9581 (cond
9582 ((= 0 eat) ;multi byte
9583 (setq ret (concat ret (char-to-string sum)))
9584 (setq sum 0))
9585 ((not bytes) ; single byte(s)
9586 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9587 ret)))
9589 (defun org-link-unescape-single-byte-sequence (hex)
9590 "Unhexify hex-encoded single byte character sequences."
9591 (mapconcat (lambda (byte)
9592 (char-to-string (string-to-number byte 16)))
9593 (cdr (split-string hex "%")) ""))
9595 (defun org-fixup-message-id-for-http (s)
9596 "Replace special characters in a message id, so it can be used in an http query."
9597 (when (string-match "%" s)
9598 (setq s (mapconcat (lambda (c)
9599 (if (eq c ?%)
9600 "%25"
9601 (char-to-string c)))
9602 s "")))
9603 (while (string-match "<" s)
9604 (setq s (replace-match "%3C" t t s)))
9605 (while (string-match ">" s)
9606 (setq s (replace-match "%3E" t t s)))
9607 (while (string-match "@" s)
9608 (setq s (replace-match "%40" t t s)))
9611 (defun org-link-prettify (link)
9612 "Return a human-readable representation of LINK.
9613 The car of LINK must be a raw link.
9614 The cdr of LINK must be either a link description or nil."
9615 (let ((desc (or (cadr link) "<no description>")))
9616 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9617 "<" (car link) ">")))
9619 ;;;###autoload
9620 (defun org-insert-link-global ()
9621 "Insert a link like Org mode does.
9622 This command can be called in any mode to insert a link in Org syntax."
9623 (interactive)
9624 (org-load-modules-maybe)
9625 (org-run-like-in-org-mode 'org-insert-link))
9627 (defun org-insert-all-links (arg &optional pre post)
9628 "Insert all links in `org-stored-links'.
9629 When a universal prefix, do not delete the links from `org-stored-links'.
9630 When `ARG' is a number, insert the last N link(s).
9631 `PRE' and `POST' are optional arguments to define a string to
9632 prepend or to append."
9633 (interactive "P")
9634 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9635 (links (copy-sequence org-stored-links))
9636 (pr (or pre "- "))
9637 (po (or post "\n"))
9638 (cnt 1) l)
9639 (if (null org-stored-links)
9640 (message "No link to insert")
9641 (while (and (or (listp arg) (>= arg cnt))
9642 (setq l (if (listp arg)
9643 (pop links)
9644 (pop org-stored-links))))
9645 (setq cnt (1+ cnt))
9646 (insert pr)
9647 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9648 (insert po)))))
9650 (defun org-insert-last-stored-link (arg)
9651 "Insert the last link stored in `org-stored-links'."
9652 (interactive "p")
9653 (org-insert-all-links arg "" "\n"))
9655 (defun org-link-fontify-links-to-this-file ()
9656 "Fontify links to the current file in `org-stored-links'."
9657 (let ((f (buffer-file-name)) a b)
9658 (setq a (mapcar (lambda(l)
9659 (let ((ll (car l)))
9660 (when (and (string-match "^file:\\(.+\\)::" ll)
9661 (equal f (expand-file-name (match-string 1 ll))))
9662 ll)))
9663 org-stored-links))
9664 (when (featurep 'org-id)
9665 (setq b (mapcar (lambda(l)
9666 (let ((ll (car l)))
9667 (when (and (string-match "^id:\\(.+\\)$" ll)
9668 (equal f (expand-file-name
9669 (or (org-id-find-id-file
9670 (match-string 1 ll)) ""))))
9671 ll)))
9672 org-stored-links)))
9673 (mapcar (lambda(l)
9674 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9675 (delq nil (append a b)))))
9677 (defvar org--links-history nil)
9678 (defun org-insert-link (&optional complete-file link-location default-description)
9679 "Insert a link. At the prompt, enter the link.
9681 Completion can be used to insert any of the link protocol prefixes in use.
9683 The history can be used to select a link previously stored with
9684 `org-store-link'. When the empty string is entered (i.e. if you just
9685 press `RET' at the prompt), the link defaults to the most recently
9686 stored link. As `SPC' triggers completion in the minibuffer, you need to
9687 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9689 You will also be prompted for a description, and if one is given, it will
9690 be displayed in the buffer instead of the link.
9692 If there is already a link at point, this command will allow you to edit
9693 link and description parts.
9695 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9696 file name can be
9697 selected using completion. The path to the file will be relative to the
9698 current directory if the file is in the current directory or a subdirectory.
9699 Otherwise, the link will be the absolute path as completed in the minibuffer
9700 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9701 option `org-link-file-path-type'.
9703 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9704 absolute path even if the file is in
9705 the current directory or below.
9707 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9708 prefix negates `org-keep-stored-link-after-insertion'.
9710 If the LINK-LOCATION parameter is non-nil, this value will be used as
9711 the link location instead of reading one interactively.
9713 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9714 be used as the default description. Otherwise, if
9715 `org-make-link-description-function' is non-nil, this function
9716 will be called with the link target, and the result will be the
9717 default link description. When called non-interactivily, don't
9718 allow to edit the default description."
9719 (interactive "P")
9720 (let* ((wcf (current-window-configuration))
9721 (origbuf (current-buffer))
9722 (region (when (org-region-active-p)
9723 (buffer-substring (region-beginning) (region-end))))
9724 (remove (and region (list (region-beginning) (region-end))))
9725 (desc region)
9726 (link link-location)
9727 (abbrevs org-link-abbrev-alist-local)
9728 entry all-prefixes auto-desc)
9729 (cond
9730 (link-location) ; specified by arg, just use it.
9731 ((org-in-regexp org-bracket-link-regexp 1)
9732 ;; We do have a link at point, and we are going to edit it.
9733 (setq remove (list (match-beginning 0) (match-end 0)))
9734 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9735 (setq link (read-string "Link: "
9736 (org-link-unescape
9737 (match-string-no-properties 1)))))
9738 ((or (org-in-regexp org-angle-link-re)
9739 (org-in-regexp org-plain-link-re))
9740 ;; Convert to bracket link
9741 (setq remove (list (match-beginning 0) (match-end 0))
9742 link (read-string "Link: "
9743 (org-unbracket-string "<" ">" (match-string 0)))))
9744 ((member complete-file '((4) (16)))
9745 ;; Completing read for file names.
9746 (setq link (org-file-complete-link complete-file)))
9748 ;; Read link, with completion for stored links.
9749 (org-link-fontify-links-to-this-file)
9750 (org-switch-to-buffer-other-window "*Org Links*")
9751 (with-current-buffer "*Org Links*"
9752 (erase-buffer)
9753 (insert "Insert a link.
9754 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9755 (when org-stored-links
9756 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9757 (insert (mapconcat 'org-link-prettify
9758 (reverse org-stored-links) "\n")))
9759 (goto-char (point-min)))
9760 (let ((cw (selected-window)))
9761 (select-window (get-buffer-window "*Org Links*" 'visible))
9762 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9763 (unless (pos-visible-in-window-p (point-max))
9764 (org-fit-window-to-buffer))
9765 (and (window-live-p cw) (select-window cw)))
9766 (setq all-prefixes (append (mapcar 'car abbrevs)
9767 (mapcar 'car org-link-abbrev-alist)
9768 (org-link-types)))
9769 (unwind-protect
9770 ;; Fake a link history, containing the stored links.
9771 (let ((org--links-history
9772 (append (mapcar #'car org-stored-links)
9773 org-insert-link-history)))
9774 (setq link
9775 (org-completing-read
9776 "Link: "
9777 (append
9778 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9779 (mapcar #'car org-stored-links))
9780 nil nil nil
9781 'org--links-history
9782 (caar org-stored-links)))
9783 (unless (org-string-nw-p link) (user-error "No link selected"))
9784 (dolist (l org-stored-links)
9785 (when (equal link (cadr l))
9786 (setq link (car l))
9787 (setq auto-desc t)))
9788 (when (or (member link all-prefixes)
9789 (and (equal ":" (substring link -1))
9790 (member (substring link 0 -1) all-prefixes)
9791 (setq link (substring link 0 -1))))
9792 (setq link (with-current-buffer origbuf
9793 (org-link-try-special-completion link)))))
9794 (set-window-configuration wcf)
9795 (kill-buffer "*Org Links*"))
9796 (setq entry (assoc link org-stored-links))
9797 (or entry (push link org-insert-link-history))
9798 (setq desc (or desc (nth 1 entry)))))
9800 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9801 (not org-keep-stored-link-after-insertion))
9802 (setq org-stored-links (delq (assoc link org-stored-links)
9803 org-stored-links)))
9805 (when (and (string-match org-plain-link-re link)
9806 (not (string-match org-ts-regexp link)))
9807 ;; URL-like link, normalize the use of angular brackets.
9808 (setq link (org-unbracket-string "<" ">" link)))
9810 ;; Check if we are linking to the current file with a search
9811 ;; option If yes, simplify the link by using only the search
9812 ;; option.
9813 (when (and buffer-file-name
9814 (let ((case-fold-search nil))
9815 (string-match "\\`file:\\(.+?\\)::" link)))
9816 (let ((path (match-string-no-properties 1 link))
9817 (search (substring-no-properties link (match-end 0))))
9818 (save-match-data
9819 (when (equal (file-truename buffer-file-name) (file-truename path))
9820 ;; We are linking to this same file, with a search option
9821 (setq link search)))))
9823 ;; Check if we can/should use a relative path. If yes, simplify
9824 ;; the link.
9825 (let ((case-fold-search nil))
9826 (when (string-match "\\`\\(file\\|docview\\):" link)
9827 (let* ((type (match-string-no-properties 0 link))
9828 (path-start (match-end 0))
9829 (search (and (string-match "::\\(.*\\)\\'" link)
9830 (match-string 1 link)))
9831 (path
9832 (if search
9833 (substring-no-properties
9834 link path-start (match-beginning 0))
9835 (substring-no-properties link (match-end 0))))
9836 (origpath path))
9837 (cond
9838 ((or (eq org-link-file-path-type 'absolute)
9839 (equal complete-file '(16)))
9840 (setq path (abbreviate-file-name (expand-file-name path))))
9841 ((eq org-link-file-path-type 'noabbrev)
9842 (setq path (expand-file-name path)))
9843 ((eq org-link-file-path-type 'relative)
9844 (setq path (file-relative-name path)))
9846 (save-match-data
9847 (if (string-match (concat "^" (regexp-quote
9848 (expand-file-name
9849 (file-name-as-directory
9850 default-directory))))
9851 (expand-file-name path))
9852 ;; We are linking a file with relative path name.
9853 (setq path (substring (expand-file-name path)
9854 (match-end 0)))
9855 (setq path (abbreviate-file-name (expand-file-name path)))))))
9856 (setq link (concat type path (and search (concat "::" search))))
9857 (when (equal desc origpath)
9858 (setq desc path)))))
9860 (unless auto-desc
9861 (let ((initial-input
9862 (cond
9863 (default-description)
9864 ((not org-make-link-description-function) desc)
9865 (t (condition-case nil
9866 (funcall org-make-link-description-function link desc)
9867 (error
9868 (message "Can't get link description from `%s'"
9869 (symbol-name org-make-link-description-function))
9870 (sit-for 2)
9871 nil))))))
9872 (setq desc (if (called-interactively-p 'any)
9873 (read-string "Description: " initial-input)
9874 initial-input))))
9876 (unless (string-match "\\S-" desc) (setq desc nil))
9877 (when remove (apply 'delete-region remove))
9878 (insert (org-make-link-string link desc))
9879 ;; Redisplay so as the new link has proper invisible characters.
9880 (sit-for 0)))
9882 (defun org-link-try-special-completion (type)
9883 "If there is completion support for link type TYPE, offer it."
9884 (let ((fun (org-link-get-parameter type :complete)))
9885 (if (functionp fun)
9886 (funcall fun)
9887 (read-string "Link (no completion support): " (concat type ":")))))
9889 (defun org-file-complete-link (&optional arg)
9890 "Create a file link using completion."
9891 (let ((file (read-file-name "File: "))
9892 (pwd (file-name-as-directory (expand-file-name ".")))
9893 (pwd1 (file-name-as-directory (abbreviate-file-name
9894 (expand-file-name ".")))))
9895 (cond ((equal arg '(16))
9896 (concat "file:"
9897 (abbreviate-file-name (expand-file-name file))))
9898 ((string-match
9899 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9900 (concat "file:" (match-string 1 file)))
9901 ((string-match
9902 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9903 (expand-file-name file))
9904 (concat "file:"
9905 (match-string 1 (expand-file-name file))))
9906 (t (concat "file:" file)))))
9909 ;;; Opening/following a link
9911 (defvar org-link-search-failed nil)
9913 (defvar org-open-link-functions nil
9914 "Hook for functions finding a plain text link.
9915 These functions must take a single argument, the link content.
9916 They will be called for links that look like [[link text][description]]
9917 when LINK TEXT does not have a protocol like \"http:\" and does not look
9918 like a filename (e.g. \"./blue.png\").
9920 These functions will be called *before* Org attempts to resolve the
9921 link by doing text searches in the current buffer - so if you want a
9922 link \"[[target]]\" to still find \"<<target>>\", your function should
9923 handle this as a special case.
9925 When the function does handle the link, it must return a non-nil value.
9926 If it decides that it is not responsible for this link, it must return
9927 nil to indicate that that Org can continue with other options like
9928 exact and fuzzy text search.")
9930 (defun org-next-link (&optional search-backward)
9931 "Move forward to the next link.
9932 If the link is in hidden text, expose it."
9933 (interactive "P")
9934 (when (and org-link-search-failed (eq this-command last-command))
9935 (goto-char (point-min))
9936 (message "Link search wrapped back to beginning of buffer"))
9937 (setq org-link-search-failed nil)
9938 (let* ((pos (point))
9939 (ct (org-context))
9940 (a (assq :link ct))
9941 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9942 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9943 ((looking-at org-any-link-re)
9944 ;; Don't stay stuck at link without an org-link face
9945 (forward-char (if search-backward -1 1))))
9946 (if (funcall srch-fun org-any-link-re nil t)
9947 (progn
9948 (goto-char (match-beginning 0))
9949 (when (org-invisible-p) (org-show-context)))
9950 (goto-char pos)
9951 (setq org-link-search-failed t)
9952 (message "No further link found"))))
9954 (defun org-previous-link ()
9955 "Move backward to the previous link.
9956 If the link is in hidden text, expose it."
9957 (interactive)
9958 (org-next-link t))
9960 (defun org-translate-link (s)
9961 "Translate a link string if a translation function has been defined."
9962 (with-temp-buffer
9963 (insert (org-trim s))
9964 (org-trim (org-element-interpret-data (org-element-context)))))
9966 (defun org-translate-link-from-planner (type path)
9967 "Translate a link from Emacs Planner syntax so that Org can follow it.
9968 This is still an experimental function, your mileage may vary."
9969 (cond
9970 ((member type '("http" "https" "news" "ftp"))
9971 ;; standard Internet links are the same.
9972 nil)
9973 ((and (equal type "irc") (string-match "^//" path))
9974 ;; Planner has two / at the beginning of an irc link, we have 1.
9975 ;; We should have zero, actually....
9976 (setq path (substring path 1)))
9977 ((and (equal type "lisp") (string-match "^/" path))
9978 ;; Planner has a slash, we do not.
9979 (setq type "elisp" path (substring path 1)))
9980 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9981 ;; A typical message link. Planner has the id after the final slash,
9982 ;; we separate it with a hash mark
9983 (setq path (concat (match-string 1 path) "#"
9984 (org-unbracket-string "<" ">" (match-string 2 path))))))
9985 (cons type path))
9987 (defun org-find-file-at-mouse (ev)
9988 "Open file link or URL at mouse."
9989 (interactive "e")
9990 (mouse-set-point ev)
9991 (org-open-at-point 'in-emacs))
9993 (defun org-open-at-mouse (ev)
9994 "Open file link or URL at mouse.
9995 See the docstring of `org-open-file' for details."
9996 (interactive "e")
9997 (mouse-set-point ev)
9998 (when (eq major-mode 'org-agenda-mode)
9999 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10000 (org-open-at-point))
10002 (defvar org-window-config-before-follow-link nil
10003 "The window configuration before following a link.
10004 This is saved in case the need arises to restore it.")
10006 ;;;###autoload
10007 (defun org-open-at-point-global ()
10008 "Follow a link or a time-stamp like Org mode does.
10009 Also follow links and emails as seen by `thing-at-point'.
10010 This command can be called in any mode to follow an external
10011 link or a time-stamp that has Org mode syntax. Its behavior
10012 is undefined when called on internal links like fuzzy links.
10013 Raise a user error when there is nothing to follow."
10014 (interactive)
10015 (let ((tap-url (thing-at-point 'url))
10016 (tap-email (thing-at-point 'email)))
10017 (cond ((org-in-regexp org-any-link-re)
10018 (org-open-link-from-string (match-string-no-properties 0)))
10019 ((or (org-in-regexp org-ts-regexp-both nil t)
10020 (org-in-regexp org-tsr-regexp-both nil t))
10021 (org-follow-timestamp-link))
10022 (tap-url (org-open-link-from-string tap-url))
10023 (tap-email (org-open-link-from-string
10024 (concat "mailto:" tap-email)))
10025 (t (user-error "No link found")))))
10027 ;;;###autoload
10028 (defun org-open-link-from-string (s &optional arg reference-buffer)
10029 "Open a link in the string S, as if it was in Org mode."
10030 (interactive "sLink: \nP")
10031 (let ((reference-buffer (or reference-buffer (current-buffer))))
10032 (with-temp-buffer
10033 (let ((org-inhibit-startup (not reference-buffer)))
10034 (org-mode)
10035 (insert s)
10036 (goto-char (point-min))
10037 (when reference-buffer
10038 (setq org-link-abbrev-alist-local
10039 (with-current-buffer reference-buffer
10040 org-link-abbrev-alist-local)))
10041 (org-open-at-point arg reference-buffer)))))
10043 (defvar org-open-at-point-functions nil
10044 "Hook that is run when following a link at point.
10046 Functions in this hook must return t if they identify and follow
10047 a link at point. If they don't find anything interesting at point,
10048 they must return nil.")
10050 (defvar org-link-search-inhibit-query nil)
10051 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10052 (defun org--open-doi-link (path)
10053 "Open a \"doi\" type link.
10054 PATH is a the path to search for, as a string."
10055 (browse-url (url-encode-url (concat org-doi-server-url path))))
10057 (defun org--open-elisp-link (path)
10058 "Open a \"elisp\" type link.
10059 PATH is the sexp to evaluate, as a string."
10060 (let ((cmd path))
10061 (if (or (and (org-string-nw-p
10062 org-confirm-elisp-link-not-regexp)
10063 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10064 (not org-confirm-elisp-link-function)
10065 (funcall org-confirm-elisp-link-function
10066 (format "Execute \"%s\" as elisp? "
10067 (org-add-props cmd nil 'face 'org-warning))))
10068 (message "%s => %s" cmd
10069 (if (eq (string-to-char cmd) ?\()
10070 (eval (read cmd))
10071 (call-interactively (read cmd))))
10072 (user-error "Abort"))))
10074 (defun org--open-help-link (path)
10075 "Open a \"help\" type link.
10076 PATH is a symbol name, as a string."
10077 (pcase (intern path)
10078 ((and (pred fboundp) variable) (describe-function variable))
10079 ((and (pred boundp) function) (describe-variable function))
10080 (name (user-error "Unknown function or variable: %s" name))))
10082 (defun org--open-shell-link (path)
10083 "Open a \"shell\" type link.
10084 PATH is the command to execute, as a string."
10085 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10086 (cmd path))
10087 (if (or (and (org-string-nw-p
10088 org-confirm-shell-link-not-regexp)
10089 (string-match
10090 org-confirm-shell-link-not-regexp cmd))
10091 (not org-confirm-shell-link-function)
10092 (funcall org-confirm-shell-link-function
10093 (format "Execute \"%s\" in shell? "
10094 (org-add-props cmd nil
10095 'face 'org-warning))))
10096 (progn
10097 (message "Executing %s" cmd)
10098 (shell-command cmd buf)
10099 (when (featurep 'midnight)
10100 (setq clean-buffer-list-kill-buffer-names
10101 (cons (buffer-name buf)
10102 clean-buffer-list-kill-buffer-names))))
10103 (user-error "Abort"))))
10105 (defun org-open-at-point (&optional arg reference-buffer)
10106 "Open link, timestamp, footnote or tags at point.
10108 When point is on a link, follow it. Normally, files will be
10109 opened by an appropriate application. If the optional prefix
10110 argument ARG is non-nil, Emacs will visit the file. With
10111 a double prefix argument, try to open outside of Emacs, in the
10112 application the system uses for this file type.
10114 When point is on a timestamp, open the agenda at the day
10115 specified.
10117 When point is a footnote definition, move to the first reference
10118 found. If it is on a reference, move to the associated
10119 definition.
10121 When point is on a headline, display a list of every link in the
10122 entry, so it is possible to pick one, or all, of them. If point
10123 is on a tag, call `org-tags-view' instead.
10125 When optional argument REFERENCE-BUFFER is non-nil, it should
10126 specify a buffer from where the link search should happen. This
10127 is used internally by `org-open-link-from-string'.
10129 On top of syntactically correct links, this function will also
10130 try to open links and time-stamps in comments, example
10131 blocks... i.e., whenever point is on something looking like
10132 a timestamp or a link."
10133 (interactive "P")
10134 ;; On a code block, open block's results.
10135 (unless (call-interactively 'org-babel-open-src-block-result)
10136 (org-load-modules-maybe)
10137 (setq org-window-config-before-follow-link (current-window-configuration))
10138 (org-remove-occur-highlights nil nil t)
10139 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10140 (let* ((context
10141 ;; Only consider supported types, even if they are not
10142 ;; the closest one.
10143 (org-element-lineage
10144 (org-element-context)
10145 '(clock footnote-definition footnote-reference headline
10146 inlinetask link timestamp)
10148 (type (org-element-type context))
10149 (value (org-element-property :value context)))
10150 (cond
10151 ;; On a headline or an inlinetask, but not on a timestamp,
10152 ;; a link, a footnote reference.
10153 ((memq type '(headline inlinetask))
10154 (org-match-line org-complex-heading-regexp)
10155 (if (and (match-beginning 5)
10156 (>= (point) (match-beginning 5))
10157 (< (point) (match-end 5)))
10158 ;; On tags.
10159 (org-tags-view arg (substring (match-string 5) 0 -1))
10160 ;; Not on tags.
10161 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10162 (`(nil . ,_)
10163 (require 'org-attach)
10164 (org-attach-reveal 'if-exists))
10165 (`(,links . ,links-end)
10166 (dolist (link (if (stringp links) (list links) links))
10167 (search-forward link nil links-end)
10168 (goto-char (match-beginning 0))
10169 (org-open-at-point))))))
10170 ;; On a footnote reference or at definition's label.
10171 ((or (eq type 'footnote-reference)
10172 (and (eq type 'footnote-definition)
10173 (save-excursion
10174 ;; Do not validate action when point is on the
10175 ;; spaces right after the footnote label, in
10176 ;; order to be on par with behavior on links.
10177 (skip-chars-forward " \t")
10178 (let ((begin
10179 (org-element-property :contents-begin context)))
10180 (if begin (< (point) begin)
10181 (= (org-element-property :post-affiliated context)
10182 (line-beginning-position)))))))
10183 (org-footnote-action))
10184 ;; No valid context. Ignore catch-all types like `headline'.
10185 ;; If point is on something looking like a link or
10186 ;; a time-stamp, try opening it. It may be useful in
10187 ;; comments, example blocks...
10188 ((memq type '(footnote-definition headline inlinetask nil))
10189 (call-interactively #'org-open-at-point-global))
10190 ;; On a clock line, make sure point is on the timestamp
10191 ;; before opening it.
10192 ((and (eq type 'clock)
10193 value
10194 (>= (point) (org-element-property :begin value))
10195 (<= (point) (org-element-property :end value)))
10196 (org-follow-timestamp-link))
10197 ;; Do nothing on white spaces after an object.
10198 ((>= (point)
10199 (save-excursion
10200 (goto-char (org-element-property :end context))
10201 (skip-chars-backward " \t")
10202 (point)))
10203 (user-error "No link found"))
10204 ((eq type 'timestamp) (org-follow-timestamp-link))
10205 ((eq type 'link)
10206 (let ((type (org-element-property :type context))
10207 (path (org-link-unescape (org-element-property :path context))))
10208 ;; Switch back to REFERENCE-BUFFER needed when called in
10209 ;; a temporary buffer through `org-open-link-from-string'.
10210 (with-current-buffer (or reference-buffer (current-buffer))
10211 (cond
10212 ((equal type "file")
10213 (if (string-match "[*?{]" (file-name-nondirectory path))
10214 (dired path)
10215 ;; Look into `org-link-parameters' in order to find
10216 ;; a DEDICATED-FUNCTION to open file. The function
10217 ;; will be applied on raw link instead of parsed
10218 ;; link due to the limitation in `org-add-link-type'
10219 ;; ("open" function called with a single argument).
10220 ;; If no such function is found, fallback to
10221 ;; `org-open-file'.
10222 (let* ((option (org-element-property :search-option context))
10223 (app (org-element-property :application context))
10224 (dedicated-function
10225 (org-link-get-parameter
10226 (if app (concat type "+" app) type)
10227 :follow)))
10228 (if dedicated-function
10229 (funcall dedicated-function
10230 (concat path
10231 (and option (concat "::" option))))
10232 (apply #'org-open-file
10233 path
10234 (cond (arg)
10235 ((equal app "emacs") 'emacs)
10236 ((equal app "sys") 'system))
10237 (cond ((not option) nil)
10238 ((string-match-p "\\`[0-9]+\\'" option)
10239 (list (string-to-number option)))
10240 (t (list nil
10241 (org-link-unescape option)))))))))
10242 ((functionp (org-link-get-parameter type :follow))
10243 (funcall (org-link-get-parameter type :follow) path))
10244 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10245 (unless (run-hook-with-args-until-success
10246 'org-open-link-functions path)
10247 (if (not arg) (org-mark-ring-push)
10248 (switch-to-buffer-other-window
10249 (org-get-buffer-for-internal-link (current-buffer))))
10250 (let ((destination
10251 (org-with-wide-buffer
10252 (if (equal type "radio")
10253 (org-search-radio-target
10254 (org-element-property :path context))
10255 (org-link-search
10256 (if (member type '("custom-id" "coderef"))
10257 (org-element-property :raw-link context)
10258 path)
10259 ;; Prevent fuzzy links from matching
10260 ;; themselves.
10261 (and (equal type "fuzzy")
10262 (+ 2 (org-element-property :begin context)))))
10263 (point))))
10264 (unless (and (<= (point-min) destination)
10265 (>= (point-max) destination))
10266 (widen))
10267 (goto-char destination))))
10268 (t (browse-url-at-point))))))
10269 (t (user-error "No link found")))))
10270 (run-hook-with-args 'org-follow-link-hook)))
10272 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10273 "Offer links in the current entry and return the selected link.
10274 If there is only one link, return it.
10275 If NTH is an integer, return the NTH link found.
10276 If ZERO is a string, check also this string for a link, and if
10277 there is one, return it."
10278 (with-current-buffer buffer
10279 (org-with-wide-buffer
10280 (goto-char marker)
10281 (let ((cnt ?0)
10282 have-zero end links link c)
10283 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10284 (push (match-string 0 zero) links)
10285 (setq cnt (1- cnt) have-zero t))
10286 (save-excursion
10287 (org-back-to-heading t)
10288 (setq end (save-excursion (outline-next-heading) (point)))
10289 (while (re-search-forward org-any-link-re end t)
10290 (push (match-string 0) links))
10291 (setq links (org-uniquify (reverse links))))
10292 (cond
10293 ((null links)
10294 (message "No links"))
10295 ((equal (length links) 1)
10296 (setq link (car links)))
10297 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10298 (setq link (nth (if have-zero nth (1- nth)) links)))
10299 (t ; we have to select a link
10300 (save-excursion
10301 (save-window-excursion
10302 (delete-other-windows)
10303 (with-output-to-temp-buffer "*Select Link*"
10304 (dolist (l links)
10305 (cond
10306 ((not (string-match org-bracket-link-regexp l))
10307 (princ (format "[%c] %s\n" (cl-incf cnt)
10308 (org-unbracket-string "<" ">" l))))
10309 ((match-end 3)
10310 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10311 (match-string 3 l) (match-string 1 l))))
10312 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10313 (match-string 1 l)))))))
10314 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10315 (message "Select link to open, RET to open all:")
10316 (setq c (read-char-exclusive))
10317 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10318 (when (equal c ?q) (user-error "Abort"))
10319 (if (equal c ?\C-m)
10320 (setq link links)
10321 (setq nth (- c ?0))
10322 (when have-zero (setq nth (1+ nth)))
10323 (unless (and (integerp nth) (>= (length links) nth))
10324 (user-error "Invalid link selection"))
10325 (setq link (nth (1- nth) links)))))
10326 (cons link end)))))
10328 ;; TODO: These functions are deprecated since `org-open-at-point'
10329 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10330 (defun org-open-file-with-system (path)
10331 "Open file at PATH using the system way of opening it."
10332 (org-open-file path 'system))
10333 (defun org-open-file-with-emacs (path)
10334 "Open file at PATH in Emacs."
10335 (org-open-file path 'emacs))
10338 ;;; File search
10340 (defvar org-create-file-search-functions nil
10341 "List of functions to construct the right search string for a file link.
10342 These functions are called in turn with point at the location to
10343 which the link should point.
10345 A function in the hook should first test if it would like to
10346 handle this file type, for example by checking the `major-mode'
10347 or the file extension. If it decides not to handle this file, it
10348 should just return nil to give other functions a chance. If it
10349 does handle the file, it must return the search string to be used
10350 when following the link. The search string will be part of the
10351 file link, given after a double colon, and `org-open-at-point'
10352 will automatically search for it. If special measures must be
10353 taken to make the search successful, another function should be
10354 added to the companion hook `org-execute-file-search-functions',
10355 which see.
10357 A function in this hook may also use `setq' to set the variable
10358 `description' to provide a suggestion for the descriptive text to
10359 be used for this link when it gets inserted into an Org buffer
10360 with \\[org-insert-link].")
10362 (defvar org-execute-file-search-functions nil
10363 "List of functions to execute a file search triggered by a link.
10365 Functions added to this hook must accept a single argument, the
10366 search string that was part of the file link, the part after the
10367 double colon. The function must first check if it would like to
10368 handle this search, for example by checking the `major-mode' or
10369 the file extension. If it decides not to handle this search, it
10370 should just return nil to give other functions a chance. If it
10371 does handle the search, it must return a non-nil value to keep
10372 other functions from trying.
10374 Each function can access the current prefix argument through the
10375 variable `current-prefix-arg'. Note that a single prefix is used
10376 to force opening a link in Emacs, so it may be good to only use a
10377 numeric or double prefix to guide the search function.
10379 In case this is needed, a function in this hook can also restore
10380 the window configuration before `org-open-at-point' was called using:
10382 (set-window-configuration org-window-config-before-follow-link)")
10384 (defun org-search-radio-target (target)
10385 "Search a radio target matching TARGET in current buffer.
10386 White spaces are not significant."
10387 (let ((re (format "<<<%s>>>"
10388 (mapconcat #'regexp-quote
10389 (split-string target)
10390 "[ \t]+\\(?:\n[ \t]*\\)?")))
10391 (origin (point)))
10392 (goto-char (point-min))
10393 (catch :radio-match
10394 (while (re-search-forward re nil t)
10395 (backward-char)
10396 (let ((object (org-element-context)))
10397 (when (eq (org-element-type object) 'radio-target)
10398 (goto-char (org-element-property :begin object))
10399 (org-show-context 'link-search)
10400 (throw :radio-match nil))))
10401 (goto-char origin)
10402 (user-error "No match for radio target: %s" target))))
10404 (defun org-link-search (s &optional avoid-pos stealth)
10405 "Search for a search string S.
10407 If S starts with \"#\", it triggers a custom ID search.
10409 If S is enclosed within parenthesis, it initiates a coderef
10410 search.
10412 If S is surrounded by forward slashes, it is interpreted as
10413 a regular expression. In Org mode files, this will create an
10414 `org-occur' sparse tree. In ordinary files, `occur' will be used
10415 to list matches. If the current buffer is in `dired-mode', grep
10416 will be used to search in all files.
10418 When AVOID-POS is given, ignore matches near that position.
10420 When optional argument STEALTH is non-nil, do not modify
10421 visibility around point, thus ignoring `org-show-context-detail'
10422 variable.
10424 Search is case-insensitive and ignores white spaces. Return type
10425 of matched result, which is either `dedicated' or `fuzzy'."
10426 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10427 (let* ((case-fold-search t)
10428 (origin (point))
10429 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10430 (starred (eq (string-to-char normalized) ?*))
10431 (words (split-string (if starred (substring s 1) s)))
10432 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10433 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10434 type)
10435 (cond
10436 ;; Check if there are any special search functions.
10437 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10438 ((eq (string-to-char s) ?#)
10439 ;; Look for a custom ID S if S starts with "#".
10440 (let* ((id (substring normalized 1))
10441 (match (org-find-property "CUSTOM_ID" id)))
10442 (if match (progn (goto-char match) (setf type 'dedicated))
10443 (error "No match for custom ID: %s" id))))
10444 ((string-match "\\`(\\(.*\\))\\'" normalized)
10445 ;; Look for coderef targets if S is enclosed within parenthesis.
10446 (let ((coderef (match-string-no-properties 1 normalized))
10447 (re (substring s-single-re 1 -1)))
10448 (goto-char (point-min))
10449 (catch :coderef-match
10450 (while (re-search-forward re nil t)
10451 (let ((element (org-element-at-point)))
10452 (when (and (memq (org-element-type element)
10453 '(example-block src-block))
10454 ;; Build proper regexp according to current
10455 ;; block's label format.
10456 (let ((label-fmt
10457 (regexp-quote
10458 (or (org-element-property :label-fmt element)
10459 org-coderef-label-format))))
10460 (save-excursion
10461 (beginning-of-line)
10462 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10463 (format label-fmt coderef))))))
10464 (setq type 'dedicated)
10465 (goto-char (match-beginning 1))
10466 (throw :coderef-match nil))))
10467 (goto-char origin)
10468 (error "No match for coderef: %s" coderef))))
10469 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10470 ;; Look for a regular expression.
10471 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10472 (match-string 1 s)))
10473 ;; From here, we handle fuzzy links.
10475 ;; Look for targets, only if not in a headline search.
10476 ((and (not starred)
10477 (let ((target (format "<<%s>>" s-multi-re)))
10478 (catch :target-match
10479 (goto-char (point-min))
10480 (while (re-search-forward target nil t)
10481 (backward-char)
10482 (let ((context (org-element-context)))
10483 (when (eq (org-element-type context) 'target)
10484 (setq type 'dedicated)
10485 (goto-char (org-element-property :begin context))
10486 (throw :target-match t))))
10487 nil))))
10488 ;; Look for elements named after S, only if not in a headline
10489 ;; search.
10490 ((and (not starred)
10491 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10492 (catch :name-match
10493 (goto-char (point-min))
10494 (while (re-search-forward name nil t)
10495 (let ((element (org-element-at-point)))
10496 (when (equal words
10497 (split-string
10498 (org-element-property :name element)))
10499 (setq type 'dedicated)
10500 (beginning-of-line)
10501 (throw :name-match t))))
10502 nil))))
10503 ;; Regular text search. Prefer headlines in Org mode buffers.
10504 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10505 ;; statistics cookies and tags.
10506 ((and (derived-mode-p 'org-mode)
10507 (let ((title-re
10508 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10509 org-outline-regexp-bol
10510 org-comment-string
10511 (mapconcat #'regexp-quote words ".+")))
10512 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10513 (comment-re (eval-when-compile
10514 (format "\\`%s[ \t]+" org-comment-string))))
10515 (goto-char (point-min))
10516 (catch :found
10517 (while (re-search-forward title-re nil t)
10518 (when (equal words
10519 (split-string
10520 (replace-regexp-in-string
10521 cookie-re ""
10522 (replace-regexp-in-string
10523 comment-re "" (org-get-heading t t t)))))
10524 (throw :found t)))
10525 nil)))
10526 (beginning-of-line)
10527 (setq type 'dedicated))
10528 ;; Offer to create non-existent headline depending on
10529 ;; `org-link-search-must-match-exact-headline'.
10530 ((and (derived-mode-p 'org-mode)
10531 (not org-link-search-inhibit-query)
10532 (eq org-link-search-must-match-exact-headline 'query-to-create)
10533 (yes-or-no-p "No match - create this as a new heading? "))
10534 (goto-char (point-max))
10535 (unless (bolp) (newline))
10536 (org-insert-heading nil t t)
10537 (insert s "\n")
10538 (beginning-of-line 0))
10539 ;; Only headlines are looked after. No need to process
10540 ;; further: throw an error.
10541 ((and (derived-mode-p 'org-mode)
10542 (or starred org-link-search-must-match-exact-headline))
10543 (goto-char origin)
10544 (error "No match for fuzzy expression: %s" normalized))
10545 ;; Regular text search.
10546 ((catch :fuzzy-match
10547 (goto-char (point-min))
10548 (while (re-search-forward s-multi-re nil t)
10549 ;; Skip match if it contains AVOID-POS or it is included in
10550 ;; a link with a description but outside the description.
10551 (unless (or (and avoid-pos
10552 (<= (match-beginning 0) avoid-pos)
10553 (> (match-end 0) avoid-pos))
10554 (and (save-match-data
10555 (org-in-regexp org-bracket-link-regexp))
10556 (match-beginning 3)
10557 (or (> (match-beginning 3) (point))
10558 (<= (match-end 3) (point)))
10559 (org-element-lineage
10560 (save-match-data (org-element-context))
10561 '(link) t)))
10562 (goto-char (match-beginning 0))
10563 (setq type 'fuzzy)
10564 (throw :fuzzy-match t)))
10565 nil))
10566 ;; All failed. Throw an error.
10567 (t (goto-char origin)
10568 (error "No match for fuzzy expression: %s" normalized)))
10569 ;; Disclose surroundings of match, if appropriate.
10570 (when (and (derived-mode-p 'org-mode) (not stealth))
10571 (org-show-context 'link-search))
10572 type))
10574 (defun org-get-buffer-for-internal-link (buffer)
10575 "Return a buffer to be used for displaying the link target of internal links."
10576 (cond
10577 ((not org-display-internal-link-with-indirect-buffer)
10578 buffer)
10579 ((string-suffix-p "(Clone)" (buffer-name buffer))
10580 (message "Buffer is already a clone, not making another one")
10581 ;; we also do not modify visibility in this case
10582 buffer)
10583 (t ; make a new indirect buffer for displaying the link
10584 (let* ((bn (buffer-name buffer))
10585 (ibn (concat bn "(Clone)"))
10586 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10587 (with-current-buffer ib (org-overview))
10588 ib))))
10590 (defun org-do-occur (regexp &optional cleanup)
10591 "Call the Emacs command `occur'.
10592 If CLEANUP is non-nil, remove the printout of the regular expression
10593 in the *Occur* buffer. This is useful if the regex is long and not useful
10594 to read."
10595 (occur regexp)
10596 (when cleanup
10597 (let ((cwin (selected-window)) win beg end)
10598 (when (setq win (get-buffer-window "*Occur*"))
10599 (select-window win))
10600 (goto-char (point-min))
10601 (when (re-search-forward "match[a-z]+" nil t)
10602 (setq beg (match-end 0))
10603 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10604 (setq end (1- (match-beginning 0)))))
10605 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10606 (goto-char (point-min))
10607 (select-window cwin))))
10610 ;;; The Mark Ring
10612 (defvar org-mark-ring nil
10613 "Mark ring for positions before jumps in Org mode.")
10615 (defvar org-mark-ring-last-goto nil
10616 "Last position in the mark ring used to go back.")
10618 ;; Fill and close the ring
10619 (setq org-mark-ring nil)
10620 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10622 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10623 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10624 org-mark-ring)
10626 (defun org-mark-ring-push (&optional pos buffer)
10627 "Put the current position into the mark ring and rotate it.
10628 Also push position into the Emacs mark ring. If optional
10629 argument POS and BUFFER are not nil, mark this location instead."
10630 (interactive)
10631 (let ((pos (or pos (point)))
10632 (buffer (or buffer (current-buffer))))
10633 (with-current-buffer buffer
10634 (org-with-point-at pos (push-mark nil t)))
10635 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10636 (move-marker (car org-mark-ring) pos buffer))
10637 (message
10638 (substitute-command-keys
10639 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10641 (defun org-mark-ring-goto (&optional n)
10642 "Jump to the previous position in the mark ring.
10643 With prefix arg N, jump back that many stored positions. When
10644 called several times in succession, walk through the entire ring.
10645 Org mode commands jumping to a different position in the current file,
10646 or to another Org file, automatically push the old position onto the ring."
10647 (interactive "p")
10648 (let (p m)
10649 (if (eq last-command this-command)
10650 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10651 (setq p org-mark-ring))
10652 (setq org-mark-ring-last-goto p)
10653 (setq m (car p))
10654 (pop-to-buffer-same-window (marker-buffer m))
10655 (goto-char m)
10656 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10658 (defun org-add-angle-brackets (s)
10659 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10660 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10663 ;;; Following specific links
10665 (defvar org-agenda-buffer-tmp-name)
10666 (defvar org-agenda-start-on-weekday)
10667 (defun org-follow-timestamp-link ()
10668 "Open an agenda view for the time-stamp date/range at point."
10669 (cond
10670 ((org-at-date-range-p t)
10671 (let ((org-agenda-start-on-weekday)
10672 (t1 (match-string 1))
10673 (t2 (match-string 2)) tt1 tt2)
10674 (setq tt1 (time-to-days (org-time-string-to-time t1))
10675 tt2 (time-to-days (org-time-string-to-time t2)))
10676 (let ((org-agenda-buffer-tmp-name
10677 (format "*Org Agenda(a:%s)"
10678 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10679 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10680 ((org-at-timestamp-p 'lax)
10681 (let ((org-agenda-buffer-tmp-name
10682 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10683 (org-agenda-list nil (time-to-days (org-time-string-to-time
10684 (substring (match-string 1) 0 10)))
10685 1)))
10686 (t (error "This should not happen"))))
10689 ;;; Following file links
10690 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10691 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10692 (declare-function mailcap-mime-info
10693 "mailcap" (string &optional request no-decode))
10694 (defvar org-wait nil)
10695 (defun org-open-file (path &optional in-emacs line search)
10696 "Open the file at PATH.
10697 First, this expands any special file name abbreviations. Then the
10698 configuration variable `org-file-apps' is checked if it contains an
10699 entry for this file type, and if yes, the corresponding command is launched.
10701 If no application is found, Emacs simply visits the file.
10703 With optional prefix argument IN-EMACS, Emacs will visit the file.
10704 With a double \\[universal-argument] \\[universal-argument] \
10705 prefix arg, Org tries to avoid opening in Emacs
10706 and to use an external application to visit the file.
10708 Optional LINE specifies a line to go to, optional SEARCH a string
10709 to search for. If LINE or SEARCH is given, the file will be
10710 opened in Emacs, unless an entry from org-file-apps that makes
10711 use of groups in a regexp matches.
10713 If you want to change the way frames are used when following a
10714 link, please customize `org-link-frame-setup'.
10716 If the file does not exist, an error is thrown."
10717 (let* ((file (if (equal path "")
10718 buffer-file-name
10719 (substitute-in-file-name (expand-file-name path))))
10720 (file-apps (append org-file-apps (org-default-apps)))
10721 (apps (cl-remove-if
10722 'org-file-apps-entry-match-against-dlink-p file-apps))
10723 (apps-dlink (cl-remove-if-not
10724 'org-file-apps-entry-match-against-dlink-p file-apps))
10725 (remp (and (assq 'remote apps) (file-remote-p file)))
10726 (dirp (unless remp (file-directory-p file)))
10727 (file (if (and dirp org-open-directory-means-index-dot-org)
10728 (concat (file-name-as-directory file) "index.org")
10729 file))
10730 (a-m-a-p (assq 'auto-mode apps))
10731 (dfile (downcase file))
10732 ;; Reconstruct the original link from the PATH, LINE and
10733 ;; SEARCH args.
10734 (link (cond (line (concat file "::" (number-to-string line)))
10735 (search (concat file "::" search))
10736 (t file)))
10737 (dlink (downcase link))
10738 (ext
10739 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10740 (match-string 1 dfile)))
10741 (save-position-maybe
10742 (let ((old-buffer (current-buffer))
10743 (old-pos (point))
10744 (old-mode major-mode))
10745 (lambda ()
10746 (and (derived-mode-p 'org-mode)
10747 (eq old-mode 'org-mode)
10748 (or (not (eq old-buffer (current-buffer)))
10749 (not (eq old-pos (point))))
10750 (org-mark-ring-push old-pos old-buffer)))))
10751 cmd link-match-data)
10752 (cond
10753 ((member in-emacs '((16) system))
10754 (setq cmd (cdr (assq 'system apps))))
10755 (in-emacs (setq cmd 'emacs))
10757 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10758 (and dirp (cdr (assq 'directory apps)))
10759 ;; First, try matching against apps-dlink if we
10760 ;; get a match here, store the match data for
10761 ;; later.
10762 (let ((match (assoc-default dlink apps-dlink
10763 'string-match)))
10764 (if match
10765 (progn (setq link-match-data (match-data))
10766 match)
10767 (progn (setq in-emacs (or in-emacs line search))
10768 nil))) ; if we have no match in apps-dlink,
10769 ; always open the file in emacs if line or search
10770 ; is given (for backwards compatibility)
10771 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10772 'string-match)
10773 (cdr (assoc ext apps))
10774 (cdr (assq t apps))))))
10775 (when (eq cmd 'system)
10776 (setq cmd (cdr (assq 'system apps))))
10777 (when (eq cmd 'default)
10778 (setq cmd (cdr (assoc t apps))))
10779 (when (eq cmd 'mailcap)
10780 (require 'mailcap)
10781 (mailcap-parse-mailcaps)
10782 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10783 (command (mailcap-mime-info mime-type)))
10784 (if (stringp command)
10785 (setq cmd command)
10786 (setq cmd 'emacs))))
10787 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10788 (not (file-exists-p file))
10789 (not org-open-non-existing-files))
10790 (user-error "No such file: %s" file))
10791 (cond
10792 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10793 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10794 (while (string-match "['\"]%s['\"]" cmd)
10795 (setq cmd (replace-match "%s" t t cmd)))
10796 (setq cmd (replace-regexp-in-string
10797 "%s"
10798 (shell-quote-argument (convert-standard-filename file))
10800 nil t))
10802 ;; Replace "%1", "%2" etc. in command with group matches from regex
10803 (save-match-data
10804 (let ((match-index 1)
10805 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10806 (set-match-data link-match-data)
10807 (while (<= match-index number-of-groups)
10808 (let ((regex (concat "%" (number-to-string match-index)))
10809 (replace-with (match-string match-index dlink)))
10810 (while (string-match regex cmd)
10811 (setq cmd (replace-match replace-with t t cmd))))
10812 (setq match-index (+ match-index 1)))))
10814 (save-window-excursion
10815 (message "Running %s...done" cmd)
10816 (start-process-shell-command cmd nil cmd)
10817 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10818 ((or (stringp cmd)
10819 (eq cmd 'emacs))
10820 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10821 (widen)
10822 (cond (line (org-goto-line line)
10823 (when (derived-mode-p 'org-mode) (org-reveal)))
10824 (search (condition-case err
10825 (org-link-search search)
10826 ;; Save position before error-ing out so user
10827 ;; can easily move back to the original buffer.
10828 (error (funcall save-position-maybe)
10829 (error (nth 1 err)))))))
10830 ((functionp cmd)
10831 (save-match-data
10832 (set-match-data link-match-data)
10833 (condition-case nil
10834 (funcall cmd file link)
10835 ;; FIXME: Remove this check when most default installations
10836 ;; of Emacs have at least Org 9.0.
10837 ((debug wrong-number-of-arguments wrong-type-argument
10838 invalid-function)
10839 (user-error "Please see Org News for version 9.0 about \
10840 `org-file-apps'--Lisp error: %S" cmd)))))
10841 ((consp cmd)
10842 ;; FIXME: Remove this check when most default installations of
10843 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10844 ;; fall back to `org-link-frame-setup' for an old usage of
10845 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10846 (user-error "Please see Org News for version 9.0 about \
10847 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10848 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10849 (funcall save-position-maybe)))
10851 (defun org-file-apps-entry-match-against-dlink-p (entry)
10852 "This function returns non-nil if `entry' uses a regular
10853 expression which should be matched against the whole link by
10854 org-open-file.
10856 It assumes that is the case when the entry uses a regular
10857 expression which has at least one grouping construct and the
10858 action is either a lisp form or a command string containing
10859 `%1', i.e. using at least one subexpression match as a
10860 parameter."
10861 (let ((selector (car entry))
10862 (action (cdr entry)))
10863 (if (stringp selector)
10864 (and (> (regexp-opt-depth selector) 0)
10865 (or (and (stringp action)
10866 (string-match "%[0-9]" action))
10867 (consp action)))
10868 nil)))
10870 (defun org-default-apps ()
10871 "Return the default applications for this operating system."
10872 (cond
10873 ((eq system-type 'darwin)
10874 org-file-apps-defaults-macosx)
10875 ((eq system-type 'windows-nt)
10876 org-file-apps-defaults-windowsnt)
10877 (t org-file-apps-defaults-gnu)))
10879 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10880 "Convert extensions to regular expressions in the cars of LIST.
10881 Also, weed out any non-string entries, because the return value is used
10882 only for regexp matching.
10883 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10884 point to the symbol `emacs', indicating that the file should
10885 be opened in Emacs."
10886 (append
10887 (delq nil
10888 (mapcar (lambda (x)
10889 (unless (not (stringp (car x)))
10890 (if (string-match "\\W" (car x))
10892 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10893 list))
10894 (when add-auto-mode
10895 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10898 ;;;; Refiling
10900 (defun org-get-org-file ()
10901 "Read a filename, with default directory `org-directory'."
10902 (let ((default (or org-default-notes-file remember-data-file)))
10903 (read-file-name (format "File name [%s]: " default)
10904 (file-name-as-directory org-directory)
10905 default)))
10907 (defun org-notes-order-reversed-p ()
10908 "Check if the current file should receive notes in reversed order."
10909 (cond
10910 ((not org-reverse-note-order) nil)
10911 ((eq t org-reverse-note-order) t)
10912 ((not (listp org-reverse-note-order)) nil)
10913 (t (catch 'exit
10914 (dolist (entry org-reverse-note-order)
10915 (when (string-match (car entry) buffer-file-name)
10916 (throw 'exit (cdr entry))))))))
10918 (defvar org-refile-target-table nil
10919 "The list of refile targets, created by `org-refile'.")
10921 (defvar org-agenda-new-buffers nil
10922 "Buffers created to visit agenda files.")
10924 (defvar org-refile-cache nil
10925 "Cache for refile targets.")
10927 (defvar org-refile-markers nil
10928 "All the markers used for caching refile locations.")
10930 (defun org-refile-marker (pos)
10931 "Get a new refile marker, but only if caching is in use."
10932 (if (not org-refile-use-cache)
10934 (let ((m (make-marker)))
10935 (move-marker m pos)
10936 (push m org-refile-markers)
10937 m)))
10939 (defun org-refile-cache-clear ()
10940 "Clear the refile cache and disable all the markers."
10941 (dolist (m org-refile-markers) (move-marker m nil))
10942 (setq org-refile-markers nil)
10943 (setq org-refile-cache nil)
10944 (message "Refile cache has been cleared"))
10946 (defun org-refile-cache-check-set (set)
10947 "Check if all the markers in the cache still have live buffers."
10948 (let (marker)
10949 (catch 'exit
10950 (while (and set (setq marker (nth 3 (pop set))))
10951 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10952 (when (and marker (null (marker-buffer marker)))
10953 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10954 (sit-for 3)
10955 (throw 'exit nil)))
10956 t)))
10958 (defun org-refile-cache-put (set &rest identifiers)
10959 "Push the refile targets SET into the cache, under IDENTIFIERS."
10960 (let* ((key (sha1 (prin1-to-string identifiers)))
10961 (entry (assoc key org-refile-cache)))
10962 (if entry
10963 (setcdr entry set)
10964 (push (cons key set) org-refile-cache))))
10966 (defun org-refile-cache-get (&rest identifiers)
10967 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10968 (cond
10969 ((not org-refile-cache) nil)
10970 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10972 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10973 org-refile-cache))))
10974 (and set (org-refile-cache-check-set set) set)))))
10976 (defvar org-outline-path-cache nil
10977 "Alist between buffer positions and outline paths.
10978 It value is an alist (POSITION . PATH) where POSITION is the
10979 buffer position at the beginning of an entry and PATH is a list
10980 of strings describing the outline path for that entry, in reverse
10981 order.")
10983 (defun org-refile-get-targets (&optional default-buffer)
10984 "Produce a table with refile targets."
10985 (let ((case-fold-search nil)
10986 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10987 (entries (or org-refile-targets '((nil . (:level . 1)))))
10988 targets tgs files desc descre)
10989 (message "Getting targets...")
10990 (with-current-buffer (or default-buffer (current-buffer))
10991 (dolist (entry entries)
10992 (setq files (car entry) desc (cdr entry))
10993 (cond
10994 ((null files) (setq files (list (current-buffer))))
10995 ((eq files 'org-agenda-files)
10996 (setq files (org-agenda-files 'unrestricted)))
10997 ((and (symbolp files) (fboundp files))
10998 (setq files (funcall files)))
10999 ((and (symbolp files) (boundp files))
11000 (setq files (symbol-value files))))
11001 (when (stringp files) (setq files (list files)))
11002 (cond
11003 ((eq (car desc) :tag)
11004 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11005 ((eq (car desc) :todo)
11006 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11007 ((eq (car desc) :regexp)
11008 (setq descre (cdr desc)))
11009 ((eq (car desc) :level)
11010 (setq descre (concat "^\\*\\{" (number-to-string
11011 (if org-odd-levels-only
11012 (1- (* 2 (cdr desc)))
11013 (cdr desc)))
11014 "\\}[ \t]")))
11015 ((eq (car desc) :maxlevel)
11016 (setq descre (concat "^\\*\\{1," (number-to-string
11017 (if org-odd-levels-only
11018 (1- (* 2 (cdr desc)))
11019 (cdr desc)))
11020 "\\}[ \t]")))
11021 (t (error "Bad refiling target description %s" desc)))
11022 (dolist (f files)
11023 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11025 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11026 (progn
11027 (when (bufferp f)
11028 (setq f (buffer-file-name (buffer-base-buffer f))))
11029 (setq f (and f (expand-file-name f)))
11030 (when (eq org-refile-use-outline-path 'file)
11031 (push (list (file-name-nondirectory f) f nil nil) tgs))
11032 (when (eq org-refile-use-outline-path 'buffer-name)
11033 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11034 (when (eq org-refile-use-outline-path 'full-file-path)
11035 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11036 (org-with-wide-buffer
11037 (goto-char (point-min))
11038 (setq org-outline-path-cache nil)
11039 (while (re-search-forward descre nil t)
11040 (beginning-of-line)
11041 (let ((case-fold-search nil))
11042 (looking-at org-complex-heading-regexp))
11043 (let ((begin (point))
11044 (heading (match-string-no-properties 4)))
11045 (unless (or (and
11046 org-refile-target-verify-function
11047 (not
11048 (funcall org-refile-target-verify-function)))
11049 (not heading))
11050 (let ((re (format org-complex-heading-regexp-format
11051 (regexp-quote heading)))
11052 (target
11053 (if (not org-refile-use-outline-path) heading
11054 (mapconcat
11055 #'identity
11056 (append
11057 (pcase org-refile-use-outline-path
11058 (`file (list (file-name-nondirectory
11059 (buffer-file-name
11060 (buffer-base-buffer)))))
11061 (`full-file-path
11062 (list (buffer-file-name
11063 (buffer-base-buffer))))
11064 (`buffer-name
11065 (list (buffer-name
11066 (buffer-base-buffer))))
11067 (_ nil))
11068 (mapcar (lambda (s) (replace-regexp-in-string
11069 "/" "\\/" s nil t))
11070 (org-get-outline-path t t)))
11071 "/"))))
11072 (push (list target f re (org-refile-marker (point)))
11073 tgs)))
11074 (when (= (point) begin)
11075 ;; Verification function has not moved point.
11076 (end-of-line)))))))
11077 (when org-refile-use-cache
11078 (org-refile-cache-put tgs (buffer-file-name) descre))
11079 (setq targets (append tgs targets))))))
11080 (message "Getting targets...done")
11081 (delete-dups (nreverse targets))))
11083 (defun org--get-outline-path-1 (&optional use-cache)
11084 "Return outline path to current headline.
11086 Outline path is a list of strings, in reverse order. When
11087 optional argument USE-CACHE is non-nil, make use of a cache. See
11088 `org-get-outline-path' for details.
11090 Assume buffer is widened and point is on a headline."
11091 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11092 (let ((p (point))
11093 (heading (let ((case-fold-search nil))
11094 (looking-at org-complex-heading-regexp)
11095 (if (not (match-end 4)) ""
11096 ;; Remove statistics cookies.
11097 (org-trim
11098 (org-link-display-format
11099 (replace-regexp-in-string
11100 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11101 (match-string-no-properties 4))))))))
11102 (if (org-up-heading-safe)
11103 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11104 (when use-cache
11105 (push (cons p path) org-outline-path-cache))
11106 path)
11107 ;; This is a new root node. Since we assume we are moving
11108 ;; forward, we can drop previous cache so as to limit number
11109 ;; of associations there.
11110 (let ((path (list heading)))
11111 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11112 path)))))
11114 (defun org-get-outline-path (&optional with-self use-cache)
11115 "Return the outline path to the current entry.
11117 An outline path is a list of ancestors for current headline, as
11118 a list of strings. Statistics cookies are removed and links are
11119 replaced with their description, if any, or their path otherwise.
11121 When optional argument WITH-SELF is non-nil, the path also
11122 includes the current headline.
11124 When optional argument USE-CACHE is non-nil, cache outline paths
11125 between calls to this function so as to avoid backtracking. This
11126 argument is useful when planning to find more than one outline
11127 path in the same document. In that case, there are two
11128 conditions to satisfy:
11129 - `org-outline-path-cache' is set to nil before starting the
11130 process;
11131 - outline paths are computed by increasing buffer positions."
11132 (org-with-wide-buffer
11133 (and (or (and with-self (org-back-to-heading t))
11134 (org-up-heading-safe))
11135 (reverse (org--get-outline-path-1 use-cache)))))
11137 (defun org-format-outline-path (path &optional width prefix separator)
11138 "Format the outline path PATH for display.
11139 WIDTH is the maximum number of characters that is available.
11140 PREFIX is a prefix to be included in the returned string,
11141 such as the file name.
11142 SEPARATOR is inserted between the different parts of the path,
11143 the default is \"/\"."
11144 (setq width (or width 79))
11145 (setq path (delq nil path))
11146 (unless (> width 0)
11147 (user-error "Argument `width' must be positive"))
11148 (setq separator (or separator "/"))
11149 (let* ((org-odd-levels-only nil)
11150 (fpath (concat
11151 prefix (and prefix path separator)
11152 (mapconcat
11153 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11154 (cl-loop for head in path
11155 for n from 0
11156 collect (org-add-props
11157 head nil 'face
11158 (nth (% n org-n-level-faces) org-level-faces)))
11159 separator))))
11160 (when (> (length fpath) width)
11161 (if (< width 7)
11162 ;; It's unlikely that `width' will be this small, but don't
11163 ;; waste characters by adding ".." if it is.
11164 (setq fpath (substring fpath 0 width))
11165 (setf (substring fpath (- width 2)) "..")))
11166 fpath))
11168 (defun org-display-outline-path (&optional file current separator just-return-string)
11169 "Display the current outline path in the echo area.
11171 If FILE is non-nil, prepend the output with the file name.
11172 If CURRENT is non-nil, append the current heading to the output.
11173 SEPARATOR is passed through to `org-format-outline-path'. It separates
11174 the different parts of the path and defaults to \"/\".
11175 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11176 (interactive "P")
11177 (let* (case-fold-search
11178 (bfn (buffer-file-name (buffer-base-buffer)))
11179 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11180 res)
11181 (when current (setq path (append path
11182 (save-excursion
11183 (org-back-to-heading t)
11184 (when (looking-at org-complex-heading-regexp)
11185 (list (match-string 4)))))))
11186 (setq res
11187 (org-format-outline-path
11188 path
11189 (1- (frame-width))
11190 (and file bfn (concat (file-name-nondirectory bfn) separator))
11191 separator))
11192 (if just-return-string
11193 (org-no-properties res)
11194 (org-unlogged-message "%s" res))))
11196 (defvar org-refile-history nil
11197 "History for refiling operations.")
11199 (defvar org-after-refile-insert-hook nil
11200 "Hook run after `org-refile' has inserted its stuff at the new location.
11201 Note that this is still *before* the stuff will be removed from
11202 the *old* location.")
11204 (defvar org-capture-last-stored-marker)
11205 (defvar org-refile-keep nil
11206 "Non-nil means `org-refile' will copy instead of refile.")
11208 (defun org-copy ()
11209 "Like `org-refile', but copy."
11210 (interactive)
11211 (let ((org-refile-keep t))
11212 (org-refile nil nil nil "Copy")))
11214 (defun org-refile (&optional arg default-buffer rfloc msg)
11215 "Move the entry or entries at point to another heading.
11217 The list of target headings is compiled using the information in
11218 `org-refile-targets', which see.
11220 At the target location, the entry is filed as a subitem of the
11221 target heading. Depending on `org-reverse-note-order', the new
11222 subitem will either be the first or the last subitem.
11224 If there is an active region, all entries in that region will be
11225 refiled. However, the region must fulfill the requirement that
11226 the first heading sets the top-level of the moved text.
11228 With a `\\[universal-argument]' ARG, the command will only visit the target \
11229 location
11230 and not actually move anything.
11232 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11233 location where the last
11234 refiling operation has put the subtree.
11236 With a numeric prefix argument of `2', refile to the running clock.
11238 With a numeric prefix argument of `3', emulate `org-refile-keep'
11239 being set to t and copy to the target location, don't move it.
11240 Beware that keeping refiled entries may result in duplicated ID
11241 properties.
11243 RFLOC can be a refile location obtained in a different way.
11245 MSG is a string to replace \"Refile\" in the default prompt with
11246 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11248 See also `org-refile-use-outline-path'.
11250 If you are using target caching (see `org-refile-use-cache'), you
11251 have to clear the target cache in order to find new targets.
11252 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11253 prefix argument (`C-u C-u C-u C-c C-w')."
11254 (interactive "P")
11255 (if (member arg '(0 (64)))
11256 (org-refile-cache-clear)
11257 (let* ((actionmsg (cond (msg msg)
11258 ((equal arg 3) "Refile (and keep)")
11259 (t "Refile")))
11260 (regionp (org-region-active-p))
11261 (region-start (and regionp (region-beginning)))
11262 (region-end (and regionp (region-end)))
11263 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11264 pos it nbuf file level reversed)
11265 (setq last-command nil)
11266 (when regionp
11267 (goto-char region-start)
11268 (or (bolp) (goto-char (point-at-bol)))
11269 (setq region-start (point))
11270 (unless (or (org-kill-is-subtree-p
11271 (buffer-substring region-start region-end))
11272 (prog1 org-refile-active-region-within-subtree
11273 (let ((s (point-at-eol)))
11274 (org-toggle-heading)
11275 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11276 (user-error "The region is not a (sequence of) subtree(s)")))
11277 (if (equal arg '(16))
11278 (org-refile-goto-last-stored)
11279 (when (or
11280 (and (equal arg 2)
11281 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11282 (prog1
11283 (setq it (list (or org-clock-heading "running clock")
11284 (buffer-file-name
11285 (marker-buffer org-clock-hd-marker))
11287 (marker-position org-clock-hd-marker)))
11288 (setq arg nil)))
11289 (setq it
11290 (or rfloc
11291 (let (heading-text)
11292 (save-excursion
11293 (unless (and arg (listp arg))
11294 (org-back-to-heading t)
11295 (setq heading-text
11296 (replace-regexp-in-string
11297 org-bracket-link-regexp
11298 "\\3"
11299 (or (nth 4 (org-heading-components))
11300 ""))))
11301 (org-refile-get-location
11302 (cond ((and arg (listp arg)) "Goto")
11303 (regionp (concat actionmsg " region to"))
11304 (t (concat actionmsg " subtree \""
11305 heading-text "\" to")))
11306 default-buffer
11307 (and (not (equal '(4) arg))
11308 org-refile-allow-creating-parent-nodes)))))))
11309 (setq file (nth 1 it)
11310 pos (nth 3 it))
11311 (when (and (not arg)
11313 (equal (buffer-file-name) file)
11314 (if regionp
11315 (and (>= pos region-start)
11316 (<= pos region-end))
11317 (and (>= pos (point))
11318 (< pos (save-excursion
11319 (org-end-of-subtree t t))))))
11320 (error "Cannot refile to position inside the tree or region"))
11321 (setq nbuf (or (find-buffer-visiting file)
11322 (find-file-noselect file)))
11323 (if (and arg (not (equal arg 3)))
11324 (progn
11325 (pop-to-buffer-same-window nbuf)
11326 (goto-char (cond (pos)
11327 ((org-notes-order-reversed-p) (point-min))
11328 (t (point-max))))
11329 (org-show-context 'org-goto))
11330 (if regionp
11331 (progn
11332 (org-kill-new (buffer-substring region-start region-end))
11333 (org-save-markers-in-region region-start region-end))
11334 (org-copy-subtree 1 nil t))
11335 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11336 (find-file-noselect file)))
11337 (setq reversed (org-notes-order-reversed-p))
11338 (org-with-wide-buffer
11339 (if pos
11340 (progn
11341 (goto-char pos)
11342 (setq level (org-get-valid-level (funcall outline-level) 1))
11343 (goto-char
11344 (if reversed
11345 (or (outline-next-heading) (point-max))
11346 (or (save-excursion (org-get-next-sibling))
11347 (org-end-of-subtree t t)
11348 (point-max)))))
11349 (setq level 1)
11350 (if (not reversed)
11351 (goto-char (point-max))
11352 (goto-char (point-min))
11353 (or (outline-next-heading) (goto-char (point-max)))))
11354 (unless (bolp) (newline))
11355 (org-paste-subtree level nil nil t)
11356 (when org-log-refile
11357 (org-add-log-setup 'refile nil nil org-log-refile)
11358 (unless (eq org-log-refile 'note)
11359 (save-excursion (org-add-log-note))))
11360 (and org-auto-align-tags
11361 (let ((org-loop-over-headlines-in-active-region nil))
11362 (org-align-tags)))
11363 (let ((bookmark-name (plist-get org-bookmark-names-plist
11364 :last-refile)))
11365 (when bookmark-name
11366 (with-demoted-errors
11367 (bookmark-set bookmark-name))))
11368 ;; If we are refiling for capture, make sure that the
11369 ;; last-capture pointers point here
11370 (when (bound-and-true-p org-capture-is-refiling)
11371 (let ((bookmark-name (plist-get org-bookmark-names-plist
11372 :last-capture-marker)))
11373 (when bookmark-name
11374 (with-demoted-errors
11375 (bookmark-set bookmark-name))))
11376 (move-marker org-capture-last-stored-marker (point)))
11377 (when (fboundp 'deactivate-mark) (deactivate-mark))
11378 (run-hooks 'org-after-refile-insert-hook)))
11379 (unless org-refile-keep
11380 (if regionp
11381 (delete-region (point) (+ (point) (- region-end region-start)))
11382 (org-preserve-local-variables
11383 (delete-region
11384 (and (org-back-to-heading t) (point))
11385 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11386 (when (featurep 'org-inlinetask)
11387 (org-inlinetask-remove-END-maybe))
11388 (setq org-markers-to-move nil)
11389 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11391 (defun org-refile-goto-last-stored ()
11392 "Go to the location where the last refile was stored."
11393 (interactive)
11394 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11395 (message "This is the location of the last refile"))
11397 (defun org-refile--get-location (refloc tbl)
11398 "When user refile to REFLOC, find the associated target in TBL.
11399 Also check `org-refile-target-table'."
11400 (car (delq
11402 (mapcar
11403 (lambda (r) (or (assoc r tbl)
11404 (assoc r org-refile-target-table)))
11405 (list (replace-regexp-in-string "/$" "" refloc)
11406 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11408 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11409 "Prompt the user for a refile location, using PROMPT.
11410 PROMPT should not be suffixed with a colon and a space, because
11411 this function appends the default value from
11412 `org-refile-history' automatically, if that is not empty."
11413 (let ((org-refile-targets org-refile-targets)
11414 (org-refile-use-outline-path org-refile-use-outline-path))
11415 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11416 (unless org-refile-target-table
11417 (user-error "No refile targets"))
11418 (let* ((cbuf (current-buffer))
11419 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11420 (cfunc (if (and org-refile-use-outline-path
11421 org-outline-path-complete-in-steps)
11422 #'org-olpath-completing-read
11423 #'completing-read))
11424 (extra (if org-refile-use-outline-path "/" ""))
11425 (cbnex (concat (buffer-name) extra))
11426 (filename (and cfn (expand-file-name cfn)))
11427 (tbl (mapcar
11428 (lambda (x)
11429 (if (and (not (member org-refile-use-outline-path
11430 '(file full-file-path)))
11431 (not (equal filename (nth 1 x))))
11432 (cons (concat (car x) extra " ("
11433 (file-name-nondirectory (nth 1 x)) ")")
11434 (cdr x))
11435 (cons (concat (car x) extra) (cdr x))))
11436 org-refile-target-table))
11437 (completion-ignore-case t)
11438 cdef
11439 (prompt (concat prompt
11440 (or (and (car org-refile-history)
11441 (concat " (default " (car org-refile-history) ")"))
11442 (and (assoc cbnex tbl) (setq cdef cbnex)
11443 (concat " (default " cbnex ")"))) ": "))
11444 pa answ parent-target child parent old-hist)
11445 (setq old-hist org-refile-history)
11446 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11447 nil 'org-refile-history (or cdef (car org-refile-history))))
11448 (if (setq pa (org-refile--get-location answ tbl))
11449 (progn
11450 (org-refile-check-position pa)
11451 (when (or (not org-refile-history)
11452 (not (eq old-hist org-refile-history))
11453 (not (equal (car pa) (car org-refile-history))))
11454 (setq org-refile-history
11455 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11456 org-refile-history
11457 (cdr org-refile-history))))
11458 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11459 (pop org-refile-history)))
11461 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11462 (progn
11463 (setq parent (match-string 1 answ)
11464 child (match-string 2 answ))
11465 (setq parent-target (org-refile--get-location parent tbl))
11466 (when (and parent-target
11467 (or (eq new-nodes t)
11468 (and (eq new-nodes 'confirm)
11469 (y-or-n-p (format "Create new node \"%s\"? "
11470 child)))))
11471 (org-refile-new-child parent-target child)))
11472 (user-error "Invalid target location")))))
11474 (declare-function org-string-nw-p "org-macs" (s))
11475 (defun org-refile-check-position (refile-pointer)
11476 "Check if the refile pointer matches the headline to which it points."
11477 (let* ((file (nth 1 refile-pointer))
11478 (re (nth 2 refile-pointer))
11479 (pos (nth 3 refile-pointer))
11480 buffer)
11481 (if (and (not (markerp pos)) (not file))
11482 (user-error "Please indicate a target file in the refile path")
11483 (when (org-string-nw-p re)
11484 (setq buffer (if (markerp pos)
11485 (marker-buffer pos)
11486 (or (find-buffer-visiting file)
11487 (find-file-noselect file))))
11488 (with-current-buffer buffer
11489 (org-with-wide-buffer
11490 (goto-char pos)
11491 (beginning-of-line 1)
11492 (unless (looking-at-p re)
11493 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11495 (defun org-refile-new-child (parent-target child)
11496 "Use refile target PARENT-TARGET to add new CHILD below it."
11497 (unless parent-target
11498 (error "Cannot find parent for new node"))
11499 (let ((file (nth 1 parent-target))
11500 (pos (nth 3 parent-target))
11501 level)
11502 (with-current-buffer (or (find-buffer-visiting file)
11503 (find-file-noselect file))
11504 (org-with-wide-buffer
11505 (if pos
11506 (goto-char pos)
11507 (goto-char (point-max))
11508 (unless (bolp) (newline)))
11509 (when (looking-at org-outline-regexp)
11510 (setq level (funcall outline-level))
11511 (org-end-of-subtree t t))
11512 (org-back-over-empty-lines)
11513 (insert "\n" (make-string
11514 (if pos (org-get-valid-level level 1) 1) ?*)
11515 " " child "\n")
11516 (beginning-of-line 0)
11517 (list (concat (car parent-target) "/" child) file "" (point))))))
11519 (defun org-olpath-completing-read (prompt collection &rest args)
11520 "Read an outline path like a file name."
11521 (let ((thetable collection))
11522 (apply #'completing-read
11523 prompt
11524 (lambda (string predicate &optional flag)
11525 (cond
11526 ((eq flag nil) (try-completion string thetable))
11527 ((eq flag t)
11528 (let ((l (length string)))
11529 (mapcar (lambda (x)
11530 (let ((r (substring x l))
11531 (f (if (string-match " ([^)]*)$" x)
11532 (match-string 0 x)
11533 "")))
11534 (if (string-match "/" r)
11535 (concat string (substring r 0 (match-end 0)) f)
11536 x)))
11537 (all-completions string thetable predicate))))
11538 ;; Exact match?
11539 ((eq flag 'lambda) (assoc string thetable))))
11540 args)))
11542 ;;;; Dynamic blocks
11544 (defun org-find-dblock (name)
11545 "Find the first dynamic block with name NAME in the buffer.
11546 If not found, stay at current position and return nil."
11547 (let ((case-fold-search t) pos)
11548 (save-excursion
11549 (goto-char (point-min))
11550 (setq pos (and (re-search-forward
11551 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11552 (match-beginning 0))))
11553 (when pos (goto-char pos))
11554 pos))
11556 (defun org-create-dblock (plist)
11557 "Create a dynamic block section, with parameters taken from PLIST.
11558 PLIST must contain a :name entry which is used as the name of the block."
11559 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11560 (end-of-line 1)
11561 (newline))
11562 (let ((col (current-column))
11563 (name (plist-get plist :name)))
11564 (insert "#+BEGIN: " name)
11565 (while plist
11566 (if (eq (car plist) :name)
11567 (setq plist (cddr plist))
11568 (insert " " (prin1-to-string (pop plist)))))
11569 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11570 (beginning-of-line -2)))
11572 (defun org-prepare-dblock ()
11573 "Prepare dynamic block for refresh.
11574 This empties the block, puts the cursor at the insert position and returns
11575 the property list including an extra property :name with the block name."
11576 (unless (looking-at org-dblock-start-re)
11577 (user-error "Not at a dynamic block"))
11578 (let* ((begdel (1+ (match-end 0)))
11579 (name (org-no-properties (match-string 1)))
11580 (params (append (list :name name)
11581 (read (concat "(" (match-string 3) ")")))))
11582 (save-excursion
11583 (beginning-of-line 1)
11584 (skip-chars-forward " \t")
11585 (setq params (plist-put params :indentation-column (current-column))))
11586 (unless (re-search-forward org-dblock-end-re nil t)
11587 (error "Dynamic block not terminated"))
11588 (setq params
11589 (append params
11590 (list :content (buffer-substring
11591 begdel (match-beginning 0)))))
11592 (delete-region begdel (match-beginning 0))
11593 (goto-char begdel)
11594 (open-line 1)
11595 params))
11597 (defun org-map-dblocks (&optional command)
11598 "Apply COMMAND to all dynamic blocks in the current buffer.
11599 If COMMAND is not given, use `org-update-dblock'."
11600 (let ((cmd (or command 'org-update-dblock)))
11601 (save-excursion
11602 (goto-char (point-min))
11603 (while (re-search-forward org-dblock-start-re nil t)
11604 (goto-char (match-beginning 0))
11605 (save-excursion
11606 (condition-case nil
11607 (funcall cmd)
11608 (error (message "Error during update of dynamic block"))))
11609 (unless (re-search-forward org-dblock-end-re nil t)
11610 (error "Dynamic block not terminated"))))))
11612 (defun org-dblock-update (&optional arg)
11613 "User command for updating dynamic blocks.
11614 Update the dynamic block at point. With prefix ARG, update all dynamic
11615 blocks in the buffer."
11616 (interactive "P")
11617 (if arg
11618 (org-update-all-dblocks)
11619 (or (looking-at org-dblock-start-re)
11620 (org-beginning-of-dblock))
11621 (org-update-dblock)))
11623 (defun org-update-dblock ()
11624 "Update the dynamic block at point.
11625 This means to empty the block, parse for parameters and then call
11626 the correct writing function."
11627 (interactive)
11628 (save-excursion
11629 (let* ((win (selected-window))
11630 (pos (point))
11631 (line (org-current-line))
11632 (params (org-prepare-dblock))
11633 (name (plist-get params :name))
11634 (indent (plist-get params :indentation-column))
11635 (cmd (intern (concat "org-dblock-write:" name))))
11636 (message "Updating dynamic block `%s' at line %d..." name line)
11637 (funcall cmd params)
11638 (message "Updating dynamic block `%s' at line %d...done" name line)
11639 (goto-char pos)
11640 (when (and indent (> indent 0))
11641 (setq indent (make-string indent ?\ ))
11642 (save-excursion
11643 (select-window win)
11644 (org-beginning-of-dblock)
11645 (forward-line 1)
11646 (while (not (looking-at org-dblock-end-re))
11647 (insert indent)
11648 (beginning-of-line 2))
11649 (when (looking-at org-dblock-end-re)
11650 (and (looking-at "[ \t]+")
11651 (replace-match ""))
11652 (insert indent)))))))
11654 (defun org-beginning-of-dblock ()
11655 "Find the beginning of the dynamic block at point.
11656 Error if there is no such block at point."
11657 (let ((pos (point))
11658 beg)
11659 (end-of-line 1)
11660 (if (and (re-search-backward org-dblock-start-re nil t)
11661 (setq beg (match-beginning 0))
11662 (re-search-forward org-dblock-end-re nil t)
11663 (> (match-end 0) pos))
11664 (goto-char beg)
11665 (goto-char pos)
11666 (error "Not in a dynamic block"))))
11668 (defun org-update-all-dblocks ()
11669 "Update all dynamic blocks in the buffer.
11670 This function can be used in a hook."
11671 (interactive)
11672 (when (derived-mode-p 'org-mode)
11673 (org-map-dblocks 'org-update-dblock)))
11676 ;;;; Completion
11678 (declare-function org-export-backend-options "ox" (cl-x) t)
11679 (defun org-get-export-keywords ()
11680 "Return a list of all currently understood export keywords.
11681 Export keywords include options, block names, attributes and
11682 keywords relative to each registered export back-end."
11683 (let (keywords)
11684 (dolist (backend
11685 (bound-and-true-p org-export-registered-backends)
11686 (delq nil keywords))
11687 ;; Back-end name (for keywords, like #+LATEX:)
11688 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11689 (dolist (option-entry (org-export-backend-options backend))
11690 ;; Back-end options.
11691 (push (nth 1 option-entry) keywords)))))
11693 (defconst org-options-keywords
11694 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11695 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11696 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11697 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11698 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11700 (defcustom org-structure-template-alist
11701 '(("a" . "export ascii")
11702 ("c" . "center")
11703 ("C" . "comment")
11704 ("e" . "example")
11705 ("E" . "export")
11706 ("h" . "export html")
11707 ("l" . "export latex")
11708 ("q" . "quote")
11709 ("s" . "src")
11710 ("v" . "verse"))
11711 "An alist of keys and block types.
11712 `org-insert-structure-template' will display a menu with this
11713 list of templates to choose from. The block type is inserted,
11714 with \"#+BEGIN_\" and \"#+END_\" added automatically.
11716 The menu keys are defined by the car of each entry in this alist.
11717 If two entries have the keys \"a\" and \"aa\" respectively, the
11718 former will be inserted by typing \"a TAB/RET/SPC\" and the
11719 latter will be inserted by typing \"aa\". If an entry with the
11720 key \"aab\" is later added, it can be inserted by typing \"ab\".
11722 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11723 block can be inserted by pressing TAB after the string \"<KEY\"."
11724 :group 'org-edit-structure
11725 :type '(repeat
11726 (cons (string :tag "Key")
11727 (string :tag "Template")))
11728 :package-version '(Org . "9.2"))
11730 (defun org--insert-structure-template-mks ()
11731 "Present `org-structure-template-alist' with `org-mks'.
11733 Menus are added if keys require more than one keystroke. Tabs
11734 are added to single key entries when more than one stroke is
11735 needed. Keys longer than two characters are reduced to two
11736 characters."
11737 (let* (case-fold-search
11738 (templates (append org-structure-template-alist
11739 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11740 (keys (mapcar #'car templates))
11741 (start-letters
11742 (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11743 ;; Sort each element of `org-structure-template-alist' into
11744 ;; sublists according to the first letter.
11745 (superlist
11746 (mapcar (lambda (letter)
11747 (list letter
11748 (cl-remove-if-not
11749 (apply-partially #'string-match-p (concat "^" letter))
11750 templates :key #'car)))
11751 start-letters)))
11752 (org-mks
11753 (apply #'append
11754 ;; Make an `org-mks' table. If only one element is
11755 ;; present in a sublist, make it part of the top-menu,
11756 ;; otherwise make a submenu according to the starting
11757 ;; letter and populate it.
11758 (mapcar (lambda (sublist)
11759 (if (eq 1 (length (cadr sublist)))
11760 (mapcar (lambda (elm)
11761 (list (substring (car elm) 0 1)
11762 (cdr elm) ""))
11763 (cadr sublist))
11764 ;; Create submenu.
11765 (let* ((topkey (car sublist))
11766 (elms (cadr sublist))
11767 (keys (mapcar #'car elms))
11768 (long (> (length elms) 3)))
11769 (append
11770 (list
11771 ;; Make a description of the submenu.
11772 (list topkey
11773 (concat
11774 (mapconcat #'cdr
11775 (cl-subseq elms 0 (if long 3 (length elms)))
11776 ", ")
11777 (when long ", ..."))))
11778 ;; List of entries in submenu.
11779 (cl-mapcar #'list
11780 (org--insert-structure-template-unique-keys keys)
11781 (mapcar #'cdr elms)
11782 (make-list (length elms) ""))))))
11783 superlist))
11784 "Select a key\n============"
11785 "Key: ")))
11787 (defun org--insert-structure-template-unique-keys (keys)
11788 "Make a list of unique, two characters long elements from KEYS.
11790 Elements of length one have a tab appended. Elements of length
11791 two are kept as is. Longer elements are truncated to length two.
11793 If an element cannot be made unique, an error is raised."
11794 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11795 menu-keys)
11796 (dolist (key orderd-keys)
11797 (let ((potential-key
11798 (cl-case (length key)
11799 (1 (concat key "\t"))
11800 (2 key)
11801 (otherwise
11802 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11803 (mapcar (apply-partially #'concat (substring key 0 1))
11804 (split-string (substring key 1) "" t)))))))
11805 (if (or (not potential-key) (assoc potential-key menu-keys))
11806 (user-error "Could not make unique key for %s." key)
11807 (push (cons potential-key key) menu-keys))))
11808 (mapcar #'car
11809 (cl-sort menu-keys #'<
11810 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11812 (defun org-insert-structure-template (type)
11813 "Insert a block structure of the type #+begin_foo/#+end_foo.
11814 Select a block from `org-structure-template-alist' then type
11815 either RET, TAB or SPC to write the block type. With an active
11816 region, wrap the region in the block. Otherwise, insert an empty
11817 block."
11818 (interactive
11819 (list (pcase (org--insert-structure-template-mks)
11820 (`("\t" . ,_) (read-string "Structure type: "))
11821 (`(,_ ,choice . ,_) choice))))
11822 (let* ((region? (use-region-p))
11823 (col (current-indentation))
11824 (indent (make-string col ?\s))
11825 (special? (string-match-p "\\(src\\|export\\)\\'" type))
11826 (region-string (and region?
11827 (buffer-substring (region-beginning)
11828 (region-end))))
11829 (region-end-blank (and region?
11830 (save-excursion
11831 (goto-char (region-end))
11832 (when (looking-at "[ \t]*$")
11833 (replace-match "")
11834 t))))
11836 (when region? (delete-region (region-beginning) (region-end)))
11837 (unless (save-excursion (skip-chars-backward "[ \t]") (bolp))
11838 (insert "\n"))
11839 (beginning-of-line)
11840 (save-excursion
11841 (insert
11842 (with-temp-buffer
11843 (when region?
11844 (insert region-string "\n")
11845 (when (string-match-p
11846 (concat "\\`" (regexp-opt '("example" "export" "src")))
11847 type)
11848 (org-escape-code-in-region (point-min) (point-max))))
11849 (goto-char (point-min))
11850 ;; Delete trailing white-lines.
11851 (when region?
11852 (while (looking-at-p "^[ \t]*$")
11853 (delete-region (line-beginning-position)
11854 (line-beginning-position 2))))
11855 (save-excursion
11856 (while (not (eobp))
11857 (unless (looking-at-p indent)
11858 (insert indent))
11859 (forward-line)))
11860 (insert
11861 indent
11862 (format "#+begin_%s%s\n" type (if special? " " "")))
11863 (unless region? (indent-to col))
11864 (setq s (point))
11865 (goto-char (point-max))
11866 (skip-chars-backward "[ \t\n]" s)
11867 (delete-region (line-end-position) (point-max))
11868 (insert "\n" indent
11869 (format "#+end_%s" (car (split-string type)))
11870 (if region-end-blank "" "\n"))
11871 (buffer-substring (point-min) (point))))
11872 (when (and (eobp) (not (bolp))) (insert "\n")))
11873 (cond (special?
11874 (end-of-line))
11876 (forward-line)
11877 (skip-chars-forward "[ \t]*")))))
11880 ;;;; TODO, DEADLINE, Comments
11882 (defun org-toggle-comment ()
11883 "Change the COMMENT state of an entry."
11884 (interactive)
11885 (save-excursion
11886 (org-back-to-heading)
11887 (let ((case-fold-search nil))
11888 (looking-at org-complex-heading-regexp))
11889 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11890 (skip-chars-forward " \t")
11891 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11892 (if (org-in-commented-heading-p t)
11893 (delete-region (point)
11894 (progn (search-forward " " (line-end-position) 'move)
11895 (skip-chars-forward " \t")
11896 (point)))
11897 (insert org-comment-string)
11898 (unless (eolp) (insert " ")))))
11900 (defvar org-last-todo-state-is-todo nil
11901 "This is non-nil when the last TODO state change led to a TODO state.
11902 If the last change removed the TODO tag or switched to DONE, then
11903 this is nil.")
11905 (defvar org-todo-setup-filter-hook nil
11906 "Hook for functions that pre-filter todo specs.
11907 Each function takes a todo spec and returns either nil or the spec
11908 transformed into canonical form." )
11910 (defvar org-todo-get-default-hook nil
11911 "Hook for functions that get a default item for todo.
11912 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11913 nil or a string to be used for the todo mark." )
11915 (defvar org-agenda-headline-snapshot-before-repeat)
11917 (defun org-current-effective-time ()
11918 "Return current time adjusted for `org-extend-today-until' variable."
11919 (let* ((ct (org-current-time))
11920 (dct (decode-time ct))
11921 (ct1
11922 (cond
11923 (org-use-last-clock-out-time-as-effective-time
11924 (or (org-clock-get-last-clock-out-time) ct))
11925 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11926 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11927 (t ct))))
11928 ct1))
11930 (defun org-todo-yesterday (&optional arg)
11931 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11932 (interactive "P")
11933 (if (eq major-mode 'org-agenda-mode)
11934 (apply 'org-agenda-todo-yesterday arg)
11935 (let* ((org-use-effective-time t)
11936 (hour (nth 2 (decode-time (org-current-time))))
11937 (org-extend-today-until (1+ hour)))
11938 (org-todo arg))))
11940 (defvar org-block-entry-blocking ""
11941 "First entry preventing the TODO state change.")
11943 (defun org-cancel-repeater ()
11944 "Cancel a repeater by setting its numeric value to zero."
11945 (interactive)
11946 (save-excursion
11947 (org-back-to-heading t)
11948 (let ((bound1 (point))
11949 (bound0 (save-excursion (outline-next-heading) (point))))
11950 (when (and (re-search-forward
11951 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11952 org-deadline-time-regexp "\\)\\|\\("
11953 org-ts-regexp "\\)")
11954 bound0 t)
11955 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11956 bound1 t))
11957 (replace-match "0" t nil nil 1)))))
11959 (defvar org-state)
11960 (defvar org-blocked-by-checkboxes)
11961 (defun org-todo (&optional arg)
11962 "Change the TODO state of an item.
11964 The state of an item is given by a keyword at the start of the heading,
11965 like
11966 *** TODO Write paper
11967 *** DONE Call mom
11969 The different keywords are specified in the variable `org-todo-keywords'.
11970 By default the available states are \"TODO\" and \"DONE\". So, for this
11971 example: when the item starts with TODO, it is changed to DONE.
11972 When it starts with DONE, the DONE is removed. And when neither TODO nor
11973 DONE are present, add TODO at the beginning of the heading.
11975 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11976 state.
11977 With numeric prefix ARG, switch to that state.
11978 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11979 next set of TODO \
11980 keywords (nextset).
11981 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11982 prefix, circumvent any state blocking.
11983 With a numeric prefix arg of 0, inhibit note taking for the change.
11984 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
11986 When called through ELisp, arg is also interpreted in the following way:
11987 `none' -> empty state
11988 \"\" -> switch to empty state
11989 `done' -> switch to DONE
11990 `nextset' -> switch to the next set of keywords
11991 `previousset' -> switch to the previous set of keywords
11992 \"WAITING\" -> switch to the specified keyword, but only if it
11993 really is a member of `org-todo-keywords'."
11994 (interactive "P")
11995 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11996 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11997 'region-start-level 'region))
11998 org-loop-over-headlines-in-active-region)
11999 (org-map-entries
12000 `(org-todo ,arg)
12001 org-loop-over-headlines-in-active-region
12002 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12003 (when (equal arg '(16)) (setq arg 'nextset))
12004 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12005 (let ((org-blocker-hook org-blocker-hook)
12006 commentp
12007 case-fold-search)
12008 (when (equal arg '(64))
12009 (setq arg nil org-blocker-hook nil))
12010 (when (and org-blocker-hook
12011 (or org-inhibit-blocking
12012 (org-entry-get nil "NOBLOCKING")))
12013 (setq org-blocker-hook nil))
12014 (save-excursion
12015 (catch 'exit
12016 (org-back-to-heading t)
12017 (when (org-in-commented-heading-p t)
12018 (org-toggle-comment)
12019 (setq commentp t))
12020 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12021 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12022 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12023 (let* ((match-data (match-data))
12024 (startpos (copy-marker (line-beginning-position)))
12025 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12026 (org-log-done org-log-done)
12027 (org-log-repeat org-log-repeat)
12028 (org-todo-log-states org-todo-log-states)
12029 (org-inhibit-logging
12030 (if (equal arg 0)
12031 (progn (setq arg nil) 'note) org-inhibit-logging))
12032 (this (match-string 1))
12033 (hl-pos (match-beginning 0))
12034 (head (org-get-todo-sequence-head this))
12035 (ass (assoc head org-todo-kwd-alist))
12036 (interpret (nth 1 ass))
12037 (done-word (nth 3 ass))
12038 (final-done-word (nth 4 ass))
12039 (org-last-state (or this ""))
12040 (completion-ignore-case t)
12041 (member (member this org-todo-keywords-1))
12042 (tail (cdr member))
12043 (org-state (cond
12044 ((and org-todo-key-trigger
12045 (or (and (equal arg '(4))
12046 (eq org-use-fast-todo-selection 'prefix))
12047 (and (not arg) org-use-fast-todo-selection
12048 (not (eq org-use-fast-todo-selection
12049 'prefix)))))
12050 ;; Use fast selection.
12051 (org-fast-todo-selection))
12052 ((and (equal arg '(4))
12053 (or (not org-use-fast-todo-selection)
12054 (not org-todo-key-trigger)))
12055 ;; Read a state with completion.
12056 (completing-read
12057 "State: " (mapcar #'list org-todo-keywords-1)
12058 nil t))
12059 ((eq arg 'right)
12060 (if this
12061 (if tail (car tail) nil)
12062 (car org-todo-keywords-1)))
12063 ((eq arg 'left)
12064 (unless (equal member org-todo-keywords-1)
12065 (if this
12066 (nth (- (length org-todo-keywords-1)
12067 (length tail) 2)
12068 org-todo-keywords-1)
12069 (org-last org-todo-keywords-1))))
12070 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12071 (setq arg nil))) ;hack to fall back to cycling
12072 (arg
12073 ;; User or caller requests a specific state.
12074 (cond
12075 ((equal arg "") nil)
12076 ((eq arg 'none) nil)
12077 ((eq arg 'done) (or done-word (car org-done-keywords)))
12078 ((eq arg 'nextset)
12079 (or (car (cdr (member head org-todo-heads)))
12080 (car org-todo-heads)))
12081 ((eq arg 'previousset)
12082 (let ((org-todo-heads (reverse org-todo-heads)))
12083 (or (car (cdr (member head org-todo-heads)))
12084 (car org-todo-heads))))
12085 ((car (member arg org-todo-keywords-1)))
12086 ((stringp arg)
12087 (user-error "State `%s' not valid in this file" arg))
12088 ((nth (1- (prefix-numeric-value arg))
12089 org-todo-keywords-1))))
12090 ((null member) (or head (car org-todo-keywords-1)))
12091 ((equal this final-done-word) nil) ;-> make empty
12092 ((null tail) nil) ;-> first entry
12093 ((memq interpret '(type priority))
12094 (if (eq this-command last-command)
12095 (car tail)
12096 (if (> (length tail) 0)
12097 (or done-word (car org-done-keywords))
12098 nil)))
12100 (car tail))))
12101 (org-state (or
12102 (run-hook-with-args-until-success
12103 'org-todo-get-default-hook org-state org-last-state)
12104 org-state))
12105 (next (if org-state (concat " " org-state " ") " "))
12106 (change-plist (list :type 'todo-state-change :from this :to org-state
12107 :position startpos))
12108 dolog now-done-p)
12109 (when org-blocker-hook
12110 (let (org-blocked-by-checkboxes block-reason)
12111 (setq org-last-todo-state-is-todo
12112 (not (member this org-done-keywords)))
12113 (unless (save-excursion
12114 (save-match-data
12115 (org-with-wide-buffer
12116 (run-hook-with-args-until-failure
12117 'org-blocker-hook change-plist))))
12118 (setq block-reason (if org-blocked-by-checkboxes
12119 "contained checkboxes"
12120 (format "\"%s\"" org-block-entry-blocking)))
12121 (if (called-interactively-p 'interactive)
12122 (user-error "TODO state change from %s to %s blocked (by %s)"
12123 this org-state block-reason)
12124 ;; Fail silently.
12125 (message "TODO state change from %s to %s blocked (by %s)"
12126 this org-state block-reason)
12127 (throw 'exit nil)))))
12128 (store-match-data match-data)
12129 (replace-match next t t)
12130 (cond ((equal this org-state)
12131 (message "TODO state was already %s" (org-trim next)))
12132 ((not (pos-visible-in-window-p hl-pos))
12133 (message "TODO state changed to %s" (org-trim next))))
12134 (unless head
12135 (setq head (org-get-todo-sequence-head org-state)
12136 ass (assoc head org-todo-kwd-alist)
12137 interpret (nth 1 ass)
12138 done-word (nth 3 ass)
12139 final-done-word (nth 4 ass)))
12140 (when (memq arg '(nextset previousset))
12141 (message "Keyword-Set %d/%d: %s"
12142 (- (length org-todo-sets) -1
12143 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12144 (length org-todo-sets)
12145 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12146 (setq org-last-todo-state-is-todo
12147 (not (member org-state org-done-keywords)))
12148 (setq now-done-p (and (member org-state org-done-keywords)
12149 (not (member this org-done-keywords))))
12150 (and logging (org-local-logging logging))
12151 (when (and (or org-todo-log-states org-log-done)
12152 (not (eq org-inhibit-logging t))
12153 (not (memq arg '(nextset previousset))))
12154 ;; We need to look at recording a time and note.
12155 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12156 (nth 2 (assoc this org-todo-log-states))))
12157 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12158 (setq dolog 'time))
12159 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12160 (and org-state
12161 (member org-state org-not-done-keywords)
12162 (not (member this org-not-done-keywords))))
12163 ;; This is now a todo state and was not one before
12164 ;; If there was a CLOSED time stamp, get rid of it.
12165 (org-add-planning-info nil nil 'closed))
12166 (when (and now-done-p org-log-done)
12167 ;; It is now done, and it was not done before.
12168 (org-add-planning-info 'closed (org-current-effective-time))
12169 (when (and (not dolog) (eq 'note org-log-done))
12170 (org-add-log-setup 'done org-state this 'note)))
12171 (when (and org-state dolog)
12172 ;; This is a non-nil state, and we need to log it.
12173 (org-add-log-setup 'state org-state this dolog)))
12174 ;; Fixup tag positioning.
12175 (org-todo-trigger-tag-changes org-state)
12176 (when org-auto-align-tags (org-align-tags))
12177 (when org-provide-todo-statistics
12178 (org-update-parent-todo-statistics))
12179 (run-hooks 'org-after-todo-state-change-hook)
12180 (when (and arg (not (member org-state org-done-keywords)))
12181 (setq head (org-get-todo-sequence-head org-state)))
12182 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12183 ;; Do we need to trigger a repeat?
12184 (when now-done-p
12185 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12186 ;; This is for the agenda, take a snapshot of the headline.
12187 (save-match-data
12188 (setq org-agenda-headline-snapshot-before-repeat
12189 (org-get-heading))))
12190 (org-auto-repeat-maybe org-state))
12191 ;; Fixup cursor location if close to the keyword.
12192 (when (and (outline-on-heading-p)
12193 (not (bolp))
12194 (save-excursion (beginning-of-line 1)
12195 (looking-at org-todo-line-regexp))
12196 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12197 (goto-char (or (match-end 2) (match-end 1)))
12198 (and (looking-at " ") (just-one-space)))
12199 (when org-trigger-hook
12200 (save-excursion
12201 (run-hook-with-args 'org-trigger-hook change-plist)))
12202 (when commentp (org-toggle-comment))))))))
12204 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12205 "Block turning an entry into a TODO, using the hierarchy.
12206 This checks whether the current task should be blocked from state
12207 changes. Such blocking occurs when:
12209 1. The task has children which are not all in a completed state.
12211 2. A task has a parent with the property :ORDERED:, and there
12212 are siblings prior to the current task with incomplete
12213 status.
12215 3. The parent of the task is blocked because it has siblings that should
12216 be done first, or is child of a block grandparent TODO entry."
12218 (if (not org-enforce-todo-dependencies)
12219 t ; if locally turned off don't block
12220 (catch 'dont-block
12221 ;; If this is not a todo state change, or if this entry is already DONE,
12222 ;; do not block
12223 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12224 (member (plist-get change-plist :from)
12225 (cons 'done org-done-keywords))
12226 (member (plist-get change-plist :to)
12227 (cons 'todo org-not-done-keywords))
12228 (not (plist-get change-plist :to)))
12229 (throw 'dont-block t))
12230 ;; If this task has children, and any are undone, it's blocked
12231 (save-excursion
12232 (org-back-to-heading t)
12233 (let ((this-level (funcall outline-level)))
12234 (outline-next-heading)
12235 (let ((child-level (funcall outline-level)))
12236 (while (and (not (eobp))
12237 (> child-level this-level))
12238 ;; this todo has children, check whether they are all
12239 ;; completed
12240 (when (and (not (org-entry-is-done-p))
12241 (org-entry-is-todo-p))
12242 (setq org-block-entry-blocking (org-get-heading))
12243 (throw 'dont-block nil))
12244 (outline-next-heading)
12245 (setq child-level (funcall outline-level))))))
12246 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12247 ;; any previous siblings are undone, it's blocked
12248 (save-excursion
12249 (org-back-to-heading t)
12250 (let* ((pos (point))
12251 (parent-pos (and (org-up-heading-safe) (point)))
12252 (case-fold-search nil))
12253 (unless parent-pos (throw 'dont-block t)) ; no parent
12254 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12255 (forward-line 1)
12256 (re-search-forward org-not-done-heading-regexp pos t))
12257 (setq org-block-entry-blocking (match-string 0))
12258 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12259 ;; Search further up the hierarchy, to see if an ancestor is blocked
12260 (while t
12261 (goto-char parent-pos)
12262 (unless (looking-at org-not-done-heading-regexp)
12263 (throw 'dont-block t)) ; do not block, parent is not a TODO
12264 (setq pos (point))
12265 (setq parent-pos (and (org-up-heading-safe) (point)))
12266 (unless parent-pos (throw 'dont-block t)) ; no parent
12267 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12268 (forward-line 1)
12269 (re-search-forward org-not-done-heading-regexp pos t)
12270 (setq org-block-entry-blocking (org-get-heading)))
12271 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12273 (defcustom org-track-ordered-property-with-tag nil
12274 "Should the ORDERED property also be shown as a tag?
12275 The ORDERED property decides if an entry should require subtasks to be
12276 completed in sequence. Since a property is not very visible, setting
12277 this option means that toggling the ORDERED property with the command
12278 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12279 not relevant for the behavior, but it makes things more visible.
12281 Note that toggling the tag with tags commands will not change the property
12282 and therefore not influence behavior!
12284 This can be t, meaning the tag ORDERED should be used, It can also be a
12285 string to select a different tag for this task."
12286 :group 'org-todo
12287 :type '(choice
12288 (const :tag "No tracking" nil)
12289 (const :tag "Track with ORDERED tag" t)
12290 (string :tag "Use other tag")))
12292 (defun org-toggle-ordered-property ()
12293 "Toggle the ORDERED property of the current entry.
12294 For better visibility, you can track the value of this property with a tag.
12295 See variable `org-track-ordered-property-with-tag'."
12296 (interactive)
12297 (let* ((t1 org-track-ordered-property-with-tag)
12298 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12299 (save-excursion
12300 (org-back-to-heading)
12301 (if (org-entry-get nil "ORDERED")
12302 (progn
12303 (org-delete-property "ORDERED")
12304 (and tag (org-toggle-tag tag 'off))
12305 (message "Subtasks can be completed in arbitrary order"))
12306 (org-entry-put nil "ORDERED" "t")
12307 (and tag (org-toggle-tag tag 'on))
12308 (message "Subtasks must be completed in sequence")))))
12310 (defun org-block-todo-from-checkboxes (change-plist)
12311 "Block turning an entry into a TODO, using checkboxes.
12312 This checks whether the current task should be blocked from state
12313 changes because there are unchecked boxes in this entry."
12314 (if (not org-enforce-todo-checkbox-dependencies)
12315 t ; if locally turned off don't block
12316 (catch 'dont-block
12317 ;; If this is not a todo state change, or if this entry is already DONE,
12318 ;; do not block
12319 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12320 (member (plist-get change-plist :from)
12321 (cons 'done org-done-keywords))
12322 (member (plist-get change-plist :to)
12323 (cons 'todo org-not-done-keywords))
12324 (not (plist-get change-plist :to)))
12325 (throw 'dont-block t))
12326 ;; If this task has checkboxes that are not checked, it's blocked
12327 (save-excursion
12328 (org-back-to-heading t)
12329 (let ((beg (point)) end)
12330 (outline-next-heading)
12331 (setq end (point))
12332 (goto-char beg)
12333 (when (org-list-search-forward
12334 (concat (org-item-beginning-re)
12335 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12336 "\\[[- ]\\]")
12337 end t)
12338 (when (boundp 'org-blocked-by-checkboxes)
12339 (setq org-blocked-by-checkboxes t))
12340 (throw 'dont-block nil))))
12341 t))) ; do not block
12343 (defun org-entry-blocked-p ()
12344 "Non-nil if entry at point is blocked."
12345 (and (not (org-entry-get nil "NOBLOCKING"))
12346 (member (org-entry-get nil "TODO") org-not-done-keywords)
12347 (not (run-hook-with-args-until-failure
12348 'org-blocker-hook
12349 (list :type 'todo-state-change
12350 :position (point)
12351 :from 'todo
12352 :to 'done)))))
12354 (defun org-update-statistics-cookies (all)
12355 "Update the statistics cookie, either from TODO or from checkboxes.
12356 This should be called with the cursor in a line with a statistics
12357 cookie. When called with a \\[universal-argument] prefix, update
12358 all statistics cookies in the buffer."
12359 (interactive "P")
12360 (if all
12361 (progn
12362 (org-update-checkbox-count 'all)
12363 (org-map-entries 'org-update-parent-todo-statistics))
12364 (if (not (org-at-heading-p))
12365 (org-update-checkbox-count)
12366 (let ((pos (point-marker))
12367 end l1 l2)
12368 (ignore-errors (org-back-to-heading t))
12369 (if (not (org-at-heading-p))
12370 (org-update-checkbox-count)
12371 (setq l1 (org-outline-level))
12372 (setq end (save-excursion
12373 (outline-next-heading)
12374 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12375 (point)))
12376 (if (and (save-excursion
12377 (re-search-forward
12378 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12379 (not (save-excursion (re-search-forward
12380 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12381 (org-update-checkbox-count)
12382 (if (and l2 (> l2 l1))
12383 (progn
12384 (goto-char end)
12385 (org-update-parent-todo-statistics))
12386 (goto-char pos)
12387 (beginning-of-line 1)
12388 (while (re-search-forward
12389 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12390 (point-at-eol) t)
12391 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12392 (goto-char pos)
12393 (move-marker pos nil)))))
12395 (defvar org-entry-property-inherited-from) ;; defined below
12396 (defun org-update-parent-todo-statistics ()
12397 "Update any statistics cookie in the parent of the current headline.
12398 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12399 the entire subtree and this will travel up the hierarchy and update
12400 statistics everywhere."
12401 (let* ((prop (save-excursion (org-up-heading-safe)
12402 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12403 (recursive (or (not org-hierarchical-todo-statistics)
12404 (and prop (string-match "\\<recursive\\>" prop))))
12405 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12407 (first t)
12408 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12409 level ltoggle l1 new ndel
12410 (cnt-all 0) (cnt-done 0) is-percent kwd
12411 checkbox-beg cookie-present)
12412 (catch 'exit
12413 (save-excursion
12414 (beginning-of-line 1)
12415 (setq ltoggle (funcall outline-level))
12416 ;; Three situations are to consider:
12418 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12419 ;; to the top-level ancestor on the headline;
12421 ;; 2. If parent has "recursive" property, repeat up to the
12422 ;; headline setting that property, taking inheritance into
12423 ;; account;
12425 ;; 3. Else, move up to direct parent and proceed only once.
12426 (while (and (setq level (org-up-heading-safe))
12427 (or recursive first)
12428 (>= (point) lim))
12429 (setq first nil cookie-present nil)
12430 (unless (and level
12431 (not (string-match
12432 "\\<checkbox\\>"
12433 (downcase (or (org-entry-get nil "COOKIE_DATA")
12434 "")))))
12435 (throw 'exit nil))
12436 (while (re-search-forward box-re (point-at-eol) t)
12437 (setq cnt-all 0 cnt-done 0 cookie-present t)
12438 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12439 (save-match-data
12440 (unless (outline-next-heading) (throw 'exit nil))
12441 (while (and (looking-at org-complex-heading-regexp)
12442 (> (setq l1 (length (match-string 1))) level))
12443 (setq kwd (and (or recursive (= l1 ltoggle))
12444 (match-string 2)))
12445 (if (or (eq org-provide-todo-statistics 'all-headlines)
12446 (and (eq org-provide-todo-statistics t)
12447 (or (member kwd org-done-keywords)))
12448 (and (listp org-provide-todo-statistics)
12449 (stringp (car org-provide-todo-statistics))
12450 (or (member kwd org-provide-todo-statistics)
12451 (member kwd org-done-keywords)))
12452 (and (listp org-provide-todo-statistics)
12453 (listp (car org-provide-todo-statistics))
12454 (or (member kwd (car org-provide-todo-statistics))
12455 (and (member kwd org-done-keywords)
12456 (member kwd (cadr org-provide-todo-statistics))))))
12457 (setq cnt-all (1+ cnt-all))
12458 (and (eq org-provide-todo-statistics t)
12460 (setq cnt-all (1+ cnt-all))))
12461 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12462 (member kwd org-done-keywords))
12463 (and (listp org-provide-todo-statistics)
12464 (listp (car org-provide-todo-statistics))
12465 (member kwd org-done-keywords)
12466 (member kwd (cadr org-provide-todo-statistics)))
12467 (and (listp org-provide-todo-statistics)
12468 (stringp (car org-provide-todo-statistics))
12469 (member kwd org-done-keywords)))
12470 (setq cnt-done (1+ cnt-done)))
12471 (outline-next-heading)))
12472 (setq new
12473 (if is-percent
12474 (format "[%d%%]" (floor (* 100.0 cnt-done)
12475 (max 1 cnt-all)))
12476 (format "[%d/%d]" cnt-done cnt-all))
12477 ndel (- (match-end 0) checkbox-beg))
12478 (goto-char checkbox-beg)
12479 (insert new)
12480 (delete-region (point) (+ (point) ndel))
12481 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12482 (when cookie-present
12483 (run-hook-with-args 'org-after-todo-statistics-hook
12484 cnt-done (- cnt-all cnt-done))))))
12485 (run-hooks 'org-todo-statistics-hook)))
12487 (defvar org-after-todo-statistics-hook nil
12488 "Hook that is called after a TODO statistics cookie has been updated.
12489 Each function is called with two arguments: the number of not-done entries
12490 and the number of done entries.
12492 For example, the following function, when added to this hook, will switch
12493 an entry to DONE when all children are done, and back to TODO when new
12494 entries are set to a TODO status. Note that this hook is only called
12495 when there is a statistics cookie in the headline!
12497 (defun org-summary-todo (n-done n-not-done)
12498 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12499 (let (org-log-done org-log-states) ; turn off logging
12500 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12503 (defvar org-todo-statistics-hook nil
12504 "Hook that is run whenever Org thinks TODO statistics should be updated.
12505 This hook runs even if there is no statistics cookie present, in which case
12506 `org-after-todo-statistics-hook' would not run.")
12508 (defun org-todo-trigger-tag-changes (state)
12509 "Apply the changes defined in `org-todo-state-tags-triggers'."
12510 (let ((l org-todo-state-tags-triggers)
12511 changes)
12512 (when (or (not state) (equal state ""))
12513 (setq changes (append changes (cdr (assoc "" l)))))
12514 (when (and (stringp state) (> (length state) 0))
12515 (setq changes (append changes (cdr (assoc state l)))))
12516 (when (member state org-not-done-keywords)
12517 (setq changes (append changes (cdr (assq 'todo l)))))
12518 (when (member state org-done-keywords)
12519 (setq changes (append changes (cdr (assq 'done l)))))
12520 (dolist (c changes)
12521 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12523 (defun org-local-logging (value)
12524 "Get logging settings from a property VALUE."
12525 ;; Directly set the variables, they are already local.
12526 (setq org-log-done nil
12527 org-log-repeat nil
12528 org-todo-log-states nil)
12529 (dolist (w (split-string value))
12530 (let (a)
12531 (cond
12532 ((setq a (assoc w org-startup-options))
12533 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12534 (set (nth 1 a) (nth 2 a))))
12535 ((setq a (org-extract-log-state-settings w))
12536 (and (member (car a) org-todo-keywords-1)
12537 (push a org-todo-log-states)))))))
12539 (defun org-get-todo-sequence-head (kwd)
12540 "Return the head of the TODO sequence to which KWD belongs.
12541 If KWD is not set, check if there is a text property remembering the
12542 right sequence."
12543 (let (p)
12544 (cond
12545 ((not kwd)
12546 (or (get-text-property (point-at-bol) 'org-todo-head)
12547 (progn
12548 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12549 nil (point-at-eol)))
12550 (get-text-property p 'org-todo-head))))
12551 ((not (member kwd org-todo-keywords-1))
12552 (car org-todo-keywords-1))
12553 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12555 (defun org-fast-todo-selection ()
12556 "Fast TODO keyword selection with single keys.
12557 Returns the new TODO keyword, or nil if no state change should occur."
12558 (let* ((fulltable org-todo-key-alist)
12559 (done-keywords org-done-keywords) ;; needed for the faces.
12560 (maxlen (apply 'max (mapcar
12561 (lambda (x)
12562 (if (stringp (car x)) (string-width (car x)) 0))
12563 fulltable)))
12564 (expert nil)
12565 (fwidth (+ maxlen 3 1 3))
12566 (ncol (/ (- (window-width) 4) fwidth))
12567 tg cnt e c tbl
12568 groups ingroup)
12569 (save-excursion
12570 (save-window-excursion
12571 (if expert
12572 (set-buffer (get-buffer-create " *Org todo*"))
12573 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12574 (erase-buffer)
12575 (setq-local org-done-keywords done-keywords)
12576 (setq tbl fulltable cnt 0)
12577 (while (setq e (pop tbl))
12578 (cond
12579 ((equal e '(:startgroup))
12580 (push '() groups) (setq ingroup t)
12581 (unless (= cnt 0)
12582 (setq cnt 0)
12583 (insert "\n"))
12584 (insert "{ "))
12585 ((equal e '(:endgroup))
12586 (setq ingroup nil cnt 0)
12587 (insert "}\n"))
12588 ((equal e '(:newline))
12589 (unless (= cnt 0)
12590 (setq cnt 0)
12591 (insert "\n")
12592 (setq e (car tbl))
12593 (while (equal (car tbl) '(:newline))
12594 (insert "\n")
12595 (setq tbl (cdr tbl)))))
12597 (setq tg (car e) c (cdr e))
12598 (when ingroup (push tg (car groups)))
12599 (setq tg (org-add-props tg nil 'face
12600 (org-get-todo-face tg)))
12601 (when (and (= cnt 0) (not ingroup)) (insert " "))
12602 (insert "[" c "] " tg (make-string
12603 (- fwidth 4 (length tg)) ?\ ))
12604 (when (= (setq cnt (1+ cnt)) ncol)
12605 (insert "\n")
12606 (when ingroup (insert " "))
12607 (setq cnt 0)))))
12608 (insert "\n")
12609 (goto-char (point-min))
12610 (unless expert (org-fit-window-to-buffer))
12611 (message "[a-z..]:Set [SPC]:clear")
12612 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12613 (cond
12614 ((or (= c ?\C-g)
12615 (and (= c ?q) (not (rassoc c fulltable))))
12616 (setq quit-flag t))
12617 ((= c ?\ ) nil)
12618 ((setq e (rassoc c fulltable) tg (car e))
12620 (t (setq quit-flag t)))))))
12622 (defun org-entry-is-todo-p ()
12623 (member (org-get-todo-state) org-not-done-keywords))
12625 (defun org-entry-is-done-p ()
12626 (member (org-get-todo-state) org-done-keywords))
12628 (defun org-get-todo-state ()
12629 "Return the TODO keyword of the current subtree."
12630 (save-excursion
12631 (org-back-to-heading t)
12632 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12633 (match-end 2)
12634 (match-string 2))))
12636 (defun org-at-date-range-p (&optional inactive-ok)
12637 "Non-nil if point is inside a date range.
12639 When optional argument INACTIVE-OK is non-nil, also consider
12640 inactive time ranges.
12642 When this function returns a non-nil value, match data is set
12643 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12644 on INACTIVE-OK."
12645 (interactive)
12646 (save-excursion
12647 (catch 'exit
12648 (let ((pos (point)))
12649 (skip-chars-backward "^[<\r\n")
12650 (skip-chars-backward "<[")
12651 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12652 (>= (match-end 0) pos)
12653 (throw 'exit t))
12654 (skip-chars-backward "^<[\r\n")
12655 (skip-chars-backward "<[")
12656 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12657 (>= (match-end 0) pos)
12658 (throw 'exit t)))
12659 nil)))
12661 (defun org-get-repeat (&optional timestamp)
12662 "Check if there is a time-stamp with repeater in this entry.
12664 Return the repeater, as a string, or nil. Also return nil when
12665 this function is called before first heading.
12667 When optional argument TIMESTAMP is a string, extract the
12668 repeater from there instead."
12669 (save-match-data
12670 (cond (timestamp
12671 (and (string-match org-repeat-re timestamp)
12672 (match-string-no-properties 1 timestamp)))
12673 ((org-before-first-heading-p) nil)
12675 (save-excursion
12676 (org-back-to-heading t)
12677 (let ((end (org-entry-end-position)))
12678 (catch :repeat
12679 (while (re-search-forward org-repeat-re end t)
12680 (when (save-match-data (org-at-timestamp-p 'agenda))
12681 (throw :repeat (match-string-no-properties 1)))))))))))
12683 (defvar org-last-changed-timestamp)
12684 (defvar org-last-inserted-timestamp)
12685 (defvar org-log-post-message)
12686 (defvar org-log-note-purpose)
12687 (defvar org-log-note-how nil)
12688 (defvar org-log-note-extra)
12689 (defun org-auto-repeat-maybe (done-word)
12690 "Check if the current headline contains a repeated time-stamp.
12692 If yes, set TODO state back to what it was and change the base date
12693 of repeating deadline/scheduled time stamps to new date.
12695 This function is run automatically after each state change to a DONE state."
12696 (let* ((repeat (org-get-repeat))
12697 (aa (assoc org-last-state org-todo-kwd-alist))
12698 (interpret (nth 1 aa))
12699 (head (nth 2 aa))
12700 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12701 (msg "Entry repeats: ")
12702 (org-log-done nil)
12703 (org-todo-log-states nil)
12704 (end (copy-marker (org-entry-end-position))))
12705 (unwind-protect
12706 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12707 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12708 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12709 (and (stringp org-todo-repeat-to-state)
12710 org-todo-repeat-to-state)
12711 (and org-todo-repeat-to-state org-last-state))))
12712 (org-todo (cond
12713 ((and to-state (member to-state org-todo-keywords-1))
12714 to-state)
12715 ((eq interpret 'type) org-last-state)
12716 (head)
12717 (t 'none))))
12718 (org-back-to-heading t)
12719 (org-add-planning-info nil nil 'closed)
12720 ;; When `org-log-repeat' is non-nil or entry contains
12721 ;; a clock, set LAST_REPEAT property.
12722 (when (or org-log-repeat
12723 (catch :clock
12724 (save-excursion
12725 (while (re-search-forward org-clock-line-re end t)
12726 (when (org-at-clock-log-p) (throw :clock t))))))
12727 (org-entry-put nil "LAST_REPEAT" (format-time-string
12728 (org-time-stamp-format t t)
12729 (current-time))))
12730 (when org-log-repeat
12731 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12732 (memq 'org-add-log-note post-command-hook))
12733 ;; We are already setup for some record.
12734 (when (eq org-log-repeat 'note)
12735 ;; Make sure we take a note, not only a time stamp.
12736 (setq org-log-note-how 'note))
12737 ;; Set up for taking a record.
12738 (org-add-log-setup 'state
12739 (or done-word (car org-done-keywords))
12740 org-last-state
12741 org-log-repeat)))
12742 (let ((planning-re (regexp-opt
12743 (list org-scheduled-string org-deadline-string))))
12744 (while (re-search-forward org-ts-regexp end t)
12745 (let* ((ts (match-string 0))
12746 (planning? (org-at-planning-p))
12747 (type (if (not planning?) "Plain:"
12748 (save-excursion
12749 (re-search-backward
12750 planning-re (line-beginning-position) t)
12751 (match-string 0)))))
12752 (cond
12753 ;; Ignore fake time-stamps (e.g., within comments).
12754 ((not (org-at-timestamp-p 'agenda)))
12755 ;; Time-stamps without a repeater are usually
12756 ;; skipped. However, a SCHEDULED time-stamp without
12757 ;; one is removed, as they are no longer relevant.
12758 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12759 ts))
12760 (when (equal type org-scheduled-string)
12761 (org-remove-timestamp-with-keyword type)))
12763 (let ((n (string-to-number (match-string 2 ts)))
12764 (what (match-string 3 ts)))
12765 (when (equal what "w") (setq n (* n 7) what "d"))
12766 (when (and (equal what "h")
12767 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12768 ts)))
12769 (user-error
12770 "Cannot repeat in Repeat in %d hour(s) because no hour \
12771 has been set"
12773 ;; Preparation, see if we need to modify the start
12774 ;; date for the change.
12775 (when (match-end 1)
12776 (let ((time (save-match-data
12777 (org-time-string-to-time ts))))
12778 (cond
12779 ((equal (match-string 1 ts) ".")
12780 ;; Shift starting date to today
12781 (org-timestamp-change
12782 (- (org-today) (time-to-days time))
12783 'day))
12784 ((equal (match-string 1 ts) "+")
12785 (let ((nshiftmax 10)
12786 (nshift 0))
12787 (while (or (= nshift 0)
12788 (not (time-less-p (current-time) time)))
12789 (when (= (cl-incf nshift) nshiftmax)
12790 (or (y-or-n-p
12791 (format "%d repeater intervals were not \
12792 enough to shift date past today. Continue? "
12793 nshift))
12794 (user-error "Abort")))
12795 (org-timestamp-change n (cdr (assoc what whata)))
12796 (org-in-regexp org-ts-regexp3)
12797 (setq ts (match-string 1))
12798 (setq time
12799 (save-match-data
12800 (org-time-string-to-time ts)))))
12801 (org-timestamp-change (- n) (cdr (assoc what whata)))
12802 ;; Rematch, so that we have everything in place
12803 ;; for the real shift.
12804 (org-in-regexp org-ts-regexp3)
12805 (setq ts (match-string 1))
12806 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12807 ts)))))
12808 (save-excursion
12809 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12810 (setq msg
12811 (concat
12812 msg type " " org-last-changed-timestamp " "))))))))
12813 (setq org-log-post-message msg)
12814 (message "%s" msg))
12815 (set-marker end nil))))
12817 (defun org-show-todo-tree (arg)
12818 "Make a compact tree which shows all headlines marked with TODO.
12819 The tree will show the lines where the regexp matches, and all higher
12820 headlines above the match.
12821 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12822 With a numeric prefix N, construct a sparse tree for the Nth element
12823 of `org-todo-keywords-1'."
12824 (interactive "P")
12825 (let ((case-fold-search nil)
12826 (kwd-re
12827 (cond ((null arg) org-not-done-regexp)
12828 ((equal arg '(4))
12829 (let ((kwd
12830 (completing-read "Keyword (or KWD1|KWD2|...): "
12831 (mapcar #'list org-todo-keywords-1))))
12832 (concat "\\("
12833 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12834 "\\)\\>")))
12835 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12836 (regexp-quote (nth (1- (prefix-numeric-value arg))
12837 org-todo-keywords-1)))
12838 (t (user-error "Invalid prefix argument: %s" arg)))))
12839 (message "%d TODO entries found"
12840 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12842 (defun org--deadline-or-schedule (arg type time)
12843 "Insert DEADLINE or SCHEDULE information in current entry.
12844 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12845 `org-schedule' for information about ARG and TIME arguments."
12846 (let* ((deadline? (eq type 'deadline))
12847 (keyword (if deadline? org-deadline-string org-scheduled-string))
12848 (log (if deadline? org-log-redeadline org-log-reschedule))
12849 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12850 (old-date-time (and old-date (org-time-string-to-time old-date)))
12851 ;; Save repeater cookie from either TIME or current scheduled
12852 ;; time stamp. We are going to insert it back at the end of
12853 ;; the process.
12854 (repeater (or (and (org-string-nw-p time)
12855 ;; We use `org-repeat-re' because we need
12856 ;; to tell the difference between a real
12857 ;; repeater and a time delta, e.g. "+2d".
12858 (string-match org-repeat-re time)
12859 (match-string 1 time))
12860 (and (org-string-nw-p old-date)
12861 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12862 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12863 old-date)
12864 (match-string 1 old-date)))))
12865 (pcase arg
12866 (`(4)
12867 (if (not old-date)
12868 (message (if deadline? "Entry had no deadline to remove"
12869 "Entry was not scheduled"))
12870 (when (and old-date log)
12871 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12872 nil old-date log))
12873 (org-remove-timestamp-with-keyword keyword)
12874 (message (if deadline? "Entry no longer has a deadline."
12875 "Entry is no longer scheduled."))))
12876 (`(16)
12877 (save-excursion
12878 (org-back-to-heading t)
12879 (let ((regexp (if deadline? org-deadline-time-regexp
12880 org-scheduled-time-regexp)))
12881 (if (not (re-search-forward regexp (line-end-position 2) t))
12882 (user-error (if deadline? "No deadline information to update"
12883 "No scheduled information to update"))
12884 (let* ((rpl0 (match-string 1))
12885 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12886 (msg (if deadline? "Warn starting from" "Delay until")))
12887 (replace-match
12888 (concat keyword
12889 " <" rpl
12890 (format " -%dd"
12891 (abs (- (time-to-days
12892 (save-match-data
12893 (org-read-date
12894 nil t nil msg old-date-time)))
12895 (time-to-days old-date-time))))
12896 ">") t t))))))
12898 (org-add-planning-info type time 'closed)
12899 (when (and old-date
12901 (not (equal old-date org-last-inserted-timestamp)))
12902 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12903 org-last-inserted-timestamp
12904 old-date
12905 log))
12906 (when repeater
12907 (save-excursion
12908 (org-back-to-heading t)
12909 (when (re-search-forward
12910 (concat keyword " " org-last-inserted-timestamp)
12911 (line-end-position 2)
12913 (goto-char (1- (match-end 0)))
12914 (insert " " repeater)
12915 (setq org-last-inserted-timestamp
12916 (concat (substring org-last-inserted-timestamp 0 -1)
12917 " " repeater
12918 (substring org-last-inserted-timestamp -1))))))
12919 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12920 org-last-inserted-timestamp)))))
12922 (defun org-deadline (arg &optional time)
12923 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12924 With one universal prefix argument, remove any deadline from the item.
12925 With two universal prefix arguments, prompt for a warning delay.
12926 With argument TIME, set the deadline at the corresponding date. TIME
12927 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12928 (interactive "P")
12929 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12930 (org-map-entries
12931 (lambda () (org--deadline-or-schedule arg 'deadline time))
12933 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12934 'region-start-level
12935 'region)
12936 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12937 (org--deadline-or-schedule arg 'deadline time)))
12939 (defun org-schedule (arg &optional time)
12940 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12941 With one universal prefix argument, remove any scheduling date from the item.
12942 With two universal prefix arguments, prompt for a delay cookie.
12943 With argument TIME, scheduled at the corresponding date. TIME can
12944 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12945 (interactive "P")
12946 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12947 (org-map-entries
12948 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12950 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12951 'region-start-level
12952 'region)
12953 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12954 (org--deadline-or-schedule arg 'scheduled time)))
12956 (defun org-get-scheduled-time (pom &optional inherit)
12957 "Get the scheduled time as a time tuple, of a format suitable
12958 for calling org-schedule with, or if there is no scheduling,
12959 returns nil."
12960 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12961 (when time
12962 (apply 'encode-time (org-parse-time-string time)))))
12964 (defun org-get-deadline-time (pom &optional inherit)
12965 "Get the deadline as a time tuple, of a format suitable for
12966 calling org-deadline with, or if there is no scheduling, returns
12967 nil."
12968 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12969 (when time
12970 (apply 'encode-time (org-parse-time-string time)))))
12972 (defun org-remove-timestamp-with-keyword (keyword)
12973 "Remove all time stamps with KEYWORD in the current entry."
12974 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12975 beg)
12976 (save-excursion
12977 (org-back-to-heading t)
12978 (setq beg (point))
12979 (outline-next-heading)
12980 (while (re-search-backward re beg t)
12981 (replace-match "")
12982 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12983 (equal (char-before) ?\ ))
12984 (backward-delete-char 1)
12985 (when (string-match "^[ \t]*$" (buffer-substring
12986 (point-at-bol) (point-at-eol)))
12987 (delete-region (point-at-bol)
12988 (min (point-max) (1+ (point-at-eol))))))))))
12990 (defvar org-time-was-given) ; dynamically scoped parameter
12991 (defvar org-end-time-was-given) ; dynamically scoped parameter
12993 (defun org-at-planning-p ()
12994 "Non-nil when point is on a planning info line."
12995 ;; This is as accurate and faster than `org-element-at-point' since
12996 ;; planning info location is fixed in the section.
12997 (org-with-wide-buffer
12998 (beginning-of-line)
12999 (and (looking-at-p org-planning-line-re)
13000 (eq (point)
13001 (ignore-errors
13002 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13003 (org-back-to-heading t)
13004 (org-with-limited-levels (org-back-to-heading t)))
13005 (line-beginning-position 2))))))
13007 (defun org-add-planning-info (what &optional time &rest remove)
13008 "Insert new timestamp with keyword in the planning line.
13009 WHAT indicates what kind of time stamp to add. It is a symbol
13010 among `closed', `deadline', `scheduled' and nil. TIME indicates
13011 the time to use. If none is given, the user is prompted for
13012 a date. REMOVE indicates what kind of entries to remove. An old
13013 WHAT entry will also be removed."
13014 (let (org-time-was-given org-end-time-was-given default-time default-input)
13015 (catch 'exit
13016 (when (and (memq what '(scheduled deadline))
13017 (or (not time)
13018 (and (stringp time)
13019 (string-match "^[-+]+[0-9]" time))))
13020 ;; Try to get a default date/time from existing timestamp
13021 (save-excursion
13022 (org-back-to-heading t)
13023 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13024 (when (re-search-forward (if (eq what 'scheduled)
13025 org-scheduled-time-regexp
13026 org-deadline-time-regexp)
13027 end t)
13028 (setq ts (match-string 1)
13029 default-time (apply 'encode-time (org-parse-time-string ts))
13030 default-input (and ts (org-get-compact-tod ts)))))))
13031 (when what
13032 (setq time
13033 (if (stringp time)
13034 ;; This is a string (relative or absolute), set
13035 ;; proper date.
13036 (apply #'encode-time
13037 (org-read-date-analyze
13038 time default-time (decode-time default-time)))
13039 ;; If necessary, get the time from the user
13040 (or time (org-read-date nil 'to-time nil nil
13041 default-time default-input)))))
13043 (org-with-wide-buffer
13044 (org-back-to-heading t)
13045 (forward-line)
13046 (unless (bolp) (insert "\n"))
13047 (cond ((looking-at-p org-planning-line-re)
13048 ;; Move to current indentation.
13049 (skip-chars-forward " \t")
13050 ;; Check if we have to remove something.
13051 (dolist (type (if what (cons what remove) remove))
13052 (save-excursion
13053 (when (re-search-forward
13054 (cl-case type
13055 (closed org-closed-time-regexp)
13056 (deadline org-deadline-time-regexp)
13057 (scheduled org-scheduled-time-regexp)
13058 (otherwise
13059 (error "Invalid planning type: %s" type)))
13060 (line-end-position) t)
13061 ;; Delete until next keyword or end of line.
13062 (delete-region
13063 (match-beginning 0)
13064 (if (re-search-forward org-keyword-time-not-clock-regexp
13065 (line-end-position)
13067 (match-beginning 0)
13068 (line-end-position))))))
13069 ;; If there is nothing more to add and no more keyword
13070 ;; is left, remove the line completely.
13071 (if (and (looking-at-p "[ \t]*$") (not what))
13072 (delete-region (line-beginning-position)
13073 (line-beginning-position 2))
13074 ;; If we removed last keyword, do not leave trailing
13075 ;; white space at the end of line.
13076 (let ((p (point)))
13077 (save-excursion
13078 (end-of-line)
13079 (unless (= (skip-chars-backward " \t" p) 0)
13080 (delete-region (point) (line-end-position)))))))
13081 ((not what) (throw 'exit nil)) ; Nothing to do.
13082 (t (insert-before-markers "\n")
13083 (backward-char 1)
13084 (when org-adapt-indentation
13085 (indent-to-column (1+ (org-outline-level))))))
13086 (when what
13087 ;; Insert planning keyword.
13088 (insert (cl-case what
13089 (closed org-closed-string)
13090 (deadline org-deadline-string)
13091 (scheduled org-scheduled-string)
13092 (otherwise (error "Invalid planning type: %s" what)))
13093 " ")
13094 ;; Insert associated timestamp.
13095 (let ((ts (org-insert-time-stamp
13096 time
13097 (or org-time-was-given
13098 (and (eq what 'closed) org-log-done-with-time))
13099 (eq what 'closed)
13100 nil nil (list org-end-time-was-given))))
13101 (unless (eolp) (insert " "))
13102 ts))))))
13104 (defvar org-log-note-marker (make-marker)
13105 "Marker pointing at the entry where the note is to be inserted.")
13106 (defvar org-log-note-purpose nil)
13107 (defvar org-log-note-state nil)
13108 (defvar org-log-note-previous-state nil)
13109 (defvar org-log-note-extra nil)
13110 (defvar org-log-note-window-configuration nil)
13111 (defvar org-log-note-return-to (make-marker))
13112 (defvar org-log-note-effective-time nil
13113 "Remembered current time so that dynamically scoped
13114 `org-extend-today-until' affects timestamps in state change log")
13116 (defvar org-log-post-message nil
13117 "Message to be displayed after a log note has been stored.
13118 The auto-repeater uses this.")
13120 (defun org-add-note ()
13121 "Add a note to the current entry.
13122 This is done in the same way as adding a state change note."
13123 (interactive)
13124 (org-add-log-setup 'note))
13126 (defun org-log-beginning (&optional create)
13127 "Return expected start of log notes in current entry.
13128 When optional argument CREATE is non-nil, the function creates
13129 a drawer to store notes, if necessary. Returned position ignores
13130 narrowing."
13131 (org-with-wide-buffer
13132 (let ((drawer (org-log-into-drawer)))
13133 (cond
13134 (drawer
13135 (org-end-of-meta-data)
13136 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13137 (end (if (org-at-heading-p) (point)
13138 (save-excursion (outline-next-heading) (point))))
13139 (case-fold-search t))
13140 (catch 'exit
13141 ;; Try to find existing drawer.
13142 (while (re-search-forward regexp end t)
13143 (let ((element (org-element-at-point)))
13144 (when (eq (org-element-type element) 'drawer)
13145 (let ((cend (org-element-property :contents-end element)))
13146 (when (and (not org-log-states-order-reversed) cend)
13147 (goto-char cend)))
13148 (throw 'exit nil))))
13149 ;; No drawer found. Create one, if permitted.
13150 (when create
13151 (unless (bolp) (insert "\n"))
13152 (let ((beg (point)))
13153 (insert ":" drawer ":\n:END:\n")
13154 (org-indent-region beg (point))
13155 (org-flag-region
13156 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13157 (end-of-line -1)))))
13159 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13160 (skip-chars-forward " \t\n")
13161 (beginning-of-line)
13162 (unless org-log-states-order-reversed
13163 (org-skip-over-state-notes)
13164 (skip-chars-backward " \t\n")
13165 (forward-line)))))
13166 (if (bolp) (point) (line-beginning-position 2))))
13168 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13169 "Set up the post command hook to take a note.
13170 If this is about to TODO state change, the new state is expected in STATE.
13171 HOW is an indicator what kind of note should be created.
13172 EXTRA is additional text that will be inserted into the notes buffer."
13173 (move-marker org-log-note-marker (point))
13174 (setq org-log-note-purpose purpose
13175 org-log-note-state state
13176 org-log-note-previous-state prev-state
13177 org-log-note-how how
13178 org-log-note-extra extra
13179 org-log-note-effective-time (org-current-effective-time))
13180 (add-hook 'post-command-hook 'org-add-log-note 'append))
13182 (defun org-skip-over-state-notes ()
13183 "Skip past the list of State notes in an entry."
13184 (when (ignore-errors (goto-char (org-in-item-p)))
13185 (let* ((struct (org-list-struct))
13186 (prevs (org-list-prevs-alist struct))
13187 (regexp
13188 (concat "[ \t]*- +"
13189 (replace-regexp-in-string
13190 " +" " +"
13191 (org-replace-escapes
13192 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13193 `(("%d" . ,org-ts-regexp-inactive)
13194 ("%D" . ,org-ts-regexp)
13195 ("%s" . "\"\\S-+\"")
13196 ("%S" . "\"\\S-+\"")
13197 ("%t" . ,org-ts-regexp-inactive)
13198 ("%T" . ,org-ts-regexp)
13199 ("%u" . ".*?")
13200 ("%U" . ".*?")))))))
13201 (while (looking-at-p regexp)
13202 (goto-char (or (org-list-get-next-item (point) struct prevs)
13203 (org-list-get-item-end (point) struct)))))))
13205 (defun org-add-log-note (&optional _purpose)
13206 "Pop up a window for taking a note, and add this note later."
13207 (remove-hook 'post-command-hook 'org-add-log-note)
13208 (setq org-log-note-window-configuration (current-window-configuration))
13209 (delete-other-windows)
13210 (move-marker org-log-note-return-to (point))
13211 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13212 (goto-char org-log-note-marker)
13213 (org-switch-to-buffer-other-window "*Org Note*")
13214 (erase-buffer)
13215 (if (memq org-log-note-how '(time state))
13216 (org-store-log-note)
13217 (let ((org-inhibit-startup t)) (org-mode))
13218 (insert (format "# Insert note for %s.
13219 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13220 (cl-case org-log-note-purpose
13221 (clock-out "stopped clock")
13222 (done "closed todo item")
13223 (reschedule "rescheduling")
13224 (delschedule "no longer scheduled")
13225 (redeadline "changing deadline")
13226 (deldeadline "removing deadline")
13227 (refile "refiling")
13228 (note "this entry")
13229 (state
13230 (format "state change from \"%s\" to \"%s\""
13231 (or org-log-note-previous-state "")
13232 (or org-log-note-state "")))
13233 (t (error "This should not happen")))))
13234 (when org-log-note-extra (insert org-log-note-extra))
13235 (setq-local org-finish-function 'org-store-log-note)
13236 (run-hooks 'org-log-buffer-setup-hook)))
13238 (defvar org-note-abort nil) ; dynamically scoped
13239 (defun org-store-log-note ()
13240 "Finish taking a log note, and insert it to where it belongs."
13241 (let ((txt (prog1 (buffer-string)
13242 (kill-buffer)))
13243 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13244 lines)
13245 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13246 (setq txt (replace-match "" t t txt)))
13247 (when (string-match "\\s-+\\'" txt)
13248 (setq txt (replace-match "" t t txt)))
13249 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13250 (when (org-string-nw-p note)
13251 (setq note
13252 (org-replace-escapes
13253 note
13254 (list (cons "%u" (user-login-name))
13255 (cons "%U" user-full-name)
13256 (cons "%t" (format-time-string
13257 (org-time-stamp-format 'long 'inactive)
13258 org-log-note-effective-time))
13259 (cons "%T" (format-time-string
13260 (org-time-stamp-format 'long nil)
13261 org-log-note-effective-time))
13262 (cons "%d" (format-time-string
13263 (org-time-stamp-format nil 'inactive)
13264 org-log-note-effective-time))
13265 (cons "%D" (format-time-string
13266 (org-time-stamp-format nil nil)
13267 org-log-note-effective-time))
13268 (cons "%s" (cond
13269 ((not org-log-note-state) "")
13270 ((string-match-p org-ts-regexp
13271 org-log-note-state)
13272 (format "\"[%s]\""
13273 (substring org-log-note-state 1 -1)))
13274 (t (format "\"%s\"" org-log-note-state))))
13275 (cons "%S"
13276 (cond
13277 ((not org-log-note-previous-state) "")
13278 ((string-match-p org-ts-regexp
13279 org-log-note-previous-state)
13280 (format "\"[%s]\""
13281 (substring
13282 org-log-note-previous-state 1 -1)))
13283 (t (format "\"%s\""
13284 org-log-note-previous-state)))))))
13285 (when lines (setq note (concat note " \\\\")))
13286 (push note lines))
13287 (when (and lines (not org-note-abort))
13288 (with-current-buffer (marker-buffer org-log-note-marker)
13289 (org-with-wide-buffer
13290 ;; Find location for the new note.
13291 (goto-char org-log-note-marker)
13292 (set-marker org-log-note-marker nil)
13293 ;; Note associated to a clock is to be located right after
13294 ;; the clock. Do not move point.
13295 (unless (eq org-log-note-purpose 'clock-out)
13296 (goto-char (org-log-beginning t)))
13297 ;; Make sure point is at the beginning of an empty line.
13298 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13299 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13300 ;; In an existing list, add a new item at the top level.
13301 ;; Otherwise, indent line like a regular one.
13302 (let ((itemp (org-in-item-p)))
13303 (if itemp
13304 (indent-line-to
13305 (let ((struct (save-excursion
13306 (goto-char itemp) (org-list-struct))))
13307 (org-list-get-ind (org-list-get-top-point struct) struct)))
13308 (org-indent-line)))
13309 (insert (org-list-bullet-string "-") (pop lines))
13310 (let ((ind (org-list-item-body-column (line-beginning-position))))
13311 (dolist (line lines)
13312 (insert "\n")
13313 (indent-line-to ind)
13314 (insert line)))
13315 (message "Note stored")
13316 (org-back-to-heading t))
13317 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13318 ;; from within `org-add-log-note' because `buffer-undo-list'
13319 ;; is then modified outside of `org-with-remote-undo'.
13320 (when (eq this-command 'org-agenda-todo)
13321 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13322 ;; Don't add undo information when called from `org-agenda-todo'.
13323 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13324 (set-window-configuration org-log-note-window-configuration)
13325 (with-current-buffer (marker-buffer org-log-note-return-to)
13326 (goto-char org-log-note-return-to))
13327 (move-marker org-log-note-return-to nil)
13328 (when org-log-post-message (message "%s" org-log-post-message))))
13330 (defun org-remove-empty-drawer-at (pos)
13331 "Remove an empty drawer at position POS.
13332 POS may also be a marker."
13333 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13334 (org-with-wide-buffer
13335 (goto-char pos)
13336 (let ((drawer (org-element-at-point)))
13337 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13338 (not (org-element-property :contents-begin drawer)))
13339 (delete-region (org-element-property :begin drawer)
13340 (progn (goto-char (org-element-property :end drawer))
13341 (skip-chars-backward " \r\t\n")
13342 (forward-line)
13343 (point))))))))
13345 (defvar org-ts-type nil)
13346 (defun org-sparse-tree (&optional arg type)
13347 "Create a sparse tree, prompt for the details.
13348 This command can create sparse trees. You first need to select the type
13349 of match used to create the tree:
13351 t Show all TODO entries.
13352 T Show entries with a specific TODO keyword.
13353 m Show entries selected by a tags/property match.
13354 p Enter a property name and its value (both with completion on existing
13355 names/values) and show entries with that property.
13356 r Show entries matching a regular expression (`/' can be used as well).
13357 b Show deadlines and scheduled items before a date.
13358 a Show deadlines and scheduled items after a date.
13359 d Show deadlines due within `org-deadline-warning-days'.
13360 D Show deadlines and scheduled items between a date range."
13361 (interactive "P")
13362 (setq type (or type org-sparse-tree-default-date-type))
13363 (setq org-ts-type type)
13364 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13365 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13366 \[c]ycle through date types: %s"
13367 (cl-case type
13368 (all "all timestamps")
13369 (scheduled "only scheduled")
13370 (deadline "only deadline")
13371 (active "only active timestamps")
13372 (inactive "only inactive timestamps")
13373 (closed "with a closed time-stamp")
13374 (otherwise "scheduled/deadline")))
13375 (let ((answer (read-char-exclusive)))
13376 (cl-case answer
13378 (org-sparse-tree
13380 (cadr
13381 (memq type '(nil all scheduled deadline active inactive closed)))))
13382 (?d (call-interactively 'org-check-deadlines))
13383 (?b (call-interactively 'org-check-before-date))
13384 (?a (call-interactively 'org-check-after-date))
13385 (?D (call-interactively 'org-check-dates-range))
13386 (?t (call-interactively 'org-show-todo-tree))
13387 (?T (org-show-todo-tree '(4)))
13388 (?m (call-interactively 'org-match-sparse-tree))
13389 ((?p ?P)
13390 (let* ((kwd (completing-read
13391 "Property: " (mapcar #'list (org-buffer-property-keys))))
13392 (value (completing-read
13393 "Value: " (mapcar #'list (org-property-values kwd)))))
13394 (unless (string-match "\\`{.*}\\'" value)
13395 (setq value (concat "\"" value "\"")))
13396 (org-match-sparse-tree arg (concat kwd "=" value))))
13397 ((?r ?R ?/) (call-interactively 'org-occur))
13398 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13400 (defvar-local org-occur-highlights nil
13401 "List of overlays used for occur matches.")
13402 (defvar-local org-occur-parameters nil
13403 "Parameters of the active org-occur calls.
13404 This is a list, each call to org-occur pushes as cons cell,
13405 containing the regular expression and the callback, onto the list.
13406 The list can contain several entries if `org-occur' has been called
13407 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13408 will only contain one set of parameters. When the highlights are
13409 removed (for example with `C-c C-c', or with the next edit (depending
13410 on `org-remove-highlights-with-change'), this variable is emptied
13411 as well.")
13413 (defun org-occur (regexp &optional keep-previous callback)
13414 "Make a compact tree which shows all matches of REGEXP.
13416 The tree will show the lines where the regexp matches, and any other context
13417 defined in `org-show-context-detail', which see.
13419 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13420 done by a previous call to `org-occur' will be kept, to allow stacking of
13421 calls to this command.
13423 Optional argument CALLBACK can be a function of no argument. In this case,
13424 it is called with point at the end of the match, match data being set
13425 accordingly. Current match is shown only if the return value is non-nil.
13426 The function must neither move point nor alter narrowing."
13427 (interactive "sRegexp: \nP")
13428 (when (equal regexp "")
13429 (user-error "Regexp cannot be empty"))
13430 (unless keep-previous
13431 (org-remove-occur-highlights nil nil t))
13432 (push (cons regexp callback) org-occur-parameters)
13433 (let ((cnt 0))
13434 (save-excursion
13435 (goto-char (point-min))
13436 (when (or (not keep-previous) ; do not want to keep
13437 (not org-occur-highlights)) ; no previous matches
13438 ;; hide everything
13439 (org-overview))
13440 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13441 (isearch-no-upper-case-p regexp t)
13442 org-occur-case-fold-search)))
13443 (while (re-search-forward regexp nil t)
13444 (when (or (not callback)
13445 (save-match-data (funcall callback)))
13446 (setq cnt (1+ cnt))
13447 (when org-highlight-sparse-tree-matches
13448 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13449 (org-show-context 'occur-tree)))))
13450 (when org-remove-highlights-with-change
13451 (add-hook 'before-change-functions 'org-remove-occur-highlights
13452 nil 'local))
13453 (unless org-sparse-tree-open-archived-trees
13454 (org-hide-archived-subtrees (point-min) (point-max)))
13455 (run-hooks 'org-occur-hook)
13456 (when (called-interactively-p 'interactive)
13457 (message "%d match(es) for regexp %s" cnt regexp))
13458 cnt))
13460 (defun org-occur-next-match (&optional n _reset)
13461 "Function for `next-error-function' to find sparse tree matches.
13462 N is the number of matches to move, when negative move backwards.
13463 This function always goes back to the starting point when no
13464 match is found."
13465 (let* ((limit (if (< n 0) (point-min) (point-max)))
13466 (search-func (if (< n 0)
13467 'previous-single-char-property-change
13468 'next-single-char-property-change))
13469 (n (abs n))
13470 (pos (point))
13472 (catch 'exit
13473 (while (setq p1 (funcall search-func (point) 'org-type))
13474 (when (equal p1 limit)
13475 (goto-char pos)
13476 (user-error "No more matches"))
13477 (when (equal (get-char-property p1 'org-type) 'org-occur)
13478 (setq n (1- n))
13479 (when (= n 0)
13480 (goto-char p1)
13481 (throw 'exit (point))))
13482 (goto-char p1))
13483 (goto-char p1)
13484 (user-error "No more matches"))))
13486 (defun org-highlight-new-match (beg end)
13487 "Highlight from BEG to END and mark the highlight is an occur headline."
13488 (let ((ov (make-overlay beg end)))
13489 (overlay-put ov 'face 'secondary-selection)
13490 (overlay-put ov 'org-type 'org-occur)
13491 (push ov org-occur-highlights)))
13493 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13494 "Remove the occur highlights from the buffer.
13495 BEG and END are ignored. If NOREMOVE is nil, remove this function
13496 from the `before-change-functions' in the current buffer."
13497 (interactive)
13498 (unless org-inhibit-highlight-removal
13499 (mapc #'delete-overlay org-occur-highlights)
13500 (setq org-occur-highlights nil)
13501 (setq org-occur-parameters nil)
13502 (unless noremove
13503 (remove-hook 'before-change-functions
13504 'org-remove-occur-highlights 'local))))
13506 ;;;; Priorities
13508 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13509 "Regular expression matching the priority indicator.")
13511 (defvar org-remove-priority-next-time nil)
13513 (defun org-priority-up ()
13514 "Increase the priority of the current item."
13515 (interactive)
13516 (org-priority 'up))
13518 (defun org-priority-down ()
13519 "Decrease the priority of the current item."
13520 (interactive)
13521 (org-priority 'down))
13523 (defun org-priority (&optional action show)
13524 "Change the priority of an item.
13526 When called interactively with a `\\[universal-argument]' prefix,
13527 show the priority in the minibuffer instead of changing it.
13529 When called programatically, ACTION can be `set', `up', `down',
13530 or a character."
13531 (interactive "P")
13532 (when show
13533 ;; Deprecation warning inserted for Org 9.2; once enough time has
13534 ;; passed the SHOW argument should be removed.
13535 (warn "`org-priority' called with deprecated SHOW argument"))
13536 (if (equal action '(4))
13537 (org-show-priority)
13538 (unless org-enable-priority-commands
13539 (user-error "Priority commands are disabled"))
13540 (setq action (or action 'set))
13541 (let (current new news have remove)
13542 (save-excursion
13543 (org-back-to-heading t)
13544 (when (looking-at org-priority-regexp)
13545 (setq current (string-to-char (match-string 2))
13546 have t))
13547 (cond
13548 ((eq action 'remove)
13549 (setq remove t new ?\ ))
13550 ((or (eq action 'set)
13551 (integerp action))
13552 (if (not (eq action 'set))
13553 (setq new action)
13554 (message "Priority %c-%c, SPC to remove: "
13555 org-highest-priority org-lowest-priority)
13556 (save-match-data
13557 (setq new (read-char-exclusive))))
13558 (when (and (= (upcase org-highest-priority) org-highest-priority)
13559 (= (upcase org-lowest-priority) org-lowest-priority))
13560 (setq new (upcase new)))
13561 (cond ((equal new ?\s) (setq remove t))
13562 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13563 (user-error "Priority must be between `%c' and `%c'"
13564 org-highest-priority org-lowest-priority))))
13565 ((eq action 'up)
13566 (setq new (if have
13567 (1- current) ; normal cycling
13568 ;; last priority was empty
13569 (if (eq last-command this-command)
13570 org-lowest-priority ; wrap around empty to lowest
13571 ;; default
13572 (if org-priority-start-cycle-with-default
13573 org-default-priority
13574 (1- org-default-priority))))))
13575 ((eq action 'down)
13576 (setq new (if have
13577 (1+ current) ; normal cycling
13578 ;; last priority was empty
13579 (if (eq last-command this-command)
13580 org-highest-priority ; wrap around empty to highest
13581 ;; default
13582 (if org-priority-start-cycle-with-default
13583 org-default-priority
13584 (1+ org-default-priority))))))
13585 (t (user-error "Invalid action")))
13586 (when (or (< (upcase new) org-highest-priority)
13587 (> (upcase new) org-lowest-priority))
13588 (if (and (memq action '(up down))
13589 (not have) (not (eq last-command this-command)))
13590 ;; `new' is from default priority
13591 (error
13592 "The default can not be set, see `org-default-priority' why")
13593 ;; normal cycling: `new' is beyond highest/lowest priority
13594 ;; and is wrapped around to the empty priority
13595 (setq remove t)))
13596 (setq news (format "%c" new))
13597 (if have
13598 (if remove
13599 (replace-match "" t t nil 1)
13600 (replace-match news t t nil 2))
13601 (if remove
13602 (user-error "No priority cookie found in line")
13603 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13604 (if (match-end 2)
13605 (progn
13606 (goto-char (match-end 2))
13607 (insert " [#" news "]"))
13608 (goto-char (match-beginning 3))
13609 (insert "[#" news "] "))))
13610 (org-align-tags))
13611 (if remove
13612 (message "Priority removed")
13613 (message "Priority of current item set to %s" news)))))
13615 (defun org-show-priority ()
13616 "Show the priority of the current item.
13617 This priority is composed of the main priority given with the [#A] cookies,
13618 and by additional input from the age of a schedules or deadline entry."
13619 (interactive)
13620 (let ((pri (if (eq major-mode 'org-agenda-mode)
13621 (org-get-at-bol 'priority)
13622 (save-excursion
13623 (save-match-data
13624 (beginning-of-line)
13625 (and (looking-at org-heading-regexp)
13626 (org-get-priority (match-string 0))))))))
13627 (message "Priority is %d" (if pri pri -1000))))
13629 (defun org-get-priority (s)
13630 "Find priority cookie and return priority."
13631 (save-match-data
13632 (if (functionp org-get-priority-function)
13633 (funcall org-get-priority-function)
13634 (if (not (string-match org-priority-regexp s))
13635 (* 1000 (- org-lowest-priority org-default-priority))
13636 (* 1000 (- org-lowest-priority
13637 (string-to-char (match-string 2 s))))))))
13639 ;;;; Tags
13641 (defvar org-agenda-archives-mode)
13642 (defvar org-map-continue-from nil
13643 "Position from where mapping should continue.
13644 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13646 (defvar org-scanner-tags nil
13647 "The current tag list while the tags scanner is running.")
13649 (defvar org-trust-scanner-tags nil
13650 "Should `org-get-tags' use the tags for the scanner.
13651 This is for internal dynamical scoping only.
13652 When this is non-nil, the function `org-get-tags' will return the value
13653 of `org-scanner-tags' instead of building the list by itself. This
13654 can lead to large speed-ups when the tags scanner is used in a file with
13655 many entries, and when the list of tags is retrieved, for example to
13656 obtain a list of properties. Building the tags list for each entry in such
13657 a file becomes an N^2 operation - but with this variable set, it scales
13658 as N.")
13660 (defvar org--matcher-tags-todo-only nil)
13662 (defun org-scan-tags (action matcher todo-only &optional start-level)
13663 "Scan headline tags with inheritance and produce output ACTION.
13665 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13666 or `agenda' to produce an entry list for an agenda view. It can also be
13667 a Lisp form or a function that should be called at each matched headline, in
13668 this case the return value is a list of all return values from these calls.
13670 MATCHER is a function accepting three arguments, returning
13671 a non-nil value whenever a given set of tags qualifies a headline
13672 for inclusion. See `org-make-tags-matcher' for more information.
13673 As a special case, it can also be set to t (respectively nil) in
13674 order to match all (respectively none) headline.
13676 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13677 included in the output.
13679 START-LEVEL can be a string with asterisks, reducing the scope to
13680 headlines matching this string."
13681 (require 'org-agenda)
13682 (let* ((re (concat "^"
13683 (if start-level
13684 ;; Get the correct level to match
13685 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13686 org-outline-regexp)
13687 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13688 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13689 (props (list 'face 'default
13690 'done-face 'org-agenda-done
13691 'undone-face 'default
13692 'mouse-face 'highlight
13693 'org-not-done-regexp org-not-done-regexp
13694 'org-todo-regexp org-todo-regexp
13695 'org-complex-heading-regexp org-complex-heading-regexp
13696 'help-echo
13697 (format "mouse-2 or RET jump to Org file %S"
13698 (abbreviate-file-name
13699 (or (buffer-file-name (buffer-base-buffer))
13700 (buffer-name (buffer-base-buffer)))))))
13701 (org-map-continue-from nil)
13702 lspos tags tags-list
13703 (tags-alist (list (cons 0 org-file-tags)))
13704 (llast 0) rtn rtn1 level category i txt
13705 todo marker entry priority
13706 ts-date ts-date-type ts-date-pair)
13707 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13708 (setq action (list 'lambda nil action)))
13709 (save-excursion
13710 (goto-char (point-min))
13711 (when (eq action 'sparse-tree)
13712 (org-overview)
13713 (org-remove-occur-highlights))
13714 (while (let (case-fold-search)
13715 (re-search-forward re nil t))
13716 (setq org-map-continue-from nil)
13717 (catch :skip
13718 ;; Ignore closing parts of inline tasks.
13719 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13720 (throw :skip t))
13721 (setq todo
13722 ;; TODO: is the 1-2 difference a bug?
13723 (when (match-end 1) (match-string-no-properties 2))
13724 tags (when (match-end 4) (match-string-no-properties 4)))
13725 (goto-char (setq lspos (match-beginning 0)))
13726 (setq level (org-reduced-level (org-outline-level))
13727 category (org-get-category))
13728 (when (eq action 'agenda)
13729 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13730 ts-date (car ts-date-pair)
13731 ts-date-type (cdr ts-date-pair)))
13732 (setq i llast llast level)
13733 ;; remove tag lists from same and sublevels
13734 (while (>= i level)
13735 (when (setq entry (assoc i tags-alist))
13736 (setq tags-alist (delete entry tags-alist)))
13737 (setq i (1- i)))
13738 ;; add the next tags
13739 (when tags
13740 (setq tags (org-split-string tags ":")
13741 tags-alist
13742 (cons (cons level tags) tags-alist)))
13743 ;; compile tags for current headline
13744 (setq tags-list
13745 (if org-use-tag-inheritance
13746 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13747 tags)
13748 org-scanner-tags tags-list)
13749 (when org-use-tag-inheritance
13750 (setcdr (car tags-alist)
13751 (mapcar (lambda (x)
13752 (setq x (copy-sequence x))
13753 (org-add-prop-inherited x))
13754 (cdar tags-alist))))
13755 (when (and tags org-use-tag-inheritance
13756 (or (not (eq t org-use-tag-inheritance))
13757 org-tags-exclude-from-inheritance))
13758 ;; Selective inheritance, remove uninherited ones.
13759 (setcdr (car tags-alist)
13760 (org-remove-uninherited-tags (cdar tags-alist))))
13761 (when (and
13763 ;; eval matcher only when the todo condition is OK
13764 (and (or (not todo-only) (member todo org-todo-keywords-1))
13765 (if (functionp matcher)
13766 (let ((case-fold-search t) (org-trust-scanner-tags t))
13767 (funcall matcher todo tags-list level))
13768 matcher))
13770 ;; Call the skipper, but return t if it does not
13771 ;; skip, so that the `and' form continues evaluating.
13772 (progn
13773 (unless (eq action 'sparse-tree) (org-agenda-skip))
13776 ;; Check if timestamps are deselecting this entry
13777 (or (not todo-only)
13778 (and (member todo org-todo-keywords-1)
13779 (or (not org-agenda-tags-todo-honor-ignore-options)
13780 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13782 ;; select this headline
13783 (cond
13784 ((eq action 'sparse-tree)
13785 (and org-highlight-sparse-tree-matches
13786 (org-get-heading) (match-end 0)
13787 (org-highlight-new-match
13788 (match-beginning 1) (match-end 1)))
13789 (org-show-context 'tags-tree))
13790 ((eq action 'agenda)
13791 (setq txt (org-agenda-format-item
13793 (concat
13794 (if (eq org-tags-match-list-sublevels 'indented)
13795 (make-string (1- level) ?.) "")
13796 (org-get-heading))
13797 (make-string level ?\s)
13798 category
13799 tags-list)
13800 priority (org-get-priority txt))
13801 (goto-char lspos)
13802 (setq marker (org-agenda-new-marker))
13803 (org-add-props txt props
13804 'org-marker marker 'org-hd-marker marker 'org-category category
13805 'todo-state todo
13806 'ts-date ts-date
13807 'priority priority
13808 'type (concat "tagsmatch" ts-date-type))
13809 (push txt rtn))
13810 ((functionp action)
13811 (setq org-map-continue-from nil)
13812 (save-excursion
13813 (setq rtn1 (funcall action))
13814 (push rtn1 rtn)))
13815 (t (user-error "Invalid action")))
13817 ;; if we are to skip sublevels, jump to end of subtree
13818 (unless org-tags-match-list-sublevels
13819 (org-end-of-subtree t)
13820 (backward-char 1))))
13821 ;; Get the correct position from where to continue
13822 (if org-map-continue-from
13823 (goto-char org-map-continue-from)
13824 (and (= (point) lspos) (end-of-line 1)))))
13825 (when (and (eq action 'sparse-tree)
13826 (not org-sparse-tree-open-archived-trees))
13827 (org-hide-archived-subtrees (point-min) (point-max)))
13828 (nreverse rtn)))
13830 (defun org-remove-uninherited-tags (tags)
13831 "Remove all tags that are not inherited from the list TAGS."
13832 (cond
13833 ((eq org-use-tag-inheritance t)
13834 (if org-tags-exclude-from-inheritance
13835 (org-delete-all org-tags-exclude-from-inheritance tags)
13836 tags))
13837 ((not org-use-tag-inheritance) nil)
13838 ((stringp org-use-tag-inheritance)
13839 (delq nil (mapcar
13840 (lambda (x)
13841 (if (and (string-match org-use-tag-inheritance x)
13842 (not (member x org-tags-exclude-from-inheritance)))
13843 x nil))
13844 tags)))
13845 ((listp org-use-tag-inheritance)
13846 (delq nil (mapcar
13847 (lambda (x)
13848 (if (member x org-use-tag-inheritance) x nil))
13849 tags)))))
13851 (defun org-match-sparse-tree (&optional todo-only match)
13852 "Create a sparse tree according to tags string MATCH.
13854 MATCH is a string with match syntax. It can contain a selection
13855 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13856 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13857 those. See the manual for details.
13859 If optional argument TODO-ONLY is non-nil, only select lines that
13860 are also TODO tasks."
13861 (interactive "P")
13862 (org-agenda-prepare-buffers (list (current-buffer)))
13863 (let ((org--matcher-tags-todo-only todo-only))
13864 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13865 org--matcher-tags-todo-only)))
13867 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13869 (defvar org-cached-props nil)
13870 (defun org-cached-entry-get (pom property)
13871 (if (or (eq t org-use-property-inheritance)
13872 (and (stringp org-use-property-inheritance)
13873 (let ((case-fold-search t))
13874 (string-match-p org-use-property-inheritance property)))
13875 (and (listp org-use-property-inheritance)
13876 (member-ignore-case property org-use-property-inheritance)))
13877 ;; Caching is not possible, check it directly.
13878 (org-entry-get pom property 'inherit)
13879 ;; Get all properties, so we can do complicated checks easily.
13880 (cdr (assoc-string property
13881 (or org-cached-props
13882 (setq org-cached-props (org-entry-properties pom)))
13883 t))))
13885 (defun org-global-tags-completion-table (&optional files)
13886 "Return the list of all tags in all agenda buffer/files.
13887 Optional FILES argument is a list of files which can be used
13888 instead of the agenda files."
13889 (save-excursion
13890 (org-uniquify
13891 (delq nil
13892 (apply #'append
13893 (mapcar
13894 (lambda (file)
13895 (set-buffer (find-file-noselect file))
13896 (org--tag-add-to-alist
13897 (org-get-buffer-tags)
13898 (mapcar (lambda (x)
13899 (and (stringp (car-safe x))
13900 (list (car-safe x))))
13901 org-current-tag-alist)))
13902 (if (car-safe files) files
13903 (org-agenda-files))))))))
13905 (defun org-make-tags-matcher (match)
13906 "Create the TAGS/TODO matcher form for the selection string MATCH.
13908 Returns a cons of the selection string MATCH and a function
13909 implementing the matcher.
13911 The matcher is to be called at an Org entry, with point on the
13912 headline, and returns non-nil if the entry matches the selection
13913 string MATCH. It must be called with three arguments: the TODO
13914 keyword at the entry (or nil if none), the list of all tags at
13915 the entry including inherited ones and the reduced level of the
13916 headline. Additionally, the category of the entry, if any, must
13917 be specified as the text property `org-category' on the headline.
13919 This function sets the variable `org--matcher-tags-todo-only' to
13920 a non-nil value if the matcher restricts matching to TODO
13921 entries, otherwise it is not touched.
13923 See also `org-scan-tags'."
13924 (unless match
13925 ;; Get a new match request, with completion against the global
13926 ;; tags table and the local tags in current buffer.
13927 (let ((org-last-tags-completion-table
13928 (org--tag-add-to-alist
13929 (org-get-buffer-tags)
13930 (org-global-tags-completion-table))))
13931 (setq match
13932 (completing-read
13933 "Match: "
13934 'org-tags-completion-function nil nil nil 'org-tags-history))))
13936 (let ((match0 match)
13937 (re (concat
13938 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13939 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13940 "\\([<>=]\\{1,2\\}\\)"
13941 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13942 "\\|" org-tag-re "\\)"))
13943 (start 0)
13944 tagsmatch todomatch tagsmatcher todomatcher)
13946 ;; Expand group tags.
13947 (setq match (org-tags-expand match))
13949 ;; Check if there is a TODO part of this match, which would be the
13950 ;; part after a "/". To make sure that this slash is not part of
13951 ;; a property value to be matched against, we also check that
13952 ;; there is no / after that slash. First, find the last slash.
13953 (let ((s 0))
13954 (while (string-match "/+" match s)
13955 (setq start (match-beginning 0))
13956 (setq s (match-end 0))))
13957 (if (and (string-match "/+" match start)
13958 (not (string-match-p "\"" match start)))
13959 ;; Match contains also a TODO-matching request.
13960 (progn
13961 (setq tagsmatch (substring match 0 (match-beginning 0)))
13962 (setq todomatch (substring match (match-end 0)))
13963 (when (string-prefix-p "!" todomatch)
13964 (setq org--matcher-tags-todo-only t)
13965 (setq todomatch (substring todomatch 1)))
13966 (when (string-match "\\`\\s-*\\'" todomatch)
13967 (setq todomatch nil)))
13968 ;; Only matching tags.
13969 (setq tagsmatch match)
13970 (setq todomatch nil))
13972 ;; Make the tags matcher.
13973 (when (org-string-nw-p tagsmatch)
13974 (let ((orlist nil)
13975 (orterms (org-split-string tagsmatch "|"))
13976 term)
13977 (while (setq term (pop orterms))
13978 (while (and (equal (substring term -1) "\\") orterms)
13979 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13980 (while (string-match re term)
13981 (let* ((rest (substring term (match-end 0)))
13982 (minus (and (match-end 1)
13983 (equal (match-string 1 term) "-")))
13984 (tag (save-match-data
13985 (replace-regexp-in-string
13986 "\\\\-" "-" (match-string 2 term))))
13987 (regexp (eq (string-to-char tag) ?{))
13988 (levelp (match-end 4))
13989 (propp (match-end 5))
13991 (cond
13992 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
13993 (levelp
13994 `(,(org-op-to-function (match-string 3 term))
13995 level
13996 ,(string-to-number (match-string 4 term))))
13997 (propp
13998 (let* ((gv (pcase (upcase (match-string 5 term))
13999 ("CATEGORY"
14000 '(get-text-property (point) 'org-category))
14001 ("TODO" 'todo)
14002 (p `(org-cached-entry-get nil ,p))))
14003 (pv (match-string 7 term))
14004 (regexp (eq (string-to-char pv) ?{))
14005 (strp (eq (string-to-char pv) ?\"))
14006 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14007 (po (org-op-to-function (match-string 6 term)
14008 (if timep 'time strp))))
14009 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14010 (when timep (setq pv (org-matcher-time pv)))
14011 (cond ((and regexp (eq po '/=))
14012 `(not (string-match ,pv (or ,gv ""))))
14013 (regexp `(string-match ,pv (or ,gv "")))
14014 (strp `(,po (or ,gv "") ,pv))
14016 `(,po
14017 (string-to-number (or ,gv ""))
14018 ,(string-to-number pv))))))
14019 (t `(member ,tag tags-list)))))
14020 (push (if minus `(not ,mm) mm) tagsmatcher)
14021 (setq term rest)))
14022 (push `(and ,@tagsmatcher) orlist)
14023 (setq tagsmatcher nil))
14024 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14026 ;; Make the TODO matcher.
14027 (when (org-string-nw-p todomatch)
14028 (let ((orlist nil))
14029 (dolist (term (org-split-string todomatch "|"))
14030 (while (string-match re term)
14031 (let* ((minus (and (match-end 1)
14032 (equal (match-string 1 term) "-")))
14033 (kwd (match-string 2 term))
14034 (regexp (eq (string-to-char kwd) ?{))
14035 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14036 `(equal todo ,kwd))))
14037 (push (if minus `(not ,mm) mm) todomatcher))
14038 (setq term (substring term (match-end 0))))
14039 (push (if (> (length todomatcher) 1)
14040 (cons 'and todomatcher)
14041 (car todomatcher))
14042 orlist)
14043 (setq todomatcher nil))
14044 (setq todomatcher (cons 'or orlist))))
14046 ;; Return the string and function of the matcher. If no
14047 ;; tags-specific or todo-specific matcher exists, match
14048 ;; everything.
14049 (let ((matcher (if (and tagsmatcher todomatcher)
14050 `(and ,tagsmatcher ,todomatcher)
14051 (or tagsmatcher todomatcher t))))
14052 (when org--matcher-tags-todo-only
14053 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14054 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14056 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14057 "Expand group tags in MATCH.
14059 This replaces every group tag in MATCH with a regexp tag search.
14060 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14061 will be replaced like this:
14063 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14064 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14065 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14067 Replacing by a regexp preserves the structure of the match.
14068 E.g., this expansion
14070 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14072 will match anything tagged with \"Lab\" and \"Home\", or tagged
14073 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14075 A group tag in MATCH can contain regular expressions of its own.
14076 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14077 will be replaced like this:
14079 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14081 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14082 assumed to be a single group tag, and the function will return
14083 the list of tags in this group.
14085 When DOWNCASE is non-nil, expand downcased TAGS."
14086 (if org-group-tags
14087 (let* ((case-fold-search t)
14088 (stable org-mode-syntax-table)
14089 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14090 (taggroups (if downcased
14091 (mapcar (lambda (tg) (mapcar #'downcase tg))
14092 taggroups)
14093 taggroups))
14094 (taggroups-keys (mapcar #'car taggroups))
14095 (return-match (if downcased (downcase match) match))
14096 (count 0)
14097 (work-already-expanded tags-already-expanded)
14098 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14099 ;; @ and _ are allowed as word-components in tags.
14100 (modify-syntax-entry ?@ "w" stable)
14101 (modify-syntax-entry ?_ "w" stable)
14102 ;; Temporarily replace regexp-expressions in the match-expression.
14103 (while (string-match "{.+?}" return-match)
14104 (cl-incf count)
14105 (push (match-string 0 return-match) regexps-in-match)
14106 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14107 (while (and taggroups-keys
14108 (with-syntax-table stable
14109 (string-match
14110 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14111 (regexp-opt taggroups-keys) "\\>\\)")
14112 return-match)))
14113 (let* ((dir (match-string 1 return-match))
14114 (tag (match-string 2 return-match))
14115 (tag (if downcased (downcase tag) tag)))
14116 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14117 (member tag tags-already-expanded))
14118 (setq tags-in-group (assoc tag taggroups))
14119 (push tag work-already-expanded)
14120 ;; Recursively expand each tag in the group, if the tag hasn't
14121 ;; already been expanded. Restore the match-data after all recursive calls.
14122 (save-match-data
14123 (let (tags-expanded)
14124 (dolist (x (cdr tags-in-group))
14125 (if (and (member x taggroups-keys)
14126 (not (member x work-already-expanded)))
14127 (setq tags-expanded
14128 (delete-dups
14129 (append
14130 (org-tags-expand x t downcased
14131 work-already-expanded)
14132 tags-expanded)))
14133 (setq tags-expanded
14134 (append (list x) tags-expanded)))
14135 (setq work-already-expanded
14136 (delete-dups
14137 (append tags-expanded
14138 work-already-expanded))))
14139 (setq tags-in-group
14140 (delete-dups (cons (car tags-in-group)
14141 tags-expanded)))))
14142 ;; Filter tag-regexps from tags.
14143 (setq regexp-in-group-escaped
14144 (delq nil (mapcar (lambda (x)
14145 (if (stringp x)
14146 (and (equal "{" (substring x 0 1))
14147 (equal "}" (substring x -1))
14150 tags-in-group))
14151 regexp-in-group
14152 (mapcar (lambda (x)
14153 (substring x 1 -1))
14154 regexp-in-group-escaped)
14155 tags-in-group
14156 (delq nil (mapcar (lambda (x)
14157 (if (stringp x)
14158 (and (not (equal "{" (substring x 0 1)))
14159 (not (equal "}" (substring x -1)))
14162 tags-in-group)))
14163 ;; If single-as-list, do no more in the while-loop.
14164 (if (not single-as-list)
14165 (progn
14166 (when regexp-in-group
14167 (setq regexp-in-group
14168 (concat "\\|"
14169 (mapconcat 'identity regexp-in-group
14170 "\\|"))))
14171 (setq tags-in-group
14172 (concat dir
14173 "{\\<"
14174 (regexp-opt tags-in-group)
14175 "\\>"
14176 regexp-in-group
14177 "}"))
14178 (when (stringp tags-in-group)
14179 (org-add-props tags-in-group '(grouptag t)))
14180 (setq return-match
14181 (replace-match tags-in-group t t return-match)))
14182 (setq tags-in-group
14183 (append regexp-in-group-escaped tags-in-group))))
14184 (setq taggroups-keys (delete tag taggroups-keys))))
14185 ;; Add the regular expressions back into the match-expression again.
14186 (while regexps-in-match
14187 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14188 (pop regexps-in-match)
14189 return-match t t))
14190 (cl-decf count))
14191 (if single-as-list
14192 (if tags-in-group tags-in-group (list return-match))
14193 return-match))
14194 (if single-as-list
14195 (list (if downcased (downcase match) match))
14196 match)))
14198 (defun org-op-to-function (op &optional stringp)
14199 "Turn an operator into the appropriate function."
14200 (setq op
14201 (cond
14202 ((equal op "<" ) '(< org-string< org-time<))
14203 ((equal op ">" ) '(> org-string> org-time>))
14204 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14205 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14206 ((member op '("=" "==")) '(= string= org-time=))
14207 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14208 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14210 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14211 (defvar org-tags-overlay (make-overlay 1 1))
14212 (delete-overlay org-tags-overlay)
14214 (defun org-add-prop-inherited (s)
14215 (add-text-properties 0 (length s) '(inherited t) s)
14218 (defun org-toggle-tag (tag &optional onoff)
14219 "Toggle the tag TAG for the current line.
14220 If ONOFF is `on' or `off', don't toggle but set to this state."
14221 (save-excursion
14222 (org-back-to-heading t)
14223 (let ((current
14224 ;; Reverse the tags list so any new tag is appended to the
14225 ;; current list of tags.
14226 (nreverse (org-get-tags nil t)))
14227 res)
14228 (pcase onoff
14229 (`off (setq current (delete tag current)))
14230 ((or `on (guard (not (member tag current))))
14231 (setq res t)
14232 (cl-pushnew tag current :test #'equal))
14233 (_ (setq current (delete tag current))))
14234 (org-set-tags (nreverse current))
14235 res)))
14237 (defun org--align-tags-here (to-col)
14238 "Align tags on the current headline to TO-COL.
14239 Assume point is on a headline. Preserve point when aligning
14240 tags."
14241 (when (and (org-match-line org-tag-line-re)
14242 (/= to-col (save-excursion ;nothing to do?
14243 (goto-char (match-beginning 1)) (current-column))))
14244 (let* ((shift (if (>= to-col 0) to-col
14245 (- (abs to-col) (string-width (match-string 1)))))
14246 (origin (point-marker))
14247 (column (current-column))
14248 (tags-start (match-beginning 1))
14249 (blank-start (save-excursion
14250 (goto-char tags-start)
14251 (skip-chars-backward " \t")
14252 (point)))
14253 (in-blank? (and (> origin blank-start)
14254 (<= origin tags-start))))
14255 (delete-region blank-start tags-start)
14256 (goto-char blank-start)
14257 (let ((indent-tabs-mode nil)) (indent-to shift 1))
14258 ;; Try to move back to original position. If point was in the
14259 ;; blanks before the tags, ORIGIN marker is of no use because it
14260 ;; now points to BLANK-START. Use COLUMN instead.
14261 (if in-blank? (org-move-to-column column)
14262 (goto-char origin)))))
14264 (defun org-set-tags-command (&optional arg)
14265 "Set the tags for the current visible entry.
14267 When called with `\\[universal-argument]' prefix argument ARG, \
14268 realign all tags
14269 in the current buffer. If a region is active, set tags for
14270 all headlines in the region.
14272 This function is for interactive use only;
14273 in Lisp code use `org-set-tags' instead."
14274 (interactive "P")
14275 (cond
14276 (arg (org-align-tags t))
14277 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14278 ;; Disable `org-loop-over-headlines-in-active-region' for
14279 ;; successive calls.
14280 (let (org-loop-over-headlines-in-active-region)
14281 (org-map-entries
14282 #'org-set-tags-command
14284 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14285 'region-start-level
14286 'region)
14287 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14289 (save-excursion
14290 (org-back-to-heading)
14291 (let* ((all-tags (org-get-tags))
14292 (table (setq org-last-tags-completion-table
14293 (org--tag-add-to-alist
14294 (and org-complete-tags-always-offer-all-agenda-tags
14295 (org-global-tags-completion-table
14296 (org-agenda-files)))
14297 (or org-current-tag-alist (org-get-buffer-tags)))))
14298 (current-tags
14299 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14300 all-tags))
14301 (inherited-tags
14302 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14303 all-tags))
14304 (tags
14305 (replace-regexp-in-string
14306 ;; Ignore all forbidden characters in tags.
14307 "[^[:alnum:]_@#%]+" ":"
14308 (if (or (eq t org-use-fast-tag-selection)
14309 (and org-use-fast-tag-selection
14310 (delq nil (mapcar #'cdr table))))
14311 (org-fast-tag-selection
14312 current-tags
14313 inherited-tags
14314 table
14315 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14316 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14317 (org-trim (completing-read
14318 "Tags: "
14319 #'org-tags-completion-function
14320 nil nil (org-make-tag-string current-tags)
14321 'org-tags-history)))))))
14322 (org-set-tags tags))))))
14324 (defun org-align-tags (&optional all)
14325 "Align tags in current entry.
14326 When optional argument ALL is non-nil, align all tags in the
14327 visible part of the buffer."
14328 (let ((get-indent-column
14329 (lambda ()
14330 (let ((offset (if (bound-and-true-p org-indent-mode)
14331 (* (1- org-indent-indentation-per-level)
14332 (1- (org-current-level)))
14333 0)))
14334 (+ org-tags-column
14335 (if (> org-tags-column 0) (- offset) offset))))))
14336 (if (and (not all) (org-at-heading-p))
14337 (org--align-tags-here (funcall get-indent-column))
14338 (save-excursion
14339 (if all
14340 (while (re-search-forward org-tag-line-re nil t)
14341 (org--align-tags-here (funcall get-indent-column)))
14342 (org-back-to-heading t)
14343 (org--align-tags-here (funcall get-indent-column)))))))
14345 (defun org-set-tags (tags)
14346 "Set the tags of the current entry to TAGS, replacing current tags.
14348 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14349 If TAGS is nil or the empty string, all tags are removed.
14351 This function assumes point is on a headline."
14352 (org-with-wide-buffer
14353 (let ((tags (pcase tags
14354 ((pred listp) tags)
14355 ((pred stringp) (split-string (org-trim tags) ":" t))
14356 (_ (error "Invalid tag specification: %S" tags))))
14357 (old-tags (org-get-tags nil t))
14358 (change-flag nil))
14359 (when (functionp org-tags-sort-function)
14360 (setq tags (sort tags org-tags-sort-function)))
14361 (unless (equal tags old-tags) (setq change-flag t))
14362 ;; Delete previous tags and any trailing white space.
14363 (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
14364 (line-end-position)))
14365 (skip-chars-backward " \t")
14366 (delete-region (point) (line-end-position))
14367 ;; Deleting white spaces may break an otherwise empty headline.
14368 ;; Re-introduce one space in this case.
14369 (unless (org-at-heading-p) (insert " "))
14370 (when tags
14371 (save-excursion (insert " " (org-make-tag-string tags)))
14372 ;; When text is being inserted on an invisible region
14373 ;; boundary, it can be inadvertently sucked into
14374 ;; invisibility.
14375 (unless (org-invisible-p (line-beginning-position))
14376 (org-flag-region (point) (line-end-position) nil 'outline)))
14377 ;; Align tags, if any.
14378 (when tags (org-align-tags))
14379 (when change-flag (run-hooks 'org-after-tags-change-hook)))))
14381 (defun org-change-tag-in-region (beg end tag off)
14382 "Add or remove TAG for each entry in the region.
14383 This works in the agenda, and also in an Org buffer."
14384 (interactive
14385 (list (region-beginning) (region-end)
14386 (let ((org-last-tags-completion-table
14387 (if (derived-mode-p 'org-mode)
14388 (org--tag-add-to-alist
14389 (org-get-buffer-tags)
14390 (org-global-tags-completion-table))
14391 (org-global-tags-completion-table))))
14392 (completing-read
14393 "Tag: " 'org-tags-completion-function nil nil nil
14394 'org-tags-history))
14395 (progn
14396 (message "[s]et or [r]emove? ")
14397 (equal (read-char-exclusive) ?r))))
14398 (when (fboundp 'deactivate-mark) (deactivate-mark))
14399 (let ((agendap (equal major-mode 'org-agenda-mode))
14400 l1 l2 m buf pos newhead (cnt 0))
14401 (goto-char end)
14402 (setq l2 (1- (org-current-line)))
14403 (goto-char beg)
14404 (setq l1 (org-current-line))
14405 (cl-loop for l from l1 to l2 do
14406 (org-goto-line l)
14407 (setq m (get-text-property (point) 'org-hd-marker))
14408 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14409 (and agendap m))
14410 (setq buf (if agendap (marker-buffer m) (current-buffer))
14411 pos (if agendap m (point)))
14412 (with-current-buffer buf
14413 (save-excursion
14414 (save-restriction
14415 (goto-char pos)
14416 (setq cnt (1+ cnt))
14417 (org-toggle-tag tag (if off 'off 'on))
14418 (setq newhead (org-get-heading)))))
14419 (and agendap (org-agenda-change-all-lines newhead m))))
14420 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14422 (defun org-tags-completion-function (string _predicate &optional flag)
14423 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14424 (confirm (lambda (x) (stringp (car x)))))
14425 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14426 (setq s1 (match-string 1 string)
14427 s2 (match-string 2 string))
14428 (setq s1 "" s2 string))
14429 (cond
14430 ((eq flag nil)
14431 ;; try completion
14432 (setq rtn (try-completion s2 ctable confirm))
14433 (when (stringp rtn)
14434 (setq rtn
14435 (concat s1 s2 (substring rtn (length s2))
14436 (if (and org-add-colon-after-tag-completion
14437 (assoc rtn ctable))
14438 ":" ""))))
14439 rtn)
14440 ((eq flag t)
14441 ;; all-completions
14442 (all-completions s2 ctable confirm))
14443 ((eq flag 'lambda)
14444 ;; exact match?
14445 (assoc s2 ctable)))))
14447 (defun org-fast-tag-insert (kwd tags face &optional end)
14448 "Insert KWD, and the TAGS, the latter with face FACE.
14449 Also insert END."
14450 (insert (format "%-12s" (concat kwd ":"))
14451 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14452 (or end "")))
14454 (defun org-fast-tag-show-exit (flag)
14455 (save-excursion
14456 (org-goto-line 3)
14457 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14458 (replace-match ""))
14459 (when flag
14460 (end-of-line 1)
14461 (org-move-to-column (- (window-width) 19) t)
14462 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14464 (defun org-set-current-tags-overlay (current prefix)
14465 "Add an overlay to CURRENT tag with PREFIX."
14466 (let ((s (org-make-tag-string current)))
14467 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14468 (org-overlay-display org-tags-overlay (concat prefix s))))
14470 (defvar org-last-tag-selection-key nil)
14471 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14472 "Fast tag selection with single keys.
14473 CURRENT is the current list of tags in the headline, INHERITED is the
14474 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14475 possibly with grouping information. TODO-TABLE is a similar table with
14476 TODO keywords, should these have keys assigned to them.
14477 If the keys are nil, a-z are automatically assigned.
14478 Returns the new tags string, or nil to not change the current settings."
14479 (let* ((fulltable (append table todo-table))
14480 (maxlen (if (null fulltable) 0
14481 (apply #'max
14482 (mapcar (lambda (x)
14483 (if (stringp (car x)) (string-width (car x))
14485 fulltable))))
14486 (buf (current-buffer))
14487 (expert (eq org-fast-tag-selection-single-key 'expert))
14488 (buffer-tags nil)
14489 (fwidth (+ maxlen 3 1 3))
14490 (ncol (/ (- (window-width) 4) fwidth))
14491 (i-face 'org-done)
14492 (c-face 'org-todo)
14493 tg cnt e c char c1 c2 ntable tbl rtn
14494 ov-start ov-end ov-prefix
14495 (exit-after-next org-fast-tag-selection-single-key)
14496 (done-keywords org-done-keywords)
14497 groups ingroup intaggroup)
14498 (save-excursion
14499 (beginning-of-line)
14500 (if (looking-at org-tag-line-re)
14501 (setq ov-start (match-beginning 1)
14502 ov-end (match-end 1)
14503 ov-prefix "")
14504 (setq ov-start (1- (point-at-eol))
14505 ov-end (1+ ov-start))
14506 (skip-chars-forward "^\n\r")
14507 (setq ov-prefix
14508 (concat
14509 (buffer-substring (1- (point)) (point))
14510 (if (> (current-column) org-tags-column)
14512 (make-string (- org-tags-column (current-column)) ?\ ))))))
14513 (move-overlay org-tags-overlay ov-start ov-end)
14514 (save-window-excursion
14515 (if expert
14516 (set-buffer (get-buffer-create " *Org tags*"))
14517 (delete-other-windows)
14518 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14519 (org-switch-to-buffer-other-window " *Org tags*"))
14520 (erase-buffer)
14521 (setq-local org-done-keywords done-keywords)
14522 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14523 (org-fast-tag-insert "Current" current c-face "\n\n")
14524 (org-fast-tag-show-exit exit-after-next)
14525 (org-set-current-tags-overlay current ov-prefix)
14526 (setq tbl fulltable char ?a cnt 0)
14527 (while (setq e (pop tbl))
14528 (cond
14529 ((eq (car e) :startgroup)
14530 (push '() groups) (setq ingroup t)
14531 (unless (zerop cnt)
14532 (setq cnt 0)
14533 (insert "\n"))
14534 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14535 ((eq (car e) :endgroup)
14536 (setq ingroup nil cnt 0)
14537 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14538 ((eq (car e) :startgrouptag)
14539 (setq intaggroup t)
14540 (unless (zerop cnt)
14541 (setq cnt 0)
14542 (insert "\n"))
14543 (insert "[ "))
14544 ((eq (car e) :endgrouptag)
14545 (setq intaggroup nil cnt 0)
14546 (insert "]\n"))
14547 ((equal e '(:newline))
14548 (unless (zerop cnt)
14549 (setq cnt 0)
14550 (insert "\n")
14551 (setq e (car tbl))
14552 (while (equal (car tbl) '(:newline))
14553 (insert "\n")
14554 (setq tbl (cdr tbl)))))
14555 ((equal e '(:grouptags)) (insert " : "))
14557 (setq tg (copy-sequence (car e)) c2 nil)
14558 (if (cdr e)
14559 (setq c (cdr e))
14560 ;; automatically assign a character.
14561 (setq c1 (string-to-char
14562 (downcase (substring
14563 tg (if (= (string-to-char tg) ?@) 1 0)))))
14564 (if (or (rassoc c1 ntable) (rassoc c1 table))
14565 (while (or (rassoc char ntable) (rassoc char table))
14566 (setq char (1+ char)))
14567 (setq c2 c1))
14568 (setq c (or c2 char)))
14569 (when ingroup (push tg (car groups)))
14570 (setq tg (org-add-props tg nil 'face
14571 (cond
14572 ((not (assoc tg table))
14573 (org-get-todo-face tg))
14574 ((member tg current) c-face)
14575 ((member tg inherited) i-face))))
14576 (when (equal (caar tbl) :grouptags)
14577 (org-add-props tg nil 'face 'org-tag-group))
14578 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14579 (insert "[" c "] " tg (make-string
14580 (- fwidth 4 (length tg)) ?\ ))
14581 (push (cons tg c) ntable)
14582 (when (= (cl-incf cnt) ncol)
14583 (insert "\n")
14584 (when (or ingroup intaggroup) (insert " "))
14585 (setq cnt 0)))))
14586 (setq ntable (nreverse ntable))
14587 (insert "\n")
14588 (goto-char (point-min))
14589 (unless expert (org-fit-window-to-buffer))
14590 (setq rtn
14591 (catch 'exit
14592 (while t
14593 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14594 (if (not groups) "no " "")
14595 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14596 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14597 (setq org-last-tag-selection-key c)
14598 (cond
14599 ((= c ?\r) (throw 'exit t))
14600 ((= c ?!)
14601 (setq groups (not groups))
14602 (goto-char (point-min))
14603 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14604 ((= c ?\C-c)
14605 (if (not expert)
14606 (org-fast-tag-show-exit
14607 (setq exit-after-next (not exit-after-next)))
14608 (setq expert nil)
14609 (delete-other-windows)
14610 (set-window-buffer (split-window-vertically) " *Org tags*")
14611 (org-switch-to-buffer-other-window " *Org tags*")
14612 (org-fit-window-to-buffer)))
14613 ((or (= c ?\C-g)
14614 (and (= c ?q) (not (rassoc c ntable))))
14615 (delete-overlay org-tags-overlay)
14616 (setq quit-flag t))
14617 ((= c ?\ )
14618 (setq current nil)
14619 (when exit-after-next (setq exit-after-next 'now)))
14620 ((= c ?\t)
14621 (condition-case nil
14622 (setq tg (completing-read
14623 "Tag: "
14624 (or buffer-tags
14625 (with-current-buffer buf
14626 (setq buffer-tags
14627 (org-get-buffer-tags))))))
14628 (quit (setq tg "")))
14629 (when (string-match "\\S-" tg)
14630 (cl-pushnew (list tg) buffer-tags :test #'equal)
14631 (if (member tg current)
14632 (setq current (delete tg current))
14633 (push tg current)))
14634 (when exit-after-next (setq exit-after-next 'now)))
14635 ((setq e (rassoc c todo-table) tg (car e))
14636 (with-current-buffer buf
14637 (save-excursion (org-todo tg)))
14638 (when exit-after-next (setq exit-after-next 'now)))
14639 ((setq e (rassoc c ntable) tg (car e))
14640 (if (member tg current)
14641 (setq current (delete tg current))
14642 (cl-loop for g in groups do
14643 (when (member tg g)
14644 (dolist (x g) (setq current (delete x current)))))
14645 (push tg current))
14646 (when exit-after-next (setq exit-after-next 'now))))
14648 ;; Create a sorted list
14649 (setq current
14650 (sort current
14651 (lambda (a b)
14652 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14653 (when (eq exit-after-next 'now) (throw 'exit t))
14654 (goto-char (point-min))
14655 (beginning-of-line 2)
14656 (delete-region (point) (point-at-eol))
14657 (org-fast-tag-insert "Current" current c-face)
14658 (org-set-current-tags-overlay current ov-prefix)
14659 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14660 (while (re-search-forward tag-re nil t)
14661 (let ((tag (match-string 1)))
14662 (add-text-properties
14663 (match-beginning 1) (match-end 1)
14664 (list 'face
14665 (cond
14666 ((member tag current) c-face)
14667 ((member tag inherited) i-face)
14668 (t (get-text-property (match-beginning 1) '
14669 face))))))))
14670 (goto-char (point-min)))))
14671 (delete-overlay org-tags-overlay)
14672 (if rtn
14673 (mapconcat 'identity current ":")
14674 nil))))
14676 (defun org-make-tag-string (tags)
14677 "Return string associated to TAGS.
14678 TAGS is a list of strings."
14679 (if (null tags) ""
14680 (format ":%s:" (mapconcat #'identity tags ":"))))
14682 (defun org--get-local-tags ()
14683 "Return list of tags for the current headline.
14684 Assume point is at the beginning of the headline."
14685 (and (looking-at org-tag-line-re)
14686 (split-string (match-string-no-properties 2) ":" t)))
14688 (defun org-get-tags (&optional pos local)
14689 "Get the list of tags specified in the current headline.
14691 When argument POS is non-nil, retrieve tags for headline at POS.
14693 Accoring to `org-use-tags-inheritance', tags may be inherited
14694 from parent headlines, and from the whole document, through
14695 `org-file-tags'. However, when optional argument LOCAL is
14696 non-nil, only return tags really specified in the considered
14697 headline.
14699 Inherited tags have the `inherited' text property."
14700 (if (and org-trust-scanner-tags
14701 (or (not pos) (eq pos (point)))
14702 (not local))
14703 org-scanner-tags
14704 (org-with-point-at (or pos (point))
14705 (unless (org-before-first-heading-p)
14706 (org-back-to-heading t)
14707 (let ((tags (org--get-local-tags)))
14708 (if (or local (not org-use-tag-inheritance)) tags
14709 (while (org-up-heading-safe)
14710 (setq tags (append (mapcar #'org-add-prop-inherited
14711 (org--get-local-tags))
14712 tags)))
14713 (org-remove-uninherited-tags
14714 (delete-dups (append org-file-tags tags)))))))))
14716 (defun org-get-buffer-tags ()
14717 "Get a table of all tags used in the buffer, for completion."
14718 (org-with-point-at 1
14719 (let (tags)
14720 (while (re-search-forward org-tag-line-re nil t)
14721 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14722 tags)))
14723 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14725 ;;;; The mapping API
14727 (defvar org-agenda-skip-comment-trees)
14728 (defvar org-agenda-skip-function)
14729 (defun org-map-entries (func &optional match scope &rest skip)
14730 "Call FUNC at each headline selected by MATCH in SCOPE.
14732 FUNC is a function or a lisp form. The function will be called without
14733 arguments, with the cursor positioned at the beginning of the headline.
14734 The return values of all calls to the function will be collected and
14735 returned as a list.
14737 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14738 does not need to preserve point. After evaluation, the cursor will be
14739 moved to the end of the line (presumably of the headline of the
14740 processed entry) and search continues from there. Under some
14741 circumstances, this may not produce the wanted results. For example,
14742 if you have removed (e.g. archived) the current (sub)tree it could
14743 mean that the next entry will be skipped entirely. In such cases, you
14744 can specify the position from where search should continue by making
14745 FUNC set the variable `org-map-continue-from' to the desired buffer
14746 position.
14748 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14749 Only headlines that are matched by this query will be considered during
14750 the iteration. When MATCH is nil or t, all headlines will be
14751 visited by the iteration.
14753 SCOPE determines the scope of this command. It can be any of:
14755 nil The current buffer, respecting the restriction if any
14756 tree The subtree started with the entry at point
14757 region The entries within the active region, if any
14758 region-start-level
14759 The entries within the active region, but only those at
14760 the same level than the first one.
14761 file The current buffer, without restriction
14762 file-with-archives
14763 The current buffer, and any archives associated with it
14764 agenda All agenda files
14765 agenda-with-archives
14766 All agenda files with any archive files associated with them
14767 \(file1 file2 ...)
14768 If this is a list, all files in the list will be scanned
14770 The remaining args are treated as settings for the skipping facilities of
14771 the scanner. The following items can be given here:
14773 archive skip trees with the archive tag
14774 comment skip trees with the COMMENT keyword
14775 function or Emacs Lisp form:
14776 will be used as value for `org-agenda-skip-function', so
14777 whenever the function returns a position, FUNC will not be
14778 called for that entry and search will continue from the
14779 position returned
14781 If your function needs to retrieve the tags including inherited tags
14782 at the *current* entry, you can use the value of the variable
14783 `org-scanner-tags' which will be much faster than getting the value
14784 with `org-get-tags'. If your function gets properties with
14785 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14786 to t around the call to `org-entry-properties' to get the same speedup.
14787 Note that if your function moves around to retrieve tags and properties at
14788 a *different* entry, you cannot use these techniques."
14789 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14790 (not (org-region-active-p)))
14791 (let* ((org-agenda-archives-mode nil) ; just to make sure
14792 (org-agenda-skip-archived-trees (memq 'archive skip))
14793 (org-agenda-skip-comment-trees (memq 'comment skip))
14794 (org-agenda-skip-function
14795 (car (org-delete-all '(comment archive) skip)))
14796 (org-tags-match-list-sublevels t)
14797 (start-level (eq scope 'region-start-level))
14798 matcher res
14799 org-todo-keywords-for-agenda
14800 org-done-keywords-for-agenda
14801 org-todo-keyword-alist-for-agenda
14802 org-tag-alist-for-agenda
14803 org--matcher-tags-todo-only)
14805 (cond
14806 ((eq match t) (setq matcher t))
14807 ((eq match nil) (setq matcher t))
14808 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14810 (save-excursion
14811 (save-restriction
14812 (cond ((eq scope 'tree)
14813 (org-back-to-heading t)
14814 (org-narrow-to-subtree)
14815 (setq scope nil))
14816 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14817 (org-region-active-p))
14818 ;; If needed, set start-level to a string like "2"
14819 (when start-level
14820 (save-excursion
14821 (goto-char (region-beginning))
14822 (unless (org-at-heading-p) (outline-next-heading))
14823 (setq start-level (org-current-level))))
14824 (narrow-to-region (region-beginning)
14825 (save-excursion
14826 (goto-char (region-end))
14827 (unless (and (bolp) (org-at-heading-p))
14828 (outline-next-heading))
14829 (point)))
14830 (setq scope nil)))
14832 (if (not scope)
14833 (progn
14834 (org-agenda-prepare-buffers
14835 (and buffer-file-name (list buffer-file-name)))
14836 (setq res
14837 (org-scan-tags
14838 func matcher org--matcher-tags-todo-only start-level)))
14839 ;; Get the right scope
14840 (cond
14841 ((and scope (listp scope) (symbolp (car scope)))
14842 (setq scope (eval scope)))
14843 ((eq scope 'agenda)
14844 (setq scope (org-agenda-files t)))
14845 ((eq scope 'agenda-with-archives)
14846 (setq scope (org-agenda-files t))
14847 (setq scope (org-add-archive-files scope)))
14848 ((eq scope 'file)
14849 (setq scope (and buffer-file-name (list buffer-file-name))))
14850 ((eq scope 'file-with-archives)
14851 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14852 (org-agenda-prepare-buffers scope)
14853 (dolist (file scope)
14854 (with-current-buffer (org-find-base-buffer-visiting file)
14855 (org-with-wide-buffer
14856 (goto-char (point-min))
14857 (setq res
14858 (append
14860 (org-scan-tags
14861 func matcher org--matcher-tags-todo-only)))))))))
14862 res)))
14864 ;;; Properties API
14866 (defconst org-special-properties
14867 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14868 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14869 "The special properties valid in Org mode.
14870 These are properties that are not defined in the property drawer,
14871 but in some other way.")
14873 (defconst org-default-properties
14874 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14875 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14876 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14877 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14878 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14879 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14880 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14881 "Some properties that are used by Org mode for various purposes.
14882 Being in this list makes sure that they are offered for completion.")
14884 (defun org--valid-property-p (property)
14885 "Non nil when string PROPERTY is a valid property name."
14886 (not
14887 (or (equal property "")
14888 (string-match-p "\\s-" property))))
14890 (defun org--update-property-plist (key val props)
14891 "Associate KEY to VAL in alist PROPS.
14892 Modifications are made by side-effect. Return new alist."
14893 (let* ((appending (string= (substring key -1) "+"))
14894 (key (if appending (substring key 0 -1) key))
14895 (old (assoc-string key props t)))
14896 (if (not old) (cons (cons key val) props)
14897 (setcdr old (if appending (concat (cdr old) " " val) val))
14898 props)))
14900 (defun org-get-property-block (&optional beg force)
14901 "Return the (beg . end) range of the body of the property drawer.
14902 BEG is the beginning of the current subtree, or of the part
14903 before the first headline. If it is not given, it will be found.
14904 If the drawer does not exist, create it if FORCE is non-nil, or
14905 return nil."
14906 (org-with-wide-buffer
14907 (when beg (goto-char beg))
14908 (unless (org-before-first-heading-p)
14909 (let ((beg (cond (beg)
14910 ((or (not (featurep 'org-inlinetask))
14911 (org-inlinetask-in-task-p))
14912 (org-back-to-heading t))
14913 (t (org-with-limited-levels (org-back-to-heading t))))))
14914 (forward-line)
14915 (when (looking-at-p org-planning-line-re) (forward-line))
14916 (cond ((looking-at org-property-drawer-re)
14917 (forward-line)
14918 (cons (point) (progn (goto-char (match-end 0))
14919 (line-beginning-position))))
14920 (force
14921 (goto-char beg)
14922 (org-insert-property-drawer)
14923 (let ((pos (save-excursion (search-forward ":END:")
14924 (line-beginning-position))))
14925 (cons pos pos))))))))
14927 (defun org-at-property-p ()
14928 "Non-nil when point is inside a property drawer.
14929 See `org-property-re' for match data, if applicable."
14930 (save-excursion
14931 (beginning-of-line)
14932 (and (looking-at org-property-re)
14933 (let ((property-drawer (save-match-data (org-get-property-block))))
14934 (and property-drawer
14935 (>= (point) (car property-drawer))
14936 (< (point) (cdr property-drawer)))))))
14938 (defun org-property-action ()
14939 "Do an action on properties."
14940 (interactive)
14941 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14942 (let ((c (read-char-exclusive)))
14943 (cl-case c
14944 (?s (call-interactively #'org-set-property))
14945 (?d (call-interactively #'org-delete-property))
14946 (?D (call-interactively #'org-delete-property-globally))
14947 (?c (call-interactively #'org-compute-property-at-point))
14948 (otherwise (user-error "No such property action %c" c)))))
14950 (defun org-inc-effort ()
14951 "Increment the value of the effort property in the current entry."
14952 (interactive)
14953 (org-set-effort t))
14955 (defvar org-clock-effort) ; Defined in org-clock.el.
14956 (defvar org-clock-current-task) ; Defined in org-clock.el.
14957 (defun org-set-effort (&optional increment value)
14958 "Set the effort property of the current entry.
14959 If INCREMENT is non-nil, set the property to the next allowed
14960 value. Otherwise, if optional argument VALUE is provided, use
14961 it. Eventually, prompt for the new value if none of the previous
14962 variables is set."
14963 (interactive "P")
14964 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14965 (current (org-entry-get nil org-effort-property))
14966 (value
14967 (cond
14968 (increment
14969 (unless allowed (user-error "Allowed effort values are not set"))
14970 (or (cl-caadr (member (list current) allowed))
14971 (user-error "Unknown value %S among allowed values" current)))
14972 (value
14973 (if (stringp value) value
14974 (error "Invalid effort value: %S" value)))
14976 (let ((must-match
14977 (and allowed
14978 (not (get-text-property 0 'org-unrestricted
14979 (caar allowed))))))
14980 (completing-read "Effort: " allowed nil must-match))))))
14981 (unless (equal current value)
14982 (org-entry-put nil org-effort-property value))
14983 (org-refresh-property '((effort . identity)
14984 (effort-minutes . org-duration-to-minutes))
14985 value)
14986 (when (equal (org-get-heading t t t t)
14987 (bound-and-true-p org-clock-current-task))
14988 (setq org-clock-effort (org-get-at-bol 'effort))
14989 (org-clock-update-mode-line))
14990 (message "%s is now %s" org-effort-property value)))
14992 (defun org-entry-properties (&optional pom which)
14993 "Get all properties of the current entry.
14995 When POM is a buffer position, get all properties from the entry
14996 there instead.
14998 This includes the TODO keyword, the tags, time strings for
14999 deadline, scheduled, and clocking, and any additional properties
15000 defined in the entry.
15002 If WHICH is nil or `all', get all properties. If WHICH is
15003 `special' or `standard', only get that subclass. If WHICH is
15004 a string, only get that property.
15006 Return value is an alist. Keys are properties, as upcased
15007 strings."
15008 (org-with-point-at pom
15009 (when (and (derived-mode-p 'org-mode)
15010 (ignore-errors (org-back-to-heading t)))
15011 (catch 'exit
15012 (let* ((beg (point))
15013 (specific (and (stringp which) (upcase which)))
15014 (which (cond ((not specific) which)
15015 ((member specific org-special-properties) 'special)
15016 (t 'standard)))
15017 props)
15018 ;; Get the special properties, like TODO and TAGS.
15019 (when (memq which '(nil all special))
15020 (when (or (not specific) (string= specific "CLOCKSUM"))
15021 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15022 (when clocksum
15023 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15024 props)))
15025 (when specific (throw 'exit props)))
15026 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15027 (let ((clocksumt (get-text-property (point)
15028 :org-clock-minutes-today)))
15029 (when clocksumt
15030 (push (cons "CLOCKSUM_T"
15031 (org-duration-from-minutes clocksumt))
15032 props)))
15033 (when specific (throw 'exit props)))
15034 (when (or (not specific) (string= specific "ITEM"))
15035 (let ((case-fold-search nil))
15036 (when (looking-at org-complex-heading-regexp)
15037 (push (cons "ITEM"
15038 (let ((title (match-string-no-properties 4)))
15039 (if (org-string-nw-p title)
15040 (org-remove-tabs title)
15041 "")))
15042 props)))
15043 (when specific (throw 'exit props)))
15044 (when (or (not specific) (string= specific "TODO"))
15045 (let ((case-fold-search nil))
15046 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15047 (push (cons "TODO" (match-string-no-properties 2)) props)))
15048 (when specific (throw 'exit props)))
15049 (when (or (not specific) (string= specific "PRIORITY"))
15050 (push (cons "PRIORITY"
15051 (if (looking-at org-priority-regexp)
15052 (match-string-no-properties 2)
15053 (char-to-string org-default-priority)))
15054 props)
15055 (when specific (throw 'exit props)))
15056 (when (or (not specific) (string= specific "FILE"))
15057 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15058 props)
15059 (when specific (throw 'exit props)))
15060 (when (or (not specific) (string= specific "TAGS"))
15061 (let ((tags (org-get-tags nil t)))
15062 (when tags
15063 (push (cons "TAGS" (org-make-tag-string tags))
15064 props)))
15065 (when specific (throw 'exit props)))
15066 (when (or (not specific) (string= specific "ALLTAGS"))
15067 (let ((tags (org-get-tags)))
15068 (when tags
15069 (push (cons "ALLTAGS" (org-make-tag-string tags))
15070 props)))
15071 (when specific (throw 'exit props)))
15072 (when (or (not specific) (string= specific "BLOCKED"))
15073 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15074 (when specific (throw 'exit props)))
15075 (when (or (not specific)
15076 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15077 (forward-line)
15078 (when (looking-at-p org-planning-line-re)
15079 (end-of-line)
15080 (let ((bol (line-beginning-position))
15081 ;; Backward compatibility: time keywords used to
15082 ;; be configurable (before 8.3). Make sure we
15083 ;; get the correct keyword.
15084 (key-assoc `(("CLOSED" . ,org-closed-string)
15085 ("DEADLINE" . ,org-deadline-string)
15086 ("SCHEDULED" . ,org-scheduled-string))))
15087 (dolist (pair (if specific (list (assoc specific key-assoc))
15088 key-assoc))
15089 (save-excursion
15090 (when (search-backward (cdr pair) bol t)
15091 (goto-char (match-end 0))
15092 (skip-chars-forward " \t")
15093 (and (looking-at org-ts-regexp-both)
15094 (push (cons (car pair)
15095 (match-string-no-properties 0))
15096 props)))))))
15097 (when specific (throw 'exit props)))
15098 (when (or (not specific)
15099 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15100 (let ((find-ts
15101 (lambda (end ts)
15102 ;; Fix next time-stamp before END. TS is the
15103 ;; list of time-stamps found so far.
15104 (let ((ts ts)
15105 (regexp (cond
15106 ((string= specific "TIMESTAMP")
15107 org-ts-regexp)
15108 ((string= specific "TIMESTAMP_IA")
15109 org-ts-regexp-inactive)
15110 ((assoc "TIMESTAMP_IA" ts)
15111 org-ts-regexp)
15112 ((assoc "TIMESTAMP" ts)
15113 org-ts-regexp-inactive)
15114 (t org-ts-regexp-both))))
15115 (catch 'next
15116 (while (re-search-forward regexp end t)
15117 (backward-char)
15118 (let ((object (org-element-context)))
15119 ;; Accept to match timestamps in node
15120 ;; properties, too.
15121 (when (memq (org-element-type object)
15122 '(node-property timestamp))
15123 (let ((type
15124 (org-element-property :type object)))
15125 (cond
15126 ((and (memq type '(active active-range))
15127 (not (equal specific "TIMESTAMP_IA")))
15128 (unless (assoc "TIMESTAMP" ts)
15129 (push (cons "TIMESTAMP"
15130 (org-element-property
15131 :raw-value object))
15133 (when specific (throw 'exit ts))))
15134 ((and (memq type '(inactive inactive-range))
15135 (not (string= specific "TIMESTAMP")))
15136 (unless (assoc "TIMESTAMP_IA" ts)
15137 (push (cons "TIMESTAMP_IA"
15138 (org-element-property
15139 :raw-value object))
15141 (when specific (throw 'exit ts))))))
15142 ;; Both timestamp types are found,
15143 ;; move to next part.
15144 (when (= (length ts) 2) (throw 'next ts)))))
15145 ts)))))
15146 (goto-char beg)
15147 ;; First look for timestamps within headline.
15148 (let ((ts (funcall find-ts (line-end-position) nil)))
15149 (if (= (length ts) 2) (setq props (nconc ts props))
15150 ;; Then find timestamps in the section, skipping
15151 ;; planning line.
15152 (let ((end (save-excursion (outline-next-heading))))
15153 (forward-line)
15154 (when (looking-at-p org-planning-line-re) (forward-line))
15155 (setq props (nconc (funcall find-ts end ts) props))))))))
15156 ;; Get the standard properties, like :PROP:.
15157 (when (memq which '(nil all standard))
15158 ;; If we are looking after a specific property, delegate
15159 ;; to `org-entry-get', which is faster. However, make an
15160 ;; exception for "CATEGORY", since it can be also set
15161 ;; through keywords (i.e. #+CATEGORY).
15162 (if (and specific (not (equal specific "CATEGORY")))
15163 (let ((value (org-entry-get beg specific nil t)))
15164 (throw 'exit (and value (list (cons specific value)))))
15165 (let ((range (org-get-property-block beg)))
15166 (when range
15167 (let ((end (cdr range)) seen-base)
15168 (goto-char (car range))
15169 ;; Unlike to `org--update-property-plist', we
15170 ;; handle the case where base values is found
15171 ;; after its extension. We also forbid standard
15172 ;; properties to be named as special properties.
15173 (while (re-search-forward org-property-re end t)
15174 (let* ((key (upcase (match-string-no-properties 2)))
15175 (extendp (string-match-p "\\+\\'" key))
15176 (key-base (if extendp (substring key 0 -1) key))
15177 (value (match-string-no-properties 3)))
15178 (cond
15179 ((member-ignore-case key-base org-special-properties))
15180 (extendp
15181 (setq props
15182 (org--update-property-plist key value props)))
15183 ((member key seen-base))
15184 (t (push key seen-base)
15185 (let ((p (assoc-string key props t)))
15186 (if p (setcdr p (concat value " " (cdr p)))
15187 (push (cons key value) props))))))))))))
15188 (unless (assoc "CATEGORY" props)
15189 (push (cons "CATEGORY" (org-get-category beg)) props)
15190 (when (string= specific "CATEGORY") (throw 'exit props)))
15191 ;; Return value.
15192 props)))))
15194 (defun org--property-local-values (property literal-nil)
15195 "Return value for PROPERTY in current entry.
15196 Value is a list whose car is the base value for PROPERTY and cdr
15197 a list of accumulated values. Return nil if neither is found in
15198 the entry. Also return nil when PROPERTY is set to \"nil\",
15199 unless LITERAL-NIL is non-nil."
15200 (let ((range (org-get-property-block)))
15201 (when range
15202 (goto-char (car range))
15203 (let* ((case-fold-search t)
15204 (end (cdr range))
15205 (value
15206 ;; Base value.
15207 (save-excursion
15208 (let ((v (and (re-search-forward
15209 (org-re-property property nil t) end t)
15210 (match-string-no-properties 3))))
15211 (list (if literal-nil v (org-not-nil v)))))))
15212 ;; Find additional values.
15213 (let* ((property+ (org-re-property (concat property "+") nil t)))
15214 (while (re-search-forward property+ end t)
15215 (push (match-string-no-properties 3) value)))
15216 ;; Return final values.
15217 (and (not (equal value '(nil))) (nreverse value))))))
15219 (defun org--property-global-value (property literal-nil)
15220 "Return value for PROPERTY in current buffer.
15221 Return value is a string. Return nil if property is not set
15222 globally. Also return nil when PROPERTY is set to \"nil\",
15223 unless LITERAL-NIL is non-nil."
15224 (let ((global
15225 (cdr (or (assoc-string property org-file-properties t)
15226 (assoc-string property org-global-properties t)
15227 (assoc-string property org-global-properties-fixed t)))))
15228 (if literal-nil global (org-not-nil global))))
15230 (defun org-entry-get (pom property &optional inherit literal-nil)
15231 "Get value of PROPERTY for entry or content at point-or-marker POM.
15233 If INHERIT is non-nil and the entry does not have the property,
15234 then also check higher levels of the hierarchy. If INHERIT is
15235 the symbol `selective', use inheritance only if the setting in
15236 `org-use-property-inheritance' selects PROPERTY for inheritance.
15238 If the property is present but empty, the return value is the
15239 empty string. If the property is not present at all, nil is
15240 returned. In any other case, return the value as a string.
15241 Search is case-insensitive.
15243 If LITERAL-NIL is set, return the string value \"nil\" as
15244 a string, do not interpret it as the list atom nil. This is used
15245 for inheritance when a \"nil\" value can supersede a non-nil
15246 value higher up the hierarchy."
15247 (org-with-point-at pom
15248 (cond
15249 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15250 ;; We need a special property. Use `org-entry-properties' to
15251 ;; retrieve it, but specify the wanted property.
15252 (cdr (assoc-string property (org-entry-properties nil property))))
15253 ((and inherit
15254 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15255 (org-entry-get-with-inheritance property literal-nil))
15257 (let* ((local (org--property-local-values property literal-nil))
15258 (value (and local (mapconcat #'identity (delq nil local) " "))))
15259 (if literal-nil value (org-not-nil value)))))))
15261 (defun org-property-or-variable-value (var &optional inherit)
15262 "Check if there is a property fixing the value of VAR.
15263 If yes, return this value. If not, return the current value of the variable."
15264 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15265 (if (and prop (stringp prop) (string-match "\\S-" prop))
15266 (read prop)
15267 (symbol-value var))))
15269 (defun org-entry-delete (pom property)
15270 "Delete PROPERTY from entry at point-or-marker POM.
15271 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15272 non-nil when a property was removed."
15273 (org-with-point-at pom
15274 (pcase (org-get-property-block)
15275 (`(,begin . ,origin)
15276 (let* ((end (copy-marker origin))
15277 (re (org-re-property
15278 (concat (regexp-quote property) "\\+?") t t)))
15279 (goto-char begin)
15280 (while (re-search-forward re end t)
15281 (delete-region (match-beginning 0) (line-beginning-position 2)))
15282 ;; If drawer is empty, remove it altogether.
15283 (when (= begin end)
15284 (delete-region (line-beginning-position 0)
15285 (line-beginning-position 2)))
15286 ;; Return non-nil if some property was removed.
15287 (prog1 (/= end origin) (set-marker end nil))))
15288 (_ nil))))
15290 ;; Multi-values properties are properties that contain multiple values
15291 ;; These values are assumed to be single words, separated by whitespace.
15292 (defun org-entry-add-to-multivalued-property (pom property value)
15293 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15294 (let* ((old (org-entry-get pom property))
15295 (values (and old (split-string old))))
15296 (setq value (org-entry-protect-space value))
15297 (unless (member value values)
15298 (setq values (append values (list value)))
15299 (org-entry-put pom property (mapconcat #'identity values " ")))))
15301 (defun org-entry-remove-from-multivalued-property (pom property value)
15302 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15303 (let* ((old (org-entry-get pom property))
15304 (values (and old (split-string old))))
15305 (setq value (org-entry-protect-space value))
15306 (when (member value values)
15307 (setq values (delete value values))
15308 (org-entry-put pom property (mapconcat #'identity values " ")))))
15310 (defun org-entry-member-in-multivalued-property (pom property value)
15311 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15312 (let* ((old (org-entry-get pom property))
15313 (values (and old (split-string old))))
15314 (setq value (org-entry-protect-space value))
15315 (member value values)))
15317 (defun org-entry-get-multivalued-property (pom property)
15318 "Return a list of values in a multivalued property."
15319 (let* ((value (org-entry-get pom property))
15320 (values (and value (split-string value))))
15321 (mapcar #'org-entry-restore-space values)))
15323 (defun org-entry-put-multivalued-property (pom property &rest values)
15324 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15325 VALUES should be a list of strings. Spaces will be protected."
15326 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15327 (let* ((value (org-entry-get pom property))
15328 (values (and value (split-string value))))
15329 (mapcar #'org-entry-restore-space values)))
15331 (defun org-entry-protect-space (s)
15332 "Protect spaces and newline in string S."
15333 (while (string-match " " s)
15334 (setq s (replace-match "%20" t t s)))
15335 (while (string-match "\n" s)
15336 (setq s (replace-match "%0A" t t s)))
15339 (defun org-entry-restore-space (s)
15340 "Restore spaces and newline in string S."
15341 (while (string-match "%20" s)
15342 (setq s (replace-match " " t t s)))
15343 (while (string-match "%0A" s)
15344 (setq s (replace-match "\n" t t s)))
15347 (defvar org-entry-property-inherited-from (make-marker)
15348 "Marker pointing to the entry from where a property was inherited.
15349 Each call to `org-entry-get-with-inheritance' will set this marker to the
15350 location of the entry where the inheritance search matched. If there was
15351 no match, the marker will point nowhere.
15352 Note that also `org-entry-get' calls this function, if the INHERIT flag
15353 is set.")
15355 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15356 "Get PROPERTY of entry or content at point, search higher levels if needed.
15357 The search will stop at the first ancestor which has the property defined.
15358 If the value found is \"nil\", return nil to show that the property
15359 should be considered as undefined (this is the meaning of nil here).
15360 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15361 (move-marker org-entry-property-inherited-from nil)
15362 (org-with-wide-buffer
15363 (let (value)
15364 (catch 'exit
15365 (while t
15366 (let ((v (org--property-local-values property literal-nil)))
15367 (when v
15368 (setq value
15369 (concat (mapconcat #'identity (delq nil v) " ")
15370 (and value " ")
15371 value)))
15372 (cond
15373 ((car v)
15374 (org-back-to-heading t)
15375 (move-marker org-entry-property-inherited-from (point))
15376 (throw 'exit nil))
15377 ((org-up-heading-safe))
15379 (let ((global (org--property-global-value property literal-nil)))
15380 (cond ((not global))
15381 (value (setq value (concat global " " value)))
15382 (t (setq value global))))
15383 (throw 'exit nil))))))
15384 (if literal-nil value (org-not-nil value)))))
15386 (defvar org-property-changed-functions nil
15387 "Hook called when the value of a property has changed.
15388 Each hook function should accept two arguments, the name of the property
15389 and the new value.")
15391 (defun org-entry-put (pom property value)
15392 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15394 If the value is nil, it is converted to the empty string. If it
15395 is not a string, an error is raised. Also raise an error on
15396 invalid property names.
15398 PROPERTY can be any regular property (see
15399 `org-special-properties'). It can also be \"TODO\",
15400 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15402 For the last two properties, VALUE may have any of the special
15403 values \"earlier\" and \"later\". The function then increases or
15404 decreases scheduled or deadline date by one day."
15405 (cond ((null value) (setq value ""))
15406 ((not (stringp value)) (error "Properties values should be strings"))
15407 ((not (org--valid-property-p property))
15408 (user-error "Invalid property name: \"%s\"" property)))
15409 (org-with-point-at pom
15410 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15411 (org-back-to-heading t)
15412 (org-with-limited-levels (org-back-to-heading t)))
15413 (let ((beg (point)))
15414 (cond
15415 ((equal property "TODO")
15416 (cond ((not (org-string-nw-p value)) (setq value 'none))
15417 ((not (member value org-todo-keywords-1))
15418 (user-error "\"%s\" is not a valid TODO state" value)))
15419 (org-todo value)
15420 (org-align-tags))
15421 ((equal property "PRIORITY")
15422 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15423 (org-align-tags))
15424 ((equal property "SCHEDULED")
15425 (forward-line)
15426 (if (and (looking-at-p org-planning-line-re)
15427 (re-search-forward
15428 org-scheduled-time-regexp (line-end-position) t))
15429 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15430 ((string= value "later") (org-timestamp-change 1 'day))
15431 ((string= value "") (org-schedule '(4)))
15432 (t (org-schedule nil value)))
15433 (if (member value '("earlier" "later" ""))
15434 (call-interactively #'org-schedule)
15435 (org-schedule nil value))))
15436 ((equal property "DEADLINE")
15437 (forward-line)
15438 (if (and (looking-at-p org-planning-line-re)
15439 (re-search-forward
15440 org-deadline-time-regexp (line-end-position) t))
15441 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15442 ((string= value "later") (org-timestamp-change 1 'day))
15443 ((string= value "") (org-deadline '(4)))
15444 (t (org-deadline nil value)))
15445 (if (member value '("earlier" "later" ""))
15446 (call-interactively #'org-deadline)
15447 (org-deadline nil value))))
15448 ((member property org-special-properties)
15449 (error "The %s property cannot be set with `org-entry-put'" property))
15451 (let* ((range (org-get-property-block beg 'force))
15452 (end (cdr range))
15453 (case-fold-search t))
15454 (goto-char (car range))
15455 (if (re-search-forward (org-re-property property nil t) end t)
15456 (progn (delete-region (match-beginning 0) (match-end 0))
15457 (goto-char (match-beginning 0)))
15458 (goto-char end)
15459 (insert "\n")
15460 (backward-char))
15461 (insert ":" property ":")
15462 (when value (insert " " value))
15463 (org-indent-line)))))
15464 (run-hook-with-args 'org-property-changed-functions property value)))
15466 (defun org-buffer-property-keys (&optional specials defaults columns)
15467 "Get all property keys in the current buffer.
15469 When SPECIALS is non-nil, also list the special properties that
15470 reflect things like tags and TODO state.
15472 When DEFAULTS is non-nil, also include properties that has
15473 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15474 DESCRIPTION, LOCATION, and LOGGING and others.
15476 When COLUMNS in non-nil, also include property names given in
15477 COLUMN formats in the current buffer."
15478 (let ((case-fold-search t)
15479 (props (append
15480 (and specials org-special-properties)
15481 (and defaults (cons org-effort-property org-default-properties))
15482 nil)))
15483 (org-with-wide-buffer
15484 (goto-char (point-min))
15485 (while (re-search-forward org-property-start-re nil t)
15486 (catch :skip
15487 (let ((range (org-get-property-block)))
15488 (unless range (throw :skip nil))
15489 (goto-char (car range))
15490 (let ((begin (car range))
15491 (end (cdr range)))
15492 ;; Make sure that found property block is not located
15493 ;; before current point, as it would generate an infloop.
15494 ;; It can happen, for example, in the following
15495 ;; situation:
15497 ;; * Headline
15498 ;; :PROPERTIES:
15499 ;; ...
15500 ;; :END:
15501 ;; *************** Inlinetask
15502 ;; #+BEGIN_EXAMPLE
15503 ;; :PROPERTIES:
15504 ;; #+END_EXAMPLE
15506 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15507 (while (< (point) end)
15508 (let ((p (progn (looking-at org-property-re)
15509 (match-string-no-properties 2))))
15510 ;; Only add true property name, not extension symbol.
15511 (push (if (not (string-match-p "\\+\\'" p)) p
15512 (substring p 0 -1))
15513 props))
15514 (forward-line))))
15515 (outline-next-heading)))
15516 (when columns
15517 (goto-char (point-min))
15518 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15519 (let ((element (org-element-at-point)))
15520 (when (memq (org-element-type element) '(keyword node-property))
15521 (let ((value (org-element-property :value element))
15522 (start 0))
15523 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15524 \\(?:{[^}]+}\\)?"
15525 value start)
15526 (setq start (match-end 0))
15527 (let ((p (match-string-no-properties 1 value)))
15528 (unless (member-ignore-case p org-special-properties)
15529 (push p props))))))))))
15530 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15532 (defun org-property-values (key)
15533 "List all non-nil values of property KEY in current buffer."
15534 (org-with-wide-buffer
15535 (goto-char (point-min))
15536 (let ((case-fold-search t)
15537 (re (org-re-property key))
15538 values)
15539 (while (re-search-forward re nil t)
15540 (push (org-entry-get (point) key) values))
15541 (delete-dups values))))
15543 (defun org-insert-property-drawer ()
15544 "Insert a property drawer into the current entry."
15545 (org-with-wide-buffer
15546 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15547 (org-back-to-heading t)
15548 (org-with-limited-levels (org-back-to-heading t)))
15549 (forward-line)
15550 (when (looking-at-p org-planning-line-re) (forward-line))
15551 (unless (looking-at-p org-property-drawer-re)
15552 ;; Make sure we start editing a line from current entry, not from
15553 ;; next one. It prevents extending text properties or overlays
15554 ;; belonging to the latter.
15555 (when (bolp) (backward-char))
15556 (let ((begin (1+ (point)))
15557 (inhibit-read-only t))
15558 (insert "\n:PROPERTIES:\n:END:")
15559 (when (eobp) (insert "\n"))
15560 (org-indent-region begin (point))))))
15562 (defun org-insert-drawer (&optional arg drawer)
15563 "Insert a drawer at point.
15565 When optional argument ARG is non-nil, insert a property drawer.
15567 Optional argument DRAWER, when non-nil, is a string representing
15568 drawer's name. Otherwise, the user is prompted for a name.
15570 If a region is active, insert the drawer around that region
15571 instead.
15573 Point is left between drawer's boundaries."
15574 (interactive "P")
15575 (let* ((drawer (if arg "PROPERTIES"
15576 (or drawer (read-from-minibuffer "Drawer: ")))))
15577 (cond
15578 ;; With C-u, fall back on `org-insert-property-drawer'
15579 (arg (org-insert-property-drawer))
15580 ;; Check validity of suggested drawer's name.
15581 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15582 (user-error "Invalid drawer name"))
15583 ;; With an active region, insert a drawer at point.
15584 ((not (org-region-active-p))
15585 (progn
15586 (unless (bolp) (insert "\n"))
15587 (insert (format ":%s:\n\n:END:\n" drawer))
15588 (forward-line -2)))
15589 ;; Otherwise, insert the drawer at point
15591 (let ((rbeg (region-beginning))
15592 (rend (copy-marker (region-end))))
15593 (unwind-protect
15594 (progn
15595 (goto-char rbeg)
15596 (beginning-of-line)
15597 (when (save-excursion
15598 (re-search-forward org-outline-regexp-bol rend t))
15599 (user-error "Drawers cannot contain headlines"))
15600 ;; Position point at the beginning of the first
15601 ;; non-blank line in region. Insert drawer's opening
15602 ;; there, then indent it.
15603 (org-skip-whitespace)
15604 (beginning-of-line)
15605 (insert ":" drawer ":\n")
15606 (forward-line -1)
15607 (indent-for-tab-command)
15608 ;; Move point to the beginning of the first blank line
15609 ;; after the last non-blank line in region. Insert
15610 ;; drawer's closing, then indent it.
15611 (goto-char rend)
15612 (skip-chars-backward " \r\t\n")
15613 (insert "\n:END:")
15614 (deactivate-mark t)
15615 (indent-for-tab-command)
15616 (unless (eolp) (insert "\n")))
15617 ;; Clear marker, whatever the outcome of insertion is.
15618 (set-marker rend nil)))))))
15620 (defvar org-property-set-functions-alist nil
15621 "Property set function alist.
15622 Each entry should have the following format:
15624 (PROPERTY . READ-FUNCTION)
15626 The read function will be called with the same argument as
15627 `org-completing-read'.")
15629 (defun org-set-property-function (property)
15630 "Get the function that should be used to set PROPERTY.
15631 This is computed according to `org-property-set-functions-alist'."
15632 (or (cdr (assoc property org-property-set-functions-alist))
15633 'org-completing-read))
15635 (defun org-read-property-value (property)
15636 "Read PROPERTY value from user."
15637 (let* ((completion-ignore-case t)
15638 (allowed (org-property-get-allowed-values nil property 'table))
15639 (cur (org-entry-get nil property))
15640 (prompt (concat property " value"
15641 (if (and cur (string-match "\\S-" cur))
15642 (concat " [" cur "]") "") ": "))
15643 (set-function (org-set-property-function property))
15644 (val (if allowed
15645 (funcall set-function prompt allowed nil
15646 (not (get-text-property 0 'org-unrestricted
15647 (caar allowed))))
15648 (funcall set-function prompt
15649 (mapcar 'list (org-property-values property))
15650 nil nil "" nil cur))))
15651 (org-trim val)))
15653 (defvar org-last-set-property nil)
15654 (defvar org-last-set-property-value nil)
15655 (defun org-read-property-name ()
15656 "Read a property name."
15657 (let ((completion-ignore-case t)
15658 (default-prop (or (and (org-at-property-p)
15659 (match-string-no-properties 2))
15660 org-last-set-property)))
15661 (org-completing-read
15662 (concat "Property"
15663 (if default-prop (concat " [" default-prop "]") "")
15664 ": ")
15665 (mapcar #'list (org-buffer-property-keys nil t t))
15666 nil nil nil nil default-prop)))
15668 (defun org-set-property-and-value (use-last)
15669 "Allow to set [PROPERTY]: [value] direction from prompt.
15670 When use-default, don't even ask, just use the last
15671 \"[PROPERTY]: [value]\" string from the history."
15672 (interactive "P")
15673 (let* ((completion-ignore-case t)
15674 (pv (or (and use-last org-last-set-property-value)
15675 (org-completing-read
15676 "Enter a \"[Property]: [value]\" pair: "
15677 nil nil nil nil nil
15678 org-last-set-property-value)))
15679 prop val)
15680 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15681 (setq prop (match-string 1 pv)
15682 val (match-string 2 pv))
15683 (org-set-property prop val))))
15685 (defun org-set-property (property value)
15686 "In the current entry, set PROPERTY to VALUE.
15688 When called interactively, this will prompt for a property name, offering
15689 completion on existing and default properties. And then it will prompt
15690 for a value, offering completion either on allowed values (via an inherited
15691 xxx_ALL property) or on existing values in other instances of this property
15692 in the current file.
15694 Throw an error when trying to set a property with an invalid name."
15695 (interactive (list nil nil))
15696 (let ((property (or property (org-read-property-name))))
15697 ;; `org-entry-put' also makes the following check, but this one
15698 ;; avoids polluting `org-last-set-property' and
15699 ;; `org-last-set-property-value' needlessly.
15700 (unless (org--valid-property-p property)
15701 (user-error "Invalid property name: \"%s\"" property))
15702 (let ((value (or value (org-read-property-value property)))
15703 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15704 (setq org-last-set-property property)
15705 (setq org-last-set-property-value (concat property ": " value))
15706 ;; Possibly postprocess the inserted value:
15707 (when fn (setq value (funcall fn value)))
15708 (unless (equal (org-entry-get nil property) value)
15709 (org-entry-put nil property value)))))
15711 (defun org-find-property (property &optional value)
15712 "Find first entry in buffer that sets PROPERTY.
15714 When optional argument VALUE is non-nil, only consider an entry
15715 if it contains PROPERTY set to this value. If PROPERTY should be
15716 explicitly set to nil, use string \"nil\" for VALUE.
15718 Return position where the entry begins, or nil if there is no
15719 such entry. If narrowing is in effect, only search the visible
15720 part of the buffer."
15721 (save-excursion
15722 (goto-char (point-min))
15723 (let ((case-fold-search t)
15724 (re (org-re-property property nil (not value) value)))
15725 (catch 'exit
15726 (while (re-search-forward re nil t)
15727 (when (if value (org-at-property-p)
15728 (org-entry-get (point) property nil t))
15729 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15731 (defun org-delete-property (property)
15732 "In the current entry, delete PROPERTY."
15733 (interactive
15734 (let* ((completion-ignore-case t)
15735 (cat (org-entry-get (point) "CATEGORY"))
15736 (props0 (org-entry-properties nil 'standard))
15737 (props (if cat props0
15738 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15739 (prop (if (< 1 (length props))
15740 (completing-read "Property: " props nil t)
15741 (caar props))))
15742 (list prop)))
15743 (if (not property)
15744 (message "No property to delete in this entry")
15745 (org-entry-delete nil property)
15746 (message "Property \"%s\" deleted" property)))
15748 (defun org-delete-property-globally (property)
15749 "Remove PROPERTY globally, from all entries.
15750 This function ignores narrowing, if any."
15751 (interactive
15752 (let* ((completion-ignore-case t)
15753 (prop (completing-read
15754 "Globally remove property: "
15755 (mapcar #'list (org-buffer-property-keys)))))
15756 (list prop)))
15757 (org-with-wide-buffer
15758 (goto-char (point-min))
15759 (let ((count 0)
15760 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15761 (while (re-search-forward re nil t)
15762 (when (org-entry-delete (point) property) (cl-incf count)))
15763 (message "Property \"%s\" removed from %d entries" property count))))
15765 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15767 (defun org-compute-property-at-point ()
15768 "Compute the property at point.
15769 This looks for an enclosing column format, extracts the operator and
15770 then applies it to the property in the column format's scope."
15771 (interactive)
15772 (unless (org-at-property-p)
15773 (user-error "Not at a property"))
15774 (let ((prop (match-string-no-properties 2)))
15775 (org-columns-get-format-and-top-level)
15776 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15777 (user-error "No operator defined for property %s" prop))
15778 (org-columns-compute prop)))
15780 (defvar org-property-allowed-value-functions nil
15781 "Hook for functions supplying allowed values for a specific property.
15782 The functions must take a single argument, the name of the property, and
15783 return a flat list of allowed values. If \":ETC\" is one of
15784 the values, this means that these values are intended as defaults for
15785 completion, but that other values should be allowed too.
15786 The functions must return nil if they are not responsible for this
15787 property.")
15789 (defun org-property-get-allowed-values (pom property &optional table)
15790 "Get allowed values for the property PROPERTY.
15791 When TABLE is non-nil, return an alist that can directly be used for
15792 completion."
15793 (let (vals)
15794 (cond
15795 ((equal property "TODO")
15796 (setq vals (org-with-point-at pom
15797 (append org-todo-keywords-1 '("")))))
15798 ((equal property "PRIORITY")
15799 (let ((n org-lowest-priority))
15800 (while (>= n org-highest-priority)
15801 (push (char-to-string n) vals)
15802 (setq n (1- n)))))
15803 ((equal property "CATEGORY"))
15804 ((member property org-special-properties))
15805 ((setq vals (run-hook-with-args-until-success
15806 'org-property-allowed-value-functions property)))
15808 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15809 (when (and vals (string-match "\\S-" vals))
15810 (setq vals (car (read-from-string (concat "(" vals ")"))))
15811 (setq vals (mapcar (lambda (x)
15812 (cond ((stringp x) x)
15813 ((numberp x) (number-to-string x))
15814 ((symbolp x) (symbol-name x))
15815 (t "???")))
15816 vals)))))
15817 (when (member ":ETC" vals)
15818 (setq vals (remove ":ETC" vals))
15819 (org-add-props (car vals) '(org-unrestricted t)))
15820 (if table (mapcar 'list vals) vals)))
15822 (defun org-property-previous-allowed-value (&optional _previous)
15823 "Switch to the next allowed value for this property."
15824 (interactive)
15825 (org-property-next-allowed-value t))
15827 (defun org-property-next-allowed-value (&optional previous)
15828 "Switch to the next allowed value for this property."
15829 (interactive)
15830 (unless (org-at-property-p)
15831 (user-error "Not at a property"))
15832 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15833 (key (match-string 2))
15834 (value (match-string 3))
15835 (allowed (or (org-property-get-allowed-values (point) key)
15836 (and (member value '("[ ]" "[-]" "[X]"))
15837 '("[ ]" "[X]"))))
15838 (heading (save-match-data (nth 4 (org-heading-components))))
15839 nval)
15840 (unless allowed
15841 (user-error "Allowed values for this property have not been defined"))
15842 (when previous (setq allowed (reverse allowed)))
15843 (when (member value allowed)
15844 (setq nval (car (cdr (member value allowed)))))
15845 (setq nval (or nval (car allowed)))
15846 (when (equal nval value)
15847 (user-error "Only one allowed value for this property"))
15848 (org-at-property-p)
15849 (replace-match (concat " :" key ": " nval) t t)
15850 (org-indent-line)
15851 (beginning-of-line 1)
15852 (skip-chars-forward " \t")
15853 (when (equal prop org-effort-property)
15854 (org-refresh-property
15855 '((effort . identity)
15856 (effort-minutes . org-duration-to-minutes))
15857 nval)
15858 (when (string= org-clock-current-task heading)
15859 (setq org-clock-effort nval)
15860 (org-clock-update-mode-line)))
15861 (run-hook-with-args 'org-property-changed-functions key nval)))
15863 (defun org-find-olp (path &optional this-buffer)
15864 "Return a marker pointing to the entry at outline path OLP.
15865 If anything goes wrong, throw an error.
15866 You can wrap this call to catch the error like this:
15868 (condition-case msg
15869 (org-mobile-locate-entry (match-string 4))
15870 (error (nth 1 msg)))
15872 The return value will then be either a string with the error message,
15873 or a marker if everything is OK.
15875 If THIS-BUFFER is set, the outline path does not contain a file,
15876 only headings."
15877 (let* ((file (if this-buffer buffer-file-name (pop path)))
15878 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15879 (level 1)
15880 (lmin 1)
15881 (lmax 1)
15882 end found flevel)
15883 (unless buffer (error "File not found :%s" file))
15884 (with-current-buffer buffer
15885 (unless (derived-mode-p 'org-mode)
15886 (error "Buffer %s needs to be in Org mode" buffer))
15887 (org-with-wide-buffer
15888 (goto-char (point-min))
15889 (dolist (heading path)
15890 (let ((re (format org-complex-heading-regexp-format
15891 (regexp-quote heading)))
15892 (cnt 0))
15893 (while (re-search-forward re end t)
15894 (setq level (- (match-end 1) (match-beginning 1)))
15895 (when (and (>= level lmin) (<= level lmax))
15896 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15897 (when (= cnt 0)
15898 (error "Heading not found on level %d: %s" lmax heading))
15899 (when (> cnt 1)
15900 (error "Heading not unique on level %d: %s" lmax heading))
15901 (goto-char found)
15902 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15903 (setq end (save-excursion (org-end-of-subtree t t)))))
15904 (when (org-at-heading-p)
15905 (point-marker))))))
15907 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15908 "Find node HEADING in BUFFER.
15909 Return a marker to the heading if it was found, or nil if not.
15910 If POS-ONLY is set, return just the position instead of a marker.
15912 The heading text must match exact, but it may have a TODO keyword,
15913 a priority cookie and tags in the standard locations."
15914 (with-current-buffer (or buffer (current-buffer))
15915 (org-with-wide-buffer
15916 (goto-char (point-min))
15917 (let (case-fold-search)
15918 (when (re-search-forward
15919 (format org-complex-heading-regexp-format
15920 (regexp-quote heading)) nil t)
15921 (if pos-only
15922 (match-beginning 0)
15923 (move-marker (make-marker) (match-beginning 0))))))))
15925 (defun org-find-exact-heading-in-directory (heading &optional dir)
15926 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15927 When the target headline is found, return a marker to this location."
15928 (let ((files (directory-files (or dir default-directory)
15929 t "\\`[^.#].*\\.org\\'"))
15930 visiting m buffer)
15931 (catch 'found
15932 (dolist (file files)
15933 (message "trying %s" file)
15934 (setq visiting (org-find-base-buffer-visiting file))
15935 (setq buffer (or visiting (find-file-noselect file)))
15936 (setq m (org-find-exact-headline-in-buffer
15937 heading buffer))
15938 (when (and (not m) (not visiting)) (kill-buffer buffer))
15939 (and m (throw 'found m))))))
15941 (defun org-find-entry-with-id (ident)
15942 "Locate the entry that contains the ID property with exact value IDENT.
15943 IDENT can be a string, a symbol or a number, this function will search for
15944 the string representation of it.
15945 Return the position where this entry starts, or nil if there is no such entry."
15946 (interactive "sID: ")
15947 (let ((id (cond
15948 ((stringp ident) ident)
15949 ((symbolp ident) (symbol-name ident))
15950 ((numberp ident) (number-to-string ident))
15951 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15952 (org-with-wide-buffer (org-find-property "ID" id))))
15954 ;;;; Timestamps
15956 (defvar org-last-changed-timestamp nil)
15957 (defvar org-last-inserted-timestamp nil
15958 "The last time stamp inserted with `org-insert-time-stamp'.")
15960 (defun org-time-stamp (arg &optional inactive)
15961 "Prompt for a date/time and insert a time stamp.
15963 If the user specifies a time like HH:MM or if this command is
15964 called with at least one prefix argument, the time stamp contains
15965 the date and the time. Otherwise, only the date is included.
15967 All parts of a date not specified by the user are filled in from
15968 the timestamp at point, if any, or the current date/time
15969 otherwise.
15971 If there is already a timestamp at the cursor, it is replaced.
15973 With two universal prefix arguments, insert an active timestamp
15974 with the current time without prompting the user.
15976 When called from lisp, the timestamp is inactive if INACTIVE is
15977 non-nil."
15978 (interactive "P")
15979 (let* ((ts (cond
15980 ((org-at-date-range-p t)
15981 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
15982 ((org-at-timestamp-p 'lax) (match-string 0))))
15983 ;; Default time is either the timestamp at point or today.
15984 ;; When entering a range, only the range start is considered.
15985 (default-time (if (not ts) (current-time)
15986 (apply #'encode-time (org-parse-time-string ts))))
15987 (default-input (and ts (org-get-compact-tod ts)))
15988 (repeater (and ts
15989 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
15990 (match-string 0 ts)))
15991 org-time-was-given
15992 org-end-time-was-given
15993 (time
15994 (and (if (equal arg '(16)) (current-time)
15995 ;; Preserve `this-command' and `last-command'.
15996 (let ((this-command this-command)
15997 (last-command last-command))
15998 (org-read-date
15999 arg 'totime nil nil default-time default-input
16000 inactive))))))
16001 (cond
16002 ((and ts
16003 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16004 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16005 (insert "--")
16006 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16008 ;; Make sure we're on a timestamp. When in the middle of a date
16009 ;; range, move arbitrarily to range end.
16010 (unless (org-at-timestamp-p 'lax)
16011 (skip-chars-forward "-")
16012 (org-at-timestamp-p 'lax))
16013 (replace-match "")
16014 (setq org-last-changed-timestamp
16015 (org-insert-time-stamp
16016 time (or org-time-was-given arg)
16017 inactive nil nil (list org-end-time-was-given)))
16018 (when repeater
16019 (backward-char)
16020 (insert " " repeater)
16021 (setq org-last-changed-timestamp
16022 (concat (substring org-last-inserted-timestamp 0 -1)
16023 " " repeater ">")))
16024 (message "Timestamp updated"))
16025 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16026 (t (org-insert-time-stamp
16027 time (or org-time-was-given arg) inactive nil nil
16028 (list org-end-time-was-given))))))
16030 ;; FIXME: can we use this for something else, like computing time differences?
16031 (defun org-get-compact-tod (s)
16032 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16033 (let* ((t1 (match-string 1 s))
16034 (h1 (string-to-number (match-string 2 s)))
16035 (m1 (string-to-number (match-string 3 s)))
16036 (t2 (and (match-end 4) (match-string 5 s)))
16037 (h2 (and t2 (string-to-number (match-string 6 s))))
16038 (m2 (and t2 (string-to-number (match-string 7 s))))
16039 dh dm)
16040 (if (not t2)
16042 (setq dh (- h2 h1) dm (- m2 m1))
16043 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16044 (concat t1 "+" (number-to-string dh)
16045 (and (/= 0 dm) (format ":%02d" dm)))))))
16047 (defun org-time-stamp-inactive (&optional arg)
16048 "Insert an inactive time stamp.
16050 An inactive time stamp is enclosed in square brackets instead of angle
16051 brackets. It is inactive in the sense that it does not trigger agenda entries,
16052 does not link to the calendar and cannot be changed with the S-cursor keys.
16053 So these are more for recording a certain time/date.
16055 If the user specifies a time like HH:MM or if this command is called with
16056 at least one prefix argument, the time stamp contains the date and the time.
16057 Otherwise, only the date is included.
16059 When called with two universal prefix arguments, insert an active time stamp
16060 with the current time without prompting the user."
16061 (interactive "P")
16062 (org-time-stamp arg 'inactive))
16064 (defvar org-date-ovl (make-overlay 1 1))
16065 (overlay-put org-date-ovl 'face 'org-date-selected)
16066 (delete-overlay org-date-ovl)
16068 (defvar org-ans1) ; dynamically scoped parameter
16069 (defvar org-ans2) ; dynamically scoped parameter
16071 (defvar org-plain-time-of-day-regexp) ; defined below
16073 (defvar org-overriding-default-time nil) ; dynamically scoped
16074 (defvar org-read-date-overlay nil)
16075 (defvar org-dcst nil) ; dynamically scoped
16076 (defvar org-read-date-history nil)
16077 (defvar org-read-date-final-answer nil)
16078 (defvar org-read-date-analyze-futurep nil)
16079 (defvar org-read-date-analyze-forced-year nil)
16080 (defvar org-read-date-inactive)
16082 (defvar org-read-date-minibuffer-local-map
16083 (let* ((map (make-sparse-keymap)))
16084 (set-keymap-parent map minibuffer-local-map)
16085 (org-defkey map (kbd ".")
16086 (lambda () (interactive)
16087 ;; Are we at the beginning of the prompt?
16088 (if (looking-back "^[^:]+: "
16089 (let ((inhibit-field-text-motion t))
16090 (line-beginning-position)))
16091 (org-eval-in-calendar '(calendar-goto-today))
16092 (insert "."))))
16093 (org-defkey map (kbd "C-.")
16094 (lambda () (interactive)
16095 (org-eval-in-calendar '(calendar-goto-today))))
16096 (org-defkey map (kbd "M-S-<left>")
16097 (lambda () (interactive)
16098 (org-eval-in-calendar '(calendar-backward-month 1))))
16099 (org-defkey map (kbd "ESC S-<left>")
16100 (lambda () (interactive)
16101 (org-eval-in-calendar '(calendar-backward-month 1))))
16102 (org-defkey map (kbd "M-S-<right>")
16103 (lambda () (interactive)
16104 (org-eval-in-calendar '(calendar-forward-month 1))))
16105 (org-defkey map (kbd "ESC S-<right>")
16106 (lambda () (interactive)
16107 (org-eval-in-calendar '(calendar-forward-month 1))))
16108 (org-defkey map (kbd "M-S-<up>")
16109 (lambda () (interactive)
16110 (org-eval-in-calendar '(calendar-backward-year 1))))
16111 (org-defkey map (kbd "ESC S-<up>")
16112 (lambda () (interactive)
16113 (org-eval-in-calendar '(calendar-backward-year 1))))
16114 (org-defkey map (kbd "M-S-<down>")
16115 (lambda () (interactive)
16116 (org-eval-in-calendar '(calendar-forward-year 1))))
16117 (org-defkey map (kbd "ESC S-<down>")
16118 (lambda () (interactive)
16119 (org-eval-in-calendar '(calendar-forward-year 1))))
16120 (org-defkey map (kbd "S-<up>")
16121 (lambda () (interactive)
16122 (org-eval-in-calendar '(calendar-backward-week 1))))
16123 (org-defkey map (kbd "S-<down>")
16124 (lambda () (interactive)
16125 (org-eval-in-calendar '(calendar-forward-week 1))))
16126 (org-defkey map (kbd "S-<left>")
16127 (lambda () (interactive)
16128 (org-eval-in-calendar '(calendar-backward-day 1))))
16129 (org-defkey map (kbd "S-<right>")
16130 (lambda () (interactive)
16131 (org-eval-in-calendar '(calendar-forward-day 1))))
16132 (org-defkey map (kbd "!")
16133 (lambda () (interactive)
16134 (org-eval-in-calendar '(diary-view-entries))
16135 (message "")))
16136 (org-defkey map (kbd ">")
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-scroll-left 1))))
16139 (org-defkey map (kbd "<")
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-scroll-right 1))))
16142 (org-defkey map (kbd "C-v")
16143 (lambda () (interactive)
16144 (org-eval-in-calendar
16145 '(calendar-scroll-left-three-months 1))))
16146 (org-defkey map (kbd "M-v")
16147 (lambda () (interactive)
16148 (org-eval-in-calendar
16149 '(calendar-scroll-right-three-months 1))))
16150 map)
16151 "Keymap for minibuffer commands when using `org-read-date'.")
16153 (defvar org-def)
16154 (defvar org-defdecode)
16155 (defvar org-with-time)
16157 (defvar calendar-setup) ; Dynamically scoped.
16158 (defun org-read-date (&optional with-time to-time from-string prompt
16159 default-time default-input inactive)
16160 "Read a date, possibly a time, and make things smooth for the user.
16161 The prompt will suggest to enter an ISO date, but you can also enter anything
16162 which will at least partially be understood by `parse-time-string'.
16163 Unrecognized parts of the date will default to the current day, month, year,
16164 hour and minute. If this command is called to replace a timestamp at point,
16165 or to enter the second timestamp of a range, the default time is taken
16166 from the existing stamp. Furthermore, the command prefers the future,
16167 so if you are giving a date where the year is not given, and the day-month
16168 combination is already past in the current year, it will assume you
16169 mean next year. For details, see the manual. A few examples:
16171 3-2-5 --> 2003-02-05
16172 feb 15 --> currentyear-02-15
16173 2/15 --> currentyear-02-15
16174 sep 12 9 --> 2009-09-12
16175 12:45 --> today 12:45
16176 22 sept 0:34 --> currentyear-09-22 0:34
16177 12 --> currentyear-currentmonth-12
16178 Fri --> nearest Friday after today
16179 -Tue --> last Tuesday
16180 etc.
16182 Furthermore you can specify a relative date by giving, as the *first* thing
16183 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16184 change in days weeks, months, years.
16185 With a single plus or minus, the date is relative to today. With a double
16186 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16187 +4d --> four days from today
16188 +4 --> same as above
16189 +2w --> two weeks from today
16190 ++5 --> five days from default date
16192 The function understands only English month and weekday abbreviations.
16194 While prompting, a calendar is popped up - you can also select the
16195 date with the mouse (button 1). The calendar shows a period of three
16196 months. To scroll it to other months, use the keys `>' and `<'.
16197 If you don't like the calendar, turn it off with
16198 (setq org-read-date-popup-calendar nil)
16200 With optional argument TO-TIME, the date will immediately be converted
16201 to an internal time.
16202 With an optional argument WITH-TIME, the prompt will suggest to
16203 also insert a time. Note that when WITH-TIME is not set, you can
16204 still enter a time, and this function will inform the calling routine
16205 about this change. The calling routine may then choose to change the
16206 format used to insert the time stamp into the buffer to include the time.
16207 With optional argument FROM-STRING, read from this string instead from
16208 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16209 the time/date that is used for everything that is not specified by the
16210 user."
16211 (require 'parse-time)
16212 (let* ((org-with-time with-time)
16213 (org-time-stamp-rounding-minutes
16214 (if (equal org-with-time '(16))
16215 '(0 0)
16216 org-time-stamp-rounding-minutes))
16217 (org-dcst org-display-custom-times)
16218 (ct (org-current-time))
16219 (org-def (or org-overriding-default-time default-time ct))
16220 (org-defdecode (decode-time org-def))
16221 (cur-frame (selected-frame))
16222 (mouse-autoselect-window nil) ; Don't let the mouse jump
16223 (calendar-setup
16224 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16225 (calendar-move-hook nil)
16226 (calendar-view-diary-initially-flag nil)
16227 (calendar-view-holidays-initially-flag nil)
16228 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16229 ;; Rationalize `org-def' and `org-defdecode', if required.
16230 (when (< (nth 2 org-defdecode) org-extend-today-until)
16231 (setf (nth 2 org-defdecode) -1)
16232 (setf (nth 1 org-defdecode) 59)
16233 (setq org-def (apply #'encode-time org-defdecode))
16234 (setq org-defdecode (decode-time org-def)))
16235 (let* ((timestr (format-time-string
16236 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16237 org-def))
16238 (prompt (concat (if prompt (concat prompt " ") "")
16239 (format "Date+time [%s]: " timestr))))
16240 (cond
16241 (from-string (setq ans from-string))
16242 (org-read-date-popup-calendar
16243 (save-excursion
16244 (save-window-excursion
16245 (calendar)
16246 (when (eq calendar-setup 'calendar-only)
16247 (setq cal-frame
16248 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16249 (select-frame cal-frame))
16250 (org-eval-in-calendar '(setq cursor-type nil) t)
16251 (unwind-protect
16252 (progn
16253 (calendar-forward-day (- (time-to-days org-def)
16254 (calendar-absolute-from-gregorian
16255 (calendar-current-date))))
16256 (org-eval-in-calendar nil t)
16257 (let* ((old-map (current-local-map))
16258 (map (copy-keymap calendar-mode-map))
16259 (minibuffer-local-map
16260 (copy-keymap org-read-date-minibuffer-local-map)))
16261 (org-defkey map (kbd "RET") 'org-calendar-select)
16262 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16263 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16264 (unwind-protect
16265 (progn
16266 (use-local-map map)
16267 (setq org-read-date-inactive inactive)
16268 (add-hook 'post-command-hook 'org-read-date-display)
16269 (setq org-ans0
16270 (read-string prompt
16271 default-input
16272 'org-read-date-history
16273 nil))
16274 ;; org-ans0: from prompt
16275 ;; org-ans1: from mouse click
16276 ;; org-ans2: from calendar motion
16277 (setq ans
16278 (concat org-ans0 " " (or org-ans1 org-ans2))))
16279 (remove-hook 'post-command-hook 'org-read-date-display)
16280 (use-local-map old-map)
16281 (when org-read-date-overlay
16282 (delete-overlay org-read-date-overlay)
16283 (setq org-read-date-overlay nil)))))
16284 (bury-buffer "*Calendar*")
16285 (when cal-frame
16286 (delete-frame cal-frame)
16287 (select-frame-set-input-focus cur-frame))))))
16289 (t ; Naked prompt only
16290 (unwind-protect
16291 (setq ans (read-string prompt default-input
16292 'org-read-date-history timestr))
16293 (when org-read-date-overlay
16294 (delete-overlay org-read-date-overlay)
16295 (setq org-read-date-overlay nil))))))
16297 (setq final (org-read-date-analyze ans org-def org-defdecode))
16299 (when org-read-date-analyze-forced-year
16300 (message "Year was forced into %s"
16301 (if org-read-date-force-compatible-dates
16302 "compatible range (1970-2037)"
16303 "range representable on this machine"))
16304 (ding))
16306 ;; One round trip to get rid of 34th of August and stuff like that....
16307 (setq final (decode-time (apply 'encode-time final)))
16309 (setq org-read-date-final-answer ans)
16311 (if to-time
16312 (apply 'encode-time final)
16313 (if (and (boundp 'org-time-was-given) org-time-was-given)
16314 (format "%04d-%02d-%02d %02d:%02d"
16315 (nth 5 final) (nth 4 final) (nth 3 final)
16316 (nth 2 final) (nth 1 final))
16317 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16319 (defun org-read-date-display ()
16320 "Display the current date prompt interpretation in the minibuffer."
16321 (when org-read-date-display-live
16322 (when org-read-date-overlay
16323 (delete-overlay org-read-date-overlay))
16324 (when (minibufferp (current-buffer))
16325 (save-excursion
16326 (end-of-line 1)
16327 (while (not (equal (buffer-substring
16328 (max (point-min) (- (point) 4)) (point))
16329 " "))
16330 (insert " ")))
16331 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16332 " " (or org-ans1 org-ans2)))
16333 (org-end-time-was-given nil)
16334 (f (org-read-date-analyze ans org-def org-defdecode))
16335 (fmts (if org-dcst
16336 org-time-stamp-custom-formats
16337 org-time-stamp-formats))
16338 (fmt (if (or org-with-time
16339 (and (boundp 'org-time-was-given) org-time-was-given))
16340 (cdr fmts)
16341 (car fmts)))
16342 (txt (format-time-string fmt (apply 'encode-time f)))
16343 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16344 (txt (concat "=> " txt)))
16345 (when (and org-end-time-was-given
16346 (string-match org-plain-time-of-day-regexp txt))
16347 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16348 org-end-time-was-given
16349 (substring txt (match-end 0)))))
16350 (when org-read-date-analyze-futurep
16351 (setq txt (concat txt " (=>F)")))
16352 (setq org-read-date-overlay
16353 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16354 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16356 (defun org-read-date-analyze (ans def defdecode)
16357 "Analyze the combined answer of the date prompt."
16358 ;; FIXME: cleanup and comment
16359 ;; Pass `current-time' result to `decode-time' (instead of calling
16360 ;; without arguments) so that only `current-time' has to be
16361 ;; overridden in tests.
16362 (let ((org-def def)
16363 (org-defdecode defdecode)
16364 (nowdecode (decode-time (current-time)))
16365 delta deltan deltaw deltadef year month day
16366 hour minute second wday pm h2 m2 tl wday1
16367 iso-year iso-weekday iso-week iso-date futurep kill-year)
16368 (setq org-read-date-analyze-futurep nil
16369 org-read-date-analyze-forced-year nil)
16370 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16371 (setq ans "+0"))
16373 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16374 (setq ans (replace-match "" t t ans)
16375 deltan (car delta)
16376 deltaw (nth 1 delta)
16377 deltadef (nth 2 delta)))
16379 ;; Check if there is an iso week date in there. If yes, store the
16380 ;; info and postpone interpreting it until the rest of the parsing
16381 ;; is done.
16382 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16383 (setq iso-year (when (match-end 1)
16384 (org-small-year-to-year
16385 (string-to-number (match-string 1 ans))))
16386 iso-weekday (when (match-end 3)
16387 (string-to-number (match-string 3 ans)))
16388 iso-week (string-to-number (match-string 2 ans)))
16389 (setq ans (replace-match "" t t ans)))
16391 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16392 (when (string-match
16393 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16394 (setq year (if (match-end 2)
16395 (string-to-number (match-string 2 ans))
16396 (progn (setq kill-year t)
16397 (string-to-number (format-time-string "%Y"))))
16398 month (string-to-number (match-string 3 ans))
16399 day (string-to-number (match-string 4 ans)))
16400 (setq year (org-small-year-to-year year))
16401 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16402 t nil ans)))
16404 ;; Help matching dotted european dates
16405 (when (string-match
16406 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16407 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16408 (setq kill-year t)
16409 (string-to-number (format-time-string "%Y")))
16410 day (string-to-number (match-string 1 ans))
16411 month (string-to-number (match-string 2 ans))
16412 ans (replace-match (format "%04d-%02d-%02d" year month day)
16413 t nil ans)))
16415 ;; Help matching american dates, like 5/30 or 5/30/7
16416 (when (string-match
16417 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16418 (setq year (if (match-end 4)
16419 (string-to-number (match-string 4 ans))
16420 (progn (setq kill-year t)
16421 (string-to-number (format-time-string "%Y"))))
16422 month (string-to-number (match-string 1 ans))
16423 day (string-to-number (match-string 2 ans)))
16424 (setq year (org-small-year-to-year year))
16425 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16426 t nil ans)))
16427 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16428 ;; If there is a time with am/pm, and *no* time without it, we convert
16429 ;; so that matching will be successful.
16430 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16431 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16432 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16433 (setq hour (string-to-number (match-string 1 ans))
16434 minute (if (match-end 3)
16435 (string-to-number (match-string 3 ans))
16437 pm (equal ?p
16438 (string-to-char (downcase (match-string 4 ans)))))
16439 (if (and (= hour 12) (not pm))
16440 (setq hour 0)
16441 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16442 (setq ans (replace-match (format "%02d:%02d" hour minute)
16443 t t ans))))
16445 ;; Check if a time range is given as a duration
16446 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16447 (setq hour (string-to-number (match-string 1 ans))
16448 h2 (+ hour (string-to-number (match-string 3 ans)))
16449 minute (string-to-number (match-string 2 ans))
16450 m2 (+ minute (if (match-end 5) (string-to-number
16451 (match-string 5 ans))0)))
16452 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16453 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16454 t t ans)))
16456 ;; Check if there is a time range
16457 (when (boundp 'org-end-time-was-given)
16458 (setq org-time-was-given nil)
16459 (when (and (string-match org-plain-time-of-day-regexp ans)
16460 (match-end 8))
16461 (setq org-end-time-was-given (match-string 8 ans))
16462 (setq ans (concat (substring ans 0 (match-beginning 7))
16463 (substring ans (match-end 7))))))
16465 (setq tl (parse-time-string ans)
16466 day (or (nth 3 tl) (nth 3 org-defdecode))
16467 month
16468 (cond ((nth 4 tl))
16469 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16470 ;; Day was specified. Make sure DAY+MONTH
16471 ;; combination happens in the future.
16472 ((nth 3 tl)
16473 (setq futurep t)
16474 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16475 (nth 4 nowdecode)))
16476 (t (nth 4 org-defdecode)))
16477 year
16478 (cond ((and (not kill-year) (nth 5 tl)))
16479 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16480 ;; Month was guessed in the future and is at least
16481 ;; equal to NOWDECODE's. Fix year accordingly.
16482 (futurep
16483 (if (or (> month (nth 4 nowdecode))
16484 (>= day (nth 3 nowdecode)))
16485 (nth 5 nowdecode)
16486 (1+ (nth 5 nowdecode))))
16487 ;; Month was specified. Make sure MONTH+YEAR
16488 ;; combination happens in the future.
16489 ((nth 4 tl)
16490 (setq futurep t)
16491 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16492 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16493 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16494 (t (nth 5 nowdecode))))
16495 (t (nth 5 org-defdecode)))
16496 hour (or (nth 2 tl) (nth 2 org-defdecode))
16497 minute (or (nth 1 tl) (nth 1 org-defdecode))
16498 second (or (nth 0 tl) 0)
16499 wday (nth 6 tl))
16501 (when (and (eq org-read-date-prefer-future 'time)
16502 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16503 (equal day (nth 3 nowdecode))
16504 (equal month (nth 4 nowdecode))
16505 (equal year (nth 5 nowdecode))
16506 (nth 2 tl)
16507 (or (< (nth 2 tl) (nth 2 nowdecode))
16508 (and (= (nth 2 tl) (nth 2 nowdecode))
16509 (nth 1 tl)
16510 (< (nth 1 tl) (nth 1 nowdecode)))))
16511 (setq day (1+ day)
16512 futurep t))
16514 ;; Special date definitions below
16515 (cond
16516 (iso-week
16517 ;; There was an iso week
16518 (require 'cal-iso)
16519 (setq futurep nil)
16520 (setq year (or iso-year year)
16521 day (or iso-weekday wday 1)
16522 wday nil ; to make sure that the trigger below does not match
16523 iso-date (calendar-gregorian-from-absolute
16524 (calendar-iso-to-absolute
16525 (list iso-week day year))))
16526 ; FIXME: Should we also push ISO weeks into the future?
16527 ; (when (and org-read-date-prefer-future
16528 ; (not iso-year)
16529 ; (< (calendar-absolute-from-gregorian iso-date)
16530 ; (time-to-days (current-time))))
16531 ; (setq year (1+ year)
16532 ; iso-date (calendar-gregorian-from-absolute
16533 ; (calendar-iso-to-absolute
16534 ; (list iso-week day year)))))
16535 (setq month (car iso-date)
16536 year (nth 2 iso-date)
16537 day (nth 1 iso-date)))
16538 (deltan
16539 (setq futurep nil)
16540 (unless deltadef
16541 ;; Pass `current-time' result to `decode-time' (instead of
16542 ;; calling without arguments) so that only `current-time' has
16543 ;; to be overridden in tests.
16544 (let ((now (decode-time (current-time))))
16545 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16546 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16547 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16548 ((equal deltaw "m") (setq month (+ month deltan)))
16549 ((equal deltaw "y") (setq year (+ year deltan)))))
16550 ((and wday (not (nth 3 tl)))
16551 ;; Weekday was given, but no day, so pick that day in the week
16552 ;; on or after the derived date.
16553 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16554 (unless (equal wday wday1)
16555 (setq day (+ day (% (- wday wday1 -7) 7))))))
16556 (when (and (boundp 'org-time-was-given)
16557 (nth 2 tl))
16558 (setq org-time-was-given t))
16559 (when (< year 100) (setq year (+ 2000 year)))
16560 ;; Check of the date is representable
16561 (if org-read-date-force-compatible-dates
16562 (progn
16563 (when (< year 1970)
16564 (setq year 1970 org-read-date-analyze-forced-year t))
16565 (when (> year 2037)
16566 (setq year 2037 org-read-date-analyze-forced-year t)))
16567 (condition-case nil
16568 (ignore (encode-time second minute hour day month year))
16569 (error
16570 (setq year (nth 5 org-defdecode))
16571 (setq org-read-date-analyze-forced-year t))))
16572 (setq org-read-date-analyze-futurep futurep)
16573 (list second minute hour day month year)))
16575 (defvar parse-time-weekdays)
16576 (defun org-read-date-get-relative (s today default)
16577 "Check string S for special relative date string.
16578 TODAY and DEFAULT are internal times, for today and for a default.
16579 Return shift list (N what def-flag)
16580 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16581 N is the number of WHATs to shift.
16582 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16583 the DEFAULT date rather than TODAY."
16584 (require 'parse-time)
16585 (when (and
16586 (string-match
16587 (concat
16588 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16589 "\\([0-9]+\\)?"
16590 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16591 "\\([ \t]\\|$\\)") s)
16592 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16593 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16594 (string-to-char (substring (match-string 1 s) -1))
16595 ?+))
16596 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16597 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16598 (what (if (match-end 3) (match-string 3 s) "d"))
16599 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16600 (date (if rel default today))
16601 (wday (nth 6 (decode-time date)))
16602 delta)
16603 (if wday1
16604 (progn
16605 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16606 (when (= delta 0) (setq delta 7))
16607 (when (= dir ?-)
16608 (setq delta (- delta 7))
16609 (when (= delta 0) (setq delta -7)))
16610 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16611 (list delta "d" rel))
16612 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16614 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16615 "Turn a user-specified date into the internal representation.
16616 The internal representation needed by the calendar is (month day year).
16617 This is a wrapper to handle the brain-dead convention in calendar that
16618 user function argument order change dependent on argument order."
16619 (pcase calendar-date-style
16620 (`american (list arg1 arg2 arg3))
16621 (`european (list arg2 arg1 arg3))
16622 (`iso (list arg2 arg3 arg1))))
16624 (defun org-eval-in-calendar (form &optional keepdate)
16625 "Eval FORM in the calendar window and return to current window.
16626 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16627 (let ((sf (selected-frame))
16628 (sw (selected-window)))
16629 (select-window (get-buffer-window "*Calendar*" t))
16630 (eval form)
16631 (when (and (not keepdate) (calendar-cursor-to-date))
16632 (let* ((date (calendar-cursor-to-date))
16633 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16634 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16635 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16636 (select-window sw)
16637 (select-frame-set-input-focus sf)))
16639 (defun org-calendar-select ()
16640 "Return to `org-read-date' with the date currently selected.
16641 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16642 (interactive)
16643 (when (calendar-cursor-to-date)
16644 (let* ((date (calendar-cursor-to-date))
16645 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16646 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16647 (when (active-minibuffer-window) (exit-minibuffer))))
16649 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16650 "Insert a date stamp for the date given by the internal TIME.
16651 See `format-time-string' for the format of TIME.
16652 WITH-HM means use the stamp format that includes the time of the day.
16653 INACTIVE means use square brackets instead of angular ones, so that the
16654 stamp will not contribute to the agenda.
16655 PRE and POST are optional strings to be inserted before and after the
16656 stamp.
16657 The command returns the inserted time stamp."
16658 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16659 stamp)
16660 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16661 (insert-before-markers (or pre ""))
16662 (when (listp extra)
16663 (setq extra (car extra))
16664 (if (and (stringp extra)
16665 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16666 (setq extra (format "-%02d:%02d"
16667 (string-to-number (match-string 1 extra))
16668 (string-to-number (match-string 2 extra))))
16669 (setq extra nil)))
16670 (when extra
16671 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16672 (insert-before-markers (setq stamp (format-time-string fmt time)))
16673 (insert-before-markers (or post ""))
16674 (setq org-last-inserted-timestamp stamp)))
16676 (defun org-toggle-time-stamp-overlays ()
16677 "Toggle the use of custom time stamp formats."
16678 (interactive)
16679 (setq org-display-custom-times (not org-display-custom-times))
16680 (unless org-display-custom-times
16681 (let ((p (point-min)) (bmp (buffer-modified-p)))
16682 (while (setq p (next-single-property-change p 'display))
16683 (when (and (get-text-property p 'display)
16684 (eq (get-text-property p 'face) 'org-date))
16685 (remove-text-properties
16686 p (setq p (next-single-property-change p 'display))
16687 '(display t))))
16688 (set-buffer-modified-p bmp)))
16689 (org-restart-font-lock)
16690 (setq org-table-may-need-update t)
16691 (if org-display-custom-times
16692 (message "Time stamps are overlaid with custom format")
16693 (message "Time stamp overlays removed")))
16695 (defun org-display-custom-time (beg end)
16696 "Overlay modified time stamp format over timestamp between BEG and END."
16697 (let* ((ts (buffer-substring beg end))
16698 t1 with-hm tf time str (off 0))
16699 (save-match-data
16700 (setq t1 (org-parse-time-string ts t))
16701 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16702 (setq off (- (match-end 0) (match-beginning 0)))))
16703 (setq end (- end off))
16704 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16705 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16706 time (org-fix-decoded-time t1)
16707 str (org-add-props
16708 (format-time-string
16709 (substring tf 1 -1) (apply 'encode-time time))
16710 nil 'mouse-face 'highlight))
16711 (put-text-property beg end 'display str)))
16713 (defun org-fix-decoded-time (time)
16714 "Set 0 instead of nil for the first 6 elements of time.
16715 Don't touch the rest."
16716 (let ((n 0))
16717 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16719 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16720 "Difference between TIMESTAMP-STRING and now in days.
16721 If SECONDS is non-nil, return the difference in seconds."
16722 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16723 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16724 (funcall fdiff (current-time)))))
16726 (defun org-deadline-close-p (timestamp-string &optional ndays)
16727 "Is the time in TIMESTAMP-STRING close to the current date?"
16728 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16729 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16730 (not (org-entry-is-done-p))))
16732 (defun org-get-wdays (ts &optional delay zero-delay)
16733 "Get the deadline lead time appropriate for timestring TS.
16734 When DELAY is non-nil, get the delay time for scheduled items
16735 instead of the deadline lead time. When ZERO-DELAY is non-nil
16736 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16737 don't try to find the delay cookie in the scheduled timestamp."
16738 (let ((tv (if delay org-scheduled-delay-days
16739 org-deadline-warning-days)))
16740 (cond
16741 ((or (and delay (< tv 0))
16742 (and delay zero-delay (<= tv 0))
16743 (and (not delay) (<= tv 0)))
16744 ;; Enforce this value no matter what
16745 (- tv))
16746 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16747 ;; lead time is specified.
16748 (floor (* (string-to-number (match-string 1 ts))
16749 (cdr (assoc (match-string 2 ts)
16750 '(("d" . 1) ("w" . 7)
16751 ("m" . 30.4) ("y" . 365.25)
16752 ("h" . 0.041667)))))))
16753 ;; go for the default.
16754 (t tv))))
16756 (defun org-calendar-select-mouse (ev)
16757 "Return to `org-read-date' with the date currently selected.
16758 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16759 (interactive "e")
16760 (mouse-set-point ev)
16761 (when (calendar-cursor-to-date)
16762 (let* ((date (calendar-cursor-to-date))
16763 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16764 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16765 (when (active-minibuffer-window) (exit-minibuffer))))
16767 (defun org-check-deadlines (ndays)
16768 "Check if there are any deadlines due or past due.
16769 A deadline is considered due if it happens within `org-deadline-warning-days'
16770 days from today's date. If the deadline appears in an entry marked DONE,
16771 it is not shown. A numeric prefix argument NDAYS can be used to test that
16772 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16773 are shown."
16774 (interactive "P")
16775 (let* ((org-warn-days
16776 (cond
16777 ((equal ndays '(4)) 100000)
16778 (ndays (prefix-numeric-value ndays))
16779 (t (abs org-deadline-warning-days))))
16780 (case-fold-search nil)
16781 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16782 (callback
16783 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16784 (message "%d deadlines past-due or due within %d days"
16785 (org-occur regexp nil callback)
16786 org-warn-days)))
16788 (defsubst org-re-timestamp (type)
16789 "Return a regexp for timestamp TYPE.
16790 Allowed values for TYPE are:
16792 all: all timestamps
16793 active: only active timestamps (<...>)
16794 inactive: only inactive timestamps ([...])
16795 scheduled: only scheduled timestamps
16796 deadline: only deadline timestamps
16797 closed: only closed time-stamps
16799 When TYPE is nil, fall back on returning a regexp that matches
16800 both scheduled and deadline timestamps."
16801 (cl-case type
16802 (all org-ts-regexp-both)
16803 (active org-ts-regexp)
16804 (inactive org-ts-regexp-inactive)
16805 (scheduled org-scheduled-time-regexp)
16806 (deadline org-deadline-time-regexp)
16807 (closed org-closed-time-regexp)
16808 (otherwise
16809 (concat "\\<"
16810 (regexp-opt (list org-deadline-string org-scheduled-string))
16811 " *<\\([^>]+\\)>"))))
16813 (defun org-check-before-date (d)
16814 "Check if there are deadlines or scheduled entries before date D."
16815 (interactive (list (org-read-date)))
16816 (let* ((case-fold-search nil)
16817 (regexp (org-re-timestamp org-ts-type))
16818 (ts-type org-ts-type)
16819 (callback
16820 (lambda ()
16821 (let ((match (match-string 1)))
16822 (and (if (memq ts-type '(active inactive all))
16823 (eq (org-element-type (save-excursion
16824 (backward-char)
16825 (org-element-context)))
16826 'timestamp)
16827 (org-at-planning-p))
16828 (time-less-p
16829 (org-time-string-to-time match)
16830 (org-time-string-to-time d)))))))
16831 (message "%d entries before %s"
16832 (org-occur regexp nil callback)
16833 d)))
16835 (defun org-check-after-date (d)
16836 "Check if there are deadlines or scheduled entries after date D."
16837 (interactive (list (org-read-date)))
16838 (let* ((case-fold-search nil)
16839 (regexp (org-re-timestamp org-ts-type))
16840 (ts-type org-ts-type)
16841 (callback
16842 (lambda ()
16843 (let ((match (match-string 1)))
16844 (and (if (memq ts-type '(active inactive all))
16845 (eq (org-element-type (save-excursion
16846 (backward-char)
16847 (org-element-context)))
16848 'timestamp)
16849 (org-at-planning-p))
16850 (not (time-less-p
16851 (org-time-string-to-time match)
16852 (org-time-string-to-time d))))))))
16853 (message "%d entries after %s"
16854 (org-occur regexp nil callback)
16855 d)))
16857 (defun org-check-dates-range (start-date end-date)
16858 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16859 (interactive (list (org-read-date nil nil nil "Range starts")
16860 (org-read-date nil nil nil "Range end")))
16861 (let ((case-fold-search nil)
16862 (regexp (org-re-timestamp org-ts-type))
16863 (callback
16864 (let ((type org-ts-type))
16865 (lambda ()
16866 (let ((match (match-string 1)))
16867 (and
16868 (if (memq type '(active inactive all))
16869 (eq (org-element-type (save-excursion
16870 (backward-char)
16871 (org-element-context)))
16872 'timestamp)
16873 (org-at-planning-p))
16874 (not (time-less-p
16875 (org-time-string-to-time match)
16876 (org-time-string-to-time start-date)))
16877 (time-less-p
16878 (org-time-string-to-time match)
16879 (org-time-string-to-time end-date))))))))
16880 (message "%d entries between %s and %s"
16881 (org-occur regexp nil callback) start-date end-date)))
16883 (defun org-evaluate-time-range (&optional to-buffer)
16884 "Evaluate a time range by computing the difference between start and end.
16885 Normally the result is just printed in the echo area, but with prefix arg
16886 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16887 If the time range is actually in a table, the result is inserted into the
16888 next column.
16889 For time difference computation, a year is assumed to be exactly 365
16890 days in order to avoid rounding problems."
16891 (interactive "P")
16893 (org-clock-update-time-maybe)
16894 (save-excursion
16895 (unless (org-at-date-range-p t)
16896 (goto-char (point-at-bol))
16897 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16898 (unless (org-at-date-range-p t)
16899 (user-error "Not at a time-stamp range, and none found in current line")))
16900 (let* ((ts1 (match-string 1))
16901 (ts2 (match-string 2))
16902 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16903 (match-end (match-end 0))
16904 (time1 (org-time-string-to-time ts1))
16905 (time2 (org-time-string-to-time ts2))
16906 (t1 (float-time time1))
16907 (t2 (float-time time2))
16908 (diff (abs (- t2 t1)))
16909 (negative (< (- t2 t1) 0))
16910 ;; (ys (floor (* 365 24 60 60)))
16911 (ds (* 24 60 60))
16912 (hs (* 60 60))
16913 (fy "%dy %dd %02d:%02d")
16914 (fy1 "%dy %dd")
16915 (fd "%dd %02d:%02d")
16916 (fd1 "%dd")
16917 (fh "%02d:%02d")
16918 y d h m align)
16919 (if havetime
16920 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16922 d (floor (/ diff ds)) diff (mod diff ds)
16923 h (floor (/ diff hs)) diff (mod diff hs)
16924 m (floor (/ diff 60)))
16925 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16927 d (floor (+ (/ diff ds) 0.5))
16928 h 0 m 0))
16929 (if (not to-buffer)
16930 (message "%s" (org-make-tdiff-string y d h m))
16931 (if (org-at-table-p)
16932 (progn
16933 (goto-char match-end)
16934 (setq align t)
16935 (and (looking-at " *|") (goto-char (match-end 0))))
16936 (goto-char match-end))
16937 (when (looking-at
16938 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16939 (replace-match ""))
16940 (when negative (insert " -"))
16941 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16942 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16943 (insert " " (format fh h m))))
16944 (when align (org-table-align))
16945 (message "Time difference inserted")))))
16947 (defun org-make-tdiff-string (y d h m)
16948 (let ((fmt "")
16949 (l nil))
16950 (when (> y 0)
16951 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16952 (push y l))
16953 (when (> d 0)
16954 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16955 (push d l))
16956 (when (> h 0)
16957 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16958 (push h l))
16959 (when (> m 0)
16960 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16961 (push m l))
16962 (apply 'format fmt (nreverse l))))
16964 (defun org-time-string-to-time (s)
16965 "Convert timestamp string S into internal time."
16966 (apply #'encode-time (org-parse-time-string s)))
16968 (defun org-time-string-to-seconds (s)
16969 "Convert a timestamp string S into a number of seconds."
16970 (float-time (org-time-string-to-time s)))
16972 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
16974 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
16975 "Convert time stamp S to an absolute day number.
16977 If DAYNR in non-nil, and there is a specifier for a cyclic time
16978 stamp, get the closest date to DAYNR. If PREFER is
16979 `past' (respectively `future') return a date past (respectively
16980 after) or equal to DAYNR.
16982 POS is the location of time stamp S, as a buffer position in
16983 BUFFER.
16985 Diary sexp timestamps are matched against DAYNR, when non-nil.
16986 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
16987 signaled."
16988 (cond
16989 ((string-match "\\`%%\\((.*)\\)" s)
16990 ;; Sexp timestamp: try to match DAYNR, if available, since we're
16991 ;; only able to match individual dates. If it fails, raise an
16992 ;; error.
16993 (if (and daynr
16994 (org-diary-sexp-entry
16995 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
16996 daynr
16997 (signal 'org-diary-sexp-no-match (list s))))
16998 (daynr (org-closest-date s daynr prefer))
16999 (t (time-to-days
17000 (condition-case errdata
17001 (apply #'encode-time (org-parse-time-string s))
17002 (error (error "Bad timestamp `%s'%s\nError was: %s"
17004 (if (not (and buffer pos)) ""
17005 (format-message " at %d in buffer `%s'" pos buffer))
17006 (cdr errdata))))))))
17008 (defun org-days-to-iso-week (days)
17009 "Return the iso week number."
17010 (require 'cal-iso)
17011 (car (calendar-iso-from-absolute days)))
17013 (defun org-small-year-to-year (year)
17014 "Convert 2-digit years into 4-digit years.
17015 YEAR is expanded into one of the 30 next years, if possible, or
17016 into a past one. Any year larger than 99 is returned unchanged."
17017 (if (>= year 100) year
17018 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17019 (century (/ current 100))
17020 (offset (- year (% current 100))))
17021 (cond ((> offset 30) (+ (* (1- century) 100) year))
17022 ((> offset -70) (+ (* century 100) year))
17023 (t (+ (* (1+ century) 100) year))))))
17025 (defun org-time-from-absolute (d)
17026 "Return the time corresponding to date D.
17027 D may be an absolute day number, or a calendar-type list (month day year)."
17028 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17029 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17031 (defvar org-agenda-current-date)
17032 (defun org-calendar-holiday ()
17033 "List of holidays, for Diary display in Org mode."
17034 (require 'holidays)
17035 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17036 (and hl (mapconcat #'identity hl "; "))))
17038 (defun org-diary-sexp-entry (sexp entry d)
17039 "Process a SEXP diary ENTRY for date D."
17040 (require 'diary-lib)
17041 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17042 ;; dynamically.
17043 (let* ((sexp `(let ((entry ,entry)
17044 (date ',d))
17045 ,(car (read-from-string sexp))))
17046 (result (if calendar-debug-sexp (eval sexp)
17047 (condition-case nil
17048 (eval sexp)
17049 (error
17050 (beep)
17051 (message "Bad sexp at line %d in %s: %s"
17052 (org-current-line)
17053 (buffer-file-name) sexp)
17054 (sleep-for 2))))))
17055 (cond ((stringp result) (split-string result "; "))
17056 ((and (consp result)
17057 (not (consp (cdr result)))
17058 (stringp (cdr result))) (cdr result))
17059 ((and (consp result)
17060 (stringp (car result))) result)
17061 (result entry))))
17063 (defun org-diary-to-ical-string (frombuf)
17064 "Get iCalendar entries from diary entries in buffer FROMBUF.
17065 This uses the icalendar.el library."
17066 (let* ((tmpdir temporary-file-directory)
17067 (tmpfile (make-temp-name
17068 (expand-file-name "orgics" tmpdir)))
17069 buf rtn b e)
17070 (with-current-buffer frombuf
17071 (icalendar-export-region (point-min) (point-max) tmpfile)
17072 (setq buf (find-buffer-visiting tmpfile))
17073 (set-buffer buf)
17074 (goto-char (point-min))
17075 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17076 (setq b (match-beginning 0)))
17077 (goto-char (point-max))
17078 (when (re-search-backward "^END:VEVENT" nil t)
17079 (setq e (match-end 0)))
17080 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17081 (kill-buffer buf)
17082 (delete-file tmpfile)
17083 rtn))
17085 (defun org-closest-date (start current prefer)
17086 "Return closest date to CURRENT starting from START.
17088 CURRENT and START are both time stamps.
17090 When PREFER is `past', return a date that is either CURRENT or
17091 past. When PREFER is `future', return a date that is either
17092 CURRENT or future.
17094 Only time stamps with a repeater are modified. Any other time
17095 stamp stay unchanged. In any case, return value is an absolute
17096 day number."
17097 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17098 ;; No repeater. Do not shift time stamp.
17099 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17100 (let ((value (string-to-number (match-string 1 start)))
17101 (type (match-string 2 start)))
17102 (if (= 0 value)
17103 ;; Repeater with a 0-value is considered as void.
17104 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17105 (let* ((base (org-date-to-gregorian start))
17106 (target (org-date-to-gregorian current))
17107 (sday (calendar-absolute-from-gregorian base))
17108 (cday (calendar-absolute-from-gregorian target))
17109 n1 n2)
17110 ;; If START is already past CURRENT, just return START.
17111 (if (<= cday sday) sday
17112 ;; Compute closest date before (N1) and closest date past
17113 ;; (N2) CURRENT.
17114 (pcase type
17115 ("h"
17116 (let ((missing-hours
17117 (mod (+ (- (* 24 (- cday sday))
17118 (nth 2 (org-parse-time-string start)))
17119 org-extend-today-until)
17120 value)))
17121 (setf n1 (if (= missing-hours 0) cday
17122 (- cday (1+ (/ missing-hours 24)))))
17123 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17124 ((or "d" "w")
17125 (let ((value (if (equal type "w") (* 7 value) value)))
17126 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17127 (setf n2 (+ n1 value))))
17128 ("m"
17129 (let* ((add-months
17130 (lambda (d n)
17131 ;; Add N months to gregorian date D, i.e.,
17132 ;; a list (MONTH DAY YEAR). Return a valid
17133 ;; gregorian date.
17134 (let ((m (+ (nth 0 d) n)))
17135 (list (mod m 12)
17136 (nth 1 d)
17137 (+ (/ m 12) (nth 2 d))))))
17138 (months ; Complete months to TARGET.
17139 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17140 (- (nth 0 target) (nth 0 base))
17141 ;; If START's day is greater than
17142 ;; TARGET's, remove incomplete month.
17143 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17144 value)
17145 value))
17146 (before (funcall add-months base months)))
17147 (setf n1 (calendar-absolute-from-gregorian before))
17148 (setf n2
17149 (calendar-absolute-from-gregorian
17150 (funcall add-months before value)))))
17152 (let* ((d (nth 1 base))
17153 (m (nth 0 base))
17154 (y (nth 2 base))
17155 (years ; Complete years to TARGET.
17156 (* (/ (- (nth 2 target)
17158 ;; If START's month and day are
17159 ;; greater than TARGET's, remove
17160 ;; incomplete year.
17161 (if (or (> (nth 0 target) m)
17162 (and (= (nth 0 target) m)
17163 (> (nth 1 target) d)))
17166 value)
17167 value))
17168 (before (list m d (+ y years))))
17169 (setf n1 (calendar-absolute-from-gregorian before))
17170 (setf n2 (calendar-absolute-from-gregorian
17171 (list m d (+ (nth 2 before) value)))))))
17172 ;; Handle PREFER parameter, if any.
17173 (cond
17174 ((eq prefer 'past) (if (= cday n2) n2 n1))
17175 ((eq prefer 'future) (if (= cday n1) n1 n2))
17176 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17178 (defun org-date-to-gregorian (d)
17179 "Turn any specification of date D into a Gregorian date for the calendar."
17180 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17181 ((and (listp d) (= (length d) 3)) d)
17182 ((stringp d)
17183 (let ((d (org-parse-time-string d)))
17184 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17185 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17187 (defun org-timestamp-up (&optional arg)
17188 "Increase the date item at the cursor by one.
17189 If the cursor is on the year, change the year. If it is on the month,
17190 the day or the time, change that. If the cursor is on the enclosing
17191 bracket, change the timestamp type.
17192 With prefix ARG, change by that many units."
17193 (interactive "p")
17194 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17196 (defun org-timestamp-down (&optional arg)
17197 "Decrease the date item at the cursor by one.
17198 If the cursor is on the year, change the year. If it is on the month,
17199 the day or the time, change that. If the cursor is on the enclosing
17200 bracket, change the timestamp type.
17201 With prefix ARG, change by that many units."
17202 (interactive "p")
17203 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17205 (defun org-timestamp-up-day (&optional arg)
17206 "Increase the date in the time stamp by one day.
17207 With prefix ARG, change that many days."
17208 (interactive "p")
17209 (if (and (not (org-at-timestamp-p 'lax))
17210 (org-at-heading-p))
17211 (org-todo 'up)
17212 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17214 (defun org-timestamp-down-day (&optional arg)
17215 "Decrease the date in the time stamp by one day.
17216 With prefix ARG, change that many days."
17217 (interactive "p")
17218 (if (and (not (org-at-timestamp-p 'lax))
17219 (org-at-heading-p))
17220 (org-todo 'down)
17221 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17223 (defun org-at-timestamp-p (&optional extended)
17224 "Non-nil if point is inside a timestamp.
17226 By default, the function only consider syntactically valid active
17227 timestamps. However, the caller may have a broader definition
17228 for timestamps. As a consequence, optional argument EXTENDED can
17229 be set to the following values
17231 `inactive'
17233 Include also syntactically valid inactive timestamps.
17235 `agenda'
17237 Include timestamps allowed in Agenda, i.e., those in
17238 properties drawers, planning lines and clock lines.
17240 `lax'
17242 Ignore context. The function matches any part of the
17243 document looking like a timestamp. This includes comments,
17244 example blocks...
17246 For backward-compatibility with Org 9.0, every other non-nil
17247 value is equivalent to `inactive'.
17249 When at a timestamp, return the position of the point as a symbol
17250 among `bracket', `after', `year', `month', `hour', `minute',
17251 `day' or a number of character from the last know part of the
17252 time stamp.
17254 When matching, the match groups are the following:
17255 group 1: year
17256 group 2: month
17257 group 3: day number
17258 group 4: day name
17259 group 5: hours, if any
17260 group 6: minutes, if any"
17261 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17262 (pos (point))
17263 (match?
17264 (let ((boundaries (org-in-regexp regexp)))
17265 (save-match-data
17266 (cond ((null boundaries) nil)
17267 ((eq extended 'lax) t)
17269 (or (and (eq extended 'agenda)
17270 (or (org-at-planning-p)
17271 (org-at-property-p)
17272 (and (bound-and-true-p
17273 org-agenda-include-inactive-timestamps)
17274 (org-at-clock-log-p))))
17275 (eq 'timestamp
17276 (save-excursion
17277 (when (= pos (cdr boundaries)) (forward-char -1))
17278 (org-element-type (org-element-context)))))))))))
17279 (cond
17280 ((not match?) nil)
17281 ((= pos (match-beginning 0)) 'bracket)
17282 ;; Distinguish location right before the closing bracket from
17283 ;; right after it.
17284 ((= pos (1- (match-end 0))) 'bracket)
17285 ((= pos (match-end 0)) 'after)
17286 ((org-pos-in-match-range pos 2) 'year)
17287 ((org-pos-in-match-range pos 3) 'month)
17288 ((org-pos-in-match-range pos 7) 'hour)
17289 ((org-pos-in-match-range pos 8) 'minute)
17290 ((or (org-pos-in-match-range pos 4)
17291 (org-pos-in-match-range pos 5)) 'day)
17292 ((and (> pos (or (match-end 8) (match-end 5)))
17293 (< pos (match-end 0)))
17294 (- pos (or (match-end 8) (match-end 5))))
17295 (t 'day))))
17297 (defun org-toggle-timestamp-type ()
17298 "Toggle the type (<active> or [inactive]) of a time stamp."
17299 (interactive)
17300 (when (org-at-timestamp-p 'lax)
17301 (let ((beg (match-beginning 0)) (end (match-end 0))
17302 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17303 (save-excursion
17304 (goto-char beg)
17305 (while (re-search-forward "[][<>]" end t)
17306 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17307 t t)))
17308 (message "Timestamp is now %sactive"
17309 (if (equal (char-after beg) ?<) "" "in")))))
17311 (defun org-at-clock-log-p ()
17312 "Non-nil if point is on a clock log line."
17313 (and (org-match-line org-clock-line-re)
17314 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17316 (defvar org-clock-history) ; defined in org-clock.el
17317 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17318 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17319 "Change the date in the time stamp at point.
17320 The date will be changed by N times WHAT. WHAT can be `day', `month',
17321 `year', `minute', `second'. If WHAT is not given, the cursor position
17322 in the timestamp determines what will be changed.
17323 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17324 (let ((origin (point))
17325 (timestamp? (org-at-timestamp-p 'lax))
17326 origin-cat
17327 with-hm inactive
17328 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17329 extra rem
17330 ts time time0 fixnext clrgx)
17331 (unless timestamp? (user-error "Not at a timestamp"))
17332 (if (and (not what) (eq timestamp? 'bracket))
17333 (org-toggle-timestamp-type)
17334 ;; Point isn't on brackets. Remember the part of the time-stamp
17335 ;; the point was in. Indeed, size of time-stamps may change,
17336 ;; but point must be kept in the same category nonetheless.
17337 (setq origin-cat timestamp?)
17338 (when (and (not what) (not (eq timestamp? 'day))
17339 org-display-custom-times
17340 (get-text-property (point) 'display)
17341 (not (get-text-property (1- (point)) 'display)))
17342 (setq timestamp? 'day))
17343 (setq timestamp? (or what timestamp?)
17344 inactive (= (char-after (match-beginning 0)) ?\[)
17345 ts (match-string 0))
17346 (replace-match "")
17347 (when (string-match
17348 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17350 (setq extra (match-string 1 ts))
17351 (when suppress-tmp-delay
17352 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17353 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17354 (setq with-hm t))
17355 (setq time0 (org-parse-time-string ts))
17356 (when (and updown
17357 (eq timestamp? 'minute)
17358 (not current-prefix-arg))
17359 ;; This looks like s-up and s-down. Change by one rounding step.
17360 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17361 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17362 (setcar (cdr time0) (+ (nth 1 time0)
17363 (if (> n 0) (- rem) (- dm rem))))))
17364 (setq time
17365 (apply #'encode-time
17366 (or (car time0) 0)
17367 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17368 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17369 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17370 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17371 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17372 (nthcdr 6 time0)))
17373 (when (and (memq timestamp? '(hour minute))
17374 extra
17375 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17376 (setq extra (org-modify-ts-extra
17377 extra
17378 (if (eq timestamp? 'hour) 2 5)
17379 n dm)))
17380 (when (integerp timestamp?)
17381 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17382 (when (eq what 'calendar)
17383 (let ((cal-date (org-get-date-from-calendar)))
17384 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17385 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17386 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17387 (setcar time0 (or (car time0) 0))
17388 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17389 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17390 (setq time (apply 'encode-time time0))))
17391 ;; Insert the new time-stamp, and ensure point stays in the same
17392 ;; category as before (i.e. not after the last position in that
17393 ;; category).
17394 (let ((pos (point)))
17395 ;; Stay before inserted string. `save-excursion' is of no use.
17396 (setq org-last-changed-timestamp
17397 (org-insert-time-stamp time with-hm inactive nil nil extra))
17398 (goto-char pos))
17399 (save-match-data
17400 (looking-at org-ts-regexp3)
17401 (goto-char
17402 (pcase origin-cat
17403 ;; `day' category ends before `hour' if any, or at the end
17404 ;; of the day name.
17405 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17406 (`hour (min (match-end 7) origin))
17407 (`minute (min (1- (match-end 8)) origin))
17408 ((pred integerp) (min (1- (match-end 0)) origin))
17409 ;; Point was right after the time-stamp. However, the
17410 ;; time-stamp length might have changed, so refer to
17411 ;; (match-end 0) instead.
17412 (`after (match-end 0))
17413 ;; `year' and `month' have both fixed size: point couldn't
17414 ;; have moved into another part.
17415 (_ origin))))
17416 ;; Update clock if on a CLOCK line.
17417 (org-clock-update-time-maybe)
17418 ;; Maybe adjust the closest clock in `org-clock-history'
17419 (when org-clock-adjust-closest
17420 (if (not (and (org-at-clock-log-p)
17421 (< 1 (length (delq nil (mapcar 'marker-position
17422 org-clock-history))))))
17423 (message "No clock to adjust")
17424 (cond ((save-excursion ; fix previous clock?
17425 (re-search-backward org-ts-regexp0 nil t)
17426 (looking-back (concat org-clock-string " \\[")
17427 (line-beginning-position)))
17428 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17429 ((save-excursion ; fix next clock?
17430 (re-search-backward org-ts-regexp0 nil t)
17431 (looking-at (concat org-ts-regexp0 "\\] =>")))
17432 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17433 (save-window-excursion
17434 ;; Find closest clock to point, adjust the previous/next one in history
17435 (let* ((p (save-excursion (org-back-to-heading t)))
17436 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17437 (clfixnth
17438 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17439 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17440 (if (not clfixpos)
17441 (message "No clock to adjust")
17442 (save-excursion
17443 (org-goto-marker-or-bmk clfixpos)
17444 (org-show-subtree)
17445 (when (re-search-forward clrgx nil t)
17446 (goto-char (match-beginning 1))
17447 (let (org-clock-adjust-closest)
17448 (org-timestamp-change n timestamp? updown))
17449 (message "Clock adjusted in %s for heading: %s"
17450 (file-name-nondirectory (buffer-file-name))
17451 (org-get-heading t t)))))))))
17452 ;; Try to recenter the calendar window, if any.
17453 (when (and org-calendar-follow-timestamp-change
17454 (get-buffer-window "*Calendar*" t)
17455 (memq timestamp? '(day month year)))
17456 (org-recenter-calendar (time-to-days time))))))
17458 (defun org-modify-ts-extra (s pos n dm)
17459 "Change the different parts of the lead-time and repeat fields in timestamp."
17460 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17461 ng h m new rem)
17462 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17463 (cond
17464 ((or (org-pos-in-match-range pos 2)
17465 (org-pos-in-match-range pos 3))
17466 (setq m (string-to-number (match-string 3 s))
17467 h (string-to-number (match-string 2 s)))
17468 (if (org-pos-in-match-range pos 2)
17469 (setq h (+ h n))
17470 (setq n (* dm (with-no-warnings (signum n))))
17471 (unless (= 0 (setq rem (% m dm)))
17472 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17473 (setq m (+ m n)))
17474 (when (< m 0) (setq m (+ m 60) h (1- h)))
17475 (when (> m 59) (setq m (- m 60) h (1+ h)))
17476 (setq h (mod h 24))
17477 (setq ng 1 new (format "-%02d:%02d" h m)))
17478 ((org-pos-in-match-range pos 6)
17479 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17480 ((org-pos-in-match-range pos 5)
17481 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17483 ((org-pos-in-match-range pos 9)
17484 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17485 ((org-pos-in-match-range pos 8)
17486 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17488 (when ng
17489 (setq s (concat
17490 (substring s 0 (match-beginning ng))
17492 (substring s (match-end ng))))))
17495 (defun org-recenter-calendar (d)
17496 "If the calendar is visible, recenter it to date D."
17497 (let ((cwin (get-buffer-window "*Calendar*" t)))
17498 (when cwin
17499 (let ((calendar-move-hook nil))
17500 (with-selected-window cwin
17501 (calendar-goto-date
17502 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17504 (defun org-goto-calendar (&optional arg)
17505 "Go to the Emacs calendar at the current date.
17506 If there is a time stamp in the current line, go to that date.
17507 A prefix ARG can be used to force the current date."
17508 (interactive "P")
17509 (let ((calendar-move-hook nil)
17510 (calendar-view-holidays-initially-flag nil)
17511 (calendar-view-diary-initially-flag nil)
17512 diff)
17513 (when (or (org-at-timestamp-p 'lax)
17514 (org-match-line (concat ".*" org-ts-regexp)))
17515 (let ((d1 (time-to-days (current-time)))
17516 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17517 (setq diff (- d2 d1))))
17518 (calendar)
17519 (calendar-goto-today)
17520 (when (and diff (not arg)) (calendar-forward-day diff))))
17522 (defun org-get-date-from-calendar ()
17523 "Return a list (month day year) of date at point in calendar."
17524 (with-current-buffer "*Calendar*"
17525 (save-match-data
17526 (calendar-cursor-to-date))))
17528 (defun org-date-from-calendar ()
17529 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17530 If there is already a time stamp at the cursor position, update it."
17531 (interactive)
17532 (if (org-at-timestamp-p 'lax)
17533 (org-timestamp-change 0 'calendar)
17534 (let ((cal-date (org-get-date-from-calendar)))
17535 (org-insert-time-stamp
17536 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17538 (defcustom org-effort-durations
17539 `(("min" . 1)
17540 ("h" . 60)
17541 ("d" . ,(* 60 8))
17542 ("w" . ,(* 60 8 5))
17543 ("m" . ,(* 60 8 5 4))
17544 ("y" . ,(* 60 8 5 40)))
17545 "Conversion factor to minutes for an effort modifier.
17547 Each entry has the form (MODIFIER . MINUTES).
17549 In an effort string, a number followed by MODIFIER is multiplied
17550 by the specified number of MINUTES to obtain an effort in
17551 minutes.
17553 For example, if the value of this variable is ((\"hours\" . 60)), then an
17554 effort string \"2hours\" is equivalent to 120 minutes."
17555 :group 'org-agenda
17556 :version "26.1"
17557 :package-version '(Org . "8.3")
17558 :type '(alist :key-type (string :tag "Modifier")
17559 :value-type (number :tag "Minutes")))
17561 (defcustom org-image-actual-width t
17562 "Should we use the actual width of images when inlining them?
17564 When set to t, always use the image width.
17566 When set to a number, use imagemagick (when available) to set
17567 the image's width to this value.
17569 When set to a number in a list, try to get the width from any
17570 #+ATTR.* keyword if it matches a width specification like
17572 #+ATTR_HTML: :width 300px
17574 and fall back on that number if none is found.
17576 When set to nil, try to get the width from an #+ATTR.* keyword
17577 and fall back on the original width if none is found.
17579 This requires Emacs >= 24.1, build with imagemagick support."
17580 :group 'org-appearance
17581 :version "24.4"
17582 :package-version '(Org . "8.0")
17583 :type '(choice
17584 (const :tag "Use the image width" t)
17585 (integer :tag "Use a number of pixels")
17586 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17587 (const :tag "Use #+ATTR* or don't resize" nil)))
17589 (defcustom org-agenda-inhibit-startup nil
17590 "Inhibit startup when preparing agenda buffers.
17591 When this variable is t, the initialization of the Org agenda
17592 buffers is inhibited: e.g. the visibility state is not set, the
17593 tables are not re-aligned, etc."
17594 :type 'boolean
17595 :version "24.3"
17596 :group 'org-agenda)
17598 (defcustom org-agenda-ignore-properties nil
17599 "Avoid updating text properties when building the agenda.
17600 Properties are used to prepare buffers for effort estimates,
17601 appointments, statistics and subtree-local categories.
17602 If you don't use these in the agenda, you can add them to this
17603 list and agenda building will be a bit faster.
17604 The value is a list, with zero or more of the symbols `effort', `appt',
17605 `stats' or `category'."
17606 :type '(set :greedy t
17607 (const effort)
17608 (const appt)
17609 (const stats)
17610 (const category))
17611 :version "26.1"
17612 :package-version '(Org . "8.3")
17613 :group 'org-agenda)
17615 ;;;; Files
17617 (defun org-save-all-org-buffers ()
17618 "Save all Org buffers without user confirmation."
17619 (interactive)
17620 (message "Saving all Org buffers...")
17621 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17622 (when (featurep 'org-id) (org-id-locations-save))
17623 (message "Saving all Org buffers... done"))
17625 (defun org-revert-all-org-buffers ()
17626 "Revert all Org buffers.
17627 Prompt for confirmation when there are unsaved changes.
17628 Be sure you know what you are doing before letting this function
17629 overwrite your changes.
17631 This function is useful in a setup where one tracks Org files
17632 with a version control system, to revert on one machine after pulling
17633 changes from another. I believe the procedure must be like this:
17635 1. M-x org-save-all-org-buffers
17636 2. Pull changes from the other machine, resolve conflicts
17637 3. M-x org-revert-all-org-buffers"
17638 (interactive)
17639 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17640 (user-error "Abort"))
17641 (save-excursion
17642 (save-window-excursion
17643 (dolist (b (buffer-list))
17644 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17645 (with-current-buffer b buffer-file-name))
17646 (pop-to-buffer-same-window b)
17647 (revert-buffer t 'no-confirm)))
17648 (when (and (featurep 'org-id) org-id-track-globally)
17649 (org-id-locations-load)))))
17651 ;;;; Agenda files
17653 ;;;###autoload
17654 (defun org-switchb (&optional arg)
17655 "Switch between Org buffers.
17657 With `\\[universal-argument]' prefix, restrict available buffers to files.
17659 With `\\[universal-argument] \\[universal-argument]' \
17660 prefix, restrict available buffers to agenda files."
17661 (interactive "P")
17662 (let ((blist (org-buffer-list
17663 (cond ((equal arg '(4)) 'files)
17664 ((equal arg '(16)) 'agenda)))))
17665 (pop-to-buffer-same-window
17666 (completing-read "Org buffer: "
17667 (mapcar #'list (mapcar #'buffer-name blist))
17668 nil t))))
17670 (defun org-buffer-list (&optional predicate exclude-tmp)
17671 "Return a list of Org buffers.
17672 PREDICATE can be `export', `files' or `agenda'.
17674 export restrict the list to Export buffers.
17675 files restrict the list to buffers visiting Org files.
17676 agenda restrict the list to buffers visiting agenda files.
17678 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17679 (let* ((bfn nil)
17680 (agenda-files (and (eq predicate 'agenda)
17681 (mapcar 'file-truename (org-agenda-files t))))
17682 (filter
17683 (cond
17684 ((eq predicate 'files)
17685 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17686 ((eq predicate 'export)
17687 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17688 ((eq predicate 'agenda)
17689 (lambda (b)
17690 (with-current-buffer b
17691 (and (derived-mode-p 'org-mode)
17692 (setq bfn (buffer-file-name b))
17693 (member (file-truename bfn) agenda-files)))))
17694 (t (lambda (b) (with-current-buffer b
17695 (or (derived-mode-p 'org-mode)
17696 (string-match "\\*Org .*Export"
17697 (buffer-name b)))))))))
17698 (delq nil
17699 (mapcar
17700 (lambda(b)
17701 (if (and (funcall filter b)
17702 (or (not exclude-tmp)
17703 (not (string-match "tmp" (buffer-name b)))))
17705 nil))
17706 (buffer-list)))))
17708 (defun org-agenda-files (&optional unrestricted archives)
17709 "Get the list of agenda files.
17710 Optional UNRESTRICTED means return the full list even if a restriction
17711 is currently in place.
17712 When ARCHIVES is t, include all archive files that are really being
17713 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17714 `org-agenda-archives-mode' is t."
17715 (let ((files
17716 (cond
17717 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17718 ((stringp org-agenda-files) (org-read-agenda-file-list))
17719 ((listp org-agenda-files) org-agenda-files)
17720 (t (error "Invalid value of `org-agenda-files'")))))
17721 (setq files (apply 'append
17722 (mapcar (lambda (f)
17723 (if (file-directory-p f)
17724 (directory-files
17725 f t org-agenda-file-regexp)
17726 (list f)))
17727 files)))
17728 (when org-agenda-skip-unavailable-files
17729 (setq files (delq nil
17730 (mapcar (function
17731 (lambda (file)
17732 (and (file-readable-p file) file)))
17733 files))))
17734 (when (or (eq archives t)
17735 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17736 (setq files (org-add-archive-files files)))
17737 files))
17739 (defun org-agenda-file-p (&optional file)
17740 "Return non-nil, if FILE is an agenda file.
17741 If FILE is omitted, use the file associated with the current
17742 buffer."
17743 (let ((fname (or file (buffer-file-name))))
17744 (and fname
17745 (member (file-truename fname)
17746 (mapcar #'file-truename (org-agenda-files t))))))
17748 (defun org-edit-agenda-file-list ()
17749 "Edit the list of agenda files.
17750 Depending on setup, this either uses customize to edit the variable
17751 `org-agenda-files', or it visits the file that is holding the list. In the
17752 latter case, the buffer is set up in a way that saving it automatically kills
17753 the buffer and restores the previous window configuration."
17754 (interactive)
17755 (if (stringp org-agenda-files)
17756 (let ((cw (current-window-configuration)))
17757 (find-file org-agenda-files)
17758 (setq-local org-window-configuration cw)
17759 (add-hook 'after-save-hook
17760 (lambda ()
17761 (set-window-configuration
17762 (prog1 org-window-configuration
17763 (kill-buffer (current-buffer))))
17764 (org-install-agenda-files-menu)
17765 (message "New agenda file list installed"))
17766 nil 'local)
17767 (message "%s" (substitute-command-keys
17768 "Edit list and finish with \\[save-buffer]")))
17769 (customize-variable 'org-agenda-files)))
17771 (defun org-store-new-agenda-file-list (list)
17772 "Set new value for the agenda file list and save it correctly."
17773 (if (stringp org-agenda-files)
17774 (let ((fe (org-read-agenda-file-list t)) b u)
17775 (while (setq b (find-buffer-visiting org-agenda-files))
17776 (kill-buffer b))
17777 (with-temp-file org-agenda-files
17778 (insert
17779 (mapconcat
17780 (lambda (f) ;; Keep un-expanded entries.
17781 (if (setq u (assoc f fe))
17782 (cdr u)
17784 list "\n")
17785 "\n")))
17786 (let ((org-mode-hook nil) (org-inhibit-startup t)
17787 (org-insert-mode-line-in-empty-file nil))
17788 (setq org-agenda-files list)
17789 (customize-save-variable 'org-agenda-files org-agenda-files))))
17791 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17792 "Read the list of agenda files from a file.
17793 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17794 filenames, used by `org-store-new-agenda-file-list' to write back
17795 un-expanded file names."
17796 (when (file-directory-p org-agenda-files)
17797 (error "`org-agenda-files' cannot be a single directory"))
17798 (when (stringp org-agenda-files)
17799 (with-temp-buffer
17800 (insert-file-contents org-agenda-files)
17801 (mapcar
17802 (lambda (f)
17803 (let ((e (expand-file-name (substitute-in-file-name f)
17804 org-directory)))
17805 (if pair-with-expansion
17806 (cons e f)
17807 e)))
17808 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17810 ;;;###autoload
17811 (defun org-cycle-agenda-files ()
17812 "Cycle through the files in `org-agenda-files'.
17813 If the current buffer visits an agenda file, find the next one in the list.
17814 If the current buffer does not, find the first agenda file."
17815 (interactive)
17816 (let* ((fs (or (org-agenda-files t)
17817 (user-error "No agenda files")))
17818 (files (copy-sequence fs))
17819 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17820 file)
17821 (when tcf
17822 (while (and (setq file (pop files))
17823 (not (equal (file-truename file) tcf)))))
17824 (find-file (car (or files fs)))
17825 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17827 (defun org-agenda-file-to-front (&optional to-end)
17828 "Move/add the current file to the top of the agenda file list.
17829 If the file is not present in the list, it is added to the front. If it is
17830 present, it is moved there. With optional argument TO-END, add/move to the
17831 end of the list."
17832 (interactive "P")
17833 (let ((org-agenda-skip-unavailable-files nil)
17834 (file-alist (mapcar (lambda (x)
17835 (cons (file-truename x) x))
17836 (org-agenda-files t)))
17837 (ctf (file-truename
17838 (or buffer-file-name
17839 (user-error "Please save the current buffer to a file"))))
17840 x had)
17841 (setq x (assoc ctf file-alist) had x)
17843 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17844 (if to-end
17845 (setq file-alist (append (delq x file-alist) (list x)))
17846 (setq file-alist (cons x (delq x file-alist))))
17847 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17848 (org-install-agenda-files-menu)
17849 (message "File %s to %s of agenda file list"
17850 (if had "moved" "added") (if to-end "end" "front"))))
17852 (defun org-remove-file (&optional file)
17853 "Remove current file from the list of files in variable `org-agenda-files'.
17854 These are the files which are being checked for agenda entries.
17855 Optional argument FILE means use this file instead of the current."
17856 (interactive)
17857 (let* ((org-agenda-skip-unavailable-files nil)
17858 (file (or file buffer-file-name
17859 (user-error "Current buffer does not visit a file")))
17860 (true-file (file-truename file))
17861 (afile (abbreviate-file-name file))
17862 (files (delq nil (mapcar
17863 (lambda (x)
17864 (unless (equal true-file
17865 (file-truename x))
17867 (org-agenda-files t)))))
17868 (if (not (= (length files) (length (org-agenda-files t))))
17869 (progn
17870 (org-store-new-agenda-file-list files)
17871 (org-install-agenda-files-menu)
17872 (message "Removed from Org Agenda list: %s" afile))
17873 (message "File was not in list: %s (not removed)" afile))))
17875 (defun org-file-menu-entry (file)
17876 (vector file (list 'find-file file) t))
17878 (defun org-check-agenda-file (file)
17879 "Make sure FILE exists. If not, ask user what to do."
17880 (unless (file-exists-p file)
17881 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17882 (abbreviate-file-name file))
17883 (let ((r (downcase (read-char-exclusive))))
17884 (cond
17885 ((equal r ?r)
17886 (org-remove-file file)
17887 (throw 'nextfile t))
17888 (t (user-error "Abort"))))))
17890 (defun org-get-agenda-file-buffer (file)
17891 "Get an agenda buffer visiting FILE.
17892 If the buffer needs to be created, add it to the list of buffers
17893 which might be released later."
17894 (let ((buf (org-find-base-buffer-visiting file)))
17895 (if buf
17896 buf ; just return it
17897 ;; Make a new buffer and remember it
17898 (setq buf (find-file-noselect file))
17899 (when buf (push buf org-agenda-new-buffers))
17900 buf)))
17902 (defun org-release-buffers (blist)
17903 "Release all buffers in list, asking the user for confirmation when needed.
17904 When a buffer is unmodified, it is just killed. When modified, it is saved
17905 \(if the user agrees) and then killed."
17906 (let (file)
17907 (dolist (buf blist)
17908 (setq file (buffer-file-name buf))
17909 (when (and (buffer-modified-p buf)
17910 file
17911 (y-or-n-p (format "Save file %s? " file)))
17912 (with-current-buffer buf (save-buffer)))
17913 (kill-buffer buf))))
17915 (defun org-agenda-prepare-buffers (files)
17916 "Create buffers for all agenda files, protect archived trees and comments."
17917 (interactive)
17918 (let ((pa '(:org-archived t))
17919 (pc '(:org-comment t))
17920 (pall '(:org-archived t :org-comment t))
17921 (inhibit-read-only t)
17922 (org-inhibit-startup org-agenda-inhibit-startup)
17923 (rea (org-make-tag-string (list org-archive-tag)))
17924 re pos)
17925 (setq org-tag-alist-for-agenda nil
17926 org-tag-groups-alist-for-agenda nil)
17927 (save-excursion
17928 (save-restriction
17929 (dolist (file files)
17930 (catch 'nextfile
17931 (if (bufferp file)
17932 (set-buffer file)
17933 (org-check-agenda-file file)
17934 (set-buffer (org-get-agenda-file-buffer file)))
17935 (widen)
17936 (org-set-regexps-and-options 'tags-only)
17937 (setq pos (point))
17938 (or (memq 'category org-agenda-ignore-properties)
17939 (org-refresh-category-properties))
17940 (or (memq 'stats org-agenda-ignore-properties)
17941 (org-refresh-stats-properties))
17942 (or (memq 'effort org-agenda-ignore-properties)
17943 (org-refresh-effort-properties))
17944 (or (memq 'appt org-agenda-ignore-properties)
17945 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17946 (setq org-todo-keywords-for-agenda
17947 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17948 (setq org-done-keywords-for-agenda
17949 (append org-done-keywords-for-agenda org-done-keywords))
17950 (setq org-todo-keyword-alist-for-agenda
17951 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17952 (setq org-tag-alist-for-agenda
17953 (org--tag-add-to-alist
17954 org-tag-alist-for-agenda
17955 org-current-tag-alist))
17956 ;; Merge current file's tag groups into global
17957 ;; `org-tag-groups-alist-for-agenda'.
17958 (when org-group-tags
17959 (dolist (alist org-tag-groups-alist)
17960 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17961 (if old
17962 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17963 (push alist org-tag-groups-alist-for-agenda)))))
17964 (with-silent-modifications
17965 (save-excursion
17966 (remove-text-properties (point-min) (point-max) pall)
17967 (when org-agenda-skip-archived-trees
17968 (goto-char (point-min))
17969 (while (re-search-forward rea nil t)
17970 (when (org-at-heading-p t)
17971 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17972 (goto-char (point-min))
17973 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17974 (while (re-search-forward re nil t)
17975 (when (save-match-data (org-in-commented-heading-p t))
17976 (add-text-properties
17977 (match-beginning 0) (org-end-of-subtree t) pc)))))
17978 (goto-char pos)))))
17979 (setq org-todo-keywords-for-agenda
17980 (org-uniquify org-todo-keywords-for-agenda))
17981 (setq org-todo-keyword-alist-for-agenda
17982 (org-uniquify org-todo-keyword-alist-for-agenda))))
17985 ;;;; CDLaTeX minor mode
17987 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17988 "Keymap for the minor `org-cdlatex-mode'.")
17990 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17991 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17992 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17993 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
17994 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
17996 (defvar org-cdlatex-texmathp-advice-is-done nil
17997 "Flag remembering if we have applied the advice to texmathp already.")
17999 (define-minor-mode org-cdlatex-mode
18000 "Toggle the minor `org-cdlatex-mode'.
18001 This mode supports entering LaTeX environment and math in LaTeX fragments
18002 in Org mode.
18003 \\{org-cdlatex-mode-map}"
18004 nil " OCDL" nil
18005 (when org-cdlatex-mode
18006 (require 'cdlatex)
18007 (run-hooks 'cdlatex-mode-hook)
18008 (cdlatex-compute-tables))
18009 (unless org-cdlatex-texmathp-advice-is-done
18010 (setq org-cdlatex-texmathp-advice-is-done t)
18011 (defadvice texmathp (around org-math-always-on activate)
18012 "Always return t in Org buffers.
18013 This is because we want to insert math symbols without dollars even outside
18014 the LaTeX math segments. If Org mode thinks that point is actually inside
18015 an embedded LaTeX fragment, let `texmathp' do its job.
18016 `\\[org-cdlatex-mode-map]'"
18017 (interactive)
18018 (let (p)
18019 (cond
18020 ((not (derived-mode-p 'org-mode)) ad-do-it)
18021 ((eq this-command 'cdlatex-math-symbol)
18022 (setq ad-return-value t
18023 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18025 (let ((p (org-inside-LaTeX-fragment-p)))
18026 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18027 (setq ad-return-value t
18028 texmathp-why '("Org mode embedded math" . 0))
18029 (when p ad-do-it)))))))))
18031 (defun turn-on-org-cdlatex ()
18032 "Unconditionally turn on `org-cdlatex-mode'."
18033 (org-cdlatex-mode 1))
18035 (defun org-try-cdlatex-tab ()
18036 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18037 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18038 - inside a LaTeX fragment, or
18039 - after the first word in a line, where an abbreviation expansion could
18040 insert a LaTeX environment."
18041 (when org-cdlatex-mode
18042 (cond
18043 ;; Before any word on the line: No expansion possible.
18044 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18045 ;; Just after first word on the line: Expand it. Make sure it
18046 ;; cannot happen on headlines, though.
18047 ((save-excursion
18048 (skip-chars-backward "a-zA-Z0-9*")
18049 (skip-chars-backward " \t")
18050 (and (bolp) (not (org-at-heading-p))))
18051 (cdlatex-tab) t)
18052 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18054 (defun org-cdlatex-underscore-caret (&optional _arg)
18055 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18056 Revert to the normal definition outside of these fragments."
18057 (interactive "P")
18058 (if (org-inside-LaTeX-fragment-p)
18059 (call-interactively 'cdlatex-sub-superscript)
18060 (let (org-cdlatex-mode)
18061 (call-interactively (key-binding (vector last-input-event))))))
18063 (defun org-cdlatex-math-modify (&optional _arg)
18064 "Execute `cdlatex-math-modify' in LaTeX fragments.
18065 Revert to the normal definition outside of these fragments."
18066 (interactive "P")
18067 (if (org-inside-LaTeX-fragment-p)
18068 (call-interactively 'cdlatex-math-modify)
18069 (let (org-cdlatex-mode)
18070 (call-interactively (key-binding (vector last-input-event))))))
18072 (defun org-cdlatex-environment-indent (&optional environment item)
18073 "Execute `cdlatex-environment' and indent the inserted environment.
18075 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18077 The inserted environment is indented to current indentation
18078 unless point is at the beginning of the line, in which the
18079 environment remains unintended."
18080 (interactive)
18081 ;; cdlatex-environment always return nil. Therefore, capture output
18082 ;; first and determine if an environment was selected.
18083 (let* ((beg (point-marker))
18084 (end (copy-marker (point) t))
18085 (inserted (progn
18086 (ignore-errors (cdlatex-environment environment item))
18087 (< beg end)))
18088 ;; Figure out how many lines to move forward after the
18089 ;; environment has been inserted.
18090 (lines (when inserted
18091 (save-excursion
18092 (- (cl-loop while (< beg (point))
18093 with x = 0
18094 do (forward-line -1)
18095 (cl-incf x)
18096 finally return x)
18097 (if (progn (goto-char beg)
18098 (and (progn (skip-chars-forward " \t") (eolp))
18099 (progn (skip-chars-backward " \t") (bolp))))
18100 1 0)))))
18101 (env (org-trim (delete-and-extract-region beg end))))
18102 (when inserted
18103 ;; Get indentation of next line unless at column 0.
18104 (let ((ind (if (bolp) 0
18105 (save-excursion
18106 (org-return-indent)
18107 (prog1 (current-indentation)
18108 (when (progn (skip-chars-forward " \t") (eolp))
18109 (delete-region beg (point)))))))
18110 (bol (progn (skip-chars-backward " \t") (bolp))))
18111 ;; Insert a newline before environment unless at column zero
18112 ;; to "escape" the current line. Insert a newline if
18113 ;; something is one the same line as \end{ENVIRONMENT}.
18114 (insert
18115 (concat (unless bol "\n") env
18116 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18117 (unless (zerop ind)
18118 (save-excursion
18119 (goto-char beg)
18120 (while (< (point) end)
18121 (unless (eolp) (indent-line-to ind))
18122 (forward-line))))
18123 (goto-char beg)
18124 (forward-line lines)
18125 (indent-line-to ind)))
18126 (set-marker beg nil)
18127 (set-marker end nil)))
18130 ;;;; LaTeX fragments
18132 (defun org-inside-LaTeX-fragment-p ()
18133 "Test if point is inside a LaTeX fragment.
18134 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18135 sequence appearing also before point.
18136 Even though the matchers for math are configurable, this function assumes
18137 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18138 delimiters are skipped when they have been removed by customization.
18139 The return value is nil, or a cons cell with the delimiter and the
18140 position of this delimiter.
18142 This function does a reasonably good job, but can locally be fooled by
18143 for example currency specifications. For example it will assume being in
18144 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18145 fragments that are properly closed, but during editing, we have to live
18146 with the uncertainty caused by missing closing delimiters. This function
18147 looks only before point, not after."
18148 (catch 'exit
18149 (let ((pos (point))
18150 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18151 (lim (save-excursion (org-backward-paragraph) (point)))
18152 dd-on str (start 0) m re)
18153 (goto-char pos)
18154 (when dodollar
18155 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18156 re (nth 1 (assoc "$" org-latex-regexps)))
18157 (while (string-match re str start)
18158 (cond
18159 ((= (match-end 0) (length str))
18160 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18161 ((= (match-end 0) (- (length str) 5))
18162 (throw 'exit nil))
18163 (t (setq start (match-end 0))))))
18164 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18165 (goto-char pos)
18166 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18167 (and (match-beginning 2) (throw 'exit nil))
18168 ;; count $$
18169 (while (re-search-backward "\\$\\$" lim t)
18170 (setq dd-on (not dd-on)))
18171 (goto-char pos)
18172 (when dd-on (cons "$$" m))))))
18174 (defun org-inside-latex-macro-p ()
18175 "Is point inside a LaTeX macro or its arguments?"
18176 (save-match-data
18177 (org-in-regexp
18178 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18180 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18181 "Build an overlay between BEG and END using IMAGE file.
18182 Argument IMAGETYPE is the extension of the displayed image,
18183 as a string. It defaults to \"png\"."
18184 (let ((ov (make-overlay beg end))
18185 (imagetype (or (intern imagetype) 'png)))
18186 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18187 (overlay-put ov 'evaporate t)
18188 (overlay-put ov
18189 'modification-hooks
18190 (list (lambda (o _flag _beg _end &optional _l)
18191 (delete-overlay o))))
18192 (overlay-put ov
18193 'display
18194 (list 'image :type imagetype :file image :ascent 'center))))
18196 (defun org--list-latex-overlays (&optional beg end)
18197 "List all Org LaTeX overlays in current buffer.
18198 Limit to overlays between BEG and END when those are provided."
18199 (cl-remove-if-not
18200 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18201 (overlays-in (or beg (point-min)) (or end (point-max)))))
18203 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18204 "Remove all overlays with LaTeX fragment images in current buffer.
18205 When optional arguments BEG and END are non-nil, remove all
18206 overlays between them instead. Return a non-nil value when some
18207 overlays were removed, nil otherwise."
18208 (let ((overlays (org--list-latex-overlays beg end)))
18209 (mapc #'delete-overlay overlays)
18210 overlays))
18212 (defun org-toggle-latex-fragment (&optional arg)
18213 "Preview the LaTeX fragment at point, or all locally or globally.
18215 If the cursor is on a LaTeX fragment, create the image and overlay
18216 it over the source code, if there is none. Remove it otherwise.
18217 If there is no fragment at point, display all fragments in the
18218 current section.
18220 With prefix ARG, preview or clear image for all fragments in the
18221 current subtree or in the whole buffer when used before the first
18222 headline. With a prefix ARG `\\[universal-argument] \
18223 \\[universal-argument]' preview or clear images
18224 for all fragments in the buffer."
18225 (interactive "P")
18226 (when (display-graphic-p)
18227 (catch 'exit
18228 (save-excursion
18229 (let (beg end msg)
18230 (cond
18231 ((or (equal arg '(16))
18232 (and (equal arg '(4))
18233 (org-with-limited-levels (org-before-first-heading-p))))
18234 (if (org-remove-latex-fragment-image-overlays)
18235 (progn (message "LaTeX fragments images removed from buffer")
18236 (throw 'exit nil))
18237 (setq msg "Creating images for buffer...")))
18238 ((equal arg '(4))
18239 (org-with-limited-levels (org-back-to-heading t))
18240 (setq beg (point))
18241 (setq end (progn (org-end-of-subtree t) (point)))
18242 (if (org-remove-latex-fragment-image-overlays beg end)
18243 (progn
18244 (message "LaTeX fragment images removed from subtree")
18245 (throw 'exit nil))
18246 (setq msg "Creating images for subtree...")))
18247 ((let ((datum (org-element-context)))
18248 (when (memq (org-element-type datum)
18249 '(latex-environment latex-fragment))
18250 (setq beg (org-element-property :begin datum))
18251 (setq end (org-element-property :end datum))
18252 (if (org-remove-latex-fragment-image-overlays beg end)
18253 (progn (message "LaTeX fragment image removed")
18254 (throw 'exit nil))
18255 (setq msg "Creating image...")))))
18257 (org-with-limited-levels
18258 (setq beg (if (org-at-heading-p) (line-beginning-position)
18259 (outline-previous-heading)
18260 (point)))
18261 (setq end (progn (outline-next-heading) (point)))
18262 (if (org-remove-latex-fragment-image-overlays beg end)
18263 (progn
18264 (message "LaTeX fragment images removed from section")
18265 (throw 'exit nil))
18266 (setq msg "Creating images for section...")))))
18267 (let ((file (buffer-file-name (buffer-base-buffer))))
18268 (org-format-latex
18269 (concat org-preview-latex-image-directory "org-ltximg")
18270 beg end
18271 ;; Emacs cannot overlay images from remote hosts. Create
18272 ;; it in `temporary-file-directory' instead.
18273 (if (or (not file) (file-remote-p file))
18274 temporary-file-directory
18275 default-directory)
18276 'overlays msg 'forbuffer org-preview-latex-default-process))
18277 (message (concat msg "done")))))))
18279 (defun org-format-latex
18280 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18281 "Replace LaTeX fragments with links to an image.
18283 The function takes care of creating the replacement image.
18285 Only consider fragments between BEG and END when those are
18286 provided.
18288 When optional argument OVERLAYS is non-nil, display the image on
18289 top of the fragment instead of replacing it.
18291 PROCESSING-TYPE is the conversion method to use, as a symbol.
18293 Some of the options can be changed using the variable
18294 `org-format-latex-options', which see."
18295 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18296 (unless (eq processing-type 'verbatim)
18297 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18298 (cnt 0)
18299 checkdir-flag)
18300 (goto-char (or beg (point-min)))
18301 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18302 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18303 (overlay-recenter (or end (point-max))))
18304 (while (re-search-forward math-regexp end t)
18305 (unless (and overlays
18306 (eq (get-char-property (point) 'org-overlay-type)
18307 'org-latex-overlay))
18308 (let* ((context (org-element-context))
18309 (type (org-element-type context)))
18310 (when (memq type '(latex-environment latex-fragment))
18311 (let ((block-type (eq type 'latex-environment))
18312 (value (org-element-property :value context))
18313 (beg (org-element-property :begin context))
18314 (end (save-excursion
18315 (goto-char (org-element-property :end context))
18316 (skip-chars-backward " \r\t\n")
18317 (point))))
18318 (cond
18319 ((eq processing-type 'mathjax)
18320 ;; Prepare for MathJax processing.
18321 (if (not (string-match "\\`\\$\\$?" value))
18322 (goto-char end)
18323 (delete-region beg end)
18324 (if (string= (match-string 0 value) "$$")
18325 (insert "\\[" (substring value 2 -2) "\\]")
18326 (insert "\\(" (substring value 1 -1) "\\)"))))
18327 ((assq processing-type org-preview-latex-process-alist)
18328 ;; Process to an image.
18329 (cl-incf cnt)
18330 (goto-char beg)
18331 (let* ((processing-info
18332 (cdr (assq processing-type org-preview-latex-process-alist)))
18333 (face (face-at-point))
18334 ;; Get the colors from the face at point.
18336 (let ((color (plist-get org-format-latex-options
18337 :foreground)))
18338 (if (and forbuffer (eq color 'auto))
18339 (face-attribute face :foreground nil 'default)
18340 color)))
18342 (let ((color (plist-get org-format-latex-options
18343 :background)))
18344 (if (and forbuffer (eq color 'auto))
18345 (face-attribute face :background nil 'default)
18346 color)))
18347 (hash (sha1 (prin1-to-string
18348 (list org-format-latex-header
18349 org-latex-default-packages-alist
18350 org-latex-packages-alist
18351 org-format-latex-options
18352 forbuffer value fg bg))))
18353 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18354 (absprefix (expand-file-name prefix dir))
18355 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18356 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18357 (sep (and block-type "\n\n"))
18358 (link (concat sep "[[file:" linkfile "]]" sep))
18359 (options
18360 (org-combine-plists
18361 org-format-latex-options
18362 `(:foreground ,fg :background ,bg))))
18363 (when msg (message msg cnt))
18364 (unless checkdir-flag ; Ensure the directory exists.
18365 (setq checkdir-flag t)
18366 (let ((todir (file-name-directory absprefix)))
18367 (unless (file-directory-p todir)
18368 (make-directory todir t))))
18369 (unless (file-exists-p movefile)
18370 (org-create-formula-image
18371 value movefile options forbuffer processing-type))
18372 (if overlays
18373 (progn
18374 (dolist (o (overlays-in beg end))
18375 (when (eq (overlay-get o 'org-overlay-type)
18376 'org-latex-overlay)
18377 (delete-overlay o)))
18378 (org--format-latex-make-overlay beg end movefile imagetype)
18379 (goto-char end))
18380 (delete-region beg end)
18381 (insert
18382 (org-add-props link
18383 (list 'org-latex-src
18384 (replace-regexp-in-string "\"" "" value)
18385 'org-latex-src-embed-type
18386 (if block-type 'paragraph 'character)))))))
18387 ((eq processing-type 'mathml)
18388 ;; Process to MathML.
18389 (unless (org-format-latex-mathml-available-p)
18390 (user-error "LaTeX to MathML converter not configured"))
18391 (cl-incf cnt)
18392 (when msg (message msg cnt))
18393 (goto-char beg)
18394 (delete-region beg end)
18395 (insert (org-format-latex-as-mathml
18396 value block-type prefix dir)))
18398 (error "Unknown conversion process %s for LaTeX fragments"
18399 processing-type)))))))))))
18401 (defun org-create-math-formula (latex-frag &optional mathml-file)
18402 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18403 Use `org-latex-to-mathml-convert-command'. If the conversion is
18404 sucessful, return the portion between \"<math...> </math>\"
18405 elements otherwise return nil. When MATHML-FILE is specified,
18406 write the results in to that file. When invoked as an
18407 interactive command, prompt for LATEX-FRAG, with initial value
18408 set to the current active region and echo the results for user
18409 inspection."
18410 (interactive (list (let ((frag (when (org-region-active-p)
18411 (buffer-substring-no-properties
18412 (region-beginning) (region-end)))))
18413 (read-string "LaTeX Fragment: " frag nil frag))))
18414 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18415 (let* ((tmp-in-file
18416 (let ((file (file-relative-name
18417 (make-temp-name (expand-file-name "ltxmathml-in")))))
18418 (write-region latex-frag nil file)
18419 file))
18420 (tmp-out-file (file-relative-name
18421 (make-temp-name (expand-file-name "ltxmathml-out"))))
18422 (cmd (format-spec
18423 org-latex-to-mathml-convert-command
18424 `((?j . ,(and org-latex-to-mathml-jar-file
18425 (shell-quote-argument
18426 (expand-file-name
18427 org-latex-to-mathml-jar-file))))
18428 (?I . ,(shell-quote-argument tmp-in-file))
18429 (?i . ,latex-frag)
18430 (?o . ,(shell-quote-argument tmp-out-file)))))
18431 mathml shell-command-output)
18432 (when (called-interactively-p 'any)
18433 (unless (org-format-latex-mathml-available-p)
18434 (user-error "LaTeX to MathML converter not configured")))
18435 (message "Running %s" cmd)
18436 (setq shell-command-output (shell-command-to-string cmd))
18437 (setq mathml
18438 (when (file-readable-p tmp-out-file)
18439 (with-current-buffer (find-file-noselect tmp-out-file t)
18440 (goto-char (point-min))
18441 (when (re-search-forward
18442 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18443 (regexp-quote
18444 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18445 nil t)
18446 (prog1 (match-string 0) (kill-buffer))))))
18447 (cond
18448 (mathml
18449 (setq mathml
18450 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18451 (when mathml-file
18452 (write-region mathml nil mathml-file))
18453 (when (called-interactively-p 'any)
18454 (message mathml)))
18455 ((message "LaTeX to MathML conversion failed")
18456 (message shell-command-output)))
18457 (delete-file tmp-in-file)
18458 (when (file-exists-p tmp-out-file)
18459 (delete-file tmp-out-file))
18460 mathml))
18462 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18463 prefix &optional dir)
18464 "Use `org-create-math-formula' but check local cache first."
18465 (let* ((absprefix (expand-file-name prefix dir))
18466 (print-length nil) (print-level nil)
18467 (formula-id (concat
18468 "formula-"
18469 (sha1
18470 (prin1-to-string
18471 (list latex-frag
18472 org-latex-to-mathml-convert-command)))))
18473 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18474 (formula-cache-dir (file-name-directory formula-cache)))
18476 (unless (file-directory-p formula-cache-dir)
18477 (make-directory formula-cache-dir t))
18479 (unless (file-exists-p formula-cache)
18480 (org-create-math-formula latex-frag formula-cache))
18482 (if (file-exists-p formula-cache)
18483 ;; Successful conversion. Return the link to MathML file.
18484 (org-add-props
18485 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18486 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18487 'org-latex-src-embed-type (if latex-frag-type
18488 'paragraph 'character)))
18489 ;; Failed conversion. Return the LaTeX fragment verbatim
18490 latex-frag)))
18492 (defun org--get-display-dpi ()
18493 "Get the DPI of the display.
18494 The function assumes that the display has the same pixel width in
18495 the horizontal and vertical directions."
18496 (if (display-graphic-p)
18497 (round (/ (display-pixel-height)
18498 (/ (display-mm-height) 25.4)))
18499 (error "Attempt to calculate the dpi of a non-graphic display")))
18501 (defun org-create-formula-image
18502 (string tofile options buffer &optional processing-type)
18503 "Create an image from LaTeX source using external processes.
18505 The LaTeX STRING is saved to a temporary LaTeX file, then
18506 converted to an image file by process PROCESSING-TYPE defined in
18507 `org-preview-latex-process-alist'. A nil value defaults to
18508 `org-preview-latex-default-process'.
18510 The generated image file is eventually moved to TOFILE.
18512 The OPTIONS argument controls the size, foreground color and
18513 background color of the generated image.
18515 When BUFFER non-nil, this function is used for LaTeX previewing.
18516 Otherwise, it is used to deal with LaTeX snippets showed in
18517 a HTML file."
18518 (let* ((processing-type (or processing-type
18519 org-preview-latex-default-process))
18520 (processing-info
18521 (cdr (assq processing-type org-preview-latex-process-alist)))
18522 (programs (plist-get processing-info :programs))
18523 (error-message (or (plist-get processing-info :message) ""))
18524 (use-xcolor (plist-get processing-info :use-xcolor))
18525 (image-input-type (plist-get processing-info :image-input-type))
18526 (image-output-type (plist-get processing-info :image-output-type))
18527 (post-clean (or (plist-get processing-info :post-clean)
18528 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18529 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18530 (latex-header
18531 (or (plist-get processing-info :latex-header)
18532 (org-latex-make-preamble
18533 (org-export-get-environment (org-export-get-backend 'latex))
18534 org-format-latex-header
18535 'snippet)))
18536 (latex-compiler (plist-get processing-info :latex-compiler))
18537 (image-converter (plist-get processing-info :image-converter))
18538 (tmpdir temporary-file-directory)
18539 (texfilebase (make-temp-name
18540 (expand-file-name "orgtex" tmpdir)))
18541 (texfile (concat texfilebase ".tex"))
18542 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18543 '(1.0 . 1.0)))
18544 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18545 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18546 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18547 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18548 "Black"))
18549 (bg (or (plist-get options (if buffer :background :html-background))
18550 "Transparent"))
18551 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18552 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18553 (dolist (program programs)
18554 (org-check-external-command program error-message))
18555 (if use-xcolor
18556 (progn (if (eq fg 'default)
18557 (setq fg (org-latex-color :foreground))
18558 (setq fg (org-latex-color-format fg)))
18559 (if (eq bg 'default)
18560 (setq bg (org-latex-color :background))
18561 (setq bg (org-latex-color-format
18562 (if (string= bg "Transparent") "white" bg))))
18563 (with-temp-file texfile
18564 (insert latex-header)
18565 (insert "\n\\begin{document}\n"
18566 "\\definecolor{fg}{rgb}{" fg "}\n"
18567 "\\definecolor{bg}{rgb}{" bg "}\n"
18568 "\n\\pagecolor{bg}\n"
18569 "\n{\\color{fg}\n"
18570 string
18571 "\n}\n"
18572 "\n\\end{document}\n")))
18573 (if (eq fg 'default)
18574 (setq fg (org-dvipng-color :foreground))
18575 (unless (string= fg "Transparent")
18576 (setq fg (org-dvipng-color-format fg))))
18577 (if (eq bg 'default)
18578 (setq bg (org-dvipng-color :background))
18579 (unless (string= bg "Transparent")
18580 (setq bg (org-dvipng-color-format bg))))
18581 (with-temp-file texfile
18582 (insert latex-header)
18583 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18585 (let* ((err-msg (format "Please adjust `%s' part of \
18586 `org-preview-latex-process-alist'."
18587 processing-type))
18588 (image-input-file
18589 (org-compile-file
18590 texfile latex-compiler image-input-type err-msg log-buf))
18591 (image-output-file
18592 (org-compile-file
18593 image-input-file image-converter image-output-type err-msg log-buf
18594 `((?F . ,(shell-quote-argument fg))
18595 (?B . ,(shell-quote-argument bg))
18596 (?D . ,(shell-quote-argument (format "%s" dpi)))
18597 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18598 (copy-file image-output-file tofile 'replace)
18599 (dolist (e post-clean)
18600 (when (file-exists-p (concat texfilebase e))
18601 (delete-file (concat texfilebase e))))
18602 image-output-file)))
18604 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18605 "Fill a LaTeX header template TPL.
18606 In the template, the following place holders will be recognized:
18608 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18609 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18610 [PACKAGES] \\usepackage statements for PKG
18611 [NO-PACKAGES] do not include PKG
18612 [EXTRA] the string EXTRA
18613 [NO-EXTRA] do not include EXTRA
18615 For backward compatibility, if both the positive and the negative place
18616 holder is missing, the positive one (without the \"NO-\") will be
18617 assumed to be present at the end of the template.
18618 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18619 EXTRA is a string.
18620 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18621 (let (rpl (end ""))
18622 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18623 (setq rpl (if (or (match-end 1) (not def-pkg))
18624 "" (org-latex-packages-to-string def-pkg snippets-p t))
18625 tpl (replace-match rpl t t tpl))
18626 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18628 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18629 (setq rpl (if (or (match-end 1) (not pkg))
18630 "" (org-latex-packages-to-string pkg snippets-p t))
18631 tpl (replace-match rpl t t tpl))
18632 (when pkg (setq end
18633 (concat end "\n"
18634 (org-latex-packages-to-string pkg snippets-p)))))
18636 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18637 (setq rpl (if (or (match-end 1) (not extra))
18638 "" (concat extra "\n"))
18639 tpl (replace-match rpl t t tpl))
18640 (when (and extra (string-match "\\S-" extra))
18641 (setq end (concat end "\n" extra))))
18643 (if (string-match "\\S-" end)
18644 (concat tpl "\n" end)
18645 tpl)))
18647 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18648 "Turn an alist of packages into a string with the \\usepackage macros."
18649 (setq pkg (mapconcat (lambda(p)
18650 (cond
18651 ((stringp p) p)
18652 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18653 (format "%% Package %s omitted" (cadr p)))
18654 ((equal "" (car p))
18655 (format "\\usepackage{%s}" (cadr p)))
18657 (format "\\usepackage[%s]{%s}"
18658 (car p) (cadr p)))))
18660 "\n"))
18661 (if newline (concat pkg "\n") pkg))
18663 (defun org-dvipng-color (attr)
18664 "Return a RGB color specification for dvipng."
18665 (org-dvipng-color-format (face-attribute 'default attr nil)))
18667 (defun org-dvipng-color-format (color-name)
18668 "Convert COLOR-NAME to a RGB color value for dvipng."
18669 (apply #'format "rgb %s %s %s"
18670 (mapcar 'org-normalize-color
18671 (color-values color-name))))
18673 (defun org-latex-color (attr)
18674 "Return a RGB color for the LaTeX color package."
18675 (org-latex-color-format (face-attribute 'default attr nil)))
18677 (defun org-latex-color-format (color-name)
18678 "Convert COLOR-NAME to a RGB color value."
18679 (apply #'format "%s,%s,%s"
18680 (mapcar 'org-normalize-color
18681 (color-values color-name))))
18683 (defun org-normalize-color (value)
18684 "Return string to be used as color value for an RGB component."
18685 (format "%g" (/ value 65535.0)))
18688 ;; Image display
18690 (defvar-local org-inline-image-overlays nil)
18692 (defun org-toggle-inline-images (&optional include-linked)
18693 "Toggle the display of inline images.
18694 INCLUDE-LINKED is passed to `org-display-inline-images'."
18695 (interactive "P")
18696 (if org-inline-image-overlays
18697 (progn
18698 (org-remove-inline-images)
18699 (when (called-interactively-p 'interactive)
18700 (message "Inline image display turned off")))
18701 (org-display-inline-images include-linked)
18702 (when (called-interactively-p 'interactive)
18703 (message (if org-inline-image-overlays
18704 (format "%d images displayed inline"
18705 (length org-inline-image-overlays))
18706 "No images to display inline")))))
18708 (defun org-redisplay-inline-images ()
18709 "Refresh the display of inline images."
18710 (interactive)
18711 (if (not org-inline-image-overlays)
18712 (org-toggle-inline-images)
18713 (org-toggle-inline-images)
18714 (org-toggle-inline-images)))
18716 (defun org-display-inline-images (&optional include-linked refresh beg end)
18717 "Display inline images.
18719 An inline image is a link which follows either of these
18720 conventions:
18722 1. Its path is a file with an extension matching return value
18723 from `image-file-name-regexp' and it has no contents.
18725 2. Its description consists in a single link of the previous
18726 type.
18728 When optional argument INCLUDE-LINKED is non-nil, also links with
18729 a text description part will be inlined. This can be nice for
18730 a quick look at those images, but it does not reflect what
18731 exported files will look like.
18733 When optional argument REFRESH is non-nil, refresh existing
18734 images between BEG and END. This will create new image displays
18735 only if necessary. BEG and END default to the buffer
18736 boundaries."
18737 (interactive "P")
18738 (when (display-graphic-p)
18739 (unless refresh
18740 (org-remove-inline-images)
18741 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18742 (org-with-wide-buffer
18743 (goto-char (or beg (point-min)))
18744 (let* ((case-fold-search t)
18745 (file-extension-re (image-file-name-regexp))
18746 (link-abbrevs (mapcar #'car
18747 (append org-link-abbrev-alist-local
18748 org-link-abbrev-alist)))
18749 ;; Check absolute, relative file names and explicit
18750 ;; "file:" links. Also check link abbreviations since
18751 ;; some might expand to "file" links.
18752 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18753 (if (not link-abbrevs) ""
18754 (format "\\|\\(?:%s:\\)"
18755 (regexp-opt link-abbrevs))))))
18756 (while (re-search-forward file-types-re end t)
18757 (let ((link (save-match-data (org-element-context))))
18758 ;; Check if we're at an inline image, i.e., an image file
18759 ;; link without a description (unless INCLUDE-LINKED is
18760 ;; non-nil).
18761 (when (and (equal "file" (org-element-property :type link))
18762 (or include-linked
18763 (null (org-element-contents link)))
18764 (string-match-p file-extension-re
18765 (org-element-property :path link)))
18766 (let ((file (expand-file-name
18767 (org-link-unescape
18768 (org-element-property :path link)))))
18769 (when (file-exists-p file)
18770 (let ((width
18771 ;; Apply `org-image-actual-width' specifications.
18772 (cond
18773 ((not (image-type-available-p 'imagemagick)) nil)
18774 ((eq org-image-actual-width t) nil)
18775 ((listp org-image-actual-width)
18777 ;; First try to find a width among
18778 ;; attributes associated to the paragraph
18779 ;; containing link.
18780 (let ((paragraph
18781 (let ((e link))
18782 (while (and (setq e (org-element-property
18783 :parent e))
18784 (not (eq (org-element-type e)
18785 'paragraph))))
18786 e)))
18787 (when paragraph
18788 (save-excursion
18789 (goto-char (org-element-property :begin paragraph))
18790 (when
18791 (re-search-forward
18792 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18793 (org-element-property
18794 :post-affiliated paragraph)
18796 (string-to-number (match-string 1))))))
18797 ;; Otherwise, fall-back to provided number.
18798 (car org-image-actual-width)))
18799 ((numberp org-image-actual-width)
18800 org-image-actual-width)))
18801 (old (get-char-property-and-overlay
18802 (org-element-property :begin link)
18803 'org-image-overlay)))
18804 (if (and (car-safe old) refresh)
18805 (image-refresh (overlay-get (cdr old) 'display))
18806 (let ((image (create-image file
18807 (and width 'imagemagick)
18809 :width width)))
18810 (when image
18811 (let ((ov (make-overlay
18812 (org-element-property :begin link)
18813 (progn
18814 (goto-char
18815 (org-element-property :end link))
18816 (skip-chars-backward " \t")
18817 (point)))))
18818 (overlay-put ov 'display image)
18819 (overlay-put ov 'face 'default)
18820 (overlay-put ov 'org-image-overlay t)
18821 (overlay-put
18822 ov 'modification-hooks
18823 (list 'org-display-inline-remove-overlay))
18824 (push ov org-inline-image-overlays)))))))))))))))
18826 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18827 "Remove inline-display overlay if a corresponding region is modified."
18828 (let ((inhibit-modification-hooks t))
18829 (when (and ov after)
18830 (delete ov org-inline-image-overlays)
18831 (delete-overlay ov))))
18833 (defun org-remove-inline-images ()
18834 "Remove inline display of images."
18835 (interactive)
18836 (mapc #'delete-overlay org-inline-image-overlays)
18837 (setq org-inline-image-overlays nil))
18840 ;;; Key bindings
18842 (defun org-remap (map &rest commands)
18843 "In MAP, remap the functions given in COMMANDS.
18844 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18845 (let (new old)
18846 (while commands
18847 (setq old (pop commands) new (pop commands))
18848 (org-defkey map (vector 'remap old) new))))
18850 ;;;; Outline functions that can be remapped in Org
18851 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18852 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18853 (define-key org-mode-map [remap outline-forward-same-level]
18854 #'org-forward-heading-same-level)
18855 (define-key org-mode-map [remap outline-backward-same-level]
18856 #'org-backward-heading-same-level)
18857 (define-key org-mode-map [remap outline-show-branches]
18858 #'org-kill-note-or-show-branches)
18859 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18860 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18861 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18862 (define-key org-mode-map [remap outline-next-visible-heading]
18863 #'org-next-visible-heading)
18864 (define-key org-mode-map [remap outline-previous-visible-heading]
18865 #'org-previous-visible-heading)
18866 (define-key org-mode-map [remap show-children] #'org-show-children)
18868 ;;;; Make `C-c C-x' a prefix key
18869 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18871 ;;;; TAB key with modifiers
18872 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18873 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18874 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18875 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18876 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18878 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18879 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18880 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18882 ;;;; RET key with modifiers
18883 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18884 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18885 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18886 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18887 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18889 ;;;; Cursor keys with modifiers
18890 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18891 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18892 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18893 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18894 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18895 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18896 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18898 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18899 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18900 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18901 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18902 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18903 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18904 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18905 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18906 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18907 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18909 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18910 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18911 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18912 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18914 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18915 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18916 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18917 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18919 ;;;; Babel keys
18920 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18921 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18922 (define-key org-babel-map key def))
18924 ;;;; Extra keys for TTY access.
18926 ;; We only set them when really needed because otherwise the
18927 ;; menus don't show the simple keys
18929 (when (or org-use-extra-keys (not window-system))
18930 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18931 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18932 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18933 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18934 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18935 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18936 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18937 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18938 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18939 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18940 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18941 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18942 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18943 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18944 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18945 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18946 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18947 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18948 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18949 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18950 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18952 ;;;; Narrow map
18953 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18954 (org-defkey narrow-map "b" #'org-narrow-to-block)
18955 (org-defkey narrow-map "e" #'org-narrow-to-element)
18957 ;;;; Remap usual Emacs bindings
18958 (org-remap org-mode-map
18959 'self-insert-command 'org-self-insert-command
18960 'delete-char 'org-delete-char
18961 'delete-backward-char 'org-delete-backward-char
18962 'kill-line 'org-kill-line
18963 'open-line 'org-open-line
18964 'yank 'org-yank
18965 'comment-dwim 'org-comment-dwim
18966 'move-beginning-of-line 'org-beginning-of-line
18967 'move-end-of-line 'org-end-of-line
18968 'forward-paragraph 'org-forward-paragraph
18969 'backward-paragraph 'org-backward-paragraph
18970 'backward-sentence 'org-backward-sentence
18971 'forward-sentence 'org-forward-sentence
18972 'fill-paragraph 'org-fill-paragraph
18973 'delete-indentation 'org-delete-indentation
18974 'transpose-words 'org-transpose-words)
18976 ;;;; All the other keys
18977 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18978 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18979 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18980 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18981 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18982 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18983 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18984 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18985 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18986 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18987 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18988 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18989 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18990 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18991 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18992 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18993 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
18994 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
18995 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
18996 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
18997 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
18998 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
18999 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
19000 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
19001 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
19002 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
19003 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
19004 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
19005 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
19006 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
19007 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
19008 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
19009 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
19010 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
19011 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
19012 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
19013 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
19014 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
19015 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
19016 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
19017 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
19018 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
19019 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
19020 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19021 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19022 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19023 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19024 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19025 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19026 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19027 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19028 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19029 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19030 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19031 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19032 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19033 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19034 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19035 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19036 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19037 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19038 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19039 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19040 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19041 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19042 (org-defkey org-mode-map (kbd "RET") #'org-return)
19043 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19044 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19045 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19046 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19047 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19048 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19049 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19050 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19051 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19052 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19053 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19054 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19055 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19056 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19057 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19058 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19059 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19060 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19061 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19062 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19063 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19064 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19065 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19067 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19068 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19069 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19071 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19072 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19073 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19074 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19075 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19076 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19077 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19078 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19079 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19080 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19081 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19082 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19083 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19084 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19085 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19086 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19087 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19088 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19089 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19090 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19091 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19092 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19093 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19094 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19095 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19096 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19097 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19098 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19100 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19102 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19104 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19105 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19107 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19110 ;;; Speed commands
19112 (defconst org-speed-commands-default
19114 ("Outline Navigation")
19115 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19116 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19117 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19118 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19119 ("F" . org-next-block)
19120 ("B" . org-previous-block)
19121 ("u" . (org-speed-move-safe 'outline-up-heading))
19122 ("j" . org-goto)
19123 ("g" . (org-refile t))
19124 ("Outline Visibility")
19125 ("c" . org-cycle)
19126 ("C" . org-shifttab)
19127 (" " . org-display-outline-path)
19128 ("s" . org-toggle-narrow-to-subtree)
19129 ("k" . org-cut-subtree)
19130 ("=" . org-columns)
19131 ("Outline Structure Editing")
19132 ("U" . org-metaup)
19133 ("D" . org-metadown)
19134 ("r" . org-metaright)
19135 ("l" . org-metaleft)
19136 ("R" . org-shiftmetaright)
19137 ("L" . org-shiftmetaleft)
19138 ("i" . (progn (forward-char 1) (call-interactively
19139 'org-insert-heading-respect-content)))
19140 ("^" . org-sort)
19141 ("w" . org-refile)
19142 ("a" . org-archive-subtree-default-with-confirmation)
19143 ("@" . org-mark-subtree)
19144 ("#" . org-toggle-comment)
19145 ("Clock Commands")
19146 ("I" . org-clock-in)
19147 ("O" . org-clock-out)
19148 ("Meta Data Editing")
19149 ("t" . org-todo)
19150 ("," . (org-priority))
19151 ("0" . (org-priority ?\ ))
19152 ("1" . (org-priority ?A))
19153 ("2" . (org-priority ?B))
19154 ("3" . (org-priority ?C))
19155 (":" . org-set-tags-command)
19156 ("e" . org-set-effort)
19157 ("E" . org-inc-effort)
19158 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19159 (org-entry-put (point) "APPT_WARNTIME" m)))
19160 ("Agenda Views etc")
19161 ("v" . org-agenda)
19162 ("/" . org-sparse-tree)
19163 ("Misc")
19164 ("o" . org-open-at-point)
19165 ("?" . org-speed-command-help)
19166 ("<" . (org-agenda-set-restriction-lock 'subtree))
19167 (">" . (org-agenda-remove-restriction-lock))
19169 "The default speed commands.")
19171 (defun org-print-speed-command (e)
19172 (if (> (length (car e)) 1)
19173 (progn
19174 (princ "\n")
19175 (princ (car e))
19176 (princ "\n")
19177 (princ (make-string (length (car e)) ?-))
19178 (princ "\n"))
19179 (princ (car e))
19180 (princ " ")
19181 (if (symbolp (cdr e))
19182 (princ (symbol-name (cdr e)))
19183 (prin1 (cdr e)))
19184 (princ "\n")))
19186 (defun org-speed-command-help ()
19187 "Show the available speed commands."
19188 (interactive)
19189 (if (not org-use-speed-commands)
19190 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19191 (with-output-to-temp-buffer "*Help*"
19192 (princ "User-defined Speed commands\n===========================\n")
19193 (mapc #'org-print-speed-command org-speed-commands-user)
19194 (princ "\n")
19195 (princ "Built-in Speed commands\n=======================\n")
19196 (mapc #'org-print-speed-command org-speed-commands-default))
19197 (with-current-buffer "*Help*"
19198 (setq truncate-lines t))))
19200 (defun org-speed-move-safe (cmd)
19201 "Execute CMD, but make sure that the cursor always ends up in a headline.
19202 If not, return to the original position and throw an error."
19203 (interactive)
19204 (let ((pos (point)))
19205 (call-interactively cmd)
19206 (unless (and (bolp) (org-at-heading-p))
19207 (goto-char pos)
19208 (error "Boundary reached while executing %s" cmd))))
19210 (defvar org-self-insert-command-undo-counter 0)
19212 (defvar org-table-auto-blank-field) ; defined in org-table.el
19213 (defvar org-speed-command nil)
19215 (defun org-speed-command-activate (keys)
19216 "Hook for activating single-letter speed commands.
19217 `org-speed-commands-default' specifies a minimal command set.
19218 Use `org-speed-commands-user' for further customization."
19219 (when (or (and (bolp) (looking-at org-outline-regexp))
19220 (and (functionp org-use-speed-commands)
19221 (funcall org-use-speed-commands)))
19222 (cdr (assoc keys (append org-speed-commands-user
19223 org-speed-commands-default)))))
19225 (defun org-babel-speed-command-activate (keys)
19226 "Hook for activating single-letter code block commands."
19227 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19228 (cdr (assoc keys org-babel-key-bindings))))
19230 (defcustom org-speed-command-hook
19231 '(org-speed-command-activate org-babel-speed-command-activate)
19232 "Hook for activating speed commands at strategic locations.
19233 Hook functions are called in sequence until a valid handler is
19234 found.
19236 Each hook takes a single argument, a user-pressed command key
19237 which is also a `self-insert-command' from the global map.
19239 Within the hook, examine the cursor position and the command key
19240 and return nil or a valid handler as appropriate. Handler could
19241 be one of an interactive command, a function, or a form.
19243 Set `org-use-speed-commands' to non-nil value to enable this
19244 hook. The default setting is `org-speed-command-activate'."
19245 :group 'org-structure
19246 :version "24.1"
19247 :type 'hook)
19249 (defun org-self-insert-command (N)
19250 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19251 If the cursor is in a table looking at whitespace, the whitespace is
19252 overwritten, and the table is not marked as requiring realignment."
19253 (interactive "p")
19254 (org-check-before-invisible-edit 'insert)
19255 (cond
19256 ((and org-use-speed-commands
19257 (let ((kv (this-command-keys-vector)))
19258 (setq org-speed-command
19259 (run-hook-with-args-until-success
19260 'org-speed-command-hook
19261 (make-string 1 (aref kv (1- (length kv))))))))
19262 (cond
19263 ((commandp org-speed-command)
19264 (setq this-command org-speed-command)
19265 (call-interactively org-speed-command))
19266 ((functionp org-speed-command)
19267 (funcall org-speed-command))
19268 ((and org-speed-command (listp org-speed-command))
19269 (eval org-speed-command))
19270 (t (let (org-use-speed-commands)
19271 (call-interactively 'org-self-insert-command)))))
19272 ((and
19273 (= N 1)
19274 (not (org-region-active-p))
19275 (org-at-table-p)
19276 (progn
19277 ;; Check if we blank the field, and if that triggers align.
19278 (and (featurep 'org-table)
19279 org-table-auto-blank-field
19280 (memq last-command
19281 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19282 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19283 ;; Got extra space, this field does not determine
19284 ;; column width.
19285 (let (org-table-may-need-update) (org-table-blank-field))
19286 ;; No extra space, this field may determine column
19287 ;; width.
19288 (org-table-blank-field)))
19290 (looking-at "[^|\n]* |"))
19291 ;; There is room for insertion without re-aligning the table.
19292 (self-insert-command N)
19293 (org-table-with-shrunk-field
19294 (save-excursion
19295 (skip-chars-forward "^|")
19296 ;; Do not delete last space, which is
19297 ;; `org-table-separator-space', but the regular space before
19298 ;; it.
19299 (delete-region (- (point) 2) (1- (point))))))
19301 (setq org-table-may-need-update t)
19302 (self-insert-command N)
19303 (org-fix-tags-on-the-fly)
19304 (when org-self-insert-cluster-for-undo
19305 (if (not (eq last-command 'org-self-insert-command))
19306 (setq org-self-insert-command-undo-counter 1)
19307 (if (>= org-self-insert-command-undo-counter 20)
19308 (setq org-self-insert-command-undo-counter 1)
19309 (and (> org-self-insert-command-undo-counter 0)
19310 buffer-undo-list (listp buffer-undo-list)
19311 (not (cadr buffer-undo-list)) ; remove nil entry
19312 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19313 (setq org-self-insert-command-undo-counter
19314 (1+ org-self-insert-command-undo-counter))))))))
19316 (defun org-check-before-invisible-edit (kind)
19317 "Check is editing if kind KIND would be dangerous with invisible text around.
19318 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19319 ;; First, try to get out of here as quickly as possible, to reduce overhead
19320 (when (and org-catch-invisible-edits
19321 (or (not (boundp 'visible-mode)) (not visible-mode))
19322 (or (get-char-property (point) 'invisible)
19323 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19324 ;; OK, we need to take a closer look. Do not consider
19325 ;; invisibility obtained through text properties (e.g., link
19326 ;; fontification), as it cannot be toggled.
19327 (let* ((invisible-at-point
19328 (pcase (get-char-property-and-overlay (point) 'invisible)
19329 (`(,_ . ,(and (pred overlayp) o)) o)))
19330 ;; Assume that point cannot land in the middle of an
19331 ;; overlay, or between two overlays.
19332 (invisible-before-point
19333 (and (not invisible-at-point)
19334 (not (bobp))
19335 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19336 (`(,_ . ,(and (pred overlayp) o)) o))))
19337 (border-and-ok-direction
19339 ;; Check if we are acting predictably before invisible
19340 ;; text.
19341 (and invisible-at-point
19342 (memq kind '(insert delete-backward)))
19343 ;; Check if we are acting predictably after invisible text
19344 ;; This works not well, and I have turned it off. It seems
19345 ;; better to always show and stop after invisible text.
19346 ;; (and (not invisible-at-point) invisible-before-point
19347 ;; (memq kind '(insert delete)))
19349 (when (or invisible-at-point invisible-before-point)
19350 (when (eq org-catch-invisible-edits 'error)
19351 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19352 (if (and org-custom-properties-overlays
19353 (y-or-n-p "Display invisible properties in this buffer? "))
19354 (org-toggle-custom-properties-visibility)
19355 ;; Make the area visible
19356 (save-excursion
19357 (when invisible-before-point
19358 (goto-char
19359 (previous-single-char-property-change (point) 'invisible)))
19360 ;; Remove whatever overlay is currently making yet-to-be
19361 ;; edited text invisible. Also remove nested invisibility
19362 ;; related overlays.
19363 (delete-overlay (or invisible-at-point invisible-before-point))
19364 (let ((origin (if invisible-at-point (point) (1- (point)))))
19365 (while (pcase (get-char-property-and-overlay origin 'invisible)
19366 (`(,_ . ,(and (pred overlayp) o))
19367 (delete-overlay o)
19368 t)))))
19369 (cond
19370 ((eq org-catch-invisible-edits 'show)
19371 ;; That's it, we do the edit after showing
19372 (message
19373 "Unfolding invisible region around point before editing")
19374 (sit-for 1))
19375 ((and (eq org-catch-invisible-edits 'smart)
19376 border-and-ok-direction)
19377 (message "Unfolding invisible region around point before editing"))
19379 ;; Don't do the edit, make the user repeat it in full visibility
19380 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19382 (defun org-fix-tags-on-the-fly ()
19383 "Align tags in headline at point.
19384 Unlike `org-align-tags', this function does nothing if point is
19385 either not currently on a tagged headline or on a tag."
19386 (when (and (org-match-line org-tag-line-re)
19387 (< (point) (match-beginning 1)))
19388 (org-align-tags)))
19390 (defun org-delete-backward-char (N)
19391 "Like `delete-backward-char', insert whitespace at field end in tables.
19392 When deleting backwards, in tables this function will insert whitespace in
19393 front of the next \"|\" separator, to keep the table aligned. The table will
19394 still be marked for re-alignment if the field did fill the entire column,
19395 because, in this case the deletion might narrow the column."
19396 (interactive "p")
19397 (save-match-data
19398 (org-check-before-invisible-edit 'delete-backward)
19399 (if (and (= N 1)
19400 (not overwrite-mode)
19401 (not (org-region-active-p))
19402 (not (eq (char-before) ?|))
19403 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19404 (looking-at-p ".*?|")
19405 (org-at-table-p))
19406 (progn (forward-char -1) (org-delete-char 1))
19407 (backward-delete-char N)
19408 (org-fix-tags-on-the-fly))))
19410 (defun org-delete-char (N)
19411 "Like `delete-char', but insert whitespace at field end in tables.
19412 When deleting characters, in tables this function will insert whitespace in
19413 front of the next \"|\" separator, to keep the table aligned. The table will
19414 still be marked for re-alignment if the field did fill the entire column,
19415 because, in this case the deletion might narrow the column."
19416 (interactive "p")
19417 (save-match-data
19418 (org-check-before-invisible-edit 'delete)
19419 (cond
19420 ((or (/= N 1)
19421 (eq (char-after) ?|)
19422 (save-excursion (skip-chars-backward " \t") (bolp))
19423 (not (org-at-table-p)))
19424 (delete-char N)
19425 (org-fix-tags-on-the-fly))
19426 ((looking-at ".\\(.*?\\)|")
19427 (let* ((update? org-table-may-need-update)
19428 (noalign (looking-at-p ".*? |")))
19429 (delete-char 1)
19430 (org-table-with-shrunk-field
19431 (save-excursion
19432 ;; Last space is `org-table-separator-space', so insert
19433 ;; a regular one before it instead.
19434 (goto-char (- (match-end 0) 2))
19435 (insert " ")))
19436 ;; If there were two spaces at the end, this field does not
19437 ;; determine the width of the column.
19438 (when noalign (setq org-table-may-need-update update?))))
19440 (delete-char N)))))
19442 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19443 (put 'org-self-insert-command 'delete-selection
19444 (lambda ()
19445 (not (run-hook-with-args-until-success
19446 'self-insert-uses-region-functions))))
19447 (put 'orgtbl-self-insert-command 'delete-selection
19448 (lambda ()
19449 (not (run-hook-with-args-until-success
19450 'self-insert-uses-region-functions))))
19451 (put 'org-delete-char 'delete-selection 'supersede)
19452 (put 'org-delete-backward-char 'delete-selection 'supersede)
19453 (put 'org-yank 'delete-selection 'yank)
19455 ;; Make `flyspell-mode' delay after some commands
19456 (put 'org-self-insert-command 'flyspell-delayed t)
19457 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19458 (put 'org-delete-char 'flyspell-delayed t)
19459 (put 'org-delete-backward-char 'flyspell-delayed t)
19461 ;; Make pabbrev-mode expand after Org mode commands
19462 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19463 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19465 (defun org-transpose-words ()
19466 "Transpose words for Org.
19467 This uses the `org-mode-transpose-word-syntax-table' syntax
19468 table, which interprets characters in `org-emphasis-alist' as
19469 word constituents."
19470 (interactive)
19471 (with-syntax-table org-mode-transpose-word-syntax-table
19472 (call-interactively 'transpose-words)))
19474 (defvar org-ctrl-c-ctrl-c-hook nil
19475 "Hook for functions attaching themselves to `C-c C-c'.
19477 This can be used to add additional functionality to the C-c C-c
19478 key which executes context-dependent commands. This hook is run
19479 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19480 run after the last test.
19482 Each function will be called with no arguments. The function
19483 must check if the context is appropriate for it to act. If yes,
19484 it should do its thing and then return a non-nil value. If the
19485 context is wrong, just do nothing and return nil.")
19487 (defvar org-ctrl-c-ctrl-c-final-hook nil
19488 "Hook for functions attaching themselves to `C-c C-c'.
19490 This can be used to add additional functionality to the C-c C-c
19491 key which executes context-dependent commands. This hook is run
19492 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19493 before the first test.
19495 Each function will be called with no arguments. The function
19496 must check if the context is appropriate for it to act. If yes,
19497 it should do its thing and then return a non-nil value. If the
19498 context is wrong, just do nothing and return nil.")
19500 (defvar org-tab-first-hook nil
19501 "Hook for functions to attach themselves to TAB.
19502 See `org-ctrl-c-ctrl-c-hook' for more information.
19503 This hook runs as the first action when TAB is pressed, even before
19504 `org-cycle' messes around with the `outline-regexp' to cater for
19505 inline tasks and plain list item folding.
19506 If any function in this hook returns t, any other actions that
19507 would have been caused by TAB (such as table field motion or visibility
19508 cycling) will not occur.")
19510 (defvar org-tab-after-check-for-table-hook nil
19511 "Hook for functions to attach themselves to TAB.
19512 See `org-ctrl-c-ctrl-c-hook' for more information.
19513 This hook runs after it has been established that the cursor is not in a
19514 table, but before checking if the cursor is in a headline or if global cycling
19515 should be done.
19516 If any function in this hook returns t, not other actions like visibility
19517 cycling will be done.")
19519 (defvar org-tab-after-check-for-cycling-hook nil
19520 "Hook for functions to attach themselves to TAB.
19521 See `org-ctrl-c-ctrl-c-hook' for more information.
19522 This hook runs after it has been established that not table field motion and
19523 not visibility should be done because of current context. This is probably
19524 the place where a package like yasnippets can hook in.")
19526 (defvar org-tab-before-tab-emulation-hook nil
19527 "Hook for functions to attach themselves to TAB.
19528 See `org-ctrl-c-ctrl-c-hook' for more information.
19529 This hook runs after every other options for TAB have been exhausted, but
19530 before indentation and \t insertion takes place.")
19532 (defvar org-metaleft-hook nil
19533 "Hook for functions attaching themselves to `M-left'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-metaright-hook nil
19536 "Hook for functions attaching themselves to `M-right'.
19537 See `org-ctrl-c-ctrl-c-hook' for more information.")
19538 (defvar org-metaup-hook nil
19539 "Hook for functions attaching themselves to `M-up'.
19540 See `org-ctrl-c-ctrl-c-hook' for more information.")
19541 (defvar org-metadown-hook nil
19542 "Hook for functions attaching themselves to `M-down'.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-shiftmetaleft-hook nil
19545 "Hook for functions attaching themselves to `M-S-left'.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-shiftmetaright-hook nil
19548 "Hook for functions attaching themselves to `M-S-right'.
19549 See `org-ctrl-c-ctrl-c-hook' for more information.")
19550 (defvar org-shiftmetaup-hook nil
19551 "Hook for functions attaching themselves to `M-S-up'.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.")
19553 (defvar org-shiftmetadown-hook nil
19554 "Hook for functions attaching themselves to `M-S-down'.
19555 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defvar org-metareturn-hook nil
19557 "Hook for functions attaching themselves to `M-RET'.
19558 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defvar org-shiftup-hook nil
19560 "Hook for functions attaching themselves to `S-up'.
19561 See `org-ctrl-c-ctrl-c-hook' for more information.")
19562 (defvar org-shiftup-final-hook nil
19563 "Hook for functions attaching themselves to `S-up'.
19564 This one runs after all other options except shift-select have been excluded.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-shiftdown-hook nil
19567 "Hook for functions attaching themselves to `S-down'.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-shiftdown-final-hook nil
19570 "Hook for functions attaching themselves to `S-down'.
19571 This one runs after all other options except shift-select have been excluded.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.")
19573 (defvar org-shiftleft-hook nil
19574 "Hook for functions attaching themselves to `S-left'.
19575 See `org-ctrl-c-ctrl-c-hook' for more information.")
19576 (defvar org-shiftleft-final-hook nil
19577 "Hook for functions attaching themselves to `S-left'.
19578 This one runs after all other options except shift-select have been excluded.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.")
19580 (defvar org-shiftright-hook nil
19581 "Hook for functions attaching themselves to `S-right'.
19582 See `org-ctrl-c-ctrl-c-hook' for more information.")
19583 (defvar org-shiftright-final-hook nil
19584 "Hook for functions attaching themselves to `S-right'.
19585 This one runs after all other options except shift-select have been excluded.
19586 See `org-ctrl-c-ctrl-c-hook' for more information.")
19588 (defun org-modifier-cursor-error ()
19589 "Throw an error, a modified cursor command was applied in wrong context."
19590 (user-error "This command is active in special context like tables, headlines or items"))
19592 (defun org-shiftselect-error ()
19593 "Throw an error because Shift-Cursor command was applied in wrong context."
19594 (if (and (boundp 'shift-select-mode) shift-select-mode)
19595 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19596 (user-error "This command works only in special context like headlines or timestamps")))
19598 (defun org-call-for-shift-select (cmd)
19599 (let ((this-command-keys-shift-translated t))
19600 (call-interactively cmd)))
19602 (defun org-shifttab (&optional arg)
19603 "Global visibility cycling or move to previous table field.
19604 Call `org-table-previous-field' within a table.
19605 When ARG is nil, cycle globally through visibility states.
19606 When ARG is a numeric prefix, show contents of this level."
19607 (interactive "P")
19608 (cond
19609 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19610 ((integerp arg)
19611 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19612 (message "Content view to level: %d" arg)
19613 (org-content (prefix-numeric-value arg2))
19614 (org-cycle-show-empty-lines t)
19615 (setq org-cycle-global-status 'overview)))
19616 (t (call-interactively 'org-global-cycle))))
19618 (defun org-shiftmetaleft ()
19619 "Promote subtree or delete table column.
19620 Calls `org-promote-subtree', `org-outdent-item-tree', or
19621 `org-table-delete-column', depending on context. See the
19622 individual commands for more information."
19623 (interactive)
19624 (cond
19625 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19626 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19627 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19628 ((if (not (org-region-active-p)) (org-at-item-p)
19629 (save-excursion (goto-char (region-beginning))
19630 (org-at-item-p)))
19631 (call-interactively 'org-outdent-item-tree))
19632 (t (org-modifier-cursor-error))))
19634 (defun org-shiftmetaright ()
19635 "Demote subtree or insert table column.
19636 Calls `org-demote-subtree', `org-indent-item-tree', or
19637 `org-table-insert-column', depending on context. See the
19638 individual commands for more information."
19639 (interactive)
19640 (cond
19641 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19642 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19643 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19644 ((if (not (org-region-active-p)) (org-at-item-p)
19645 (save-excursion (goto-char (region-beginning))
19646 (org-at-item-p)))
19647 (call-interactively 'org-indent-item-tree))
19648 (t (org-modifier-cursor-error))))
19650 (defun org-shiftmetaup (&optional _arg)
19651 "Drag the line at point up.
19652 In a table, kill the current row.
19653 On a clock timestamp, update the value of the timestamp like `S-<up>'
19654 but also adjust the previous clocked item in the clock history.
19655 Everywhere else, drag the line at point up."
19656 (interactive "P")
19657 (cond
19658 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19659 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19660 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19661 (call-interactively 'org-timestamp-up)))
19662 (t (call-interactively 'org-drag-line-backward))))
19664 (defun org-shiftmetadown (&optional _arg)
19665 "Drag the line at point down.
19666 In a table, insert an empty row at the current line.
19667 On a clock timestamp, update the value of the timestamp like `S-<down>'
19668 but also adjust the previous clocked item in the clock history.
19669 Everywhere else, drag the line at point down."
19670 (interactive "P")
19671 (cond
19672 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19673 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19674 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19675 (call-interactively 'org-timestamp-down)))
19676 (t (call-interactively 'org-drag-line-forward))))
19678 (defsubst org-hidden-tree-error ()
19679 (user-error
19680 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19682 (defun org-metaleft (&optional _arg)
19683 "Promote heading, list item at point or move table column left.
19685 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19686 depending on context. With no specific context, calls the Emacs
19687 default `backward-word'. See the individual commands for more
19688 information.
19690 This function runs the hook `org-metaleft-hook' as a first step,
19691 and returns at first non-nil value."
19692 (interactive "P")
19693 (cond
19694 ((run-hook-with-args-until-success 'org-metaleft-hook))
19695 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19696 ((org-with-limited-levels
19697 (or (org-at-heading-p)
19698 (and (org-region-active-p)
19699 (save-excursion
19700 (goto-char (region-beginning))
19701 (org-at-heading-p)))))
19702 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19703 (call-interactively 'org-do-promote))
19704 ;; At an inline task.
19705 ((org-at-heading-p)
19706 (call-interactively 'org-inlinetask-promote))
19707 ((or (org-at-item-p)
19708 (and (org-region-active-p)
19709 (save-excursion
19710 (goto-char (region-beginning))
19711 (org-at-item-p))))
19712 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19713 (call-interactively 'org-outdent-item))
19714 (t (call-interactively 'backward-word))))
19716 (defun org-metaright (&optional _arg)
19717 "Demote heading, list item at point or move table column right.
19719 In front of a drawer or a block keyword, indent it correctly.
19721 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19722 `org-indent-drawer' or `org-indent-block' depending on context.
19723 With no specific context, calls the Emacs default `forward-word'.
19724 See the individual commands for more information.
19726 This function runs the hook `org-metaright-hook' as a first step,
19727 and returns at first non-nil value."
19728 (interactive "P")
19729 (cond
19730 ((run-hook-with-args-until-success 'org-metaright-hook))
19731 ((org-at-table-p) (call-interactively 'org-table-move-column))
19732 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19733 ((org-at-block-p) (call-interactively 'org-indent-block))
19734 ((org-with-limited-levels
19735 (or (org-at-heading-p)
19736 (and (org-region-active-p)
19737 (save-excursion
19738 (goto-char (region-beginning))
19739 (org-at-heading-p)))))
19740 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19741 (call-interactively 'org-do-demote))
19742 ;; At an inline task.
19743 ((org-at-heading-p)
19744 (call-interactively 'org-inlinetask-demote))
19745 ((or (org-at-item-p)
19746 (and (org-region-active-p)
19747 (save-excursion
19748 (goto-char (region-beginning))
19749 (org-at-item-p))))
19750 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19751 (call-interactively 'org-indent-item))
19752 (t (call-interactively 'forward-word))))
19754 (defun org-check-for-hidden (what)
19755 "Check if there are hidden headlines/items in the current visual line.
19756 WHAT can be either `headlines' or `items'. If the current line is
19757 an outline or item heading and it has a folded subtree below it,
19758 this function returns t, nil otherwise."
19759 (let ((re (cond
19760 ((eq what 'headlines) org-outline-regexp-bol)
19761 ((eq what 'items) (org-item-beginning-re))
19762 (t (error "This should not happen"))))
19763 beg end)
19764 (save-excursion
19765 (catch 'exit
19766 (unless (org-region-active-p)
19767 (setq beg (point-at-bol))
19768 (beginning-of-line 2)
19769 (while (and (not (eobp)) ;; this is like `next-line'
19770 (get-char-property (1- (point)) 'invisible))
19771 (beginning-of-line 2))
19772 (setq end (point))
19773 (goto-char beg)
19774 (goto-char (point-at-eol))
19775 (setq end (max end (point)))
19776 (while (re-search-forward re end t)
19777 (when (get-char-property (match-beginning 0) 'invisible)
19778 (throw 'exit t))))
19779 nil))))
19781 (defun org-metaup (&optional _arg)
19782 "Move subtree up or move table row up.
19783 Calls `org-move-subtree-up' or `org-table-move-row' or
19784 `org-move-item-up', depending on context. See the individual commands
19785 for more information."
19786 (interactive "P")
19787 (cond
19788 ((run-hook-with-args-until-success 'org-metaup-hook))
19789 ((org-region-active-p)
19790 (let* ((a (min (region-beginning) (region-end)))
19791 (b (1- (max (region-beginning) (region-end))))
19792 (c (save-excursion (goto-char a)
19793 (move-beginning-of-line 0)))
19794 (d (save-excursion (goto-char a)
19795 (move-end-of-line 0) (point))))
19796 (transpose-regions a b c d)
19797 (goto-char c)))
19798 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19799 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19800 ((org-at-item-p) (call-interactively 'org-move-item-up))
19801 (t (org-drag-element-backward))))
19803 (defun org-metadown (&optional _arg)
19804 "Move subtree down or move table row down.
19805 Calls `org-move-subtree-down' or `org-table-move-row' or
19806 `org-move-item-down', depending on context. See the individual
19807 commands for more information."
19808 (interactive "P")
19809 (cond
19810 ((run-hook-with-args-until-success 'org-metadown-hook))
19811 ((org-region-active-p)
19812 (let* ((a (min (region-beginning) (region-end)))
19813 (b (max (region-beginning) (region-end)))
19814 (c (save-excursion (goto-char b)
19815 (move-beginning-of-line 1)))
19816 (d (save-excursion (goto-char b)
19817 (move-end-of-line 1) (1+ (point)))))
19818 (transpose-regions a b c d)
19819 (goto-char d)))
19820 ((org-at-table-p) (call-interactively 'org-table-move-row))
19821 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19822 ((org-at-item-p) (call-interactively 'org-move-item-down))
19823 (t (org-drag-element-forward))))
19825 (defun org-shiftup (&optional arg)
19826 "Increase item in timestamp or increase priority of current headline.
19827 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19828 depending on context. See the individual commands for more information."
19829 (interactive "P")
19830 (cond
19831 ((run-hook-with-args-until-success 'org-shiftup-hook))
19832 ((and org-support-shift-select (org-region-active-p))
19833 (org-call-for-shift-select 'previous-line))
19834 ((org-at-timestamp-p 'lax)
19835 (call-interactively (if org-edit-timestamp-down-means-later
19836 'org-timestamp-down 'org-timestamp-up)))
19837 ((and (not (eq org-support-shift-select 'always))
19838 org-enable-priority-commands
19839 (org-at-heading-p))
19840 (call-interactively 'org-priority-up))
19841 ((and (not org-support-shift-select) (org-at-item-p))
19842 (call-interactively 'org-previous-item))
19843 ((org-clocktable-try-shift 'up arg))
19844 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19845 (org-support-shift-select
19846 (org-call-for-shift-select 'previous-line))
19847 (t (org-shiftselect-error))))
19849 (defun org-shiftdown (&optional arg)
19850 "Decrease item in timestamp or decrease priority of current headline.
19851 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19852 depending on context. See the individual commands for more information."
19853 (interactive "P")
19854 (cond
19855 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19856 ((and org-support-shift-select (org-region-active-p))
19857 (org-call-for-shift-select 'next-line))
19858 ((org-at-timestamp-p 'lax)
19859 (call-interactively (if org-edit-timestamp-down-means-later
19860 'org-timestamp-up 'org-timestamp-down)))
19861 ((and (not (eq org-support-shift-select 'always))
19862 org-enable-priority-commands
19863 (org-at-heading-p))
19864 (call-interactively 'org-priority-down))
19865 ((and (not org-support-shift-select) (org-at-item-p))
19866 (call-interactively 'org-next-item))
19867 ((org-clocktable-try-shift 'down arg))
19868 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19869 (org-support-shift-select
19870 (org-call-for-shift-select 'next-line))
19871 (t (org-shiftselect-error))))
19873 (defun org-shiftright (&optional arg)
19874 "Cycle the thing at point or in the current line, depending on context.
19875 Depending on context, this does one of the following:
19877 - switch a timestamp at point one day into the future
19878 - on a headline, switch to the next TODO keyword.
19879 - on an item, switch entire list to the next bullet type
19880 - on a property line, switch to the next allowed value
19881 - on a clocktable definition line, move time block into the future"
19882 (interactive "P")
19883 (cond
19884 ((run-hook-with-args-until-success 'org-shiftright-hook))
19885 ((and org-support-shift-select (org-region-active-p))
19886 (org-call-for-shift-select 'forward-char))
19887 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19888 ((and (not (eq org-support-shift-select 'always))
19889 (org-at-heading-p))
19890 (let ((org-inhibit-logging
19891 (not org-treat-S-cursor-todo-selection-as-state-change))
19892 (org-inhibit-blocking
19893 (not org-treat-S-cursor-todo-selection-as-state-change)))
19894 (org-call-with-arg 'org-todo 'right)))
19895 ((or (and org-support-shift-select
19896 (not (eq org-support-shift-select 'always))
19897 (org-at-item-bullet-p))
19898 (and (not org-support-shift-select) (org-at-item-p)))
19899 (org-call-with-arg 'org-cycle-list-bullet nil))
19900 ((and (not (eq org-support-shift-select 'always))
19901 (org-at-property-p))
19902 (call-interactively 'org-property-next-allowed-value))
19903 ((org-clocktable-try-shift 'right arg))
19904 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19905 (org-support-shift-select
19906 (org-call-for-shift-select 'forward-char))
19907 (t (org-shiftselect-error))))
19909 (defun org-shiftleft (&optional arg)
19910 "Cycle the thing at point or in the current line, depending on context.
19911 Depending on context, this does one of the following:
19913 - switch a timestamp at point one day into the past
19914 - on a headline, switch to the previous TODO keyword.
19915 - on an item, switch entire list to the previous bullet type
19916 - on a property line, switch to the previous allowed value
19917 - on a clocktable definition line, move time block into the past"
19918 (interactive "P")
19919 (cond
19920 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19921 ((and org-support-shift-select (org-region-active-p))
19922 (org-call-for-shift-select 'backward-char))
19923 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19924 ((and (not (eq org-support-shift-select 'always))
19925 (org-at-heading-p))
19926 (let ((org-inhibit-logging
19927 (not org-treat-S-cursor-todo-selection-as-state-change))
19928 (org-inhibit-blocking
19929 (not org-treat-S-cursor-todo-selection-as-state-change)))
19930 (org-call-with-arg 'org-todo 'left)))
19931 ((or (and org-support-shift-select
19932 (not (eq org-support-shift-select 'always))
19933 (org-at-item-bullet-p))
19934 (and (not org-support-shift-select) (org-at-item-p)))
19935 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19936 ((and (not (eq org-support-shift-select 'always))
19937 (org-at-property-p))
19938 (call-interactively 'org-property-previous-allowed-value))
19939 ((org-clocktable-try-shift 'left arg))
19940 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19941 (org-support-shift-select
19942 (org-call-for-shift-select 'backward-char))
19943 (t (org-shiftselect-error))))
19945 (defun org-shiftcontrolright ()
19946 "Switch to next TODO set."
19947 (interactive)
19948 (cond
19949 ((and org-support-shift-select (org-region-active-p))
19950 (org-call-for-shift-select 'forward-word))
19951 ((and (not (eq org-support-shift-select 'always))
19952 (org-at-heading-p))
19953 (org-call-with-arg 'org-todo 'nextset))
19954 (org-support-shift-select
19955 (org-call-for-shift-select 'forward-word))
19956 (t (org-shiftselect-error))))
19958 (defun org-shiftcontrolleft ()
19959 "Switch to previous TODO set."
19960 (interactive)
19961 (cond
19962 ((and org-support-shift-select (org-region-active-p))
19963 (org-call-for-shift-select 'backward-word))
19964 ((and (not (eq org-support-shift-select 'always))
19965 (org-at-heading-p))
19966 (org-call-with-arg 'org-todo 'previousset))
19967 (org-support-shift-select
19968 (org-call-for-shift-select 'backward-word))
19969 (t (org-shiftselect-error))))
19971 (defun org-shiftcontrolup (&optional n)
19972 "Change timestamps synchronously up in CLOCK log lines.
19973 Optional argument N tells to change by that many units."
19974 (interactive "P")
19975 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19976 (let (org-support-shift-select)
19977 (org-clock-timestamps-up n))
19978 (user-error "Not at a clock log")))
19980 (defun org-shiftcontroldown (&optional n)
19981 "Change timestamps synchronously down in CLOCK log lines.
19982 Optional argument N tells to change by that many units."
19983 (interactive "P")
19984 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19985 (let (org-support-shift-select)
19986 (org-clock-timestamps-down n))
19987 (user-error "Not at a clock log")))
19989 (defun org-increase-number-at-point (&optional inc)
19990 "Increment the number at point.
19991 With an optional prefix numeric argument INC, increment using
19992 this numeric value."
19993 (interactive "p")
19994 (if (not (number-at-point))
19995 (user-error "Not on a number")
19996 (unless inc (setq inc 1))
19997 (let ((pos (point))
19998 (beg (skip-chars-backward "-+^/*0-9eE."))
19999 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20000 (setq nap (buffer-substring-no-properties
20001 (+ pos beg) (+ pos beg end)))
20002 (delete-region (+ pos beg) (+ pos beg end))
20003 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20004 (when (org-at-table-p)
20005 (org-table-align)
20006 (org-table-end-of-field 1))))
20008 (defun org-decrease-number-at-point (&optional inc)
20009 "Decrement the number at point.
20010 With an optional prefix numeric argument INC, decrement using
20011 this numeric value."
20012 (interactive "p")
20013 (org-increase-number-at-point (- (or inc 1))))
20015 (defun org-ctrl-c-ret ()
20016 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20017 (interactive)
20018 (cond
20019 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20020 (t (call-interactively 'org-insert-heading))))
20022 (defun org-find-visible ()
20023 (let ((s (point)))
20024 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20025 (get-char-property s 'invisible)))
20027 (defun org-find-invisible ()
20028 (let ((s (point)))
20029 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20030 (not (get-char-property s 'invisible))))
20033 (defun org-copy-visible (beg end)
20034 "Copy the visible parts of the region."
20035 (interactive "r")
20036 (let ((result ""))
20037 (while (/= beg end)
20038 (when (get-char-property beg 'invisible)
20039 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20040 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20041 (setq result (concat result (buffer-substring beg next)))
20042 (setq beg next)))
20043 (kill-new result)
20044 (message "Visible strings have been copied to the kill ring.")))
20046 (defun org-copy-special ()
20047 "Copy region in table or copy current subtree.
20048 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20049 context. See the individual commands for more information."
20050 (interactive)
20051 (call-interactively
20052 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20054 (defun org-cut-special ()
20055 "Cut region in table or cut current subtree.
20056 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20057 context. See the individual commands for more information."
20058 (interactive)
20059 (call-interactively
20060 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20062 (defun org-paste-special (arg)
20063 "Paste rectangular region into table, or past subtree relative to level.
20064 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20065 See the individual commands for more information."
20066 (interactive "P")
20067 (if (org-at-table-p)
20068 (org-table-paste-rectangle)
20069 (org-paste-subtree arg)))
20071 (defun org-edit-special (&optional arg)
20072 "Call a special editor for the element at point.
20073 When at a table, call the formula editor with `org-table-edit-formulas'.
20074 When in a source code block, call `org-edit-src-code'.
20075 When in a fixed-width region, call `org-edit-fixed-width-region'.
20076 When in an export block, call `org-edit-export-block'.
20077 When in a LaTeX environment, call `org-edit-latex-environment'.
20078 When at an #+INCLUDE keyword, visit the included file.
20079 When at a footnote reference, call `org-edit-footnote-reference'
20080 On a link, call `ffap' to visit the link at point.
20081 Otherwise, return a user error."
20082 (interactive "P")
20083 (let ((element (org-element-at-point)))
20084 (barf-if-buffer-read-only)
20085 (pcase (org-element-type element)
20086 (`src-block
20087 (if (not arg) (org-edit-src-code)
20088 (let* ((info (org-babel-get-src-block-info))
20089 (lang (nth 0 info))
20090 (params (nth 2 info))
20091 (session (cdr (assq :session params))))
20092 (if (not session) (org-edit-src-code)
20093 ;; At a src-block with a session and function called with
20094 ;; an ARG: switch to the buffer related to the inferior
20095 ;; process.
20096 (switch-to-buffer
20097 (funcall (intern (concat "org-babel-prep-session:" lang))
20098 session params))))))
20099 (`keyword
20100 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20101 (org-open-link-from-string
20102 (format "[[%s]]"
20103 (expand-file-name
20104 (let ((value (org-element-property :value element)))
20105 (cond ((org-file-url-p value)
20106 (user-error "The file is specified as a URL, cannot be edited"))
20107 ((not (org-string-nw-p value))
20108 (user-error "No file to edit"))
20109 ((string-match "\\`\"\\(.*?\\)\"" value)
20110 (match-string 1 value))
20111 ((string-match "\\`[^ \t\"]\\S-*" value)
20112 (match-string 0 value))
20113 (t (user-error "No valid file specified")))))))
20114 (user-error "No special environment to edit here")))
20115 (`table
20116 (if (eq (org-element-property :type element) 'table.el)
20117 (org-edit-table.el)
20118 (call-interactively 'org-table-edit-formulas)))
20119 ;; Only Org tables contain `table-row' type elements.
20120 (`table-row (call-interactively 'org-table-edit-formulas))
20121 (`example-block (org-edit-src-code))
20122 (`export-block (org-edit-export-block))
20123 (`fixed-width (org-edit-fixed-width-region))
20124 (`latex-environment (org-edit-latex-environment))
20126 ;; No notable element at point. Though, we may be at a link or
20127 ;; a footnote reference, which are objects. Thus, scan deeper.
20128 (let ((context (org-element-context element)))
20129 (pcase (org-element-type context)
20130 (`footnote-reference (org-edit-footnote-reference))
20131 (`inline-src-block (org-edit-inline-src-code))
20132 (`link (call-interactively #'ffap))
20133 (_ (user-error "No special environment to edit here"))))))))
20135 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20136 (defun org-ctrl-c-ctrl-c (&optional arg)
20137 "Set tags in headline, or update according to changed information at point.
20139 This command does many different things, depending on context:
20141 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20142 this is what we do.
20144 - If the cursor is on a statistics cookie, update it.
20146 - If the cursor is in a headline, prompt for tags and insert them
20147 into the current line, aligned to `org-tags-column'. When called
20148 with prefix arg, realign all tags in the current buffer.
20150 - If the cursor is in one of the special #+KEYWORD lines, this
20151 triggers scanning the buffer for these lines and updating the
20152 information.
20154 - If the cursor is inside a table, realign the table. This command
20155 works even if the automatic table editor has been turned off.
20157 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20158 the entire table.
20160 - If the cursor is at a footnote reference or definition, jump to
20161 the corresponding definition or references, respectively.
20163 - If the cursor is a the beginning of a dynamic block, update it.
20165 - If the current buffer is a capture buffer, close note and file it.
20167 - If the cursor is on a <<<target>>>, update radio targets and
20168 corresponding links in this buffer.
20170 - If the cursor is on a numbered item in a plain list, renumber the
20171 ordered list.
20173 - If the cursor is on a checkbox, toggle it.
20175 - If the cursor is on a code block, evaluate it. The variable
20176 `org-confirm-babel-evaluate' can be used to control prompting
20177 before code block evaluation, by default every code block
20178 evaluation requires confirmation. Code block evaluation can be
20179 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20180 (interactive "P")
20181 (cond
20182 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20183 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20184 (org-remove-occur-highlights)
20185 (message "Temporary highlights/overlays removed from current buffer"))
20186 ((and (local-variable-p 'org-finish-function)
20187 (fboundp org-finish-function))
20188 (funcall org-finish-function))
20189 ((org-babel-hash-at-point))
20190 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20192 (let* ((context
20193 (org-element-lineage
20194 (org-element-context)
20195 ;; Limit to supported contexts.
20196 '(babel-call clock dynamic-block footnote-definition
20197 footnote-reference inline-babel-call inline-src-block
20198 inlinetask item keyword node-property paragraph
20199 plain-list planning property-drawer radio-target
20200 src-block statistics-cookie table table-cell table-row
20201 timestamp)
20203 (type (org-element-type context)))
20204 ;; For convenience: at the first line of a paragraph on the same
20205 ;; line as an item, apply function on that item instead.
20206 (when (eq type 'paragraph)
20207 (let ((parent (org-element-property :parent context)))
20208 (when (and (eq (org-element-type parent) 'item)
20209 (= (line-beginning-position)
20210 (org-element-property :begin parent)))
20211 (setq context parent)
20212 (setq type 'item))))
20213 ;; Act according to type of element or object at point.
20215 ;; Do nothing on a blank line, except if it is contained in
20216 ;; a src block. Hence, we first check if point is in such
20217 ;; a block and then if it is at a blank line.
20218 (pcase type
20219 ((or `inline-src-block `src-block)
20220 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20221 (org-babel-eval-wipe-error-buffer)
20222 (org-babel-execute-src-block
20223 current-prefix-arg (org-babel-get-src-block-info nil context))))
20224 ((guard (org-match-line "[ \t]*$"))
20225 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20226 (user-error
20227 (substitute-command-keys
20228 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20229 ((or `babel-call `inline-babel-call)
20230 (let ((info (org-babel-lob-get-info context)))
20231 (when info (org-babel-execute-src-block nil info))))
20232 (`clock (org-clock-update-time-maybe))
20233 (`dynamic-block
20234 (save-excursion
20235 (goto-char (org-element-property :post-affiliated context))
20236 (org-update-dblock)))
20237 (`footnote-definition
20238 (goto-char (org-element-property :post-affiliated context))
20239 (call-interactively 'org-footnote-action))
20240 (`footnote-reference (call-interactively #'org-footnote-action))
20241 ((or `headline `inlinetask)
20242 (save-excursion (goto-char (org-element-property :begin context))
20243 (call-interactively #'org-set-tags-command)))
20244 (`item
20245 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20246 ;; unconditionally, whereas `C-u' will toggle its presence.
20247 ;; Without a universal argument, if the item has a checkbox,
20248 ;; toggle it. Otherwise repair the list.
20249 (let* ((box (org-element-property :checkbox context))
20250 (struct (org-element-property :structure context))
20251 (old-struct (copy-tree struct))
20252 (parents (org-list-parents-alist struct))
20253 (prevs (org-list-prevs-alist struct))
20254 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20255 (org-list-set-checkbox
20256 (org-element-property :begin context) struct
20257 (cond ((equal arg '(16)) "[-]")
20258 ((and (not box) (equal arg '(4))) "[ ]")
20259 ((or (not box) (equal arg '(4))) nil)
20260 ((eq box 'on) "[ ]")
20261 (t "[X]")))
20262 ;; Mimic `org-list-write-struct' but with grabbing a return
20263 ;; value from `org-list-struct-fix-box'.
20264 (org-list-struct-fix-ind struct parents 2)
20265 (org-list-struct-fix-item-end struct)
20266 (org-list-struct-fix-bul struct prevs)
20267 (org-list-struct-fix-ind struct parents)
20268 (let ((block-item
20269 (org-list-struct-fix-box struct parents prevs orderedp)))
20270 (if (and box (equal struct old-struct))
20271 (if (equal arg '(16))
20272 (message "Checkboxes already reset")
20273 (user-error "Cannot toggle this checkbox: %s"
20274 (if (eq box 'on)
20275 "all subitems checked"
20276 "unchecked subitems")))
20277 (org-list-struct-apply-struct struct old-struct)
20278 (org-update-checkbox-count-maybe))
20279 (when block-item
20280 (message "Checkboxes were removed due to empty box at line %d"
20281 (org-current-line block-item))))))
20282 (`keyword
20283 (let ((org-inhibit-startup-visibility-stuff t)
20284 (org-startup-align-all-tables nil))
20285 (when (boundp 'org-table-coordinate-overlays)
20286 (mapc #'delete-overlay org-table-coordinate-overlays)
20287 (setq org-table-coordinate-overlays nil))
20288 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20289 (message "Local setup has been refreshed"))
20290 (`plain-list
20291 ;; At a plain list, with a double C-u argument, set
20292 ;; checkboxes of each item to "[-]", whereas a single one
20293 ;; will toggle their presence according to the state of the
20294 ;; first item in the list. Without an argument, repair the
20295 ;; list.
20296 (let* ((begin (org-element-property :contents-begin context))
20297 (struct (org-element-property :structure context))
20298 (old-struct (copy-tree struct))
20299 (first-box (save-excursion
20300 (goto-char begin)
20301 (looking-at org-list-full-item-re)
20302 (match-string-no-properties 3)))
20303 (new-box (cond ((equal arg '(16)) "[-]")
20304 ((equal arg '(4)) (unless first-box "[ ]"))
20305 ((equal first-box "[X]") "[ ]")
20306 (t "[X]"))))
20307 (cond
20308 (arg
20309 (dolist (pos
20310 (org-list-get-all-items
20311 begin struct (org-list-prevs-alist struct)))
20312 (org-list-set-checkbox pos struct new-box)))
20313 ((and first-box (eq (point) begin))
20314 ;; For convenience, when point is at bol on the first
20315 ;; item of the list and no argument is provided, simply
20316 ;; toggle checkbox of that item, if any.
20317 (org-list-set-checkbox begin struct new-box)))
20318 (when (equal
20319 (org-list-write-struct
20320 struct (org-list-parents-alist struct) old-struct)
20321 old-struct)
20322 (message "Cannot update this checkbox"))
20323 (org-update-checkbox-count-maybe)))
20324 ((or `property-drawer `node-property)
20325 (call-interactively #'org-property-action))
20326 (`radio-target
20327 (call-interactively #'org-update-radio-target-regexp))
20328 (`statistics-cookie
20329 (call-interactively #'org-update-statistics-cookies))
20330 ((or `table `table-cell `table-row)
20331 ;; At a table, recalculate every field and align it. Also
20332 ;; send the table if necessary. If the table has
20333 ;; a `table.el' type, just give up. At a table row or cell,
20334 ;; maybe recalculate line but always align table.
20335 (if (eq (org-element-property :type context) 'table.el)
20336 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20337 Use `\\[org-edit-special]' to edit table.el tables"))
20338 (if (or (eq type 'table)
20339 ;; Check if point is at a TBLFM line.
20340 (and (eq type 'table-row)
20341 (= (point) (org-element-property :end context))))
20342 (save-excursion
20343 (if (org-at-TBLFM-p)
20344 (progn (require 'org-table)
20345 (org-table-calc-current-TBLFM))
20346 (goto-char (org-element-property :contents-begin context))
20347 (org-call-with-arg 'org-table-recalculate (or arg t))
20348 (orgtbl-send-table 'maybe)))
20349 (org-table-maybe-eval-formula)
20350 (cond (arg (call-interactively #'org-table-recalculate))
20351 ((org-table-maybe-recalculate-line))
20352 (t (org-table-align))))))
20353 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20354 (org-timestamp-change 0 'day))
20355 ((and `nil (guard (org-at-heading-p)))
20356 ;; When point is on an unsupported object type, we can miss
20357 ;; the fact that it also is at a heading. Handle it here.
20358 (call-interactively #'org-set-tags-command))
20359 ((guard
20360 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20362 (user-error
20363 (substitute-command-keys
20364 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20366 (defun org-mode-restart ()
20367 (interactive)
20368 (let ((indent-status (bound-and-true-p org-indent-mode)))
20369 (funcall major-mode)
20370 (hack-local-variables)
20371 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20372 (org-indent-mode -1))
20373 (org-reset-file-cache))
20374 (message "%s restarted" major-mode))
20376 (defun org-kill-note-or-show-branches ()
20377 "Abort storing current note, or call `outline-show-branches'."
20378 (interactive)
20379 (if (not org-finish-function)
20380 (save-excursion
20381 (save-restriction
20382 (org-narrow-to-subtree)
20383 (org-flag-subtree t)
20384 (call-interactively 'outline-show-branches)
20385 (org-hide-archived-subtrees (point-min) (point-max))))
20386 (let ((org-note-abort t))
20387 (funcall org-finish-function))))
20389 (defun org-delete-indentation (&optional arg)
20390 "Join current line to previous and fix whitespace at join.
20392 If previous line is a headline add to headline title. Otherwise
20393 the function calls `delete-indentation'.
20395 With a non-nil optional argument, join it to the following one."
20396 (interactive "*P")
20397 (if (save-excursion
20398 (beginning-of-line (if arg 1 0))
20399 (let ((case-fold-search nil))
20400 (looking-at org-complex-heading-regexp)))
20401 ;; At headline.
20402 (let ((tags-column (when (match-beginning 5)
20403 (save-excursion (goto-char (match-beginning 5))
20404 (current-column))))
20405 (string (concat " " (progn (when arg (forward-line 1))
20406 (org-trim (delete-and-extract-region
20407 (line-beginning-position)
20408 (line-end-position)))))))
20409 (unless (bobp) (delete-region (point) (1- (point))))
20410 (goto-char (or (match-end 4)
20411 (match-beginning 5)
20412 (match-end 0)))
20413 (skip-chars-backward " \t")
20414 (save-excursion (insert string))
20415 ;; Adjust alignment of tags.
20416 (cond
20417 ((not tags-column)) ;no tags
20418 (org-auto-align-tags (org-align-tags))
20419 (t (org--align-tags-here tags-column)))) ;preserve tags column
20420 (delete-indentation arg)))
20422 (defun org-open-line (n)
20423 "Insert a new row in tables, call `open-line' elsewhere.
20424 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20425 As a special case, when a document starts with a table, allow to
20426 call `open-line' on the very first character."
20427 (interactive "*p")
20428 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20429 (org-table-insert-row)
20430 (open-line n)))
20432 (defun org-return (&optional indent)
20433 "Goto next table row or insert a newline.
20435 Calls `org-table-next-row' or `newline', depending on context.
20437 When optional INDENT argument is non-nil, call
20438 `newline-and-indent' instead of `newline'.
20440 When `org-return-follows-link' is non-nil and point is on
20441 a timestamp or a link, call `org-open-at-point'. However, it
20442 will not happen if point is in a table or on a \"dead\"
20443 object (e.g., within a comment). In these case, you need to use
20444 `org-open-at-point' directly."
20445 (interactive)
20446 (let ((context (if org-return-follows-link (org-element-context)
20447 (org-element-at-point))))
20448 (cond
20449 ;; In a table, call `org-table-next-row'. However, before first
20450 ;; column or after last one, split the table.
20451 ((or (and (eq (org-element-type context) 'table)
20452 (>= (point) (org-element-property :contents-begin context))
20453 (< (point) (org-element-property :contents-end context)))
20454 (org-element-lineage context '(table-row table-cell) t))
20455 (if (or (looking-at-p "[ \t]*$")
20456 (save-excursion (skip-chars-backward " \t") (bolp)))
20457 (insert "\n")
20458 (org-table-justify-field-maybe)
20459 (call-interactively #'org-table-next-row)))
20460 ;; On a link or a timestamp, call `org-open-at-point' if
20461 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20462 ;; locations, e.g., in a comment, as `org-open-at-point'.
20463 ((and org-return-follows-link
20464 (or (and (eq 'link (org-element-type context))
20465 ;; Ensure point is not on the white spaces after
20466 ;; the link.
20467 (let ((origin (point)))
20468 (org-with-point-at (org-element-property :end context)
20469 (skip-chars-backward " \t")
20470 (> (point) origin))))
20471 (org-in-regexp org-ts-regexp-both nil t)
20472 (org-in-regexp org-tsr-regexp-both nil t)
20473 (org-in-regexp org-any-link-re nil t)))
20474 (call-interactively #'org-open-at-point))
20475 ;; Insert newline in heading, but preserve tags.
20476 ((and (not (bolp))
20477 (save-excursion (beginning-of-line)
20478 (let ((case-fold-search nil))
20479 (looking-at org-complex-heading-regexp))))
20480 ;; At headline. Split line. However, if point is on keyword,
20481 ;; priority cookie or tags, do not break any of them: add
20482 ;; a newline after the headline instead.
20483 (let ((tags-column (and (match-beginning 5)
20484 (save-excursion (goto-char (match-beginning 5))
20485 (current-column))))
20486 (string
20487 (when (and (match-end 4) (org-point-in-group (point) 4))
20488 (delete-and-extract-region (point) (match-end 4)))))
20489 ;; Adjust tag alignment.
20490 (cond
20491 ((not (and tags-column string)))
20492 (org-auto-align-tags (org-align-tags))
20493 (t (org--align-tags-here tags-column))) ;preserve tags column
20494 (end-of-line)
20495 (org-show-entry)
20496 (if indent (newline-and-indent) (newline))
20497 (when string (save-excursion (insert (org-trim string))))))
20498 ;; In a list, make sure indenting keeps trailing text within.
20499 ((and indent
20500 (not (eolp))
20501 (org-element-lineage context '(item)))
20502 (let ((trailing-data
20503 (delete-and-extract-region (point) (line-end-position))))
20504 (newline-and-indent)
20505 (save-excursion (insert trailing-data))))
20507 ;; Do not auto-fill when point is in an Org property drawer.
20508 (let ((auto-fill-function (and (not (org-at-property-p))
20509 auto-fill-function)))
20510 (if indent
20511 (newline-and-indent)
20512 (newline)))))))
20514 (defun org-return-indent ()
20515 "Goto next table row or insert a newline and indent.
20516 Calls `org-table-next-row' or `newline-and-indent', depending on
20517 context. See the individual commands for more information."
20518 (interactive)
20519 (org-return t))
20521 (defun org-ctrl-c-tab (&optional _arg)
20522 "Toggle columns width in a table, or show children.
20523 Call `org-table-toggle-column-width' if point is in a table.
20524 Otherwise, call `org-show-children'."
20525 (interactive "p")
20526 (call-interactively
20527 (if (org-at-table-p) #'org-table-toggle-column-width
20528 #'org-show-children)))
20530 (defun org-ctrl-c-star ()
20531 "Compute table, or change heading status of lines.
20532 Calls `org-table-recalculate' or `org-toggle-heading',
20533 depending on context."
20534 (interactive)
20535 (cond
20536 ((org-at-table-p)
20537 (call-interactively 'org-table-recalculate))
20539 ;; Convert all lines in region to list items
20540 (call-interactively 'org-toggle-heading))))
20542 (defun org-ctrl-c-minus ()
20543 "Insert separator line in table or modify bullet status of line.
20544 Also turns a plain line or a region of lines into list items.
20545 Calls `org-table-insert-hline', `org-toggle-item', or
20546 `org-cycle-list-bullet', depending on context."
20547 (interactive)
20548 (cond
20549 ((org-at-table-p)
20550 (call-interactively 'org-table-insert-hline))
20551 ((org-region-active-p)
20552 (call-interactively 'org-toggle-item))
20553 ((org-in-item-p)
20554 (call-interactively 'org-cycle-list-bullet))
20556 (call-interactively 'org-toggle-item))))
20558 (defun org-toggle-heading (&optional nstars)
20559 "Convert headings to normal text, or items or text to headings.
20560 If there is no active region, only convert the current line.
20562 With a `\\[universal-argument]' prefix, convert the whole list at
20563 point into heading.
20565 In a region:
20567 - If the first non blank line is a headline, remove the stars
20568 from all headlines in the region.
20570 - If it is a normal line, turn each and every normal line (i.e.,
20571 not an heading or an item) in the region into headings. If you
20572 want to convert only the first line of this region, use one
20573 universal prefix argument.
20575 - If it is a plain list item, turn all plain list items into headings.
20577 When converting a line into a heading, the number of stars is chosen
20578 such that the lines become children of the current entry. However,
20579 when a numeric prefix argument is given, its value determines the
20580 number of stars to add."
20581 (interactive "P")
20582 (let ((skip-blanks
20583 (function
20584 ;; Return beginning of first non-blank line, starting from
20585 ;; line at POS.
20586 (lambda (pos)
20587 (save-excursion
20588 (goto-char pos)
20589 (while (org-at-comment-p) (forward-line))
20590 (skip-chars-forward " \r\t\n")
20591 (point-at-bol)))))
20592 beg end toggled)
20593 ;; Determine boundaries of changes. If a universal prefix has
20594 ;; been given, put the list in a region. If region ends at a bol,
20595 ;; do not consider the last line to be in the region.
20597 (when (and current-prefix-arg (org-at-item-p))
20598 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20599 (org-mark-element))
20601 (if (org-region-active-p)
20602 (setq beg (funcall skip-blanks (region-beginning))
20603 end (copy-marker (save-excursion
20604 (goto-char (region-end))
20605 (if (bolp) (point) (point-at-eol)))))
20606 (setq beg (funcall skip-blanks (point-at-bol))
20607 end (copy-marker (point-at-eol))))
20608 ;; Ensure inline tasks don't count as headings.
20609 (org-with-limited-levels
20610 (save-excursion
20611 (goto-char beg)
20612 (cond
20613 ;; Case 1. Started at an heading: de-star headings.
20614 ((org-at-heading-p)
20615 (while (< (point) end)
20616 (when (org-at-heading-p t)
20617 (looking-at org-outline-regexp) (replace-match "")
20618 (setq toggled t))
20619 (forward-line)))
20620 ;; Case 2. Started at an item: change items into headlines.
20621 ;; One star will be added by `org-list-to-subtree'.
20622 ((org-at-item-p)
20623 (while (< (point) end)
20624 (when (org-at-item-p)
20625 ;; Pay attention to cases when region ends before list.
20626 (let* ((struct (org-list-struct))
20627 (list-end
20628 (min (org-list-get-bottom-point struct) (1+ end))))
20629 (save-restriction
20630 (narrow-to-region (point) list-end)
20631 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20632 (setq toggled t))
20633 (forward-line)))
20634 ;; Case 3. Started at normal text: make every line an heading,
20635 ;; skipping headlines and items.
20636 (t (let* ((stars
20637 (make-string
20638 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20639 (add-stars
20640 (cond (nstars "") ; stars from prefix only
20641 ((equal stars "") "*") ; before first heading
20642 (org-odd-levels-only "**") ; inside heading, odd
20643 (t "*"))) ; inside heading, oddeven
20644 (rpl (concat stars add-stars " "))
20645 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20646 (while (< (point) (if (equal nstars '(4)) lend end))
20647 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20648 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20649 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20650 (forward-line)))))))
20651 (unless toggled (message "Cannot toggle heading from here"))))
20653 (defun org-meta-return (&optional arg)
20654 "Insert a new heading or wrap a region in a table.
20655 Calls `org-insert-heading', `org-insert-item' or
20656 `org-table-wrap-region', depending on context. When called with
20657 an argument, unconditionally call `org-insert-heading'."
20658 (interactive "P")
20659 (org-check-before-invisible-edit 'insert)
20660 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20661 (call-interactively (cond (arg #'org-insert-heading)
20662 ((org-at-table-p) #'org-table-wrap-region)
20663 ((org-in-item-p) #'org-insert-item)
20664 (t #'org-insert-heading)))))
20666 ;;; Menu entries
20668 (defsubst org-in-subtree-not-table-p ()
20669 "Are we in a subtree and not in a table?"
20670 (and (not (org-before-first-heading-p))
20671 (not (org-at-table-p))))
20673 ;; Define the Org mode menus
20674 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20675 '("Tbl"
20676 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20677 ["Next Field" org-cycle (org-at-table-p)]
20678 ["Previous Field" org-shifttab (org-at-table-p)]
20679 ["Next Row" org-return (org-at-table-p)]
20680 "--"
20681 ["Blank Field" org-table-blank-field (org-at-table-p)]
20682 ["Edit Field" org-table-edit-field (org-at-table-p)]
20683 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20684 "--"
20685 ("Column"
20686 ["Move Column Left" org-metaleft (org-at-table-p)]
20687 ["Move Column Right" org-metaright (org-at-table-p)]
20688 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20689 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20690 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20691 ("Row"
20692 ["Move Row Up" org-metaup (org-at-table-p)]
20693 ["Move Row Down" org-metadown (org-at-table-p)]
20694 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20695 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20696 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20697 "--"
20698 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20699 ("Rectangle"
20700 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20701 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20702 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20703 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20704 "--"
20705 ("Calculate"
20706 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20707 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20708 ["Edit Formulas" org-edit-special (org-at-table-p)]
20709 "--"
20710 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20711 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20712 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20713 "--"
20714 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20715 "--"
20716 ["Sum Column/Rectangle" org-table-sum
20717 (or (org-at-table-p) (org-region-active-p))]
20718 ["Which Column?" org-table-current-column (org-at-table-p)])
20719 ["Debug Formulas"
20720 org-table-toggle-formula-debugger
20721 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20722 ["Show Col/Row Numbers"
20723 org-table-toggle-coordinate-overlays
20724 :style toggle
20725 :selected (bound-and-true-p org-table-overlay-coordinates)]
20726 "--"
20727 ["Create" org-table-create (not (org-at-table-p))]
20728 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20729 ["Import from File" org-table-import (not (org-at-table-p))]
20730 ["Export to File" org-table-export (org-at-table-p)]
20731 "--"
20732 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20733 "--"
20734 ("Plot"
20735 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20736 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20738 (easy-menu-define org-org-menu org-mode-map "Org menu"
20739 '("Org"
20740 ("Show/Hide"
20741 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20742 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20743 ["Sparse Tree..." org-sparse-tree t]
20744 ["Reveal Context" org-reveal t]
20745 ["Show All" org-show-all t]
20746 "--"
20747 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20748 "--"
20749 ["New Heading" org-insert-heading t]
20750 ("Navigate Headings"
20751 ["Up" outline-up-heading t]
20752 ["Next" outline-next-visible-heading t]
20753 ["Previous" outline-previous-visible-heading t]
20754 ["Next Same Level" outline-forward-same-level t]
20755 ["Previous Same Level" outline-backward-same-level t]
20756 "--"
20757 ["Jump" org-goto t])
20758 ("Edit Structure"
20759 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20760 "--"
20761 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20762 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20763 "--"
20764 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20765 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20766 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20767 "--"
20768 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20769 "--"
20770 ["Copy visible text" org-copy-visible t]
20771 "--"
20772 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20773 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20774 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20775 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20776 "--"
20777 ["Sort Region/Children" org-sort t]
20778 "--"
20779 ["Convert to odd levels" org-convert-to-odd-levels t]
20780 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20781 ("Editing"
20782 ["Emphasis..." org-emphasize t]
20783 ["Edit Source Example" org-edit-special t]
20784 "--"
20785 ["Footnote new/jump" org-footnote-action t]
20786 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20787 ("Archive"
20788 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20789 "--"
20790 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20791 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20792 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20794 "--"
20795 ("Hyperlinks"
20796 ["Store Link (Global)" org-store-link t]
20797 ["Find existing link to here" org-occur-link-in-agenda-files t]
20798 ["Insert Link" org-insert-link t]
20799 ["Follow Link" org-open-at-point t]
20800 "--"
20801 ["Next link" org-next-link t]
20802 ["Previous link" org-previous-link t]
20803 "--"
20804 ["Descriptive Links"
20805 org-toggle-link-display
20806 :style radio
20807 :selected org-descriptive-links
20809 ["Literal Links"
20810 org-toggle-link-display
20811 :style radio
20812 :selected (not org-descriptive-links)])
20813 "--"
20814 ("TODO Lists"
20815 ["TODO/DONE/-" org-todo t]
20816 ("Select keyword"
20817 ["Next keyword" org-shiftright (org-at-heading-p)]
20818 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20819 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20820 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20821 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20822 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20823 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20824 "--"
20825 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20826 :selected org-enforce-todo-dependencies :style toggle :active t]
20827 "Settings for tree at point"
20828 ["Do Children sequentially" org-toggle-ordered-property :style radio
20829 :selected (org-entry-get nil "ORDERED")
20830 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20831 ["Do Children parallel" org-toggle-ordered-property :style radio
20832 :selected (not (org-entry-get nil "ORDERED"))
20833 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20834 "--"
20835 ["Set Priority" org-priority t]
20836 ["Priority Up" org-shiftup t]
20837 ["Priority Down" org-shiftdown t]
20838 "--"
20839 ["Get news from all feeds" org-feed-update-all t]
20840 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20841 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20842 ("TAGS and Properties"
20843 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20844 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20845 "--"
20846 ["Set property" org-set-property (not (org-before-first-heading-p))]
20847 ["Column view of properties" org-columns t]
20848 ["Insert Column View DBlock" org-columns-insert-dblock t])
20849 ("Dates and Scheduling"
20850 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20851 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20852 ("Change Date"
20853 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20854 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20855 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20856 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20857 ["Compute Time Range" org-evaluate-time-range t]
20858 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20859 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20860 "--"
20861 ["Custom time format" org-toggle-time-stamp-overlays
20862 :style radio :selected org-display-custom-times]
20863 "--"
20864 ["Goto Calendar" org-goto-calendar t]
20865 ["Date from Calendar" org-date-from-calendar t]
20866 "--"
20867 ["Start/Restart Timer" org-timer-start t]
20868 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20869 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20870 ["Insert Timer String" org-timer t]
20871 ["Insert Timer Item" org-timer-item t])
20872 ("Logging work"
20873 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20874 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20875 ["Clock out" org-clock-out t]
20876 ["Clock cancel" org-clock-cancel t]
20877 "--"
20878 ["Mark as default task" org-clock-mark-default-task t]
20879 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20880 ["Goto running clock" org-clock-goto t]
20881 "--"
20882 ["Display times" org-clock-display t]
20883 ["Create clock table" org-clock-report t]
20884 "--"
20885 ["Record DONE time"
20886 (progn (setq org-log-done (not org-log-done))
20887 (message "Switching to %s will %s record a timestamp"
20888 (car org-done-keywords)
20889 (if org-log-done "automatically" "not")))
20890 :style toggle :selected org-log-done])
20891 "--"
20892 ["Agenda Command..." org-agenda t]
20893 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20894 ("File List for Agenda")
20895 ("Special views current file"
20896 ["TODO Tree" org-show-todo-tree t]
20897 ["Check Deadlines" org-check-deadlines t]
20898 ["Tags/Property tree" org-match-sparse-tree t])
20899 "--"
20900 ["Export/Publish..." org-export-dispatch t]
20901 ("LaTeX"
20902 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20903 :style toggle :selected org-cdlatex-mode]
20904 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20905 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20906 ["Modify math symbol" org-cdlatex-math-modify
20907 (org-inside-LaTeX-fragment-p)]
20908 ["Insert citation" org-reftex-citation t])
20909 "--"
20910 ("MobileOrg"
20911 ["Push Files and Views" org-mobile-push t]
20912 ["Get Captured and Flagged" org-mobile-pull t]
20913 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20914 "--"
20915 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20916 "--"
20917 ("Documentation"
20918 ["Show Version" org-version t]
20919 ["Info Documentation" org-info t]
20920 ["Browse Org News" org-browse-news t])
20921 ("Customize"
20922 ["Browse Org Group" org-customize t]
20923 "--"
20924 ["Expand This Menu" org-create-customize-menu
20925 (fboundp 'customize-menu-create)])
20926 ["Send bug report" org-submit-bug-report t]
20927 "--"
20928 ("Refresh/Reload"
20929 ["Refresh setup current buffer" org-mode-restart t]
20930 ["Reload Org (after update)" org-reload t]
20931 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
20933 (defun org-info (&optional node)
20934 "Read documentation for Org in the info system.
20935 With optional NODE, go directly to that node."
20936 (interactive)
20937 (info (format "(org)%s" (or node ""))))
20939 (defun org-browse-news ()
20940 "Browse the news for the latest major release."
20941 (interactive)
20942 (browse-url "https://orgmode.org/Changes.html"))
20944 ;;;###autoload
20945 (defun org-submit-bug-report ()
20946 "Submit a bug report on Org via mail.
20948 Don't hesitate to report any problems or inaccurate documentation.
20950 If you don't have setup sending mail from (X)Emacs, please copy the
20951 output buffer into your mail program, as it gives us important
20952 information about your Org version and configuration."
20953 (interactive)
20954 (require 'reporter)
20955 (defvar reporter-prompt-for-summary-p)
20956 (org-load-modules-maybe)
20957 (org-require-autoloaded-modules)
20958 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20959 (reporter-submit-bug-report
20960 "emacs-orgmode@gnu.org"
20961 (org-version nil 'full)
20962 (let (list)
20963 (save-window-excursion
20964 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20965 (delete-other-windows)
20966 (erase-buffer)
20967 (insert "You are about to submit a bug report to the Org mailing list.
20969 We would like to add your full Org and Outline configuration to the
20970 bug report. This greatly simplifies the work of the maintainer and
20971 other experts on the mailing list.
20973 HOWEVER, some variables you have customized may contain private
20974 information. The names of customers, colleagues, or friends, might
20975 appear in the form of file names, tags, todo states, or search strings.
20976 If you answer yes to the prompt, you might want to check and remove
20977 such private information before sending the email.")
20978 (add-text-properties (point-min) (point-max) '(face org-warning))
20979 (when (yes-or-no-p "Include your Org configuration ")
20980 (mapatoms
20981 (lambda (v)
20982 (and (boundp v)
20983 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20984 (or (and (symbol-value v)
20985 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20986 (and
20987 (get v 'custom-type) (get v 'standard-value)
20988 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20989 (push v list)))))
20990 (kill-buffer (get-buffer "*Warn about privacy*"))
20991 list))
20992 nil nil
20993 "Remember to cover the basics, that is, what you expected to happen and
20994 what in fact did happen. You don't know how to make a good report? See
20996 https://orgmode.org/manual/Feedback.html#Feedback
20998 Your bug report will be posted to the Org mailing list.
20999 ------------------------------------------------------------------------")
21000 (save-excursion
21001 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21002 (replace-match "\\1Bug: \\3 [\\2]")))))
21005 (defun org-install-agenda-files-menu ()
21006 (let ((bl (buffer-list)))
21007 (save-excursion
21008 (while bl
21009 (set-buffer (pop bl))
21010 (when (derived-mode-p 'org-mode) (setq bl nil)))
21011 (when (derived-mode-p 'org-mode)
21012 (easy-menu-change
21013 '("Org") "File List for Agenda"
21014 (append
21015 (list
21016 ["Edit File List" (org-edit-agenda-file-list) t]
21017 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21018 ["Remove Current File from List" org-remove-file t]
21019 ["Cycle through agenda files" org-cycle-agenda-files t]
21020 ["Occur in all agenda files" org-occur-in-agenda-files t]
21021 "--")
21022 (mapcar 'org-file-menu-entry
21023 ;; Prevent initialization from failing.
21024 (ignore-errors (org-agenda-files t)))))))))
21026 ;;;; Documentation
21028 (defun org-require-autoloaded-modules ()
21029 (interactive)
21030 (mapc #'require
21031 '(org-agenda org-archive org-attach org-clock org-colview org-id
21032 org-table org-timer)))
21034 ;;;###autoload
21035 (defun org-reload (&optional uncompiled)
21036 "Reload all Org Lisp files.
21037 With prefix arg UNCOMPILED, load the uncompiled versions."
21038 (interactive "P")
21039 (require 'loadhist)
21040 (let* ((org-dir (org-find-library-dir "org"))
21041 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21042 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21043 (remove-re (format "\\`%s\\'"
21044 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21045 (feats (delete-dups
21046 (mapcar 'file-name-sans-extension
21047 (mapcar 'file-name-nondirectory
21048 (delq nil
21049 (mapcar 'feature-file
21050 features))))))
21051 (lfeat (append
21052 (sort
21053 (setq feats
21054 (delq nil (mapcar
21055 (lambda (f)
21056 (if (and (string-match feature-re f)
21057 (not (string-match remove-re f)))
21058 f nil))
21059 feats)))
21060 'string-lessp)
21061 (list "org-version" "org")))
21062 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21063 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21064 load-uncore load-misses)
21065 (setq load-misses
21066 (delq 't
21067 (mapcar (lambda (f)
21068 (or (org-load-noerror-mustsuffix (concat org-dir f))
21069 (and (string= org-dir contrib-dir)
21070 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21071 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21072 (add-to-list 'load-uncore f 'append)
21075 lfeat)))
21076 (when load-uncore
21077 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21078 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21079 (if load-misses
21080 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21081 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21082 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21084 ;;;###autoload
21085 (defun org-customize ()
21086 "Call the customize function with org as argument."
21087 (interactive)
21088 (org-load-modules-maybe)
21089 (org-require-autoloaded-modules)
21090 (customize-browse 'org))
21092 (defun org-create-customize-menu ()
21093 "Create a full customization menu for Org mode, insert it into the menu."
21094 (interactive)
21095 (org-load-modules-maybe)
21096 (org-require-autoloaded-modules)
21097 (if (fboundp 'customize-menu-create)
21098 (progn
21099 (easy-menu-change
21100 '("Org") "Customize"
21101 `(["Browse Org group" org-customize t]
21102 "--"
21103 ,(customize-menu-create 'org)
21104 ["Set" Custom-set t]
21105 ["Save" Custom-save t]
21106 ["Reset to Current" Custom-reset-current t]
21107 ["Reset to Saved" Custom-reset-saved t]
21108 ["Reset to Standard Settings" Custom-reset-standard t]))
21109 (message "\"Org\"-menu now contains full customization menu"))
21110 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21112 ;;;; Miscellaneous stuff
21114 ;;; Generally useful functions
21116 (defun org-link-display-format (s)
21117 "Replace links in string S with their description.
21118 If there is no description, use the link target."
21119 (save-match-data
21120 (replace-regexp-in-string
21121 org-bracket-link-analytic-regexp
21122 (lambda (m)
21123 (if (match-end 5) (match-string 5 m)
21124 (concat (match-string 1 m) (match-string 3 m))))
21125 s nil t)))
21127 (defun org-toggle-link-display ()
21128 "Toggle the literal or descriptive display of links."
21129 (interactive)
21130 (if org-descriptive-links
21131 (remove-from-invisibility-spec '(org-link))
21132 (add-to-invisibility-spec '(org-link)))
21133 (org-restart-font-lock)
21134 (setq org-descriptive-links (not org-descriptive-links)))
21136 (defun org-in-clocktable-p ()
21137 "Check if the cursor is in a clocktable."
21138 (let ((pos (point)) start)
21139 (save-excursion
21140 (end-of-line 1)
21141 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21142 (setq start (match-beginning 0))
21143 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21144 (>= (match-end 0) pos)
21145 start))))
21147 (defun org-in-verbatim-emphasis ()
21148 (save-match-data
21149 (and (org-in-regexp org-verbatim-re 2)
21150 (>= (point) (match-beginning 3))
21151 (<= (point) (match-end 4)))))
21153 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21154 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21155 (if (and marker (marker-buffer marker)
21156 (buffer-live-p (marker-buffer marker)))
21157 (progn
21158 (pop-to-buffer-same-window (marker-buffer marker))
21159 (when (or (> marker (point-max)) (< marker (point-min)))
21160 (widen))
21161 (goto-char marker)
21162 (org-show-context 'org-goto))
21163 (if bookmark
21164 (bookmark-jump bookmark)
21165 (error "Cannot find location"))))
21167 (defun org-quote-csv-field (s)
21168 "Quote field for inclusion in CSV material."
21169 (if (string-match "[\",]" s)
21170 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21173 (defun org-force-self-insert (N)
21174 "Needed to enforce self-insert under remapping."
21175 (interactive "p")
21176 (self-insert-command N))
21178 (defun org-fill-template (template alist)
21179 "Find each %key of ALIST in TEMPLATE and replace it."
21180 (let ((case-fold-search nil))
21181 (dolist (entry (sort (copy-sequence alist)
21182 (lambda (a b) (< (length (car a)) (length (car b))))))
21183 (setq template
21184 (replace-regexp-in-string
21185 (concat "%" (regexp-quote (car entry)))
21186 (or (cdr entry) "") template t t)))
21187 template))
21189 (defun org-quote-vert (s)
21190 "Replace \"|\" with \"\\vert\"."
21191 (while (string-match "|" s)
21192 (setq s (replace-match "\\vert" t t s)))
21195 (defun org-uuidgen-p (s)
21196 "Is S an ID created by UUIDGEN?"
21197 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21199 (defun org-in-src-block-p (&optional inside)
21200 "Whether point is in a code source block.
21201 When INSIDE is non-nil, don't consider we are within a src block
21202 when point is at #+BEGIN_SRC or #+END_SRC."
21203 (let ((case-fold-search t))
21204 (or (and (eq (get-char-property (point) 'src-block) t))
21205 (and (not inside)
21206 (save-match-data
21207 (save-excursion
21208 (beginning-of-line)
21209 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21211 (defun org-context ()
21212 "Return a list of contexts of the current cursor position.
21213 If several contexts apply, all are returned.
21214 Each context entry is a list with a symbol naming the context, and
21215 two positions indicating start and end of the context. Possible
21216 contexts are:
21218 :headline anywhere in a headline
21219 :headline-stars on the leading stars in a headline
21220 :todo-keyword on a TODO keyword (including DONE) in a headline
21221 :tags on the TAGS in a headline
21222 :priority on the priority cookie in a headline
21223 :item on the first line of a plain list item
21224 :item-bullet on the bullet/number of a plain list item
21225 :checkbox on the checkbox in a plain list item
21226 :table in an Org table
21227 :table-special on a special filed in a table
21228 :table-table in a table.el table
21229 :clocktable in a clocktable
21230 :src-block in a source block
21231 :link on a hyperlink
21232 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21233 :target on a <<target>>
21234 :radio-target on a <<<radio-target>>>
21235 :latex-fragment on a LaTeX fragment
21236 :latex-preview on a LaTeX fragment with overlaid preview image
21238 This function expects the position to be visible because it uses font-lock
21239 faces as a help to recognize the following contexts: :table-special, :link,
21240 and :keyword."
21241 (let* ((f (get-text-property (point) 'face))
21242 (faces (if (listp f) f (list f)))
21243 (case-fold-search t)
21244 (p (point)) clist o)
21245 ;; First the large context
21246 (cond
21247 ((org-at-heading-p t)
21248 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21249 (when (progn
21250 (beginning-of-line 1)
21251 (looking-at org-todo-line-tags-regexp))
21252 (push (org-point-in-group p 1 :headline-stars) clist)
21253 (push (org-point-in-group p 2 :todo-keyword) clist)
21254 (push (org-point-in-group p 4 :tags) clist))
21255 (goto-char p)
21256 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21257 (when (looking-at "\\[#[A-Z0-9]\\]")
21258 (push (org-point-in-group p 0 :priority) clist)))
21260 ((org-at-item-p)
21261 (push (org-point-in-group p 2 :item-bullet) clist)
21262 (push (list :item (point-at-bol)
21263 (save-excursion (org-end-of-item) (point)))
21264 clist)
21265 (and (org-at-item-checkbox-p)
21266 (push (org-point-in-group p 0 :checkbox) clist)))
21268 ((org-at-table-p)
21269 (push (list :table (org-table-begin) (org-table-end)) clist)
21270 (when (memq 'org-formula faces)
21271 (push (list :table-special
21272 (previous-single-property-change p 'face)
21273 (next-single-property-change p 'face)) clist)))
21274 ((org-at-table-p 'any)
21275 (push (list :table-table) clist)))
21276 (goto-char p)
21278 (let ((case-fold-search t))
21279 ;; New the "medium" contexts: clocktables, source blocks
21280 (cond ((org-in-clocktable-p)
21281 (push (list :clocktable
21282 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21283 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21284 (match-beginning 1))
21285 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21286 (match-end 0))) clist))
21287 ((org-in-src-block-p)
21288 (push (list :src-block
21289 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21290 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21291 (match-beginning 1))
21292 (and (search-forward "#+END_SRC" nil t)
21293 (match-beginning 0))) clist))))
21294 (goto-char p)
21296 ;; Now the small context
21297 (cond
21298 ((org-at-timestamp-p)
21299 (push (org-point-in-group p 0 :timestamp) clist))
21300 ((memq 'org-link faces)
21301 (push (list :link
21302 (previous-single-property-change p 'face)
21303 (next-single-property-change p 'face)) clist))
21304 ((memq 'org-special-keyword faces)
21305 (push (list :keyword
21306 (previous-single-property-change p 'face)
21307 (next-single-property-change p 'face)) clist))
21308 ((org-at-target-p)
21309 (push (org-point-in-group p 0 :target) clist)
21310 (goto-char (1- (match-beginning 0)))
21311 (when (looking-at org-radio-target-regexp)
21312 (push (org-point-in-group p 0 :radio-target) clist))
21313 (goto-char p))
21314 ((setq o (cl-some
21315 (lambda (o)
21316 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21318 (overlays-at (point))))
21319 (push (list :latex-fragment
21320 (overlay-start o) (overlay-end o)) clist)
21321 (push (list :latex-preview
21322 (overlay-start o) (overlay-end o)) clist))
21323 ((org-inside-LaTeX-fragment-p)
21324 ;; FIXME: positions wrong.
21325 (push (list :latex-fragment (point) (point)) clist)))
21327 (setq clist (nreverse (delq nil clist)))
21328 clist))
21330 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21331 "Non-nil when point is between matches of START-RE and END-RE.
21333 Also return a non-nil value when point is on one of the matches.
21335 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21336 buffer positions. Default values are the positions of headlines
21337 surrounding the point.
21339 The functions returns a cons cell whose car (resp. cdr) is the
21340 position before START-RE (resp. after END-RE)."
21341 (save-match-data
21342 (let ((pos (point))
21343 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21344 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21345 beg end)
21346 (save-excursion
21347 ;; Point is on a block when on START-RE or if START-RE can be
21348 ;; found before it...
21349 (and (or (org-in-regexp start-re)
21350 (re-search-backward start-re limit-up t))
21351 (setq beg (match-beginning 0))
21352 ;; ... and END-RE after it...
21353 (goto-char (match-end 0))
21354 (re-search-forward end-re limit-down t)
21355 (> (setq end (match-end 0)) pos)
21356 ;; ... without another START-RE in-between.
21357 (goto-char (match-beginning 0))
21358 (not (re-search-backward start-re (1+ beg) t))
21359 ;; Return value.
21360 (cons beg end))))))
21362 (defun org-in-block-p (names)
21363 "Non-nil when point belongs to a block whose name belongs to NAMES.
21365 NAMES is a list of strings containing names of blocks.
21367 Return first block name matched, or nil. Beware that in case of
21368 nested blocks, the returned name may not belong to the closest
21369 block from point."
21370 (save-match-data
21371 (catch 'exit
21372 (let ((case-fold-search t)
21373 (lim-up (save-excursion (outline-previous-heading)))
21374 (lim-down (save-excursion (outline-next-heading))))
21375 (dolist (name names)
21376 (let ((n (regexp-quote name)))
21377 (when (org-between-regexps-p
21378 (concat "^[ \t]*#\\+begin_" n)
21379 (concat "^[ \t]*#\\+end_" n)
21380 lim-up lim-down)
21381 (throw 'exit n)))))
21382 nil)))
21384 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21385 "Call `multi-occur' with buffers for all agenda files."
21386 (interactive "sOrg-files matching: ")
21387 (let* ((files (org-agenda-files))
21388 (tnames (mapcar #'file-truename files))
21389 (extra org-agenda-text-search-extra-files))
21390 (when (eq (car extra) 'agenda-archives)
21391 (setq extra (cdr extra))
21392 (setq files (org-add-archive-files files)))
21393 (dolist (f extra)
21394 (unless (member (file-truename f) tnames)
21395 (unless (member f files) (setq files (append files (list f))))
21396 (setq tnames (append tnames (list (file-truename f))))))
21397 (multi-occur
21398 (mapcar (lambda (x)
21399 (with-current-buffer
21400 ;; FIXME: Why not just (find-file-noselect x)?
21401 ;; Is it to avoid the "revert buffer" prompt?
21402 (or (get-file-buffer x) (find-file-noselect x))
21403 (widen)
21404 (current-buffer)))
21405 files)
21406 regexp)))
21408 (add-hook 'occur-mode-find-occurrence-hook
21409 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21411 (defun org-occur-link-in-agenda-files ()
21412 "Create a link and search for it in the agendas.
21413 The link is not stored in `org-stored-links', it is just created
21414 for the search purpose."
21415 (interactive)
21416 (let ((link (condition-case nil
21417 (org-store-link nil)
21418 (error "Unable to create a link to here"))))
21419 (org-occur-in-agenda-files (regexp-quote link))))
21421 (defun org-back-over-empty-lines ()
21422 "Move backwards over whitespace, to the beginning of the first empty line.
21423 Returns the number of empty lines passed."
21424 (let ((pos (point)))
21425 (if (cdr (assq 'heading org-blank-before-new-entry))
21426 (skip-chars-backward " \t\n\r")
21427 (unless (eobp)
21428 (forward-line -1)))
21429 (beginning-of-line 2)
21430 (goto-char (min (point) pos))
21431 (count-lines (point) pos)))
21433 (defun org-replace-escapes (string table)
21434 "Replace %-escapes in STRING with values in TABLE.
21435 TABLE is an association list with keys like \"%a\" and string values.
21436 The sequences in STRING may contain normal field width and padding information,
21437 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21438 so values can contain further %-escapes if they are define later in TABLE."
21439 (let ((tbl (copy-alist table))
21440 (case-fold-search nil)
21441 (pchg 0)
21442 re rpl)
21443 (dolist (e tbl)
21444 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21445 (when (and (cdr e) (string-match re (cdr e)))
21446 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21447 (safe "SREF"))
21448 (add-text-properties 0 3 (list 'sref sref) safe)
21449 (setcdr e (replace-match safe t t (cdr e)))))
21450 (while (string-match re string)
21451 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21452 (cdr e)))
21453 (setq string (replace-match rpl t t string))))
21454 (while (setq pchg (next-property-change pchg string))
21455 (let ((sref (get-text-property pchg 'sref string)))
21456 (when (and sref (string-match "SREF" string pchg))
21457 (setq string (replace-match sref t t string)))))
21458 string))
21460 ;;; TODO: Only called once, from ox-odt which should probably use
21461 ;;; org-export-inline-image-p or something.
21462 (defun org-file-image-p (file)
21463 "Return non-nil if FILE is an image."
21464 (save-match-data
21465 (string-match (image-file-name-regexp) file)))
21467 (defun org-get-cursor-date (&optional with-time)
21468 "Return the date at cursor in as a time.
21469 This works in the calendar and in the agenda, anywhere else it just
21470 returns the current time.
21471 If WITH-TIME is non-nil, returns the time of the event at point (in
21472 the agenda) or the current time of the day."
21473 (let (date day defd tp hod mod)
21474 (when with-time
21475 (setq tp (get-text-property (point) 'time))
21476 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21477 (setq hod (string-to-number (match-string 1 tp))
21478 mod (string-to-number (match-string 2 tp))))
21479 (or tp (let ((now (decode-time)))
21480 (setq hod (nth 2 now)
21481 mod (nth 1 now)))))
21482 (cond
21483 ((eq major-mode 'calendar-mode)
21484 (setq date (calendar-cursor-to-date)
21485 defd (encode-time 0 (or mod 0) (or hod 0)
21486 (nth 1 date) (nth 0 date) (nth 2 date))))
21487 ((eq major-mode 'org-agenda-mode)
21488 (setq day (get-text-property (point) 'day))
21489 (when day
21490 (setq date (calendar-gregorian-from-absolute day)
21491 defd (encode-time 0 (or mod 0) (or hod 0)
21492 (nth 1 date) (nth 0 date) (nth 2 date))))))
21493 (or defd (current-time))))
21495 (defun org-mark-subtree (&optional up)
21496 "Mark the current subtree.
21497 This puts point at the start of the current subtree, and mark at
21498 the end. If a numeric prefix UP is given, move up into the
21499 hierarchy of headlines by UP levels before marking the subtree."
21500 (interactive "P")
21501 (org-with-limited-levels
21502 (cond ((org-at-heading-p) (beginning-of-line))
21503 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21504 (t (outline-previous-visible-heading 1))))
21505 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21506 (if (called-interactively-p 'any)
21507 (call-interactively 'org-mark-element)
21508 (org-mark-element)))
21510 ;;; Indentation
21512 (defvar org-element-greater-elements)
21513 (defun org--get-expected-indentation (element contentsp)
21514 "Expected indentation column for current line, according to ELEMENT.
21515 ELEMENT is an element containing point. CONTENTSP is non-nil
21516 when indentation is to be computed according to contents of
21517 ELEMENT."
21518 (let ((type (org-element-type element))
21519 (start (org-element-property :begin element))
21520 (post-affiliated (org-element-property :post-affiliated element)))
21521 (org-with-wide-buffer
21522 (cond
21523 (contentsp
21524 (cl-case type
21525 ((diary-sexp footnote-definition) 0)
21526 ((headline inlinetask nil)
21527 (if (not org-adapt-indentation) 0
21528 (let ((level (org-current-level)))
21529 (if level (1+ level) 0))))
21530 ((item plain-list) (org-list-item-body-column post-affiliated))
21532 (goto-char start)
21533 (current-indentation))))
21534 ((memq type '(headline inlinetask nil))
21535 (if (org-match-line "[ \t]*$")
21536 (org--get-expected-indentation element t)
21538 ((memq type '(diary-sexp footnote-definition)) 0)
21539 ;; First paragraph of a footnote definition or an item.
21540 ;; Indent like parent.
21541 ((< (line-beginning-position) start)
21542 (org--get-expected-indentation
21543 (org-element-property :parent element) t))
21544 ;; At first line: indent according to previous sibling, if any,
21545 ;; ignoring footnote definitions and inline tasks, or parent's
21546 ;; contents.
21547 ((= (line-beginning-position) start)
21548 (catch 'exit
21549 (while t
21550 (if (= (point-min) start) (throw 'exit 0)
21551 (goto-char (1- start))
21552 (let* ((previous (org-element-at-point))
21553 (parent previous))
21554 (while (and parent (<= (org-element-property :end parent) start))
21555 (setq previous parent
21556 parent (org-element-property :parent parent)))
21557 (cond
21558 ((not previous) (throw 'exit 0))
21559 ((> (org-element-property :end previous) start)
21560 (throw 'exit (org--get-expected-indentation previous t)))
21561 ((memq (org-element-type previous)
21562 '(footnote-definition inlinetask))
21563 (setq start (org-element-property :begin previous)))
21564 (t (goto-char (org-element-property :begin previous))
21565 (throw 'exit
21566 (if (bolp) (current-indentation)
21567 ;; At first paragraph in an item or
21568 ;; a footnote definition.
21569 (org--get-expected-indentation
21570 (org-element-property :parent previous) t))))))))))
21571 ;; Otherwise, move to the first non-blank line above.
21573 (beginning-of-line)
21574 (let ((pos (point)))
21575 (skip-chars-backward " \r\t\n")
21576 (cond
21577 ;; Two blank lines end a footnote definition or a plain
21578 ;; list. When we indent an empty line after them, the
21579 ;; containing list or footnote definition is over, so it
21580 ;; qualifies as a previous sibling. Therefore, we indent
21581 ;; like its first line.
21582 ((and (memq type '(footnote-definition plain-list))
21583 (> (count-lines (point) pos) 2))
21584 (goto-char start)
21585 (current-indentation))
21586 ;; Line above is the first one of a paragraph at the
21587 ;; beginning of an item or a footnote definition. Indent
21588 ;; like parent.
21589 ((< (line-beginning-position) start)
21590 (org--get-expected-indentation
21591 (org-element-property :parent element) t))
21592 ;; Line above is the beginning of an element, i.e., point
21593 ;; was originally on the blank lines between element's start
21594 ;; and contents.
21595 ((= (line-beginning-position) post-affiliated)
21596 (org--get-expected-indentation element t))
21597 ;; POS is after contents in a greater element. Indent like
21598 ;; the beginning of the element.
21599 ((and (memq type org-element-greater-elements)
21600 (let ((cend (org-element-property :contents-end element)))
21601 (and cend (<= cend pos))))
21602 ;; As a special case, if point is at the end of a footnote
21603 ;; definition or an item, indent like the very last element
21604 ;; within. If that last element is an item, indent like
21605 ;; its contents.
21606 (if (memq type '(footnote-definition item plain-list))
21607 (let ((last (org-element-at-point)))
21608 (goto-char pos)
21609 (org--get-expected-indentation
21610 last (eq (org-element-type last) 'item)))
21611 (goto-char start)
21612 (current-indentation)))
21613 ;; In any other case, indent like the current line.
21614 (t (current-indentation)))))))))
21616 (defun org--align-node-property ()
21617 "Align node property at point.
21618 Alignment is done according to `org-property-format', which see."
21619 (when (save-excursion
21620 (beginning-of-line)
21621 (looking-at org-property-re))
21622 (replace-match
21623 (concat (match-string 4)
21624 (org-trim
21625 (format org-property-format (match-string 1) (match-string 3))))
21626 t t)))
21628 (defun org-indent-line ()
21629 "Indent line depending on context.
21631 Indentation is done according to the following rules:
21633 - Footnote definitions, diary sexps, headlines and inline tasks
21634 have to start at column 0.
21636 - On the very first line of an element, consider, in order, the
21637 next rules until one matches:
21639 1. If there's a sibling element before, ignoring footnote
21640 definitions and inline tasks, indent like its first line.
21642 2. If element has a parent, indent like its contents. More
21643 precisely, if parent is an item, indent after the
21644 description part, if any, or the bullet (see
21645 `org-list-description-max-indent'). Else, indent like
21646 parent's first line.
21648 3. Otherwise, indent relatively to current level, if
21649 `org-adapt-indentation' is non-nil, or to left margin.
21651 - On a blank line at the end of an element, indent according to
21652 the type of the element. More precisely
21654 1. If element is a plain list, an item, or a footnote
21655 definition, indent like the very last element within.
21657 2. If element is a paragraph, indent like its last non blank
21658 line.
21660 3. Otherwise, indent like its very first line.
21662 - In the code part of a source block, use language major mode
21663 to indent current line if `org-src-tab-acts-natively' is
21664 non-nil. If it is nil, do nothing.
21666 - Otherwise, indent like the first non-blank line above.
21668 The function doesn't indent an item as it could break the whole
21669 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21670 `\\[org-shiftmetaright]'.
21672 Also align node properties according to `org-property-format'."
21673 (interactive)
21674 (cond
21675 ((org-at-heading-p) 'noindent)
21677 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21678 (type (org-element-type element)))
21679 (cond ((and (memq type '(plain-list item))
21680 (= (line-beginning-position)
21681 (org-element-property :post-affiliated element)))
21682 'noindent)
21683 ((and (eq type 'latex-environment)
21684 (>= (point) (org-element-property :post-affiliated element))
21685 (< (point) (org-with-wide-buffer
21686 (goto-char (org-element-property :end element))
21687 (skip-chars-backward " \r\t\n")
21688 (line-beginning-position 2))))
21689 'noindent)
21690 ((and (eq type 'src-block)
21691 org-src-tab-acts-natively
21692 (> (line-beginning-position)
21693 (org-element-property :post-affiliated element))
21694 (< (line-beginning-position)
21695 (org-with-wide-buffer
21696 (goto-char (org-element-property :end element))
21697 (skip-chars-backward " \r\t\n")
21698 (line-beginning-position))))
21699 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21701 (let ((column (org--get-expected-indentation element nil)))
21702 ;; Preserve current column.
21703 (if (<= (current-column) (current-indentation))
21704 (indent-line-to column)
21705 (save-excursion (indent-line-to column))))
21706 ;; Align node property. Also preserve current column.
21707 (when (eq type 'node-property)
21708 (let ((column (current-column)))
21709 (org--align-node-property)
21710 (org-move-to-column column)))))))))
21712 (defun org-indent-region (start end)
21713 "Indent each non-blank line in the region.
21714 Called from a program, START and END specify the region to
21715 indent. The function will not indent contents of example blocks,
21716 verse blocks and export blocks as leading white spaces are
21717 assumed to be significant there."
21718 (interactive "r")
21719 (save-excursion
21720 (goto-char start)
21721 (skip-chars-forward " \r\t\n")
21722 (unless (eobp) (beginning-of-line))
21723 (let ((indent-to
21724 (lambda (ind pos)
21725 ;; Set IND as indentation for all lines between point and
21726 ;; POS. Blank lines are ignored. Leave point after POS
21727 ;; once done.
21728 (let ((limit (copy-marker pos)))
21729 (while (< (point) limit)
21730 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21731 (forward-line))
21732 (set-marker limit nil))))
21733 (end (copy-marker end)))
21734 (while (< (point) end)
21735 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21736 (let* ((element (org-element-at-point))
21737 (type (org-element-type element))
21738 (element-end (copy-marker (org-element-property :end element)))
21739 (ind (org--get-expected-indentation element nil)))
21740 (cond
21741 ;; Element indented as a single block. Example blocks
21742 ;; preserving indentation are a special case since the
21743 ;; "contents" must not be indented whereas the block
21744 ;; boundaries can.
21745 ((or (memq type '(export-block latex-environment))
21746 (and (eq type 'example-block)
21747 (not
21748 (or org-src-preserve-indentation
21749 (org-element-property :preserve-indent element)))))
21750 (let ((offset (- ind (current-indentation))))
21751 (unless (zerop offset)
21752 (indent-rigidly (org-element-property :begin element)
21753 (org-element-property :end element)
21754 offset)))
21755 (goto-char element-end))
21756 ;; Elements indented line wise. Be sure to exclude
21757 ;; example blocks (preserving indentation) and source
21758 ;; blocks from this category as they are treated
21759 ;; specially later.
21760 ((or (memq type '(paragraph table table-row))
21761 (not (or (org-element-property :contents-begin element)
21762 (memq type '(example-block src-block)))))
21763 (when (eq type 'node-property)
21764 (org--align-node-property)
21765 (beginning-of-line))
21766 (funcall indent-to ind (min element-end end)))
21767 ;; Elements consisting of three parts: before the
21768 ;; contents, the contents, and after the contents. The
21769 ;; contents are treated specially, according to the
21770 ;; element type, or not indented at all. Other parts are
21771 ;; indented as a single block.
21773 (let* ((post (copy-marker
21774 (org-element-property :post-affiliated element)))
21775 (cbeg
21776 (copy-marker
21777 (cond
21778 ((not (org-element-property :contents-begin element))
21779 ;; Fake contents for source blocks.
21780 (org-with-wide-buffer
21781 (goto-char post)
21782 (line-beginning-position 2)))
21783 ((memq type '(footnote-definition item plain-list))
21784 ;; Contents in these elements could start on
21785 ;; the same line as the beginning of the
21786 ;; element. Make sure we start indenting
21787 ;; from the second line.
21788 (org-with-wide-buffer
21789 (goto-char post)
21790 (end-of-line)
21791 (skip-chars-forward " \r\t\n")
21792 (if (eobp) (point) (line-beginning-position))))
21793 (t (org-element-property :contents-begin element)))))
21794 (cend (copy-marker
21795 (or (org-element-property :contents-end element)
21796 ;; Fake contents for source blocks.
21797 (org-with-wide-buffer
21798 (goto-char element-end)
21799 (skip-chars-backward " \r\t\n")
21800 (line-beginning-position)))
21801 t)))
21802 ;; Do not change items indentation individually as it
21803 ;; might break the list as a whole. On the other
21804 ;; hand, when at a plain list, indent it as a whole.
21805 (cond ((eq type 'plain-list)
21806 (let ((offset (- ind (current-indentation))))
21807 (unless (zerop offset)
21808 (indent-rigidly (org-element-property :begin element)
21809 (org-element-property :end element)
21810 offset))
21811 (goto-char cbeg)))
21812 ((eq type 'item) (goto-char cbeg))
21813 (t (funcall indent-to ind (min cbeg end))))
21814 (when (< (point) end)
21815 (cl-case type
21816 ((example-block verse-block))
21817 (src-block
21818 ;; In a source block, indent source code
21819 ;; according to language major mode, but only if
21820 ;; `org-src-tab-acts-natively' is non-nil.
21821 (when (and (< (point) end) org-src-tab-acts-natively)
21822 (ignore-errors
21823 (org-babel-do-in-edit-buffer
21824 (indent-region (point-min) (point-max))))))
21825 (t (org-indent-region (point) (min cend end))))
21826 (goto-char (min cend end))
21827 (when (< (point) end)
21828 (funcall indent-to ind (min element-end end))))
21829 (set-marker post nil)
21830 (set-marker cbeg nil)
21831 (set-marker cend nil))))
21832 (set-marker element-end nil))))
21833 (set-marker end nil))))
21835 (defun org-indent-drawer ()
21836 "Indent the drawer at point."
21837 (interactive)
21838 (unless (save-excursion
21839 (beginning-of-line)
21840 (looking-at-p org-drawer-regexp))
21841 (user-error "Not at a drawer"))
21842 (let ((element (org-element-at-point)))
21843 (unless (memq (org-element-type element) '(drawer property-drawer))
21844 (user-error "Not at a drawer"))
21845 (org-with-wide-buffer
21846 (org-indent-region (org-element-property :begin element)
21847 (org-element-property :end element))))
21848 (message "Drawer at point indented"))
21850 (defun org-indent-block ()
21851 "Indent the block at point."
21852 (interactive)
21853 (unless (save-excursion
21854 (beginning-of-line)
21855 (let ((case-fold-search t))
21856 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21857 (user-error "Not at a block"))
21858 (let ((element (org-element-at-point)))
21859 (unless (memq (org-element-type element)
21860 '(comment-block center-block dynamic-block example-block
21861 export-block quote-block special-block
21862 src-block verse-block))
21863 (user-error "Not at a block"))
21864 (org-with-wide-buffer
21865 (org-indent-region (org-element-property :begin element)
21866 (org-element-property :end element))))
21867 (message "Block at point indented"))
21870 ;;; Filling
21872 ;; We use our own fill-paragraph and auto-fill functions.
21874 ;; `org-fill-paragraph' relies on adaptive filling and context
21875 ;; checking. Appropriate `fill-prefix' is computed with
21876 ;; `org-adaptive-fill-function'.
21878 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21879 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21880 ;; `org-adaptive-fill-function' value. Internally,
21881 ;; `org-comment-line-break-function' breaks the line.
21883 ;; `org-setup-filling' installs filling and auto-filling related
21884 ;; variables during `org-mode' initialization.
21886 (defun org-setup-filling ()
21887 (require 'org-element)
21888 ;; Prevent auto-fill from inserting unwanted new items.
21889 (when (boundp 'fill-nobreak-predicate)
21890 (setq-local
21891 fill-nobreak-predicate
21892 (org-uniquify
21893 (append fill-nobreak-predicate
21894 '(org-fill-line-break-nobreak-p
21895 org-fill-n-macro-as-item-nobreak-p
21896 org-fill-paragraph-with-timestamp-nobreak-p)))))
21897 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21898 (setq-local paragraph-start paragraph-ending)
21899 (setq-local paragraph-separate paragraph-ending))
21900 (setq-local fill-paragraph-function 'org-fill-paragraph)
21901 (setq-local auto-fill-inhibit-regexp nil)
21902 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21903 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21904 (setq-local comment-line-break-function 'org-comment-line-break-function))
21906 (defun org-fill-line-break-nobreak-p ()
21907 "Non-nil when a new line at point would create an Org line break."
21908 (save-excursion
21909 (skip-chars-backward "[ \t]")
21910 (skip-chars-backward "\\\\")
21911 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21913 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21914 "Non-nil when a new line at point would split a timestamp."
21915 (and (org-at-timestamp-p 'lax)
21916 (not (looking-at org-ts-regexp-both))))
21918 (defun org-fill-n-macro-as-item-nobreak-p ()
21919 "Non-nil when a new line at point would create a new list."
21920 ;; During export, a "n" macro followed by a dot or a closing
21921 ;; parenthesis can end up being parsed as a new list item.
21922 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21924 (defvar orgtbl-line-start-regexp) ; From org-table.el
21925 (defun org-adaptive-fill-function ()
21926 "Compute a fill prefix for the current line.
21927 Return fill prefix, as a string, or nil if current line isn't
21928 meant to be filled. For convenience, if `adaptive-fill-regexp'
21929 matches in paragraphs or comments, use it."
21930 (org-with-wide-buffer
21931 (unless (org-at-heading-p)
21932 (let* ((p (line-beginning-position))
21933 (element (save-excursion
21934 (beginning-of-line)
21935 (org-element-at-point)))
21936 (type (org-element-type element))
21937 (post-affiliated (org-element-property :post-affiliated element)))
21938 (unless (< p post-affiliated)
21939 (cl-case type
21940 (comment
21941 (save-excursion
21942 (beginning-of-line)
21943 (looking-at "[ \t]*")
21944 (concat (match-string 0) "# ")))
21945 (footnote-definition "")
21946 ((item plain-list)
21947 (make-string (org-list-item-body-column post-affiliated) ?\s))
21948 (paragraph
21949 ;; Fill prefix is usually the same as the current line,
21950 ;; unless the paragraph is at the beginning of an item.
21951 (let ((parent (org-element-property :parent element)))
21952 (save-excursion
21953 (beginning-of-line)
21954 (cond ((eq (org-element-type parent) 'item)
21955 (make-string (org-list-item-body-column
21956 (org-element-property :begin parent))
21957 ?\s))
21958 ((and adaptive-fill-regexp
21959 ;; Locally disable
21960 ;; `adaptive-fill-function' to let
21961 ;; `fill-context-prefix' handle
21962 ;; `adaptive-fill-regexp' variable.
21963 (let (adaptive-fill-function)
21964 (fill-context-prefix
21965 post-affiliated
21966 (org-element-property :end element)))))
21967 ((looking-at "[ \t]+") (match-string 0))
21968 (t "")))))
21969 (comment-block
21970 ;; Only fill contents if P is within block boundaries.
21971 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21972 (forward-line)
21973 (point)))
21974 (cend (save-excursion
21975 (goto-char (org-element-property :end element))
21976 (skip-chars-backward " \r\t\n")
21977 (line-beginning-position))))
21978 (when (and (>= p cbeg) (< p cend))
21979 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21980 (match-string 0)
21981 ""))))))))))
21983 (defun org-fill-element (&optional justify)
21984 "Fill element at point, when applicable.
21986 This function only applies to comment blocks, comments, example
21987 blocks and paragraphs. Also, as a special case, re-align table
21988 when point is at one.
21990 If JUSTIFY is non-nil (interactively, with prefix argument),
21991 justify as well. If `sentence-end-double-space' is non-nil, then
21992 period followed by one space does not end a sentence, so don't
21993 break a line there. The variable `fill-column' controls the
21994 width for filling.
21996 For convenience, when point is at a plain list, an item or
21997 a footnote definition, try to fill the first paragraph within."
21998 (with-syntax-table org-mode-transpose-word-syntax-table
21999 ;; Move to end of line in order to get the first paragraph within
22000 ;; a plain list or a footnote definition.
22001 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22002 ;; First check if point is in a blank line at the beginning of
22003 ;; the buffer. In that case, ignore filling.
22004 (cl-case (org-element-type element)
22005 ;; Use major mode filling function is src blocks.
22006 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22007 ;; Align Org tables, leave table.el tables as-is.
22008 (table-row (org-table-align) t)
22009 (table
22010 (when (eq (org-element-property :type element) 'org)
22011 (save-excursion
22012 (goto-char (org-element-property :post-affiliated element))
22013 (org-table-align)))
22015 (paragraph
22016 ;; Paragraphs may contain `line-break' type objects.
22017 (let ((beg (max (point-min)
22018 (org-element-property :contents-begin element)))
22019 (end (min (point-max)
22020 (org-element-property :contents-end element))))
22021 ;; Do nothing if point is at an affiliated keyword.
22022 (if (< (line-end-position) beg) t
22023 ;; Fill paragraph, taking line breaks into account.
22024 (save-excursion
22025 (goto-char beg)
22026 (let ((cuts (list beg)))
22027 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22028 (when (eq 'line-break
22029 (org-element-type
22030 (save-excursion (backward-char)
22031 (org-element-context))))
22032 (push (point) cuts)))
22033 (dolist (c (delq end cuts))
22034 (fill-region-as-paragraph c end justify)
22035 (setq end c))))
22036 t)))
22037 ;; Contents of `comment-block' type elements should be
22038 ;; filled as plain text, but only if point is within block
22039 ;; markers.
22040 (comment-block
22041 (let* ((case-fold-search t)
22042 (beg (save-excursion
22043 (goto-char (org-element-property :begin element))
22044 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22045 (forward-line)
22046 (point)))
22047 (end (save-excursion
22048 (goto-char (org-element-property :end element))
22049 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22050 (line-beginning-position))))
22051 (if (or (< (point) beg) (> (point) end)) t
22052 (fill-region-as-paragraph
22053 (save-excursion (end-of-line)
22054 (re-search-backward "^[ \t]*$" beg 'move)
22055 (line-beginning-position))
22056 (save-excursion (beginning-of-line)
22057 (re-search-forward "^[ \t]*$" end 'move)
22058 (line-beginning-position))
22059 justify))))
22060 ;; Fill comments.
22061 (comment
22062 (let ((begin (org-element-property :post-affiliated element))
22063 (end (org-element-property :end element)))
22064 (when (and (>= (point) begin) (<= (point) end))
22065 (let ((begin (save-excursion
22066 (end-of-line)
22067 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22068 (progn (forward-line) (point))
22069 begin)))
22070 (end (save-excursion
22071 (end-of-line)
22072 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22073 (1- (line-beginning-position))
22074 (skip-chars-backward " \r\t\n")
22075 (line-end-position)))))
22076 ;; Do not fill comments when at a blank line.
22077 (when (> end begin)
22078 (let ((fill-prefix
22079 (save-excursion
22080 (beginning-of-line)
22081 (looking-at "[ \t]*#")
22082 (let ((comment-prefix (match-string 0)))
22083 (goto-char (match-end 0))
22084 (if (looking-at adaptive-fill-regexp)
22085 (concat comment-prefix (match-string 0))
22086 (concat comment-prefix " "))))))
22087 (save-excursion
22088 (fill-region-as-paragraph begin end justify))))))
22090 ;; Ignore every other element.
22091 (otherwise t)))))
22093 (defun org-fill-paragraph (&optional justify region)
22094 "Fill element at point, when applicable.
22096 This function only applies to comment blocks, comments, example
22097 blocks and paragraphs. Also, as a special case, re-align table
22098 when point is at one.
22100 For convenience, when point is at a plain list, an item or
22101 a footnote definition, try to fill the first paragraph within.
22103 If JUSTIFY is non-nil (interactively, with prefix argument),
22104 justify as well. If `sentence-end-double-space' is non-nil, then
22105 period followed by one space does not end a sentence, so don't
22106 break a line there. The variable `fill-column' controls the
22107 width for filling.
22109 The REGION argument is non-nil if called interactively; in that
22110 case, if Transient Mark mode is enabled and the mark is active,
22111 fill each of the elements in the active region, instead of just
22112 filling the current element."
22113 (interactive (progn
22114 (barf-if-buffer-read-only)
22115 (list (when current-prefix-arg 'full) t)))
22116 (cond
22117 ((and region transient-mark-mode mark-active
22118 (not (eq (region-beginning) (region-end))))
22119 (let ((origin (point-marker))
22120 (start (region-beginning)))
22121 (unwind-protect
22122 (progn
22123 (goto-char (region-end))
22124 (while (> (point) start)
22125 (org-backward-paragraph)
22126 (org-fill-element justify)))
22127 (goto-char origin)
22128 (set-marker origin nil))))
22129 (t (org-fill-element justify))))
22131 (defun org-auto-fill-function ()
22132 "Auto-fill function."
22133 ;; Check if auto-filling is meaningful.
22134 (let ((fc (current-fill-column)))
22135 (when (and fc (> (current-column) fc))
22136 (let* ((fill-prefix (org-adaptive-fill-function))
22137 ;; Enforce empty fill prefix, if required. Otherwise, it
22138 ;; will be computed again.
22139 (adaptive-fill-mode (not (equal fill-prefix ""))))
22140 (when fill-prefix (do-auto-fill))))))
22142 (defun org-comment-line-break-function (&optional soft)
22143 "Break line at point and indent, continuing comment if within one.
22144 The inserted newline is marked hard if variable
22145 `use-hard-newlines' is true, unless optional argument SOFT is
22146 non-nil."
22147 (if soft (insert-and-inherit ?\n) (newline 1))
22148 (save-excursion (forward-char -1) (delete-horizontal-space))
22149 (delete-horizontal-space)
22150 (indent-to-left-margin)
22151 (insert-before-markers-and-inherit fill-prefix))
22154 ;;; Fixed Width Areas
22156 (defun org-toggle-fixed-width ()
22157 "Toggle fixed-width markup.
22159 Add or remove fixed-width markup on current line, whenever it
22160 makes sense. Return an error otherwise.
22162 If a region is active and if it contains only fixed-width areas
22163 or blank lines, remove all fixed-width markup in it. If the
22164 region contains anything else, convert all non-fixed-width lines
22165 to fixed-width ones.
22167 Blank lines at the end of the region are ignored unless the
22168 region only contains such lines."
22169 (interactive)
22170 (if (not (org-region-active-p))
22171 ;; No region:
22173 ;; Remove fixed width marker only in a fixed-with element.
22175 ;; Add fixed width maker in paragraphs, in blank lines after
22176 ;; elements or at the beginning of a headline or an inlinetask,
22177 ;; and before any one-line elements (e.g., a clock).
22178 (progn
22179 (beginning-of-line)
22180 (let* ((element (org-element-at-point))
22181 (type (org-element-type element)))
22182 (cond
22183 ((and (eq type 'fixed-width)
22184 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22185 (replace-match
22186 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22187 ((and (memq type '(babel-call clock comment diary-sexp headline
22188 horizontal-rule keyword paragraph
22189 planning))
22190 (<= (org-element-property :post-affiliated element) (point)))
22191 (skip-chars-forward " \t")
22192 (insert ": "))
22193 ((and (looking-at-p "[ \t]*$")
22194 (or (eq type 'inlinetask)
22195 (save-excursion
22196 (skip-chars-forward " \r\t\n")
22197 (<= (org-element-property :end element) (point)))))
22198 (delete-region (point) (line-end-position))
22199 (org-indent-line)
22200 (insert ": "))
22201 (t (user-error "Cannot insert a fixed-width line here")))))
22202 ;; Region active.
22203 (let* ((begin (save-excursion
22204 (goto-char (region-beginning))
22205 (line-beginning-position)))
22206 (end (copy-marker
22207 (save-excursion
22208 (goto-char (region-end))
22209 (unless (eolp) (beginning-of-line))
22210 (if (save-excursion (re-search-backward "\\S-" begin t))
22211 (progn (skip-chars-backward " \r\t\n") (point))
22212 (point)))))
22213 (all-fixed-width-p
22214 (catch 'not-all-p
22215 (save-excursion
22216 (goto-char begin)
22217 (skip-chars-forward " \r\t\n")
22218 (when (eobp) (throw 'not-all-p nil))
22219 (while (< (point) end)
22220 (let ((element (org-element-at-point)))
22221 (if (eq (org-element-type element) 'fixed-width)
22222 (goto-char (org-element-property :end element))
22223 (throw 'not-all-p nil))))
22224 t))))
22225 (if all-fixed-width-p
22226 (save-excursion
22227 (goto-char begin)
22228 (while (< (point) end)
22229 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22230 (replace-match
22231 "" nil nil nil
22232 (if (= (line-end-position) (match-end 0)) 0 1)))
22233 (forward-line)))
22234 (let ((min-ind (point-max)))
22235 ;; Find minimum indentation across all lines.
22236 (save-excursion
22237 (goto-char begin)
22238 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22239 (setq min-ind 0)
22240 (catch 'zerop
22241 (while (< (point) end)
22242 (unless (looking-at-p "[ \t]*$")
22243 (let ((ind (current-indentation)))
22244 (setq min-ind (min min-ind ind))
22245 (when (zerop ind) (throw 'zerop t))))
22246 (forward-line)))))
22247 ;; Loop over all lines and add fixed-width markup everywhere
22248 ;; but in fixed-width lines.
22249 (save-excursion
22250 (goto-char begin)
22251 (while (< (point) end)
22252 (cond
22253 ((org-at-heading-p)
22254 (insert ": ")
22255 (forward-line)
22256 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22257 (insert ":")
22258 (forward-line)))
22259 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22260 (let* ((element (org-element-at-point))
22261 (element-end (org-element-property :end element)))
22262 (if (eq (org-element-type element) 'fixed-width)
22263 (progn (goto-char element-end)
22264 (skip-chars-backward " \r\t\n")
22265 (forward-line))
22266 (let ((limit (min end element-end)))
22267 (while (< (point) limit)
22268 (org-move-to-column min-ind t)
22269 (insert ": ")
22270 (forward-line))))))
22272 (org-move-to-column min-ind t)
22273 (insert ": ")
22274 (forward-line)))))))
22275 (set-marker end nil))))
22278 ;;; Blocks
22280 (defun org-block-map (function &optional start end)
22281 "Call FUNCTION at the head of all source blocks in the current buffer.
22282 Optional arguments START and END can be used to limit the range."
22283 (let ((start (or start (point-min)))
22284 (end (or end (point-max))))
22285 (save-excursion
22286 (goto-char start)
22287 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22288 (save-excursion
22289 (save-match-data
22290 (goto-char (match-beginning 0))
22291 (funcall function)))))))
22293 (defun org-next-block (arg &optional backward block-regexp)
22294 "Jump to the next block.
22296 With a prefix argument ARG, jump forward ARG many blocks.
22298 When BACKWARD is non-nil, jump to the previous block.
22300 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22301 Match data is set according to this regexp when the function
22302 returns.
22304 Return point at beginning of the opening line of found block.
22305 Throw an error if no block is found."
22306 (interactive "p")
22307 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22308 (case-fold-search t)
22309 (search-fn (if backward #'re-search-backward #'re-search-forward))
22310 (count (or arg 1))
22311 (origin (point))
22312 last-element)
22313 (if backward (beginning-of-line) (end-of-line))
22314 (while (and (> count 0) (funcall search-fn re nil t))
22315 (let ((element (save-excursion
22316 (goto-char (match-beginning 0))
22317 (save-match-data (org-element-at-point)))))
22318 (when (and (memq (org-element-type element)
22319 '(center-block comment-block dynamic-block
22320 example-block export-block quote-block
22321 special-block src-block verse-block))
22322 (<= (match-beginning 0)
22323 (org-element-property :post-affiliated element)))
22324 (setq last-element element)
22325 (cl-decf count))))
22326 (if (= count 0)
22327 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22328 (save-match-data (org-show-context)))
22329 (goto-char origin)
22330 (user-error "No %s code blocks" (if backward "previous" "further")))))
22332 (defun org-previous-block (arg &optional block-regexp)
22333 "Jump to the previous block.
22334 With a prefix argument ARG, jump backward ARG many source blocks.
22335 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22336 (interactive "p")
22337 (org-next-block arg t block-regexp))
22340 ;;; Comments
22342 ;; Org comments syntax is quite complex. It requires the entire line
22343 ;; to be just a comment. Also, even with the right syntax at the
22344 ;; beginning of line, some elements (e.g., verse-block or
22345 ;; example-block) don't accept comments. Usual Emacs comment commands
22346 ;; cannot cope with those requirements. Therefore, Org replaces them.
22348 ;; Org still relies on `comment-dwim', but cannot trust
22349 ;; `comment-only-p'. So, `comment-region-function' and
22350 ;; `uncomment-region-function' both point
22351 ;; to`org-comment-or-uncomment-region'. Eventually,
22352 ;; `org-insert-comment' takes care of insertion of comments at the
22353 ;; beginning of line.
22355 ;; `org-setup-comments-handling' install comments related variables
22356 ;; during `org-mode' initialization.
22358 (defun org-setup-comments-handling ()
22359 (interactive)
22360 (setq-local comment-use-syntax nil)
22361 (setq-local comment-start "# ")
22362 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22363 (setq-local comment-insert-comment-function 'org-insert-comment)
22364 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22365 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22367 (defun org-insert-comment ()
22368 "Insert an empty comment above current line.
22369 If the line is empty, insert comment at its beginning. When
22370 point is within a source block, comment according to the related
22371 major mode."
22372 (if (let ((element (org-element-at-point)))
22373 (and (eq (org-element-type element) 'src-block)
22374 (< (save-excursion
22375 (goto-char (org-element-property :post-affiliated element))
22376 (line-end-position))
22377 (point))
22378 (> (save-excursion
22379 (goto-char (org-element-property :end element))
22380 (skip-chars-backward " \r\t\n")
22381 (line-beginning-position))
22382 (point))))
22383 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22384 (beginning-of-line)
22385 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22386 (open-line 1))
22387 (org-indent-line)
22388 (insert "# ")))
22390 (defvar comment-empty-lines) ; From newcomment.el.
22391 (defun org-comment-or-uncomment-region (beg end &rest _)
22392 "Comment or uncomment each non-blank line in the region.
22393 Uncomment each non-blank line between BEG and END if it only
22394 contains commented lines. Otherwise, comment them. If region is
22395 strictly within a source block, use appropriate comment syntax."
22396 (if (let ((element (org-element-at-point)))
22397 (and (eq (org-element-type element) 'src-block)
22398 (< (save-excursion
22399 (goto-char (org-element-property :post-affiliated element))
22400 (line-end-position))
22401 beg)
22402 (>= (save-excursion
22403 (goto-char (org-element-property :end element))
22404 (skip-chars-backward " \r\t\n")
22405 (line-beginning-position))
22406 end)))
22407 ;; Translate region boundaries for the Org buffer to the source
22408 ;; buffer.
22409 (let ((offset (- end beg)))
22410 (save-excursion
22411 (goto-char beg)
22412 (org-babel-do-in-edit-buffer
22413 (comment-or-uncomment-region (point) (+ offset (point))))))
22414 (save-restriction
22415 ;; Restrict region
22416 (narrow-to-region (save-excursion (goto-char beg)
22417 (skip-chars-forward " \r\t\n" end)
22418 (line-beginning-position))
22419 (save-excursion (goto-char end)
22420 (skip-chars-backward " \r\t\n" beg)
22421 (line-end-position)))
22422 (let ((uncommentp
22423 ;; UNCOMMENTP is non-nil when every non blank line between
22424 ;; BEG and END is a comment.
22425 (save-excursion
22426 (goto-char (point-min))
22427 (while (and (not (eobp))
22428 (let ((element (org-element-at-point)))
22429 (and (eq (org-element-type element) 'comment)
22430 (goto-char (min (point-max)
22431 (org-element-property
22432 :end element)))))))
22433 (eobp))))
22434 (if uncommentp
22435 ;; Only blank lines and comments in region: uncomment it.
22436 (save-excursion
22437 (goto-char (point-min))
22438 (while (not (eobp))
22439 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22440 (replace-match "" nil nil nil 1))
22441 (forward-line)))
22442 ;; Comment each line in region.
22443 (let ((min-indent (point-max)))
22444 ;; First find the minimum indentation across all lines.
22445 (save-excursion
22446 (goto-char (point-min))
22447 (while (and (not (eobp)) (not (zerop min-indent)))
22448 (unless (looking-at "[ \t]*$")
22449 (setq min-indent (min min-indent (current-indentation))))
22450 (forward-line)))
22451 ;; Then loop over all lines.
22452 (save-excursion
22453 (goto-char (point-min))
22454 (while (not (eobp))
22455 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22456 ;; Don't get fooled by invisible text (e.g. link path)
22457 ;; when moving to column MIN-INDENT.
22458 (let ((buffer-invisibility-spec nil))
22459 (org-move-to-column min-indent t))
22460 (insert comment-start))
22461 (forward-line)))))))))
22463 (defun org-comment-dwim (_arg)
22464 "Call the comment command you mean.
22465 Call `org-toggle-comment' if on a heading, otherwise call
22466 `comment-dwim', within a source edit buffer if needed."
22467 (interactive "*P")
22468 (cond ((org-at-heading-p)
22469 (call-interactively #'org-toggle-comment))
22470 ((org-in-src-block-p)
22471 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22472 (t (call-interactively #'comment-dwim))))
22475 ;;; Timestamps API
22477 ;; This section contains tools to operate on, or create, timestamp
22478 ;; objects, as returned by, e.g. `org-element-context'.
22480 (defun org-timestamp-from-string (s)
22481 "Convert Org timestamp S, as a string, into a timestamp object.
22482 Return nil if S is not a valid timestamp string."
22483 (when (org-string-nw-p s)
22484 (with-temp-buffer
22485 (save-excursion (insert s))
22486 (org-element-timestamp-parser))))
22488 (defun org-timestamp-from-time (time &optional with-time inactive)
22489 "Convert a time value into a timestamp object.
22491 TIME is an Emacs internal time representation, as returned, e.g.,
22492 by `current-time'.
22494 When optional argument WITH-TIME is non-nil, return a timestamp
22495 object with a time part, i.e., with hours and minutes.
22497 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22498 return an active timestamp."
22499 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22500 (org-element-create 'timestamp
22501 (list :type (if inactive 'inactive 'active)
22502 :year-start year
22503 :month-start month
22504 :day-start day
22505 :hour-start (and with-time hour)
22506 :minute-start (and with-time minute)))))
22508 (defun org-timestamp-to-time (timestamp &optional end)
22509 "Convert TIMESTAMP object into an Emacs internal time value.
22510 Use end of date range or time range when END is non-nil.
22511 Otherwise, use its start."
22512 (apply #'encode-time
22513 (cons 0
22514 (mapcar
22515 (lambda (prop) (or (org-element-property prop timestamp) 0))
22516 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22517 '(:minute-start :hour-start :day-start :month-start
22518 :year-start))))))
22520 (defun org-timestamp-has-time-p (timestamp)
22521 "Non-nil when TIMESTAMP has a time specified."
22522 (org-element-property :hour-start timestamp))
22524 (defun org-timestamp-format (timestamp format &optional end utc)
22525 "Format a TIMESTAMP object into a string.
22527 FORMAT is a format specifier to be passed to
22528 `format-time-string'.
22530 When optional argument END is non-nil, use end of date-range or
22531 time-range, if possible.
22533 When optional argument UTC is non-nil, time is be expressed as
22534 Universal Time."
22535 (format-time-string format (org-timestamp-to-time timestamp end)
22536 (and utc t)))
22538 (defun org-timestamp-split-range (timestamp &optional end)
22539 "Extract a TIMESTAMP object from a date or time range.
22541 END, when non-nil, means extract the end of the range.
22542 Otherwise, extract its start.
22544 Return a new timestamp object."
22545 (let ((type (org-element-property :type timestamp)))
22546 (if (memq type '(active inactive diary)) timestamp
22547 (let ((split-ts (org-element-copy timestamp)))
22548 ;; Set new type.
22549 (org-element-put-property
22550 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22551 ;; Copy start properties over end properties if END is
22552 ;; non-nil. Otherwise, copy end properties over `start' ones.
22553 (let ((p-alist '((:minute-start . :minute-end)
22554 (:hour-start . :hour-end)
22555 (:day-start . :day-end)
22556 (:month-start . :month-end)
22557 (:year-start . :year-end))))
22558 (dolist (p-cell p-alist)
22559 (org-element-put-property
22560 split-ts
22561 (funcall (if end #'car #'cdr) p-cell)
22562 (org-element-property
22563 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22564 ;; Eventually refresh `:raw-value'.
22565 (org-element-put-property split-ts :raw-value nil)
22566 (org-element-put-property
22567 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22569 (defun org-timestamp-translate (timestamp &optional boundary)
22570 "Translate TIMESTAMP object to custom format.
22572 Format string is defined in `org-time-stamp-custom-formats',
22573 which see.
22575 When optional argument BOUNDARY is non-nil, it is either the
22576 symbol `start' or `end'. In this case, only translate the
22577 starting or ending part of TIMESTAMP if it is a date or time
22578 range. Otherwise, translate both parts.
22580 Return timestamp as-is if `org-display-custom-times' is nil or if
22581 it has a `diary' type."
22582 (let ((type (org-element-property :type timestamp)))
22583 (if (or (not org-display-custom-times) (eq type 'diary))
22584 (org-element-interpret-data timestamp)
22585 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22586 org-time-stamp-custom-formats)))
22587 (if (and (not boundary) (memq type '(active-range inactive-range)))
22588 (concat (org-timestamp-format timestamp fmt)
22589 "--"
22590 (org-timestamp-format timestamp fmt t))
22591 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22593 ;;; Other stuff
22595 (defvar reftex-docstruct-symbol)
22596 (defvar org--rds)
22598 (defun org-reftex-citation ()
22599 "Use reftex-citation to insert a citation into the buffer.
22600 This looks for a line like
22602 #+BIBLIOGRAPHY: foo plain option:-d
22604 and derives from it that foo.bib is the bibliography file relevant
22605 for this document. It then installs the necessary environment for RefTeX
22606 to work in this buffer and calls `reftex-citation' to insert a citation
22607 into the buffer.
22609 Export of such citations to both LaTeX and HTML is handled by the contributed
22610 package ox-bibtex by Taru Karttunen."
22611 (interactive)
22612 (let ((reftex-docstruct-symbol 'org--rds)
22613 org--rds bib)
22614 (org-with-wide-buffer
22615 (let ((case-fold-search t)
22616 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22617 (if (not (save-excursion
22618 (or (re-search-forward re nil t)
22619 (re-search-backward re nil t))))
22620 (user-error "No bibliography defined in file")
22621 (setq bib (concat (match-string 1) ".bib")
22622 org--rds (list (list 'bib bib))))))
22623 (call-interactively 'reftex-citation)))
22625 ;;;; Functions extending outline functionality
22627 (defun org-beginning-of-line (&optional n)
22628 "Go to the beginning of the current visible line.
22630 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22631 symbol `reversed', on the first attempt move to where the
22632 headline text starts, and only move to beginning of line when the
22633 cursor is already before the start of the text of the headline.
22635 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22636 start of the text on the second attempt.
22638 With argument N not nil or 1, move forward N - 1 lines first."
22639 (interactive "^p")
22640 (let ((origin (point))
22641 (special (pcase org-special-ctrl-a/e
22642 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22643 deactivate-mark)
22644 ;; First move to a visible line.
22645 (if (bound-and-true-p visual-line-mode)
22646 (beginning-of-visual-line n)
22647 (move-beginning-of-line n)
22648 ;; `move-beginning-of-line' may leave point after invisible
22649 ;; characters if line starts with such of these (e.g., with
22650 ;; a link at column 0). Really move to the beginning of the
22651 ;; current visible line.
22652 (beginning-of-line))
22653 (cond
22654 ;; No special behavior. Point is already at the beginning of
22655 ;; a line, logical or visual.
22656 ((not special))
22657 ;; `beginning-of-visual-line' left point before logical beginning
22658 ;; of line: point is at the beginning of a visual line. Bail
22659 ;; out.
22660 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22661 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22662 ;; At a headline, special position is before the title, but
22663 ;; after any TODO keyword or priority cookie.
22664 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22665 (line-end-position)))
22666 (bol (point)))
22667 (if (eq special 'reversed)
22668 (when (and (= origin bol) (eq last-command this-command))
22669 (goto-char refpos))
22670 (when (or (> origin refpos) (= origin bol))
22671 (goto-char refpos)))))
22672 ((and (looking-at org-list-full-item-re)
22673 (memq (org-element-type (save-match-data (org-element-at-point)))
22674 '(item plain-list)))
22675 ;; Set special position at first white space character after
22676 ;; bullet, and check-box, if any.
22677 (let ((after-bullet
22678 (let ((box (match-end 3)))
22679 (cond ((not box) (match-end 1))
22680 ((eq (char-after box) ?\s) (1+ box))
22681 (t box)))))
22682 (if (eq special 'reversed)
22683 (when (and (= (point) origin) (eq last-command this-command))
22684 (goto-char after-bullet))
22685 (when (or (> origin after-bullet) (= (point) origin))
22686 (goto-char after-bullet)))))
22687 ;; No special context. Point is already at beginning of line.
22688 (t nil))))
22690 (defun org-end-of-line (&optional n)
22691 "Go to the end of the line, but before ellipsis, if any.
22693 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22694 symbol `reversed', ignore tags on the first attempt, and only
22695 move to after the tags when the cursor is already beyond the end
22696 of the headline.
22698 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22699 on the second attempt.
22701 With argument N not nil or 1, move forward N - 1 lines first."
22702 (interactive "^p")
22703 (let ((origin (point))
22704 (special (pcase org-special-ctrl-a/e
22705 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22706 deactivate-mark)
22707 ;; First move to a visible line.
22708 (if (bound-and-true-p visual-line-mode)
22709 (beginning-of-visual-line n)
22710 (move-beginning-of-line n))
22711 (cond
22712 ;; At a headline, with tags.
22713 ((and special
22714 (save-excursion
22715 (beginning-of-line)
22716 (let ((case-fold-search nil))
22717 (looking-at org-complex-heading-regexp)))
22718 (match-end 5))
22719 (let ((tags (save-excursion
22720 (goto-char (match-beginning 5))
22721 (skip-chars-backward " \t")
22722 (point)))
22723 (visual-end (and (bound-and-true-p visual-line-mode)
22724 (save-excursion
22725 (end-of-visual-line)
22726 (point)))))
22727 ;; If `end-of-visual-line' brings us before end of line or
22728 ;; even tags, i.e., the headline spans over multiple visual
22729 ;; lines, move there.
22730 (cond ((and visual-end
22731 (< visual-end tags)
22732 (<= origin visual-end))
22733 (goto-char visual-end))
22734 ((eq special 'reversed)
22735 (if (and (= origin (line-end-position))
22736 (eq this-command last-command))
22737 (goto-char tags)
22738 (end-of-line)))
22740 (if (or (< origin tags) (= origin (line-end-position)))
22741 (goto-char tags)
22742 (end-of-line))))))
22743 ((bound-and-true-p visual-line-mode)
22744 (let ((bol (line-beginning-position)))
22745 (end-of-visual-line)
22746 ;; If `end-of-visual-line' gets us past the ellipsis at the
22747 ;; end of a line, backtrack and use `end-of-line' instead.
22748 (when (/= bol (line-beginning-position))
22749 (goto-char bol)
22750 (end-of-line))))
22751 (t (end-of-line)))))
22753 (defun org-backward-sentence (&optional _arg)
22754 "Go to beginning of sentence, or beginning of table field.
22755 This will call `backward-sentence' or `org-table-beginning-of-field',
22756 depending on context."
22757 (interactive)
22758 (let* ((element (org-element-at-point))
22759 (contents-begin (org-element-property :contents-begin element))
22760 (table (org-element-lineage element '(table) t)))
22761 (if (and table
22762 (> (point) contents-begin)
22763 (<= (point) (org-element-property :contents-end table)))
22764 (call-interactively #'org-table-beginning-of-field)
22765 (save-restriction
22766 (when (and contents-begin
22767 (< (point-min) contents-begin)
22768 (> (point) contents-begin))
22769 (narrow-to-region contents-begin
22770 (org-element-property :contents-end element)))
22771 (call-interactively #'backward-sentence)))))
22773 (defun org-forward-sentence (&optional _arg)
22774 "Go to end of sentence, or end of table field.
22775 This will call `forward-sentence' or `org-table-end-of-field',
22776 depending on context."
22777 (interactive)
22778 (if (and (org-at-heading-p)
22779 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22780 (save-restriction
22781 (narrow-to-region (line-beginning-position) (line-end-position))
22782 (call-interactively #'forward-sentence))
22783 (let* ((element (org-element-at-point))
22784 (contents-end (org-element-property :contents-end element))
22785 (table (org-element-lineage element '(table) t)))
22786 (if (and table
22787 (>= (point) (org-element-property :contents-begin table))
22788 (< (point) contents-end))
22789 (call-interactively #'org-table-end-of-field)
22790 (save-restriction
22791 (when (and contents-end
22792 (> (point-max) contents-end)
22793 ;; Skip blank lines between elements.
22794 (< (org-element-property :end element)
22795 (save-excursion (goto-char contents-end)
22796 (skip-chars-forward " \r\t\n"))))
22797 (narrow-to-region (org-element-property :contents-begin element)
22798 contents-end))
22799 ;; End of heading is considered as the end of a sentence.
22800 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22801 (call-interactively #'forward-sentence)))))))
22803 (defun org-kill-line (&optional _arg)
22804 "Kill line, to tags or end of line."
22805 (interactive)
22806 (cond
22807 ((or (not org-special-ctrl-k)
22808 (bolp)
22809 (not (org-at-heading-p)))
22810 (when (and (get-char-property (line-end-position) 'invisible)
22811 org-ctrl-k-protect-subtree
22812 (or (eq org-ctrl-k-protect-subtree 'error)
22813 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22814 (user-error
22815 (substitute-command-keys
22816 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22817 (call-interactively
22818 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22819 ((looking-at org-tag-line-re)
22820 (let ((end (save-excursion
22821 (goto-char (match-beginning 1))
22822 (skip-chars-backward " \t"))))
22823 (if (<= end (point)) ;on tags part
22824 (kill-region (point) (line-end-position))
22825 (kill-region (point) end)))
22826 (org-align-tags))
22827 (t (kill-region (point) (line-end-position)))))
22829 (defun org-yank (&optional arg)
22830 "Yank. If the kill is a subtree, treat it specially.
22831 This command will look at the current kill and check if is a single
22832 subtree, or a series of subtrees[1]. If it passes the test, and if the
22833 cursor is at the beginning of a line or after the stars of a currently
22834 empty headline, then the yank is handled specially. How exactly depends
22835 on the value of the following variables.
22837 `org-yank-folded-subtrees'
22838 By default, this variable is non-nil, which results in
22839 subtree(s) being folded after insertion, except if doing so
22840 would swallow text after the yanked text.
22842 `org-yank-adjusted-subtrees'
22843 When non-nil (the default value is nil), the subtree will be
22844 promoted or demoted in order to fit into the local outline tree
22845 structure, which means that the level will be adjusted so that it
22846 becomes the smaller one of the two *visible* surrounding headings.
22848 Any prefix to this command will cause `yank' to be called directly with
22849 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22850 will just
22851 plainly yank the text as it is.
22853 \[1] The test checks if the first non-white line is a heading
22854 and if there are no other headings with fewer stars."
22855 (interactive "P")
22856 (org-yank-generic 'yank arg))
22858 (defun org-yank-generic (command arg)
22859 "Perform some yank-like command.
22861 This function implements the behavior described in the `org-yank'
22862 documentation. However, it has been generalized to work for any
22863 interactive command with similar behavior."
22865 ;; pretend to be command COMMAND
22866 (setq this-command command)
22868 (if arg
22869 (call-interactively command)
22871 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22872 (and (org-kill-is-subtree-p)
22873 (or (bolp)
22874 (and (looking-at "[ \t]*$")
22875 (string-match
22876 "\\`\\*+\\'"
22877 (buffer-substring (point-at-bol) (point)))))))
22878 swallowp)
22879 (cond
22880 ((and subtreep org-yank-folded-subtrees)
22881 (let ((beg (point))
22882 end)
22883 (if (and subtreep org-yank-adjusted-subtrees)
22884 (org-paste-subtree nil nil 'for-yank)
22885 (call-interactively command))
22887 (setq end (point))
22888 (goto-char beg)
22889 (when (and (bolp) subtreep
22890 (not (setq swallowp
22891 (org-yank-folding-would-swallow-text beg end))))
22892 (org-with-limited-levels
22893 (or (looking-at org-outline-regexp)
22894 (re-search-forward org-outline-regexp-bol end t))
22895 (while (and (< (point) end) (looking-at org-outline-regexp))
22896 (outline-hide-subtree)
22897 (org-cycle-show-empty-lines 'folded)
22898 (condition-case nil
22899 (outline-forward-same-level 1)
22900 (error (goto-char end))))))
22901 (when swallowp
22902 (message
22903 "Inserted text not folded because that would swallow text"))
22905 (goto-char end)
22906 (skip-chars-forward " \t\n\r")
22907 (beginning-of-line 1)
22908 (push-mark beg 'nomsg)))
22909 ((and subtreep org-yank-adjusted-subtrees)
22910 (let ((beg (point-at-bol)))
22911 (org-paste-subtree nil nil 'for-yank)
22912 (push-mark beg 'nomsg)))
22914 (call-interactively command))))))
22916 (defun org-yank-folding-would-swallow-text (beg end)
22917 "Would hide-subtree at BEG swallow any text after END?"
22918 (let (level)
22919 (org-with-limited-levels
22920 (save-excursion
22921 (goto-char beg)
22922 (when (or (looking-at org-outline-regexp)
22923 (re-search-forward org-outline-regexp-bol end t))
22924 (setq level (org-outline-level)))
22925 (goto-char end)
22926 (skip-chars-forward " \t\r\n\v\f")
22927 (not (or (eobp)
22928 (and (bolp) (looking-at-p org-outline-regexp)
22929 (<= (org-outline-level) level))))))))
22931 (defun org-back-to-heading (&optional invisible-ok)
22932 "Call `outline-back-to-heading', but provide a better error message."
22933 (condition-case nil
22934 (outline-back-to-heading invisible-ok)
22935 (error (error "Before first headline at position %d in buffer %s"
22936 (point) (current-buffer)))))
22938 (defun org-before-first-heading-p ()
22939 "Before first heading?"
22940 (save-excursion
22941 (end-of-line)
22942 (null (re-search-backward org-outline-regexp-bol nil t))))
22944 (defun org-at-heading-p (&optional ignored)
22945 (outline-on-heading-p t))
22947 (defun org-in-commented-heading-p (&optional no-inheritance)
22948 "Non-nil if point is under a commented heading.
22949 This function also checks ancestors of the current headline,
22950 unless optional argument NO-INHERITANCE is non-nil."
22951 (cond
22952 ((org-before-first-heading-p) nil)
22953 ((let ((headline (nth 4 (org-heading-components))))
22954 (and headline
22955 (let ((case-fold-search nil))
22956 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22957 headline)))))
22958 (no-inheritance nil)
22960 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22962 (defun org-at-comment-p nil
22963 "Is cursor in a commented line?"
22964 (save-excursion
22965 (save-match-data
22966 (beginning-of-line)
22967 (looking-at "^[ \t]*# "))))
22969 (defun org-at-drawer-p nil
22970 "Is cursor at a drawer keyword?"
22971 (save-excursion
22972 (move-beginning-of-line 1)
22973 (looking-at org-drawer-regexp)))
22975 (defun org-at-block-p nil
22976 "Is cursor at a block keyword?"
22977 (save-excursion
22978 (move-beginning-of-line 1)
22979 (looking-at org-block-regexp)))
22981 (defun org-point-at-end-of-empty-headline ()
22982 "If point is at the end of an empty headline, return t, else nil.
22983 If the heading only contains a TODO keyword, it is still still considered
22984 empty."
22985 (let ((case-fold-search nil))
22986 (and (looking-at "[ \t]*$")
22987 org-todo-line-regexp
22988 (save-excursion
22989 (beginning-of-line)
22990 (looking-at org-todo-line-regexp)
22991 (string= (match-string 3) "")))))
22993 (defun org-at-heading-or-item-p ()
22994 (or (org-at-heading-p) (org-at-item-p)))
22996 (defun org-at-target-p ()
22997 (or (org-in-regexp org-radio-target-regexp)
22998 (org-in-regexp org-target-regexp)))
23000 (defun org-up-heading-all (arg)
23001 "Move to the heading line of which the present line is a subheading.
23002 This function considers both visible and invisible heading lines.
23003 With argument, move up ARG levels."
23004 (outline-up-heading arg t))
23006 (defun org-up-heading-safe ()
23007 "Move to the heading line of which the present line is a subheading.
23008 This version will not throw an error. It will return the level of the
23009 headline found, or nil if no higher level is found.
23011 Also, this function will be a lot faster than `outline-up-heading',
23012 because it relies on stars being the outline starters. This can really
23013 make a significant difference in outlines with very many siblings."
23014 (when (ignore-errors (org-back-to-heading t))
23015 (let ((level-up (1- (funcall outline-level))))
23016 (and (> level-up 0)
23017 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23018 (funcall outline-level)))))
23020 (defun org-first-sibling-p ()
23021 "Is this heading the first child of its parents?"
23022 (interactive)
23023 (let ((re org-outline-regexp-bol)
23024 level l)
23025 (unless (org-at-heading-p t)
23026 (user-error "Not at a heading"))
23027 (setq level (funcall outline-level))
23028 (save-excursion
23029 (if (not (re-search-backward re nil t))
23031 (setq l (funcall outline-level))
23032 (< l level)))))
23034 (defun org-goto-sibling (&optional previous)
23035 "Goto the next sibling, even if it is invisible.
23036 When PREVIOUS is set, go to the previous sibling instead. Returns t
23037 when a sibling was found. When none is found, return nil and don't
23038 move point."
23039 (let ((fun (if previous 're-search-backward 're-search-forward))
23040 (pos (point))
23041 (re org-outline-regexp-bol)
23042 level l)
23043 (when (ignore-errors (org-back-to-heading t))
23044 (setq level (funcall outline-level))
23045 (catch 'exit
23046 (or previous (forward-char 1))
23047 (while (funcall fun re nil t)
23048 (setq l (funcall outline-level))
23049 (when (< l level) (goto-char pos) (throw 'exit nil))
23050 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23051 (goto-char pos)
23052 nil))))
23054 (defun org-show-siblings ()
23055 "Show all siblings of the current headline."
23056 (save-excursion
23057 (while (org-goto-sibling) (org-flag-heading nil)))
23058 (save-excursion
23059 (while (org-goto-sibling 'previous)
23060 (org-flag-heading nil))))
23062 (defun org-goto-first-child ()
23063 "Goto the first child, even if it is invisible.
23064 Return t when a child was found. Otherwise don't move point and
23065 return nil."
23066 (let (level (pos (point)) (re org-outline-regexp-bol))
23067 (when (ignore-errors (org-back-to-heading t))
23068 (setq level (outline-level))
23069 (forward-char 1)
23070 (if (and (re-search-forward re nil t) (> (outline-level) level))
23071 (progn (goto-char (match-beginning 0)) t)
23072 (goto-char pos) nil))))
23074 (defun org-show-hidden-entry ()
23075 "Show an entry where even the heading is hidden."
23076 (save-excursion
23077 (org-show-entry)))
23079 (defun org-flag-heading (flag &optional entry)
23080 "Flag the current heading. FLAG non-nil means make invisible.
23081 When ENTRY is non-nil, show the entire entry."
23082 (save-excursion
23083 (org-back-to-heading t)
23084 ;; Check if we should show the entire entry
23085 (if (not entry)
23086 (org-flag-region
23087 (line-end-position 0) (line-end-position) flag 'outline)
23088 (org-show-entry)
23089 (save-excursion
23090 (and (outline-next-heading)
23091 (org-flag-heading nil))))))
23093 (defun org-get-next-sibling ()
23094 "Move to next heading of the same level, and return point.
23095 If there is no such heading, return nil.
23096 This is like outline-next-sibling, but invisible headings are ok."
23097 (let ((level (funcall outline-level)))
23098 (outline-next-heading)
23099 (while (and (not (eobp)) (> (funcall outline-level) level))
23100 (outline-next-heading))
23101 (unless (or (eobp) (< (funcall outline-level) level))
23102 (point))))
23104 (defun org-get-last-sibling ()
23105 "Move to previous heading of the same level, and return point.
23106 If there is no such heading, return nil."
23107 (let ((opoint (point))
23108 (level (funcall outline-level)))
23109 (outline-previous-heading)
23110 (when (and (/= (point) opoint) (outline-on-heading-p t))
23111 (while (and (> (funcall outline-level) level)
23112 (not (bobp)))
23113 (outline-previous-heading))
23114 (unless (< (funcall outline-level) level)
23115 (point)))))
23117 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23118 "Goto to the end of a subtree."
23119 ;; This contains an exact copy of the original function, but it uses
23120 ;; `org-back-to-heading', to make it work also in invisible
23121 ;; trees. And is uses an invisible-ok argument.
23122 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23123 ;; Furthermore, when used inside Org, finding the end of a large subtree
23124 ;; with many children and grandchildren etc, this can be much faster
23125 ;; than the outline version.
23126 (org-back-to-heading invisible-ok)
23127 (let ((first t)
23128 (level (funcall outline-level)))
23129 (if (and (derived-mode-p 'org-mode) (< level 1000))
23130 ;; A true heading (not a plain list item), in Org
23131 ;; This means we can easily find the end by looking
23132 ;; only for the right number of stars. Using a regexp to do
23133 ;; this is so much faster than using a Lisp loop.
23134 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23135 (forward-char 1)
23136 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23137 ;; something else, do it the slow way
23138 (while (and (not (eobp))
23139 (or first (> (funcall outline-level) level)))
23140 (setq first nil)
23141 (outline-next-heading)))
23142 (unless to-heading
23143 (when (memq (preceding-char) '(?\n ?\^M))
23144 ;; Go to end of line before heading
23145 (forward-char -1)
23146 (when (memq (preceding-char) '(?\n ?\^M))
23147 ;; leave blank line before heading
23148 (forward-char -1)))))
23149 (point))
23151 (defun org-end-of-meta-data (&optional full)
23152 "Skip planning line and properties drawer in current entry.
23153 When optional argument FULL is non-nil, also skip empty lines,
23154 clocking lines and regular drawers at the beginning of the
23155 entry."
23156 (org-back-to-heading t)
23157 (forward-line)
23158 (when (looking-at-p org-planning-line-re) (forward-line))
23159 (when (looking-at org-property-drawer-re)
23160 (goto-char (match-end 0))
23161 (forward-line))
23162 (when (and full (not (org-at-heading-p)))
23163 (catch 'exit
23164 (let ((end (save-excursion (outline-next-heading) (point)))
23165 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23166 (while (not (eobp))
23167 (cond ((looking-at-p org-drawer-regexp)
23168 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23169 (forward-line)
23170 (throw 'exit t)))
23171 ((looking-at-p re) (forward-line))
23172 (t (throw 'exit t))))))))
23174 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23175 "Move forward to the ARG'th subheading at same level as this one.
23176 Stop at the first and last subheadings of a superior heading.
23177 Normally this only looks at visible headings, but when INVISIBLE-OK is
23178 non-nil it will also look at invisible ones."
23179 (interactive "p")
23180 (let ((backward? (and arg (< arg 0))))
23181 (if (org-before-first-heading-p)
23182 (if backward? (goto-char (point-min)) (outline-next-heading))
23183 (org-back-to-heading invisible-ok)
23184 (unless backward? (end-of-line)) ;do not match current headline
23185 (let ((level (- (match-end 0) (match-beginning 0) 1))
23186 (f (if backward? #'re-search-backward #'re-search-forward))
23187 (count (if arg (abs arg) 1))
23188 (result (point)))
23189 (while (and (> count 0)
23190 (funcall f org-outline-regexp-bol nil 'move))
23191 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23192 (cond ((< l level) (setq count 0))
23193 ((and (= l level)
23194 (or invisible-ok
23195 (not (org-invisible-p
23196 (line-beginning-position)))))
23197 (cl-decf count)
23198 (when (= l level) (setq result (point)))))))
23199 (goto-char result))
23200 (beginning-of-line))))
23202 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23203 "Move backward to the ARG'th subheading at same level as this one.
23204 Stop at the first and last subheadings of a superior heading."
23205 (interactive "p")
23206 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23208 (defun org-next-visible-heading (arg)
23209 "Move to the next visible heading.
23211 This function wraps `outline-next-visible-heading' with
23212 `org-with-limited-levels' in order to skip over inline tasks and
23213 respect customization of `org-odd-levels-only'."
23214 (interactive "p")
23215 (org-with-limited-levels
23216 (outline-next-visible-heading arg)))
23218 (defun org-previous-visible-heading (arg)
23219 "Move to the previous visible heading.
23221 This function wraps `outline-previous-visible-heading' with
23222 `org-with-limited-levels' in order to skip over inline tasks and
23223 respect customization of `org-odd-levels-only'."
23224 (interactive "p")
23225 (org-with-limited-levels
23226 (outline-previous-visible-heading arg)))
23228 (defun org-forward-paragraph ()
23229 "Move forward to beginning of next paragraph or equivalent.
23231 The function moves point to the beginning of the next visible
23232 structural element, which can be a paragraph, a table, a list
23233 item, etc. It also provides some special moves for convenience:
23235 - On an affiliated keyword, jump to the beginning of the
23236 relative element.
23237 - On an item or a footnote definition, move to the second
23238 element inside, if any.
23239 - On a table or a property drawer, jump after it.
23240 - On a verse or source block, stop after blank lines."
23241 (interactive)
23242 (unless (eobp)
23243 (let* ((deactivate-mark nil)
23244 (element (org-element-at-point))
23245 (type (org-element-type element))
23246 (post-affiliated (org-element-property :post-affiliated element))
23247 (contents-begin (org-element-property :contents-begin element))
23248 (contents-end (org-element-property :contents-end element))
23249 (end (let ((end (org-element-property :end element)) (parent element))
23250 (while (and (setq parent (org-element-property :parent parent))
23251 (= (org-element-property :contents-end parent) end))
23252 (setq end (org-element-property :end parent)))
23253 end)))
23254 (cond ((not element)
23255 (skip-chars-forward " \r\t\n")
23256 (or (eobp) (beginning-of-line)))
23257 ;; On affiliated keywords, move to element's beginning.
23258 ((< (point) post-affiliated)
23259 (goto-char post-affiliated))
23260 ;; At a table row, move to the end of the table. Similarly,
23261 ;; at a node property, move to the end of the property
23262 ;; drawer.
23263 ((memq type '(node-property table-row))
23264 (goto-char (org-element-property
23265 :end (org-element-property :parent element))))
23266 ((memq type '(property-drawer table)) (goto-char end))
23267 ;; Consider blank lines as separators in verse and source
23268 ;; blocks to ease editing.
23269 ((memq type '(src-block verse-block))
23270 (when (eq type 'src-block)
23271 (setq contents-end
23272 (save-excursion (goto-char end)
23273 (skip-chars-backward " \r\t\n")
23274 (line-beginning-position))))
23275 (beginning-of-line)
23276 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23277 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23278 (goto-char end)
23279 (skip-chars-forward " \r\t\n")
23280 (if (= (point) contents-end) (goto-char end)
23281 (beginning-of-line))))
23282 ;; With no contents, just skip element.
23283 ((not contents-begin) (goto-char end))
23284 ;; If contents are invisible, skip the element altogether.
23285 ((org-invisible-p (line-end-position))
23286 (cl-case type
23287 (headline
23288 (org-with-limited-levels (outline-next-visible-heading 1)))
23289 ;; At a plain list, make sure we move to the next item
23290 ;; instead of skipping the whole list.
23291 (plain-list (forward-char)
23292 (org-forward-paragraph))
23293 (otherwise (goto-char end))))
23294 ((>= (point) contents-end) (goto-char end))
23295 ((>= (point) contents-begin)
23296 ;; This can only happen on paragraphs and plain lists.
23297 (cl-case type
23298 (paragraph (goto-char end))
23299 ;; At a plain list, try to move to second element in
23300 ;; first item, if possible.
23301 (plain-list (end-of-line)
23302 (org-forward-paragraph))))
23303 ;; When contents start on the middle of a line (e.g. in
23304 ;; items and footnote definitions), try to reach first
23305 ;; element starting after current line.
23306 ((> (line-end-position) contents-begin)
23307 (end-of-line)
23308 (org-forward-paragraph))
23309 (t (goto-char contents-begin))))))
23311 (defun org-backward-paragraph ()
23312 "Move backward to start of previous paragraph or equivalent.
23314 The function moves point to the beginning of the current
23315 structural element, which can be a paragraph, a table, a list
23316 item, etc., or to the beginning of the previous visible one if
23317 point is already there. It also provides some special moves for
23318 convenience:
23320 - On an affiliated keyword, jump to the first one.
23321 - On a table or a property drawer, move to its beginning.
23322 - On comment, example, export, src and verse blocks, stop
23323 before blank lines."
23324 (interactive)
23325 (unless (bobp)
23326 (let* ((deactivate-mark nil)
23327 (element (org-element-at-point))
23328 (type (org-element-type element))
23329 (contents-end (org-element-property :contents-end element))
23330 (post-affiliated (org-element-property :post-affiliated element))
23331 (begin (org-element-property :begin element))
23332 (special? ;blocks handled specially
23333 (memq type '(comment-block example-block export-block src-block
23334 verse-block)))
23335 (contents-begin
23336 (if special?
23337 ;; These types have no proper contents. Fake line
23338 ;; below the block opening line as contents beginning.
23339 (save-excursion (goto-char begin) (line-beginning-position 2))
23340 (org-element-property :contents-begin element))))
23341 (cond
23342 ((not element) (goto-char (point-min)))
23343 ((= (point) begin)
23344 (backward-char)
23345 (org-backward-paragraph))
23346 ((<= (point) post-affiliated) (goto-char begin))
23347 ;; Special behavior: on a table or a property drawer, move to
23348 ;; its beginning.
23349 ((memq type '(node-property table-row))
23350 (goto-char (org-element-property
23351 :post-affiliated (org-element-property :parent element))))
23352 (special?
23353 (if (<= (point) contents-begin) (goto-char post-affiliated)
23354 ;; Inside a verse block, see blank lines as paragraph
23355 ;; separators.
23356 (let ((origin (point)))
23357 (skip-chars-backward " \r\t\n" contents-begin)
23358 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23359 (skip-chars-forward " \r\t\n" origin)
23360 (if (= (point) origin) (goto-char contents-begin)
23361 (beginning-of-line))))))
23362 ((eq type 'paragraph) (goto-char contents-begin)
23363 ;; When at first paragraph in an item or a footnote definition,
23364 ;; move directly to beginning of line.
23365 (let ((parent-contents
23366 (org-element-property
23367 :contents-begin (org-element-property :parent element))))
23368 (when (and parent-contents (= parent-contents contents-begin))
23369 (beginning-of-line))))
23370 ;; At the end of a greater element, move to the beginning of
23371 ;; the last element within.
23372 ((and contents-end (>= (point) contents-end))
23373 (goto-char (1- contents-end))
23374 (org-backward-paragraph))
23375 (t (goto-char (or post-affiliated begin))))
23376 ;; Ensure we never leave point invisible.
23377 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23379 (defun org-forward-element ()
23380 "Move forward by one element.
23381 Move to the next element at the same level, when possible."
23382 (interactive)
23383 (cond ((eobp) (user-error "Cannot move further down"))
23384 ((org-with-limited-levels (org-at-heading-p))
23385 (let ((origin (point)))
23386 (goto-char (org-end-of-subtree nil t))
23387 (unless (org-with-limited-levels (org-at-heading-p))
23388 (goto-char origin)
23389 (user-error "Cannot move further down"))))
23391 (let* ((elem (org-element-at-point))
23392 (end (org-element-property :end elem))
23393 (parent (org-element-property :parent elem)))
23394 (cond ((and parent (= (org-element-property :contents-end parent) end))
23395 (goto-char (org-element-property :end parent)))
23396 ((integer-or-marker-p end) (goto-char end))
23397 (t (message "No element at point")))))))
23399 (defun org-backward-element ()
23400 "Move backward by one element.
23401 Move to the previous element at the same level, when possible."
23402 (interactive)
23403 (cond ((bobp) (user-error "Cannot move further up"))
23404 ((org-with-limited-levels (org-at-heading-p))
23405 ;; At a headline, move to the previous one, if any, or stay
23406 ;; here.
23407 (let ((origin (point)))
23408 (org-with-limited-levels (org-backward-heading-same-level 1))
23409 ;; When current headline has no sibling above, move to its
23410 ;; parent.
23411 (when (= (point) origin)
23412 (or (org-with-limited-levels (org-up-heading-safe))
23413 (progn (goto-char origin)
23414 (user-error "Cannot move further up"))))))
23416 (let* ((elem (org-element-at-point))
23417 (beg (org-element-property :begin elem)))
23418 (cond
23419 ;; Move to beginning of current element if point isn't
23420 ;; there already.
23421 ((null beg) (message "No element at point"))
23422 ((/= (point) beg) (goto-char beg))
23423 (t (goto-char beg)
23424 (skip-chars-backward " \r\t\n")
23425 (unless (bobp)
23426 (let ((prev (org-element-at-point)))
23427 (goto-char (org-element-property :begin prev))
23428 (while (and (setq prev (org-element-property :parent prev))
23429 (<= (org-element-property :end prev) beg))
23430 (goto-char (org-element-property :begin prev)))))))))))
23432 (defun org-up-element ()
23433 "Move to upper element."
23434 (interactive)
23435 (if (org-with-limited-levels (org-at-heading-p))
23436 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23437 (let* ((elem (org-element-at-point))
23438 (parent (org-element-property :parent elem)))
23439 (if parent (goto-char (org-element-property :begin parent))
23440 (if (org-with-limited-levels (org-before-first-heading-p))
23441 (user-error "No surrounding element")
23442 (org-with-limited-levels (org-back-to-heading)))))))
23444 (defun org-down-element ()
23445 "Move to inner element."
23446 (interactive)
23447 (let ((element (org-element-at-point)))
23448 (cond
23449 ((memq (org-element-type element) '(plain-list table))
23450 (goto-char (org-element-property :contents-begin element))
23451 (forward-char))
23452 ((memq (org-element-type element) org-element-greater-elements)
23453 ;; If contents are hidden, first disclose them.
23454 (when (org-invisible-p (line-end-position)) (org-cycle))
23455 (goto-char (or (org-element-property :contents-begin element)
23456 (user-error "No content for this element"))))
23457 (t (user-error "No inner element")))))
23459 (defun org-drag-element-backward ()
23460 "Move backward element at point."
23461 (interactive)
23462 (let ((elem (or (org-element-at-point)
23463 (user-error "No element at point"))))
23464 (if (eq (org-element-type elem) 'headline)
23465 ;; Preserve point when moving a whole tree, even if point was
23466 ;; on blank lines below the headline.
23467 (let ((offset (skip-chars-backward " \t\n")))
23468 (unwind-protect (org-move-subtree-up)
23469 (forward-char (- offset))))
23470 (let ((prev-elem
23471 (save-excursion
23472 (goto-char (org-element-property :begin elem))
23473 (skip-chars-backward " \r\t\n")
23474 (unless (bobp)
23475 (let* ((beg (org-element-property :begin elem))
23476 (prev (org-element-at-point))
23477 (up prev))
23478 (while (and (setq up (org-element-property :parent up))
23479 (<= (org-element-property :end up) beg))
23480 (setq prev up))
23481 prev)))))
23482 ;; Error out if no previous element or previous element is
23483 ;; a parent of the current one.
23484 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23485 (user-error "Cannot drag element backward")
23486 (let ((pos (point)))
23487 (org-element-swap-A-B prev-elem elem)
23488 (goto-char (+ (org-element-property :begin prev-elem)
23489 (- pos (org-element-property :begin elem))))))))))
23491 (defun org-drag-element-forward ()
23492 "Move forward element at point."
23493 (interactive)
23494 (let* ((pos (point))
23495 (elem (or (org-element-at-point)
23496 (user-error "No element at point"))))
23497 (when (= (point-max) (org-element-property :end elem))
23498 (user-error "Cannot drag element forward"))
23499 (goto-char (org-element-property :end elem))
23500 (let ((next-elem (org-element-at-point)))
23501 (when (or (org-element-nested-p elem next-elem)
23502 (and (eq (org-element-type next-elem) 'headline)
23503 (not (eq (org-element-type elem) 'headline))))
23504 (goto-char pos)
23505 (user-error "Cannot drag element forward"))
23506 ;; Compute new position of point: it's shifted by NEXT-ELEM
23507 ;; body's length (without final blanks) and by the length of
23508 ;; blanks between ELEM and NEXT-ELEM.
23509 (let ((size-next (- (save-excursion
23510 (goto-char (org-element-property :end next-elem))
23511 (skip-chars-backward " \r\t\n")
23512 (forward-line)
23513 ;; Small correction if buffer doesn't end
23514 ;; with a newline character.
23515 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23516 (org-element-property :begin next-elem)))
23517 (size-blank (- (org-element-property :end elem)
23518 (save-excursion
23519 (goto-char (org-element-property :end elem))
23520 (skip-chars-backward " \r\t\n")
23521 (forward-line)
23522 (point)))))
23523 (org-element-swap-A-B elem next-elem)
23524 (goto-char (+ pos size-next size-blank))))))
23526 (defun org-drag-line-forward (arg)
23527 "Drag the line at point ARG lines forward."
23528 (interactive "p")
23529 (dotimes (_ (abs arg))
23530 (let ((c (current-column)))
23531 (if (< 0 arg)
23532 (progn
23533 (beginning-of-line 2)
23534 (transpose-lines 1)
23535 (beginning-of-line 0))
23536 (transpose-lines 1)
23537 (beginning-of-line -1))
23538 (org-move-to-column c))))
23540 (defun org-drag-line-backward (arg)
23541 "Drag the line at point ARG lines backward."
23542 (interactive "p")
23543 (org-drag-line-forward (- arg)))
23545 (defun org-mark-element ()
23546 "Put point at beginning of this element, mark at end.
23548 Interactively, if this command is repeated or (in Transient Mark
23549 mode) if the mark is active, it marks the next element after the
23550 ones already marked."
23551 (interactive)
23552 (let (deactivate-mark)
23553 (if (and (called-interactively-p 'any)
23554 (or (and (eq last-command this-command) (mark t))
23555 (and transient-mark-mode mark-active)))
23556 (set-mark
23557 (save-excursion
23558 (goto-char (mark))
23559 (goto-char (org-element-property :end (org-element-at-point)))))
23560 (let ((element (org-element-at-point)))
23561 (end-of-line)
23562 (push-mark (org-element-property :end element) t t)
23563 (goto-char (org-element-property :begin element))))))
23565 (defun org-narrow-to-element ()
23566 "Narrow buffer to current element."
23567 (interactive)
23568 (let ((elem (org-element-at-point)))
23569 (cond
23570 ((eq (car elem) 'headline)
23571 (narrow-to-region
23572 (org-element-property :begin elem)
23573 (org-element-property :end elem)))
23574 ((memq (car elem) org-element-greater-elements)
23575 (narrow-to-region
23576 (org-element-property :contents-begin elem)
23577 (org-element-property :contents-end elem)))
23579 (narrow-to-region
23580 (org-element-property :begin elem)
23581 (org-element-property :end elem))))))
23583 (defun org-transpose-element ()
23584 "Transpose current and previous elements, keeping blank lines between.
23585 Point is moved after both elements."
23586 (interactive)
23587 (org-skip-whitespace)
23588 (let ((end (org-element-property :end (org-element-at-point))))
23589 (org-drag-element-backward)
23590 (goto-char end)))
23592 (defun org-unindent-buffer ()
23593 "Un-indent the visible part of the buffer.
23594 Relative indentation (between items, inside blocks, etc.) isn't
23595 modified."
23596 (interactive)
23597 (unless (eq major-mode 'org-mode)
23598 (user-error "Cannot un-indent a buffer not in Org mode"))
23599 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23600 (unindent-tree
23601 (lambda (contents)
23602 (dolist (element (reverse contents))
23603 (if (memq (org-element-type element) '(headline section))
23604 (funcall unindent-tree (org-element-contents element))
23605 (save-excursion
23606 (save-restriction
23607 (narrow-to-region
23608 (org-element-property :begin element)
23609 (org-element-property :end element))
23610 (org-do-remove-indentation))))))))
23611 (funcall unindent-tree (org-element-contents parse-tree))))
23613 (defun org-make-options-regexp (kwds &optional extra)
23614 "Make a regular expression for keyword lines.
23615 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23616 when non-nil, is a regexp matching keywords names."
23617 (concat "^[ \t]*#\\+\\("
23618 (regexp-opt kwds)
23619 (and extra (concat (and kwds "\\|") extra))
23620 "\\):[ \t]*\\(.*\\)"))
23623 ;;; Finish up
23625 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23626 (lambda () (add-hook 'change-major-mode-hook
23627 'org-show-all 'append 'local)))
23629 (provide 'org)
23631 (run-hooks 'org-load-hook)
23633 ;;; org.el ends here