"src block" -> "source block" in documentation and comments
[org-mode/org-tableheadings.git] / lisp / org.el
blobebe928bcc3013705bc5263ab76d5bac3988d2118
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: https://orgmode.org
10 ;; Version: 9.2
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org mode develops organizational tasks around NOTES files that
33 ;; contain information about projects as plain text. Org mode is
34 ;; implemented on top of outline-mode, which makes it possible to keep
35 ;; the content of large files well structured. Visibility cycling and
36 ;; structure editing help to work with the tree. Tables are easily
37 ;; created with a built-in table editor. Org mode supports ToDo
38 ;; items, deadlines, time stamps, and scheduling. It dynamically
39 ;; compiles entries into an agenda that utilizes and smoothly
40 ;; integrates much of the Emacs calendar and diary. Plain text
41 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
42 ;; entries, and any files related to the projects. For printing and
43 ;; sharing of notes, an Org file can be exported as a structured ASCII
44 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
45 ;; file. It can also serve as a publishing tool for a set of linked
46 ;; webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; https://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the doc/ directory.
62 ;; A list of recent changes can be found at
63 ;; https://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar-local org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (defvar org-inlinetask-min-level)
72 ;;;; Require other packages
74 (require 'cl-lib)
76 (eval-when-compile (require 'gnus-sum))
78 (require 'calendar)
79 (require 'find-func)
80 (require 'format-spec)
82 (or (eq this-command 'eval-buffer)
83 (condition-case nil
84 (load (concat (file-name-directory load-file-name)
85 "org-loaddefs.el")
86 nil t t t)
87 (error
88 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
89 (sit-for 3)
90 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
91 (sit-for 3))))
93 (eval-and-compile (require 'org-macs))
94 (require 'org-compat)
96 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
97 ;; some places -- e.g. see the macro `org-with-limited-levels'.
98 (defvar org-outline-regexp "\\*+ "
99 "Regexp to match Org headlines.")
101 (defvar org-outline-regexp-bol "^\\*+ "
102 "Regexp to match Org headlines.
103 This is similar to `org-outline-regexp' but additionally makes
104 sure that we are at the beginning of the line.")
106 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
107 "Matches a headline, putting stars and text into groups.
108 Stars are put in group 1 and the trimmed body in group 2.")
110 (declare-function calendar-check-holidays "holidays" (date))
111 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
112 (declare-function cdlatex-math-symbol "ext:cdlatex")
113 (declare-function 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 task 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
2917 You can have local logging settings for a subtree by setting the LOGGING
2918 property to one or more of these keywords.
2920 This variable has an effect when calling `org-schedule' or
2921 `org-agenda-schedule' only."
2922 :group 'org-todo
2923 :group 'org-progress
2924 :type '(choice
2925 (const :tag "No logging" nil)
2926 (const :tag "Record timestamp" time)
2927 (const :tag "Record timestamp with note" note)))
2929 (defcustom org-log-redeadline nil
2930 "Information to record when the deadline date of a task is modified.
2932 Possible values are:
2934 nil Don't add anything, just change the date
2935 time Add a time stamp to the task
2936 note Prompt for a note and add it with template `org-log-note-headings'
2938 This option can also be set with on a per-file-basis with
2940 #+STARTUP: nologredeadline
2941 #+STARTUP: logredeadline
2942 #+STARTUP: lognoteredeadline
2944 You can have local logging settings for a subtree by setting the LOGGING
2945 property to one or more of these keywords.
2947 This variable has an effect when calling `org-deadline' or
2948 `org-agenda-deadline' only."
2949 :group 'org-todo
2950 :group 'org-progress
2951 :type '(choice
2952 (const :tag "No logging" nil)
2953 (const :tag "Record timestamp" time)
2954 (const :tag "Record timestamp with note." note)))
2956 (defcustom org-log-note-clock-out nil
2957 "Non-nil means record a note when clocking out of an item.
2958 This can also be configured on a per-file basis by adding one of
2959 the following lines anywhere in the buffer:
2961 #+STARTUP: lognoteclock-out
2962 #+STARTUP: nolognoteclock-out"
2963 :group 'org-todo
2964 :group 'org-progress
2965 :type 'boolean)
2967 (defcustom org-log-done-with-time t
2968 "Non-nil means the CLOSED time stamp will contain date and time.
2969 When nil, only the date will be recorded."
2970 :group 'org-progress
2971 :type 'boolean)
2973 (defcustom org-log-note-headings
2974 '((done . "CLOSING NOTE %t")
2975 (state . "State %-12s from %-12S %t")
2976 (note . "Note taken on %t")
2977 (reschedule . "Rescheduled from %S on %t")
2978 (delschedule . "Not scheduled, was %S on %t")
2979 (redeadline . "New deadline from %S on %t")
2980 (deldeadline . "Removed deadline, was %S on %t")
2981 (refile . "Refiled on %t")
2982 (clock-out . ""))
2983 "Headings for notes added to entries.
2985 The value is an alist, with the car being a symbol indicating the
2986 note context, and the cdr is the heading to be used. The heading
2987 may also be the empty string. The following placeholders can be
2988 used:
2990 %t a time stamp.
2991 %T an active time stamp instead the default inactive one
2992 %d a short-format time stamp.
2993 %D an active short-format time stamp.
2994 %s the new TODO state or time stamp (inactive), in double quotes.
2995 %S the old TODO state or time stamp (inactive), in double quotes.
2996 %u the user name.
2997 %U full user name.
2999 In fact, it is not a good idea to change the `state' entry,
3000 because Agenda Log mode depends on the format of these entries."
3001 :group 'org-todo
3002 :group 'org-progress
3003 :type '(list :greedy t
3004 (cons (const :tag "Heading when closing an item" done) string)
3005 (cons (const :tag
3006 "Heading when changing todo state (todo sequence only)"
3007 state) string)
3008 (cons (const :tag "Heading when just taking a note" note) string)
3009 (cons (const :tag "Heading when rescheduling" reschedule) string)
3010 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3011 (cons (const :tag "Heading when changing deadline" redeadline) string)
3012 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3013 (cons (const :tag "Heading when refiling" refile) string)
3014 (cons (const :tag "Heading when clocking out" clock-out) string)))
3016 (unless (assq 'note org-log-note-headings)
3017 (push '(note . "%t") org-log-note-headings))
3019 (defcustom org-log-into-drawer nil
3020 "Non-nil means insert state change notes and time stamps into a drawer.
3021 When nil, state changes notes will be inserted after the headline and
3022 any scheduling and clock lines, but not inside a drawer.
3024 The value of this variable should be the name of the drawer to use.
3025 LOGBOOK is proposed as the default drawer for this purpose, you can
3026 also set this to a string to define the drawer of your choice.
3028 A value of t is also allowed, representing \"LOGBOOK\".
3030 A value of t or nil can also be set with on a per-file-basis with
3032 #+STARTUP: logdrawer
3033 #+STARTUP: nologdrawer
3035 If this variable is set, `org-log-state-notes-insert-after-drawers'
3036 will be ignored.
3038 You can set the property LOG_INTO_DRAWER to overrule this setting for
3039 a subtree.
3041 Do not check directly this variable in a Lisp program. Call
3042 function `org-log-into-drawer' instead."
3043 :group 'org-todo
3044 :group 'org-progress
3045 :type '(choice
3046 (const :tag "Not into a drawer" nil)
3047 (const :tag "LOGBOOK" t)
3048 (string :tag "Other")))
3050 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3052 (defun org-log-into-drawer ()
3053 "Name of the log drawer, as a string, or nil.
3054 This is the value of `org-log-into-drawer'. However, if the
3055 current entry has or inherits a LOG_INTO_DRAWER property, it will
3056 be used instead of the default value."
3057 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3058 (cond ((equal p "nil") nil)
3059 ((equal p "t") "LOGBOOK")
3060 ((stringp p) p)
3061 (p "LOGBOOK")
3062 ((stringp org-log-into-drawer) org-log-into-drawer)
3063 (org-log-into-drawer "LOGBOOK"))))
3065 (defcustom org-log-state-notes-insert-after-drawers nil
3066 "Non-nil means insert state change notes after any drawers in entry.
3067 Only the drawers that *immediately* follow the headline and the
3068 deadline/scheduled line are skipped.
3069 When nil, insert notes right after the heading and perhaps the line
3070 with deadline/scheduling if present.
3072 This variable will have no effect if `org-log-into-drawer' is
3073 set."
3074 :group 'org-todo
3075 :group 'org-progress
3076 :type 'boolean)
3078 (defcustom org-log-states-order-reversed t
3079 "Non-nil means the latest state note will be directly after heading.
3080 When nil, the state change notes will be ordered according to time.
3082 This option can also be set with on a per-file-basis with
3084 #+STARTUP: logstatesreversed
3085 #+STARTUP: nologstatesreversed"
3086 :group 'org-todo
3087 :group 'org-progress
3088 :type 'boolean)
3090 (defcustom org-todo-repeat-to-state nil
3091 "The TODO state to which a repeater should return the repeating task.
3092 By default this is the first task of a TODO sequence or the
3093 previous state of a TYPE_TODO set. But you can specify to use
3094 the previous state in a TODO sequence or a string.
3096 Alternatively, you can set the :REPEAT_TO_STATE: property of the
3097 entry, which has precedence over this option."
3098 :group 'org-todo
3099 :version "24.1"
3100 :type '(choice (const :tag "Use the previous TODO state" t)
3101 (const :tag "Use the head of the TODO sequence" nil)
3102 (string :tag "Use a specific TODO state")))
3104 (defcustom org-log-repeat 'time
3105 "Non-nil means record moving through the DONE state when triggering repeat.
3106 An auto-repeating task is immediately switched back to TODO when
3107 marked DONE. If you are not logging state changes (by adding \"@\"
3108 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3109 record a closing note, there will be no record of the task moving
3110 through DONE. This variable forces taking a note anyway.
3112 nil Don't force a record
3113 time Record a time stamp
3114 note Prompt for a note and add it with template `org-log-note-headings'
3116 This option can also be set with on a per-file-basis with
3118 #+STARTUP: nologrepeat
3119 #+STARTUP: logrepeat
3120 #+STARTUP: lognoterepeat
3122 You can have local logging settings for a subtree by setting the LOGGING
3123 property to one or more of these keywords."
3124 :group 'org-todo
3125 :group 'org-progress
3126 :type '(choice
3127 (const :tag "Don't force a record" nil)
3128 (const :tag "Force recording the DONE state" time)
3129 (const :tag "Force recording a note with the DONE state" note)))
3132 (defgroup org-priorities nil
3133 "Priorities in Org mode."
3134 :tag "Org Priorities"
3135 :group 'org-todo)
3137 (defcustom org-enable-priority-commands t
3138 "Non-nil means priority commands are active.
3139 When nil, these commands will be disabled, so that you never accidentally
3140 set a priority."
3141 :group 'org-priorities
3142 :type 'boolean)
3144 (defcustom org-highest-priority ?A
3145 "The highest priority of TODO items. A character like ?A, ?B etc.
3146 Must have a smaller ASCII number than `org-lowest-priority'."
3147 :group 'org-priorities
3148 :type 'character)
3150 (defcustom org-lowest-priority ?C
3151 "The lowest priority of TODO items. A character like ?A, ?B etc.
3152 Must have a larger ASCII number than `org-highest-priority'."
3153 :group 'org-priorities
3154 :type 'character)
3156 (defcustom org-default-priority ?B
3157 "The default priority of TODO items.
3158 This is the priority an item gets if no explicit priority is given.
3159 When starting to cycle on an empty priority the first step in the cycle
3160 depends on `org-priority-start-cycle-with-default'. The resulting first
3161 step priority must not exceed the range from `org-highest-priority' to
3162 `org-lowest-priority' which means that `org-default-priority' has to be
3163 in this range exclusive or inclusive the range boundaries. Else the
3164 first step refuses to set the default and the second will fall back
3165 to (depending on the command used) the highest or lowest priority."
3166 :group 'org-priorities
3167 :type 'character)
3169 (defcustom org-priority-start-cycle-with-default t
3170 "Non-nil means start with default priority when starting to cycle.
3171 When this is nil, the first step in the cycle will be (depending on the
3172 command used) one higher or lower than the default priority.
3173 See also `org-default-priority'."
3174 :group 'org-priorities
3175 :type 'boolean)
3177 (defcustom org-get-priority-function nil
3178 "Function to extract the priority from a string.
3179 The string is normally the headline. If this is nil Org computes the
3180 priority from the priority cookie like [#A] in the headline. It returns
3181 an integer, increasing by 1000 for each priority level.
3182 The user can set a different function here, which should take a string
3183 as an argument and return the numeric priority."
3184 :group 'org-priorities
3185 :version "24.1"
3186 :type '(choice
3187 (const nil)
3188 (function)))
3190 (defgroup org-time nil
3191 "Options concerning time stamps and deadlines in Org mode."
3192 :tag "Org Time"
3193 :group 'org)
3195 (defcustom org-time-stamp-rounding-minutes '(0 5)
3196 "Number of minutes to round time stamps to.
3197 \\<org-mode-map>\
3198 These are two values, the first applies when first creating a time stamp.
3199 The second applies when changing it with the commands `S-up' and `S-down'.
3200 When changing the time stamp, this means that it will change in steps
3201 of N minutes, as given by the second value.
3203 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3204 numbers should be factors of 60, so for example 5, 10, 15.
3206 When this is larger than 1, you can still force an exact time stamp by using
3207 a double prefix argument to a time stamp command like \
3208 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3209 and by using a prefix arg to `S-up/down' to specify the exact number
3210 of minutes to shift."
3211 :group 'org-time
3212 :get (lambda (var) ; Make sure both elements are there
3213 (if (integerp (default-value var))
3214 (list (default-value var) 5)
3215 (default-value var)))
3216 :type '(list
3217 (integer :tag "when inserting times")
3218 (integer :tag "when modifying times")))
3220 ;; Normalize old customizations of this variable.
3221 (when (integerp org-time-stamp-rounding-minutes)
3222 (setq org-time-stamp-rounding-minutes
3223 (list org-time-stamp-rounding-minutes
3224 org-time-stamp-rounding-minutes)))
3226 (defcustom org-display-custom-times nil
3227 "Non-nil means overlay custom formats over all time stamps.
3228 The formats are defined through the variable `org-time-stamp-custom-formats'.
3229 To turn this on on a per-file basis, insert anywhere in the file:
3230 #+STARTUP: customtime"
3231 :group 'org-time
3232 :set 'set-default
3233 :type 'sexp)
3234 (make-variable-buffer-local 'org-display-custom-times)
3236 (defcustom org-time-stamp-custom-formats
3237 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3238 "Custom formats for time stamps. See `format-time-string' for the syntax.
3239 These are overlaid over the default ISO format if the variable
3240 `org-display-custom-times' is set. Time like %H:%M should be at the
3241 end of the second format. The custom formats are also honored by export
3242 commands, if custom time display is turned on at the time of export."
3243 :group 'org-time
3244 :type 'sexp)
3246 (defun org-time-stamp-format (&optional long inactive)
3247 "Get the right format for a time string."
3248 (let ((f (if long (cdr org-time-stamp-formats)
3249 (car org-time-stamp-formats))))
3250 (if inactive
3251 (concat "[" (substring f 1 -1) "]")
3252 f)))
3254 (defcustom org-deadline-warning-days 14
3255 "Number of days before expiration during which a deadline becomes active.
3256 This variable governs the display in sparse trees and in the agenda.
3257 When 0 or negative, it means use this number (the absolute value of it)
3258 even if a deadline has a different individual lead time specified.
3260 Custom commands can set this variable in the options section."
3261 :group 'org-time
3262 :group 'org-agenda-daily/weekly
3263 :type 'integer)
3265 (defcustom org-scheduled-delay-days 0
3266 "Number of days before a scheduled item becomes active.
3267 This variable governs the display in sparse trees and in the agenda.
3268 The default value (i.e. 0) means: don't delay scheduled item.
3269 When negative, it means use this number (the absolute value of it)
3270 even if a scheduled item has a different individual delay time
3271 specified.
3273 Custom commands can set this variable in the options section."
3274 :group 'org-time
3275 :group 'org-agenda-daily/weekly
3276 :version "24.4"
3277 :package-version '(Org . "8.0")
3278 :type 'integer)
3280 (defcustom org-read-date-prefer-future t
3281 "Non-nil means assume future for incomplete date input from user.
3282 This affects the following situations:
3283 1. The user gives a month but not a year.
3284 For example, if it is April and you enter \"feb 2\", this will be read
3285 as Feb 2, *next* year. \"May 5\", however, will be this year.
3286 2. The user gives a day, but no month.
3287 For example, if today is the 15th, and you enter \"3\", Org will read
3288 this as the third of *next* month. However, if you enter \"17\",
3289 it will be considered as *this* month.
3291 If you set this variable to the symbol `time', then also the following
3292 will work:
3294 3. If the user gives a time.
3295 If the time is before now, it will be interpreted as tomorrow.
3297 Currently none of this works for ISO week specifications.
3299 When this option is nil, the current day, month and year will always be
3300 used as defaults.
3302 See also `org-agenda-jump-prefer-future'."
3303 :group 'org-time
3304 :type '(choice
3305 (const :tag "Never" nil)
3306 (const :tag "Check month and day" t)
3307 (const :tag "Check month, day, and time" time)))
3309 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3310 "Should the agenda jump command prefer the future for incomplete dates?
3311 The default is to do the same as configured in `org-read-date-prefer-future'.
3312 But you can also set a deviating value here.
3313 This may t or nil, or the symbol `org-read-date-prefer-future'."
3314 :group 'org-agenda
3315 :group 'org-time
3316 :version "24.1"
3317 :type '(choice
3318 (const :tag "Use org-read-date-prefer-future"
3319 org-read-date-prefer-future)
3320 (const :tag "Never" nil)
3321 (const :tag "Always" t)))
3323 (defcustom org-read-date-force-compatible-dates t
3324 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3326 Depending on the system Emacs is running on, certain dates cannot
3327 be represented with the type used internally to represent time.
3328 Dates between 1970-1-1 and 2038-1-1 can always be represented
3329 correctly. Some systems allow for earlier dates, some for later,
3330 some for both. One way to find out it to insert any date into an
3331 Org buffer, putting the cursor on the year and hitting S-up and
3332 S-down to test the range.
3334 When this variable is set to t, the date/time prompt will not let
3335 you specify dates outside the 1970-2037 range, so it is certain that
3336 these dates will work in whatever version of Emacs you are
3337 running, and also that you can move a file from one Emacs implementation
3338 to another. WHenever Org is forcing the year for you, it will display
3339 a message and beep.
3341 When this variable is nil, Org will check if the date is
3342 representable in the specific Emacs implementation you are using.
3343 If not, it will force a year, usually the current year, and beep
3344 to remind you. Currently this setting is not recommended because
3345 the likelihood that you will open your Org files in an Emacs that
3346 has limited date range is not negligible.
3348 A workaround for this problem is to use diary sexp dates for time
3349 stamps outside of this range."
3350 :group 'org-time
3351 :version "24.1"
3352 :type 'boolean)
3354 (defcustom org-read-date-display-live t
3355 "Non-nil means display current interpretation of date prompt live.
3356 This display will be in an overlay, in the minibuffer."
3357 :group 'org-time
3358 :type 'boolean)
3360 (defcustom org-read-date-popup-calendar t
3361 "Non-nil means pop up a calendar when prompting for a date.
3362 In the calendar, the date can be selected with mouse-1. However, the
3363 minibuffer will also be active, and you can simply enter the date as well.
3364 When nil, only the minibuffer will be available."
3365 :group 'org-time
3366 :type 'boolean)
3367 (defvaralias 'org-popup-calendar-for-date-prompt
3368 'org-read-date-popup-calendar)
3370 (defcustom org-extend-today-until 0
3371 "The hour when your day really ends. Must be an integer.
3372 This has influence for the following applications:
3373 - When switching the agenda to \"today\". It it is still earlier than
3374 the time given here, the day recognized as TODAY is actually yesterday.
3375 - When a date is read from the user and it is still before the time given
3376 here, the current date and time will be assumed to be yesterday, 23:59.
3377 Also, timestamps inserted in capture templates follow this rule.
3379 IMPORTANT: This is a feature whose implementation is and likely will
3380 remain incomplete. Really, it is only here because past midnight seems to
3381 be the favorite working time of John Wiegley :-)"
3382 :group 'org-time
3383 :type 'integer)
3385 (defcustom org-use-effective-time nil
3386 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3387 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3388 \"effective time\" of any timestamps between midnight and 8am will be
3389 23:59 of the previous day."
3390 :group 'org-time
3391 :version "24.1"
3392 :type 'boolean)
3394 (defcustom org-use-last-clock-out-time-as-effective-time nil
3395 "When non-nil, use the last clock out time for `org-todo'.
3396 Note that this option has precedence over the combined use of
3397 `org-use-effective-time' and `org-extend-today-until'."
3398 :group 'org-time
3399 :version "24.4"
3400 :package-version '(Org . "8.0")
3401 :type 'boolean)
3403 (defcustom org-edit-timestamp-down-means-later nil
3404 "Non-nil means S-down will increase the time in a time stamp.
3405 When nil, S-up will increase."
3406 :group 'org-time
3407 :type 'boolean)
3409 (defcustom org-calendar-follow-timestamp-change t
3410 "Non-nil means make the calendar window follow timestamp changes.
3411 When a timestamp is modified and the calendar window is visible, it will be
3412 moved to the new date."
3413 :group 'org-time
3414 :type 'boolean)
3416 (defgroup org-tags nil
3417 "Options concerning tags in Org mode."
3418 :tag "Org Tags"
3419 :group 'org)
3421 (defcustom org-tag-alist nil
3422 "Default tags available in Org files.
3424 The value of this variable is an alist. Associations either:
3426 (TAG)
3427 (TAG . SELECT)
3428 (SPECIAL)
3430 where TAG is a tag as a string, SELECT is character, used to
3431 select that tag through the fast tag selection interface, and
3432 SPECIAL is one of the following keywords: `:startgroup',
3433 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
3434 `:newline'. These keywords are used to define a hierarchy of
3435 tags. See manual for details.
3437 When this variable is nil, Org mode bases tag input on what is
3438 already in the buffer. The value can be overridden locally by
3439 using a TAGS keyword, e.g.,
3441 #+TAGS: tag1 tag2
3443 See also `org-tag-persistent-alist' to sidestep this behavior."
3444 :group 'org-tags
3445 :type '(repeat
3446 (choice
3447 (cons :tag "Tag with key"
3448 (string :tag "Tag name")
3449 (character :tag "Access char"))
3450 (list :tag "Tag" (string :tag "Tag name"))
3451 (const :tag "Start radio group" (:startgroup))
3452 (const :tag "Start tag group, non distinct" (:startgrouptag))
3453 (const :tag "Group tags delimiter" (:grouptags))
3454 (const :tag "End radio group" (:endgroup))
3455 (const :tag "End tag group, non distinct" (:endgrouptag))
3456 (const :tag "New line" (:newline)))))
3458 (defcustom org-tag-persistent-alist nil
3459 "Tags always available in Org files.
3461 The value of this variable is an alist. Associations either:
3463 (TAG)
3464 (TAG . SELECT)
3465 (SPECIAL)
3467 where TAG is a tag as a string, SELECT is a character, used to
3468 select that tag through the fast tag selection interface, and
3469 SPECIAL is one of the following keywords: `:startgroup',
3470 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
3471 `:newline'. These keywords are used to define a hierarchy of
3472 tags. See manual for details.
3474 Unlike to `org-tag-alist', tags defined in this variable do not
3475 depend on a local TAGS keyword. Instead, to disable these tags
3476 on a per-file basis, insert anywhere in the file:
3478 #+STARTUP: noptag"
3479 :group 'org-tags
3480 :type '(repeat
3481 (choice
3482 (cons :tag "Tag with key"
3483 (string :tag "Tag name")
3484 (character :tag "Access char"))
3485 (list :tag "Tag" (string :tag "Tag name"))
3486 (const :tag "Start radio group" (:startgroup))
3487 (const :tag "Start tag group, non distinct" (:startgrouptag))
3488 (const :tag "Group tags delimiter" (:grouptags))
3489 (const :tag "End radio group" (:endgroup))
3490 (const :tag "End tag group, non distinct" (:endgrouptag))
3491 (const :tag "New line" (:newline)))))
3493 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3494 "If non-nil, always offer completion for all tags of all agenda files.
3495 Instead of customizing this variable directly, you might want to
3496 set it locally for capture buffers, because there no list of
3497 tags in that file can be created dynamically (there are none).
3499 (add-hook \\='org-capture-mode-hook
3500 (lambda ()
3501 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3502 :group 'org-tags
3503 :version "24.1"
3504 :type 'boolean)
3506 (defvar org-file-tags nil
3507 "List of tags that can be inherited by all entries in the file.
3508 The tags will be inherited if the variable `org-use-tag-inheritance'
3509 says they should be.
3510 This variable is populated from #+FILETAGS lines.")
3512 (defcustom org-use-fast-tag-selection 'auto
3513 "Non-nil means use fast tag selection scheme.
3514 This is a special interface to select and deselect tags with single keys.
3515 When nil, fast selection is never used.
3516 When the symbol `auto', fast selection is used if and only if selection
3517 characters for tags have been configured, either through the variable
3518 `org-tag-alist' or through a #+TAGS line in the buffer.
3519 When t, fast selection is always used and selection keys are assigned
3520 automatically if necessary."
3521 :group 'org-tags
3522 :type '(choice
3523 (const :tag "Always" t)
3524 (const :tag "Never" nil)
3525 (const :tag "When selection characters are configured" auto)))
3527 (defcustom org-fast-tag-selection-single-key nil
3528 "Non-nil means fast tag selection exits after first change.
3529 When nil, you have to press RET to exit it.
3530 During fast tag selection, you can toggle this flag with `C-c'.
3531 This variable can also have the value `expert'. In this case, the window
3532 displaying the tags menu is not even shown, until you press C-c again."
3533 :group 'org-tags
3534 :type '(choice
3535 (const :tag "No" nil)
3536 (const :tag "Yes" t)
3537 (const :tag "Expert" expert)))
3539 (defvar org-fast-tag-selection-include-todo nil
3540 "Non-nil means fast tags selection interface will also offer TODO states.
3541 This is an undocumented feature, you should not rely on it.")
3543 (defcustom org-tags-column -77
3544 "The column to which tags should be indented in a headline.
3545 If this number is positive, it specifies the column. If it is negative,
3546 it means that the tags should be flushright to that column. For example,
3547 -80 works well for a normal 80 character screen.
3548 When 0, place tags directly after headline text, with only one space in
3549 between."
3550 :group 'org-tags
3551 :type 'integer)
3553 (defcustom org-auto-align-tags t
3554 "Non-nil keeps tags aligned when modifying headlines.
3555 Some operations (i.e. demoting) change the length of a headline and
3556 therefore shift the tags around. With this option turned on, after
3557 each such operation the tags are again aligned to `org-tags-column'."
3558 :group 'org-tags
3559 :type 'boolean)
3561 (defcustom org-use-tag-inheritance t
3562 "Non-nil means tags in levels apply also for sublevels.
3563 When nil, only the tags directly given in a specific line apply there.
3564 This may also be a list of tags that should be inherited, or a regexp that
3565 matches tags that should be inherited. Additional control is possible
3566 with the variable `org-tags-exclude-from-inheritance' which gives an
3567 explicit list of tags to be excluded from inheritance, even if the value of
3568 `org-use-tag-inheritance' would select it for inheritance.
3570 If this option is t, a match early-on in a tree can lead to a large
3571 number of matches in the subtree when constructing the agenda or creating
3572 a sparse tree. If you only want to see the first match in a tree during
3573 a search, check out the variable `org-tags-match-list-sublevels'."
3574 :group 'org-tags
3575 :type '(choice
3576 (const :tag "Not" nil)
3577 (const :tag "Always" t)
3578 (repeat :tag "Specific tags" (string :tag "Tag"))
3579 (regexp :tag "Tags matched by regexp")))
3581 (defcustom org-tags-exclude-from-inheritance nil
3582 "List of tags that should never be inherited.
3583 This is a way to exclude a few tags from inheritance. For way to do
3584 the opposite, to actively allow inheritance for selected tags,
3585 see the variable `org-use-tag-inheritance'."
3586 :group 'org-tags
3587 :type '(repeat (string :tag "Tag")))
3589 (defun org-tag-inherit-p (tag)
3590 "Check if TAG is one that should be inherited."
3591 (cond
3592 ((member tag org-tags-exclude-from-inheritance) nil)
3593 ((eq org-use-tag-inheritance t) t)
3594 ((not org-use-tag-inheritance) nil)
3595 ((stringp org-use-tag-inheritance)
3596 (string-match org-use-tag-inheritance tag))
3597 ((listp org-use-tag-inheritance)
3598 (member tag org-use-tag-inheritance))
3599 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3601 (defcustom org-tags-match-list-sublevels t
3602 "Non-nil means list also sublevels of headlines matching a search.
3603 This variable applies to tags/property searches, and also to stuck
3604 projects because this search is based on a tags match as well.
3606 When set to the symbol `indented', sublevels are indented with
3607 leading dots.
3609 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3610 the sublevels of a headline matching a tag search often also match
3611 the same search. Listing all of them can create very long lists.
3612 Setting this variable to nil causes subtrees of a match to be skipped.
3614 This variable is semi-obsolete and probably should always be true. It
3615 is better to limit inheritance to certain tags using the variables
3616 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3617 :group 'org-tags
3618 :type '(choice
3619 (const :tag "No, don't list them" nil)
3620 (const :tag "Yes, do list them" t)
3621 (const :tag "List them, indented with leading dots" indented)))
3623 (defcustom org-tags-sort-function nil
3624 "When set, tags are sorted using this function as a comparator."
3625 :group 'org-tags
3626 :type '(choice
3627 (const :tag "No sorting" nil)
3628 (const :tag "Alphabetical" org-string-collate-lessp)
3629 (const :tag "Reverse alphabetical" org-string-collate-greaterp)
3630 (function :tag "Custom function" nil)))
3632 (defvar org-tags-history nil
3633 "History of minibuffer reads for tags.")
3634 (defvar org-last-tags-completion-table nil
3635 "The last used completion table for tags.")
3636 (defvar org-after-tags-change-hook nil
3637 "Hook that is run after the tags in a line have changed.")
3639 (defgroup org-properties nil
3640 "Options concerning properties in Org mode."
3641 :tag "Org Properties"
3642 :group 'org)
3644 (defcustom org-property-format "%-10s %s"
3645 "How property key/value pairs should be formatted by `indent-line'.
3646 When `indent-line' hits a property definition, it will format the line
3647 according to this format, mainly to make sure that the values are
3648 lined-up with respect to each other."
3649 :group 'org-properties
3650 :type 'string)
3652 (defcustom org-properties-postprocess-alist nil
3653 "Alist of properties and functions to adjust inserted values.
3654 Elements of this alist must be of the form
3656 ([string] [function])
3658 where [string] must be a property name and [function] must be a
3659 lambda expression: this lambda expression must take one argument,
3660 the value to adjust, and return the new value as a string.
3662 For example, this element will allow the property \"Remaining\"
3663 to be updated wrt the relation between the \"Effort\" property
3664 and the clock summary:
3666 ((\"Remaining\" (lambda(value)
3667 (let ((clocksum (org-clock-sum-current-item))
3668 (effort (org-duration-to-minutes
3669 (org-entry-get (point) \"Effort\"))))
3670 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3671 :group 'org-properties
3672 :version "24.1"
3673 :type '(alist :key-type (string :tag "Property")
3674 :value-type (function :tag "Function")))
3676 (defcustom org-use-property-inheritance nil
3677 "Non-nil means properties apply also for sublevels.
3679 This setting is chiefly used during property searches. Turning it on can
3680 cause significant overhead when doing a search, which is why it is not
3681 on by default.
3683 When nil, only the properties directly given in the current entry count.
3684 When t, every property is inherited. The value may also be a list of
3685 properties that should have inheritance, or a regular expression matching
3686 properties that should be inherited.
3688 However, note that some special properties use inheritance under special
3689 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3690 and the properties ending in \"_ALL\" when they are used as descriptor
3691 for valid values of a property.
3693 Note for programmers:
3694 When querying an entry with `org-entry-get', you can control if inheritance
3695 should be used. By default, `org-entry-get' looks only at the local
3696 properties. You can request inheritance by setting the inherit argument
3697 to t (to force inheritance) or to `selective' (to respect the setting
3698 in this variable)."
3699 :group 'org-properties
3700 :type '(choice
3701 (const :tag "Not" nil)
3702 (const :tag "Always" t)
3703 (repeat :tag "Specific properties" (string :tag "Property"))
3704 (regexp :tag "Properties matched by regexp")))
3706 (defun org-property-inherit-p (property)
3707 "Return a non-nil value if PROPERTY should be inherited."
3708 (cond
3709 ((eq org-use-property-inheritance t) t)
3710 ((not org-use-property-inheritance) nil)
3711 ((stringp org-use-property-inheritance)
3712 (string-match org-use-property-inheritance property))
3713 ((listp org-use-property-inheritance)
3714 (member-ignore-case property org-use-property-inheritance))
3715 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3717 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3718 "The default column format, if no other format has been defined.
3719 This variable can be set on the per-file basis by inserting a line
3721 #+COLUMNS: %25ITEM ....."
3722 :group 'org-properties
3723 :type 'string)
3725 (defcustom org-columns-ellipses ".."
3726 "The ellipses to be used when a field in column view is truncated.
3727 When this is the empty string, as many characters as possible are shown,
3728 but then there will be no visual indication that the field has been truncated.
3729 When this is a string of length N, the last N characters of a truncated
3730 field are replaced by this string. If the column is narrower than the
3731 ellipses string, only part of the ellipses string will be shown."
3732 :group 'org-properties
3733 :type 'string)
3735 (defconst org-global-properties-fixed
3736 '(("VISIBILITY_ALL" . "folded children content all")
3737 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3738 "List of property/value pairs that can be inherited by any entry.
3740 These are fixed values, for the preset properties. The user variable
3741 that can be used to add to this list is `org-global-properties'.
3743 The entries in this list are cons cells where the car is a property
3744 name and cdr is a string with the value. If the value represents
3745 multiple items like an \"_ALL\" property, separate the items by
3746 spaces.")
3748 (defcustom org-global-properties nil
3749 "List of property/value pairs that can be inherited by any entry.
3751 This list will be combined with the constant `org-global-properties-fixed'.
3753 The entries in this list are cons cells where the car is a property
3754 name and cdr is a string with the value.
3756 You can set buffer-local values for the same purpose in the variable
3757 `org-file-properties' this by adding lines like
3759 #+PROPERTY: NAME VALUE"
3760 :group 'org-properties
3761 :type '(repeat
3762 (cons (string :tag "Property")
3763 (string :tag "Value"))))
3765 (defvar-local org-file-properties nil
3766 "List of property/value pairs that can be inherited by any entry.
3767 Valid for the current buffer.
3768 This variable is populated from #+PROPERTY lines.")
3770 (defgroup org-agenda nil
3771 "Options concerning agenda views in Org mode."
3772 :tag "Org Agenda"
3773 :group 'org)
3775 (defvar-local org-category nil
3776 "Variable used by Org files to set a category for agenda display.
3777 Such files should use a file variable to set it, for example
3779 # -*- mode: org; org-category: \"ELisp\"
3781 or contain a special line
3783 #+CATEGORY: ELisp
3785 If the file does not specify a category, then file's base name
3786 is used instead.")
3787 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3789 (defcustom org-agenda-files nil
3790 "The files to be used for agenda display.
3792 If an entry is a directory, all files in that directory that are matched
3793 by `org-agenda-file-regexp' will be part of the file list.
3795 If the value of the variable is not a list but a single file name, then
3796 the list of agenda files is actually stored and maintained in that file,
3797 one agenda file per line. In this file paths can be given relative to
3798 `org-directory'. Tilde expansion and environment variable substitution
3799 are also made.
3801 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3802 and removed with `\\[org-remove-file]'."
3803 :group 'org-agenda
3804 :type '(choice
3805 (repeat :tag "List of files and directories" file)
3806 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3808 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3809 "Regular expression to match files for `org-agenda-files'.
3810 If any element in the list in that variable contains a directory instead
3811 of a normal file, all files in that directory that are matched by this
3812 regular expression will be included."
3813 :group 'org-agenda
3814 :type 'regexp)
3816 (defcustom org-agenda-text-search-extra-files nil
3817 "List of extra files to be searched by text search commands.
3818 These files will be searched in addition to the agenda files by the
3819 commands `org-search-view' (`\\[org-agenda] s') \
3820 and `org-occur-in-agenda-files'.
3821 Note that these files will only be searched for text search commands,
3822 not for the other agenda views like todo lists, tag searches or the weekly
3823 agenda. This variable is intended to list notes and possibly archive files
3824 that should also be searched by these two commands.
3825 In fact, if the first element in the list is the symbol `agenda-archives',
3826 then all archive files of all agenda files will be added to the search
3827 scope."
3828 :group 'org-agenda
3829 :type '(set :greedy t
3830 (const :tag "Agenda Archives" agenda-archives)
3831 (repeat :inline t (file))))
3833 (defvaralias 'org-agenda-multi-occur-extra-files
3834 'org-agenda-text-search-extra-files)
3836 (defcustom org-agenda-skip-unavailable-files nil
3837 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3838 A nil value means to remove them, after a query, from the list."
3839 :group 'org-agenda
3840 :type 'boolean)
3842 (defcustom org-agenda-diary-file 'diary-file
3843 "File to which to add new entries with the `i' key in agenda and calendar.
3844 When this is the symbol `diary-file', the functionality in the Emacs
3845 calendar will be used to add entries to the `diary-file'. But when this
3846 points to a file, `org-agenda-diary-entry' will be used instead."
3847 :group 'org-agenda
3848 :type '(choice
3849 (const :tag "The standard Emacs diary file" diary-file)
3850 (file :tag "Special Org file diary entries")))
3852 (defgroup org-latex nil
3853 "Options for embedding LaTeX code into Org mode."
3854 :tag "Org LaTeX"
3855 :group 'org)
3857 (defcustom org-format-latex-options
3858 '(:foreground default :background default :scale 1.0
3859 :html-foreground "Black" :html-background "Transparent"
3860 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3861 "Options for creating images from LaTeX fragments.
3862 This is a property list with the following properties:
3863 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3864 `default' means use the foreground of the default face.
3865 `auto' means use the foreground from the text face.
3866 :background the background color, or \"Transparent\".
3867 `default' means use the background of the default face.
3868 `auto' means use the background from the text face.
3869 :scale a scaling factor for the size of the images, to get more pixels
3870 :html-foreground, :html-background, :html-scale
3871 the same numbers for HTML export.
3872 :matchers a list indicating which matchers should be used to
3873 find LaTeX fragments. Valid members of this list are:
3874 \"begin\" find environments
3875 \"$1\" find single characters surrounded by $.$
3876 \"$\" find math expressions surrounded by $...$
3877 \"$$\" find math expressions surrounded by $$....$$
3878 \"\\(\" find math expressions surrounded by \\(...\\)
3879 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3880 :group 'org-latex
3881 :type 'plist)
3883 (defcustom org-format-latex-signal-error t
3884 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3885 When nil, just push out a message."
3886 :group 'org-latex
3887 :version "24.1"
3888 :type 'boolean)
3890 (defcustom org-latex-to-mathml-jar-file nil
3891 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3892 Use this to specify additional executable file say a jar file.
3894 When using MathToWeb as the converter, specify the full-path to
3895 your mathtoweb.jar file."
3896 :group 'org-latex
3897 :version "24.1"
3898 :type '(choice
3899 (const :tag "None" nil)
3900 (file :tag "JAR file" :must-match t)))
3902 (defcustom org-latex-to-mathml-convert-command nil
3903 "Command to convert LaTeX fragments to MathML.
3904 Replace format-specifiers in the command as noted below and use
3905 `shell-command' to convert LaTeX to MathML.
3906 %j: Executable file in fully expanded form as specified by
3907 `org-latex-to-mathml-jar-file'.
3908 %I: Input LaTeX file in fully expanded form.
3909 %i: The latex fragment to be converted.
3910 %o: Output MathML file.
3912 This command is used by `org-create-math-formula'.
3914 When using MathToWeb as the converter, set this option to
3915 \"java -jar %j -unicode -force -df %o %I\".
3917 When using LaTeXML set this option to
3918 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3919 :group 'org-latex
3920 :version "24.1"
3921 :type '(choice
3922 (const :tag "None" nil)
3923 (string :tag "\nShell command")))
3925 (defcustom org-preview-latex-default-process 'dvipng
3926 "The default process to convert LaTeX fragments to image files.
3927 All available processes and theirs documents can be found in
3928 `org-preview-latex-process-alist', which see."
3929 :group 'org-latex
3930 :version "26.1"
3931 :package-version '(Org . "9.0")
3932 :type 'symbol)
3934 (defcustom org-preview-latex-process-alist
3935 '((dvipng
3936 :programs ("latex" "dvipng")
3937 :description "dvi > png"
3938 :message "you need to install the programs: latex and dvipng."
3939 :image-input-type "dvi"
3940 :image-output-type "png"
3941 :image-size-adjust (1.0 . 1.0)
3942 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3943 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3944 (dvisvgm
3945 :programs ("latex" "dvisvgm")
3946 :description "dvi > svg"
3947 :message "you need to install the programs: latex and dvisvgm."
3948 :use-xcolor t
3949 :image-input-type "dvi"
3950 :image-output-type "svg"
3951 :image-size-adjust (1.7 . 1.5)
3952 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3953 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3954 (imagemagick
3955 :programs ("latex" "convert")
3956 :description "pdf > png"
3957 :message "you need to install the programs: latex and imagemagick."
3958 :use-xcolor t
3959 :image-input-type "pdf"
3960 :image-output-type "png"
3961 :image-size-adjust (1.0 . 1.0)
3962 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3963 :image-converter
3964 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3965 "Definitions of external processes for LaTeX previewing.
3966 Org mode can use some external commands to generate TeX snippet's images for
3967 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3968 `org-create-formula-image' how to call them.
3970 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3971 PROPERTIES accepts the following attributes:
3973 :programs list of strings, required programs.
3974 :description string, describe the process.
3975 :message string, message it when required programs cannot be found.
3976 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3977 :image-output-type string, output file type of image converter (e.g., \"png\").
3978 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3979 deal with background and foreground color of image.
3980 Otherwise, dvipng style background and foreground color
3981 format are generated. You may then refer to them in
3982 command options with \"%F\" and \"%B\".
3983 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3984 image size showed in buffer and the cdr element is for
3985 HTML file. This option is only useful for process
3986 developers, users should use variable
3987 `org-format-latex-options' instead.
3988 :post-clean list of strings, files matched are to be cleaned up once
3989 the image is generated. When nil, the files with \".dvi\",
3990 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
3991 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
3992 be cleaned up.
3993 :latex-header list of strings, the LaTeX header of the snippet file.
3994 When nil, the fallback value is used instead, which is
3995 controlled by `org-format-latex-header',
3996 `org-latex-default-packages-alist' and
3997 `org-latex-packages-alist', which see.
3998 :latex-compiler list of LaTeX commands, as strings. Each of them is given
3999 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4000 replaced with values defined below.
4001 :image-converter list of image converter commands strings. Each of them is
4002 given to the shell and supports any of the following
4003 place-holders defined below.
4005 Place-holders used by `:image-converter' and `:latex-compiler':
4007 %f input file name
4008 %b base name of input file
4009 %o base directory of input file
4010 %O absolute output file name
4012 Place-holders only used by `:image-converter':
4014 %F foreground of image
4015 %B background of image
4016 %D dpi, which is used to adjust image size by some processing commands.
4017 %S the image size scale ratio, which is used to adjust image size by some
4018 processing commands."
4019 :group 'org-latex
4020 :version "26.1"
4021 :package-version '(Org . "9.0")
4022 :type '(alist :tag "LaTeX to image backends"
4023 :value-type (plist)))
4025 (defcustom org-preview-latex-image-directory "ltximg/"
4026 "Path to store latex preview images.
4027 A relative path here creates many directories relative to the
4028 processed Org files paths. An absolute path puts all preview
4029 images at the same place."
4030 :group 'org-latex
4031 :version "26.1"
4032 :package-version '(Org . "9.0")
4033 :type 'string)
4035 (defun org-format-latex-mathml-available-p ()
4036 "Return t if `org-latex-to-mathml-convert-command' is usable."
4037 (save-match-data
4038 (when (and (boundp 'org-latex-to-mathml-convert-command)
4039 org-latex-to-mathml-convert-command)
4040 (let ((executable (car (split-string
4041 org-latex-to-mathml-convert-command))))
4042 (when (executable-find executable)
4043 (if (string-match
4044 "%j" org-latex-to-mathml-convert-command)
4045 (file-readable-p org-latex-to-mathml-jar-file)
4046 t))))))
4048 (defcustom org-format-latex-header "\\documentclass{article}
4049 \\usepackage[usenames]{color}
4050 \[PACKAGES]
4051 \[DEFAULT-PACKAGES]
4052 \\pagestyle{empty} % do not remove
4053 % The settings below are copied from fullpage.sty
4054 \\setlength{\\textwidth}{\\paperwidth}
4055 \\addtolength{\\textwidth}{-3cm}
4056 \\setlength{\\oddsidemargin}{1.5cm}
4057 \\addtolength{\\oddsidemargin}{-2.54cm}
4058 \\setlength{\\evensidemargin}{\\oddsidemargin}
4059 \\setlength{\\textheight}{\\paperheight}
4060 \\addtolength{\\textheight}{-\\headheight}
4061 \\addtolength{\\textheight}{-\\headsep}
4062 \\addtolength{\\textheight}{-\\footskip}
4063 \\addtolength{\\textheight}{-3cm}
4064 \\setlength{\\topmargin}{1.5cm}
4065 \\addtolength{\\topmargin}{-2.54cm}"
4066 "The document header used for processing LaTeX fragments.
4067 It is imperative that this header make sure that no page number
4068 appears on the page. The package defined in the variables
4069 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4070 will either replace the placeholder \"[PACKAGES]\" in this
4071 header, or they will be appended."
4072 :group 'org-latex
4073 :type 'string)
4075 (defun org-set-packages-alist (var val)
4076 "Set the packages alist and make sure it has 3 elements per entry."
4077 (set var (mapcar (lambda (x)
4078 (if (and (consp x) (= (length x) 2))
4079 (list (car x) (nth 1 x) t)
4081 val)))
4083 (defun org-get-packages-alist (var)
4084 "Get the packages alist and make sure it has 3 elements per entry."
4085 (mapcar (lambda (x)
4086 (if (and (consp x) (= (length x) 2))
4087 (list (car x) (nth 1 x) t)
4089 (default-value var)))
4091 (defcustom org-latex-default-packages-alist
4092 '(("AUTO" "inputenc" t ("pdflatex"))
4093 ("T1" "fontenc" t ("pdflatex"))
4094 ("" "graphicx" t)
4095 ("" "grffile" t)
4096 ("" "longtable" nil)
4097 ("" "wrapfig" nil)
4098 ("" "rotating" nil)
4099 ("normalem" "ulem" t)
4100 ("" "amsmath" t)
4101 ("" "textcomp" t)
4102 ("" "amssymb" t)
4103 ("" "capt-of" nil)
4104 ("" "hyperref" nil))
4105 "Alist of default packages to be inserted in the header.
4107 Change this only if one of the packages here causes an
4108 incompatibility with another package you are using.
4110 The packages in this list are needed by one part or another of
4111 Org mode to function properly:
4113 - inputenc, fontenc: for basic font and character selection
4114 - graphicx: for including images
4115 - grffile: allow periods and spaces in graphics file names
4116 - longtable: For multipage tables
4117 - wrapfig: for figure placement
4118 - rotating: for sideways figures and tables
4119 - ulem: for underline and strike-through
4120 - amsmath: for subscript and superscript and math environments
4121 - textcomp, amssymb: for various symbols used
4122 for interpreting the entities in `org-entities'. You can skip
4123 some of these packages if you don't use any of their symbols.
4124 - capt-of: for captions outside of floats
4125 - hyperref: for cross references
4127 Therefore you should not modify this variable unless you know
4128 what you are doing. The one reason to change it anyway is that
4129 you might be loading some other package that conflicts with one
4130 of the default packages. Each element is either a cell or
4131 a string.
4133 A cell is of the format
4135 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4137 If SNIPPET-FLAG is non-nil, the package also needs to be included
4138 when compiling LaTeX snippets into images for inclusion into
4139 non-LaTeX output. COMPILERS is a list of compilers that should
4140 include the package, see `org-latex-compiler'. If the document
4141 compiler is not in the list, and the list is non-nil, the package
4142 will not be inserted in the final document.
4144 A string will be inserted as-is in the header of the document."
4145 :group 'org-latex
4146 :group 'org-export-latex
4147 :set 'org-set-packages-alist
4148 :get 'org-get-packages-alist
4149 :version "26.1"
4150 :package-version '(Org . "8.3")
4151 :type '(repeat
4152 (choice
4153 (list :tag "options/package pair"
4154 (string :tag "options")
4155 (string :tag "package")
4156 (boolean :tag "Snippet")
4157 (choice
4158 (const :tag "For all compilers" nil)
4159 (repeat :tag "Allowed compiler" string)))
4160 (string :tag "A line of LaTeX"))))
4162 (defcustom org-latex-packages-alist nil
4163 "Alist of packages to be inserted in every LaTeX header.
4165 These will be inserted after `org-latex-default-packages-alist'.
4166 Each element is either a cell or a string.
4168 A cell is of the format:
4170 (\"options\" \"package\" SNIPPET-FLAG)
4172 SNIPPET-FLAG, when non-nil, indicates that this package is also
4173 needed when turning LaTeX snippets into images for inclusion into
4174 non-LaTeX output.
4176 A string will be inserted as-is in the header of the document.
4178 Make sure that you only list packages here which:
4180 - you want in every file;
4181 - do not conflict with the setup in `org-format-latex-header';
4182 - do not conflict with the default packages in
4183 `org-latex-default-packages-alist'."
4184 :group 'org-latex
4185 :group 'org-export-latex
4186 :set 'org-set-packages-alist
4187 :get 'org-get-packages-alist
4188 :type '(repeat
4189 (choice
4190 (list :tag "options/package pair"
4191 (string :tag "options")
4192 (string :tag "package")
4193 (boolean :tag "Snippet"))
4194 (string :tag "A line of LaTeX"))))
4196 (defgroup org-appearance nil
4197 "Settings for Org mode appearance."
4198 :tag "Org Appearance"
4199 :group 'org)
4201 (defcustom org-level-color-stars-only nil
4202 "Non-nil means fontify only the stars in each headline.
4203 When nil, the entire headline is fontified.
4204 Changing it requires restart of `font-lock-mode' to become effective
4205 also in regions already fontified."
4206 :group 'org-appearance
4207 :type 'boolean)
4209 (defcustom org-hide-leading-stars nil
4210 "Non-nil means hide the first N-1 stars in a headline.
4211 This works by using the face `org-hide' for these stars. This
4212 face is white for a light background, and black for a dark
4213 background. You may have to customize the face `org-hide' to
4214 make this work.
4215 Changing it requires restart of `font-lock-mode' to become effective
4216 also in regions already fontified.
4217 You may also set this on a per-file basis by adding one of the following
4218 lines to the buffer:
4220 #+STARTUP: hidestars
4221 #+STARTUP: showstars"
4222 :group 'org-appearance
4223 :type 'boolean)
4225 (defcustom org-hidden-keywords nil
4226 "List of symbols corresponding to keywords to be hidden in the Org buffer.
4227 For example, a value \\='(title) for this list makes the document's title
4228 appear in the buffer without the initial \"#+TITLE:\" part."
4229 :group 'org-appearance
4230 :version "24.1"
4231 :type '(set (const :tag "#+AUTHOR" author)
4232 (const :tag "#+DATE" date)
4233 (const :tag "#+EMAIL" email)
4234 (const :tag "#+TITLE" title)))
4236 (defcustom org-custom-properties nil
4237 "List of properties (as strings) with a special meaning.
4238 The default use of these custom properties is to let the user
4239 hide them with `org-toggle-custom-properties-visibility'."
4240 :group 'org-properties
4241 :group 'org-appearance
4242 :version "24.3"
4243 :type '(repeat (string :tag "Property Name")))
4245 (defcustom org-fontify-done-headline nil
4246 "Non-nil means change the face of a headline if it is marked DONE.
4247 Normally, only the TODO/DONE keyword indicates the state of a headline.
4248 When this is non-nil, the headline after the keyword is set to the
4249 `org-headline-done' as an additional indication."
4250 :group 'org-appearance
4251 :type 'boolean)
4253 (defcustom org-fontify-emphasized-text t
4254 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4255 Changing this variable requires a restart of Emacs to take effect."
4256 :group 'org-appearance
4257 :type 'boolean)
4259 (defcustom org-fontify-whole-heading-line nil
4260 "Non-nil means fontify the whole line for headings.
4261 This is useful when setting a background color for the
4262 org-level-* faces."
4263 :group 'org-appearance
4264 :type 'boolean)
4266 (defcustom org-highlight-latex-and-related nil
4267 "Non-nil means highlight LaTeX related syntax in the buffer.
4268 When non nil, the value should be a list containing any of the
4269 following symbols:
4270 `latex' Highlight LaTeX snippets and environments.
4271 `script' Highlight subscript and superscript.
4272 `entities' Highlight entities."
4273 :group 'org-appearance
4274 :version "24.4"
4275 :package-version '(Org . "8.0")
4276 :type '(choice
4277 (const :tag "No highlighting" nil)
4278 (set :greedy t :tag "Highlight"
4279 (const :tag "LaTeX snippets and environments" latex)
4280 (const :tag "Subscript and superscript" script)
4281 (const :tag "Entities" entities))))
4283 (defcustom org-hide-emphasis-markers nil
4284 "Non-nil mean font-lock should hide the emphasis marker characters."
4285 :group 'org-appearance
4286 :type 'boolean
4287 :safe #'booleanp)
4289 (defcustom org-hide-macro-markers nil
4290 "Non-nil mean font-lock should hide the brackets marking macro calls."
4291 :group 'org-appearance
4292 :type 'boolean)
4294 (defcustom org-pretty-entities nil
4295 "Non-nil means show entities as UTF8 characters.
4296 When nil, the \\name form remains in the buffer."
4297 :group 'org-appearance
4298 :version "24.1"
4299 :type 'boolean)
4301 (defcustom org-pretty-entities-include-sub-superscripts t
4302 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4303 :group 'org-appearance
4304 :version "24.1"
4305 :type 'boolean)
4307 (defvar org-emph-re nil
4308 "Regular expression for matching emphasis.
4309 After a match, the match groups contain these elements:
4310 0 The match of the full regular expression, including the characters
4311 before and after the proper match
4312 1 The character before the proper match, or empty at beginning of line
4313 2 The proper match, including the leading and trailing markers
4314 3 The leading marker like * or /, indicating the type of highlighting
4315 4 The text between the emphasis markers, not including the markers
4316 5 The character after the match, empty at the end of a line")
4318 (defvar org-verbatim-re nil
4319 "Regular expression for matching verbatim text.")
4321 (defvar org-emphasis-regexp-components) ; defined just below
4322 (defvar org-emphasis-alist) ; defined just below
4323 (defun org-set-emph-re (var val)
4324 "Set variable and compute the emphasis regular expression."
4325 (set var val)
4326 (when (and (boundp 'org-emphasis-alist)
4327 (boundp 'org-emphasis-regexp-components)
4328 org-emphasis-alist org-emphasis-regexp-components)
4329 (pcase-let*
4330 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4331 (body (if (<= nl 0) body
4332 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4333 (template
4334 (format (concat "\\([%s]\\|^\\)" ;before markers
4335 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4336 "\\([%s]\\|$\\)") ;after markers
4337 pre border border body border post)))
4338 (setq org-emph-re (format template "*/_+"))
4339 (setq org-verbatim-re (format template "=~")))))
4341 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4342 ;; set this option proved cumbersome. See this message/thread:
4343 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4344 (defvar org-emphasis-regexp-components
4345 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4346 "Components used to build the regular expression for emphasis.
4347 This is a list with five entries. Terminology: In an emphasis string
4348 like \" *strong word* \", we call the initial space PREMATCH, the final
4349 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4350 and \"trong wor\" is the body. The different components in this variable
4351 specify what is allowed/forbidden in each part:
4353 pre Chars allowed as prematch. Beginning of line will be allowed too.
4354 post Chars allowed as postmatch. End of line will be allowed too.
4355 border The chars *forbidden* as border characters.
4356 body-regexp A regexp like \".\" to match a body character. Don't use
4357 non-shy groups here, and don't allow newline here.
4358 newline The maximum number of newlines allowed in an emphasis exp.
4360 You need to reload Org or to restart Emacs after setting this.")
4362 (defcustom org-emphasis-alist
4363 '(("*" bold)
4364 ("/" italic)
4365 ("_" underline)
4366 ("=" org-verbatim verbatim)
4367 ("~" org-code verbatim)
4368 ("+" (:strike-through t)))
4369 "Alist of characters and faces to emphasize text.
4370 Text starting and ending with a special character will be emphasized,
4371 for example *bold*, _underlined_ and /italic/. This variable sets the
4372 marker characters and the face to be used by font-lock for highlighting
4373 in Org buffers.
4375 You need to reload Org or to restart Emacs after customizing this."
4376 :group 'org-appearance
4377 :set 'org-set-emph-re
4378 :version "24.4"
4379 :package-version '(Org . "8.0")
4380 :type '(repeat
4381 (list
4382 (string :tag "Marker character")
4383 (choice
4384 (face :tag "Font-lock-face")
4385 (plist :tag "Face property list"))
4386 (option (const verbatim)))))
4388 (defvar org-protecting-blocks '("src" "example" "export")
4389 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4390 This is needed for font-lock setup.")
4392 ;;; Functions and variables from their packages
4393 ;; Declared here to avoid compiler warnings
4394 (defvar mark-active)
4396 ;; Various packages
4397 (declare-function calc-eval "calc" (str &optional separator &rest args))
4398 (declare-function calendar-forward-day "cal-move" (arg))
4399 (declare-function calendar-goto-date "cal-move" (date))
4400 (declare-function calendar-goto-today "cal-move" ())
4401 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4402 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4403 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4404 (declare-function cdlatex-tab "ext:cdlatex" ())
4405 (declare-function dired-get-filename
4406 "dired"
4407 (&optional localp no-error-if-not-filep))
4408 (declare-function iswitchb-read-buffer
4409 "iswitchb"
4410 (prompt &optional
4411 default require-match _predicate start matches-set))
4412 (declare-function org-agenda-change-all-lines
4413 "org-agenda"
4414 (newhead hdmarker &optional fixface just-this))
4415 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4416 "org-agenda"
4417 (&optional end))
4418 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4419 (declare-function org-agenda-format-item
4420 "org-agenda"
4421 (extra txt &optional level category tags dotime
4422 remove-re habitp))
4423 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4424 (declare-function org-agenda-save-markers-for-cut-and-paste
4425 "org-agenda"
4426 (beg end))
4427 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4428 (declare-function org-agenda-skip "org-agenda" ())
4429 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4430 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4431 (declare-function org-indent-mode "org-indent" (&optional arg))
4432 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4433 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4434 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4435 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4436 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4437 (declare-function parse-time-string "parse-time" (string))
4439 (defvar align-mode-rules-list)
4440 (defvar calc-embedded-close-formula)
4441 (defvar calc-embedded-open-formula)
4442 (defvar calc-embedded-open-mode)
4443 (defvar font-lock-unfontify-region-function)
4444 (defvar iswitchb-temp-buflist)
4445 (defvar org-agenda-tags-todo-honor-ignore-options)
4446 (defvar remember-data-file)
4447 (defvar texmathp-why)
4449 ;;;###autoload
4450 (defun turn-on-orgtbl ()
4451 "Unconditionally turn on `orgtbl-mode'."
4452 (require 'org-table)
4453 (orgtbl-mode 1))
4455 (defun org-at-table-p (&optional table-type)
4456 "Non-nil if the cursor is inside an Org table.
4457 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4458 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4459 (or (not (derived-mode-p 'org-mode))
4460 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4461 (and e (or table-type
4462 (eq 'org (org-element-property :type e))))))))
4464 (defun org-at-table.el-p ()
4465 "Non-nil when point is at a table.el table."
4466 (and (org-match-line "[ \t]*[|+]")
4467 (let ((element (org-element-at-point)))
4468 (and (eq (org-element-type element) 'table)
4469 (eq (org-element-property :type element) 'table.el)))))
4471 (defun org-at-table-hline-p ()
4472 "Non-nil when point is inside a hline in a table.
4473 Assume point is already in a table."
4474 (org-match-line org-table-hline-regexp))
4476 (defun org-table-map-tables (function &optional quietly)
4477 "Apply FUNCTION to the start of all tables in the buffer."
4478 (org-with-wide-buffer
4479 (goto-char (point-min))
4480 (while (re-search-forward org-table-any-line-regexp nil t)
4481 (unless quietly
4482 (message "Mapping tables: %d%%"
4483 (floor (* 100.0 (point)) (buffer-size))))
4484 (beginning-of-line 1)
4485 (when (and (looking-at org-table-line-regexp)
4486 ;; Exclude tables in src/example/verbatim/clocktable blocks
4487 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4488 (save-excursion (funcall function))
4489 (or (looking-at org-table-line-regexp)
4490 (forward-char 1)))
4491 (re-search-forward org-table-any-border-regexp nil 1)))
4492 (unless quietly (message "Mapping tables: done")))
4494 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4495 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
4496 (declare-function org-resolve-clocks "org-clock"
4497 (&optional also-non-dangling-p prompt last-valid))
4499 (defun org-at-TBLFM-p (&optional pos)
4500 "Non-nil when point (or POS) is in #+TBLFM line."
4501 (save-excursion
4502 (goto-char (or pos (point)))
4503 (beginning-of-line)
4504 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4505 (eq (org-element-type (org-element-at-point)) 'table))))
4507 (defvar org-clock-start-time)
4508 (defvar org-clock-marker (make-marker)
4509 "Marker recording the last clock-in.")
4510 (defvar org-clock-hd-marker (make-marker)
4511 "Marker recording the last clock-in, but the headline position.")
4512 (defvar org-clock-heading ""
4513 "The heading of the current clock entry.")
4514 (defun org-clock-is-active ()
4515 "Return the buffer where the clock is currently running.
4516 Return nil if no clock is running."
4517 (marker-buffer org-clock-marker))
4519 (defun org-check-running-clock ()
4520 "Check if the current buffer contains the running clock.
4521 If yes, offer to stop it and to save the buffer with the changes."
4522 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4523 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4524 (buffer-name))))
4525 (org-clock-out)
4526 (when (y-or-n-p "Save changed buffer?")
4527 (save-buffer))))
4529 (defun org-clocktable-try-shift (dir n)
4530 "Check if this line starts a clock table, if yes, shift the time block."
4531 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4532 (org-clocktable-shift dir n)))
4534 ;;;###autoload
4535 (defun org-clock-persistence-insinuate ()
4536 "Set up hooks for clock persistence."
4537 (require 'org-clock)
4538 (add-hook 'org-mode-hook 'org-clock-load)
4539 (add-hook 'kill-emacs-hook 'org-clock-save))
4541 (defgroup org-archive nil
4542 "Options concerning archiving in Org mode."
4543 :tag "Org Archive"
4544 :group 'org-structure)
4546 (defcustom org-archive-location "%s_archive::"
4547 "The location where subtrees should be archived.
4549 The value of this variable is a string, consisting of two parts,
4550 separated by a double-colon. The first part is a filename and
4551 the second part is a headline.
4553 When the filename is omitted, archiving happens in the same file.
4554 %s in the filename will be replaced by the current file
4555 name (without the directory part). Archiving to a different file
4556 is useful to keep archived entries from contributing to the
4557 Org Agenda.
4559 The archived entries will be filed as subtrees of the specified
4560 headline. When the headline is omitted, the subtrees are simply
4561 filed away at the end of the file, as top-level entries. Also in
4562 the heading you can use %s to represent the file name, this can be
4563 useful when using the same archive for a number of different files.
4565 Here are a few examples:
4566 \"%s_archive::\"
4567 If the current file is Projects.org, archive in file
4568 Projects.org_archive, as top-level trees. This is the default.
4570 \"::* Archived Tasks\"
4571 Archive in the current file, under the top-level headline
4572 \"* Archived Tasks\".
4574 \"~/org/archive.org::\"
4575 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4577 \"~/org/archive.org::* From %s\"
4578 Archive in file ~/org/archive.org (absolute path), under headlines
4579 \"From FILENAME\" where file name is the current file name.
4581 \"~/org/datetree.org::datetree/* Finished Tasks\"
4582 The \"datetree/\" string is special, signifying to archive
4583 items to the datetree. Items are placed in either the CLOSED
4584 date of the item, or the current date if there is no CLOSED date.
4585 The heading will be a subentry to the current date. There doesn't
4586 need to be a heading, but there always needs to be a slash after
4587 datetree. For example, to store archived items directly in the
4588 datetree, use \"~/org/datetree.org::datetree/\".
4590 \"basement::** Finished Tasks\"
4591 Archive in file ./basement (relative path), as level 3 trees
4592 below the level 2 heading \"** Finished Tasks\".
4594 You may set this option on a per-file basis by adding to the buffer a
4595 line like
4597 #+ARCHIVE: basement::** Finished Tasks
4599 You may also define it locally for a subtree by setting an ARCHIVE property
4600 in the entry. If such a property is found in an entry, or anywhere up
4601 the hierarchy, it will be used."
4602 :group 'org-archive
4603 :type 'string)
4605 (defcustom org-agenda-skip-archived-trees t
4606 "Non-nil means the agenda will skip any items located in archived trees.
4607 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4608 variable is no longer recommended, you should leave it at the value t.
4609 Instead, use the key `v' to cycle the archives-mode in the agenda."
4610 :group 'org-archive
4611 :group 'org-agenda-skip
4612 :type 'boolean)
4614 (defcustom org-columns-skip-archived-trees t
4615 "Non-nil means ignore archived trees when creating column view."
4616 :group 'org-archive
4617 :group 'org-properties
4618 :type 'boolean)
4620 (defcustom org-cycle-open-archived-trees nil
4621 "Non-nil means `org-cycle' will open archived trees.
4622 An archived tree is a tree marked with the tag ARCHIVE.
4623 When nil, archived trees will stay folded. You can still open them with
4624 normal outline commands like `show-all', but not with the cycling commands."
4625 :group 'org-archive
4626 :group 'org-cycle
4627 :type 'boolean)
4629 (defcustom org-sparse-tree-open-archived-trees nil
4630 "Non-nil means sparse tree construction shows matches in archived trees.
4631 When nil, matches in these trees are highlighted, but the trees are kept in
4632 collapsed state."
4633 :group 'org-archive
4634 :group 'org-sparse-trees
4635 :type 'boolean)
4637 (defcustom org-sparse-tree-default-date-type nil
4638 "The default date type when building a sparse tree.
4639 When this is nil, a date is a scheduled or a deadline timestamp.
4640 Otherwise, these types are allowed:
4642 all: all timestamps
4643 active: only active timestamps (<...>)
4644 inactive: only inactive timestamps ([...])
4645 scheduled: only scheduled timestamps
4646 deadline: only deadline timestamps"
4647 :type '(choice (const :tag "Scheduled or deadline" nil)
4648 (const :tag "All timestamps" all)
4649 (const :tag "Only active timestamps" active)
4650 (const :tag "Only inactive timestamps" inactive)
4651 (const :tag "Only scheduled timestamps" scheduled)
4652 (const :tag "Only deadline timestamps" deadline)
4653 (const :tag "Only closed timestamps" closed))
4654 :version "26.1"
4655 :package-version '(Org . "8.3")
4656 :group 'org-sparse-trees)
4658 (defun org-cycle-hide-archived-subtrees (state)
4659 "Re-hide all archived subtrees after a visibility state change.
4660 STATE should be one of the symbols listed in the docstring of
4661 `org-cycle-hook'."
4662 (when (and (not org-cycle-open-archived-trees)
4663 (not (memq state '(overview folded))))
4664 (save-excursion
4665 (let* ((globalp (memq state '(contents all)))
4666 (beg (if globalp (point-min) (point)))
4667 (end (if globalp (point-max) (org-end-of-subtree t))))
4668 (org-hide-archived-subtrees beg end)
4669 (goto-char beg)
4670 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4671 (message "%s" (substitute-command-keys
4672 "Subtree is archived and stays closed. Use \
4673 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4675 (defun org-force-cycle-archived ()
4676 "Cycle subtree even if it is archived."
4677 (interactive)
4678 (setq this-command 'org-cycle)
4679 (let ((org-cycle-open-archived-trees t))
4680 (call-interactively 'org-cycle)))
4682 (defun org-hide-archived-subtrees (beg end)
4683 "Re-hide all archived subtrees after a visibility state change."
4684 (org-with-wide-buffer
4685 (let ((case-fold-search nil)
4686 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4687 (goto-char beg)
4688 ;; Include headline point is currently on.
4689 (beginning-of-line)
4690 (while (and (< (point) end) (re-search-forward re end t))
4691 (when (member org-archive-tag (org-get-tags nil t))
4692 (org-flag-subtree t)
4693 (org-end-of-subtree t))))))
4695 (defun org-flag-subtree (flag)
4696 (save-excursion
4697 (org-back-to-heading t)
4698 (org-flag-region (line-end-position)
4699 (progn (org-end-of-subtree t) (point))
4700 flag
4701 'outline)))
4703 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4705 ;; Declare Column View Code
4707 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4708 (declare-function org-columns-compute "org-colview" (property))
4710 ;; Declare ID code
4712 (declare-function org-id-store-link "org-id")
4713 (declare-function org-id-locations-load "org-id")
4714 (declare-function org-id-locations-save "org-id")
4715 (defvar org-id-track-globally)
4717 ;;; Variables for pre-computed regular expressions, all buffer local
4719 (defvar-local org-todo-regexp nil
4720 "Matches any of the TODO state keywords.
4721 Since TODO keywords are case-sensitive, `case-fold-search' is
4722 expected to be bound to nil when matching against this regexp.")
4724 (defvar-local org-not-done-regexp nil
4725 "Matches any of the TODO state keywords except the last one.
4726 Since TODO keywords are case-sensitive, `case-fold-search' is
4727 expected to be bound to nil when matching against this regexp.")
4729 (defvar-local org-not-done-heading-regexp nil
4730 "Matches a TODO headline that is not done.
4731 Since TODO keywords are case-sensitive, `case-fold-search' is
4732 expected to be bound to nil when matching against this regexp.")
4734 (defvar-local org-todo-line-regexp nil
4735 "Matches a headline and puts TODO state into group 2 if present.
4736 Since TODO keywords are case-sensitive, `case-fold-search' is
4737 expected to be bound to nil when matching against this regexp.")
4739 (defvar-local org-complex-heading-regexp nil
4740 "Matches a headline and puts everything into groups:
4742 group 1: Stars
4743 group 2: The TODO keyword, maybe
4744 group 3: Priority cookie
4745 group 4: True headline
4746 group 5: Tags
4748 Since TODO keywords are case-sensitive, `case-fold-search' is
4749 expected to be bound to nil when matching against this regexp.")
4751 (defvar-local org-complex-heading-regexp-format nil
4752 "Printf format to make regexp to match an exact headline.
4753 This regexp will match the headline of any node which has the
4754 exact headline text that is put into the format, but may have any
4755 TODO state, priority and tags.")
4757 (defvar-local org-todo-line-tags-regexp nil
4758 "Matches a headline and puts TODO state into group 2 if present.
4759 Also put tags into group 4 if tags are present.")
4761 (defconst org-plain-time-of-day-regexp
4762 (concat
4763 "\\(\\<[012]?[0-9]"
4764 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4765 "\\(--?"
4766 "\\(\\<[012]?[0-9]"
4767 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4768 "\\)?")
4769 "Regular expression to match a plain time or time range.
4770 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4771 groups carry important information:
4772 0 the full match
4773 1 the first time, range or not
4774 8 the second time, if it is a range.")
4776 (defconst org-plain-time-extension-regexp
4777 (concat
4778 "\\(\\<[012]?[0-9]"
4779 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4780 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4781 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4782 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4783 groups carry important information:
4784 0 the full match
4785 7 hours of duration
4786 9 minutes of duration")
4788 (defconst org-stamp-time-of-day-regexp
4789 (concat
4790 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4791 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4792 "\\(--?"
4793 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4794 "Regular expression to match a timestamp time or time range.
4795 After a match, the following groups carry important information:
4796 0 the full match
4797 1 date plus weekday, for back referencing to make sure both times are on the same day
4798 2 the first time, range or not
4799 4 the second time, if it is a range.")
4801 (defconst org-startup-options
4802 '(("fold" org-startup-folded t)
4803 ("overview" org-startup-folded t)
4804 ("nofold" org-startup-folded nil)
4805 ("showall" org-startup-folded nil)
4806 ("showeverything" org-startup-folded showeverything)
4807 ("content" org-startup-folded content)
4808 ("indent" org-startup-indented t)
4809 ("noindent" org-startup-indented nil)
4810 ("hidestars" org-hide-leading-stars t)
4811 ("showstars" org-hide-leading-stars nil)
4812 ("odd" org-odd-levels-only t)
4813 ("oddeven" org-odd-levels-only nil)
4814 ("align" org-startup-align-all-tables t)
4815 ("noalign" org-startup-align-all-tables nil)
4816 ("shrink" org-startup-shrink-all-tables t)
4817 ("inlineimages" org-startup-with-inline-images t)
4818 ("noinlineimages" org-startup-with-inline-images nil)
4819 ("latexpreview" org-startup-with-latex-preview t)
4820 ("nolatexpreview" org-startup-with-latex-preview nil)
4821 ("customtime" org-display-custom-times t)
4822 ("logdone" org-log-done time)
4823 ("lognotedone" org-log-done note)
4824 ("nologdone" org-log-done nil)
4825 ("lognoteclock-out" org-log-note-clock-out t)
4826 ("nolognoteclock-out" org-log-note-clock-out nil)
4827 ("logrepeat" org-log-repeat state)
4828 ("lognoterepeat" org-log-repeat note)
4829 ("logdrawer" org-log-into-drawer t)
4830 ("nologdrawer" org-log-into-drawer nil)
4831 ("logstatesreversed" org-log-states-order-reversed t)
4832 ("nologstatesreversed" org-log-states-order-reversed nil)
4833 ("nologrepeat" org-log-repeat nil)
4834 ("logreschedule" org-log-reschedule time)
4835 ("lognotereschedule" org-log-reschedule note)
4836 ("nologreschedule" org-log-reschedule nil)
4837 ("logredeadline" org-log-redeadline time)
4838 ("lognoteredeadline" org-log-redeadline note)
4839 ("nologredeadline" org-log-redeadline nil)
4840 ("logrefile" org-log-refile time)
4841 ("lognoterefile" org-log-refile note)
4842 ("nologrefile" org-log-refile nil)
4843 ("fninline" org-footnote-define-inline t)
4844 ("nofninline" org-footnote-define-inline nil)
4845 ("fnlocal" org-footnote-section nil)
4846 ("fnauto" org-footnote-auto-label t)
4847 ("fnprompt" org-footnote-auto-label nil)
4848 ("fnconfirm" org-footnote-auto-label confirm)
4849 ("fnplain" org-footnote-auto-label plain)
4850 ("fnadjust" org-footnote-auto-adjust t)
4851 ("nofnadjust" org-footnote-auto-adjust nil)
4852 ("constcgs" constants-unit-system cgs)
4853 ("constSI" constants-unit-system SI)
4854 ("noptag" org-tag-persistent-alist nil)
4855 ("hideblocks" org-hide-block-startup t)
4856 ("nohideblocks" org-hide-block-startup nil)
4857 ("beamer" org-startup-with-beamer-mode t)
4858 ("entitiespretty" org-pretty-entities t)
4859 ("entitiesplain" org-pretty-entities nil))
4860 "Variable associated with STARTUP options for Org.
4861 Each element is a list of three items: the startup options (as written
4862 in the #+STARTUP line), the corresponding variable, and the value to set
4863 this variable to if the option is found. An optional forth element PUSH
4864 means to push this value onto the list in the variable.")
4866 (defcustom org-group-tags t
4867 "When non-nil (the default), use group tags.
4868 This can be turned on/off through `org-toggle-tags-groups'."
4869 :group 'org-tags
4870 :group 'org-startup
4871 :type 'boolean)
4873 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4875 (defun org-toggle-tags-groups ()
4876 "Toggle support for group tags.
4877 Support for group tags is controlled by the option
4878 `org-group-tags', which is non-nil by default."
4879 (interactive)
4880 (setq org-group-tags (not org-group-tags))
4881 (cond ((and (derived-mode-p 'org-agenda-mode)
4882 org-group-tags)
4883 (org-agenda-redo))
4884 ((derived-mode-p 'org-mode)
4885 (let ((org-inhibit-startup t)) (org-mode))))
4886 (message "Groups tags support has been turned %s"
4887 (if org-group-tags "on" "off")))
4889 (defun org--tag-add-to-alist (alist1 alist2)
4890 "Merge tags from ALIST1 into ALIST2.
4892 Duplicates tags outside a group are removed. Keywords and order
4893 are preserved.
4895 The function assumes ALIST1 and ALIST2 are proper tag alists.
4896 See `org-tag-alist' for their structure."
4897 (cond
4898 ((null alist2) alist1)
4899 ((null alist1) alist2)
4901 (let ((to-add nil)
4902 (group-flag nil))
4903 (dolist (tag-pair alist1)
4904 (pcase tag-pair
4905 (`(,(or :startgrouptag :startgroup))
4906 (setq group-flag t)
4907 (push tag-pair to-add))
4908 (`(,(or :endgrouptag :endgroup))
4909 (setq group-flag nil)
4910 (push tag-pair to-add))
4911 (`(,(or :grouptags :newline))
4912 (push tag-pair to-add))
4913 (`(,tag . ,_)
4914 ;; Remove duplicates from ALIST1, unless they are in
4915 ;; a group. Indeed, it makes sense to have a tag appear in
4916 ;; multiple groups.
4917 (when (or group-flag (not (assoc tag alist2)))
4918 (push tag-pair to-add)))
4919 (_ (error "Invalid association in tag alist: %S" tag-pair))))
4920 ;; Preserve order of ALIST1.
4921 (append (nreverse to-add) alist2)))))
4923 (defun org-set-regexps-and-options (&optional tags-only)
4924 "Precompute regular expressions used in the current buffer.
4925 When optional argument TAGS-ONLY is non-nil, only compute tags
4926 related expressions."
4927 (when (derived-mode-p 'org-mode)
4928 (let ((alist (org--setup-collect-keywords
4929 (org-make-options-regexp
4930 (append '("FILETAGS" "TAGS" "SETUPFILE")
4931 (and (not tags-only)
4932 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4933 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4934 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4935 ;; Startup options. Get this early since it does change
4936 ;; behavior for other options (e.g., tags).
4937 (let ((startup (cdr (assq 'startup alist))))
4938 (dolist (option startup)
4939 (let ((entry (assoc-string option org-startup-options t)))
4940 (when entry
4941 (let ((var (nth 1 entry))
4942 (val (nth 2 entry)))
4943 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4944 (unless (listp (symbol-value var))
4945 (set (make-local-variable var) nil))
4946 (add-to-list var val)))))))
4947 (setq-local org-file-tags
4948 (mapcar #'org-add-prop-inherited
4949 (cdr (assq 'filetags alist))))
4950 (setq org-current-tag-alist
4951 (org--tag-add-to-alist
4952 org-tag-persistent-alist
4953 (let ((tags (cdr (assq 'tags alist))))
4954 (if tags (org-tag-string-to-alist tags)
4955 org-tag-alist))))
4956 (setq org-tag-groups-alist
4957 (org-tag-alist-to-groups org-current-tag-alist))
4958 (unless tags-only
4959 ;; File properties.
4960 (setq-local org-file-properties (cdr (assq 'property alist)))
4961 ;; Archive location.
4962 (let ((archive (cdr (assq 'archive alist))))
4963 (when archive (setq-local org-archive-location archive)))
4964 ;; Category.
4965 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4966 (when cat
4967 (setq-local org-category (intern cat))
4968 (setq-local org-file-properties
4969 (org--update-property-plist
4970 "CATEGORY" cat org-file-properties))))
4971 ;; Columns.
4972 (let ((column (cdr (assq 'columns alist))))
4973 (when column (setq-local org-columns-default-format column)))
4974 ;; Constants.
4975 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4976 ;; Link abbreviations.
4977 (let ((links (cdr (assq 'link alist))))
4978 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4979 ;; Priorities.
4980 (let ((priorities (cdr (assq 'priorities alist))))
4981 (when priorities
4982 (setq-local org-highest-priority (nth 0 priorities))
4983 (setq-local org-lowest-priority (nth 1 priorities))
4984 (setq-local org-default-priority (nth 2 priorities))))
4985 ;; Scripts.
4986 (let ((scripts (assq 'scripts alist)))
4987 (when scripts
4988 (setq-local org-use-sub-superscripts (cdr scripts))))
4989 ;; TODO keywords.
4990 (setq-local org-todo-kwd-alist nil)
4991 (setq-local org-todo-key-alist nil)
4992 (setq-local org-todo-key-trigger nil)
4993 (setq-local org-todo-keywords-1 nil)
4994 (setq-local org-done-keywords nil)
4995 (setq-local org-todo-heads nil)
4996 (setq-local org-todo-sets nil)
4997 (setq-local org-todo-log-states nil)
4998 (let ((todo-sequences
4999 (or (nreverse (cdr (assq 'todo alist)))
5000 (let ((d (default-value 'org-todo-keywords)))
5001 (if (not (stringp (car d))) d
5002 ;; XXX: Backward compatibility code.
5003 (list (cons org-todo-interpretation d)))))))
5004 (dolist (sequence todo-sequences)
5005 (let* ((sequence (or (run-hook-with-args-until-success
5006 'org-todo-setup-filter-hook sequence)
5007 sequence))
5008 (sequence-type (car sequence))
5009 (keywords (cdr sequence))
5010 (sep (member "|" keywords))
5011 names alist)
5012 (dolist (k (remove "|" keywords))
5013 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5015 (error "Invalid TODO keyword %s" k))
5016 (let ((name (match-string 1 k))
5017 (key (match-string 2 k))
5018 (log (org-extract-log-state-settings k)))
5019 (push name names)
5020 (push (cons name (and key (string-to-char key))) alist)
5021 (when log (push log org-todo-log-states))))
5022 (let* ((names (nreverse names))
5023 (done (if sep (org-remove-keyword-keys (cdr sep))
5024 (last names)))
5025 (head (car names))
5026 (tail (list sequence-type head (car done) (org-last done))))
5027 (add-to-list 'org-todo-heads head 'append)
5028 (push names org-todo-sets)
5029 (setq org-done-keywords (append org-done-keywords done nil))
5030 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5031 (setq org-todo-key-alist
5032 (append org-todo-key-alist
5033 (and alist
5034 (append '((:startgroup))
5035 (nreverse alist)
5036 '((:endgroup))))))
5037 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5038 (setq org-todo-sets (nreverse org-todo-sets)
5039 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5040 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5041 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5042 ;; Compute the regular expressions and other local variables.
5043 ;; Using `org-outline-regexp-bol' would complicate them much,
5044 ;; because of the fixed white space at the end of that string.
5045 (unless org-done-keywords
5046 (setq org-done-keywords
5047 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5048 (setq org-not-done-keywords
5049 (org-delete-all org-done-keywords
5050 (copy-sequence org-todo-keywords-1))
5051 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5052 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5053 org-not-done-heading-regexp
5054 (format org-heading-keyword-regexp-format org-not-done-regexp)
5055 org-todo-line-regexp
5056 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5057 org-complex-heading-regexp
5058 (concat "^\\(\\*+\\)"
5059 "\\(?: +" org-todo-regexp "\\)?"
5060 "\\(?: +\\(\\[#.\\]\\)\\)?"
5061 "\\(?: +\\(.*?\\)\\)??"
5062 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5063 "[ \t]*$")
5064 org-complex-heading-regexp-format
5065 (concat "^\\(\\*+\\)"
5066 "\\(?: +" org-todo-regexp "\\)?"
5067 "\\(?: +\\(\\[#.\\]\\)\\)?"
5068 "\\(?: +"
5069 ;; Stats cookies can be stuck to body.
5070 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5071 "\\(%s\\)"
5072 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5073 "\\)"
5074 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5075 "[ \t]*$")
5076 org-todo-line-tags-regexp
5077 (concat "^\\(\\*+\\)"
5078 "\\(?: +" org-todo-regexp "\\)?"
5079 "\\(?: +\\(.*?\\)\\)??"
5080 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5081 "[ \t]*$"))
5082 (org-compute-latex-and-related-regexp)))))
5084 (defun org--setup-collect-keywords (regexp &optional files alist)
5085 "Return setup keywords values as an alist.
5087 REGEXP matches a subset of setup keywords. FILES is a list of
5088 file names already visited. It is used to avoid circular setup
5089 files. ALIST, when non-nil, is the alist computed so far.
5091 Return value contains the following keys: `archive', `category',
5092 `columns', `constants', `filetags', `link', `priorities',
5093 `property', `scripts', `startup', `tags' and `todo'."
5094 (org-with-wide-buffer
5095 (goto-char (point-min))
5096 (let ((case-fold-search t))
5097 (while (re-search-forward regexp nil t)
5098 (let ((element (org-element-at-point)))
5099 (when (eq (org-element-type element) 'keyword)
5100 (let ((key (org-element-property :key element))
5101 (value (org-element-property :value element)))
5102 (cond
5103 ((equal key "ARCHIVE")
5104 (when (org-string-nw-p value)
5105 (push (cons 'archive value) alist)))
5106 ((equal key "CATEGORY") (push (cons 'category value) alist))
5107 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5108 ((equal key "CONSTANTS")
5109 (let* ((constants (assq 'constants alist))
5110 (store (cdr constants)))
5111 (dolist (pair (split-string value))
5112 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5113 pair)
5114 (let* ((name (match-string 1 pair))
5115 (value (match-string 2 pair))
5116 (old (assoc name store)))
5117 (if old (setcdr old value)
5118 (push (cons name value) store)))))
5119 (if constants (setcdr constants store)
5120 (push (cons 'constants store) alist))))
5121 ((equal key "FILETAGS")
5122 (when (org-string-nw-p value)
5123 (let ((old (assq 'filetags alist))
5124 (new (apply #'nconc
5125 (mapcar (lambda (x) (org-split-string x ":"))
5126 (split-string value)))))
5127 (if old (setcdr old (append new (cdr old)))
5128 (push (cons 'filetags new) alist)))))
5129 ((equal key "LINK")
5130 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5131 (let ((links (assq 'link alist))
5132 (pair (cons (match-string-no-properties 1 value)
5133 (match-string-no-properties 2 value))))
5134 (if links (push pair (cdr links))
5135 (push (list 'link pair) alist)))))
5136 ((equal key "OPTIONS")
5137 (when (and (org-string-nw-p value)
5138 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5139 (push (cons 'scripts (read (match-string 1 value))) alist)))
5140 ((equal key "PRIORITIES")
5141 (push (cons 'priorities
5142 (let ((prio (split-string value)))
5143 (if (< (length prio) 3) '(?A ?C ?B)
5144 (mapcar #'string-to-char prio))))
5145 alist))
5146 ((equal key "PROPERTY")
5147 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5148 (let* ((property (assq 'property alist))
5149 (value (org--update-property-plist
5150 (match-string-no-properties 1 value)
5151 (match-string-no-properties 2 value)
5152 (cdr property))))
5153 (if property (setcdr property value)
5154 (push (cons 'property value) alist)))))
5155 ((equal key "STARTUP")
5156 (let ((startup (assq 'startup alist)))
5157 (if startup
5158 (setcdr startup
5159 (append (cdr startup) (split-string value)))
5160 (push (cons 'startup (split-string value)) alist))))
5161 ((equal key "TAGS")
5162 (let ((tag-cell (assq 'tags alist)))
5163 (if tag-cell
5164 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5165 (push (cons 'tags value) alist))))
5166 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5167 (let ((todo (assq 'todo alist))
5168 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5169 (split-string value))))
5170 (if todo (push value (cdr todo))
5171 (push (list 'todo value) alist))))
5172 ((equal key "SETUPFILE")
5173 (unless buffer-read-only ; Do not check in Gnus messages.
5174 (let ((f (and (org-string-nw-p value)
5175 (expand-file-name
5176 (org-unbracket-string "\"" "\"" value)))))
5177 (when (and f (file-readable-p f) (not (member f files)))
5178 (with-temp-buffer
5179 (setq default-directory (file-name-directory f))
5180 (insert-file-contents f)
5181 (setq alist
5182 ;; Fake Org mode to benefit from cache
5183 ;; without recurring needlessly.
5184 (let ((major-mode 'org-mode))
5185 (org--setup-collect-keywords
5186 regexp (cons f files) alist)))))))))))))))
5187 alist)
5189 (defun org-tag-string-to-alist (s)
5190 "Return tag alist associated to string S.
5191 S is a value for TAGS keyword or produced with
5192 `org-tag-alist-to-string'. Return value is an alist suitable for
5193 `org-tag-alist' or `org-tag-persistent-alist'."
5194 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5195 (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
5196 "\\(?:(\\(.\\))\\)?\\'"))
5197 alist group-flag)
5198 (dolist (tokens lines (cdr (nreverse alist)))
5199 (push '(:newline) alist)
5200 (while tokens
5201 (let ((token (pop tokens)))
5202 (pcase token
5203 ("{"
5204 (push '(:startgroup) alist)
5205 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5206 ("}"
5207 (push '(:endgroup) alist)
5208 (setq group-flag nil))
5209 ("["
5210 (push '(:startgrouptag) alist)
5211 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5212 ("]"
5213 (push '(:endgrouptag) alist)
5214 (setq group-flag nil))
5215 (":"
5216 (push '(:grouptags) alist))
5217 ((guard (string-match tag-re token))
5218 (let ((tag (match-string 1 token))
5219 (key (and (match-beginning 2)
5220 (string-to-char (match-string 2 token)))))
5221 ;; Push all tags in groups, no matter if they already
5222 ;; appear somewhere else in the list.
5223 (when (or group-flag (not (assoc tag alist)))
5224 (push (cons tag key) alist))))))))))
5226 (defun org-tag-alist-to-string (alist &optional skip-key)
5227 "Return tag string associated to ALIST.
5229 ALIST is an alist, as defined in `org-tag-alist' or
5230 `org-tag-persistent-alist', or produced with
5231 `org-tag-string-to-alist'.
5233 Return value is a string suitable as a value for \"TAGS\"
5234 keyword.
5236 When optional argument SKIP-KEY is non-nil, skip selection keys
5237 next to tags."
5238 (mapconcat (lambda (token)
5239 (pcase token
5240 (`(:startgroup) "{")
5241 (`(:endgroup) "}")
5242 (`(:startgrouptag) "[")
5243 (`(:endgrouptag) "]")
5244 (`(:grouptags) ":")
5245 (`(:newline) "\\n")
5246 ((and
5247 (guard (not skip-key))
5248 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5249 (format "%s(%c)" tag key))
5250 (`(,(and tag (pred stringp)) . ,_) tag)
5251 (_ (user-error "Invalid tag token: %S" token))))
5252 alist
5253 " "))
5255 (defun org-tag-alist-to-groups (alist)
5256 "Return group alist from tag ALIST.
5257 ALIST is an alist, as defined in `org-tag-alist' or
5258 `org-tag-persistent-alist', or produced with
5259 `org-tag-string-to-alist'. Return value is an alist following
5260 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5261 a string, summarizing TAGS, as a list of strings."
5262 (let (groups group-status current-group)
5263 (dolist (token alist (nreverse groups))
5264 (pcase token
5265 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5266 (`(,(or :endgroup :endgrouptag))
5267 (when (eq group-status 'append)
5268 (push (nreverse current-group) groups))
5269 (setq group-status nil current-group nil))
5270 (`(:grouptags) (setq group-status 'append))
5271 ((and `(,tag . ,_) (guard group-status))
5272 (if (eq group-status 'append) (push tag current-group)
5273 (setq current-group (list tag))))
5274 (_ nil)))))
5276 (defvar org--file-cache (make-hash-table :test #'equal)
5277 "Hash table to store contents of files referenced via a URL.
5278 This is the cache of file URLs read using `org-file-contents'.")
5280 (defun org-reset-file-cache ()
5281 "Reset the cache of files downloaded by `org-file-contents'."
5282 (clrhash org--file-cache))
5284 (defun org-file-url-p (file)
5285 "Non-nil if FILE is a URL."
5286 (require 'ffap)
5287 (string-match-p ffap-url-regexp file))
5289 (defun org-file-contents (file &optional noerror nocache)
5290 "Return the contents of FILE, as a string.
5292 FILE can be a file name or URL.
5294 If FILE is a URL, download the contents. If the URL contents are
5295 already cached in the `org--file-cache' hash table, the download step
5296 is skipped.
5298 If NOERROR is non-nil, ignore the error when unable to read the FILE
5299 from file or URL.
5301 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5302 is available. This option applies only if FILE is a URL."
5303 (let* ((is-url (org-file-url-p file))
5304 (cache (and is-url
5305 (not nocache)
5306 (gethash file org--file-cache))))
5307 (cond
5308 (cache)
5309 (is-url
5310 (with-current-buffer (url-retrieve-synchronously file)
5311 (goto-char (point-min))
5312 ;; Move point to after the url-retrieve header.
5313 (search-forward "\n\n" nil :move)
5314 ;; Search for the success code only in the url-retrieve header.
5315 (if (save-excursion
5316 (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5317 ;; Update the cache `org--file-cache' and return contents.
5318 (puthash file
5319 (buffer-substring-no-properties (point) (point-max))
5320 org--file-cache)
5321 (funcall (if noerror #'message #'user-error)
5322 "Unable to fetch file from %S"
5323 file))))
5325 (with-temp-buffer
5326 (condition-case nil
5327 (progn
5328 (insert-file-contents file)
5329 (buffer-string))
5330 (file-error
5331 (funcall (if noerror #'message #'user-error)
5332 "Unable to read file %S"
5333 file))))))))
5335 (defun org-extract-log-state-settings (x)
5336 "Extract the log state setting from a TODO keyword string.
5337 This will extract info from a string like \"WAIT(w@/!)\"."
5338 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5339 (let ((kw (match-string 1 x))
5340 (log1 (and (match-end 3) (match-string 3 x)))
5341 (log2 (and (match-end 4) (match-string 4 x))))
5342 (and (or log1 log2)
5343 (list kw
5344 (and log1 (if (equal log1 "!") 'time 'note))
5345 (and log2 (if (equal log2 "!") 'time 'note)))))))
5347 (defun org-remove-keyword-keys (list)
5348 "Remove a pair of parenthesis at the end of each string in LIST."
5349 (mapcar (lambda (x)
5350 (if (string-match "(.*)$" x)
5351 (substring x 0 (match-beginning 0))
5353 list))
5355 (defun org-assign-fast-keys (alist)
5356 "Assign fast keys to a keyword-key alist.
5357 Respect keys that are already there."
5358 (let (new e (alt ?0))
5359 (while (setq e (pop alist))
5360 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5361 (cdr e)) ;; Key already assigned.
5362 (push e new)
5363 (let ((clist (string-to-list (downcase (car e))))
5364 (used (append new alist)))
5365 (when (= (car clist) ?@)
5366 (pop clist))
5367 (while (and clist (rassoc (car clist) used))
5368 (pop clist))
5369 (unless clist
5370 (while (rassoc alt used)
5371 (cl-incf alt)))
5372 (push (cons (car e) (or (car clist) alt)) new))))
5373 (nreverse new)))
5375 ;;; Some variables used in various places
5377 (defvar org-window-configuration nil
5378 "Used in various places to store a window configuration.")
5379 (defvar org-selected-window nil
5380 "Used in various places to store a window configuration.")
5381 (defvar org-finish-function nil
5382 "Function to be called when `C-c C-c' is used.
5383 This is for getting out of special buffers like capture.")
5384 (defvar org-last-state)
5386 ;; Defined somewhere in this file, but used before definition.
5387 (defvar org-entities) ;; defined in org-entities.el
5388 (defvar org-struct-menu)
5389 (defvar org-org-menu)
5390 (defvar org-tbl-menu)
5392 ;;;; Define the Org mode
5394 ;; We use a before-change function to check if a table might need
5395 ;; an update.
5396 (defvar org-table-may-need-update t
5397 "Indicates that a table might need an update.
5398 This variable is set by `org-before-change-function'.
5399 `org-table-align' sets it back to nil.")
5400 (defun org-before-change-function (_beg _end)
5401 "Every change indicates that a table might need an update."
5402 (setq org-table-may-need-update t))
5403 (defvar org-mode-map)
5404 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5405 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5406 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5407 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5408 (defvar org-table-buffer-is-an nil)
5410 (defvar bidi-paragraph-direction)
5411 (defvar buffer-face-mode-face)
5413 (require 'outline)
5415 ;; Other stuff we need.
5416 (require 'time-date)
5417 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5418 (require 'easymenu)
5419 (autoload 'easy-menu-add "easymenu")
5420 (require 'overlay)
5422 ;; (require 'org-macs) moved higher up in the file before it is first used
5423 (require 'org-entities)
5424 ;; (require 'org-compat) moved higher up in the file before it is first used
5425 (require 'org-faces)
5426 (require 'org-list)
5427 (require 'org-pcomplete)
5428 (require 'org-src)
5429 (require 'org-footnote)
5430 (require 'org-macro)
5432 ;; babel
5433 (require 'ob)
5435 ;;;###autoload
5436 (define-derived-mode org-mode outline-mode "Org"
5437 "Outline-based notes management and organizer, alias
5438 \"Carsten's outline-mode for keeping track of everything.\"
5440 Org mode develops organizational tasks around a NOTES file which
5441 contains information about projects as plain text. Org mode is
5442 implemented on top of Outline mode, which is ideal to keep the content
5443 of large files well structured. It supports ToDo items, deadlines and
5444 time stamps, which magically appear in the diary listing of the Emacs
5445 calendar. Tables are easily created with a built-in table editor.
5446 Plain text URL-like links connect to websites, emails (VM), Usenet
5447 messages (Gnus), BBDB entries, and any files related to the project.
5448 For printing and sharing of notes, an Org file (or a part of it)
5449 can be exported as a structured ASCII or HTML file.
5451 The following commands are available:
5453 \\{org-mode-map}"
5455 ;; Get rid of Outline menus, they are not needed
5456 ;; Need to do this here because define-derived-mode sets up
5457 ;; the keymap so late. Still, it is a waste to call this each time
5458 ;; we switch another buffer into Org mode.
5459 (define-key org-mode-map [menu-bar headings] 'undefined)
5460 (define-key org-mode-map [menu-bar hide] 'undefined)
5461 (define-key org-mode-map [menu-bar show] 'undefined)
5463 (org-load-modules-maybe)
5464 (org-install-agenda-files-menu)
5465 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5466 (add-to-invisibility-spec '(org-hide-block . t))
5467 (add-to-invisibility-spec '(org-hide-drawer . t))
5468 (setq-local outline-regexp org-outline-regexp)
5469 (setq-local outline-level 'org-outline-level)
5470 (setq bidi-paragraph-direction 'left-to-right)
5471 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5472 (unless org-display-table
5473 (setq org-display-table (make-display-table)))
5474 (set-display-table-slot
5475 org-display-table 4
5476 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5477 org-ellipsis)))
5478 (setq buffer-display-table org-display-table))
5479 (org-set-regexps-and-options)
5480 (org-set-font-lock-defaults)
5481 (when (and org-tag-faces (not org-tags-special-faces-re))
5482 ;; tag faces set outside customize.... force initialization.
5483 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5484 ;; Calc embedded
5485 (setq-local calc-embedded-open-mode "# ")
5486 ;; Modify a few syntax entries
5487 (modify-syntax-entry ?\" "\"")
5488 (modify-syntax-entry ?\\ "_")
5489 (modify-syntax-entry ?~ "_")
5490 (modify-syntax-entry ?< "(>")
5491 (modify-syntax-entry ?> ")<")
5492 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5493 ;; Activate before-change-function
5494 (setq-local org-table-may-need-update t)
5495 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5496 ;; Check for running clock before killing a buffer
5497 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5498 ;; Initialize macros templates.
5499 (org-macro-initialize-templates)
5500 ;; Initialize radio targets.
5501 (org-update-radio-target-regexp)
5502 ;; Indentation.
5503 (setq-local indent-line-function 'org-indent-line)
5504 (setq-local indent-region-function 'org-indent-region)
5505 ;; Filling and auto-filling.
5506 (org-setup-filling)
5507 ;; Comments.
5508 (org-setup-comments-handling)
5509 ;; Initialize cache.
5510 (org-element-cache-reset)
5511 ;; Beginning/end of defun
5512 (setq-local beginning-of-defun-function 'org-backward-element)
5513 (setq-local end-of-defun-function
5514 (lambda ()
5515 (if (not (org-at-heading-p))
5516 (org-forward-element)
5517 (org-forward-element)
5518 (forward-char -1))))
5519 ;; Next error for sparse trees
5520 (setq-local next-error-function 'org-occur-next-match)
5521 ;; Make commit log messages from Org documents easier.
5522 (setq-local add-log-current-defun-function #'org-add-log-current-headline)
5523 ;; Make sure dependence stuff works reliably, even for users who set it
5524 ;; too late :-(
5525 (if org-enforce-todo-dependencies
5526 (add-hook 'org-blocker-hook
5527 'org-block-todo-from-children-or-siblings-or-parent)
5528 (remove-hook 'org-blocker-hook
5529 'org-block-todo-from-children-or-siblings-or-parent))
5530 (if org-enforce-todo-checkbox-dependencies
5531 (add-hook 'org-blocker-hook
5532 'org-block-todo-from-checkboxes)
5533 (remove-hook 'org-blocker-hook
5534 'org-block-todo-from-checkboxes))
5536 ;; Align options lines
5537 (setq-local
5538 align-mode-rules-list
5539 '((org-in-buffer-settings
5540 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5541 (modes . '(org-mode)))))
5543 ;; Make isearch reveal context
5544 (setq-local outline-isearch-open-invisible-function
5545 (lambda (&rest _) (org-show-context 'isearch)))
5547 ;; Setup the pcomplete hooks
5548 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5549 (setq-local pcomplete-command-name-function 'org-command-at-point)
5550 (setq-local pcomplete-default-completion-function 'ignore)
5551 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5552 (setq-local pcomplete-termination-string "")
5553 (setq-local buffer-face-mode-face 'org-default)
5555 ;; If empty file that did not turn on Org mode automatically, make
5556 ;; it to.
5557 (when (and org-insert-mode-line-in-empty-file
5558 (called-interactively-p 'any)
5559 (= (point-min) (point-max)))
5560 (insert "# -*- mode: org -*-\n\n"))
5561 (unless org-inhibit-startup
5562 (org-unmodified
5563 (when org-startup-with-beamer-mode (org-beamer-mode))
5564 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5565 (org-table-map-tables
5566 (cond ((and org-startup-align-all-tables
5567 org-startup-shrink-all-tables)
5568 (lambda () (org-table-align) (org-table-shrink)))
5569 (org-startup-align-all-tables #'org-table-align)
5570 (t #'org-table-shrink))
5572 (when org-startup-with-inline-images (org-display-inline-images))
5573 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5574 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5575 (when org-startup-truncated (setq truncate-lines t))
5576 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5577 (org-refresh-effort-properties)))
5578 ;; Try to set `org-hide' face correctly.
5579 (let ((foreground (org-find-invisible-foreground)))
5580 (when foreground
5581 (set-face-foreground 'org-hide foreground))))
5583 ;; Update `customize-package-emacs-version-alist'
5584 (add-to-list 'customize-package-emacs-version-alist
5585 '(Org ("8.0" . "24.4")
5586 ("8.1" . "24.4")
5587 ("8.2" . "24.4")
5588 ("8.2.7" . "24.4")
5589 ("8.3" . "26.1")
5590 ("9.0" . "26.1")
5591 ("9.1" . "26.1")
5592 ("9.2" . "27.1")))
5594 (defvar org-mode-transpose-word-syntax-table
5595 (let ((st (make-syntax-table text-mode-syntax-table)))
5596 (dolist (c org-emphasis-alist st)
5597 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5599 (when (fboundp 'abbrev-table-put)
5600 (abbrev-table-put org-mode-abbrev-table
5601 :parents (list text-mode-abbrev-table)))
5603 (defun org-find-invisible-foreground ()
5604 (let ((candidates (remove
5605 "unspecified-bg"
5606 (nconc
5607 (list (face-background 'default)
5608 (face-background 'org-default))
5609 (mapcar
5610 (lambda (alist)
5611 (when (boundp alist)
5612 (cdr (assq 'background-color (symbol-value alist)))))
5613 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5614 (list (face-foreground 'org-hide))))))
5615 (car (remove nil candidates))))
5617 (defun org-current-time (&optional rounding-minutes past)
5618 "Current time, possibly rounded to ROUNDING-MINUTES.
5619 When ROUNDING-MINUTES is not an integer, fall back on the car of
5620 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5621 the rounding returns a past time."
5622 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5623 (car org-time-stamp-rounding-minutes)))
5624 (time (decode-time)) res)
5625 (if (< r 1)
5626 (current-time)
5627 (setq res
5628 (apply 'encode-time
5629 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5630 (nthcdr 2 time))))
5631 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5632 (seconds-to-time (- (float-time res) (* r 60)))
5633 res))))
5635 (defun org-today ()
5636 "Return today date, considering `org-extend-today-until'."
5637 (time-to-days
5638 (time-subtract (current-time)
5639 (list 0 (* 3600 org-extend-today-until) 0))))
5641 ;;;; Font-Lock stuff, including the activators
5643 (defvar org-mouse-map (make-sparse-keymap))
5644 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5645 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5646 (when org-mouse-1-follows-link
5647 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5648 (when org-tab-follows-link
5649 (org-defkey org-mouse-map (kbd "<tab>") #'org-open-at-point)
5650 (org-defkey org-mouse-map (kbd "TAB") #'org-open-at-point))
5652 (require 'font-lock)
5654 (defconst org-non-link-chars "]\t\n\r<>")
5655 (defvar org-link-types-re nil
5656 "Matches a link that has a url-like prefix like \"http:\"")
5657 (defvar org-link-re-with-space nil
5658 "Matches a link with spaces, optional angular brackets around it.")
5659 (defvar org-link-re-with-space2 nil
5660 "Matches a link with spaces, optional angular brackets around it.")
5661 (defvar org-link-re-with-space3 nil
5662 "Matches a link with spaces, only for internal part in bracket links.")
5663 (defvar org-angle-link-re nil
5664 "Matches link with angular brackets, spaces are allowed.")
5665 (defvar org-plain-link-re nil
5666 "Matches plain link, without spaces.")
5667 (defvar org-bracket-link-regexp nil
5668 "Matches a link in double brackets.")
5669 (defvar org-bracket-link-analytic-regexp nil
5670 "Regular expression used to analyze links.
5671 Here is what the match groups contain after a match:
5672 1: http:
5673 2: http
5674 3: path
5675 4: [desc]
5676 5: desc")
5677 (defvar org-bracket-link-analytic-regexp++ nil
5678 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5679 (defvar org-any-link-re nil
5680 "Regular expression matching any link.")
5682 (defconst org-match-sexp-depth 3
5683 "Number of stacked braces for sub/superscript matching.")
5685 (defun org-create-multibrace-regexp (left right n)
5686 "Create a regular expression which will match a balanced sexp.
5687 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5688 as single character strings.
5689 The regexp returned will match the entire expression including the
5690 delimiters. It will also define a single group which contains the
5691 match except for the outermost delimiters. The maximum depth of
5692 stacked delimiters is N. Escaping delimiters is not possible."
5693 (let* ((nothing (concat "[^" left right "]*?"))
5694 (or "\\|")
5695 (re nothing)
5696 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5697 (while (> n 1)
5698 (setq n (1- n)
5699 re (concat re or next)
5700 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5701 (concat left "\\(" re "\\)" right)))
5703 (defconst org-match-substring-regexp
5704 (concat
5705 "\\(\\S-\\)\\([_^]\\)\\("
5706 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5707 "\\|"
5708 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5709 "\\|"
5710 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5711 "The regular expression matching a sub- or superscript.")
5713 (defconst org-match-substring-with-braces-regexp
5714 (concat
5715 "\\(\\S-\\)\\([_^]\\)"
5716 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5717 "The regular expression matching a sub- or superscript, forcing braces.")
5719 (defun org-make-link-regexps ()
5720 "Update the link regular expressions.
5721 This should be called after the variable `org-link-parameters' has changed."
5722 (let ((types-re (regexp-opt (org-link-types) t)))
5723 (setq org-link-types-re
5724 (concat "\\`" types-re ":")
5725 org-link-re-with-space
5726 (concat "<?" types-re ":"
5727 "\\([^" org-non-link-chars " ]"
5728 "[^" org-non-link-chars "]*"
5729 "[^" org-non-link-chars " ]\\)>?")
5730 org-link-re-with-space2
5731 (concat "<?" types-re ":"
5732 "\\([^" org-non-link-chars " ]"
5733 "[^\t\n\r]*"
5734 "[^" org-non-link-chars " ]\\)>?")
5735 org-link-re-with-space3
5736 (concat "<?" types-re ":"
5737 "\\([^" org-non-link-chars " ]"
5738 "[^\t\n\r]*\\)")
5739 org-angle-link-re
5740 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5741 types-re)
5742 org-plain-link-re
5743 (concat
5744 "\\<" types-re ":"
5745 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5746 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5747 org-bracket-link-regexp
5748 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5749 org-bracket-link-analytic-regexp
5750 (concat
5751 "\\[\\["
5752 "\\(" types-re ":\\)?"
5753 "\\([^]]+\\)"
5754 "\\]"
5755 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5756 "\\]")
5757 org-bracket-link-analytic-regexp++
5758 (concat
5759 "\\[\\["
5760 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5761 "\\([^]]+\\)"
5762 "\\]"
5763 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5764 "\\]")
5765 org-any-link-re
5766 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5767 org-angle-link-re "\\)\\|\\("
5768 org-plain-link-re "\\)"))))
5770 (org-make-link-regexps)
5772 (defvar org-emph-face nil)
5774 (defun org-do-emphasis-faces (limit)
5775 "Run through the buffer and emphasize strings."
5776 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5777 (car org-emphasis-regexp-components))))
5778 (catch :exit
5779 (while (re-search-forward quick-re limit t)
5780 (let* ((marker (match-string 2))
5781 (verbatim? (member marker '("~" "="))))
5782 (when (save-excursion
5783 (goto-char (match-beginning 0))
5784 (and
5785 ;; Do not match table hlines.
5786 (not (and (equal marker "+")
5787 (org-match-line
5788 "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5789 ;; Do not match headline stars. Do not consider
5790 ;; stars of a headline as closing marker for bold
5791 ;; markup either.
5792 (not (and (equal marker "*")
5793 (save-excursion
5794 (forward-char)
5795 (skip-chars-backward "*")
5796 (looking-at-p org-outline-regexp-bol))))
5797 ;; Match full emphasis markup regexp.
5798 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5799 ;; Do not span over paragraph boundaries.
5800 (not (string-match-p org-element-paragraph-separate
5801 (match-string 2)))
5802 ;; Do not span over cells in table rows.
5803 (not (and (save-match-data (org-match-line "[ \t]*|"))
5804 (string-match-p "|" (match-string 4))))))
5805 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5806 (font-lock-prepend-text-property
5807 (match-beginning 2) (match-end 2) 'face face)
5808 (when verbatim?
5809 (org-remove-flyspell-overlays-in
5810 (match-beginning 0) (match-end 0)))
5811 (add-text-properties (match-beginning 2) (match-end 2)
5812 '(font-lock-multiline t org-emphasis t))
5813 (when org-hide-emphasis-markers
5814 (add-text-properties (match-end 4) (match-beginning 5)
5815 '(invisible org-link))
5816 (add-text-properties (match-beginning 3) (match-end 3)
5817 '(invisible org-link)))
5818 (throw :exit t))))))))
5820 (defun org-emphasize (&optional char)
5821 "Insert or change an emphasis, i.e. a font like bold or italic.
5822 If there is an active region, change that region to a new emphasis.
5823 If there is no region, just insert the marker characters and position
5824 the cursor between them.
5825 CHAR should be the marker character. If it is a space, it means to
5826 remove the emphasis of the selected region.
5827 If CHAR is not given (for example in an interactive call) it will be
5828 prompted for."
5829 (interactive)
5830 (let ((erc org-emphasis-regexp-components)
5831 (string "") beg end move s)
5832 (if (org-region-active-p)
5833 (setq beg (region-beginning)
5834 end (region-end)
5835 string (buffer-substring beg end))
5836 (setq move t))
5838 (unless char
5839 (message "Emphasis marker or tag: [%s]"
5840 (mapconcat #'car org-emphasis-alist ""))
5841 (setq char (read-char-exclusive)))
5842 (if (equal char ?\s)
5843 (setq s ""
5844 move nil)
5845 (unless (assoc (char-to-string char) org-emphasis-alist)
5846 (user-error "No such emphasis marker: \"%c\"" char))
5847 (setq s (char-to-string char)))
5848 (while (and (> (length string) 1)
5849 (equal (substring string 0 1) (substring string -1))
5850 (assoc (substring string 0 1) org-emphasis-alist))
5851 (setq string (substring string 1 -1)))
5852 (setq string (concat s string s))
5853 (when beg (delete-region beg end))
5854 (unless (or (bolp)
5855 (string-match (concat "[" (nth 0 erc) "\n]")
5856 (char-to-string (char-before (point)))))
5857 (insert " "))
5858 (unless (or (eobp)
5859 (string-match (concat "[" (nth 1 erc) "\n]")
5860 (char-to-string (char-after (point)))))
5861 (insert " ") (backward-char 1))
5862 (insert string)
5863 (and move (backward-char 1))))
5865 (defconst org-nonsticky-props
5866 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5868 (defsubst org-rear-nonsticky-at (pos)
5869 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5871 (defun org-activate-links (limit)
5872 "Add link properties to links.
5873 This includes angle, plain, and bracket links."
5874 (catch :exit
5875 (while (re-search-forward org-any-link-re limit t)
5876 (let* ((start (match-beginning 0))
5877 (end (match-end 0))
5878 (style (cond ((eq ?< (char-after start)) 'angle)
5879 ((eq ?\[ (char-after (1+ start))) 'bracket)
5880 (t 'plain))))
5881 (when (and (memq style org-highlight-links)
5882 ;; Do not confuse plain links with tags.
5883 (not (and (eq style 'plain)
5884 (let ((face (get-text-property
5885 (max (1- start) (point-min)) 'face)))
5886 (if (consp face) (memq 'org-tag face)
5887 (eq 'org-tag face))))))
5888 (let* ((link-object (save-excursion
5889 (goto-char start)
5890 (save-match-data (org-element-link-parser))))
5891 (link (org-element-property :raw-link link-object))
5892 (type (org-element-property :type link-object))
5893 (path (org-element-property :path link-object))
5894 (properties ;for link's visible part
5895 (list
5896 'face (pcase (org-link-get-parameter type :face)
5897 ((and (pred functionp) face) (funcall face path))
5898 ((and (pred facep) face) face)
5899 ((and (pred consp) face) face) ;anonymous
5900 (_ 'org-link))
5901 'mouse-face (or (org-link-get-parameter type :mouse-face)
5902 'highlight)
5903 'keymap (or (org-link-get-parameter type :keymap)
5904 org-mouse-map)
5905 'help-echo (pcase (org-link-get-parameter type :help-echo)
5906 ((and (pred stringp) echo) echo)
5907 ((and (pred functionp) echo) echo)
5908 (_ (concat "LINK: " link)))
5909 'htmlize-link (pcase (org-link-get-parameter type
5910 :htmlize-link)
5911 ((and (pred functionp) f) (funcall f))
5912 (_ `(:uri ,link)))
5913 'font-lock-multiline t)))
5914 (org-remove-flyspell-overlays-in start end)
5915 (org-rear-nonsticky-at end)
5916 (if (not (eq 'bracket style))
5917 (add-text-properties start end properties)
5918 ;; Handle invisible parts in bracket links.
5919 (remove-text-properties start end '(invisible nil))
5920 (let ((hidden
5921 (append `(invisible
5922 ,(or (org-link-get-parameter type :display)
5923 'org-link))
5924 properties))
5925 (visible-start (or (match-beginning 4) (match-beginning 2)))
5926 (visible-end (or (match-end 4) (match-end 2))))
5927 (add-text-properties start visible-start hidden)
5928 (add-text-properties visible-start visible-end properties)
5929 (add-text-properties visible-end end hidden)
5930 (org-rear-nonsticky-at visible-start)
5931 (org-rear-nonsticky-at visible-end)))
5932 (let ((f (org-link-get-parameter type :activate-func)))
5933 (when (functionp f)
5934 (funcall f start end path (eq style 'bracket))))
5935 (throw :exit t))))) ;signal success
5936 nil))
5938 (defun org-activate-code (limit)
5939 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5940 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5941 (remove-text-properties (match-beginning 0) (match-end 0)
5942 '(display t invisible t intangible t))
5945 (defcustom org-src-fontify-natively t
5946 "When non-nil, fontify code in code blocks.
5947 See also the `org-block' face."
5948 :type 'boolean
5949 :version "26.1"
5950 :package-version '(Org . "8.3")
5951 :group 'org-appearance
5952 :group 'org-babel)
5954 (defcustom org-allow-promoting-top-level-subtree nil
5955 "When non-nil, allow promoting a top level subtree.
5956 The leading star of the top level headline will be replaced
5957 by a #."
5958 :type 'boolean
5959 :version "24.1"
5960 :group 'org-appearance)
5962 (defun org-fontify-meta-lines-and-blocks (limit)
5963 (condition-case nil
5964 (org-fontify-meta-lines-and-blocks-1 limit)
5965 (error (message "Org mode fontification error in %S at %d"
5966 (current-buffer)
5967 (line-number-at-pos)))))
5969 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5970 "Fontify #+ lines and blocks."
5971 (let ((case-fold-search t))
5972 (when (re-search-forward
5973 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5974 limit t)
5975 (let ((beg (match-beginning 0))
5976 (block-start (match-end 0))
5977 (block-end nil)
5978 (lang (match-string 7))
5979 (beg1 (line-beginning-position 2))
5980 (dc1 (downcase (match-string 2)))
5981 (dc3 (downcase (match-string 3)))
5982 end end1 quoting block-type)
5983 (cond
5984 ((and (match-end 4) (equal dc3 "+begin"))
5985 ;; Truly a block
5986 (setq block-type (downcase (match-string 5))
5987 quoting (member block-type org-protecting-blocks))
5988 (when (re-search-forward
5989 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5990 nil t) ;; on purpose, we look further than LIMIT
5991 (setq end (min (point-max) (match-end 0))
5992 end1 (min (point-max) (1- (match-beginning 0))))
5993 (setq block-end (match-beginning 0))
5994 (when quoting
5995 (org-remove-flyspell-overlays-in beg1 end1)
5996 (remove-text-properties beg end
5997 '(display t invisible t intangible t)))
5998 (add-text-properties
5999 beg end '(font-lock-fontified t font-lock-multiline t))
6000 (add-text-properties beg beg1 '(face org-meta-line))
6001 (org-remove-flyspell-overlays-in beg beg1)
6002 (add-text-properties ; For end_src
6003 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6004 (org-remove-flyspell-overlays-in end1 end)
6005 (cond
6006 ((and lang (not (string= lang "")) org-src-fontify-natively)
6007 (org-src-font-lock-fontify-block lang block-start block-end)
6008 (add-text-properties beg1 block-end '(src-block t)))
6009 (quoting
6010 (add-text-properties beg1 (min (point-max) (1+ end1))
6011 (list 'face
6012 (list :inherit
6013 (let ((face-name
6014 (intern (format "org-block-%s" lang))))
6015 (append (and (facep face-name) (list face-name))
6016 '(org-block))))))) ; end of source block
6017 ((not org-fontify-quote-and-verse-blocks))
6018 ((string= block-type "quote")
6019 (add-face-text-property
6020 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6021 ((string= block-type "verse")
6022 (add-face-text-property
6023 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6024 (add-text-properties beg beg1 '(face org-block-begin-line))
6025 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6026 '(face org-block-end-line))
6028 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6029 (org-remove-flyspell-overlays-in
6030 (match-beginning 0)
6031 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6032 (add-text-properties
6033 beg (match-end 3)
6034 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6035 '(font-lock-fontified t invisible t)
6036 '(font-lock-fontified t face org-document-info-keyword)))
6037 (add-text-properties
6038 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6039 (if (string-equal dc1 "+title:")
6040 '(font-lock-fontified t face org-document-title)
6041 '(font-lock-fontified t face org-document-info))))
6042 ((string-prefix-p "+caption" dc1)
6043 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6044 (remove-text-properties (match-beginning 0) (match-end 0)
6045 '(display t invisible t intangible t))
6046 ;; Handle short captions.
6047 (save-excursion
6048 (beginning-of-line)
6049 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6050 (add-text-properties (line-beginning-position) (match-end 1)
6051 '(font-lock-fontified t face org-meta-line))
6052 (add-text-properties (match-end 0) (line-end-position)
6053 '(font-lock-fontified t face org-block))
6055 ((member dc3 '(" " ""))
6056 (org-remove-flyspell-overlays-in beg (match-end 0))
6057 (add-text-properties
6058 beg (match-end 0)
6059 '(font-lock-fontified t face font-lock-comment-face)))
6060 (t ;; just any other in-buffer setting, but not indented
6061 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6062 (remove-text-properties (match-beginning 0) (match-end 0)
6063 '(display t invisible t intangible t))
6064 (add-text-properties beg (match-end 0)
6065 '(font-lock-fontified t face org-meta-line))
6066 t))))))
6068 (defun org-fontify-drawers (limit)
6069 "Fontify drawers."
6070 (when (re-search-forward org-drawer-regexp limit t)
6071 (add-text-properties
6072 (match-beginning 0) (match-end 0)
6073 '(font-lock-fontified t face org-special-keyword))
6074 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6077 (defun org-fontify-macros (limit)
6078 "Fontify macros."
6079 (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
6080 (let ((begin (match-beginning 0))
6081 (opening-end (match-beginning 1)))
6082 (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
6083 (match-string 1))
6084 (let ((end (match-end 1))
6085 (closing-start (match-beginning 1)))
6086 (add-text-properties
6087 begin end
6088 '(font-lock-multiline t font-lock-fontified t face org-macro))
6089 (org-remove-flyspell-overlays-in begin end)
6090 (when org-hide-macro-markers
6091 (add-text-properties begin opening-end '(invisible t))
6092 (add-text-properties closing-start end '(invisible t)))
6093 t)))))
6095 (defun org-activate-footnote-links (limit)
6096 "Add text properties for footnotes."
6097 (let ((fn (org-footnote-next-reference-or-definition limit)))
6098 (when fn
6099 (let* ((beg (nth 1 fn))
6100 (end (nth 2 fn))
6101 (label (car fn))
6102 (referencep (/= (line-beginning-position) beg)))
6103 (when (and referencep (nth 3 fn))
6104 (save-excursion
6105 (goto-char beg)
6106 (search-forward (or label "fn:"))
6107 (org-remove-flyspell-overlays-in beg (match-end 0))))
6108 (add-text-properties beg end
6109 (list 'mouse-face 'highlight
6110 'keymap org-mouse-map
6111 'help-echo
6112 (if referencep "Footnote reference"
6113 "Footnote definition")
6114 'font-lock-fontified t
6115 'font-lock-multiline t
6116 'face 'org-footnote))))))
6118 (defun org-activate-dates (limit)
6119 "Add text properties for dates."
6120 (when (and (re-search-forward org-tsr-regexp-both limit t)
6121 (not (equal (char-before (match-beginning 0)) 91)))
6122 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6123 (add-text-properties (match-beginning 0) (match-end 0)
6124 (list 'mouse-face 'highlight
6125 'keymap org-mouse-map))
6126 (org-rear-nonsticky-at (match-end 0))
6127 (when org-display-custom-times
6128 ;; If it's a date range, activate custom time for second date.
6129 (when (match-end 3)
6130 (org-display-custom-time (match-beginning 3) (match-end 3)))
6131 (org-display-custom-time (match-beginning 1) (match-end 1)))
6134 (defvar-local org-target-link-regexp nil
6135 "Regular expression matching radio targets in plain text.")
6137 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6138 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6139 border border border))
6140 "Regular expression matching a link target.")
6142 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6143 "Regular expression matching a radio target.")
6145 (defconst org-any-target-regexp
6146 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6147 "Regular expression matching any target.")
6149 (defun org-activate-target-links (limit)
6150 "Add text properties for target matches."
6151 (when org-target-link-regexp
6152 (let ((case-fold-search t))
6153 (when (re-search-forward org-target-link-regexp limit t)
6154 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6155 (add-text-properties (match-beginning 1) (match-end 1)
6156 (list 'mouse-face 'highlight
6157 'keymap org-mouse-map
6158 'help-echo "Radio target link"
6159 'org-linked-text t))
6160 (org-rear-nonsticky-at (match-end 1))
6161 t))))
6163 (defun org-update-radio-target-regexp ()
6164 "Find all radio targets in this file and update the regular expression.
6165 Also refresh fontification if needed."
6166 (interactive)
6167 (let ((old-regexp org-target-link-regexp)
6168 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6169 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6170 (targets
6171 (org-with-wide-buffer
6172 (goto-char (point-min))
6173 (let (rtn)
6174 (while (re-search-forward org-radio-target-regexp nil t)
6175 ;; Make sure point is really within the object.
6176 (backward-char)
6177 (let ((obj (org-element-context)))
6178 (when (eq (org-element-type obj) 'radio-target)
6179 (cl-pushnew (org-element-property :value obj) rtn
6180 :test #'equal))))
6181 rtn))))
6182 (setq org-target-link-regexp
6183 (and targets
6184 (concat before-re
6185 (mapconcat
6186 (lambda (x)
6187 (replace-regexp-in-string
6188 " +" "\\s-+" (regexp-quote x) t t))
6189 targets
6190 "\\|")
6191 after-re)))
6192 (unless (equal old-regexp org-target-link-regexp)
6193 ;; Clean-up cache.
6194 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6195 ((not org-target-link-regexp) old-regexp)
6197 (concat before-re
6198 (mapconcat
6199 (lambda (re)
6200 (substring re (length before-re)
6201 (- (length after-re))))
6202 (list old-regexp org-target-link-regexp)
6203 "\\|")
6204 after-re)))))
6205 (org-with-wide-buffer
6206 (goto-char (point-min))
6207 (while (re-search-forward regexp nil t)
6208 (org-element-cache-refresh (match-beginning 1)))))
6209 ;; Re fontify buffer.
6210 (when (memq 'radio org-highlight-links)
6211 (org-restart-font-lock)))))
6213 (defvar org-latex-and-related-regexp nil
6214 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6216 (defun org-compute-latex-and-related-regexp ()
6217 "Compute regular expression for LaTeX, entities and sub/superscript.
6218 Result depends on variable `org-highlight-latex-and-related'."
6219 (setq-local
6220 org-latex-and-related-regexp
6221 (let* ((re-sub
6222 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6223 ((eq org-use-sub-superscripts '{})
6224 (list org-match-substring-with-braces-regexp))
6225 (org-use-sub-superscripts (list org-match-substring-regexp))))
6226 (re-latex
6227 (when (memq 'latex org-highlight-latex-and-related)
6228 (let ((matchers (plist-get org-format-latex-options :matchers)))
6229 (delq nil
6230 (mapcar (lambda (x)
6231 (and (member (car x) matchers) (nth 1 x)))
6232 org-latex-regexps)))))
6233 (re-entities
6234 (when (memq 'entities org-highlight-latex-and-related)
6235 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6236 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6238 (defun org-do-latex-and-related (limit)
6239 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6240 LIMIT bounds the search for syntax to highlight. Stop at first
6241 highlighted object, if any. Return t if some highlighting was
6242 done, nil otherwise."
6243 (when (org-string-nw-p org-latex-and-related-regexp)
6244 (catch 'found
6245 (while (re-search-forward org-latex-and-related-regexp limit t)
6246 (unless
6247 (cl-some
6248 (lambda (f)
6249 (memq f '(org-code org-verbatim underline org-special-keyword)))
6250 (save-excursion
6251 (goto-char (1+ (match-beginning 0)))
6252 (face-at-point nil t)))
6253 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6254 '(?_ ?^))
6256 0)))
6257 (font-lock-prepend-text-property
6258 (+ offset (match-beginning 0)) (match-end 0)
6259 'face 'org-latex-and-related)
6260 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6261 '(font-lock-multiline t)))
6262 (throw 'found t)))
6263 nil)))
6265 (defun org-restart-font-lock ()
6266 "Restart `font-lock-mode', to force refontification."
6267 (when (and (boundp 'font-lock-mode) font-lock-mode)
6268 (font-lock-mode -1)
6269 (font-lock-mode 1)))
6271 (defun org-activate-tags (limit)
6272 (when (re-search-forward org-tag-line-re limit t)
6273 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6274 (add-text-properties (match-beginning 1) (match-end 1)
6275 (list 'mouse-face 'highlight
6276 'keymap org-mouse-map))
6277 (org-rear-nonsticky-at (match-end 1))
6280 (defun org-outline-level ()
6281 "Compute the outline level of the heading at point.
6283 If this is called at a normal headline, the level is the number
6284 of stars. Use `org-reduced-level' to remove the effect of
6285 `org-odd-levels'. Unlike to `org-current-level', this function
6286 takes into consideration inlinetasks."
6287 (org-with-wide-buffer
6288 (end-of-line)
6289 (if (re-search-backward org-outline-regexp-bol nil t)
6290 (1- (- (match-end 0) (match-beginning 0)))
6291 0)))
6293 (defvar org-font-lock-keywords nil)
6295 (defsubst org-re-property (property &optional literal allow-null value)
6296 "Return a regexp matching a PROPERTY line.
6298 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6299 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6300 non-nil, match properties even without a value.
6302 Match group 3 is set to the value when it exists. If there is no
6303 value and ALLOW-NULL is non-nil, it is set to the empty string.
6305 With optional argument VALUE, match only property lines with
6306 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6307 unless LITERAL is non-nil."
6308 (concat
6309 "^\\(?4:[ \t]*\\)"
6310 (format "\\(?1::\\(?2:%s\\):\\)"
6311 (if literal property (regexp-quote property)))
6312 (cond (value
6313 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6314 (if literal value (regexp-quote value))))
6315 (allow-null
6316 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6318 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6320 (defconst org-property-re
6321 (org-re-property "\\S-+" 'literal t)
6322 "Regular expression matching a property line.
6323 There are four matching groups:
6324 1: :PROPKEY: including the leading and trailing colon,
6325 2: PROPKEY without the leading and trailing colon,
6326 3: PROPVAL without leading or trailing spaces,
6327 4: the indentation of the current line,
6328 5: trailing whitespace.")
6330 (defvar org-font-lock-hook nil
6331 "Functions to be called for special font lock stuff.")
6333 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6335 (defvar org-font-lock-set-keywords-hook nil
6336 "Functions that can manipulate `org-font-lock-extra-keywords'.
6337 This is called after `org-font-lock-extra-keywords' is defined, but before
6338 it is installed to be used by font lock. This can be useful if something
6339 needs to be inserted at a specific position in the font-lock sequence.")
6341 (defun org-font-lock-hook (limit)
6342 "Run `org-font-lock-hook' within LIMIT."
6343 (run-hook-with-args 'org-font-lock-hook limit))
6345 (defun org-set-font-lock-defaults ()
6346 "Set font lock defaults for the current buffer."
6347 (let* ((em org-fontify-emphasized-text)
6348 (lk org-highlight-links)
6349 (org-font-lock-extra-keywords
6350 (list
6351 ;; Call the hook
6352 '(org-font-lock-hook)
6353 ;; Headlines
6354 `(,(if org-fontify-whole-heading-line
6355 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6356 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6357 (1 (org-get-level-face 1))
6358 (2 (org-get-level-face 2))
6359 (3 (org-get-level-face 3)))
6360 ;; Table lines
6361 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6362 (1 'org-table t))
6363 ;; Table internals
6364 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6365 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6366 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6367 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6368 ;; Drawers
6369 '(org-fontify-drawers)
6370 ;; Properties
6371 (list org-property-re
6372 '(1 'org-special-keyword t)
6373 '(3 'org-property-value t))
6374 ;; Link related fontification.
6375 '(org-activate-links)
6376 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6377 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6378 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6379 (when (memq 'footnote lk) '(org-activate-footnote-links))
6380 ;; Targets.
6381 (list org-any-target-regexp '(0 'org-target t))
6382 ;; Diary sexps.
6383 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6384 ;; Macro
6385 '(org-fontify-macros)
6386 ;; TODO keyword
6387 (list (format org-heading-keyword-regexp-format
6388 org-todo-regexp)
6389 '(2 (org-get-todo-face 2) t))
6390 ;; DONE
6391 (if org-fontify-done-headline
6392 (list (format org-heading-keyword-regexp-format
6393 (concat
6394 "\\(?:"
6395 (mapconcat 'regexp-quote org-done-keywords "\\|")
6396 "\\)"))
6397 '(2 'org-headline-done t))
6398 nil)
6399 ;; Priorities
6400 '(org-font-lock-add-priority-faces)
6401 ;; Tags
6402 '(org-font-lock-add-tag-faces)
6403 ;; Tags groups
6404 (when (and org-group-tags org-tag-groups-alist)
6405 (list (concat org-outline-regexp-bol ".+\\(:"
6406 (regexp-opt (mapcar 'car org-tag-groups-alist))
6407 ":\\).*$")
6408 '(1 'org-tag-group prepend)))
6409 ;; Special keywords
6410 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6411 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6412 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6413 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6414 ;; Emphasis
6415 (when em '(org-do-emphasis-faces))
6416 ;; Checkboxes
6417 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6418 1 'org-checkbox prepend)
6419 (when (cdr (assq 'checkbox org-list-automatic-rules))
6420 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6421 (0 (org-get-checkbox-statistics-face) t)))
6422 ;; Description list items
6423 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6424 1 'org-list-dt prepend)
6425 ;; ARCHIVEd headings
6426 (list (concat
6427 org-outline-regexp-bol
6428 "\\(.*:" org-archive-tag ":.*\\)")
6429 '(1 'org-archived prepend))
6430 ;; Specials
6431 '(org-do-latex-and-related)
6432 '(org-fontify-entities)
6433 '(org-raise-scripts)
6434 ;; Code
6435 '(org-activate-code (1 'org-code t))
6436 ;; COMMENT
6437 (list (format
6438 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6439 org-todo-regexp
6440 org-comment-string)
6441 '(9 'org-special-keyword t))
6442 ;; Blocks and meta lines
6443 '(org-fontify-meta-lines-and-blocks))))
6444 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6445 (run-hooks 'org-font-lock-set-keywords-hook)
6446 ;; Now set the full font-lock-keywords
6447 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6448 (setq-local font-lock-defaults
6449 '(org-font-lock-keywords t nil nil backward-paragraph))
6450 (kill-local-variable 'font-lock-keywords)
6451 nil))
6453 (defun org-toggle-pretty-entities ()
6454 "Toggle the composition display of entities as UTF8 characters."
6455 (interactive)
6456 (setq-local org-pretty-entities (not org-pretty-entities))
6457 (org-restart-font-lock)
6458 (if org-pretty-entities
6459 (message "Entities are now displayed as UTF8 characters")
6460 (save-restriction
6461 (widen)
6462 (decompose-region (point-min) (point-max))
6463 (message "Entities are now displayed as plain text"))))
6465 (defvar-local org-custom-properties-overlays nil
6466 "List of overlays used for custom properties.")
6468 (defun org-toggle-custom-properties-visibility ()
6469 "Display or hide properties in `org-custom-properties'."
6470 (interactive)
6471 (if org-custom-properties-overlays
6472 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6473 (setq org-custom-properties-overlays nil))
6474 (when org-custom-properties
6475 (org-with-wide-buffer
6476 (goto-char (point-min))
6477 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6478 (while (re-search-forward regexp nil t)
6479 (let ((end (cdr (save-match-data (org-get-property-block)))))
6480 (when (and end (< (point) end))
6481 ;; Hide first custom property in current drawer.
6482 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6483 (overlay-put o 'invisible t)
6484 (overlay-put o 'org-custom-property t)
6485 (push o org-custom-properties-overlays))
6486 ;; Hide additional custom properties in the same drawer.
6487 (while (re-search-forward regexp end t)
6488 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6489 (overlay-put o 'invisible t)
6490 (overlay-put o 'org-custom-property t)
6491 (push o org-custom-properties-overlays)))))
6492 ;; Each entry is limited to a single property drawer.
6493 (outline-next-heading)))))))
6495 (defun org-fontify-entities (limit)
6496 "Find an entity to fontify."
6497 (let (ee)
6498 (when org-pretty-entities
6499 (catch 'match
6500 ;; "\_ "-family is left out on purpose. Only the first one,
6501 ;; i.e., "\_ ", could be fontified anyway, and it would be
6502 ;; confusing when adding a second white space character.
6503 (while (re-search-forward
6504 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6505 limit t)
6506 (when (and (not (org-at-comment-p))
6507 (setq ee (org-entity-get (match-string 1)))
6508 (= (length (nth 6 ee)) 1))
6509 (let* ((end (if (equal (match-string 2) "{}")
6510 (match-end 2)
6511 (match-end 1))))
6512 (add-text-properties
6513 (match-beginning 0) end
6514 (list 'font-lock-fontified t))
6515 (compose-region (match-beginning 0) end
6516 (nth 6 ee) nil)
6517 (backward-char 1)
6518 (throw 'match t))))
6519 nil))))
6521 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6522 "Fontify string S like in Org mode."
6523 (with-temp-buffer
6524 (insert s)
6525 (let ((org-odd-levels-only odd-levels))
6526 (org-mode)
6527 (org-font-lock-ensure)
6528 (buffer-string))))
6530 (defvar org-m nil)
6531 (defvar org-l nil)
6532 (defvar org-f nil)
6533 (defun org-get-level-face (n)
6534 "Get the right face for match N in font-lock matching of headlines."
6535 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6536 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6537 (if org-cycle-level-faces
6538 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6539 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6540 (cond
6541 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6542 ((eq n 2) org-f)
6543 (t (unless org-level-color-stars-only org-f))))
6545 (defun org-face-from-face-or-color (context inherit face-or-color)
6546 "Create a face list that inherits INHERIT, but sets the foreground color.
6547 When FACE-OR-COLOR is not a string, just return it."
6548 (if (stringp face-or-color)
6549 (list :inherit inherit
6550 (cdr (assoc context org-faces-easy-properties))
6551 face-or-color)
6552 face-or-color))
6554 (defun org-get-todo-face (kwd)
6555 "Get the right face for a TODO keyword KWD.
6556 If KWD is a number, get the corresponding match group."
6557 (when (numberp kwd) (setq kwd (match-string kwd)))
6558 (or (org-face-from-face-or-color
6559 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6560 (and (member kwd org-done-keywords) 'org-done)
6561 'org-todo))
6563 (defun org-get-priority-face (priority)
6564 "Get the right face for PRIORITY.
6565 PRIORITY is a character."
6566 (or (org-face-from-face-or-color
6567 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6568 'org-priority))
6570 (defun org-get-tag-face (tag)
6571 "Get the right face for TAG.
6572 If TAG is a number, get the corresponding match group."
6573 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6574 (or (org-face-from-face-or-color
6575 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6576 'org-tag)))
6578 (defun org-font-lock-add-priority-faces (limit)
6579 "Add the special priority faces."
6580 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6581 (add-text-properties
6582 (match-beginning 1) (match-end 1)
6583 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6584 'font-lock-fontified t))))
6586 (defun org-font-lock-add-tag-faces (limit)
6587 "Add the special tag faces."
6588 (when (and org-tag-faces org-tags-special-faces-re)
6589 (while (re-search-forward org-tags-special-faces-re limit t)
6590 (add-text-properties (match-beginning 1) (match-end 1)
6591 (list 'face (org-get-tag-face 1)
6592 'font-lock-fontified t))
6593 (backward-char 1))))
6595 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6596 "Remove fontification and activation overlays from links."
6597 (font-lock-default-unfontify-region beg end)
6598 (let* ((buffer-undo-list t)
6599 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6600 (inhibit-modification-hooks t)
6601 deactivate-mark buffer-file-name buffer-file-truename)
6602 (decompose-region beg end)
6603 (remove-text-properties beg end
6604 '(mouse-face t keymap t org-linked-text t
6605 invisible t intangible t
6606 org-emphasis t))
6607 (org-remove-font-lock-display-properties beg end)))
6609 (defconst org-script-display '(((raise -0.3) (height 0.7))
6610 ((raise 0.3) (height 0.7))
6611 ((raise -0.5))
6612 ((raise 0.5)))
6613 "Display properties for showing superscripts and subscripts.")
6615 (defun org-remove-font-lock-display-properties (beg end)
6616 "Remove specific display properties that have been added by font lock.
6617 The will remove the raise properties that are used to show superscripts
6618 and subscripts."
6619 (let (next prop)
6620 (while (< beg end)
6621 (setq next (next-single-property-change beg 'display nil end)
6622 prop (get-text-property beg 'display))
6623 (when (member prop org-script-display)
6624 (put-text-property beg next 'display nil))
6625 (setq beg next))))
6627 (defun org-raise-scripts (limit)
6628 "Add raise properties to sub/superscripts."
6629 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6630 (re-search-forward
6631 (if (eq org-use-sub-superscripts t)
6632 org-match-substring-regexp
6633 org-match-substring-with-braces-regexp)
6634 limit t))
6635 (let* ((pos (point)) table-p comment-p
6636 (mpos (match-beginning 3))
6637 (emph-p (get-text-property mpos 'org-emphasis))
6638 (link-p (get-text-property mpos 'mouse-face))
6639 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6640 (goto-char (point-at-bol))
6641 (setq table-p (looking-at-p org-table-dataline-regexp)
6642 comment-p (looking-at-p "^[ \t]*#[ +]"))
6643 (goto-char pos)
6644 ;; Handle a_b^c
6645 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6646 (unless (or comment-p emph-p link-p keyw-p)
6647 (put-text-property (match-beginning 3) (match-end 0)
6648 'display
6649 (if (equal (char-after (match-beginning 2)) ?^)
6650 (nth (if table-p 3 1) org-script-display)
6651 (nth (if table-p 2 0) org-script-display)))
6652 (add-text-properties (match-beginning 2) (match-end 2)
6653 (list 'invisible t))
6654 (when (and (eq (char-after (match-beginning 3)) ?{)
6655 (eq (char-before (match-end 3)) ?}))
6656 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6657 (list 'invisible t))
6658 (add-text-properties (1- (match-end 3)) (match-end 3)
6659 (list 'invisible t))))
6660 t)))
6662 (defun org-remove-empty-overlays-at (pos)
6663 "Remove outline overlays that do not contain non-white stuff."
6664 (dolist (o (overlays-at pos))
6665 (and (eq 'outline (overlay-get o 'invisible))
6666 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6667 (overlay-end o))))
6668 (delete-overlay o))))
6670 (defun org-show-empty-lines-in-parent ()
6671 "Move to the parent and re-show empty lines before visible headlines."
6672 (save-excursion
6673 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6674 (org-cycle-show-empty-lines context))))
6676 (defun org-files-list ()
6677 "Return `org-agenda-files' list, plus all open Org files.
6678 This is useful for operations that need to scan all of a user's
6679 open and agenda-wise Org files."
6680 (let ((files (mapcar #'expand-file-name (org-agenda-files))))
6681 (dolist (buf (buffer-list))
6682 (with-current-buffer buf
6683 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
6684 (cl-pushnew (expand-file-name (buffer-file-name)) files
6685 :test #'equal))))
6686 files))
6688 (defsubst org-entry-beginning-position ()
6689 "Return the beginning position of the current entry."
6690 (save-excursion (org-back-to-heading t) (point)))
6692 (defsubst org-entry-end-position ()
6693 "Return the end position of the current entry."
6694 (save-excursion (outline-next-heading) (point)))
6696 (defun org-subtree-end-visible-p ()
6697 "Is the end of the current subtree visible?"
6698 (pos-visible-in-window-p
6699 (save-excursion (org-end-of-subtree t) (point))))
6701 (defun org-first-headline-recenter ()
6702 "Move cursor to the first headline and recenter the headline."
6703 (let ((window (get-buffer-window)))
6704 (when window
6705 (goto-char (point-min))
6706 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6707 (set-window-start window (line-beginning-position))))))
6710 ;;; Visibility (headlines, blocks, drawers)
6712 ;;;; Headlines visibility
6714 (defun org-show-entry ()
6715 "Show the body directly following this heading.
6716 Show the heading too, if it is currently invisible."
6717 (interactive)
6718 (save-excursion
6719 (ignore-errors
6720 (org-back-to-heading t)
6721 (org-flag-region
6722 (line-end-position 0)
6723 (save-excursion
6724 (if (re-search-forward
6725 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
6726 (match-beginning 1)
6727 (point-max)))
6729 'outline))))
6731 (defun org-show-children (&optional level)
6732 "Show all direct subheadings of this heading.
6733 Prefix arg LEVEL is how many levels below the current level
6734 should be shown. Default is enough to cause the following
6735 heading to appear."
6736 (interactive "p")
6737 (save-excursion
6738 (org-back-to-heading t)
6739 (let* ((current-level (funcall outline-level))
6740 (max-level (org-get-valid-level
6741 current-level
6742 (if level (prefix-numeric-value level) 1)))
6743 (end (save-excursion (org-end-of-subtree t t)))
6744 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
6745 (past-first-child nil)
6746 ;; Make sure to skip inlinetasks.
6747 (re (format regexp-fmt
6748 current-level
6749 (cond
6750 ((not (featurep 'org-inlinetask)) "")
6751 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
6753 (t (1- org-inlinetask-min-level))))))
6754 ;; Display parent heading.
6755 (org-flag-heading nil)
6756 (forward-line)
6757 ;; Display children. First child may be deeper than expected
6758 ;; MAX-LEVEL. Since we want to display it anyway, adjust
6759 ;; MAX-LEVEL accordingly.
6760 (while (re-search-forward re end t)
6761 (unless past-first-child
6762 (setq re (format regexp-fmt
6763 current-level
6764 (max (funcall outline-level) max-level)))
6765 (setq past-first-child t))
6766 (org-flag-heading nil)))))
6768 (defun org-show-subtree ()
6769 "Show everything after this heading at deeper levels."
6770 (interactive)
6771 (org-flag-region
6772 (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
6774 ;;;; Blocks visibility
6776 (defun org-hide-block-toggle-maybe ()
6777 "Toggle visibility of block at point.
6778 Unlike to `org-hide-block-toggle', this function does not throw
6779 an error. Return a non-nil value when toggling is successful."
6780 (interactive)
6781 (ignore-errors (org-hide-block-toggle)))
6783 (defun org-hide-block-toggle (&optional force)
6784 "Toggle the visibility of the current block.
6785 When optional argument FORCE is `off', make block visible. If it
6786 is non-nil, hide it unconditionally. Throw an error when not at
6787 a block. Return a non-nil value when toggling is successful."
6788 (interactive)
6789 (let ((element (org-element-at-point)))
6790 (unless (memq (org-element-type element)
6791 '(center-block comment-block dynamic-block example-block
6792 export-block quote-block special-block
6793 src-block verse-block))
6794 (user-error "Not at a block"))
6795 (let* ((post (org-element-property :post-affiliated element))
6796 (start (save-excursion
6797 (goto-char post)
6798 (line-end-position)))
6799 (end (save-excursion
6800 (goto-char (org-element-property :end element))
6801 (skip-chars-backward " \t\n")
6802 (line-end-position))))
6803 ;; Do nothing when not before or at the block opening line or at
6804 ;; the block closing line.
6805 (unless (let ((eol (line-end-position))) (and (> eol start) (/= eol end)))
6806 (cond ((eq force 'off)
6807 (org-flag-region start end nil 'org-hide-block))
6808 (force
6809 (org-flag-region start end t 'org-hide-block))
6810 ((eq (get-char-property start 'invisible) 'org-hide-block)
6811 (org-flag-region start end nil 'org-hide-block))
6813 (org-flag-region start end t 'org-hide-block)))
6814 ;; When the block is hidden away, make sure point is left in
6815 ;; a visible part of the buffer.
6816 (when (invisible-p (max (1- (point)) (point-min)))
6817 (goto-char post))
6818 ;; Signal success.
6819 t))))
6821 (defun org-hide-block-toggle-all ()
6822 "Toggle the visibility of all blocks in the current buffer."
6823 (org-block-map 'org-hide-block-toggle))
6825 (defun org-hide-block-all ()
6826 "Fold all blocks in the current buffer."
6827 (interactive)
6828 (org-show-all '(blocks))
6829 (org-block-map 'org-hide-block-toggle-maybe))
6831 ;;;; Drawers visibility
6833 (defun org-cycle-hide-drawers (state &optional exceptions)
6834 "Re-hide all drawers after a visibility state change.
6835 STATE should be one of the symbols listed in the docstring of
6836 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
6837 a list of strings specifying which drawers should not be hidden."
6838 (when (and (derived-mode-p 'org-mode)
6839 (not (memq state '(overview folded contents))))
6840 (save-excursion
6841 (let* ((globalp (eq state 'all))
6842 (beg (if globalp (point-min) (point)))
6843 (end (if globalp (point-max)
6844 (if (eq state 'children)
6845 (save-excursion (outline-next-heading) (point))
6846 (org-end-of-subtree t)))))
6847 (goto-char beg)
6848 (while (re-search-forward org-drawer-regexp (max end (point)) t)
6849 (unless (member-ignore-case (match-string 1) exceptions)
6850 (let ((drawer (org-element-at-point)))
6851 (when (memq (org-element-type drawer) '(drawer property-drawer))
6852 (org-flag-drawer t drawer)
6853 ;; Make sure to skip drawer entirely or we might flag
6854 ;; it another time when matching its ending line with
6855 ;; `org-drawer-regexp'.
6856 (goto-char (org-element-property :end drawer))))))))))
6858 (defun org-flag-drawer (flag &optional element)
6859 "When FLAG is non-nil, hide the drawer we are at.
6860 Otherwise make it visible. When optional argument ELEMENT is
6861 a parsed drawer, as returned by `org-element-at-point', hide or
6862 show that drawer instead."
6863 (let ((drawer (or element
6864 (and (save-excursion
6865 (beginning-of-line)
6866 (looking-at-p org-drawer-regexp))
6867 (org-element-at-point)))))
6868 (when (memq (org-element-type drawer) '(drawer property-drawer))
6869 (let ((post (org-element-property :post-affiliated drawer)))
6870 (org-flag-region
6871 (save-excursion (goto-char post) (line-end-position))
6872 (save-excursion (goto-char (org-element-property :end drawer))
6873 (skip-chars-backward " \t\n")
6874 (line-end-position))
6875 flag 'org-hide-drawer)
6876 ;; When the drawer is hidden away, make sure point lies in
6877 ;; a visible part of the buffer.
6878 (when (invisible-p (max (1- (point)) (point-min)))
6879 (goto-char post))))))
6881 ;;;; Visibility cycling
6883 (defvar-local org-cycle-global-status nil)
6884 (put 'org-cycle-global-status 'org-state t)
6885 (defvar-local org-cycle-subtree-status nil)
6886 (put 'org-cycle-subtree-status 'org-state t)
6888 (defun org-show-all (&optional types)
6889 "Show all contents in the visible part of the buffer.
6890 By default, the function expands headings, blocks and drawers.
6891 When optional argument TYPE is a list of symbols among `blocks',
6892 `drawers' and `headings', to only expand one specific type."
6893 (dolist (type (or types '(blocks drawers headings)))
6894 (org-flag-region (point-min) (point-max) nil
6895 (pcase type
6896 (`blocks 'org-hide-block)
6897 (`drawers 'org-hide-drawer)
6898 (`headings 'outline)
6899 (_ (error "Invalid type: %S" type))))))
6901 ;;;###autoload
6902 (defun org-cycle (&optional arg)
6903 "TAB-action and visibility cycling for Org mode.
6905 This is the command invoked in Org mode by the `TAB' key. Its main
6906 purpose is outline visibility cycling, but it also invokes other actions
6907 in special contexts.
6909 When this function is called with a `\\[universal-argument]' prefix, rotate \
6910 the entire
6911 buffer through 3 states (global cycling)
6912 1. OVERVIEW: Show only top-level headlines.
6913 2. CONTENTS: Show all headlines of all levels, but no body text.
6914 3. SHOW ALL: Show everything.
6916 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6917 switch to the startup visibility,
6918 determined by the variable `org-startup-folded', and by any VISIBILITY
6919 properties in the buffer.
6921 With a `\\[universal-argument] \\[universal-argument] \
6922 \\[universal-argument]' prefix argument, show the entire buffer, including
6923 any drawers.
6925 When inside a table, re-align the table and move to the next field.
6927 When point is at the beginning of a headline, rotate the subtree started
6928 by this line through 3 different states (local cycling)
6929 1. FOLDED: Only the main headline is shown.
6930 2. CHILDREN: The main headline and the direct children are shown.
6931 From this state, you can move to one of the children
6932 and zoom in further.
6933 3. SUBTREE: Show the entire subtree, including body text.
6934 If there is no subtree, switch directly from CHILDREN to FOLDED.
6936 When point is at the beginning of an empty headline and the variable
6937 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6938 of the headline by demoting and promoting it to likely levels. This
6939 speeds up creation document structure by pressing `TAB' once or several
6940 times right after creating a new headline.
6942 When there is a numeric prefix, go up to a heading with level ARG, do
6943 a `show-subtree' and return to the previous cursor position. If ARG
6944 is negative, go up that many levels.
6946 When point is not at the beginning of a headline, execute the global
6947 binding for `TAB', which is re-indenting the line. See the option
6948 `org-cycle-emulate-tab' for details.
6950 As a special case, if point is at the beginning of the buffer and there is
6951 no headline in line 1, this function will act as if called with prefix arg
6952 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6953 prefix arg, but only
6954 if the variable `org-cycle-global-at-bob' is t."
6955 (interactive "P")
6956 (org-load-modules-maybe)
6957 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6958 (and org-cycle-level-after-item/entry-creation
6959 (or (org-cycle-level)
6960 (org-cycle-item-indentation))))
6961 (let* ((limit-level
6962 (or org-cycle-max-level
6963 (and (boundp 'org-inlinetask-min-level)
6964 org-inlinetask-min-level
6965 (1- org-inlinetask-min-level))))
6966 (nstars (and limit-level
6967 (if org-odd-levels-only
6968 (and limit-level (1- (* limit-level 2)))
6969 limit-level)))
6970 (org-outline-regexp
6971 (if (not (derived-mode-p 'org-mode))
6972 outline-regexp
6973 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6974 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6975 (not (looking-at org-outline-regexp))))
6976 (org-cycle-hook
6977 (if bob-special
6978 (delq 'org-optimize-window-after-visibility-change
6979 (copy-sequence org-cycle-hook))
6980 org-cycle-hook))
6981 (pos (point)))
6983 (cond
6985 ((equal arg '(16))
6986 (setq last-command 'dummy)
6987 (org-set-startup-visibility)
6988 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6990 ((equal arg '(64))
6991 (org-show-all)
6992 (org-unlogged-message "Entire buffer visible, including drawers"))
6994 ((equal arg '(4)) (org-cycle-internal-global))
6996 ;; Try hiding block at point.
6997 ((org-hide-block-toggle-maybe))
6999 ;; Try cdlatex TAB completion
7000 ((org-try-cdlatex-tab))
7002 ;; Table: enter it or move to the next field.
7003 ((org-at-table-p 'any)
7004 (if (org-at-table.el-p)
7005 (message "%s" (substitute-command-keys "\\<org-mode-map>\
7006 Use `\\[org-edit-special]' to edit table.el tables"))
7007 (if arg (org-table-edit-field t)
7008 (org-table-justify-field-maybe)
7009 (call-interactively 'org-table-next-field))))
7011 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
7013 ;; Global cycling: delegate to `org-cycle-internal-global'.
7014 (bob-special (org-cycle-internal-global))
7016 ;; Drawers: delegate to `org-flag-drawer'.
7017 ((save-excursion
7018 (beginning-of-line 1)
7019 (looking-at org-drawer-regexp))
7020 (org-flag-drawer ; toggle block visibility
7021 (not (get-char-property (match-end 0) 'invisible))))
7023 ;; Show-subtree, ARG levels up from here.
7024 ((integerp arg)
7025 (save-excursion
7026 (org-back-to-heading)
7027 (outline-up-heading (if (< arg 0) (- arg)
7028 (- (funcall outline-level) arg)))
7029 (org-show-subtree)))
7031 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
7032 ((and (featurep 'org-inlinetask)
7033 (org-inlinetask-at-task-p)
7034 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7035 (org-inlinetask-toggle-visibility))
7037 ;; At an item/headline: delegate to `org-cycle-internal-local'.
7038 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
7039 (save-excursion (move-beginning-of-line 1)
7040 (looking-at org-outline-regexp)))
7041 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7042 (org-cycle-internal-local))
7044 ;; From there: TAB emulation and template completion.
7045 (buffer-read-only (org-back-to-heading))
7047 ((run-hook-with-args-until-success
7048 'org-tab-after-check-for-cycling-hook))
7050 ((run-hook-with-args-until-success
7051 'org-tab-before-tab-emulation-hook))
7053 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7054 (or (not (bolp))
7055 (not (looking-at org-outline-regexp))))
7056 (call-interactively (global-key-binding "\t")))
7058 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7059 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7060 (or (and (eq org-cycle-emulate-tab 'white)
7061 (= (match-end 0) (point-at-eol)))
7062 (and (eq org-cycle-emulate-tab 'whitestart)
7063 (>= (match-end 0) pos))))
7065 (eq org-cycle-emulate-tab t))
7066 (call-interactively (global-key-binding "\t")))
7068 (t (save-excursion
7069 (org-back-to-heading)
7070 (org-cycle)))))))
7072 (defun org-cycle-internal-global ()
7073 "Do the global cycling action."
7074 ;; Hack to avoid display of messages for .org attachments in Gnus
7075 (let ((ga (string-match "\\*fontification" (buffer-name))))
7076 (cond
7077 ((and (eq last-command this-command)
7078 (eq org-cycle-global-status 'overview))
7079 ;; We just created the overview - now do table of contents
7080 ;; This can be slow in very large buffers, so indicate action
7081 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7082 (unless ga (org-unlogged-message "CONTENTS..."))
7083 (org-content)
7084 (unless ga (org-unlogged-message "CONTENTS...done"))
7085 (setq org-cycle-global-status 'contents)
7086 (run-hook-with-args 'org-cycle-hook 'contents))
7088 ((and (eq last-command this-command)
7089 (eq org-cycle-global-status 'contents))
7090 ;; We just showed the table of contents - now show everything
7091 (run-hook-with-args 'org-pre-cycle-hook 'all)
7092 (org-show-all '(headings blocks))
7093 (unless ga (org-unlogged-message "SHOW ALL"))
7094 (setq org-cycle-global-status 'all)
7095 (run-hook-with-args 'org-cycle-hook 'all))
7098 ;; Default action: go to overview
7099 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7100 (org-overview)
7101 (unless ga (org-unlogged-message "OVERVIEW"))
7102 (setq org-cycle-global-status 'overview)
7103 (run-hook-with-args 'org-cycle-hook 'overview)))))
7105 (defvar org-called-with-limited-levels nil
7106 "Non-nil when `org-with-limited-levels' is currently active.")
7108 (defun org-cycle-internal-local ()
7109 "Do the local cycling action."
7110 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7111 ;; First, determine end of headline (EOH), end of subtree or item
7112 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7113 (save-excursion
7114 (if (org-at-item-p)
7115 (progn
7116 (beginning-of-line)
7117 (setq struct (org-list-struct))
7118 (setq eoh (point-at-eol))
7119 (setq eos (org-list-get-item-end-before-blank (point) struct))
7120 (setq has-children (org-list-has-child-p (point) struct)))
7121 (org-back-to-heading)
7122 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7123 (setq eos (save-excursion (org-end-of-subtree t t)
7124 (when (bolp) (backward-char)) (point)))
7125 (setq has-children
7126 (or (save-excursion
7127 (let ((level (funcall outline-level)))
7128 (outline-next-heading)
7129 (and (org-at-heading-p t)
7130 (> (funcall outline-level) level))))
7131 (save-excursion
7132 (org-list-search-forward (org-item-beginning-re) eos t)))))
7133 ;; Determine end invisible part of buffer (EOL)
7134 (beginning-of-line 2)
7135 (while (and (not (eobp)) ;This is like `next-line'.
7136 (get-char-property (1- (point)) 'invisible))
7137 (goto-char (next-single-char-property-change (point) 'invisible))
7138 (and (eolp) (beginning-of-line 2)))
7139 (setq eol (point)))
7140 ;; Find out what to do next and set `this-command'
7141 (cond
7142 ((= eos eoh)
7143 ;; Nothing is hidden behind this heading
7144 (unless (org-before-first-heading-p)
7145 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7146 (org-unlogged-message "EMPTY ENTRY")
7147 (setq org-cycle-subtree-status nil)
7148 (save-excursion
7149 (goto-char eos)
7150 (outline-next-heading)
7151 (when (org-invisible-p) (org-flag-heading nil))))
7152 ((and (or (>= eol eos)
7153 (not (string-match "\\S-" (buffer-substring eol eos))))
7154 (or has-children
7155 (not (setq children-skipped
7156 org-cycle-skip-children-state-if-no-children))))
7157 ;; Entire subtree is hidden in one line: children view
7158 (unless (org-before-first-heading-p)
7159 (run-hook-with-args 'org-pre-cycle-hook 'children))
7160 (if (org-at-item-p)
7161 (org-list-set-item-visibility (point-at-bol) struct 'children)
7162 (org-show-entry)
7163 (org-with-limited-levels (org-show-children))
7164 (org-show-set-visibility 'canonical)
7165 ;; Fold every list in subtree to top-level items.
7166 (when (eq org-cycle-include-plain-lists 'integrate)
7167 (save-excursion
7168 (org-back-to-heading)
7169 (while (org-list-search-forward (org-item-beginning-re) eos t)
7170 (beginning-of-line 1)
7171 (let* ((struct (org-list-struct))
7172 (prevs (org-list-prevs-alist struct))
7173 (end (org-list-get-bottom-point struct)))
7174 (dolist (e (org-list-get-all-items (point) struct prevs))
7175 (org-list-set-item-visibility e struct 'folded))
7176 (goto-char (if (< end eos) end eos)))))))
7177 (org-unlogged-message "CHILDREN")
7178 (save-excursion
7179 (goto-char eos)
7180 (outline-next-heading)
7181 (when (org-invisible-p) (org-flag-heading nil)))
7182 (setq org-cycle-subtree-status 'children)
7183 (unless (org-before-first-heading-p)
7184 (run-hook-with-args 'org-cycle-hook 'children)))
7185 ((or children-skipped
7186 (and (eq last-command this-command)
7187 (eq org-cycle-subtree-status 'children)))
7188 ;; We just showed the children, or no children are there,
7189 ;; now show everything.
7190 (unless (org-before-first-heading-p)
7191 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7192 (org-flag-region eoh eos nil 'outline)
7193 (org-unlogged-message
7194 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7195 (setq org-cycle-subtree-status 'subtree)
7196 (unless (org-before-first-heading-p)
7197 (run-hook-with-args 'org-cycle-hook 'subtree)))
7199 ;; Default action: hide the subtree.
7200 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7201 (org-flag-region eoh eos t 'outline)
7202 (org-unlogged-message "FOLDED")
7203 (setq org-cycle-subtree-status 'folded)
7204 (unless (org-before-first-heading-p)
7205 (run-hook-with-args 'org-cycle-hook 'folded))))))
7207 ;;;###autoload
7208 (defun org-global-cycle (&optional arg)
7209 "Cycle the global visibility. For details see `org-cycle'.
7210 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7211 With a numeric prefix, show all headlines up to that level."
7212 (interactive "P")
7213 (let ((org-cycle-include-plain-lists
7214 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7215 (cond
7216 ((integerp arg)
7217 (org-show-all '(headings blocks))
7218 (outline-hide-sublevels arg)
7219 (setq org-cycle-global-status 'contents))
7220 ((equal arg '(4))
7221 (org-set-startup-visibility)
7222 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7224 (org-cycle '(4))))))
7226 (defun org-set-startup-visibility ()
7227 "Set the visibility required by startup options and properties."
7228 (cond
7229 ((eq org-startup-folded t)
7230 (org-overview))
7231 ((eq org-startup-folded 'content)
7232 (org-content))
7233 ((or (eq org-startup-folded 'showeverything)
7234 (eq org-startup-folded nil))
7235 (org-show-all)))
7236 (unless (eq org-startup-folded 'showeverything)
7237 (when org-hide-block-startup (org-hide-block-all))
7238 (org-set-visibility-according-to-property)
7239 (org-cycle-hide-archived-subtrees 'all)
7240 (org-cycle-hide-drawers 'all)
7241 (org-cycle-show-empty-lines t)))
7243 (defun org-set-visibility-according-to-property ()
7244 "Switch subtree visibilities according to :VISIBILITY: property."
7245 (interactive)
7246 (org-with-wide-buffer
7247 (goto-char (point-min))
7248 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7249 (if (not (org-at-property-p)) (outline-next-heading)
7250 (let ((state (match-string 3)))
7251 (save-excursion
7252 (org-back-to-heading t)
7253 (outline-hide-subtree)
7254 (org-reveal)
7255 (cond
7256 ((equal state "folded")
7257 (outline-hide-subtree))
7258 ((equal state "children")
7259 (org-show-hidden-entry)
7260 (org-show-children))
7261 ((equal state "content")
7262 (save-excursion
7263 (save-restriction
7264 (org-narrow-to-subtree)
7265 (org-content))))
7266 ((member state '("all" "showall"))
7267 (outline-show-subtree)))))))))
7269 (defun org-overview ()
7270 "Switch to overview mode, showing only top-level headlines.
7271 This shows all headlines with a level equal or greater than the level
7272 of the first headline in the buffer. This is important, because if the
7273 first headline is not level one, then (hide-sublevels 1) gives confusing
7274 results."
7275 (interactive)
7276 (save-excursion
7277 (let ((level
7278 (save-excursion
7279 (goto-char (point-min))
7280 (when (re-search-forward org-outline-regexp-bol nil t)
7281 (goto-char (match-beginning 0))
7282 (funcall outline-level)))))
7283 (and level (outline-hide-sublevels level)))))
7285 (defun org-content (&optional arg)
7286 "Show all headlines in the buffer, like a table of contents.
7287 With numerical argument N, show content up to level N."
7288 (interactive "P")
7289 (org-overview)
7290 (save-excursion
7291 ;; Visit all headings and show their offspring
7292 (and (integerp arg) (org-overview))
7293 (goto-char (point-max))
7294 (catch 'exit
7295 (while (and (progn (condition-case nil
7296 (outline-previous-visible-heading 1)
7297 (error (goto-char (point-min))))
7299 (looking-at org-outline-regexp))
7300 (if (integerp arg)
7301 (org-show-children (1- arg))
7302 (outline-show-branches))
7303 (when (bobp) (throw 'exit nil))))))
7305 (defun org-optimize-window-after-visibility-change (state)
7306 "Adjust the window after a change in outline visibility.
7307 This function is the default value of the hook `org-cycle-hook'."
7308 (when (get-buffer-window (current-buffer))
7309 (cond
7310 ((eq state 'content) nil)
7311 ((eq state 'all) nil)
7312 ((eq state 'folded) nil)
7313 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7314 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7316 (defun org-clean-visibility-after-subtree-move ()
7317 "Fix visibility issues after moving a subtree."
7318 ;; First, find a reasonable region to look at:
7319 ;; Start two siblings above, end three below
7320 (let* ((beg (save-excursion
7321 (and (org-get-last-sibling)
7322 (org-get-last-sibling))
7323 (point)))
7324 (end (save-excursion
7325 (and (org-get-next-sibling)
7326 (org-get-next-sibling)
7327 (org-get-next-sibling))
7328 (if (org-at-heading-p)
7329 (point-at-eol)
7330 (point))))
7331 (level (looking-at "\\*+"))
7332 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7333 (save-excursion
7334 (save-restriction
7335 (narrow-to-region beg end)
7336 (when re
7337 ;; Properly fold already folded siblings
7338 (goto-char (point-min))
7339 (while (re-search-forward re nil t)
7340 (when (and (not (org-invisible-p))
7341 (org-invisible-p (line-end-position)))
7342 (outline-hide-entry))))
7343 (org-cycle-hide-drawers 'all)
7344 (org-cycle-show-empty-lines 'overview)))))
7346 (defun org-cycle-show-empty-lines (state)
7347 "Show empty lines above all visible headlines.
7348 The region to be covered depends on STATE when called through
7349 `org-cycle-hook'. Lisp program can use t for STATE to get the
7350 entire buffer covered. Note that an empty line is only shown if there
7351 are at least `org-cycle-separator-lines' empty lines before the headline."
7352 (when (/= org-cycle-separator-lines 0)
7353 (save-excursion
7354 (let* ((n (abs org-cycle-separator-lines))
7355 (re (cond
7356 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7357 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7358 (t (let ((ns (number-to-string (- n 2))))
7359 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7360 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7361 beg end)
7362 (cond
7363 ((memq state '(overview contents t))
7364 (setq beg (point-min) end (point-max)))
7365 ((memq state '(children folded))
7366 (setq beg (point)
7367 end (progn (org-end-of-subtree t t)
7368 (line-beginning-position 2)))))
7369 (when beg
7370 (goto-char beg)
7371 (while (re-search-forward re end t)
7372 (unless (get-char-property (match-end 1) 'invisible)
7373 (let ((e (match-end 1))
7374 (b (if (>= org-cycle-separator-lines 0)
7375 (match-beginning 1)
7376 (save-excursion
7377 (goto-char (match-beginning 0))
7378 (skip-chars-backward " \t\n")
7379 (line-end-position)))))
7380 (org-flag-region b e nil 'outline))))))))
7381 ;; Never hide empty lines at the end of the file.
7382 (save-excursion
7383 (goto-char (point-max))
7384 (outline-previous-heading)
7385 (outline-end-of-heading)
7386 (when (and (looking-at "[ \t\n]+")
7387 (= (match-end 0) (point-max)))
7388 (org-flag-region (point) (match-end 0) nil 'outline))))
7390 ;;;; Reveal point location
7392 (defun org-show-context (&optional key)
7393 "Make sure point and context are visible.
7394 Optional argument KEY, when non-nil, is a symbol. See
7395 `org-show-context-detail' for allowed values and how much is to
7396 be shown."
7397 (org-show-set-visibility
7398 (cond ((symbolp org-show-context-detail) org-show-context-detail)
7399 ((cdr (assq key org-show-context-detail)))
7400 (t (cdr (assq 'default org-show-context-detail))))))
7402 (defun org-show-set-visibility (detail)
7403 "Set visibility around point according to DETAIL.
7404 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
7405 `tree', `canonical' or t. See `org-show-context-detail' for more
7406 information."
7407 ;; Show current heading and possibly its entry, following headline
7408 ;; or all children.
7409 (if (and (org-at-heading-p) (not (eq detail 'local)))
7410 (org-flag-heading nil)
7411 (org-show-entry)
7412 ;; If point is hidden within a drawer or a block, make sure to
7413 ;; expose it.
7414 (dolist (o (overlays-at (point)))
7415 (when (memq (overlay-get o 'invisible)
7416 '(org-hide-block org-hide-drawer outline))
7417 (delete-overlay o)))
7418 (unless (org-before-first-heading-p)
7419 (org-with-limited-levels
7420 (cl-case detail
7421 ((tree canonical t) (org-show-children))
7422 ((nil minimal ancestors))
7423 (t (save-excursion
7424 (outline-next-heading)
7425 (org-flag-heading nil)))))))
7426 ;; Show all siblings.
7427 (when (eq detail 'lineage) (org-show-siblings))
7428 ;; Show ancestors, possibly with their children.
7429 (when (memq detail '(ancestors lineage tree canonical t))
7430 (save-excursion
7431 (while (org-up-heading-safe)
7432 (org-flag-heading nil)
7433 (when (memq detail '(canonical t)) (org-show-entry))
7434 (when (memq detail '(tree canonical t)) (org-show-children))))))
7436 (defvar org-reveal-start-hook nil
7437 "Hook run before revealing a location.")
7439 (defun org-reveal (&optional siblings)
7440 "Show current entry, hierarchy above it, and the following headline.
7442 This can be used to show a consistent set of context around
7443 locations exposed with `org-show-context'.
7445 With optional argument SIBLINGS, on each level of the hierarchy all
7446 siblings are shown. This repairs the tree structure to what it would
7447 look like when opened with hierarchical calls to `org-cycle'.
7449 With a \\[universal-argument] \\[universal-argument] prefix, \
7450 go to the parent and show the entire tree."
7451 (interactive "P")
7452 (run-hooks 'org-reveal-start-hook)
7453 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
7454 ((equal siblings '(16))
7455 (save-excursion
7456 (when (org-up-heading-safe)
7457 (org-show-subtree)
7458 (run-hook-with-args 'org-cycle-hook 'subtree))))
7459 (t (org-show-set-visibility 'lineage))))
7462 ;;; Indirect buffer display of subtrees
7464 (defvar org-indirect-dedicated-frame nil
7465 "This is the frame being used for indirect tree display.")
7466 (defvar org-last-indirect-buffer nil)
7468 (defun org-tree-to-indirect-buffer (&optional arg)
7469 "Create indirect buffer and narrow it to current subtree.
7471 With a numerical prefix ARG, go up to this level and then take that tree.
7472 If ARG is negative, go up that many levels.
7474 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7475 indirect buffer previously made with this command, to avoid proliferation of
7476 indirect buffers. However, when you call the command with a \
7477 `\\[universal-argument]' prefix, or
7478 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7479 so that you can work with several indirect buffers at the same time. If
7480 `org-indirect-buffer-display' is `dedicated-frame', the \
7481 `\\[universal-argument]' prefix also
7482 requests that a new frame be made for the new buffer, so that the dedicated
7483 frame is not changed."
7484 (interactive "P")
7485 (let ((cbuf (current-buffer))
7486 (cwin (selected-window))
7487 (pos (point))
7488 beg end level heading ibuf)
7489 (save-excursion
7490 (org-back-to-heading t)
7491 (when (numberp arg)
7492 (setq level (org-outline-level))
7493 (when (< arg 0) (setq arg (+ level arg)))
7494 (while (> (setq level (org-outline-level)) arg)
7495 (org-up-heading-safe)))
7496 (setq beg (point)
7497 heading (org-get-heading 'no-tags))
7498 (org-end-of-subtree t t)
7499 (when (org-at-heading-p) (backward-char 1))
7500 (setq end (point)))
7501 (when (and (buffer-live-p org-last-indirect-buffer)
7502 (not (eq org-indirect-buffer-display 'new-frame))
7503 (not arg))
7504 (kill-buffer org-last-indirect-buffer))
7505 (setq ibuf (org-get-indirect-buffer cbuf heading)
7506 org-last-indirect-buffer ibuf)
7507 (cond
7508 ((or (eq org-indirect-buffer-display 'new-frame)
7509 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7510 (select-frame (make-frame))
7511 (delete-other-windows)
7512 (pop-to-buffer-same-window ibuf)
7513 (org-set-frame-title heading))
7514 ((eq org-indirect-buffer-display 'dedicated-frame)
7515 (raise-frame
7516 (select-frame (or (and org-indirect-dedicated-frame
7517 (frame-live-p org-indirect-dedicated-frame)
7518 org-indirect-dedicated-frame)
7519 (setq org-indirect-dedicated-frame (make-frame)))))
7520 (delete-other-windows)
7521 (pop-to-buffer-same-window ibuf)
7522 (org-set-frame-title (concat "Indirect: " heading)))
7523 ((eq org-indirect-buffer-display 'current-window)
7524 (pop-to-buffer-same-window ibuf))
7525 ((eq org-indirect-buffer-display 'other-window)
7526 (pop-to-buffer ibuf))
7527 (t (error "Invalid value")))
7528 (narrow-to-region beg end)
7529 (org-show-all '(headings blocks))
7530 (goto-char pos)
7531 (run-hook-with-args 'org-cycle-hook 'all)
7532 (and (window-live-p cwin) (select-window cwin))))
7534 (defun org-get-indirect-buffer (&optional buffer heading)
7535 (setq buffer (or buffer (current-buffer)))
7536 (let ((n 1) (base (buffer-name buffer)) bname)
7537 (while (buffer-live-p
7538 (get-buffer
7539 (setq bname
7540 (concat base "-"
7541 (if heading (concat heading "-" (number-to-string n))
7542 (number-to-string n))))))
7543 (setq n (1+ n)))
7544 (condition-case nil
7545 (make-indirect-buffer buffer bname 'clone)
7546 (error (make-indirect-buffer buffer bname)))))
7548 (defun org-set-frame-title (title)
7549 "Set the title of the current frame to the string TITLE."
7550 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7552 ;;;; Structure editing
7554 ;;; Inserting headlines
7556 (defun org--line-empty-p (n)
7557 "Is the Nth next line empty?
7559 Counts the current line as N = 1 and the previous line as N = 0;
7560 see `beginning-of-line'."
7561 (save-excursion
7562 (and (not (bobp))
7563 (or (beginning-of-line n) t)
7564 (save-match-data
7565 (looking-at "[ \t]*$")))))
7567 (defun org-previous-line-empty-p ()
7568 "Is the previous line a blank line?
7569 When NEXT is non-nil, check the next line instead."
7570 (org--line-empty-p 0))
7572 (defun org-next-line-empty-p ()
7573 "Is the previous line a blank line?
7574 When NEXT is non-nil, check the next line instead."
7575 (org--line-empty-p 2))
7577 (defun org--blank-before-heading-p (&optional parent)
7578 "Non-nil when an empty line should precede a new heading here.
7579 When optional argument PARENT is non-nil, consider parent
7580 headline instead of current one."
7581 (pcase (assq 'heading org-blank-before-new-entry)
7582 (`(heading . auto)
7583 (save-excursion
7584 (org-with-limited-levels
7585 (unless (and (org-before-first-heading-p)
7586 (not (outline-next-heading)))
7587 (org-back-to-heading t)
7588 (when parent (org-up-heading-safe))
7589 (cond ((not (bobp))
7590 (org-previous-line-empty-p))
7591 ((outline-next-heading)
7592 (org-previous-line-empty-p))
7593 ;; Ignore trailing spaces on last buffer line.
7594 ((progn (skip-chars-backward " \t") (bolp))
7595 (org-previous-line-empty-p))
7596 (t nil))))))
7597 (`(heading . ,value) value)
7598 (_ nil)))
7600 (defun org-insert-heading (&optional arg invisible-ok top)
7601 "Insert a new heading or an item with the same depth at point.
7603 If point is at the beginning of a heading, insert a new heading
7604 or a new headline above the current one. When at the beginning
7605 of a regular line of text, turn it into a heading.
7607 If point is in the middle of a line, split it and create a new
7608 headline with the text in the current line after point (see
7609 `org-M-RET-may-split-line' on how to modify this behavior). As
7610 a special case, on a headline, splitting can only happen on the
7611 title itself. E.g., this excludes breaking stars or tags.
7613 With a `\\[universal-argument]' prefix, set \
7614 `org-insert-heading-respect-content' to
7615 a non-nil value for the duration of the command. This forces the
7616 insertion of a heading after the current subtree, independently
7617 on the location of point.
7619 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7620 insert the heading at the end of the tree
7621 above the current heading. For example, if point is within a
7622 2nd-level heading, then it will insert a 2nd-level heading at
7623 the end of the 1st-level parent subtree.
7625 When INVISIBLE-OK is set, stop at invisible headlines when going
7626 back. This is important for non-interactive uses of the
7627 command.
7629 When optional argument TOP is non-nil, insert a level 1 heading,
7630 unconditionally."
7631 (interactive "P")
7632 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7633 (level (org-current-level))
7634 (stars (make-string (if (and level (not top)) level 1) ?*)))
7635 (cond
7636 ((or org-insert-heading-respect-content
7637 (member arg '((4) (16)))
7638 (and (not invisible-ok)
7639 (invisible-p (max (1- (point)) (point-min)))))
7640 ;; Position point at the location of insertion.
7641 (if (not level) ;before first headline
7642 (org-with-limited-levels (outline-next-heading))
7643 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7644 ;; is nil.
7645 (org-with-limited-levels (org-back-to-heading invisible-ok))
7646 (cond ((equal arg '(16))
7647 (org-up-heading-safe)
7648 (org-end-of-subtree t t))
7650 (org-end-of-subtree t t))))
7651 (unless (bolp) (insert "\n")) ;ensure final newline
7652 (unless (and blank? (org-previous-line-empty-p))
7653 (org-N-empty-lines-before-current (if blank? 1 0)))
7654 (insert stars " \n")
7655 (forward-char -1))
7656 ;; At a headline...
7657 ((org-at-heading-p)
7658 (cond ((bolp)
7659 (when blank? (save-excursion (insert "\n")))
7660 (save-excursion (insert stars " \n"))
7661 (unless (and blank? (org-previous-line-empty-p))
7662 (org-N-empty-lines-before-current (if blank? 1 0)))
7663 (end-of-line))
7664 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7665 (org-match-line org-complex-heading-regexp)
7666 (org-pos-in-match-range (point) 4))
7667 ;; Grab the text that should moved to the new headline.
7668 ;; Preserve tags.
7669 (let ((split (delete-and-extract-region (point) (match-end 4))))
7670 (if (looking-at "[ \t]*$") (replace-match "")
7671 (org-align-tags))
7672 (end-of-line)
7673 (when blank? (insert "\n"))
7674 (insert "\n" stars " ")
7675 (when (org-string-nw-p split) (insert split))
7676 (when (eobp) (save-excursion (insert "\n")))))
7678 (end-of-line)
7679 (when blank? (insert "\n"))
7680 (insert "\n" stars " ")
7681 (when (eobp) (save-excursion (insert "\n"))))))
7682 ;; On regular text, turn line into a headline or split, if
7683 ;; appropriate.
7684 ((bolp)
7685 (insert stars " ")
7686 (unless (and blank? (org-previous-line-empty-p))
7687 (org-N-empty-lines-before-current (if blank? 1 0))))
7689 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7690 (end-of-line))
7691 (insert "\n" stars " ")
7692 (unless (and blank? (org-previous-line-empty-p))
7693 (org-N-empty-lines-before-current (if blank? 1 0))))))
7694 (run-hooks 'org-insert-heading-hook))
7696 (defun org-N-empty-lines-before-current (n)
7697 "Make the number of empty lines before current exactly N.
7698 So this will delete or add empty lines."
7699 (let ((column (current-column)))
7700 (beginning-of-line)
7701 (unless (bobp)
7702 (let ((start (save-excursion
7703 (skip-chars-backward " \r\t\n")
7704 (line-end-position))))
7705 (delete-region start (line-end-position 0))))
7706 (insert (make-string n ?\n))
7707 (move-to-column column)))
7709 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7710 "Return the heading of the current entry, without the stars.
7711 When NO-TAGS is non-nil, don't include tags.
7712 When NO-TODO is non-nil, don't include TODO keywords.
7713 When NO-PRIORITY is non-nil, don't include priority cookie.
7714 When NO-COMMENT is non-nil, don't include COMMENT string.
7715 Return nil before first heading."
7716 (unless (org-before-first-heading-p)
7717 (save-excursion
7718 (org-back-to-heading t)
7719 (let ((case-fold-search nil))
7720 (looking-at org-complex-heading-regexp)
7721 (let ((todo (and (not no-todo) (match-string 2)))
7722 (priority (and (not no-priority) (match-string 3)))
7723 (headline (pcase (match-string 4)
7724 (`nil "")
7725 ((and (guard no-comment) h)
7726 (replace-regexp-in-string
7727 (eval-when-compile
7728 (format "\\`%s[ \t]+" org-comment-string))
7729 "" h))
7730 (h h)))
7731 (tags (and (not no-tags) (match-string 5))))
7732 (mapconcat #'identity
7733 (delq nil (list todo priority headline tags))
7734 " "))))))
7736 (defun org-heading-components ()
7737 "Return the components of the current heading.
7738 This is a list with the following elements:
7739 - the level as an integer
7740 - the reduced level, different if `org-odd-levels-only' is set.
7741 - the TODO keyword, or nil
7742 - the priority character, like ?A, or nil if no priority is given
7743 - the headline text itself, or the tags string if no headline text
7744 - the tags string, or nil."
7745 (save-excursion
7746 (org-back-to-heading t)
7747 (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
7748 (list (length (match-string 1))
7749 (org-reduced-level (length (match-string 1)))
7750 (match-string-no-properties 2)
7751 (and (match-end 3) (aref (match-string 3) 2))
7752 (match-string-no-properties 4)
7753 (match-string-no-properties 5)))))
7755 (defun org-get-entry ()
7756 "Get the entry text, after heading, entire subtree."
7757 (save-excursion
7758 (org-back-to-heading t)
7759 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7761 (defun org-edit-headline (&optional heading)
7762 "Edit the current headline.
7763 Set it to HEADING when provided."
7764 (interactive)
7765 (org-with-wide-buffer
7766 (org-back-to-heading t)
7767 (let ((case-fold-search nil))
7768 (when (looking-at org-complex-heading-regexp)
7769 (let* ((old (match-string-no-properties 4))
7770 (new (save-match-data
7771 (org-trim (or heading (read-string "Edit: " old))))))
7772 (unless (equal old new)
7773 (if old (replace-match new t t nil 4)
7774 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7775 (insert " " new))
7776 (org-align-tags)
7777 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7779 (defun org-insert-heading-after-current ()
7780 "Insert a new heading with same level as current, after current subtree."
7781 (interactive)
7782 (org-back-to-heading)
7783 (org-insert-heading)
7784 (org-move-subtree-down)
7785 (end-of-line 1))
7787 (defun org-insert-heading-respect-content (&optional invisible-ok)
7788 "Insert heading with `org-insert-heading-respect-content' set to t."
7789 (interactive)
7790 (org-insert-heading '(4) invisible-ok))
7792 (defun org-insert-todo-heading-respect-content (&optional force-state)
7793 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7794 (interactive)
7795 (org-insert-todo-heading force-state '(4)))
7797 (defun org-insert-todo-heading (arg &optional force-heading)
7798 "Insert a new heading with the same level and TODO state as current heading.
7800 If the heading has no TODO state, or if the state is DONE, use
7801 the first state (TODO by default). Also with one prefix arg,
7802 force first state. With two prefix args, force inserting at the
7803 end of the parent subtree.
7805 When called at a plain list item, insert a new item with an
7806 unchecked check box."
7807 (interactive "P")
7808 (when (or force-heading (not (org-insert-item 'checkbox)))
7809 (org-insert-heading (or (and (equal arg '(16)) '(16))
7810 force-heading))
7811 (save-excursion
7812 (org-forward-heading-same-level -1)
7813 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7814 (let* ((new-mark-x
7815 (if (or (equal arg '(4))
7816 (not (match-beginning 2))
7817 (member (match-string 2) org-done-keywords))
7818 (car org-todo-keywords-1)
7819 (match-string 2)))
7820 (new-mark
7822 (run-hook-with-args-until-success
7823 'org-todo-get-default-hook new-mark-x nil)
7824 new-mark-x)))
7825 (beginning-of-line 1)
7826 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7827 (if org-treat-insert-todo-heading-as-state-change
7828 (org-todo new-mark)
7829 (insert new-mark " "))))
7830 (when org-provide-todo-statistics
7831 (org-update-parent-todo-statistics))))
7833 (defun org-insert-subheading (arg)
7834 "Insert a new subheading and demote it.
7835 Works for outline headings and for plain lists alike."
7836 (interactive "P")
7837 (org-insert-heading arg)
7838 (cond
7839 ((org-at-heading-p) (org-do-demote))
7840 ((org-at-item-p) (org-indent-item))))
7842 (defun org-insert-todo-subheading (arg)
7843 "Insert a new subheading with TODO keyword or checkbox and demote it.
7844 Works for outline headings and for plain lists alike."
7845 (interactive "P")
7846 (org-insert-todo-heading arg)
7847 (cond
7848 ((org-at-heading-p) (org-do-demote))
7849 ((org-at-item-p) (org-indent-item))))
7851 ;;; Promotion and Demotion
7853 (defvar org-after-demote-entry-hook nil
7854 "Hook run after an entry has been demoted.
7855 The cursor will be at the beginning of the entry.
7856 When a subtree is being demoted, the hook will be called for each node.")
7858 (defvar org-after-promote-entry-hook nil
7859 "Hook run after an entry has been promoted.
7860 The cursor will be at the beginning of the entry.
7861 When a subtree is being promoted, the hook will be called for each node.")
7863 (defun org-promote-subtree ()
7864 "Promote the entire subtree.
7865 See also `org-promote'."
7866 (interactive)
7867 (save-excursion
7868 (org-with-limited-levels (org-map-tree 'org-promote)))
7869 (org-fix-position-after-promote))
7871 (defun org-demote-subtree ()
7872 "Demote the entire subtree.
7873 See `org-demote' and `org-promote'."
7874 (interactive)
7875 (save-excursion
7876 (org-with-limited-levels (org-map-tree 'org-demote)))
7877 (org-fix-position-after-promote))
7879 (defun org-do-promote ()
7880 "Promote the current heading higher up the tree.
7881 If the region is active in `transient-mark-mode', promote all
7882 headings in the region."
7883 (interactive)
7884 (save-excursion
7885 (if (org-region-active-p)
7886 (org-map-region 'org-promote (region-beginning) (region-end))
7887 (org-promote)))
7888 (org-fix-position-after-promote))
7890 (defun org-do-demote ()
7891 "Demote the current heading lower down the tree.
7892 If the region is active in `transient-mark-mode', demote all
7893 headings in the region."
7894 (interactive)
7895 (save-excursion
7896 (if (org-region-active-p)
7897 (org-map-region 'org-demote (region-beginning) (region-end))
7898 (org-demote)))
7899 (org-fix-position-after-promote))
7901 (defun org-fix-position-after-promote ()
7902 "Fix cursor position and indentation after demoting/promoting."
7903 (let ((pos (point)))
7904 (when (save-excursion
7905 (beginning-of-line)
7906 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
7907 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
7908 (cond ((eobp) (insert " "))
7909 ((eolp) (insert " "))
7910 ((equal (char-after) ?\s) (forward-char 1))))))
7912 (defun org-current-level ()
7913 "Return the level of the current entry, or nil if before the first headline.
7914 The level is the number of stars at the beginning of the
7915 headline. Use `org-reduced-level' to remove the effect of
7916 `org-odd-levels'. Unlike to `org-outline-level', this function
7917 ignores inlinetasks."
7918 (let ((level (org-with-limited-levels (org-outline-level))))
7919 (and (> level 0) level)))
7921 (defun org-get-previous-line-level ()
7922 "Return the outline depth of the last headline before the current line.
7923 Returns 0 for the first headline in the buffer, and nil if before the
7924 first headline."
7925 (and (org-current-level)
7926 (or (and (/= (line-beginning-position) (point-min))
7927 (save-excursion (beginning-of-line 0) (org-current-level)))
7928 0)))
7930 (defun org-reduced-level (l)
7931 "Compute the effective level of a heading.
7932 This takes into account the setting of `org-odd-levels-only'."
7933 (cond
7934 ((zerop l) 0)
7935 (org-odd-levels-only (1+ (floor (/ l 2))))
7936 (t l)))
7938 (defun org-level-increment ()
7939 "Return the number of stars that will be added or removed at a
7940 time to headlines when structure editing, based on the value of
7941 `org-odd-levels-only'."
7942 (if org-odd-levels-only 2 1))
7944 (defun org-get-valid-level (level &optional change)
7945 "Rectify a level change under the influence of `org-odd-levels-only'.
7946 LEVEL is a current level, CHANGE is by how much the level should
7947 be modified. Even if CHANGE is nil, LEVEL may be returned
7948 modified because even level numbers will become the next higher
7949 odd number. Returns values greater than 0."
7950 (if org-odd-levels-only
7951 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7952 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
7953 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7954 (max 1 (+ level (or change 0)))))
7956 (defun org-promote ()
7957 "Promote the current heading higher up the tree."
7958 (org-with-wide-buffer
7959 (org-back-to-heading t)
7960 (let* ((after-change-functions (remq 'flyspell-after-change-function
7961 after-change-functions))
7962 (level (save-match-data (funcall outline-level)))
7963 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7964 (diff (abs (- level (length up-head) -1))))
7965 (cond
7966 ((and (= level 1) org-allow-promoting-top-level-subtree)
7967 (replace-match "# " nil t))
7968 ((= level 1)
7969 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7970 (t (replace-match up-head nil t)))
7971 (unless (= level 1)
7972 (when org-auto-align-tags (org-align-tags))
7973 (when org-adapt-indentation (org-fixup-indentation (- diff))))
7974 (run-hooks 'org-after-promote-entry-hook))))
7976 (defun org-demote ()
7977 "Demote the current heading lower down the tree."
7978 (org-with-wide-buffer
7979 (org-back-to-heading t)
7980 (let* ((after-change-functions (remq 'flyspell-after-change-function
7981 after-change-functions))
7982 (level (save-match-data (funcall outline-level)))
7983 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7984 (diff (abs (- level (length down-head) -1))))
7985 (replace-match down-head nil t)
7986 (when org-auto-align-tags (org-align-tags))
7987 (when org-adapt-indentation (org-fixup-indentation diff))
7988 (run-hooks 'org-after-demote-entry-hook))))
7990 (defun org-cycle-level ()
7991 "Cycle the level of an empty headline through possible states.
7992 This goes first to child, then to parent, level, then up the hierarchy.
7993 After top level, it switches back to sibling level."
7994 (interactive)
7995 (let ((org-adapt-indentation nil))
7996 (when (org-point-at-end-of-empty-headline)
7997 (setq this-command 'org-cycle-level) ; Only needed for caching
7998 (let ((cur-level (org-current-level))
7999 (prev-level (org-get-previous-line-level)))
8000 (cond
8001 ;; If first headline in file, promote to top-level.
8002 ((= prev-level 0)
8003 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8004 do (org-do-promote)))
8005 ;; If same level as prev, demote one.
8006 ((= prev-level cur-level)
8007 (org-do-demote))
8008 ;; If parent is top-level, promote to top level if not already.
8009 ((= prev-level 1)
8010 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8011 do (org-do-promote)))
8012 ;; If top-level, return to prev-level.
8013 ((= cur-level 1)
8014 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8015 do (org-do-demote)))
8016 ;; If less than prev-level, promote one.
8017 ((< cur-level prev-level)
8018 (org-do-promote))
8019 ;; If deeper than prev-level, promote until higher than
8020 ;; prev-level.
8021 ((> cur-level prev-level)
8022 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8023 do (org-do-promote))))
8024 t))))
8026 (defun org-map-tree (fun)
8027 "Call FUN for every heading underneath the current one."
8028 (org-back-to-heading t)
8029 (let ((level (funcall outline-level)))
8030 (save-excursion
8031 (funcall fun)
8032 (while (and (progn
8033 (outline-next-heading)
8034 (> (funcall outline-level) level))
8035 (not (eobp)))
8036 (funcall fun)))))
8038 (defun org-map-region (fun beg end)
8039 "Call FUN for every heading between BEG and END."
8040 (let ((org-ignore-region t))
8041 (save-excursion
8042 (setq end (copy-marker end))
8043 (goto-char beg)
8044 (when (and (re-search-forward org-outline-regexp-bol nil t)
8045 (< (point) end))
8046 (funcall fun))
8047 (while (and (progn
8048 (outline-next-heading)
8049 (< (point) end))
8050 (not (eobp)))
8051 (funcall fun)))))
8053 (defun org-fixup-indentation (diff)
8054 "Change the indentation in the current entry by DIFF.
8056 DIFF is an integer. Indentation is done according to the
8057 following rules:
8059 - Planning information and property drawers are always indented
8060 according to the new level of the headline;
8062 - Footnote definitions and their contents are ignored;
8064 - Inlinetasks' boundaries are not shifted;
8066 - Empty lines are ignored;
8068 - Other lines' indentation are shifted by DIFF columns, unless
8069 it would introduce a structural change in the document, in
8070 which case no shifting is done at all.
8072 Assume point is at a heading or an inlinetask beginning."
8073 (org-with-wide-buffer
8074 (narrow-to-region (line-beginning-position)
8075 (save-excursion
8076 (if (org-with-limited-levels (org-at-heading-p))
8077 (org-with-limited-levels (outline-next-heading))
8078 (org-inlinetask-goto-end))
8079 (point)))
8080 (forward-line)
8081 ;; Indent properly planning info and property drawer.
8082 (when (looking-at-p org-planning-line-re)
8083 (org-indent-line)
8084 (forward-line))
8085 (when (looking-at org-property-drawer-re)
8086 (goto-char (match-end 0))
8087 (forward-line)
8088 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8089 (catch 'no-shift
8090 (when (zerop diff) (throw 'no-shift nil))
8091 ;; If DIFF is negative, first check if a shift is possible at all
8092 ;; (e.g., it doesn't break structure). This can only happen if
8093 ;; some contents are not properly indented.
8094 (let ((case-fold-search t))
8095 (when (< diff 0)
8096 (let ((diff (- diff))
8097 (forbidden-re (concat org-outline-regexp
8098 "\\|"
8099 (substring org-footnote-definition-re 1))))
8100 (save-excursion
8101 (while (not (eobp))
8102 (cond
8103 ((looking-at-p "[ \t]*$") (forward-line))
8104 ((and (looking-at-p org-footnote-definition-re)
8105 (let ((e (org-element-at-point)))
8106 (and (eq (org-element-type e) 'footnote-definition)
8107 (goto-char (org-element-property :end e))))))
8108 ((looking-at-p org-outline-regexp) (forward-line))
8109 ;; Give up if shifting would move before column 0 or
8110 ;; if it would introduce a headline or a footnote
8111 ;; definition.
8113 (skip-chars-forward " \t")
8114 (let ((ind (current-column)))
8115 (when (or (< ind diff)
8116 (and (= ind diff) (looking-at-p forbidden-re)))
8117 (throw 'no-shift nil)))
8118 ;; Ignore contents of example blocks and source
8119 ;; blocks if their indentation is meant to be
8120 ;; preserved. Jump to block's closing line.
8121 (beginning-of-line)
8122 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8123 (let ((e (org-element-at-point)))
8124 (and (memq (org-element-type e)
8125 '(example-block src-block))
8126 (or org-src-preserve-indentation
8127 (org-element-property :preserve-indent e))
8128 (goto-char (org-element-property :end e))
8129 (progn (skip-chars-backward " \r\t\n")
8130 (beginning-of-line)
8131 t))))
8132 (forward-line))))))))
8133 ;; Shift lines but footnote definitions, inlinetasks boundaries
8134 ;; by DIFF. Also skip contents of source or example blocks
8135 ;; when indentation is meant to be preserved.
8136 (while (not (eobp))
8137 (cond
8138 ((and (looking-at-p org-footnote-definition-re)
8139 (let ((e (org-element-at-point)))
8140 (and (eq (org-element-type e) 'footnote-definition)
8141 (goto-char (org-element-property :end e))))))
8142 ((looking-at-p org-outline-regexp) (forward-line))
8143 ((looking-at-p "[ \t]*$") (forward-line))
8145 (indent-line-to (+ (current-indentation) diff))
8146 (beginning-of-line)
8147 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8148 (let ((e (org-element-at-point)))
8149 (and (memq (org-element-type e)
8150 '(example-block src-block))
8151 (or org-src-preserve-indentation
8152 (org-element-property :preserve-indent e))
8153 (goto-char (org-element-property :end e))
8154 (progn (skip-chars-backward " \r\t\n")
8155 (beginning-of-line)
8156 t))))
8157 (forward-line)))))))))
8159 (defun org-convert-to-odd-levels ()
8160 "Convert an Org file with all levels allowed to one with odd levels.
8161 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8162 level 5 etc."
8163 (interactive)
8164 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8165 (let ((outline-level 'org-outline-level)
8166 (org-odd-levels-only nil) n)
8167 (save-excursion
8168 (goto-char (point-min))
8169 (while (re-search-forward "^\\*\\*+ " nil t)
8170 (setq n (- (length (match-string 0)) 2))
8171 (while (>= (setq n (1- n)) 0)
8172 (org-demote))
8173 (end-of-line 1))))))
8175 (defun org-convert-to-oddeven-levels ()
8176 "Convert an Org file with only odd levels to one with odd/even levels.
8177 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8178 file contains a section with an even level, conversion would
8179 destroy the structure of the file. An error is signaled in this
8180 case."
8181 (interactive)
8182 (goto-char (point-min))
8183 ;; First check if there are no even levels
8184 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8185 (org-show-set-visibility 'canonical)
8186 (error "Not all levels are odd in this file. Conversion not possible"))
8187 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8188 (let ((outline-regexp org-outline-regexp)
8189 (outline-level 'org-outline-level)
8190 (org-odd-levels-only nil) n)
8191 (save-excursion
8192 (goto-char (point-min))
8193 (while (re-search-forward "^\\*\\*+ " nil t)
8194 (setq n (/ (1- (length (match-string 0))) 2))
8195 (while (>= (setq n (1- n)) 0)
8196 (org-promote))
8197 (end-of-line 1))))))
8199 (defun org-tr-level (n)
8200 "Make N odd if required."
8201 (if org-odd-levels-only (1+ (/ n 2)) n))
8203 ;;; Vertical tree motion, cutting and pasting of subtrees
8205 (defun org-move-subtree-up (&optional arg)
8206 "Move the current subtree up past ARG headlines of the same level."
8207 (interactive "p")
8208 (org-move-subtree-down (- (prefix-numeric-value arg))))
8210 (defun org-move-subtree-down (&optional arg)
8211 "Move the current subtree down past ARG headlines of the same level."
8212 (interactive "p")
8213 (setq arg (prefix-numeric-value arg))
8214 (org-preserve-local-variables
8215 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8216 'org-get-last-sibling))
8217 (ins-point (make-marker))
8218 (cnt (abs arg))
8219 (col (current-column))
8220 beg end txt folded)
8221 ;; Select the tree
8222 (org-back-to-heading)
8223 (setq beg (point))
8224 (save-match-data
8225 (save-excursion (outline-end-of-heading)
8226 (setq folded (org-invisible-p)))
8227 (progn (org-end-of-subtree nil t)
8228 (unless (eobp) (backward-char))))
8229 (outline-next-heading)
8230 (setq end (point))
8231 (goto-char beg)
8232 ;; Find insertion point, with error handling
8233 (while (> cnt 0)
8234 (unless (and (funcall movfunc) (looking-at org-outline-regexp))
8235 (goto-char beg)
8236 (user-error "Cannot move past superior level or buffer limit"))
8237 (setq cnt (1- cnt)))
8238 (when (> arg 0)
8239 ;; Moving forward - still need to move over subtree
8240 (org-end-of-subtree t t)
8241 (save-excursion
8242 (org-back-over-empty-lines)
8243 (or (bolp) (newline))))
8244 (move-marker ins-point (point))
8245 (setq txt (buffer-substring beg end))
8246 (org-save-markers-in-region beg end)
8247 (delete-region beg end)
8248 (org-remove-empty-overlays-at beg)
8249 (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
8250 (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
8251 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8252 (let ((bbb (point)))
8253 (insert-before-markers txt)
8254 (org-reinstall-markers-in-region bbb)
8255 (move-marker ins-point bbb))
8256 (or (bolp) (insert "\n"))
8257 (goto-char ins-point)
8258 (org-skip-whitespace)
8259 (move-marker ins-point nil)
8260 (if folded
8261 (outline-hide-subtree)
8262 (org-show-entry)
8263 (org-show-children))
8264 (org-clean-visibility-after-subtree-move)
8265 ;; move back to the initial column we were at
8266 (move-to-column col))))
8268 (defvar org-subtree-clip ""
8269 "Clipboard for cut and paste of subtrees.
8270 This is actually only a copy of the kill, because we use the normal kill
8271 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8273 (defvar org-subtree-clip-folded nil
8274 "Was the last copied subtree folded?
8275 This is used to fold the tree back after pasting.")
8277 (defun org-cut-subtree (&optional n)
8278 "Cut the current subtree into the clipboard.
8279 With prefix arg N, cut this many sequential subtrees.
8280 This is a short-hand for marking the subtree and then cutting it."
8281 (interactive "p")
8282 (org-copy-subtree n 'cut))
8284 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8285 "Copy the current subtree into the clipboard.
8286 With prefix arg N, copy this many sequential subtrees.
8287 This is a short-hand for marking the subtree and then copying it.
8288 If CUT is non-nil, actually cut the subtree.
8289 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8290 of some markers in the region, even if CUT is non-nil. This is
8291 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8292 (interactive "p")
8293 (org-preserve-local-variables
8294 (let (beg end folded (beg0 (point)))
8295 (if (called-interactively-p 'any)
8296 (org-back-to-heading nil) ; take what looks like a subtree
8297 (org-back-to-heading t)) ; take what is really there
8298 (setq beg (point))
8299 (skip-chars-forward " \t\r\n")
8300 (save-match-data
8301 (if nosubtrees
8302 (outline-next-heading)
8303 (save-excursion (outline-end-of-heading)
8304 (setq folded (org-invisible-p)))
8305 (ignore-errors (org-forward-heading-same-level (1- n) t))
8306 (org-end-of-subtree t t)))
8307 ;; Include the end of an inlinetask
8308 (when (and (featurep 'org-inlinetask)
8309 (looking-at-p (concat (org-inlinetask-outline-regexp)
8310 "END[ \t]*$")))
8311 (end-of-line))
8312 (setq end (point))
8313 (goto-char beg0)
8314 (when (> end beg)
8315 (setq org-subtree-clip-folded folded)
8316 (when (or cut force-store-markers)
8317 (org-save-markers-in-region beg end))
8318 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8319 (setq org-subtree-clip (current-kill 0))
8320 (message "%s: Subtree(s) with %d characters"
8321 (if cut "Cut" "Copied")
8322 (length org-subtree-clip))))))
8324 (defun org-paste-subtree (&optional level tree for-yank remove)
8325 "Paste the clipboard as a subtree, with modification of headline level.
8327 The entire subtree is promoted or demoted in order to match a new headline
8328 level.
8330 If the cursor is at the beginning of a headline, the same level as
8331 that headline is used to paste the tree.
8333 If not, the new level is derived from the *visible* headings
8334 before and after the insertion point, and taken to be the inferior headline
8335 level of the two. So if the previous visible heading is level 3 and the
8336 next is level 4 (or vice versa), level 4 will be used for insertion.
8337 This makes sure that the subtree remains an independent subtree and does
8338 not swallow low level entries.
8340 You can also force a different level, either by using a numeric prefix
8341 argument, or by inserting the heading marker by hand. For example, if the
8342 cursor is after \"*****\", then the tree will be shifted to level 5.
8344 If optional TREE is given, use this text instead of the kill ring.
8346 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8347 move back over whitespace before inserting, and move point to the end of
8348 the inserted text when done.
8350 When REMOVE is non-nil, remove the subtree from the clipboard."
8351 (interactive "P")
8352 (setq tree (or tree (and kill-ring (current-kill 0))))
8353 (unless (org-kill-is-subtree-p tree)
8354 (user-error
8355 (substitute-command-keys
8356 "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
8357 (org-with-limited-levels
8358 (let* ((visp (not (org-invisible-p)))
8359 (txt tree)
8360 (old-level (if (string-match org-outline-regexp-bol txt)
8361 (- (match-end 0) (match-beginning 0) 1)
8362 -1))
8363 (force-level
8364 (cond
8365 (level (prefix-numeric-value level))
8366 ;; When point is right after the stars in an otherwise
8367 ;; empty headline, use stars as the forced level.
8368 ((and (looking-at-p "[ \t]*$")
8369 (string-match-p "^\\*+ *"
8370 (buffer-substring (line-beginning-position)
8371 (point))))
8372 (org-outline-level))
8373 ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
8374 (previous-level
8375 (save-excursion
8376 (org-previous-visible-heading 1)
8377 (if (org-at-heading-p) (org-outline-level) 1)))
8378 (next-level
8379 (save-excursion
8380 (if (org-at-heading-p) (org-outline-level)
8381 (org-next-visible-heading 1)
8382 (if (org-at-heading-p) (org-outline-level) 1))))
8383 (new-level (or force-level (max previous-level next-level)))
8384 (shift (if (or (= old-level -1)
8385 (= new-level -1)
8386 (= old-level new-level))
8388 (- new-level old-level)))
8389 (delta (if (> shift 0) -1 1))
8390 (func (if (> shift 0) #'org-demote #'org-promote))
8391 (org-odd-levels-only nil)
8392 beg end newend)
8393 ;; Remove the forced level indicator.
8394 (when (and force-level (not level))
8395 (delete-region (line-beginning-position) (point)))
8396 ;; Paste before the next visible heading or at end of buffer,
8397 ;; unless point is at the beginning of a headline.
8398 (unless (and (bolp) (org-at-heading-p))
8399 (org-next-visible-heading 1)
8400 (unless (bolp) (insert "\n")))
8401 (setq beg (point))
8402 (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8403 (insert-before-markers txt)
8404 (unless (string-suffix-p "\n" txt) (insert "\n"))
8405 (setq newend (point))
8406 (org-reinstall-markers-in-region beg)
8407 (setq end (point))
8408 (goto-char beg)
8409 (skip-chars-forward " \t\n\r")
8410 (setq beg (point))
8411 (when (and (org-invisible-p) visp)
8412 (save-excursion (outline-show-heading)))
8413 ;; Shift if necessary.
8414 (unless (= shift 0)
8415 (save-restriction
8416 (narrow-to-region beg end)
8417 (while (not (= shift 0))
8418 (org-map-region func (point-min) (point-max))
8419 (setq shift (+ delta shift)))
8420 (goto-char (point-min))
8421 (setq newend (point-max))))
8422 (when (or for-yank (called-interactively-p 'interactive))
8423 (message "Clipboard pasted as level %d subtree" new-level))
8424 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8425 kill-ring
8426 (equal org-subtree-clip (current-kill 0))
8427 org-subtree-clip-folded)
8428 ;; The tree was folded before it was killed/copied
8429 (outline-hide-subtree))
8430 (when for-yank (goto-char newend))
8431 (when remove (pop kill-ring)))))
8433 (defun org-kill-is-subtree-p (&optional txt)
8434 "Check if the current kill is an outline subtree, or a set of trees.
8435 Returns nil if kill does not start with a headline, or if the first
8436 headline level is not the largest headline level in the tree.
8437 So this will actually accept several entries of equal levels as well,
8438 which is OK for `org-paste-subtree'.
8439 If optional TXT is given, check this string instead of the current kill."
8440 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8441 (re (org-get-limited-outline-regexp))
8442 (^re (concat "^" re))
8443 (start-level (and kill
8444 (string-match
8445 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8446 kill)
8447 (- (match-end 2) (match-beginning 2) 1)))
8448 (start (1+ (or (match-beginning 2) -1))))
8449 (if (not start-level)
8450 (progn
8451 nil) ;; does not even start with a heading
8452 (catch 'exit
8453 (while (setq start (string-match ^re kill (1+ start)))
8454 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8455 (throw 'exit nil)))
8456 t))))
8458 (defvar org-markers-to-move nil
8459 "Markers that should be moved with a cut-and-paste operation.
8460 Those markers are stored together with their positions relative to
8461 the start of the region.")
8463 (defun org-save-markers-in-region (beg end)
8464 "Check markers in region.
8465 If these markers are between BEG and END, record their position relative
8466 to BEG, so that after moving the block of text, we can put the markers back
8467 into place.
8468 This function gets called just before an entry or tree gets cut from the
8469 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8470 called immediately, to move the markers with the entries."
8471 (setq org-markers-to-move nil)
8472 (when (featurep 'org-clock)
8473 (org-clock-save-markers-for-cut-and-paste beg end))
8474 (when (featurep 'org-agenda)
8475 (org-agenda-save-markers-for-cut-and-paste beg end)))
8477 (defun org-check-and-save-marker (marker beg end)
8478 "Check if MARKER is between BEG and END.
8479 If yes, remember the marker and the distance to BEG."
8480 (when (and (marker-buffer marker)
8481 (equal (marker-buffer marker) (current-buffer))
8482 (>= marker beg) (< marker end))
8483 (push (cons marker (- marker beg)) org-markers-to-move)))
8485 (defun org-reinstall-markers-in-region (beg)
8486 "Move all remembered markers to their position relative to BEG."
8487 (dolist (x org-markers-to-move)
8488 (move-marker (car x) (+ beg (cdr x))))
8489 (setq org-markers-to-move nil))
8491 (defun org-narrow-to-subtree ()
8492 "Narrow buffer to the current subtree."
8493 (interactive)
8494 (save-excursion
8495 (save-match-data
8496 (org-with-limited-levels
8497 (narrow-to-region
8498 (progn (org-back-to-heading t) (point))
8499 (progn (org-end-of-subtree t t)
8500 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8501 (point)))))))
8503 (defun org-toggle-narrow-to-subtree ()
8504 "Narrow to the subtree at point or widen a narrowed buffer."
8505 (interactive)
8506 (if (buffer-narrowed-p)
8507 (widen)
8508 (org-narrow-to-subtree)))
8510 (defun org-narrow-to-block ()
8511 "Narrow buffer to the current block."
8512 (interactive)
8513 (let* ((case-fold-search t)
8514 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8515 "^[ \t]*#\\+end_.*")))
8516 (if blockp
8517 (narrow-to-region (car blockp) (cdr blockp))
8518 (user-error "Not in a block"))))
8520 (defun org-clone-subtree-with-time-shift (n &optional shift)
8521 "Clone the task (subtree) at point N times.
8522 The clones will be inserted as siblings.
8524 In interactive use, the user will be prompted for the number of
8525 clones to be produced. If the entry has a timestamp, the user
8526 will also be prompted for a time shift, which may be a repeater
8527 as used in time stamps, for example `+3d'. To disable this,
8528 you can call the function with a universal prefix argument.
8530 When a valid repeater is given and the entry contains any time
8531 stamps, the clones will become a sequence in time, with time
8532 stamps in the subtree shifted for each clone produced. If SHIFT
8533 is nil or the empty string, time stamps will be left alone. The
8534 ID property of the original subtree is removed.
8536 In each clone, all the CLOCK entries will be removed. This
8537 prevents Org from considering that the clocked times overlap.
8539 If the original subtree did contain time stamps with a repeater,
8540 the following will happen:
8541 - the repeater will be removed in each clone
8542 - an additional clone will be produced, with the current, unshifted
8543 date(s) in the entry.
8544 - the original entry will be placed *after* all the clones, with
8545 repeater intact.
8546 - the start days in the repeater in the original entry will be shifted
8547 to past the last clone.
8548 In this way you can spell out a number of instances of a repeating task,
8549 and still retain the repeater to cover future instances of the task.
8551 As described above, N+1 clones are produced when the original
8552 subtree has a repeater. Setting N to 0, then, can be used to
8553 remove the repeater from a subtree and create a shifted clone
8554 with the original repeater."
8555 (interactive "nNumber of clones to produce: ")
8556 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8557 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8558 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8559 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8560 (shift
8561 (or shift
8562 (if (and (not (equal current-prefix-arg '(4)))
8563 (save-excursion
8564 (goto-char beg)
8565 (re-search-forward org-ts-regexp-both end-of-tree t)))
8566 (read-from-minibuffer
8567 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8568 ""))) ;No time shift
8569 (doshift
8570 (and (org-string-nw-p shift)
8571 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8572 shift)
8573 (user-error "Invalid shift specification %s" shift)))))
8574 (goto-char end-of-tree)
8575 (unless (bolp) (insert "\n"))
8576 (let* ((end (point))
8577 (template (buffer-substring beg end))
8578 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8579 (shift-what (pcase (and doshift (match-string 2 shift))
8580 (`nil nil)
8581 ("d" 'day)
8582 ("w" (setq shift-n (* 7 shift-n)) 'day)
8583 ("m" 'month)
8584 ("y" 'year)
8585 (_ (error "Unsupported time unit"))))
8586 (nmin 1)
8587 (nmax n)
8588 (n-no-remove -1)
8589 (idprop (org-entry-get nil "ID")))
8590 (when (and doshift
8591 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8592 template))
8593 (delete-region beg end)
8594 (setq end beg)
8595 (setq nmin 0)
8596 (setq nmax (1+ nmax))
8597 (setq n-no-remove nmax))
8598 (goto-char end)
8599 (cl-loop for n from nmin to nmax do
8600 (insert
8601 ;; Prepare clone.
8602 (with-temp-buffer
8603 (insert template)
8604 (org-mode)
8605 (goto-char (point-min))
8606 (org-show-subtree)
8607 (and idprop (if org-clone-delete-id
8608 (org-entry-delete nil "ID")
8609 (org-id-get-create t)))
8610 (unless (= n 0)
8611 (while (re-search-forward org-clock-line-re nil t)
8612 (delete-region (line-beginning-position)
8613 (line-beginning-position 2)))
8614 (goto-char (point-min))
8615 (while (re-search-forward org-drawer-regexp nil t)
8616 (org-remove-empty-drawer-at (point))))
8617 (goto-char (point-min))
8618 (when doshift
8619 (while (re-search-forward org-ts-regexp-both nil t)
8620 (org-timestamp-change (* n shift-n) shift-what))
8621 (unless (= n n-no-remove)
8622 (goto-char (point-min))
8623 (while (re-search-forward org-ts-regexp nil t)
8624 (save-excursion
8625 (goto-char (match-beginning 0))
8626 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8627 (delete-region (match-beginning 1) (match-end 1)))))))
8628 (buffer-string)))))
8629 (goto-char beg)))
8631 ;;; Outline Sorting
8633 (defun org-sort (&optional with-case)
8634 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8635 Optional argument WITH-CASE means sort case-sensitively."
8636 (interactive "P")
8637 (org-call-with-arg
8638 (cond ((org-at-table-p) #'org-table-sort-lines)
8639 ((org-at-item-p) #'org-sort-list)
8640 (t #'org-sort-entries))
8641 with-case))
8643 (defun org-sort-remove-invisible (s)
8644 "Remove invisible part of links and emphasis markers from string S."
8645 (remove-text-properties 0 (length s) org-rm-props s)
8646 (replace-regexp-in-string
8647 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8648 (replace-regexp-in-string
8649 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8650 (org-link-display-format s)
8651 t t) t t))
8653 (defvar org-priority-regexp) ; defined later in the file
8655 (defvar org-after-sorting-entries-or-items-hook nil
8656 "Hook that is run after a bunch of entries or items have been sorted.
8657 When children are sorted, the cursor is in the parent line when this
8658 hook gets called. When a region or a plain list is sorted, the cursor
8659 will be in the first entry of the sorted region/list.")
8661 (defun org-sort-entries
8662 (&optional with-case sorting-type getkey-func compare-func property
8663 interactive?)
8664 "Sort entries on a certain level of an outline tree.
8665 If there is an active region, the entries in the region are sorted.
8666 Else, if the cursor is before the first entry, sort the top-level items.
8667 Else, the children of the entry at point are sorted.
8669 Sorting can be alphabetically, numerically, by date/time as given by
8670 a time stamp, by a property, by priority order, or by a custom function.
8672 The command prompts for the sorting type unless it has been given to the
8673 function through the SORTING-TYPE argument, which needs to be a character,
8674 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8675 the precise meaning of each character:
8677 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8678 c By creation time, which is assumed to be the first inactive time stamp
8679 at the beginning of a line.
8680 d By deadline date/time.
8681 k By clocking time.
8682 n Numerically, by converting the beginning of the entry/item to a number.
8683 o By order of TODO keywords.
8684 p By priority according to the cookie.
8685 r By the value of a property.
8686 s By scheduled date/time.
8687 t By date/time, either the first active time stamp in the entry, or, if
8688 none exist, by the first inactive one.
8690 Capital letters will reverse the sort order.
8692 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8693 called with point at the beginning of the record. It must return a
8694 value that is compatible with COMPARE-FUNC, the function used to
8695 compare entries.
8697 Comparing entries ignores case by default. However, with an optional argument
8698 WITH-CASE, the sorting considers case as well.
8700 Sorting is done against the visible part of the headlines, it ignores hidden
8701 links.
8703 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8705 A non-nil value for INTERACTIVE? is used to signal that this
8706 function is being called interactively."
8707 (interactive (list current-prefix-arg nil nil nil nil t))
8708 (let ((case-func (if with-case 'identity 'downcase))
8709 start beg end stars re re2
8710 txt what tmp)
8711 ;; Find beginning and end of region to sort
8712 (cond
8713 ((org-region-active-p)
8714 ;; we will sort the region
8715 (setq end (region-end)
8716 what "region")
8717 (goto-char (region-beginning))
8718 (unless (org-at-heading-p) (outline-next-heading))
8719 (setq start (point)))
8720 ((or (org-at-heading-p)
8721 (ignore-errors (progn (org-back-to-heading) t)))
8722 ;; we will sort the children of the current headline
8723 (org-back-to-heading)
8724 (setq start (point)
8725 end (progn (org-end-of-subtree t t)
8726 (or (bolp) (insert "\n"))
8727 (when (>= (org-back-over-empty-lines) 1)
8728 (forward-line 1))
8729 (point))
8730 what "children")
8731 (goto-char start)
8732 (outline-show-subtree)
8733 (outline-next-heading))
8735 ;; we will sort the top-level entries in this file
8736 (goto-char (point-min))
8737 (or (org-at-heading-p) (outline-next-heading))
8738 (setq start (point))
8739 (goto-char (point-max))
8740 (beginning-of-line 1)
8741 (when (looking-at ".*?\\S-")
8742 ;; File ends in a non-white line
8743 (end-of-line 1)
8744 (insert "\n"))
8745 (setq end (point-max))
8746 (setq what "top-level")
8747 (goto-char start)
8748 (org-show-all '(headings blocks))))
8750 (setq beg (point))
8751 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8753 (looking-at "\\(\\*+\\)")
8754 (setq stars (match-string 1)
8755 re (concat "^" (regexp-quote stars) " +")
8756 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8757 txt (buffer-substring beg end))
8758 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8759 (when (and (not (equal stars "*")) (string-match re2 txt))
8760 (user-error "Region to sort contains a level above the first entry"))
8762 (unless sorting-type
8763 (message
8764 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8765 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8766 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8767 what)
8768 (setq sorting-type (read-char-exclusive)))
8770 (unless getkey-func
8771 (and (= (downcase sorting-type) ?f)
8772 (setq getkey-func
8773 (or (and interactive?
8774 (org-read-function
8775 "Function for extracting keys: "))
8776 (error "Missing key extractor")))))
8778 (and (= (downcase sorting-type) ?r)
8779 (not property)
8780 (setq property
8781 (completing-read "Property: "
8782 (mapcar #'list (org-buffer-property-keys t))
8783 nil t)))
8785 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8786 (message "Sorting entries...")
8788 (save-restriction
8789 (narrow-to-region start end)
8790 (let ((restore-clock?
8791 ;; The clock marker is lost when using `sort-subr'; mark
8792 ;; the clock with temporary `:org-clock-marker-backup'
8793 ;; text property.
8794 (when (and (eq (org-clock-is-active) (current-buffer))
8795 (<= start (marker-position org-clock-marker))
8796 (>= end (marker-position org-clock-marker)))
8797 (with-silent-modifications
8798 (put-text-property (1- org-clock-marker) org-clock-marker
8799 :org-clock-marker-backup t))
8801 (dcst (downcase sorting-type))
8802 (case-fold-search nil)
8803 (now (current-time)))
8804 (org-preserve-local-variables
8805 (sort-subr
8806 (/= dcst sorting-type)
8807 ;; This function moves to the beginning character of the
8808 ;; "record" to be sorted.
8809 (lambda nil
8810 (if (re-search-forward re nil t)
8811 (goto-char (match-beginning 0))
8812 (goto-char (point-max))))
8813 ;; This function moves to the last character of the "record" being
8814 ;; sorted.
8815 (lambda nil
8816 (save-match-data
8817 (condition-case nil
8818 (outline-forward-same-level 1)
8819 (error
8820 (goto-char (point-max))))))
8821 ;; This function returns the value that gets sorted against.
8822 (lambda ()
8823 (cond
8824 ((= dcst ?n)
8825 (string-to-number
8826 (org-sort-remove-invisible (org-get-heading t t t t))))
8827 ((= dcst ?a)
8828 (funcall case-func
8829 (org-sort-remove-invisible (org-get-heading t t t t))))
8830 ((= dcst ?k)
8831 (or (get-text-property (point) :org-clock-minutes) 0))
8832 ((= dcst ?t)
8833 (let ((end (save-excursion (outline-next-heading) (point))))
8834 (if (or (re-search-forward org-ts-regexp end t)
8835 (re-search-forward org-ts-regexp-both end t))
8836 (org-time-string-to-seconds (match-string 0))
8837 (float-time now))))
8838 ((= dcst ?c)
8839 (let ((end (save-excursion (outline-next-heading) (point))))
8840 (if (re-search-forward
8841 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8842 end t)
8843 (org-time-string-to-seconds (match-string 0))
8844 (float-time now))))
8845 ((= dcst ?s)
8846 (let ((end (save-excursion (outline-next-heading) (point))))
8847 (if (re-search-forward org-scheduled-time-regexp end t)
8848 (org-time-string-to-seconds (match-string 1))
8849 (float-time now))))
8850 ((= dcst ?d)
8851 (let ((end (save-excursion (outline-next-heading) (point))))
8852 (if (re-search-forward org-deadline-time-regexp end t)
8853 (org-time-string-to-seconds (match-string 1))
8854 (float-time now))))
8855 ((= dcst ?p)
8856 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8857 (string-to-char (match-string 2))
8858 org-default-priority))
8859 ((= dcst ?r)
8860 (or (org-entry-get nil property) ""))
8861 ((= dcst ?o)
8862 (when (looking-at org-complex-heading-regexp)
8863 (let* ((m (match-string 2))
8864 (s (if (member m org-done-keywords) '- '+)))
8865 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8866 ((= dcst ?f)
8867 (if getkey-func
8868 (progn
8869 (setq tmp (funcall getkey-func))
8870 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8871 tmp)
8872 (error "Invalid key function `%s'" getkey-func)))
8873 (t (error "Invalid sorting type `%c'" sorting-type))))
8875 (cond
8876 ((= dcst ?a) 'org-string-collate-lessp)
8877 ((= dcst ?f)
8878 (or compare-func
8879 (and interactive?
8880 (org-read-function
8881 (concat "Function for comparing keys "
8882 "(empty for default `sort-subr' predicate): ")
8883 'allow-empty))))
8884 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
8885 (when restore-clock?
8886 (move-marker org-clock-marker
8887 (1+ (next-single-property-change
8888 start :org-clock-marker-backup)))
8889 (remove-text-properties (1- org-clock-marker) org-clock-marker
8890 '(:org-clock-marker-backup t)))))
8891 (run-hooks 'org-after-sorting-entries-or-items-hook)
8892 (message "Sorting entries...done")))
8894 (defun org-contextualize-keys (alist contexts)
8895 "Return valid elements in ALIST depending on CONTEXTS.
8897 `org-agenda-custom-commands' or `org-capture-templates' are the
8898 values used for ALIST, and `org-agenda-custom-commands-contexts'
8899 or `org-capture-templates-contexts' are the associated contexts
8900 definitions."
8901 (let ((contexts
8902 ;; normalize contexts
8903 (mapcar
8904 (lambda(c) (cond ((listp (cadr c))
8905 (list (car c) (car c) (nth 1 c)))
8906 ((string= "" (cadr c))
8907 (list (car c) (car c) (nth 2 c)))
8908 (t c)))
8909 contexts))
8910 (a alist) r s)
8911 ;; loop over all commands or templates
8912 (dolist (c a)
8913 (let (vrules repl)
8914 (cond
8915 ((not (assoc (car c) contexts))
8916 (push c r))
8917 ((and (assoc (car c) contexts)
8918 (setq vrules (org-contextualize-validate-key
8919 (car c) contexts)))
8920 (mapc (lambda (vr)
8921 (unless (equal (car vr) (cadr vr))
8922 (setq repl vr)))
8923 vrules)
8924 (if (not repl) (push c r)
8925 (push (cadr repl) s)
8926 (push
8927 (cons (car c)
8928 (cdr (or (assoc (cadr repl) alist)
8929 (error "Undefined key `%s' as contextual replacement for `%s'"
8930 (cadr repl) (car c)))))
8931 r))))))
8932 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8933 (delq
8935 (delete-dups
8936 (mapcar (lambda (x)
8937 (let ((tpl (car x)))
8938 (unless (delq
8940 (mapcar (lambda (y)
8941 (equal y tpl))
8943 x)))
8944 (reverse r))))))
8946 (defun org-contextualize-validate-key (key contexts)
8947 "Check CONTEXTS for agenda or capture KEY."
8948 (let (res)
8949 (dolist (r contexts)
8950 (dolist (rr (car (last r)))
8951 (when
8952 (and (equal key (car r))
8953 (if (functionp rr) (funcall rr)
8954 (or (and (eq (car rr) 'in-file)
8955 (buffer-file-name)
8956 (string-match (cdr rr) (buffer-file-name)))
8957 (and (eq (car rr) 'in-mode)
8958 (string-match (cdr rr) (symbol-name major-mode)))
8959 (and (eq (car rr) 'in-buffer)
8960 (string-match (cdr rr) (buffer-name)))
8961 (when (and (eq (car rr) 'not-in-file)
8962 (buffer-file-name))
8963 (not (string-match (cdr rr) (buffer-file-name))))
8964 (when (eq (car rr) 'not-in-mode)
8965 (not (string-match (cdr rr) (symbol-name major-mode))))
8966 (when (eq (car rr) 'not-in-buffer)
8967 (not (string-match (cdr rr) (buffer-name)))))))
8968 (push r res))))
8969 (delete-dups (delq nil res))))
8971 ;; Defined to provide a value for defcustom, since there is no
8972 ;; string-collate-greaterp in Emacs.
8973 (defun org-string-collate-greaterp (s1 s2)
8974 "Return non-nil if S1 is greater than S2 in collation order."
8975 (not (org-string-collate-lessp s1 s2)))
8977 ;;;###autoload
8978 (defun org-run-like-in-org-mode (cmd)
8979 "Run a command, pretending that the current buffer is in Org mode.
8980 This will temporarily bind local variables that are typically bound in
8981 Org mode to the values they have in Org mode, and then interactively
8982 call CMD."
8983 (org-load-modules-maybe)
8984 (let (binds)
8985 (dolist (var (org-get-local-variables))
8986 (when (or (not (boundp (car var)))
8987 (eq (symbol-value (car var))
8988 (default-value (car var))))
8989 (push (list (car var) `(quote ,(cadr var))) binds)))
8990 (eval `(let ,binds
8991 (call-interactively (quote ,cmd))))))
8993 (defun org-get-category (&optional pos force-refresh)
8994 "Get the category applying to position POS."
8995 (save-match-data
8996 (when force-refresh (org-refresh-category-properties))
8997 (let ((pos (or pos (point))))
8998 (or (get-text-property pos 'org-category)
8999 (progn (org-refresh-category-properties)
9000 (get-text-property pos 'org-category))))))
9002 ;;; Refresh properties
9004 (defun org-refresh-properties (dprop tprop)
9005 "Refresh buffer text properties.
9006 DPROP is the drawer property and TPROP is either the
9007 corresponding text property to set, or an alist with each element
9008 being a text property (as a symbol) and a function to apply to
9009 the value of the drawer property."
9010 (let* ((case-fold-search t)
9011 (inhibit-read-only t)
9012 (inherit? (org-property-inherit-p dprop))
9013 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9014 (global (and inherit? (org--property-global-value dprop nil))))
9015 (with-silent-modifications
9016 (org-with-point-at 1
9017 ;; Set global values (e.g., values defined through
9018 ;; "#+PROPERTY:" keywords) to the whole buffer.
9019 (when global (put-text-property (point-min) (point-max) tprop global))
9020 ;; Set local values.
9021 (while (re-search-forward property-re nil t)
9022 (when (org-at-property-p)
9023 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9024 (outline-next-heading))))))
9026 (defun org-refresh-property (tprop p &optional inherit)
9027 "Refresh the buffer text property TPROP from the drawer property P.
9028 The refresh happens only for the current headline, or the whole
9029 sub-tree if optional argument INHERIT is non-nil."
9030 (unless (org-before-first-heading-p)
9031 (save-excursion
9032 (org-back-to-heading t)
9033 (let ((start (point))
9034 (end (save-excursion
9035 (if inherit (org-end-of-subtree t t)
9036 (or (outline-next-heading) (point-max))))))
9037 (if (symbolp tprop)
9038 ;; TPROP is a text property symbol.
9039 (put-text-property start end tprop p)
9040 ;; TPROP is an alist with (property . function) elements.
9041 (pcase-dolist (`(,prop . ,f) tprop)
9042 (put-text-property start end prop (funcall f p))))))))
9044 (defun org-refresh-category-properties ()
9045 "Refresh category text properties in the buffer."
9046 (let ((case-fold-search t)
9047 (inhibit-read-only t)
9048 (default-category
9049 (cond ((null org-category)
9050 (if buffer-file-name
9051 (file-name-sans-extension
9052 (file-name-nondirectory buffer-file-name))
9053 "???"))
9054 ((symbolp org-category) (symbol-name org-category))
9055 (t org-category))))
9056 (with-silent-modifications
9057 (org-with-wide-buffer
9058 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9059 ;; This is the default category for the buffer. If none is
9060 ;; found, fall-back to `org-category' or buffer file name.
9061 (put-text-property
9062 (point-min) (point-max)
9063 'org-category
9064 (catch 'buffer-category
9065 (goto-char (point-max))
9066 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9067 (let ((element (org-element-at-point)))
9068 (when (eq (org-element-type element) 'keyword)
9069 (throw 'buffer-category
9070 (org-element-property :value element)))))
9071 default-category))
9072 ;; Set sub-tree specific categories.
9073 (goto-char (point-min))
9074 (let ((regexp (org-re-property "CATEGORY")))
9075 (while (re-search-forward regexp nil t)
9076 (let ((value (match-string-no-properties 3)))
9077 (when (org-at-property-p)
9078 (put-text-property
9079 (save-excursion (org-back-to-heading t) (point))
9080 (save-excursion (org-end-of-subtree t t) (point))
9081 'org-category
9082 value)))))))))
9084 (defun org-refresh-stats-properties ()
9085 "Refresh stats text properties in the buffer."
9086 (with-silent-modifications
9087 (org-with-point-at 1
9088 (let ((regexp (concat org-outline-regexp-bol
9089 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9090 (while (re-search-forward regexp nil t)
9091 (let* ((numerator (string-to-number (match-string 1)))
9092 (denominator (and (match-end 2)
9093 (string-to-number (match-string 2))))
9094 (stats (cond ((not denominator) numerator) ;percent
9095 ((= denominator 0) 0)
9096 (t (/ (* numerator 100) denominator)))))
9097 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9098 'org-stats stats)))))))
9100 (defun org-refresh-effort-properties ()
9101 "Refresh effort properties"
9102 (org-refresh-properties
9103 org-effort-property
9104 '((effort . identity)
9105 (effort-minutes . org-duration-to-minutes))))
9107 ;;;; Link Stuff
9109 ;;; Link abbreviations
9111 (defun org-link-expand-abbrev (link)
9112 "Apply replacements as defined in `org-link-abbrev-alist'."
9113 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9114 (let* ((key (match-string 1 link))
9115 (as (or (assoc key org-link-abbrev-alist-local)
9116 (assoc key org-link-abbrev-alist)))
9117 (tag (and (match-end 2) (match-string 3 link)))
9118 rpl)
9119 (if (not as)
9120 link
9121 (setq rpl (cdr as))
9122 (cond
9123 ((symbolp rpl) (funcall rpl tag))
9124 ((string-match "%(\\([^)]+\\))" rpl)
9125 (replace-match
9126 (save-match-data
9127 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9128 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9129 ((string-match "%h" rpl)
9130 (replace-match (url-hexify-string (or tag "")) t t rpl))
9131 (t (concat rpl tag)))))
9132 link))
9134 ;;; Storing and inserting links
9136 (defvar org-insert-link-history nil
9137 "Minibuffer history for links inserted with `org-insert-link'.")
9139 (defvar org-stored-links nil
9140 "Contains the links stored with `org-store-link'.")
9142 (defvar org-store-link-plist nil
9143 "Plist with info about the most recently link created with `org-store-link'.")
9145 (defun org-store-link-functions ()
9146 "Return a list of functions that are called to create and store a link.
9147 The functions defined in the :store property of
9148 `org-link-parameters'.
9150 Each function will be called in turn until one returns a non-nil
9151 value. Each function should check if it is responsible for
9152 creating this link (for example by looking at the major mode).
9153 If not, it must exit and return nil. If yes, it should return
9154 a non-nil value after calling `org-store-link-props' with a list
9155 of properties and values. Special properties are:
9157 :type The link prefix, like \"http\". This must be given.
9158 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9159 This is obligatory as well.
9160 :description Optional default description for the second pair
9161 of brackets in an Org mode link. The user can still change
9162 this when inserting this link into an Org mode buffer.
9164 In addition to these, any additional properties can be specified
9165 and then used in capture templates."
9166 (cl-loop for link in org-link-parameters
9167 with store-func
9168 do (setq store-func (org-link-get-parameter (car link) :store))
9169 if store-func
9170 collect store-func))
9172 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9173 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9175 ;;;###autoload
9176 (defun org-store-link (arg &optional interactive?)
9177 "Store a link to the current location.
9178 \\<org-mode-map>
9179 This link is added to `org-stored-links' and can later be inserted
9180 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9182 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9183 A single
9184 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9185 `org-gnus-prefer-web-links' for links to Usenet articles.
9187 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9188 skipping storing functions that are not
9189 part of Org core.
9191 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9192 prefix ARG forces storing a link for each line in the
9193 active region.
9195 Assume the function is called interactively if INTERACTIVE? is
9196 non-nil."
9197 (interactive "P\np")
9198 (org-load-modules-maybe)
9199 (if (and (equal arg '(64)) (org-region-active-p))
9200 (save-excursion
9201 (let ((end (region-end)))
9202 (goto-char (region-beginning))
9203 (set-mark (point))
9204 (while (< (point-at-eol) end)
9205 (move-end-of-line 1) (activate-mark)
9206 (let (current-prefix-arg)
9207 (call-interactively 'org-store-link))
9208 (move-beginning-of-line 2)
9209 (set-mark (point)))))
9210 (setq org-store-link-plist nil)
9211 (let (link cpltxt desc description search txt custom-id agenda-link)
9212 (cond
9213 ;; Store a link using an external link type, if any function is
9214 ;; available. If more than one can generate a link from current
9215 ;; location, ask which one to use.
9216 ((and (not (equal arg '(16)))
9217 (let ((results-alist nil))
9218 (dolist (f (org-store-link-functions))
9219 (when (funcall f)
9220 ;; XXX: return value is not link's plist, so we
9221 ;; store the new value before it is modified. It
9222 ;; would be cleaner to ask store link functions to
9223 ;; return the plist instead.
9224 (push (cons f (copy-sequence org-store-link-plist))
9225 results-alist)))
9226 (pcase results-alist
9227 (`nil nil)
9228 (`((,_ . ,_)) t) ;single choice: nothing to do
9229 (`((,name . ,_) . ,_)
9230 ;; Reinstate link plist associated to the chosen
9231 ;; function.
9232 (apply #'org-store-link-props
9233 (cdr (assoc-string
9234 (completing-read
9235 "Which function for creating the link? "
9236 (mapcar #'car results-alist)
9237 nil t (symbol-name name))
9238 results-alist)))
9239 t))))
9240 (setq link (plist-get org-store-link-plist :link))
9241 (setq desc (or (plist-get org-store-link-plist :description)
9242 link)))
9244 ;; Store a link from a source code buffer.
9245 ((org-src-edit-buffer-p)
9246 (let ((coderef-format (org-src-coderef-format)))
9247 (cond ((org-match-line (org-src-coderef-regexp coderef-format))
9248 (setq link (format "(%s)" (match-string-no-properties 3))))
9249 (interactive?
9250 (let ((label (read-string "Code line label: ")))
9251 (end-of-line)
9252 (setq link (format coderef-format label))
9253 (let ((gc (- 79 (length link))))
9254 (if (< (current-column) gc)
9255 (org-move-to-column gc t)
9256 (insert " ")))
9257 (insert link)
9258 (setq link (concat "(" label ")"))
9259 (setq desc nil)))
9260 (t (setq link nil)))))
9262 ;; We are in the agenda, link to referenced location
9263 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9264 (let ((m (or (get-text-property (point) 'org-hd-marker)
9265 (get-text-property (point) 'org-marker))))
9266 (when m
9267 (org-with-point-at m
9268 (setq agenda-link (org-store-link nil interactive?))))))
9270 ((eq major-mode 'calendar-mode)
9271 (let ((cd (calendar-cursor-to-date)))
9272 (setq link
9273 (format-time-string
9274 (car org-time-stamp-formats)
9275 (apply 'encode-time
9276 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9277 nil nil nil))))
9278 (org-store-link-props :type "calendar" :date cd)))
9280 ((eq major-mode 'help-mode)
9281 (setq link (concat "help:" (save-excursion
9282 (goto-char (point-min))
9283 (looking-at "^[^ ]+")
9284 (match-string 0))))
9285 (org-store-link-props :type "help"))
9287 ((eq major-mode 'w3-mode)
9288 (setq cpltxt (if (and (buffer-name)
9289 (not (string-match "Untitled" (buffer-name))))
9290 (buffer-name)
9291 (url-view-url t))
9292 link (url-view-url t))
9293 (org-store-link-props :type "w3" :url (url-view-url t)))
9295 ((eq major-mode 'image-mode)
9296 (setq cpltxt (concat "file:"
9297 (abbreviate-file-name buffer-file-name))
9298 link cpltxt)
9299 (org-store-link-props :type "image" :file buffer-file-name))
9301 ;; In dired, store a link to the file of the current line
9302 ((derived-mode-p 'dired-mode)
9303 (let ((file (dired-get-filename nil t)))
9304 (setq file (if file
9305 (abbreviate-file-name
9306 (expand-file-name (dired-get-filename nil t)))
9307 ;; otherwise, no file so use current directory.
9308 default-directory))
9309 (setq cpltxt (concat "file:" file)
9310 link cpltxt)))
9312 ((setq search (run-hook-with-args-until-success
9313 'org-create-file-search-functions))
9314 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9315 "::" search))
9316 (setq cpltxt (or description link)))
9318 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9319 (org-with-limited-levels
9320 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9321 (cond
9322 ;; Store a link using the target at point
9323 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9324 (setq cpltxt
9325 (concat "file:"
9326 (abbreviate-file-name
9327 (buffer-file-name (buffer-base-buffer)))
9328 "::" (match-string 1))
9329 link cpltxt))
9330 ((and (featurep 'org-id)
9331 (or (eq org-id-link-to-org-use-id t)
9332 (and interactive?
9333 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9334 (and (eq org-id-link-to-org-use-id
9335 'create-if-interactive-and-no-custom-id)
9336 (not custom-id))))
9337 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9338 ;; Store a link using the ID at point
9339 (setq link (condition-case nil
9340 (prog1 (org-id-store-link)
9341 (setq desc (or (plist-get org-store-link-plist
9342 :description)
9343 "")))
9344 (error
9345 ;; Probably before first headline, link only to file
9346 (concat "file:"
9347 (abbreviate-file-name
9348 (buffer-file-name (buffer-base-buffer))))))))
9350 ;; Just link to current headline
9351 (setq cpltxt (concat "file:"
9352 (abbreviate-file-name
9353 (buffer-file-name (buffer-base-buffer)))))
9354 ;; Add a context search string
9355 (when (org-xor org-context-in-file-links
9356 (equal arg '(4)))
9357 (let* ((element (org-element-at-point))
9358 (name (org-element-property :name element)))
9359 (setq txt (cond
9360 ((org-at-heading-p) nil)
9361 (name)
9362 ((org-region-active-p)
9363 (buffer-substring (region-beginning) (region-end)))))
9364 (when (or (null txt) (string-match "\\S-" txt))
9365 (setq cpltxt
9366 (concat cpltxt "::"
9367 (condition-case nil
9368 (org-make-org-heading-search-string txt)
9369 (error "")))
9370 desc (or name
9371 (nth 4 (ignore-errors (org-heading-components)))
9372 "NONE")))))
9373 (when (string-match "::\\'" cpltxt)
9374 (setq cpltxt (substring cpltxt 0 -2)))
9375 (setq link cpltxt)))))
9377 ((buffer-file-name (buffer-base-buffer))
9378 ;; Just link to this file here.
9379 (setq cpltxt (concat "file:"
9380 (abbreviate-file-name
9381 (buffer-file-name (buffer-base-buffer)))))
9382 ;; Add a context string.
9383 (when (org-xor org-context-in-file-links
9384 (equal arg '(4)))
9385 (setq txt (if (org-region-active-p)
9386 (buffer-substring (region-beginning) (region-end))
9387 (buffer-substring (point-at-bol) (point-at-eol))))
9388 ;; Only use search option if there is some text.
9389 (when (string-match "\\S-" txt)
9390 (setq cpltxt
9391 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9392 desc "NONE")))
9393 (setq link cpltxt))
9395 (interactive?
9396 (user-error "No method for storing a link from this buffer"))
9398 (t (setq link nil)))
9400 ;; We're done setting link and desc, clean up
9401 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9402 (setq link (or link cpltxt)
9403 desc (or desc cpltxt))
9404 (cond ((not desc))
9405 ((equal desc "NONE") (setq desc nil))
9406 (t (setq desc
9407 (replace-regexp-in-string
9408 org-bracket-link-analytic-regexp
9409 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9410 desc))))
9411 ;; Return the link
9412 (if (not (and interactive? link))
9413 (or agenda-link (and link (org-make-link-string link desc)))
9414 (push (list link desc) org-stored-links)
9415 (message "Stored: %s" (or desc link))
9416 (when custom-id
9417 (setq link (concat "file:" (abbreviate-file-name
9418 (buffer-file-name)) "::#" custom-id))
9419 (push (list link desc) org-stored-links))
9420 (car org-stored-links)))))
9422 (defun org-store-link-props (&rest plist)
9423 "Store link properties.
9424 The properties are pre-processed by extracting names, addresses
9425 and dates."
9426 (let ((x (plist-get plist :from)))
9427 (when x
9428 (let ((adr (mail-extract-address-components x)))
9429 (setq plist (plist-put plist :fromname (car adr)))
9430 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9431 (let ((x (plist-get plist :to)))
9432 (when x
9433 (let ((adr (mail-extract-address-components x)))
9434 (setq plist (plist-put plist :toname (car adr)))
9435 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9436 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9437 (when x
9438 (setq plist (plist-put plist :date-timestamp
9439 (format-time-string
9440 (org-time-stamp-format t) x)))
9441 (setq plist (plist-put plist :date-timestamp-inactive
9442 (format-time-string
9443 (org-time-stamp-format t t) x)))))
9444 (let ((from (plist-get plist :from))
9445 (to (plist-get plist :to)))
9446 (when (and from to org-from-is-user-regexp)
9447 (setq plist
9448 (plist-put plist :fromto
9449 (if (string-match org-from-is-user-regexp from)
9450 (concat "to %t")
9451 (concat "from %f"))))))
9452 (setq org-store-link-plist plist))
9454 (defun org-add-link-props (&rest plist)
9455 "Add these properties to the link property list."
9456 (let (key value)
9457 (while plist
9458 (setq key (pop plist) value (pop plist))
9459 (setq org-store-link-plist
9460 (plist-put org-store-link-plist key value)))))
9462 (defun org-email-link-description (&optional fmt)
9463 "Return the description part of an email link.
9464 This takes information from `org-store-link-plist' and formats it
9465 according to FMT (default from `org-email-link-description-format')."
9466 (setq fmt (or fmt org-email-link-description-format))
9467 (let* ((p org-store-link-plist)
9468 (to (plist-get p :toaddress))
9469 (from (plist-get p :fromaddress))
9470 (table
9471 (list
9472 (cons "%c" (plist-get p :fromto))
9473 (cons "%F" (plist-get p :from))
9474 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9475 (cons "%T" (plist-get p :to))
9476 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9477 (cons "%s" (plist-get p :subject))
9478 (cons "%d" (plist-get p :date))
9479 (cons "%m" (plist-get p :message-id)))))
9480 (when (string-match "%c" fmt)
9481 ;; Check if the user wrote this message
9482 (if (and org-from-is-user-regexp from to
9483 (save-match-data (string-match org-from-is-user-regexp from)))
9484 (setq fmt (replace-match "to %t" t t fmt))
9485 (setq fmt (replace-match "from %f" t t fmt))))
9486 (org-replace-escapes fmt table)))
9488 (defun org-make-org-heading-search-string (&optional string)
9489 "Make search string for the current headline or STRING."
9490 (let ((s (or string
9491 (and (derived-mode-p 'org-mode)
9492 (save-excursion
9493 (org-back-to-heading t)
9494 (org-element-property :raw-value (org-element-at-point))))))
9495 (lines org-context-in-file-links))
9496 (unless string (setq s (concat "*" s))) ;Add * for headlines
9497 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9498 (when (and string (integerp lines) (> lines 0))
9499 (let ((slines (org-split-string s "\n")))
9500 (when (< lines (length slines))
9501 (setq s (mapconcat
9502 'identity
9503 (reverse (nthcdr (- (length slines) lines)
9504 (reverse slines))) "\n")))))
9505 (mapconcat #'identity (split-string s) " ")))
9507 (defconst org-link-escape-chars
9508 ;;%20 %5B %5D %25
9509 '(?\s ?\[ ?\] ?%)
9510 "List of characters that should be escaped in a link when stored to Org.
9511 This is the list that is used for internal purposes.")
9513 (defun org-make-link-string (link &optional description)
9514 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9515 (unless (org-string-nw-p link) (error "Empty link"))
9516 (let ((uri (cond ((string-match org-link-types-re link)
9517 (concat (match-string 1 link)
9518 (org-link-escape (substring link (match-end 1)))))
9519 ((or (file-name-absolute-p link)
9520 (string-match-p "\\`\\.\\.?/" link))
9521 (org-link-escape link))
9522 ;; For readability, do not encode space characters
9523 ;; in fuzzy links.
9524 (t (org-link-escape link (remq ?\s org-link-escape-chars)))))
9525 (description
9526 (and (org-string-nw-p description)
9527 ;; Remove brackets from description, as they are fatal.
9528 (replace-regexp-in-string
9529 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9530 (org-trim description)))))
9531 (format "[[%s]%s]"
9533 (if description (format "[%s]" description) ""))))
9535 (defun org-link-escape (text &optional table merge)
9536 "Return percent escaped representation of TEXT.
9537 TEXT is a string with the text to escape.
9538 Optional argument TABLE is a list with characters that should be
9539 escaped. When nil, `org-link-escape-chars' is used.
9540 If optional argument MERGE is set, merge TABLE into
9541 `org-link-escape-chars'."
9542 (let ((characters-to-encode
9543 (cond ((null table) org-link-escape-chars)
9544 (merge (append org-link-escape-chars table))
9545 (t table))))
9546 (mapconcat
9547 (lambda (c)
9548 (if (or (memq c characters-to-encode)
9549 (and org-url-hexify-p (or (< c 32) (> c 126))))
9550 (mapconcat (lambda (e) (format "%%%.2X" e))
9551 (or (encode-coding-char c 'utf-8)
9552 (error "Unable to percent escape character: %c" c))
9554 (char-to-string c)))
9555 text "")))
9557 (defun org-link-unescape (str)
9558 "Unhex hexified Unicode parts in string STR.
9559 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9560 reciprocal of `org-link-escape', which see."
9561 (if (org-string-nw-p str)
9562 (replace-regexp-in-string
9563 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9564 str))
9566 (defun org-link-unescape-compound (hex)
9567 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9568 Note: this function also decodes single byte encodings like
9569 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9570 (save-match-data
9571 (let* ((bytes (cdr (split-string hex "%")))
9572 (ret "")
9573 (eat 0)
9574 (sum 0))
9575 (while bytes
9576 (let* ((val (string-to-number (pop bytes) 16))
9577 (shift-xor
9578 (if (= 0 eat)
9579 (cond
9580 ((>= val 252) (cons 6 252))
9581 ((>= val 248) (cons 5 248))
9582 ((>= val 240) (cons 4 240))
9583 ((>= val 224) (cons 3 224))
9584 ((>= val 192) (cons 2 192))
9585 (t (cons 0 0)))
9586 (cons 6 128))))
9587 (when (>= val 192) (setq eat (car shift-xor)))
9588 (setq val (logxor val (cdr shift-xor)))
9589 (setq sum (+ (lsh sum (car shift-xor)) val))
9590 (when (> eat 0) (setq eat (- eat 1)))
9591 (cond
9592 ((= 0 eat) ;multi byte
9593 (setq ret (concat ret (char-to-string sum)))
9594 (setq sum 0))
9595 ((not bytes) ; single byte(s)
9596 (setq ret (org-link-unescape-single-byte-sequence hex))))))
9597 ret)))
9599 (defun org-link-unescape-single-byte-sequence (hex)
9600 "Unhexify hex-encoded single byte character sequences."
9601 (mapconcat (lambda (byte)
9602 (char-to-string (string-to-number byte 16)))
9603 (cdr (split-string hex "%")) ""))
9605 (defun org-fixup-message-id-for-http (s)
9606 "Replace special characters in a message id, so it can be used in an http query."
9607 (when (string-match "%" s)
9608 (setq s (mapconcat (lambda (c)
9609 (if (eq c ?%)
9610 "%25"
9611 (char-to-string c)))
9612 s "")))
9613 (while (string-match "<" s)
9614 (setq s (replace-match "%3C" t t s)))
9615 (while (string-match ">" s)
9616 (setq s (replace-match "%3E" t t s)))
9617 (while (string-match "@" s)
9618 (setq s (replace-match "%40" t t s)))
9621 (defun org-link-prettify (link)
9622 "Return a human-readable representation of LINK.
9623 The car of LINK must be a raw link.
9624 The cdr of LINK must be either a link description or nil."
9625 (let ((desc (or (cadr link) "<no description>")))
9626 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9627 "<" (car link) ">")))
9629 ;;;###autoload
9630 (defun org-insert-link-global ()
9631 "Insert a link like Org mode does.
9632 This command can be called in any mode to insert a link in Org syntax."
9633 (interactive)
9634 (org-load-modules-maybe)
9635 (org-run-like-in-org-mode 'org-insert-link))
9637 (defun org-insert-all-links (arg &optional pre post)
9638 "Insert all links in `org-stored-links'.
9639 When a universal prefix, do not delete the links from `org-stored-links'.
9640 When `ARG' is a number, insert the last N link(s).
9641 `PRE' and `POST' are optional arguments to define a string to
9642 prepend or to append."
9643 (interactive "P")
9644 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
9645 (links (copy-sequence org-stored-links))
9646 (pr (or pre "- "))
9647 (po (or post "\n"))
9648 (cnt 1) l)
9649 (if (null org-stored-links)
9650 (message "No link to insert")
9651 (while (and (or (listp arg) (>= arg cnt))
9652 (setq l (if (listp arg)
9653 (pop links)
9654 (pop org-stored-links))))
9655 (setq cnt (1+ cnt))
9656 (insert pr)
9657 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9658 (insert po)))))
9660 (defun org-insert-last-stored-link (arg)
9661 "Insert the last link stored in `org-stored-links'."
9662 (interactive "p")
9663 (org-insert-all-links arg "" "\n"))
9665 (defun org-link-fontify-links-to-this-file ()
9666 "Fontify links to the current file in `org-stored-links'."
9667 (let ((f (buffer-file-name)) a b)
9668 (setq a (mapcar (lambda(l)
9669 (let ((ll (car l)))
9670 (when (and (string-match "^file:\\(.+\\)::" ll)
9671 (equal f (expand-file-name (match-string 1 ll))))
9672 ll)))
9673 org-stored-links))
9674 (when (featurep 'org-id)
9675 (setq b (mapcar (lambda(l)
9676 (let ((ll (car l)))
9677 (when (and (string-match "^id:\\(.+\\)$" ll)
9678 (equal f (expand-file-name
9679 (or (org-id-find-id-file
9680 (match-string 1 ll)) ""))))
9681 ll)))
9682 org-stored-links)))
9683 (mapcar (lambda(l)
9684 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9685 (delq nil (append a b)))))
9687 (defvar org--links-history nil)
9688 (defun org-insert-link (&optional complete-file link-location default-description)
9689 "Insert a link. At the prompt, enter the link.
9691 Completion can be used to insert any of the link protocol prefixes in use.
9693 The history can be used to select a link previously stored with
9694 `org-store-link'. When the empty string is entered (i.e. if you just
9695 press `RET' at the prompt), the link defaults to the most recently
9696 stored link. As `SPC' triggers completion in the minibuffer, you need to
9697 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
9699 You will also be prompted for a description, and if one is given, it will
9700 be displayed in the buffer instead of the link.
9702 If there is already a link at point, this command will allow you to edit
9703 link and description parts.
9705 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
9706 file name can be
9707 selected using completion. The path to the file will be relative to the
9708 current directory if the file is in the current directory or a subdirectory.
9709 Otherwise, the link will be the absolute path as completed in the minibuffer
9710 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9711 option `org-link-file-path-type'.
9713 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
9714 absolute path even if the file is in
9715 the current directory or below.
9717 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9718 prefix negates `org-keep-stored-link-after-insertion'.
9720 If the LINK-LOCATION parameter is non-nil, this value will be used as
9721 the link location instead of reading one interactively.
9723 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9724 be used as the default description. Otherwise, if
9725 `org-make-link-description-function' is non-nil, this function
9726 will be called with the link target, and the result will be the
9727 default link description. When called non-interactivily, don't
9728 allow to edit the default description."
9729 (interactive "P")
9730 (let* ((wcf (current-window-configuration))
9731 (origbuf (current-buffer))
9732 (region (when (org-region-active-p)
9733 (buffer-substring (region-beginning) (region-end))))
9734 (remove (and region (list (region-beginning) (region-end))))
9735 (desc region)
9736 (link link-location)
9737 (abbrevs org-link-abbrev-alist-local)
9738 entry all-prefixes auto-desc)
9739 (cond
9740 (link-location) ; specified by arg, just use it.
9741 ((org-in-regexp org-bracket-link-regexp 1)
9742 ;; We do have a link at point, and we are going to edit it.
9743 (setq remove (list (match-beginning 0) (match-end 0)))
9744 (setq desc (when (match-end 3) (match-string-no-properties 3)))
9745 (setq link (read-string "Link: "
9746 (org-link-unescape
9747 (match-string-no-properties 1)))))
9748 ((or (org-in-regexp org-angle-link-re)
9749 (org-in-regexp org-plain-link-re))
9750 ;; Convert to bracket link
9751 (setq remove (list (match-beginning 0) (match-end 0))
9752 link (read-string "Link: "
9753 (org-unbracket-string "<" ">" (match-string 0)))))
9754 ((member complete-file '((4) (16)))
9755 ;; Completing read for file names.
9756 (setq link (org-file-complete-link complete-file)))
9758 ;; Read link, with completion for stored links.
9759 (org-link-fontify-links-to-this-file)
9760 (org-switch-to-buffer-other-window "*Org Links*")
9761 (with-current-buffer "*Org Links*"
9762 (erase-buffer)
9763 (insert "Insert a link.
9764 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9765 (when org-stored-links
9766 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9767 (insert (mapconcat 'org-link-prettify
9768 (reverse org-stored-links) "\n")))
9769 (goto-char (point-min)))
9770 (let ((cw (selected-window)))
9771 (select-window (get-buffer-window "*Org Links*" 'visible))
9772 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9773 (unless (pos-visible-in-window-p (point-max))
9774 (org-fit-window-to-buffer))
9775 (and (window-live-p cw) (select-window cw)))
9776 (setq all-prefixes (append (mapcar 'car abbrevs)
9777 (mapcar 'car org-link-abbrev-alist)
9778 (org-link-types)))
9779 (unwind-protect
9780 ;; Fake a link history, containing the stored links.
9781 (let ((org--links-history
9782 (append (mapcar #'car org-stored-links)
9783 org-insert-link-history)))
9784 (setq link
9785 (org-completing-read
9786 "Link: "
9787 (append
9788 (mapcar (lambda (x) (concat x ":")) all-prefixes)
9789 (mapcar #'car org-stored-links))
9790 nil nil nil
9791 'org--links-history
9792 (caar org-stored-links)))
9793 (unless (org-string-nw-p link) (user-error "No link selected"))
9794 (dolist (l org-stored-links)
9795 (when (equal link (cadr l))
9796 (setq link (car l))
9797 (setq auto-desc t)))
9798 (when (or (member link all-prefixes)
9799 (and (equal ":" (substring link -1))
9800 (member (substring link 0 -1) all-prefixes)
9801 (setq link (substring link 0 -1))))
9802 (setq link (with-current-buffer origbuf
9803 (org-link-try-special-completion link)))))
9804 (set-window-configuration wcf)
9805 (kill-buffer "*Org Links*"))
9806 (setq entry (assoc link org-stored-links))
9807 (or entry (push link org-insert-link-history))
9808 (setq desc (or desc (nth 1 entry)))))
9810 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
9811 (not org-keep-stored-link-after-insertion))
9812 (setq org-stored-links (delq (assoc link org-stored-links)
9813 org-stored-links)))
9815 (when (and (string-match org-plain-link-re link)
9816 (not (string-match org-ts-regexp link)))
9817 ;; URL-like link, normalize the use of angular brackets.
9818 (setq link (org-unbracket-string "<" ">" link)))
9820 ;; Check if we are linking to the current file with a search
9821 ;; option If yes, simplify the link by using only the search
9822 ;; option.
9823 (when (and buffer-file-name
9824 (let ((case-fold-search nil))
9825 (string-match "\\`file:\\(.+?\\)::" link)))
9826 (let ((path (match-string-no-properties 1 link))
9827 (search (substring-no-properties link (match-end 0))))
9828 (save-match-data
9829 (when (equal (file-truename buffer-file-name) (file-truename path))
9830 ;; We are linking to this same file, with a search option
9831 (setq link search)))))
9833 ;; Check if we can/should use a relative path. If yes, simplify
9834 ;; the link.
9835 (let ((case-fold-search nil))
9836 (when (string-match "\\`\\(file\\|docview\\):" link)
9837 (let* ((type (match-string-no-properties 0 link))
9838 (path-start (match-end 0))
9839 (search (and (string-match "::\\(.*\\)\\'" link)
9840 (match-string 1 link)))
9841 (path
9842 (if search
9843 (substring-no-properties
9844 link path-start (match-beginning 0))
9845 (substring-no-properties link (match-end 0))))
9846 (origpath path))
9847 (cond
9848 ((or (eq org-link-file-path-type 'absolute)
9849 (equal complete-file '(16)))
9850 (setq path (abbreviate-file-name (expand-file-name path))))
9851 ((eq org-link-file-path-type 'noabbrev)
9852 (setq path (expand-file-name path)))
9853 ((eq org-link-file-path-type 'relative)
9854 (setq path (file-relative-name path)))
9856 (save-match-data
9857 (if (string-match (concat "^" (regexp-quote
9858 (expand-file-name
9859 (file-name-as-directory
9860 default-directory))))
9861 (expand-file-name path))
9862 ;; We are linking a file with relative path name.
9863 (setq path (substring (expand-file-name path)
9864 (match-end 0)))
9865 (setq path (abbreviate-file-name (expand-file-name path)))))))
9866 (setq link (concat type path (and search (concat "::" search))))
9867 (when (equal desc origpath)
9868 (setq desc path)))))
9870 (unless auto-desc
9871 (let ((initial-input
9872 (cond
9873 (default-description)
9874 ((not org-make-link-description-function) desc)
9875 (t (condition-case nil
9876 (funcall org-make-link-description-function link desc)
9877 (error
9878 (message "Can't get link description from `%s'"
9879 (symbol-name org-make-link-description-function))
9880 (sit-for 2)
9881 nil))))))
9882 (setq desc (if (called-interactively-p 'any)
9883 (read-string "Description: " initial-input)
9884 initial-input))))
9886 (unless (string-match "\\S-" desc) (setq desc nil))
9887 (when remove (apply 'delete-region remove))
9888 (insert (org-make-link-string link desc))
9889 ;; Redisplay so as the new link has proper invisible characters.
9890 (sit-for 0)))
9892 (defun org-link-try-special-completion (type)
9893 "If there is completion support for link type TYPE, offer it."
9894 (let ((fun (org-link-get-parameter type :complete)))
9895 (if (functionp fun)
9896 (funcall fun)
9897 (read-string "Link (no completion support): " (concat type ":")))))
9899 (defun org-file-complete-link (&optional arg)
9900 "Create a file link using completion."
9901 (let ((file (read-file-name "File: "))
9902 (pwd (file-name-as-directory (expand-file-name ".")))
9903 (pwd1 (file-name-as-directory (abbreviate-file-name
9904 (expand-file-name ".")))))
9905 (cond ((equal arg '(16))
9906 (concat "file:"
9907 (abbreviate-file-name (expand-file-name file))))
9908 ((string-match
9909 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9910 (concat "file:" (match-string 1 file)))
9911 ((string-match
9912 (concat "^" (regexp-quote pwd) "\\(.+\\)")
9913 (expand-file-name file))
9914 (concat "file:"
9915 (match-string 1 (expand-file-name file))))
9916 (t (concat "file:" file)))))
9919 ;;; Opening/following a link
9921 (defvar org-link-search-failed nil)
9923 (defvar org-open-link-functions nil
9924 "Hook for functions finding a plain text link.
9925 These functions must take a single argument, the link content.
9926 They will be called for links that look like [[link text][description]]
9927 when LINK TEXT does not have a protocol like \"http:\" and does not look
9928 like a filename (e.g. \"./blue.png\").
9930 These functions will be called *before* Org attempts to resolve the
9931 link by doing text searches in the current buffer - so if you want a
9932 link \"[[target]]\" to still find \"<<target>>\", your function should
9933 handle this as a special case.
9935 When the function does handle the link, it must return a non-nil value.
9936 If it decides that it is not responsible for this link, it must return
9937 nil to indicate that that Org can continue with other options like
9938 exact and fuzzy text search.")
9940 (defun org-next-link (&optional search-backward)
9941 "Move forward to the next link.
9942 If the link is in hidden text, expose it."
9943 (interactive "P")
9944 (when (and org-link-search-failed (eq this-command last-command))
9945 (goto-char (point-min))
9946 (message "Link search wrapped back to beginning of buffer"))
9947 (setq org-link-search-failed nil)
9948 (let* ((pos (point))
9949 (ct (org-context))
9950 (a (assq :link ct))
9951 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9952 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9953 ((looking-at org-any-link-re)
9954 ;; Don't stay stuck at link without an org-link face
9955 (forward-char (if search-backward -1 1))))
9956 (if (funcall srch-fun org-any-link-re nil t)
9957 (progn
9958 (goto-char (match-beginning 0))
9959 (when (org-invisible-p) (org-show-context)))
9960 (goto-char pos)
9961 (setq org-link-search-failed t)
9962 (message "No further link found"))))
9964 (defun org-previous-link ()
9965 "Move backward to the previous link.
9966 If the link is in hidden text, expose it."
9967 (interactive)
9968 (org-next-link t))
9970 (defun org-translate-link (s)
9971 "Translate a link string if a translation function has been defined."
9972 (with-temp-buffer
9973 (insert (org-trim s))
9974 (org-trim (org-element-interpret-data (org-element-context)))))
9976 (defun org-translate-link-from-planner (type path)
9977 "Translate a link from Emacs Planner syntax so that Org can follow it.
9978 This is still an experimental function, your mileage may vary."
9979 (cond
9980 ((member type '("http" "https" "news" "ftp"))
9981 ;; standard Internet links are the same.
9982 nil)
9983 ((and (equal type "irc") (string-match "^//" path))
9984 ;; Planner has two / at the beginning of an irc link, we have 1.
9985 ;; We should have zero, actually....
9986 (setq path (substring path 1)))
9987 ((and (equal type "lisp") (string-match "^/" path))
9988 ;; Planner has a slash, we do not.
9989 (setq type "elisp" path (substring path 1)))
9990 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9991 ;; A typical message link. Planner has the id after the final slash,
9992 ;; we separate it with a hash mark
9993 (setq path (concat (match-string 1 path) "#"
9994 (org-unbracket-string "<" ">" (match-string 2 path))))))
9995 (cons type path))
9997 (defun org-find-file-at-mouse (ev)
9998 "Open file link or URL at mouse."
9999 (interactive "e")
10000 (mouse-set-point ev)
10001 (org-open-at-point 'in-emacs))
10003 (defun org-open-at-mouse (ev)
10004 "Open file link or URL at mouse.
10005 See the docstring of `org-open-file' for details."
10006 (interactive "e")
10007 (mouse-set-point ev)
10008 (when (eq major-mode 'org-agenda-mode)
10009 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10010 (org-open-at-point))
10012 (defvar org-window-config-before-follow-link nil
10013 "The window configuration before following a link.
10014 This is saved in case the need arises to restore it.")
10016 ;;;###autoload
10017 (defun org-open-at-point-global ()
10018 "Follow a link or a time-stamp like Org mode does.
10019 Also follow links and emails as seen by `thing-at-point'.
10020 This command can be called in any mode to follow an external
10021 link or a time-stamp that has Org mode syntax. Its behavior
10022 is undefined when called on internal links like fuzzy links.
10023 Raise a user error when there is nothing to follow."
10024 (interactive)
10025 (let ((tap-url (thing-at-point 'url))
10026 (tap-email (thing-at-point 'email)))
10027 (cond ((org-in-regexp org-any-link-re)
10028 (org-open-link-from-string (match-string-no-properties 0)))
10029 ((or (org-in-regexp org-ts-regexp-both nil t)
10030 (org-in-regexp org-tsr-regexp-both nil t))
10031 (org-follow-timestamp-link))
10032 (tap-url (org-open-link-from-string tap-url))
10033 (tap-email (org-open-link-from-string
10034 (concat "mailto:" tap-email)))
10035 (t (user-error "No link found")))))
10037 ;;;###autoload
10038 (defun org-open-link-from-string (s &optional arg reference-buffer)
10039 "Open a link in the string S, as if it was in Org mode."
10040 (interactive "sLink: \nP")
10041 (let ((reference-buffer (or reference-buffer (current-buffer))))
10042 (with-temp-buffer
10043 (let ((org-inhibit-startup (not reference-buffer)))
10044 (org-mode)
10045 (insert s)
10046 (goto-char (point-min))
10047 (when reference-buffer
10048 (setq org-link-abbrev-alist-local
10049 (with-current-buffer reference-buffer
10050 org-link-abbrev-alist-local)))
10051 (org-open-at-point arg reference-buffer)))))
10053 (defvar org-open-at-point-functions nil
10054 "Hook that is run when following a link at point.
10056 Functions in this hook must return t if they identify and follow
10057 a link at point. If they don't find anything interesting at point,
10058 they must return nil.")
10060 (defvar org-link-search-inhibit-query nil)
10061 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10062 (defun org--open-doi-link (path)
10063 "Open a \"doi\" type link.
10064 PATH is a the path to search for, as a string."
10065 (browse-url (url-encode-url (concat org-doi-server-url path))))
10067 (defun org--open-elisp-link (path)
10068 "Open a \"elisp\" type link.
10069 PATH is the sexp to evaluate, as a string."
10070 (let ((cmd path))
10071 (if (or (and (org-string-nw-p
10072 org-confirm-elisp-link-not-regexp)
10073 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10074 (not org-confirm-elisp-link-function)
10075 (funcall org-confirm-elisp-link-function
10076 (format "Execute \"%s\" as elisp? "
10077 (org-add-props cmd nil 'face 'org-warning))))
10078 (message "%s => %s" cmd
10079 (if (eq (string-to-char cmd) ?\()
10080 (eval (read cmd))
10081 (call-interactively (read cmd))))
10082 (user-error "Abort"))))
10084 (defun org--open-help-link (path)
10085 "Open a \"help\" type link.
10086 PATH is a symbol name, as a string."
10087 (pcase (intern path)
10088 ((and (pred fboundp) variable) (describe-function variable))
10089 ((and (pred boundp) function) (describe-variable function))
10090 (name (user-error "Unknown function or variable: %s" name))))
10092 (defun org--open-shell-link (path)
10093 "Open a \"shell\" type link.
10094 PATH is the command to execute, as a string."
10095 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10096 (cmd path))
10097 (if (or (and (org-string-nw-p
10098 org-confirm-shell-link-not-regexp)
10099 (string-match
10100 org-confirm-shell-link-not-regexp cmd))
10101 (not org-confirm-shell-link-function)
10102 (funcall org-confirm-shell-link-function
10103 (format "Execute \"%s\" in shell? "
10104 (org-add-props cmd nil
10105 'face 'org-warning))))
10106 (progn
10107 (message "Executing %s" cmd)
10108 (shell-command cmd buf)
10109 (when (featurep 'midnight)
10110 (setq clean-buffer-list-kill-buffer-names
10111 (cons (buffer-name buf)
10112 clean-buffer-list-kill-buffer-names))))
10113 (user-error "Abort"))))
10115 (defun org-open-at-point (&optional arg reference-buffer)
10116 "Open link, timestamp, footnote or tags at point.
10118 When point is on a link, follow it. Normally, files will be
10119 opened by an appropriate application. If the optional prefix
10120 argument ARG is non-nil, Emacs will visit the file. With
10121 a double prefix argument, try to open outside of Emacs, in the
10122 application the system uses for this file type.
10124 When point is on a timestamp, open the agenda at the day
10125 specified.
10127 When point is a footnote definition, move to the first reference
10128 found. If it is on a reference, move to the associated
10129 definition.
10131 When point is on a headline, display a list of every link in the
10132 entry, so it is possible to pick one, or all, of them. If point
10133 is on a tag, call `org-tags-view' instead.
10135 When optional argument REFERENCE-BUFFER is non-nil, it should
10136 specify a buffer from where the link search should happen. This
10137 is used internally by `org-open-link-from-string'.
10139 On top of syntactically correct links, this function also tries
10140 to open links and time-stamps in comments, node properties, and
10141 keywords if point is on something looking like a timestamp or
10142 a link."
10143 (interactive "P")
10144 (org-load-modules-maybe)
10145 (setq org-window-config-before-follow-link (current-window-configuration))
10146 (org-remove-occur-highlights nil nil t)
10147 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10148 (let* ((context
10149 ;; Only consider supported types, even if they are not the
10150 ;; closest one.
10151 (org-element-lineage
10152 (org-element-context)
10153 '(clock comment comment-block footnote-definition
10154 footnote-reference headline inline-src-block inlinetask
10155 keyword link node-property src-block timestamp)
10157 (type (org-element-type context))
10158 (value (org-element-property :value context)))
10159 (cond
10160 ((not type) (user-error "No link found"))
10161 ;; No valid link at point. For convenience, look if something
10162 ;; looks like a link under point in some specific places.
10163 ((memq type '(comment comment-block node-property keyword))
10164 (call-interactively #'org-open-at-point-global))
10165 ;; On a headline or an inlinetask, but not on a timestamp,
10166 ;; a link, a footnote reference.
10167 ((memq type '(headline inlinetask))
10168 (org-match-line org-complex-heading-regexp)
10169 (if (and (match-beginning 5)
10170 (>= (point) (match-beginning 5))
10171 (< (point) (match-end 5)))
10172 ;; On tags.
10173 (org-tags-view arg (substring (match-string 5) 0 -1))
10174 ;; Not on tags.
10175 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10176 (`(nil . ,_)
10177 (require 'org-attach)
10178 (org-attach-reveal 'if-exists))
10179 (`(,links . ,links-end)
10180 (dolist (link (if (stringp links) (list links) links))
10181 (search-forward link nil links-end)
10182 (goto-char (match-beginning 0))
10183 (org-open-at-point))))))
10184 ;; On a footnote reference or at definition's label.
10185 ((or (eq type 'footnote-reference)
10186 (and (eq type 'footnote-definition)
10187 (save-excursion
10188 ;; Do not validate action when point is on the
10189 ;; spaces right after the footnote label, in order
10190 ;; to be on par with behavior on links.
10191 (skip-chars-forward " \t")
10192 (let ((begin
10193 (org-element-property :contents-begin context)))
10194 (if begin (< (point) begin)
10195 (= (org-element-property :post-affiliated context)
10196 (line-beginning-position)))))))
10197 (org-footnote-action))
10198 ;; On a clock line, make sure point is on the timestamp
10199 ;; before opening it.
10200 ((and (eq type 'clock)
10201 value
10202 (>= (point) (org-element-property :begin value))
10203 (<= (point) (org-element-property :end value)))
10204 (org-follow-timestamp-link))
10205 ((eq type 'src-block) (org-babel-open-src-block-result))
10206 ;; Do nothing on white spaces after an object.
10207 ((>= (point)
10208 (save-excursion
10209 (goto-char (org-element-property :end context))
10210 (skip-chars-backward " \t")
10211 (point)))
10212 (user-error "No link found"))
10213 ((eq type 'inline-src-block) (org-babel-open-src-block-result))
10214 ((eq type 'timestamp) (org-follow-timestamp-link))
10215 ((eq type 'link)
10216 (let ((type (org-element-property :type context))
10217 (path (org-link-unescape (org-element-property :path context))))
10218 ;; Switch back to REFERENCE-BUFFER needed when called in
10219 ;; a temporary buffer through `org-open-link-from-string'.
10220 (with-current-buffer (or reference-buffer (current-buffer))
10221 (cond
10222 ((equal type "file")
10223 (if (string-match "[*?{]" (file-name-nondirectory path))
10224 (dired path)
10225 ;; Look into `org-link-parameters' in order to find
10226 ;; a DEDICATED-FUNCTION to open file. The function
10227 ;; will be applied on raw link instead of parsed link
10228 ;; due to the limitation in `org-add-link-type'
10229 ;; ("open" function called with a single argument).
10230 ;; If no such function is found, fallback to
10231 ;; `org-open-file'.
10232 (let* ((option (org-element-property :search-option context))
10233 (app (org-element-property :application context))
10234 (dedicated-function
10235 (org-link-get-parameter
10236 (if app (concat type "+" app) type)
10237 :follow)))
10238 (if dedicated-function
10239 (funcall dedicated-function
10240 (concat path
10241 (and option (concat "::" option))))
10242 (apply #'org-open-file
10243 path
10244 (cond (arg)
10245 ((equal app "emacs") 'emacs)
10246 ((equal app "sys") 'system))
10247 (cond ((not option) nil)
10248 ((string-match-p "\\`[0-9]+\\'" option)
10249 (list (string-to-number option)))
10250 (t (list nil
10251 (org-link-unescape option)))))))))
10252 ((functionp (org-link-get-parameter type :follow))
10253 (funcall (org-link-get-parameter type :follow) path))
10254 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10255 (unless (run-hook-with-args-until-success
10256 'org-open-link-functions path)
10257 (if (not arg) (org-mark-ring-push)
10258 (switch-to-buffer-other-window
10259 (org-get-buffer-for-internal-link (current-buffer))))
10260 (let ((destination
10261 (org-with-wide-buffer
10262 (if (equal type "radio")
10263 (org-search-radio-target
10264 (org-element-property :path context))
10265 (org-link-search
10266 (if (member type '("custom-id" "coderef"))
10267 (org-element-property :raw-link context)
10268 path)
10269 ;; Prevent fuzzy links from matching
10270 ;; themselves.
10271 (and (equal type "fuzzy")
10272 (+ 2 (org-element-property :begin context)))))
10273 (point))))
10274 (unless (and (<= (point-min) destination)
10275 (>= (point-max) destination))
10276 (widen))
10277 (goto-char destination))))
10278 (t (browse-url-at-point))))))
10279 (t (user-error "No link found")))))
10280 (run-hook-with-args 'org-follow-link-hook))
10282 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10283 "Offer links in the current entry and return the selected link.
10284 If there is only one link, return it.
10285 If NTH is an integer, return the NTH link found.
10286 If ZERO is a string, check also this string for a link, and if
10287 there is one, return it."
10288 (with-current-buffer buffer
10289 (org-with-wide-buffer
10290 (goto-char marker)
10291 (let ((cnt ?0)
10292 have-zero end links link c)
10293 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10294 (push (match-string 0 zero) links)
10295 (setq cnt (1- cnt) have-zero t))
10296 (save-excursion
10297 (org-back-to-heading t)
10298 (setq end (save-excursion (outline-next-heading) (point)))
10299 (while (re-search-forward org-any-link-re end t)
10300 (push (match-string 0) links))
10301 (setq links (org-uniquify (reverse links))))
10302 (cond
10303 ((null links)
10304 (message "No links"))
10305 ((equal (length links) 1)
10306 (setq link (car links)))
10307 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10308 (setq link (nth (if have-zero nth (1- nth)) links)))
10309 (t ; we have to select a link
10310 (save-excursion
10311 (save-window-excursion
10312 (delete-other-windows)
10313 (with-output-to-temp-buffer "*Select Link*"
10314 (dolist (l links)
10315 (cond
10316 ((not (string-match org-bracket-link-regexp l))
10317 (princ (format "[%c] %s\n" (cl-incf cnt)
10318 (org-unbracket-string "<" ">" l))))
10319 ((match-end 3)
10320 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10321 (match-string 3 l) (match-string 1 l))))
10322 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10323 (match-string 1 l)))))))
10324 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10325 (message "Select link to open, RET to open all:")
10326 (setq c (read-char-exclusive))
10327 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10328 (when (equal c ?q) (user-error "Abort"))
10329 (if (equal c ?\C-m)
10330 (setq link links)
10331 (setq nth (- c ?0))
10332 (when have-zero (setq nth (1+ nth)))
10333 (unless (and (integerp nth) (>= (length links) nth))
10334 (user-error "Invalid link selection"))
10335 (setq link (nth (1- nth) links)))))
10336 (cons link end)))))
10338 ;; TODO: These functions are deprecated since `org-open-at-point'
10339 ;; hard-codes behavior for "file+emacs" and "file+sys" types.
10340 (defun org-open-file-with-system (path)
10341 "Open file at PATH using the system way of opening it."
10342 (org-open-file path 'system))
10343 (defun org-open-file-with-emacs (path)
10344 "Open file at PATH in Emacs."
10345 (org-open-file path 'emacs))
10348 ;;; File search
10350 (defvar org-create-file-search-functions nil
10351 "List of functions to construct the right search string for a file link.
10352 These functions are called in turn with point at the location to
10353 which the link should point.
10355 A function in the hook should first test if it would like to
10356 handle this file type, for example by checking the `major-mode'
10357 or the file extension. If it decides not to handle this file, it
10358 should just return nil to give other functions a chance. If it
10359 does handle the file, it must return the search string to be used
10360 when following the link. The search string will be part of the
10361 file link, given after a double colon, and `org-open-at-point'
10362 will automatically search for it. If special measures must be
10363 taken to make the search successful, another function should be
10364 added to the companion hook `org-execute-file-search-functions',
10365 which see.
10367 A function in this hook may also use `setq' to set the variable
10368 `description' to provide a suggestion for the descriptive text to
10369 be used for this link when it gets inserted into an Org buffer
10370 with \\[org-insert-link].")
10372 (defvar org-execute-file-search-functions nil
10373 "List of functions to execute a file search triggered by a link.
10375 Functions added to this hook must accept a single argument, the
10376 search string that was part of the file link, the part after the
10377 double colon. The function must first check if it would like to
10378 handle this search, for example by checking the `major-mode' or
10379 the file extension. If it decides not to handle this search, it
10380 should just return nil to give other functions a chance. If it
10381 does handle the search, it must return a non-nil value to keep
10382 other functions from trying.
10384 Each function can access the current prefix argument through the
10385 variable `current-prefix-arg'. Note that a single prefix is used
10386 to force opening a link in Emacs, so it may be good to only use a
10387 numeric or double prefix to guide the search function.
10389 In case this is needed, a function in this hook can also restore
10390 the window configuration before `org-open-at-point' was called using:
10392 (set-window-configuration org-window-config-before-follow-link)")
10394 (defun org-search-radio-target (target)
10395 "Search a radio target matching TARGET in current buffer.
10396 White spaces are not significant."
10397 (let ((re (format "<<<%s>>>"
10398 (mapconcat #'regexp-quote
10399 (split-string target)
10400 "[ \t]+\\(?:\n[ \t]*\\)?")))
10401 (origin (point)))
10402 (goto-char (point-min))
10403 (catch :radio-match
10404 (while (re-search-forward re nil t)
10405 (backward-char)
10406 (let ((object (org-element-context)))
10407 (when (eq (org-element-type object) 'radio-target)
10408 (goto-char (org-element-property :begin object))
10409 (org-show-context 'link-search)
10410 (throw :radio-match nil))))
10411 (goto-char origin)
10412 (user-error "No match for radio target: %s" target))))
10414 (defun org-link-search (s &optional avoid-pos stealth)
10415 "Search for a search string S.
10417 If S starts with \"#\", it triggers a custom ID search.
10419 If S is enclosed within parenthesis, it initiates a coderef
10420 search.
10422 If S is surrounded by forward slashes, it is interpreted as
10423 a regular expression. In Org mode files, this will create an
10424 `org-occur' sparse tree. In ordinary files, `occur' will be used
10425 to list matches. If the current buffer is in `dired-mode', grep
10426 will be used to search in all files.
10428 When AVOID-POS is given, ignore matches near that position.
10430 When optional argument STEALTH is non-nil, do not modify
10431 visibility around point, thus ignoring `org-show-context-detail'
10432 variable.
10434 Search is case-insensitive and ignores white spaces. Return type
10435 of matched result, which is either `dedicated' or `fuzzy'."
10436 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10437 (let* ((case-fold-search t)
10438 (origin (point))
10439 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10440 (starred (eq (string-to-char normalized) ?*))
10441 (words (split-string (if starred (substring s 1) s)))
10442 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10443 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10444 type)
10445 (cond
10446 ;; Check if there are any special search functions.
10447 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10448 ((eq (string-to-char s) ?#)
10449 ;; Look for a custom ID S if S starts with "#".
10450 (let* ((id (substring normalized 1))
10451 (match (org-find-property "CUSTOM_ID" id)))
10452 (if match (progn (goto-char match) (setf type 'dedicated))
10453 (error "No match for custom ID: %s" id))))
10454 ((string-match "\\`(\\(.*\\))\\'" normalized)
10455 ;; Look for coderef targets if S is enclosed within parenthesis.
10456 (let ((coderef (match-string-no-properties 1 normalized))
10457 (re (substring s-single-re 1 -1)))
10458 (goto-char (point-min))
10459 (catch :coderef-match
10460 (while (re-search-forward re nil t)
10461 (let ((element (org-element-at-point)))
10462 (when (and (memq (org-element-type element)
10463 '(example-block src-block))
10464 ;; Build proper regexp according to current
10465 ;; block's label format.
10466 (let ((label-fmt
10467 (regexp-quote
10468 (or (org-element-property :label-fmt element)
10469 org-coderef-label-format))))
10470 (save-excursion
10471 (beginning-of-line)
10472 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10473 (format label-fmt coderef))))))
10474 (setq type 'dedicated)
10475 (goto-char (match-beginning 1))
10476 (throw :coderef-match nil))))
10477 (goto-char origin)
10478 (error "No match for coderef: %s" coderef))))
10479 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10480 ;; Look for a regular expression.
10481 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10482 (match-string 1 s)))
10483 ;; From here, we handle fuzzy links.
10485 ;; Look for targets, only if not in a headline search.
10486 ((and (not starred)
10487 (let ((target (format "<<%s>>" s-multi-re)))
10488 (catch :target-match
10489 (goto-char (point-min))
10490 (while (re-search-forward target nil t)
10491 (backward-char)
10492 (let ((context (org-element-context)))
10493 (when (eq (org-element-type context) 'target)
10494 (setq type 'dedicated)
10495 (goto-char (org-element-property :begin context))
10496 (throw :target-match t))))
10497 nil))))
10498 ;; Look for elements named after S, only if not in a headline
10499 ;; search.
10500 ((and (not starred)
10501 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10502 (catch :name-match
10503 (goto-char (point-min))
10504 (while (re-search-forward name nil t)
10505 (let ((element (org-element-at-point)))
10506 (when (equal words
10507 (split-string
10508 (org-element-property :name element)))
10509 (setq type 'dedicated)
10510 (beginning-of-line)
10511 (throw :name-match t))))
10512 nil))))
10513 ;; Regular text search. Prefer headlines in Org mode buffers.
10514 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10515 ;; statistics cookies and tags.
10516 ((and (derived-mode-p 'org-mode)
10517 (let ((title-re
10518 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10519 org-outline-regexp-bol
10520 org-comment-string
10521 (mapconcat #'regexp-quote words ".+")))
10522 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10523 (comment-re (eval-when-compile
10524 (format "\\`%s[ \t]+" org-comment-string))))
10525 (goto-char (point-min))
10526 (catch :found
10527 (while (re-search-forward title-re nil t)
10528 (when (equal words
10529 (split-string
10530 (replace-regexp-in-string
10531 cookie-re ""
10532 (replace-regexp-in-string
10533 comment-re "" (org-get-heading t t t)))))
10534 (throw :found t)))
10535 nil)))
10536 (beginning-of-line)
10537 (setq type 'dedicated))
10538 ;; Offer to create non-existent headline depending on
10539 ;; `org-link-search-must-match-exact-headline'.
10540 ((and (derived-mode-p 'org-mode)
10541 (not org-link-search-inhibit-query)
10542 (eq org-link-search-must-match-exact-headline 'query-to-create)
10543 (yes-or-no-p "No match - create this as a new heading? "))
10544 (goto-char (point-max))
10545 (unless (bolp) (newline))
10546 (org-insert-heading nil t t)
10547 (insert s "\n")
10548 (beginning-of-line 0))
10549 ;; Only headlines are looked after. No need to process
10550 ;; further: throw an error.
10551 ((and (derived-mode-p 'org-mode)
10552 (or starred org-link-search-must-match-exact-headline))
10553 (goto-char origin)
10554 (error "No match for fuzzy expression: %s" normalized))
10555 ;; Regular text search.
10556 ((catch :fuzzy-match
10557 (goto-char (point-min))
10558 (while (re-search-forward s-multi-re nil t)
10559 ;; Skip match if it contains AVOID-POS or it is included in
10560 ;; a link with a description but outside the description.
10561 (unless (or (and avoid-pos
10562 (<= (match-beginning 0) avoid-pos)
10563 (> (match-end 0) avoid-pos))
10564 (and (save-match-data
10565 (org-in-regexp org-bracket-link-regexp))
10566 (match-beginning 3)
10567 (or (> (match-beginning 3) (point))
10568 (<= (match-end 3) (point)))
10569 (org-element-lineage
10570 (save-match-data (org-element-context))
10571 '(link) t)))
10572 (goto-char (match-beginning 0))
10573 (setq type 'fuzzy)
10574 (throw :fuzzy-match t)))
10575 nil))
10576 ;; All failed. Throw an error.
10577 (t (goto-char origin)
10578 (error "No match for fuzzy expression: %s" normalized)))
10579 ;; Disclose surroundings of match, if appropriate.
10580 (when (and (derived-mode-p 'org-mode) (not stealth))
10581 (org-show-context 'link-search))
10582 type))
10584 (defun org-get-buffer-for-internal-link (buffer)
10585 "Return a buffer to be used for displaying the link target of internal links."
10586 (cond
10587 ((not org-display-internal-link-with-indirect-buffer)
10588 buffer)
10589 ((string-suffix-p "(Clone)" (buffer-name buffer))
10590 (message "Buffer is already a clone, not making another one")
10591 ;; we also do not modify visibility in this case
10592 buffer)
10593 (t ; make a new indirect buffer for displaying the link
10594 (let* ((bn (buffer-name buffer))
10595 (ibn (concat bn "(Clone)"))
10596 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10597 (with-current-buffer ib (org-overview))
10598 ib))))
10600 (defun org-do-occur (regexp &optional cleanup)
10601 "Call the Emacs command `occur'.
10602 If CLEANUP is non-nil, remove the printout of the regular expression
10603 in the *Occur* buffer. This is useful if the regex is long and not useful
10604 to read."
10605 (occur regexp)
10606 (when cleanup
10607 (let ((cwin (selected-window)) win beg end)
10608 (when (setq win (get-buffer-window "*Occur*"))
10609 (select-window win))
10610 (goto-char (point-min))
10611 (when (re-search-forward "match[a-z]+" nil t)
10612 (setq beg (match-end 0))
10613 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
10614 (setq end (1- (match-beginning 0)))))
10615 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10616 (goto-char (point-min))
10617 (select-window cwin))))
10620 ;;; The Mark Ring
10622 (defvar org-mark-ring nil
10623 "Mark ring for positions before jumps in Org mode.")
10625 (defvar org-mark-ring-last-goto nil
10626 "Last position in the mark ring used to go back.")
10628 ;; Fill and close the ring
10629 (setq org-mark-ring nil)
10630 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
10632 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
10633 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10634 org-mark-ring)
10636 (defun org-mark-ring-push (&optional pos buffer)
10637 "Put the current position into the mark ring and rotate it.
10638 Also push position into the Emacs mark ring. If optional
10639 argument POS and BUFFER are not nil, mark this location instead."
10640 (interactive)
10641 (let ((pos (or pos (point)))
10642 (buffer (or buffer (current-buffer))))
10643 (with-current-buffer buffer
10644 (org-with-point-at pos (push-mark nil t)))
10645 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10646 (move-marker (car org-mark-ring) pos buffer))
10647 (message
10648 (substitute-command-keys
10649 "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
10651 (defun org-mark-ring-goto (&optional n)
10652 "Jump to the previous position in the mark ring.
10653 With prefix arg N, jump back that many stored positions. When
10654 called several times in succession, walk through the entire ring.
10655 Org mode commands jumping to a different position in the current file,
10656 or to another Org file, automatically push the old position onto the ring."
10657 (interactive "p")
10658 (let (p m)
10659 (if (eq last-command this-command)
10660 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10661 (setq p org-mark-ring))
10662 (setq org-mark-ring-last-goto p)
10663 (setq m (car p))
10664 (pop-to-buffer-same-window (marker-buffer m))
10665 (goto-char m)
10666 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10668 (defun org-add-angle-brackets (s)
10669 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
10670 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
10673 ;;; Following specific links
10675 (defvar org-agenda-buffer-tmp-name)
10676 (defvar org-agenda-start-on-weekday)
10677 (defun org-follow-timestamp-link ()
10678 "Open an agenda view for the time-stamp date/range at point."
10679 (cond
10680 ((org-at-date-range-p t)
10681 (let ((org-agenda-start-on-weekday)
10682 (t1 (match-string 1))
10683 (t2 (match-string 2)) tt1 tt2)
10684 (setq tt1 (time-to-days (org-time-string-to-time t1))
10685 tt2 (time-to-days (org-time-string-to-time t2)))
10686 (let ((org-agenda-buffer-tmp-name
10687 (format "*Org Agenda(a:%s)"
10688 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10689 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10690 ((org-at-timestamp-p 'lax)
10691 (let ((org-agenda-buffer-tmp-name
10692 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10693 (org-agenda-list nil (time-to-days (org-time-string-to-time
10694 (substring (match-string 1) 0 10)))
10695 1)))
10696 (t (error "This should not happen"))))
10699 ;;; Following file links
10700 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10701 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10702 (declare-function mailcap-mime-info
10703 "mailcap" (string &optional request no-decode))
10704 (defvar org-wait nil)
10705 (defun org-open-file (path &optional in-emacs line search)
10706 "Open the file at PATH.
10707 First, this expands any special file name abbreviations. Then the
10708 configuration variable `org-file-apps' is checked if it contains an
10709 entry for this file type, and if yes, the corresponding command is launched.
10711 If no application is found, Emacs simply visits the file.
10713 With optional prefix argument IN-EMACS, Emacs will visit the file.
10714 With a double \\[universal-argument] \\[universal-argument] \
10715 prefix arg, Org tries to avoid opening in Emacs
10716 and to use an external application to visit the file.
10718 Optional LINE specifies a line to go to, optional SEARCH a string
10719 to search for. If LINE or SEARCH is given, the file will be
10720 opened in Emacs, unless an entry from org-file-apps that makes
10721 use of groups in a regexp matches.
10723 If you want to change the way frames are used when following a
10724 link, please customize `org-link-frame-setup'.
10726 If the file does not exist, an error is thrown."
10727 (let* ((file (if (equal path "")
10728 buffer-file-name
10729 (substitute-in-file-name (expand-file-name path))))
10730 (file-apps (append org-file-apps (org-default-apps)))
10731 (apps (cl-remove-if
10732 'org-file-apps-entry-match-against-dlink-p file-apps))
10733 (apps-dlink (cl-remove-if-not
10734 'org-file-apps-entry-match-against-dlink-p file-apps))
10735 (remp (and (assq 'remote apps) (file-remote-p file)))
10736 (dirp (unless remp (file-directory-p file)))
10737 (file (if (and dirp org-open-directory-means-index-dot-org)
10738 (concat (file-name-as-directory file) "index.org")
10739 file))
10740 (a-m-a-p (assq 'auto-mode apps))
10741 (dfile (downcase file))
10742 ;; Reconstruct the original link from the PATH, LINE and
10743 ;; SEARCH args.
10744 (link (cond (line (concat file "::" (number-to-string line)))
10745 (search (concat file "::" search))
10746 (t file)))
10747 (dlink (downcase link))
10748 (ext
10749 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
10750 (match-string 1 dfile)))
10751 (save-position-maybe
10752 (let ((old-buffer (current-buffer))
10753 (old-pos (point))
10754 (old-mode major-mode))
10755 (lambda ()
10756 (and (derived-mode-p 'org-mode)
10757 (eq old-mode 'org-mode)
10758 (or (not (eq old-buffer (current-buffer)))
10759 (not (eq old-pos (point))))
10760 (org-mark-ring-push old-pos old-buffer)))))
10761 cmd link-match-data)
10762 (cond
10763 ((member in-emacs '((16) system))
10764 (setq cmd (cdr (assq 'system apps))))
10765 (in-emacs (setq cmd 'emacs))
10767 (setq cmd (or (and remp (cdr (assq 'remote apps)))
10768 (and dirp (cdr (assq 'directory apps)))
10769 ;; First, try matching against apps-dlink if we
10770 ;; get a match here, store the match data for
10771 ;; later.
10772 (let ((match (assoc-default dlink apps-dlink
10773 'string-match)))
10774 (if match
10775 (progn (setq link-match-data (match-data))
10776 match)
10777 (progn (setq in-emacs (or in-emacs line search))
10778 nil))) ; if we have no match in apps-dlink,
10779 ; always open the file in emacs if line or search
10780 ; is given (for backwards compatibility)
10781 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10782 'string-match)
10783 (cdr (assoc ext apps))
10784 (cdr (assq t apps))))))
10785 (when (eq cmd 'system)
10786 (setq cmd (cdr (assq 'system apps))))
10787 (when (eq cmd 'default)
10788 (setq cmd (cdr (assoc t apps))))
10789 (when (eq cmd 'mailcap)
10790 (require 'mailcap)
10791 (mailcap-parse-mailcaps)
10792 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10793 (command (mailcap-mime-info mime-type)))
10794 (if (stringp command)
10795 (setq cmd command)
10796 (setq cmd 'emacs))))
10797 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10798 (not (file-exists-p file))
10799 (not org-open-non-existing-files))
10800 (user-error "No such file: %s" file))
10801 (cond
10802 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10803 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10804 (while (string-match "['\"]%s['\"]" cmd)
10805 (setq cmd (replace-match "%s" t t cmd)))
10806 (setq cmd (replace-regexp-in-string
10807 "%s"
10808 (shell-quote-argument (convert-standard-filename file))
10810 nil t))
10812 ;; Replace "%1", "%2" etc. in command with group matches from regex
10813 (save-match-data
10814 (let ((match-index 1)
10815 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10816 (set-match-data link-match-data)
10817 (while (<= match-index number-of-groups)
10818 (let ((regex (concat "%" (number-to-string match-index)))
10819 (replace-with (match-string match-index dlink)))
10820 (while (string-match regex cmd)
10821 (setq cmd (replace-match replace-with t t cmd))))
10822 (setq match-index (+ match-index 1)))))
10824 (save-window-excursion
10825 (message "Running %s...done" cmd)
10826 (start-process-shell-command cmd nil cmd)
10827 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10828 ((or (stringp cmd)
10829 (eq cmd 'emacs))
10830 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10831 (widen)
10832 (cond (line (org-goto-line line)
10833 (when (derived-mode-p 'org-mode) (org-reveal)))
10834 (search (condition-case err
10835 (org-link-search search)
10836 ;; Save position before error-ing out so user
10837 ;; can easily move back to the original buffer.
10838 (error (funcall save-position-maybe)
10839 (error (nth 1 err)))))))
10840 ((functionp cmd)
10841 (save-match-data
10842 (set-match-data link-match-data)
10843 (condition-case nil
10844 (funcall cmd file link)
10845 ;; FIXME: Remove this check when most default installations
10846 ;; of Emacs have at least Org 9.0.
10847 ((debug wrong-number-of-arguments wrong-type-argument
10848 invalid-function)
10849 (user-error "Please see Org News for version 9.0 about \
10850 `org-file-apps'--Lisp error: %S" cmd)))))
10851 ((consp cmd)
10852 ;; FIXME: Remove this check when most default installations of
10853 ;; Emacs have at least Org 9.0. Heads-up instead of silently
10854 ;; fall back to `org-link-frame-setup' for an old usage of
10855 ;; `org-file-apps' with sexp instead of a function for `cmd'.
10856 (user-error "Please see Org News for version 9.0 about \
10857 `org-file-apps'--Error: Deprecated usage of %S" cmd))
10858 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10859 (funcall save-position-maybe)))
10861 (defun org-file-apps-entry-match-against-dlink-p (entry)
10862 "This function returns non-nil if `entry' uses a regular
10863 expression which should be matched against the whole link by
10864 org-open-file.
10866 It assumes that is the case when the entry uses a regular
10867 expression which has at least one grouping construct and the
10868 action is either a lisp form or a command string containing
10869 `%1', i.e. using at least one subexpression match as a
10870 parameter."
10871 (let ((selector (car entry))
10872 (action (cdr entry)))
10873 (if (stringp selector)
10874 (and (> (regexp-opt-depth selector) 0)
10875 (or (and (stringp action)
10876 (string-match "%[0-9]" action))
10877 (consp action)))
10878 nil)))
10880 (defun org-default-apps ()
10881 "Return the default applications for this operating system."
10882 (cond
10883 ((eq system-type 'darwin)
10884 org-file-apps-defaults-macosx)
10885 ((eq system-type 'windows-nt)
10886 org-file-apps-defaults-windowsnt)
10887 (t org-file-apps-defaults-gnu)))
10889 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10890 "Convert extensions to regular expressions in the cars of LIST.
10891 Also, weed out any non-string entries, because the return value is used
10892 only for regexp matching.
10893 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10894 point to the symbol `emacs', indicating that the file should
10895 be opened in Emacs."
10896 (append
10897 (delq nil
10898 (mapcar (lambda (x)
10899 (unless (not (stringp (car x)))
10900 (if (string-match "\\W" (car x))
10902 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10903 list))
10904 (when add-auto-mode
10905 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10908 ;;;; Refiling
10910 (defun org-get-org-file ()
10911 "Read a filename, with default directory `org-directory'."
10912 (let ((default (or org-default-notes-file remember-data-file)))
10913 (read-file-name (format "File name [%s]: " default)
10914 (file-name-as-directory org-directory)
10915 default)))
10917 (defun org-notes-order-reversed-p ()
10918 "Check if the current file should receive notes in reversed order."
10919 (cond
10920 ((not org-reverse-note-order) nil)
10921 ((eq t org-reverse-note-order) t)
10922 ((not (listp org-reverse-note-order)) nil)
10923 (t (catch 'exit
10924 (dolist (entry org-reverse-note-order)
10925 (when (string-match (car entry) buffer-file-name)
10926 (throw 'exit (cdr entry))))))))
10928 (defvar org-refile-target-table nil
10929 "The list of refile targets, created by `org-refile'.")
10931 (defvar org-agenda-new-buffers nil
10932 "Buffers created to visit agenda files.")
10934 (defvar org-refile-cache nil
10935 "Cache for refile targets.")
10937 (defvar org-refile-markers nil
10938 "All the markers used for caching refile locations.")
10940 (defun org-refile-marker (pos)
10941 "Get a new refile marker, but only if caching is in use."
10942 (if (not org-refile-use-cache)
10944 (let ((m (make-marker)))
10945 (move-marker m pos)
10946 (push m org-refile-markers)
10947 m)))
10949 (defun org-refile-cache-clear ()
10950 "Clear the refile cache and disable all the markers."
10951 (dolist (m org-refile-markers) (move-marker m nil))
10952 (setq org-refile-markers nil)
10953 (setq org-refile-cache nil)
10954 (message "Refile cache has been cleared"))
10956 (defun org-refile-cache-check-set (set)
10957 "Check if all the markers in the cache still have live buffers."
10958 (let (marker)
10959 (catch 'exit
10960 (while (and set (setq marker (nth 3 (pop set))))
10961 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
10962 (when (and marker (null (marker-buffer marker)))
10963 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
10964 (sit-for 3)
10965 (throw 'exit nil)))
10966 t)))
10968 (defun org-refile-cache-put (set &rest identifiers)
10969 "Push the refile targets SET into the cache, under IDENTIFIERS."
10970 (let* ((key (sha1 (prin1-to-string identifiers)))
10971 (entry (assoc key org-refile-cache)))
10972 (if entry
10973 (setcdr entry set)
10974 (push (cons key set) org-refile-cache))))
10976 (defun org-refile-cache-get (&rest identifiers)
10977 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10978 (cond
10979 ((not org-refile-cache) nil)
10980 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10982 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10983 org-refile-cache))))
10984 (and set (org-refile-cache-check-set set) set)))))
10986 (defvar org-outline-path-cache nil
10987 "Alist between buffer positions and outline paths.
10988 It value is an alist (POSITION . PATH) where POSITION is the
10989 buffer position at the beginning of an entry and PATH is a list
10990 of strings describing the outline path for that entry, in reverse
10991 order.")
10993 (defun org-refile-get-targets (&optional default-buffer)
10994 "Produce a table with refile targets."
10995 (let ((case-fold-search nil)
10996 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10997 (entries (or org-refile-targets '((nil . (:level . 1)))))
10998 targets tgs files desc descre)
10999 (message "Getting targets...")
11000 (with-current-buffer (or default-buffer (current-buffer))
11001 (dolist (entry entries)
11002 (setq files (car entry) desc (cdr entry))
11003 (cond
11004 ((null files) (setq files (list (current-buffer))))
11005 ((eq files 'org-agenda-files)
11006 (setq files (org-agenda-files 'unrestricted)))
11007 ((and (symbolp files) (fboundp files))
11008 (setq files (funcall files)))
11009 ((and (symbolp files) (boundp files))
11010 (setq files (symbol-value files))))
11011 (when (stringp files) (setq files (list files)))
11012 (cond
11013 ((eq (car desc) :tag)
11014 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11015 ((eq (car desc) :todo)
11016 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11017 ((eq (car desc) :regexp)
11018 (setq descre (cdr desc)))
11019 ((eq (car desc) :level)
11020 (setq descre (concat "^\\*\\{" (number-to-string
11021 (if org-odd-levels-only
11022 (1- (* 2 (cdr desc)))
11023 (cdr desc)))
11024 "\\}[ \t]")))
11025 ((eq (car desc) :maxlevel)
11026 (setq descre (concat "^\\*\\{1," (number-to-string
11027 (if org-odd-levels-only
11028 (1- (* 2 (cdr desc)))
11029 (cdr desc)))
11030 "\\}[ \t]")))
11031 (t (error "Bad refiling target description %s" desc)))
11032 (dolist (f files)
11033 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11035 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11036 (progn
11037 (when (bufferp f)
11038 (setq f (buffer-file-name (buffer-base-buffer f))))
11039 (setq f (and f (expand-file-name f)))
11040 (when (eq org-refile-use-outline-path 'file)
11041 (push (list (file-name-nondirectory f) f nil nil) tgs))
11042 (when (eq org-refile-use-outline-path 'buffer-name)
11043 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11044 (when (eq org-refile-use-outline-path 'full-file-path)
11045 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11046 (org-with-wide-buffer
11047 (goto-char (point-min))
11048 (setq org-outline-path-cache nil)
11049 (while (re-search-forward descre nil t)
11050 (beginning-of-line)
11051 (let ((case-fold-search nil))
11052 (looking-at org-complex-heading-regexp))
11053 (let ((begin (point))
11054 (heading (match-string-no-properties 4)))
11055 (unless (or (and
11056 org-refile-target-verify-function
11057 (not
11058 (funcall org-refile-target-verify-function)))
11059 (not heading))
11060 (let ((re (format org-complex-heading-regexp-format
11061 (regexp-quote heading)))
11062 (target
11063 (if (not org-refile-use-outline-path) heading
11064 (mapconcat
11065 #'identity
11066 (append
11067 (pcase org-refile-use-outline-path
11068 (`file (list (file-name-nondirectory
11069 (buffer-file-name
11070 (buffer-base-buffer)))))
11071 (`full-file-path
11072 (list (buffer-file-name
11073 (buffer-base-buffer))))
11074 (`buffer-name
11075 (list (buffer-name
11076 (buffer-base-buffer))))
11077 (_ nil))
11078 (mapcar (lambda (s) (replace-regexp-in-string
11079 "/" "\\/" s nil t))
11080 (org-get-outline-path t t)))
11081 "/"))))
11082 (push (list target f re (org-refile-marker (point)))
11083 tgs)))
11084 (when (= (point) begin)
11085 ;; Verification function has not moved point.
11086 (end-of-line)))))))
11087 (when org-refile-use-cache
11088 (org-refile-cache-put tgs (buffer-file-name) descre))
11089 (setq targets (append tgs targets))))))
11090 (message "Getting targets...done")
11091 (delete-dups (nreverse targets))))
11093 (defun org--get-outline-path-1 (&optional use-cache)
11094 "Return outline path to current headline.
11096 Outline path is a list of strings, in reverse order. When
11097 optional argument USE-CACHE is non-nil, make use of a cache. See
11098 `org-get-outline-path' for details.
11100 Assume buffer is widened and point is on a headline."
11101 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11102 (let ((p (point))
11103 (heading (let ((case-fold-search nil))
11104 (looking-at org-complex-heading-regexp)
11105 (if (not (match-end 4)) ""
11106 ;; Remove statistics cookies.
11107 (org-trim
11108 (org-link-display-format
11109 (replace-regexp-in-string
11110 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11111 (match-string-no-properties 4))))))))
11112 (if (org-up-heading-safe)
11113 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11114 (when use-cache
11115 (push (cons p path) org-outline-path-cache))
11116 path)
11117 ;; This is a new root node. Since we assume we are moving
11118 ;; forward, we can drop previous cache so as to limit number
11119 ;; of associations there.
11120 (let ((path (list heading)))
11121 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11122 path)))))
11124 (defun org-get-outline-path (&optional with-self use-cache)
11125 "Return the outline path to the current entry.
11127 An outline path is a list of ancestors for current headline, as
11128 a list of strings. Statistics cookies are removed and links are
11129 replaced with their description, if any, or their path otherwise.
11131 When optional argument WITH-SELF is non-nil, the path also
11132 includes the current headline.
11134 When optional argument USE-CACHE is non-nil, cache outline paths
11135 between calls to this function so as to avoid backtracking. This
11136 argument is useful when planning to find more than one outline
11137 path in the same document. In that case, there are two
11138 conditions to satisfy:
11139 - `org-outline-path-cache' is set to nil before starting the
11140 process;
11141 - outline paths are computed by increasing buffer positions."
11142 (org-with-wide-buffer
11143 (and (or (and with-self (org-back-to-heading t))
11144 (org-up-heading-safe))
11145 (reverse (org--get-outline-path-1 use-cache)))))
11147 (defun org-format-outline-path (path &optional width prefix separator)
11148 "Format the outline path PATH for display.
11149 WIDTH is the maximum number of characters that is available.
11150 PREFIX is a prefix to be included in the returned string,
11151 such as the file name.
11152 SEPARATOR is inserted between the different parts of the path,
11153 the default is \"/\"."
11154 (setq width (or width 79))
11155 (setq path (delq nil path))
11156 (unless (> width 0)
11157 (user-error "Argument `width' must be positive"))
11158 (setq separator (or separator "/"))
11159 (let* ((org-odd-levels-only nil)
11160 (fpath (concat
11161 prefix (and prefix path separator)
11162 (mapconcat
11163 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11164 (cl-loop for head in path
11165 for n from 0
11166 collect (org-add-props
11167 head nil 'face
11168 (nth (% n org-n-level-faces) org-level-faces)))
11169 separator))))
11170 (when (> (length fpath) width)
11171 (if (< width 7)
11172 ;; It's unlikely that `width' will be this small, but don't
11173 ;; waste characters by adding ".." if it is.
11174 (setq fpath (substring fpath 0 width))
11175 (setf (substring fpath (- width 2)) "..")))
11176 fpath))
11178 (defun org-display-outline-path (&optional file current separator just-return-string)
11179 "Display the current outline path in the echo area.
11181 If FILE is non-nil, prepend the output with the file name.
11182 If CURRENT is non-nil, append the current heading to the output.
11183 SEPARATOR is passed through to `org-format-outline-path'. It separates
11184 the different parts of the path and defaults to \"/\".
11185 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11186 (interactive "P")
11187 (let* (case-fold-search
11188 (bfn (buffer-file-name (buffer-base-buffer)))
11189 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11190 res)
11191 (when current (setq path (append path
11192 (save-excursion
11193 (org-back-to-heading t)
11194 (when (looking-at org-complex-heading-regexp)
11195 (list (match-string 4)))))))
11196 (setq res
11197 (org-format-outline-path
11198 path
11199 (1- (frame-width))
11200 (and file bfn (concat (file-name-nondirectory bfn) separator))
11201 separator))
11202 (if just-return-string
11203 (org-no-properties res)
11204 (org-unlogged-message "%s" res))))
11206 (defvar org-refile-history nil
11207 "History for refiling operations.")
11209 (defvar org-after-refile-insert-hook nil
11210 "Hook run after `org-refile' has inserted its stuff at the new location.
11211 Note that this is still *before* the stuff will be removed from
11212 the *old* location.")
11214 (defvar org-capture-last-stored-marker)
11215 (defvar org-refile-keep nil
11216 "Non-nil means `org-refile' will copy instead of refile.")
11218 (defun org-copy ()
11219 "Like `org-refile', but copy."
11220 (interactive)
11221 (let ((org-refile-keep t))
11222 (org-refile nil nil nil "Copy")))
11224 (defun org-refile (&optional arg default-buffer rfloc msg)
11225 "Move the entry or entries at point to another heading.
11227 The list of target headings is compiled using the information in
11228 `org-refile-targets', which see.
11230 At the target location, the entry is filed as a subitem of the
11231 target heading. Depending on `org-reverse-note-order', the new
11232 subitem will either be the first or the last subitem.
11234 If there is an active region, all entries in that region will be
11235 refiled. However, the region must fulfill the requirement that
11236 the first heading sets the top-level of the moved text.
11238 With a `\\[universal-argument]' ARG, the command will only visit the target \
11239 location
11240 and not actually move anything.
11242 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11243 location where the last
11244 refiling operation has put the subtree.
11246 With a numeric prefix argument of `2', refile to the running clock.
11248 With a numeric prefix argument of `3', emulate `org-refile-keep'
11249 being set to t and copy to the target location, don't move it.
11250 Beware that keeping refiled entries may result in duplicated ID
11251 properties.
11253 RFLOC can be a refile location obtained in a different way.
11255 MSG is a string to replace \"Refile\" in the default prompt with
11256 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11258 See also `org-refile-use-outline-path'.
11260 If you are using target caching (see `org-refile-use-cache'), you
11261 have to clear the target cache in order to find new targets.
11262 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11263 prefix argument (`C-u C-u C-u C-c C-w')."
11264 (interactive "P")
11265 (if (member arg '(0 (64)))
11266 (org-refile-cache-clear)
11267 (let* ((actionmsg (cond (msg msg)
11268 ((equal arg 3) "Refile (and keep)")
11269 (t "Refile")))
11270 (regionp (org-region-active-p))
11271 (region-start (and regionp (region-beginning)))
11272 (region-end (and regionp (region-end)))
11273 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11274 pos it nbuf file level reversed)
11275 (setq last-command nil)
11276 (when regionp
11277 (goto-char region-start)
11278 (or (bolp) (goto-char (point-at-bol)))
11279 (setq region-start (point))
11280 (unless (or (org-kill-is-subtree-p
11281 (buffer-substring region-start region-end))
11282 (prog1 org-refile-active-region-within-subtree
11283 (let ((s (point-at-eol)))
11284 (org-toggle-heading)
11285 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11286 (user-error "The region is not a (sequence of) subtree(s)")))
11287 (if (equal arg '(16))
11288 (org-refile-goto-last-stored)
11289 (when (or
11290 (and (equal arg 2)
11291 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11292 (prog1
11293 (setq it (list (or org-clock-heading "running clock")
11294 (buffer-file-name
11295 (marker-buffer org-clock-hd-marker))
11297 (marker-position org-clock-hd-marker)))
11298 (setq arg nil)))
11299 (setq it
11300 (or rfloc
11301 (let (heading-text)
11302 (save-excursion
11303 (unless (and arg (listp arg))
11304 (org-back-to-heading t)
11305 (setq heading-text
11306 (replace-regexp-in-string
11307 org-bracket-link-regexp
11308 "\\3"
11309 (or (nth 4 (org-heading-components))
11310 ""))))
11311 (org-refile-get-location
11312 (cond ((and arg (listp arg)) "Goto")
11313 (regionp (concat actionmsg " region to"))
11314 (t (concat actionmsg " subtree \""
11315 heading-text "\" to")))
11316 default-buffer
11317 (and (not (equal '(4) arg))
11318 org-refile-allow-creating-parent-nodes)))))))
11319 (setq file (nth 1 it)
11320 pos (nth 3 it))
11321 (when (and (not arg)
11323 (equal (buffer-file-name) file)
11324 (if regionp
11325 (and (>= pos region-start)
11326 (<= pos region-end))
11327 (and (>= pos (point))
11328 (< pos (save-excursion
11329 (org-end-of-subtree t t))))))
11330 (error "Cannot refile to position inside the tree or region"))
11331 (setq nbuf (or (find-buffer-visiting file)
11332 (find-file-noselect file)))
11333 (if (and arg (not (equal arg 3)))
11334 (progn
11335 (pop-to-buffer-same-window nbuf)
11336 (goto-char (cond (pos)
11337 ((org-notes-order-reversed-p) (point-min))
11338 (t (point-max))))
11339 (org-show-context 'org-goto))
11340 (if regionp
11341 (progn
11342 (org-kill-new (buffer-substring region-start region-end))
11343 (org-save-markers-in-region region-start region-end))
11344 (org-copy-subtree 1 nil t))
11345 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11346 (find-file-noselect file)))
11347 (setq reversed (org-notes-order-reversed-p))
11348 (org-with-wide-buffer
11349 (if pos
11350 (progn
11351 (goto-char pos)
11352 (setq level (org-get-valid-level (funcall outline-level) 1))
11353 (goto-char
11354 (if reversed
11355 (or (outline-next-heading) (point-max))
11356 (or (save-excursion (org-get-next-sibling))
11357 (org-end-of-subtree t t)
11358 (point-max)))))
11359 (setq level 1)
11360 (if (not reversed)
11361 (goto-char (point-max))
11362 (goto-char (point-min))
11363 (or (outline-next-heading) (goto-char (point-max)))))
11364 (unless (bolp) (newline))
11365 (org-paste-subtree level nil nil t)
11366 (when org-log-refile
11367 (org-add-log-setup 'refile nil nil org-log-refile)
11368 (unless (eq org-log-refile 'note)
11369 (save-excursion (org-add-log-note))))
11370 (and org-auto-align-tags
11371 (let ((org-loop-over-headlines-in-active-region nil))
11372 (org-align-tags)))
11373 (let ((bookmark-name (plist-get org-bookmark-names-plist
11374 :last-refile)))
11375 (when bookmark-name
11376 (with-demoted-errors
11377 (bookmark-set bookmark-name))))
11378 ;; If we are refiling for capture, make sure that the
11379 ;; last-capture pointers point here
11380 (when (bound-and-true-p org-capture-is-refiling)
11381 (let ((bookmark-name (plist-get org-bookmark-names-plist
11382 :last-capture-marker)))
11383 (when bookmark-name
11384 (with-demoted-errors
11385 (bookmark-set bookmark-name))))
11386 (move-marker org-capture-last-stored-marker (point)))
11387 (when (fboundp 'deactivate-mark) (deactivate-mark))
11388 (run-hooks 'org-after-refile-insert-hook)))
11389 (unless org-refile-keep
11390 (if regionp
11391 (delete-region (point) (+ (point) (- region-end region-start)))
11392 (org-preserve-local-variables
11393 (delete-region
11394 (and (org-back-to-heading t) (point))
11395 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point))))))
11396 (when (featurep 'org-inlinetask)
11397 (org-inlinetask-remove-END-maybe))
11398 (setq org-markers-to-move nil)
11399 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11401 (defun org-refile-goto-last-stored ()
11402 "Go to the location where the last refile was stored."
11403 (interactive)
11404 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11405 (message "This is the location of the last refile"))
11407 (defun org-refile--get-location (refloc tbl)
11408 "When user refile to REFLOC, find the associated target in TBL.
11409 Also check `org-refile-target-table'."
11410 (car (delq
11412 (mapcar
11413 (lambda (r) (or (assoc r tbl)
11414 (assoc r org-refile-target-table)))
11415 (list (replace-regexp-in-string "/$" "" refloc)
11416 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11418 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11419 "Prompt the user for a refile location, using PROMPT.
11420 PROMPT should not be suffixed with a colon and a space, because
11421 this function appends the default value from
11422 `org-refile-history' automatically, if that is not empty."
11423 (let ((org-refile-targets org-refile-targets)
11424 (org-refile-use-outline-path org-refile-use-outline-path))
11425 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11426 (unless org-refile-target-table
11427 (user-error "No refile targets"))
11428 (let* ((cbuf (current-buffer))
11429 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11430 (cfunc (if (and org-refile-use-outline-path
11431 org-outline-path-complete-in-steps)
11432 #'org-olpath-completing-read
11433 #'completing-read))
11434 (extra (if org-refile-use-outline-path "/" ""))
11435 (cbnex (concat (buffer-name) extra))
11436 (filename (and cfn (expand-file-name cfn)))
11437 (tbl (mapcar
11438 (lambda (x)
11439 (if (and (not (member org-refile-use-outline-path
11440 '(file full-file-path)))
11441 (not (equal filename (nth 1 x))))
11442 (cons (concat (car x) extra " ("
11443 (file-name-nondirectory (nth 1 x)) ")")
11444 (cdr x))
11445 (cons (concat (car x) extra) (cdr x))))
11446 org-refile-target-table))
11447 (completion-ignore-case t)
11448 cdef
11449 (prompt (concat prompt
11450 (or (and (car org-refile-history)
11451 (concat " (default " (car org-refile-history) ")"))
11452 (and (assoc cbnex tbl) (setq cdef cbnex)
11453 (concat " (default " cbnex ")"))) ": "))
11454 pa answ parent-target child parent old-hist)
11455 (setq old-hist org-refile-history)
11456 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11457 nil 'org-refile-history (or cdef (car org-refile-history))))
11458 (if (setq pa (org-refile--get-location answ tbl))
11459 (progn
11460 (org-refile-check-position pa)
11461 (when (or (not org-refile-history)
11462 (not (eq old-hist org-refile-history))
11463 (not (equal (car pa) (car org-refile-history))))
11464 (setq org-refile-history
11465 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11466 org-refile-history
11467 (cdr org-refile-history))))
11468 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11469 (pop org-refile-history)))
11471 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11472 (progn
11473 (setq parent (match-string 1 answ)
11474 child (match-string 2 answ))
11475 (setq parent-target (org-refile--get-location parent tbl))
11476 (when (and parent-target
11477 (or (eq new-nodes t)
11478 (and (eq new-nodes 'confirm)
11479 (y-or-n-p (format "Create new node \"%s\"? "
11480 child)))))
11481 (org-refile-new-child parent-target child)))
11482 (user-error "Invalid target location")))))
11484 (declare-function org-string-nw-p "org-macs" (s))
11485 (defun org-refile-check-position (refile-pointer)
11486 "Check if the refile pointer matches the headline to which it points."
11487 (let* ((file (nth 1 refile-pointer))
11488 (re (nth 2 refile-pointer))
11489 (pos (nth 3 refile-pointer))
11490 buffer)
11491 (if (and (not (markerp pos)) (not file))
11492 (user-error "Please indicate a target file in the refile path")
11493 (when (org-string-nw-p re)
11494 (setq buffer (if (markerp pos)
11495 (marker-buffer pos)
11496 (or (find-buffer-visiting file)
11497 (find-file-noselect file))))
11498 (with-current-buffer buffer
11499 (org-with-wide-buffer
11500 (goto-char pos)
11501 (beginning-of-line 1)
11502 (unless (looking-at-p re)
11503 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11505 (defun org-refile-new-child (parent-target child)
11506 "Use refile target PARENT-TARGET to add new CHILD below it."
11507 (unless parent-target
11508 (error "Cannot find parent for new node"))
11509 (let ((file (nth 1 parent-target))
11510 (pos (nth 3 parent-target))
11511 level)
11512 (with-current-buffer (or (find-buffer-visiting file)
11513 (find-file-noselect file))
11514 (org-with-wide-buffer
11515 (if pos
11516 (goto-char pos)
11517 (goto-char (point-max))
11518 (unless (bolp) (newline)))
11519 (when (looking-at org-outline-regexp)
11520 (setq level (funcall outline-level))
11521 (org-end-of-subtree t t))
11522 (org-back-over-empty-lines)
11523 (insert "\n" (make-string
11524 (if pos (org-get-valid-level level 1) 1) ?*)
11525 " " child "\n")
11526 (beginning-of-line 0)
11527 (list (concat (car parent-target) "/" child) file "" (point))))))
11529 (defun org-olpath-completing-read (prompt collection &rest args)
11530 "Read an outline path like a file name."
11531 (let ((thetable collection))
11532 (apply #'completing-read
11533 prompt
11534 (lambda (string predicate &optional flag)
11535 (cond
11536 ((eq flag nil) (try-completion string thetable))
11537 ((eq flag t)
11538 (let ((l (length string)))
11539 (mapcar (lambda (x)
11540 (let ((r (substring x l))
11541 (f (if (string-match " ([^)]*)$" x)
11542 (match-string 0 x)
11543 "")))
11544 (if (string-match "/" r)
11545 (concat string (substring r 0 (match-end 0)) f)
11546 x)))
11547 (all-completions string thetable predicate))))
11548 ;; Exact match?
11549 ((eq flag 'lambda) (assoc string thetable))))
11550 args)))
11552 ;;;; Dynamic blocks
11554 (defun org-find-dblock (name)
11555 "Find the first dynamic block with name NAME in the buffer.
11556 If not found, stay at current position and return nil."
11557 (let ((case-fold-search t) pos)
11558 (save-excursion
11559 (goto-char (point-min))
11560 (setq pos (and (re-search-forward
11561 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11562 (match-beginning 0))))
11563 (when pos (goto-char pos))
11564 pos))
11566 (defun org-create-dblock (plist)
11567 "Create a dynamic block section, with parameters taken from PLIST.
11568 PLIST must contain a :name entry which is used as the name of the block."
11569 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11570 (end-of-line 1)
11571 (newline))
11572 (let ((col (current-column))
11573 (name (plist-get plist :name)))
11574 (insert "#+BEGIN: " name)
11575 (while plist
11576 (if (eq (car plist) :name)
11577 (setq plist (cddr plist))
11578 (insert " " (prin1-to-string (pop plist)))))
11579 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11580 (beginning-of-line -2)))
11582 (defun org-prepare-dblock ()
11583 "Prepare dynamic block for refresh.
11584 This empties the block, puts the cursor at the insert position and returns
11585 the property list including an extra property :name with the block name."
11586 (unless (looking-at org-dblock-start-re)
11587 (user-error "Not at a dynamic block"))
11588 (let* ((begdel (1+ (match-end 0)))
11589 (name (org-no-properties (match-string 1)))
11590 (params (append (list :name name)
11591 (read (concat "(" (match-string 3) ")")))))
11592 (save-excursion
11593 (beginning-of-line 1)
11594 (skip-chars-forward " \t")
11595 (setq params (plist-put params :indentation-column (current-column))))
11596 (unless (re-search-forward org-dblock-end-re nil t)
11597 (error "Dynamic block not terminated"))
11598 (setq params
11599 (append params
11600 (list :content (buffer-substring
11601 begdel (match-beginning 0)))))
11602 (delete-region begdel (match-beginning 0))
11603 (goto-char begdel)
11604 (open-line 1)
11605 params))
11607 (defun org-map-dblocks (&optional command)
11608 "Apply COMMAND to all dynamic blocks in the current buffer.
11609 If COMMAND is not given, use `org-update-dblock'."
11610 (let ((cmd (or command 'org-update-dblock)))
11611 (save-excursion
11612 (goto-char (point-min))
11613 (while (re-search-forward org-dblock-start-re nil t)
11614 (goto-char (match-beginning 0))
11615 (save-excursion
11616 (condition-case nil
11617 (funcall cmd)
11618 (error (message "Error during update of dynamic block"))))
11619 (unless (re-search-forward org-dblock-end-re nil t)
11620 (error "Dynamic block not terminated"))))))
11622 (defun org-dblock-update (&optional arg)
11623 "User command for updating dynamic blocks.
11624 Update the dynamic block at point. With prefix ARG, update all dynamic
11625 blocks in the buffer."
11626 (interactive "P")
11627 (if arg
11628 (org-update-all-dblocks)
11629 (or (looking-at org-dblock-start-re)
11630 (org-beginning-of-dblock))
11631 (org-update-dblock)))
11633 (defun org-update-dblock ()
11634 "Update the dynamic block at point.
11635 This means to empty the block, parse for parameters and then call
11636 the correct writing function."
11637 (interactive)
11638 (save-excursion
11639 (let* ((win (selected-window))
11640 (pos (point))
11641 (line (org-current-line))
11642 (params (org-prepare-dblock))
11643 (name (plist-get params :name))
11644 (indent (plist-get params :indentation-column))
11645 (cmd (intern (concat "org-dblock-write:" name))))
11646 (message "Updating dynamic block `%s' at line %d..." name line)
11647 (funcall cmd params)
11648 (message "Updating dynamic block `%s' at line %d...done" name line)
11649 (goto-char pos)
11650 (when (and indent (> indent 0))
11651 (setq indent (make-string indent ?\ ))
11652 (save-excursion
11653 (select-window win)
11654 (org-beginning-of-dblock)
11655 (forward-line 1)
11656 (while (not (looking-at org-dblock-end-re))
11657 (insert indent)
11658 (beginning-of-line 2))
11659 (when (looking-at org-dblock-end-re)
11660 (and (looking-at "[ \t]+")
11661 (replace-match ""))
11662 (insert indent)))))))
11664 (defun org-beginning-of-dblock ()
11665 "Find the beginning of the dynamic block at point.
11666 Error if there is no such block at point."
11667 (let ((pos (point))
11668 beg)
11669 (end-of-line 1)
11670 (if (and (re-search-backward org-dblock-start-re nil t)
11671 (setq beg (match-beginning 0))
11672 (re-search-forward org-dblock-end-re nil t)
11673 (> (match-end 0) pos))
11674 (goto-char beg)
11675 (goto-char pos)
11676 (error "Not in a dynamic block"))))
11678 (defun org-update-all-dblocks ()
11679 "Update all dynamic blocks in the buffer.
11680 This function can be used in a hook."
11681 (interactive)
11682 (when (derived-mode-p 'org-mode)
11683 (org-map-dblocks 'org-update-dblock)))
11686 ;;;; Completion
11688 (declare-function org-export-backend-options "ox" (cl-x) t)
11689 (defun org-get-export-keywords ()
11690 "Return a list of all currently understood export keywords.
11691 Export keywords include options, block names, attributes and
11692 keywords relative to each registered export back-end."
11693 (let (keywords)
11694 (dolist (backend
11695 (bound-and-true-p org-export-registered-backends)
11696 (delq nil keywords))
11697 ;; Back-end name (for keywords, like #+LATEX:)
11698 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
11699 (dolist (option-entry (org-export-backend-options backend))
11700 ;; Back-end options.
11701 (push (nth 1 option-entry) keywords)))))
11703 (defconst org-options-keywords
11704 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11705 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11706 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11707 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11708 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11710 (defcustom org-structure-template-alist
11711 '(("a" . "export ascii")
11712 ("c" . "center")
11713 ("C" . "comment")
11714 ("e" . "example")
11715 ("E" . "export")
11716 ("h" . "export html")
11717 ("l" . "export latex")
11718 ("q" . "quote")
11719 ("s" . "src")
11720 ("v" . "verse"))
11721 "An alist of keys and block types.
11722 `org-insert-structure-template' will display a menu with this
11723 list of templates to choose from. The block type is inserted,
11724 with \"#+BEGIN_\" and \"#+END_\" added automatically.
11726 The menu keys are defined by the car of each entry in this alist.
11727 If two entries have the keys \"a\" and \"aa\" respectively, the
11728 former will be inserted by typing \"a TAB/RET/SPC\" and the
11729 latter will be inserted by typing \"aa\". If an entry with the
11730 key \"aab\" is later added, it can be inserted by typing \"ab\".
11732 If loaded, Org Tempo also uses `org-structure-template-alist'. A
11733 block can be inserted by pressing TAB after the string \"<KEY\"."
11734 :group 'org-edit-structure
11735 :type '(repeat
11736 (cons (string :tag "Key")
11737 (string :tag "Template")))
11738 :package-version '(Org . "9.2"))
11740 (defun org--check-org-structure-template-alist (&optional checklist)
11741 "Check whether `org-structure-template-alist' is set up correctly.
11742 In particular, check if the Org 9.2 format is used as opposed to
11743 previous format.
11745 (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
11746 (or (eval checklist)
11747 org-structure-template-alist))))
11748 (when elm
11749 (org-display-warning
11750 (format "
11751 Please update the entries of `%s'.
11753 In Org 9.2 the format was changed from something like
11755 (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
11757 to something like
11759 (\"s\" . \"src\")
11761 Please refer to the documentation of `org-structure-template-alist'.
11763 The following entries must be updated:
11766 (or checklist 'org-structure-template-alist)
11767 (pp-to-string elm))))))
11769 (defun org--insert-structure-template-mks ()
11770 "Present `org-structure-template-alist' with `org-mks'.
11772 Menus are added if keys require more than one keystroke. Tabs
11773 are added to single key entries when more than one stroke is
11774 needed. Keys longer than two characters are reduced to two
11775 characters."
11776 (org--check-org-structure-template-alist)
11777 (let* (case-fold-search
11778 (templates (append org-structure-template-alist
11779 '(("\t" . "Press TAB, RET or SPC to write block name"))))
11780 (keys (mapcar #'car templates))
11781 (start-letters
11782 (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
11783 ;; Sort each element of `org-structure-template-alist' into
11784 ;; sublists according to the first letter.
11785 (superlist
11786 (mapcar (lambda (letter)
11787 (list letter
11788 (cl-remove-if-not
11789 (apply-partially #'string-match-p (concat "^" letter))
11790 templates :key #'car)))
11791 start-letters)))
11792 (org-mks
11793 (apply #'append
11794 ;; Make an `org-mks' table. If only one element is
11795 ;; present in a sublist, make it part of the top-menu,
11796 ;; otherwise make a submenu according to the starting
11797 ;; letter and populate it.
11798 (mapcar (lambda (sublist)
11799 (if (eq 1 (length (cadr sublist)))
11800 (mapcar (lambda (elm)
11801 (list (substring (car elm) 0 1)
11802 (cdr elm) ""))
11803 (cadr sublist))
11804 ;; Create submenu.
11805 (let* ((topkey (car sublist))
11806 (elms (cadr sublist))
11807 (keys (mapcar #'car elms))
11808 (long (> (length elms) 3)))
11809 (append
11810 (list
11811 ;; Make a description of the submenu.
11812 (list topkey
11813 (concat
11814 (mapconcat #'cdr
11815 (cl-subseq elms 0 (if long 3 (length elms)))
11816 ", ")
11817 (when long ", ..."))))
11818 ;; List of entries in submenu.
11819 (cl-mapcar #'list
11820 (org--insert-structure-template-unique-keys keys)
11821 (mapcar #'cdr elms)
11822 (make-list (length elms) ""))))))
11823 superlist))
11824 "Select a key\n============"
11825 "Key: ")))
11827 (defun org--insert-structure-template-unique-keys (keys)
11828 "Make a list of unique, two characters long elements from KEYS.
11830 Elements of length one have a tab appended. Elements of length
11831 two are kept as is. Longer elements are truncated to length two.
11833 If an element cannot be made unique, an error is raised."
11834 (let ((orderd-keys (cl-sort (copy-sequence keys) #'< :key #'length))
11835 menu-keys)
11836 (dolist (key orderd-keys)
11837 (let ((potential-key
11838 (cl-case (length key)
11839 (1 (concat key "\t"))
11840 (2 key)
11841 (otherwise
11842 (cl-find-if-not (lambda (k) (assoc k menu-keys))
11843 (mapcar (apply-partially #'concat (substring key 0 1))
11844 (split-string (substring key 1) "" t)))))))
11845 (if (or (not potential-key) (assoc potential-key menu-keys))
11846 (user-error "Could not make unique key for %s." key)
11847 (push (cons potential-key key) menu-keys))))
11848 (mapcar #'car
11849 (cl-sort menu-keys #'<
11850 :key (lambda (elm) (cl-position (cdr elm) keys))))))
11852 (defun org-insert-structure-template (type)
11853 "Insert a block structure of the type #+begin_foo/#+end_foo.
11854 Select a block from `org-structure-template-alist' then type
11855 either RET, TAB or SPC to write the block type. With an active
11856 region, wrap the region in the block. Otherwise, insert an empty
11857 block."
11858 (interactive
11859 (list (pcase (org--insert-structure-template-mks)
11860 (`("\t" . ,_) (read-string "Structure type: "))
11861 (`(,_ ,choice . ,_) choice))))
11862 (let* ((region? (use-region-p))
11863 (region-start (and region? (region-beginning)))
11864 (region-end (and region? (copy-marker (region-end))))
11865 (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
11866 (verbatim? (string-match-p
11867 (concat "\\`" (regexp-opt '("example" "export" "src")))
11868 type)))
11869 (when region? (goto-char region-start))
11870 (let ((column (current-indentation)))
11871 (if (save-excursion (skip-chars-backward " \t") (bolp))
11872 (beginning-of-line)
11873 (insert "\n"))
11874 (save-excursion
11875 (indent-to column)
11876 (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
11877 (when region?
11878 (when verbatim? (org-escape-code-in-region (point) region-end))
11879 (goto-char region-end)
11880 ;; Ignore empty lines at the end of the region.
11881 (skip-chars-backward " \r\t\n")
11882 (end-of-line))
11883 (unless (bolp) (insert "\n"))
11884 (indent-to column)
11885 (insert (format "#+end_%s" (car (split-string type))))
11886 (if (looking-at "[ \t]*$") (replace-match "")
11887 (insert "\n"))
11888 (when (and (eobp) (not (bolp))) (insert "\n")))
11889 (if extended? (end-of-line)
11890 (forward-line)
11891 (skip-chars-forward " \t")))))
11894 ;;;; TODO, DEADLINE, Comments
11896 (defun org-toggle-comment ()
11897 "Change the COMMENT state of an entry."
11898 (interactive)
11899 (save-excursion
11900 (org-back-to-heading)
11901 (let ((case-fold-search nil))
11902 (looking-at org-complex-heading-regexp))
11903 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
11904 (skip-chars-forward " \t")
11905 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
11906 (if (org-in-commented-heading-p t)
11907 (delete-region (point)
11908 (progn (search-forward " " (line-end-position) 'move)
11909 (skip-chars-forward " \t")
11910 (point)))
11911 (insert org-comment-string)
11912 (unless (eolp) (insert " ")))))
11914 (defvar org-last-todo-state-is-todo nil
11915 "This is non-nil when the last TODO state change led to a TODO state.
11916 If the last change removed the TODO tag or switched to DONE, then
11917 this is nil.")
11919 (defvar org-todo-setup-filter-hook nil
11920 "Hook for functions that pre-filter todo specs.
11921 Each function takes a todo spec and returns either nil or the spec
11922 transformed into canonical form." )
11924 (defvar org-todo-get-default-hook nil
11925 "Hook for functions that get a default item for todo.
11926 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11927 nil or a string to be used for the todo mark." )
11929 (defvar org-agenda-headline-snapshot-before-repeat)
11931 (defun org-current-effective-time ()
11932 "Return current time adjusted for `org-extend-today-until' variable."
11933 (let* ((ct (org-current-time))
11934 (dct (decode-time ct))
11935 (ct1
11936 (cond
11937 (org-use-last-clock-out-time-as-effective-time
11938 (or (org-clock-get-last-clock-out-time) ct))
11939 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11940 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11941 (t ct))))
11942 ct1))
11944 (defun org-todo-yesterday (&optional arg)
11945 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11946 (interactive "P")
11947 (if (eq major-mode 'org-agenda-mode)
11948 (apply 'org-agenda-todo-yesterday arg)
11949 (let* ((org-use-effective-time t)
11950 (hour (nth 2 (decode-time (org-current-time))))
11951 (org-extend-today-until (1+ hour)))
11952 (org-todo arg))))
11954 (defvar org-block-entry-blocking ""
11955 "First entry preventing the TODO state change.")
11957 (defun org-cancel-repeater ()
11958 "Cancel a repeater by setting its numeric value to zero."
11959 (interactive)
11960 (save-excursion
11961 (org-back-to-heading t)
11962 (let ((bound1 (point))
11963 (bound0 (save-excursion (outline-next-heading) (point))))
11964 (when (and (re-search-forward
11965 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
11966 org-deadline-time-regexp "\\)\\|\\("
11967 org-ts-regexp "\\)")
11968 bound0 t)
11969 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
11970 bound1 t))
11971 (replace-match "0" t nil nil 1)))))
11973 (defvar org-state)
11974 (defvar org-blocked-by-checkboxes)
11975 (defun org-todo (&optional arg)
11976 "Change the TODO state of an item.
11978 The state of an item is given by a keyword at the start of the heading,
11979 like
11980 *** TODO Write paper
11981 *** DONE Call mom
11983 The different keywords are specified in the variable `org-todo-keywords'.
11984 By default the available states are \"TODO\" and \"DONE\". So, for this
11985 example: when the item starts with TODO, it is changed to DONE.
11986 When it starts with DONE, the DONE is removed. And when neither TODO nor
11987 DONE are present, add TODO at the beginning of the heading.
11989 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
11990 state.
11991 With numeric prefix ARG, switch to that state.
11992 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
11993 next set of TODO \
11994 keywords (nextset).
11995 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
11996 prefix, circumvent any state blocking.
11997 With a numeric prefix arg of 0, inhibit note taking for the change.
11998 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12000 When called through ELisp, arg is also interpreted in the following way:
12001 `none' -> empty state
12002 \"\" -> switch to empty state
12003 `done' -> switch to DONE
12004 `nextset' -> switch to the next set of keywords
12005 `previousset' -> switch to the previous set of keywords
12006 \"WAITING\" -> switch to the specified keyword, but only if it
12007 really is a member of `org-todo-keywords'."
12008 (interactive "P")
12009 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12010 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12011 'region-start-level 'region))
12012 org-loop-over-headlines-in-active-region)
12013 (org-map-entries
12014 `(org-todo ,arg)
12015 org-loop-over-headlines-in-active-region
12016 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12017 (when (equal arg '(16)) (setq arg 'nextset))
12018 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12019 (let ((org-blocker-hook org-blocker-hook)
12020 commentp
12021 case-fold-search)
12022 (when (equal arg '(64))
12023 (setq arg nil org-blocker-hook nil))
12024 (when (and org-blocker-hook
12025 (or org-inhibit-blocking
12026 (org-entry-get nil "NOBLOCKING")))
12027 (setq org-blocker-hook nil))
12028 (save-excursion
12029 (catch 'exit
12030 (org-back-to-heading t)
12031 (when (org-in-commented-heading-p t)
12032 (org-toggle-comment)
12033 (setq commentp t))
12034 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12035 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12036 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12037 (let* ((match-data (match-data))
12038 (startpos (copy-marker (line-beginning-position)))
12039 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12040 (org-log-done org-log-done)
12041 (org-log-repeat org-log-repeat)
12042 (org-todo-log-states org-todo-log-states)
12043 (org-inhibit-logging
12044 (if (equal arg 0)
12045 (progn (setq arg nil) 'note) org-inhibit-logging))
12046 (this (match-string 1))
12047 (hl-pos (match-beginning 0))
12048 (head (org-get-todo-sequence-head this))
12049 (ass (assoc head org-todo-kwd-alist))
12050 (interpret (nth 1 ass))
12051 (done-word (nth 3 ass))
12052 (final-done-word (nth 4 ass))
12053 (org-last-state (or this ""))
12054 (completion-ignore-case t)
12055 (member (member this org-todo-keywords-1))
12056 (tail (cdr member))
12057 (org-state (cond
12058 ((and org-todo-key-trigger
12059 (or (and (equal arg '(4))
12060 (eq org-use-fast-todo-selection 'prefix))
12061 (and (not arg) org-use-fast-todo-selection
12062 (not (eq org-use-fast-todo-selection
12063 'prefix)))))
12064 ;; Use fast selection.
12065 (org-fast-todo-selection))
12066 ((and (equal arg '(4))
12067 (or (not org-use-fast-todo-selection)
12068 (not org-todo-key-trigger)))
12069 ;; Read a state with completion.
12070 (completing-read
12071 "State: " (mapcar #'list org-todo-keywords-1)
12072 nil t))
12073 ((eq arg 'right)
12074 (if this
12075 (if tail (car tail) nil)
12076 (car org-todo-keywords-1)))
12077 ((eq arg 'left)
12078 (unless (equal member org-todo-keywords-1)
12079 (if this
12080 (nth (- (length org-todo-keywords-1)
12081 (length tail) 2)
12082 org-todo-keywords-1)
12083 (org-last org-todo-keywords-1))))
12084 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12085 (setq arg nil))) ;hack to fall back to cycling
12086 (arg
12087 ;; User or caller requests a specific state.
12088 (cond
12089 ((equal arg "") nil)
12090 ((eq arg 'none) nil)
12091 ((eq arg 'done) (or done-word (car org-done-keywords)))
12092 ((eq arg 'nextset)
12093 (or (car (cdr (member head org-todo-heads)))
12094 (car org-todo-heads)))
12095 ((eq arg 'previousset)
12096 (let ((org-todo-heads (reverse org-todo-heads)))
12097 (or (car (cdr (member head org-todo-heads)))
12098 (car org-todo-heads))))
12099 ((car (member arg org-todo-keywords-1)))
12100 ((stringp arg)
12101 (user-error "State `%s' not valid in this file" arg))
12102 ((nth (1- (prefix-numeric-value arg))
12103 org-todo-keywords-1))))
12104 ((null member) (or head (car org-todo-keywords-1)))
12105 ((equal this final-done-word) nil) ;-> make empty
12106 ((null tail) nil) ;-> first entry
12107 ((memq interpret '(type priority))
12108 (if (eq this-command last-command)
12109 (car tail)
12110 (if (> (length tail) 0)
12111 (or done-word (car org-done-keywords))
12112 nil)))
12114 (car tail))))
12115 (org-state (or
12116 (run-hook-with-args-until-success
12117 'org-todo-get-default-hook org-state org-last-state)
12118 org-state))
12119 (next (if org-state (concat " " org-state " ") " "))
12120 (change-plist (list :type 'todo-state-change :from this :to org-state
12121 :position startpos))
12122 dolog now-done-p)
12123 (when org-blocker-hook
12124 (let (org-blocked-by-checkboxes block-reason)
12125 (setq org-last-todo-state-is-todo
12126 (not (member this org-done-keywords)))
12127 (unless (save-excursion
12128 (save-match-data
12129 (org-with-wide-buffer
12130 (run-hook-with-args-until-failure
12131 'org-blocker-hook change-plist))))
12132 (setq block-reason (if org-blocked-by-checkboxes
12133 "contained checkboxes"
12134 (format "\"%s\"" org-block-entry-blocking)))
12135 (if (called-interactively-p 'interactive)
12136 (user-error "TODO state change from %s to %s blocked (by %s)"
12137 this org-state block-reason)
12138 ;; Fail silently.
12139 (message "TODO state change from %s to %s blocked (by %s)"
12140 this org-state block-reason)
12141 (throw 'exit nil)))))
12142 (store-match-data match-data)
12143 (replace-match next t t)
12144 (cond ((equal this org-state)
12145 (message "TODO state was already %s" (org-trim next)))
12146 ((not (pos-visible-in-window-p hl-pos))
12147 (message "TODO state changed to %s" (org-trim next))))
12148 (unless head
12149 (setq head (org-get-todo-sequence-head org-state)
12150 ass (assoc head org-todo-kwd-alist)
12151 interpret (nth 1 ass)
12152 done-word (nth 3 ass)
12153 final-done-word (nth 4 ass)))
12154 (when (memq arg '(nextset previousset))
12155 (message "Keyword-Set %d/%d: %s"
12156 (- (length org-todo-sets) -1
12157 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12158 (length org-todo-sets)
12159 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12160 (setq org-last-todo-state-is-todo
12161 (not (member org-state org-done-keywords)))
12162 (setq now-done-p (and (member org-state org-done-keywords)
12163 (not (member this org-done-keywords))))
12164 (and logging (org-local-logging logging))
12165 (when (and (or org-todo-log-states org-log-done)
12166 (not (eq org-inhibit-logging t))
12167 (not (memq arg '(nextset previousset))))
12168 ;; We need to look at recording a time and note.
12169 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12170 (nth 2 (assoc this org-todo-log-states))))
12171 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12172 (setq dolog 'time))
12173 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12174 (and org-state
12175 (member org-state org-not-done-keywords)
12176 (not (member this org-not-done-keywords))))
12177 ;; This is now a todo state and was not one before
12178 ;; If there was a CLOSED time stamp, get rid of it.
12179 (org-add-planning-info nil nil 'closed))
12180 (when (and now-done-p org-log-done)
12181 ;; It is now done, and it was not done before.
12182 (org-add-planning-info 'closed (org-current-effective-time))
12183 (when (and (not dolog) (eq 'note org-log-done))
12184 (org-add-log-setup 'done org-state this 'note)))
12185 (when (and org-state dolog)
12186 ;; This is a non-nil state, and we need to log it.
12187 (org-add-log-setup 'state org-state this dolog)))
12188 ;; Fixup tag positioning.
12189 (org-todo-trigger-tag-changes org-state)
12190 (when org-auto-align-tags (org-align-tags))
12191 (when org-provide-todo-statistics
12192 (org-update-parent-todo-statistics))
12193 (run-hooks 'org-after-todo-state-change-hook)
12194 (when (and arg (not (member org-state org-done-keywords)))
12195 (setq head (org-get-todo-sequence-head org-state)))
12196 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12197 ;; Do we need to trigger a repeat?
12198 (when now-done-p
12199 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12200 ;; This is for the agenda, take a snapshot of the headline.
12201 (save-match-data
12202 (setq org-agenda-headline-snapshot-before-repeat
12203 (org-get-heading))))
12204 (org-auto-repeat-maybe org-state))
12205 ;; Fixup cursor location if close to the keyword.
12206 (when (and (outline-on-heading-p)
12207 (not (bolp))
12208 (save-excursion (beginning-of-line 1)
12209 (looking-at org-todo-line-regexp))
12210 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12211 (goto-char (or (match-end 2) (match-end 1)))
12212 (and (looking-at " ") (just-one-space)))
12213 (when org-trigger-hook
12214 (save-excursion
12215 (run-hook-with-args 'org-trigger-hook change-plist)))
12216 (when commentp (org-toggle-comment))))))))
12218 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12219 "Block turning an entry into a TODO, using the hierarchy.
12220 This checks whether the current task should be blocked from state
12221 changes. Such blocking occurs when:
12223 1. The task has children which are not all in a completed state.
12225 2. A task has a parent with the property :ORDERED:, and there
12226 are siblings prior to the current task with incomplete
12227 status.
12229 3. The parent of the task is blocked because it has siblings that should
12230 be done first, or is child of a block grandparent TODO entry."
12232 (if (not org-enforce-todo-dependencies)
12233 t ; if locally turned off don't block
12234 (catch 'dont-block
12235 ;; If this is not a todo state change, or if this entry is already DONE,
12236 ;; do not block
12237 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12238 (member (plist-get change-plist :from)
12239 (cons 'done org-done-keywords))
12240 (member (plist-get change-plist :to)
12241 (cons 'todo org-not-done-keywords))
12242 (not (plist-get change-plist :to)))
12243 (throw 'dont-block t))
12244 ;; If this task has children, and any are undone, it's blocked
12245 (save-excursion
12246 (org-back-to-heading t)
12247 (let ((this-level (funcall outline-level)))
12248 (outline-next-heading)
12249 (let ((child-level (funcall outline-level)))
12250 (while (and (not (eobp))
12251 (> child-level this-level))
12252 ;; this todo has children, check whether they are all
12253 ;; completed
12254 (when (and (not (org-entry-is-done-p))
12255 (org-entry-is-todo-p))
12256 (setq org-block-entry-blocking (org-get-heading))
12257 (throw 'dont-block nil))
12258 (outline-next-heading)
12259 (setq child-level (funcall outline-level))))))
12260 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12261 ;; any previous siblings are undone, it's blocked
12262 (save-excursion
12263 (org-back-to-heading t)
12264 (let* ((pos (point))
12265 (parent-pos (and (org-up-heading-safe) (point)))
12266 (case-fold-search nil))
12267 (unless parent-pos (throw 'dont-block t)) ; no parent
12268 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12269 (forward-line 1)
12270 (re-search-forward org-not-done-heading-regexp pos t))
12271 (setq org-block-entry-blocking (match-string 0))
12272 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12273 ;; Search further up the hierarchy, to see if an ancestor is blocked
12274 (while t
12275 (goto-char parent-pos)
12276 (unless (looking-at org-not-done-heading-regexp)
12277 (throw 'dont-block t)) ; do not block, parent is not a TODO
12278 (setq pos (point))
12279 (setq parent-pos (and (org-up-heading-safe) (point)))
12280 (unless parent-pos (throw 'dont-block t)) ; no parent
12281 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12282 (forward-line 1)
12283 (re-search-forward org-not-done-heading-regexp pos t)
12284 (setq org-block-entry-blocking (org-get-heading)))
12285 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12287 (defcustom org-track-ordered-property-with-tag nil
12288 "Should the ORDERED property also be shown as a tag?
12289 The ORDERED property decides if an entry should require subtasks to be
12290 completed in sequence. Since a property is not very visible, setting
12291 this option means that toggling the ORDERED property with the command
12292 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12293 not relevant for the behavior, but it makes things more visible.
12295 Note that toggling the tag with tags commands will not change the property
12296 and therefore not influence behavior!
12298 This can be t, meaning the tag ORDERED should be used, It can also be a
12299 string to select a different tag for this task."
12300 :group 'org-todo
12301 :type '(choice
12302 (const :tag "No tracking" nil)
12303 (const :tag "Track with ORDERED tag" t)
12304 (string :tag "Use other tag")))
12306 (defun org-toggle-ordered-property ()
12307 "Toggle the ORDERED property of the current entry.
12308 For better visibility, you can track the value of this property with a tag.
12309 See variable `org-track-ordered-property-with-tag'."
12310 (interactive)
12311 (let* ((t1 org-track-ordered-property-with-tag)
12312 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12313 (save-excursion
12314 (org-back-to-heading)
12315 (if (org-entry-get nil "ORDERED")
12316 (progn
12317 (org-delete-property "ORDERED")
12318 (and tag (org-toggle-tag tag 'off))
12319 (message "Subtasks can be completed in arbitrary order"))
12320 (org-entry-put nil "ORDERED" "t")
12321 (and tag (org-toggle-tag tag 'on))
12322 (message "Subtasks must be completed in sequence")))))
12324 (defun org-block-todo-from-checkboxes (change-plist)
12325 "Block turning an entry into a TODO, using checkboxes.
12326 This checks whether the current task should be blocked from state
12327 changes because there are unchecked boxes in this entry."
12328 (if (not org-enforce-todo-checkbox-dependencies)
12329 t ; if locally turned off don't block
12330 (catch 'dont-block
12331 ;; If this is not a todo state change, or if this entry is already DONE,
12332 ;; do not block
12333 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12334 (member (plist-get change-plist :from)
12335 (cons 'done org-done-keywords))
12336 (member (plist-get change-plist :to)
12337 (cons 'todo org-not-done-keywords))
12338 (not (plist-get change-plist :to)))
12339 (throw 'dont-block t))
12340 ;; If this task has checkboxes that are not checked, it's blocked
12341 (save-excursion
12342 (org-back-to-heading t)
12343 (let ((beg (point)) end)
12344 (outline-next-heading)
12345 (setq end (point))
12346 (goto-char beg)
12347 (when (org-list-search-forward
12348 (concat (org-item-beginning-re)
12349 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12350 "\\[[- ]\\]")
12351 end t)
12352 (when (boundp 'org-blocked-by-checkboxes)
12353 (setq org-blocked-by-checkboxes t))
12354 (throw 'dont-block nil))))
12355 t))) ; do not block
12357 (defun org-entry-blocked-p ()
12358 "Non-nil if entry at point is blocked."
12359 (and (not (org-entry-get nil "NOBLOCKING"))
12360 (member (org-entry-get nil "TODO") org-not-done-keywords)
12361 (not (run-hook-with-args-until-failure
12362 'org-blocker-hook
12363 (list :type 'todo-state-change
12364 :position (point)
12365 :from 'todo
12366 :to 'done)))))
12368 (defun org-update-statistics-cookies (all)
12369 "Update the statistics cookie, either from TODO or from checkboxes.
12370 This should be called with the cursor in a line with a statistics
12371 cookie. When called with a \\[universal-argument] prefix, update
12372 all statistics cookies in the buffer."
12373 (interactive "P")
12374 (if all
12375 (progn
12376 (org-update-checkbox-count 'all)
12377 (org-map-entries 'org-update-parent-todo-statistics))
12378 (if (not (org-at-heading-p))
12379 (org-update-checkbox-count)
12380 (let ((pos (point-marker))
12381 end l1 l2)
12382 (ignore-errors (org-back-to-heading t))
12383 (if (not (org-at-heading-p))
12384 (org-update-checkbox-count)
12385 (setq l1 (org-outline-level))
12386 (setq end (save-excursion
12387 (outline-next-heading)
12388 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12389 (point)))
12390 (if (and (save-excursion
12391 (re-search-forward
12392 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12393 (not (save-excursion (re-search-forward
12394 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12395 (org-update-checkbox-count)
12396 (if (and l2 (> l2 l1))
12397 (progn
12398 (goto-char end)
12399 (org-update-parent-todo-statistics))
12400 (goto-char pos)
12401 (beginning-of-line 1)
12402 (while (re-search-forward
12403 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12404 (point-at-eol) t)
12405 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12406 (goto-char pos)
12407 (move-marker pos nil)))))
12409 (defvar org-entry-property-inherited-from) ;; defined below
12410 (defun org-update-parent-todo-statistics ()
12411 "Update any statistics cookie in the parent of the current headline.
12412 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12413 the entire subtree and this will travel up the hierarchy and update
12414 statistics everywhere."
12415 (let* ((prop (save-excursion (org-up-heading-safe)
12416 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12417 (recursive (or (not org-hierarchical-todo-statistics)
12418 (and prop (string-match "\\<recursive\\>" prop))))
12419 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12421 (first t)
12422 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12423 level ltoggle l1 new ndel
12424 (cnt-all 0) (cnt-done 0) is-percent kwd
12425 checkbox-beg cookie-present)
12426 (catch 'exit
12427 (save-excursion
12428 (beginning-of-line 1)
12429 (setq ltoggle (funcall outline-level))
12430 ;; Three situations are to consider:
12432 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12433 ;; to the top-level ancestor on the headline;
12435 ;; 2. If parent has "recursive" property, repeat up to the
12436 ;; headline setting that property, taking inheritance into
12437 ;; account;
12439 ;; 3. Else, move up to direct parent and proceed only once.
12440 (while (and (setq level (org-up-heading-safe))
12441 (or recursive first)
12442 (>= (point) lim))
12443 (setq first nil cookie-present nil)
12444 (unless (and level
12445 (not (string-match
12446 "\\<checkbox\\>"
12447 (downcase (or (org-entry-get nil "COOKIE_DATA")
12448 "")))))
12449 (throw 'exit nil))
12450 (while (re-search-forward box-re (point-at-eol) t)
12451 (setq cnt-all 0 cnt-done 0 cookie-present t)
12452 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12453 (save-match-data
12454 (unless (outline-next-heading) (throw 'exit nil))
12455 (while (and (looking-at org-complex-heading-regexp)
12456 (> (setq l1 (length (match-string 1))) level))
12457 (setq kwd (and (or recursive (= l1 ltoggle))
12458 (match-string 2)))
12459 (if (or (eq org-provide-todo-statistics 'all-headlines)
12460 (and (eq org-provide-todo-statistics t)
12461 (or (member kwd org-done-keywords)))
12462 (and (listp org-provide-todo-statistics)
12463 (stringp (car org-provide-todo-statistics))
12464 (or (member kwd org-provide-todo-statistics)
12465 (member kwd org-done-keywords)))
12466 (and (listp org-provide-todo-statistics)
12467 (listp (car org-provide-todo-statistics))
12468 (or (member kwd (car org-provide-todo-statistics))
12469 (and (member kwd org-done-keywords)
12470 (member kwd (cadr org-provide-todo-statistics))))))
12471 (setq cnt-all (1+ cnt-all))
12472 (and (eq org-provide-todo-statistics t)
12474 (setq cnt-all (1+ cnt-all))))
12475 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12476 (member kwd org-done-keywords))
12477 (and (listp org-provide-todo-statistics)
12478 (listp (car org-provide-todo-statistics))
12479 (member kwd org-done-keywords)
12480 (member kwd (cadr org-provide-todo-statistics)))
12481 (and (listp org-provide-todo-statistics)
12482 (stringp (car org-provide-todo-statistics))
12483 (member kwd org-done-keywords)))
12484 (setq cnt-done (1+ cnt-done)))
12485 (outline-next-heading)))
12486 (setq new
12487 (if is-percent
12488 (format "[%d%%]" (floor (* 100.0 cnt-done)
12489 (max 1 cnt-all)))
12490 (format "[%d/%d]" cnt-done cnt-all))
12491 ndel (- (match-end 0) checkbox-beg))
12492 (goto-char checkbox-beg)
12493 (insert new)
12494 (delete-region (point) (+ (point) ndel))
12495 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12496 (when cookie-present
12497 (run-hook-with-args 'org-after-todo-statistics-hook
12498 cnt-done (- cnt-all cnt-done))))))
12499 (run-hooks 'org-todo-statistics-hook)))
12501 (defvar org-after-todo-statistics-hook nil
12502 "Hook that is called after a TODO statistics cookie has been updated.
12503 Each function is called with two arguments: the number of not-done entries
12504 and the number of done entries.
12506 For example, the following function, when added to this hook, will switch
12507 an entry to DONE when all children are done, and back to TODO when new
12508 entries are set to a TODO status. Note that this hook is only called
12509 when there is a statistics cookie in the headline!
12511 (defun org-summary-todo (n-done n-not-done)
12512 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12513 (let (org-log-done org-log-states) ; turn off logging
12514 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12517 (defvar org-todo-statistics-hook nil
12518 "Hook that is run whenever Org thinks TODO statistics should be updated.
12519 This hook runs even if there is no statistics cookie present, in which case
12520 `org-after-todo-statistics-hook' would not run.")
12522 (defun org-todo-trigger-tag-changes (state)
12523 "Apply the changes defined in `org-todo-state-tags-triggers'."
12524 (let ((l org-todo-state-tags-triggers)
12525 changes)
12526 (when (or (not state) (equal state ""))
12527 (setq changes (append changes (cdr (assoc "" l)))))
12528 (when (and (stringp state) (> (length state) 0))
12529 (setq changes (append changes (cdr (assoc state l)))))
12530 (when (member state org-not-done-keywords)
12531 (setq changes (append changes (cdr (assq 'todo l)))))
12532 (when (member state org-done-keywords)
12533 (setq changes (append changes (cdr (assq 'done l)))))
12534 (dolist (c changes)
12535 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12537 (defun org-local-logging (value)
12538 "Get logging settings from a property VALUE."
12539 ;; Directly set the variables, they are already local.
12540 (setq org-log-done nil
12541 org-log-repeat nil
12542 org-todo-log-states nil)
12543 (dolist (w (split-string value))
12544 (let (a)
12545 (cond
12546 ((setq a (assoc w org-startup-options))
12547 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12548 (set (nth 1 a) (nth 2 a))))
12549 ((setq a (org-extract-log-state-settings w))
12550 (and (member (car a) org-todo-keywords-1)
12551 (push a org-todo-log-states)))))))
12553 (defun org-get-todo-sequence-head (kwd)
12554 "Return the head of the TODO sequence to which KWD belongs.
12555 If KWD is not set, check if there is a text property remembering the
12556 right sequence."
12557 (let (p)
12558 (cond
12559 ((not kwd)
12560 (or (get-text-property (point-at-bol) 'org-todo-head)
12561 (progn
12562 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12563 nil (point-at-eol)))
12564 (get-text-property p 'org-todo-head))))
12565 ((not (member kwd org-todo-keywords-1))
12566 (car org-todo-keywords-1))
12567 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12569 (defun org-fast-todo-selection ()
12570 "Fast TODO keyword selection with single keys.
12571 Returns the new TODO keyword, or nil if no state change should occur."
12572 (let* ((fulltable org-todo-key-alist)
12573 (done-keywords org-done-keywords) ;; needed for the faces.
12574 (maxlen (apply 'max (mapcar
12575 (lambda (x)
12576 (if (stringp (car x)) (string-width (car x)) 0))
12577 fulltable)))
12578 (expert nil)
12579 (fwidth (+ maxlen 3 1 3))
12580 (ncol (/ (- (window-width) 4) fwidth))
12581 tg cnt e c tbl
12582 groups ingroup)
12583 (save-excursion
12584 (save-window-excursion
12585 (if expert
12586 (set-buffer (get-buffer-create " *Org todo*"))
12587 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12588 (erase-buffer)
12589 (setq-local org-done-keywords done-keywords)
12590 (setq tbl fulltable cnt 0)
12591 (while (setq e (pop tbl))
12592 (cond
12593 ((equal e '(:startgroup))
12594 (push '() groups) (setq ingroup t)
12595 (unless (= cnt 0)
12596 (setq cnt 0)
12597 (insert "\n"))
12598 (insert "{ "))
12599 ((equal e '(:endgroup))
12600 (setq ingroup nil cnt 0)
12601 (insert "}\n"))
12602 ((equal e '(:newline))
12603 (unless (= cnt 0)
12604 (setq cnt 0)
12605 (insert "\n")
12606 (setq e (car tbl))
12607 (while (equal (car tbl) '(:newline))
12608 (insert "\n")
12609 (setq tbl (cdr tbl)))))
12611 (setq tg (car e) c (cdr e))
12612 (when ingroup (push tg (car groups)))
12613 (setq tg (org-add-props tg nil 'face
12614 (org-get-todo-face tg)))
12615 (when (and (= cnt 0) (not ingroup)) (insert " "))
12616 (insert "[" c "] " tg (make-string
12617 (- fwidth 4 (length tg)) ?\ ))
12618 (when (= (setq cnt (1+ cnt)) ncol)
12619 (insert "\n")
12620 (when ingroup (insert " "))
12621 (setq cnt 0)))))
12622 (insert "\n")
12623 (goto-char (point-min))
12624 (unless expert (org-fit-window-to-buffer))
12625 (message "[a-z..]:Set [SPC]:clear")
12626 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12627 (cond
12628 ((or (= c ?\C-g)
12629 (and (= c ?q) (not (rassoc c fulltable))))
12630 (setq quit-flag t))
12631 ((= c ?\ ) nil)
12632 ((setq e (rassoc c fulltable) tg (car e))
12634 (t (setq quit-flag t)))))))
12636 (defun org-entry-is-todo-p ()
12637 (member (org-get-todo-state) org-not-done-keywords))
12639 (defun org-entry-is-done-p ()
12640 (member (org-get-todo-state) org-done-keywords))
12642 (defun org-get-todo-state ()
12643 "Return the TODO keyword of the current subtree."
12644 (save-excursion
12645 (org-back-to-heading t)
12646 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12647 (match-end 2)
12648 (match-string 2))))
12650 (defun org-at-date-range-p (&optional inactive-ok)
12651 "Non-nil if point is inside a date range.
12653 When optional argument INACTIVE-OK is non-nil, also consider
12654 inactive time ranges.
12656 When this function returns a non-nil value, match data is set
12657 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12658 on INACTIVE-OK."
12659 (interactive)
12660 (save-excursion
12661 (catch 'exit
12662 (let ((pos (point)))
12663 (skip-chars-backward "^[<\r\n")
12664 (skip-chars-backward "<[")
12665 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12666 (>= (match-end 0) pos)
12667 (throw 'exit t))
12668 (skip-chars-backward "^<[\r\n")
12669 (skip-chars-backward "<[")
12670 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12671 (>= (match-end 0) pos)
12672 (throw 'exit t)))
12673 nil)))
12675 (defun org-get-repeat (&optional timestamp)
12676 "Check if there is a time-stamp with repeater in this entry.
12678 Return the repeater, as a string, or nil. Also return nil when
12679 this function is called before first heading.
12681 When optional argument TIMESTAMP is a string, extract the
12682 repeater from there instead."
12683 (save-match-data
12684 (cond (timestamp
12685 (and (string-match org-repeat-re timestamp)
12686 (match-string-no-properties 1 timestamp)))
12687 ((org-before-first-heading-p) nil)
12689 (save-excursion
12690 (org-back-to-heading t)
12691 (let ((end (org-entry-end-position)))
12692 (catch :repeat
12693 (while (re-search-forward org-repeat-re end t)
12694 (when (save-match-data (org-at-timestamp-p 'agenda))
12695 (throw :repeat (match-string-no-properties 1)))))))))))
12697 (defvar org-last-changed-timestamp)
12698 (defvar org-last-inserted-timestamp)
12699 (defvar org-log-post-message)
12700 (defvar org-log-note-purpose)
12701 (defvar org-log-note-how nil)
12702 (defvar org-log-note-extra)
12703 (defun org-auto-repeat-maybe (done-word)
12704 "Check if the current headline contains a repeated time-stamp.
12706 If yes, set TODO state back to what it was and change the base date
12707 of repeating deadline/scheduled time stamps to new date.
12709 This function is run automatically after each state change to a DONE state."
12710 (let* ((repeat (org-get-repeat))
12711 (aa (assoc org-last-state org-todo-kwd-alist))
12712 (interpret (nth 1 aa))
12713 (head (nth 2 aa))
12714 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12715 (msg "Entry repeats: ")
12716 (org-log-done nil)
12717 (org-todo-log-states nil)
12718 (end (copy-marker (org-entry-end-position))))
12719 (unwind-protect
12720 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
12721 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
12722 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
12723 (and (stringp org-todo-repeat-to-state)
12724 org-todo-repeat-to-state)
12725 (and org-todo-repeat-to-state org-last-state))))
12726 (org-todo (cond
12727 ((and to-state (member to-state org-todo-keywords-1))
12728 to-state)
12729 ((eq interpret 'type) org-last-state)
12730 (head)
12731 (t 'none))))
12732 (org-back-to-heading t)
12733 (org-add-planning-info nil nil 'closed)
12734 ;; When `org-log-repeat' is non-nil or entry contains
12735 ;; a clock, set LAST_REPEAT property.
12736 (when (or org-log-repeat
12737 (catch :clock
12738 (save-excursion
12739 (while (re-search-forward org-clock-line-re end t)
12740 (when (org-at-clock-log-p) (throw :clock t))))))
12741 (org-entry-put nil "LAST_REPEAT" (format-time-string
12742 (org-time-stamp-format t t)
12743 (current-time))))
12744 (when org-log-repeat
12745 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12746 (memq 'org-add-log-note post-command-hook))
12747 ;; We are already setup for some record.
12748 (when (eq org-log-repeat 'note)
12749 ;; Make sure we take a note, not only a time stamp.
12750 (setq org-log-note-how 'note))
12751 ;; Set up for taking a record.
12752 (org-add-log-setup 'state
12753 (or done-word (car org-done-keywords))
12754 org-last-state
12755 org-log-repeat)))
12756 (let ((planning-re (regexp-opt
12757 (list org-scheduled-string org-deadline-string))))
12758 (while (re-search-forward org-ts-regexp end t)
12759 (let* ((ts (match-string 0))
12760 (planning? (org-at-planning-p))
12761 (type (if (not planning?) "Plain:"
12762 (save-excursion
12763 (re-search-backward
12764 planning-re (line-beginning-position) t)
12765 (match-string 0)))))
12766 (cond
12767 ;; Ignore fake time-stamps (e.g., within comments).
12768 ((not (org-at-timestamp-p 'agenda)))
12769 ;; Time-stamps without a repeater are usually
12770 ;; skipped. However, a SCHEDULED time-stamp without
12771 ;; one is removed, as they are no longer relevant.
12772 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12773 ts))
12774 (when (equal type org-scheduled-string)
12775 (org-remove-timestamp-with-keyword type)))
12777 (let ((n (string-to-number (match-string 2 ts)))
12778 (what (match-string 3 ts)))
12779 (when (equal what "w") (setq n (* n 7) what "d"))
12780 (when (and (equal what "h")
12781 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
12782 ts)))
12783 (user-error
12784 "Cannot repeat in Repeat in %d hour(s) because no hour \
12785 has been set"
12787 ;; Preparation, see if we need to modify the start
12788 ;; date for the change.
12789 (when (match-end 1)
12790 (let ((time (save-match-data
12791 (org-time-string-to-time ts))))
12792 (cond
12793 ((equal (match-string 1 ts) ".")
12794 ;; Shift starting date to today
12795 (org-timestamp-change
12796 (- (org-today) (time-to-days time))
12797 'day))
12798 ((equal (match-string 1 ts) "+")
12799 (let ((nshiftmax 10)
12800 (nshift 0))
12801 (while (or (= nshift 0)
12802 (not (time-less-p (current-time) time)))
12803 (when (= (cl-incf nshift) nshiftmax)
12804 (or (y-or-n-p
12805 (format "%d repeater intervals were not \
12806 enough to shift date past today. Continue? "
12807 nshift))
12808 (user-error "Abort")))
12809 (org-timestamp-change n (cdr (assoc what whata)))
12810 (org-in-regexp org-ts-regexp3)
12811 (setq ts (match-string 1))
12812 (setq time
12813 (save-match-data
12814 (org-time-string-to-time ts)))))
12815 (org-timestamp-change (- n) (cdr (assoc what whata)))
12816 ;; Rematch, so that we have everything in place
12817 ;; for the real shift.
12818 (org-in-regexp org-ts-regexp3)
12819 (setq ts (match-string 1))
12820 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
12821 ts)))))
12822 (save-excursion
12823 (org-timestamp-change n (cdr (assoc what whata)) nil t))
12824 (setq msg
12825 (concat
12826 msg type " " org-last-changed-timestamp " "))))))))
12827 (setq org-log-post-message msg)
12828 (message "%s" msg))
12829 (set-marker end nil))))
12831 (defun org-show-todo-tree (arg)
12832 "Make a compact tree which shows all headlines marked with TODO.
12833 The tree will show the lines where the regexp matches, and all higher
12834 headlines above the match.
12835 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
12836 With a numeric prefix N, construct a sparse tree for the Nth element
12837 of `org-todo-keywords-1'."
12838 (interactive "P")
12839 (let ((case-fold-search nil)
12840 (kwd-re
12841 (cond ((null arg) org-not-done-regexp)
12842 ((equal arg '(4))
12843 (let ((kwd
12844 (completing-read "Keyword (or KWD1|KWD2|...): "
12845 (mapcar #'list org-todo-keywords-1))))
12846 (concat "\\("
12847 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12848 "\\)\\>")))
12849 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12850 (regexp-quote (nth (1- (prefix-numeric-value arg))
12851 org-todo-keywords-1)))
12852 (t (user-error "Invalid prefix argument: %s" arg)))))
12853 (message "%d TODO entries found"
12854 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12856 (defun org--deadline-or-schedule (arg type time)
12857 "Insert DEADLINE or SCHEDULE information in current entry.
12858 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
12859 `org-schedule' for information about ARG and TIME arguments."
12860 (let* ((deadline? (eq type 'deadline))
12861 (keyword (if deadline? org-deadline-string org-scheduled-string))
12862 (log (if deadline? org-log-redeadline org-log-reschedule))
12863 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
12864 (old-date-time (and old-date (org-time-string-to-time old-date)))
12865 ;; Save repeater cookie from either TIME or current scheduled
12866 ;; time stamp. We are going to insert it back at the end of
12867 ;; the process.
12868 (repeater (or (and (org-string-nw-p time)
12869 ;; We use `org-repeat-re' because we need
12870 ;; to tell the difference between a real
12871 ;; repeater and a time delta, e.g. "+2d".
12872 (string-match org-repeat-re time)
12873 (match-string 1 time))
12874 (and (org-string-nw-p old-date)
12875 (string-match "\\([.+-]+[0-9]+[hdwmy]\
12876 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
12877 old-date)
12878 (match-string 1 old-date)))))
12879 (pcase arg
12880 (`(4)
12881 (if (not old-date)
12882 (message (if deadline? "Entry had no deadline to remove"
12883 "Entry was not scheduled"))
12884 (when (and old-date log)
12885 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
12886 nil old-date log))
12887 (org-remove-timestamp-with-keyword keyword)
12888 (message (if deadline? "Entry no longer has a deadline."
12889 "Entry is no longer scheduled."))))
12890 (`(16)
12891 (save-excursion
12892 (org-back-to-heading t)
12893 (let ((regexp (if deadline? org-deadline-time-regexp
12894 org-scheduled-time-regexp)))
12895 (if (not (re-search-forward regexp (line-end-position 2) t))
12896 (user-error (if deadline? "No deadline information to update"
12897 "No scheduled information to update"))
12898 (let* ((rpl0 (match-string 1))
12899 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
12900 (msg (if deadline? "Warn starting from" "Delay until")))
12901 (replace-match
12902 (concat keyword
12903 " <" rpl
12904 (format " -%dd"
12905 (abs (- (time-to-days
12906 (save-match-data
12907 (org-read-date
12908 nil t nil msg old-date-time)))
12909 (time-to-days old-date-time))))
12910 ">") t t))))))
12912 (org-add-planning-info type time 'closed)
12913 (when (and old-date
12915 (not (equal old-date org-last-inserted-timestamp)))
12916 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
12917 org-last-inserted-timestamp
12918 old-date
12919 log))
12920 (when repeater
12921 (save-excursion
12922 (org-back-to-heading t)
12923 (when (re-search-forward
12924 (concat keyword " " org-last-inserted-timestamp)
12925 (line-end-position 2)
12927 (goto-char (1- (match-end 0)))
12928 (insert " " repeater)
12929 (setq org-last-inserted-timestamp
12930 (concat (substring org-last-inserted-timestamp 0 -1)
12931 " " repeater
12932 (substring org-last-inserted-timestamp -1))))))
12933 (message (if deadline? "Deadline on %s" "Scheduled to %s")
12934 org-last-inserted-timestamp)))))
12936 (defun org-deadline (arg &optional time)
12937 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12938 With one universal prefix argument, remove any deadline from the item.
12939 With two universal prefix arguments, prompt for a warning delay.
12940 With argument TIME, set the deadline at the corresponding date. TIME
12941 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12942 (interactive "P")
12943 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12944 (org-map-entries
12945 (lambda () (org--deadline-or-schedule arg 'deadline time))
12947 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12948 'region-start-level
12949 'region)
12950 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12951 (org--deadline-or-schedule arg 'deadline time)))
12953 (defun org-schedule (arg &optional time)
12954 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12955 With one universal prefix argument, remove any scheduling date from the item.
12956 With two universal prefix arguments, prompt for a delay cookie.
12957 With argument TIME, scheduled at the corresponding date. TIME can
12958 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12959 (interactive "P")
12960 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12961 (org-map-entries
12962 (lambda () (org--deadline-or-schedule arg 'scheduled time))
12964 (if (eq org-loop-over-headlines-in-active-region 'start-level)
12965 'region-start-level
12966 'region)
12967 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
12968 (org--deadline-or-schedule arg 'scheduled time)))
12970 (defun org-get-scheduled-time (pom &optional inherit)
12971 "Get the scheduled time as a time tuple, of a format suitable
12972 for calling org-schedule with, or if there is no scheduling,
12973 returns nil."
12974 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12975 (when time
12976 (apply 'encode-time (org-parse-time-string time)))))
12978 (defun org-get-deadline-time (pom &optional inherit)
12979 "Get the deadline as a time tuple, of a format suitable for
12980 calling org-deadline with, or if there is no scheduling, returns
12981 nil."
12982 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12983 (when time
12984 (apply 'encode-time (org-parse-time-string time)))))
12986 (defun org-remove-timestamp-with-keyword (keyword)
12987 "Remove all time stamps with KEYWORD in the current entry."
12988 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12989 beg)
12990 (save-excursion
12991 (org-back-to-heading t)
12992 (setq beg (point))
12993 (outline-next-heading)
12994 (while (re-search-backward re beg t)
12995 (replace-match "")
12996 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12997 (equal (char-before) ?\ ))
12998 (backward-delete-char 1)
12999 (when (string-match "^[ \t]*$" (buffer-substring
13000 (point-at-bol) (point-at-eol)))
13001 (delete-region (point-at-bol)
13002 (min (point-max) (1+ (point-at-eol))))))))))
13004 (defvar org-time-was-given) ; dynamically scoped parameter
13005 (defvar org-end-time-was-given) ; dynamically scoped parameter
13007 (defun org-at-planning-p ()
13008 "Non-nil when point is on a planning info line."
13009 ;; This is as accurate and faster than `org-element-at-point' since
13010 ;; planning info location is fixed in the section.
13011 (org-with-wide-buffer
13012 (beginning-of-line)
13013 (and (looking-at-p org-planning-line-re)
13014 (eq (point)
13015 (ignore-errors
13016 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13017 (org-back-to-heading t)
13018 (org-with-limited-levels (org-back-to-heading t)))
13019 (line-beginning-position 2))))))
13021 (defun org-add-planning-info (what &optional time &rest remove)
13022 "Insert new timestamp with keyword in the planning line.
13023 WHAT indicates what kind of time stamp to add. It is a symbol
13024 among `closed', `deadline', `scheduled' and nil. TIME indicates
13025 the time to use. If none is given, the user is prompted for
13026 a date. REMOVE indicates what kind of entries to remove. An old
13027 WHAT entry will also be removed."
13028 (let (org-time-was-given org-end-time-was-given default-time default-input)
13029 (catch 'exit
13030 (when (and (memq what '(scheduled deadline))
13031 (or (not time)
13032 (and (stringp time)
13033 (string-match "^[-+]+[0-9]" time))))
13034 ;; Try to get a default date/time from existing timestamp
13035 (save-excursion
13036 (org-back-to-heading t)
13037 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13038 (when (re-search-forward (if (eq what 'scheduled)
13039 org-scheduled-time-regexp
13040 org-deadline-time-regexp)
13041 end t)
13042 (setq ts (match-string 1)
13043 default-time (apply 'encode-time (org-parse-time-string ts))
13044 default-input (and ts (org-get-compact-tod ts)))))))
13045 (when what
13046 (setq time
13047 (if (stringp time)
13048 ;; This is a string (relative or absolute), set
13049 ;; proper date.
13050 (apply #'encode-time
13051 (org-read-date-analyze
13052 time default-time (decode-time default-time)))
13053 ;; If necessary, get the time from the user
13054 (or time (org-read-date nil 'to-time nil nil
13055 default-time default-input)))))
13057 (org-with-wide-buffer
13058 (org-back-to-heading t)
13059 (forward-line)
13060 (unless (bolp) (insert "\n"))
13061 (cond ((looking-at-p org-planning-line-re)
13062 ;; Move to current indentation.
13063 (skip-chars-forward " \t")
13064 ;; Check if we have to remove something.
13065 (dolist (type (if what (cons what remove) remove))
13066 (save-excursion
13067 (when (re-search-forward
13068 (cl-case type
13069 (closed org-closed-time-regexp)
13070 (deadline org-deadline-time-regexp)
13071 (scheduled org-scheduled-time-regexp)
13072 (otherwise
13073 (error "Invalid planning type: %s" type)))
13074 (line-end-position) t)
13075 ;; Delete until next keyword or end of line.
13076 (delete-region
13077 (match-beginning 0)
13078 (if (re-search-forward org-keyword-time-not-clock-regexp
13079 (line-end-position)
13081 (match-beginning 0)
13082 (line-end-position))))))
13083 ;; If there is nothing more to add and no more keyword
13084 ;; is left, remove the line completely.
13085 (if (and (looking-at-p "[ \t]*$") (not what))
13086 (delete-region (line-beginning-position)
13087 (line-beginning-position 2))
13088 ;; If we removed last keyword, do not leave trailing
13089 ;; white space at the end of line.
13090 (let ((p (point)))
13091 (save-excursion
13092 (end-of-line)
13093 (unless (= (skip-chars-backward " \t" p) 0)
13094 (delete-region (point) (line-end-position)))))))
13095 ((not what) (throw 'exit nil)) ; Nothing to do.
13096 (t (insert-before-markers "\n")
13097 (backward-char 1)
13098 (when org-adapt-indentation
13099 (indent-to-column (1+ (org-outline-level))))))
13100 (when what
13101 ;; Insert planning keyword.
13102 (insert (cl-case what
13103 (closed org-closed-string)
13104 (deadline org-deadline-string)
13105 (scheduled org-scheduled-string)
13106 (otherwise (error "Invalid planning type: %s" what)))
13107 " ")
13108 ;; Insert associated timestamp.
13109 (let ((ts (org-insert-time-stamp
13110 time
13111 (or org-time-was-given
13112 (and (eq what 'closed) org-log-done-with-time))
13113 (eq what 'closed)
13114 nil nil (list org-end-time-was-given))))
13115 (unless (eolp) (insert " "))
13116 ts))))))
13118 (defvar org-log-note-marker (make-marker)
13119 "Marker pointing at the entry where the note is to be inserted.")
13120 (defvar org-log-note-purpose nil)
13121 (defvar org-log-note-state nil)
13122 (defvar org-log-note-previous-state nil)
13123 (defvar org-log-note-extra nil)
13124 (defvar org-log-note-window-configuration nil)
13125 (defvar org-log-note-return-to (make-marker))
13126 (defvar org-log-note-effective-time nil
13127 "Remembered current time so that dynamically scoped
13128 `org-extend-today-until' affects timestamps in state change log")
13130 (defvar org-log-post-message nil
13131 "Message to be displayed after a log note has been stored.
13132 The auto-repeater uses this.")
13134 (defun org-add-note ()
13135 "Add a note to the current entry.
13136 This is done in the same way as adding a state change note."
13137 (interactive)
13138 (org-add-log-setup 'note))
13140 (defun org-log-beginning (&optional create)
13141 "Return expected start of log notes in current entry.
13142 When optional argument CREATE is non-nil, the function creates
13143 a drawer to store notes, if necessary. Returned position ignores
13144 narrowing."
13145 (org-with-wide-buffer
13146 (let ((drawer (org-log-into-drawer)))
13147 (cond
13148 (drawer
13149 (org-end-of-meta-data)
13150 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13151 (end (if (org-at-heading-p) (point)
13152 (save-excursion (outline-next-heading) (point))))
13153 (case-fold-search t))
13154 (catch 'exit
13155 ;; Try to find existing drawer.
13156 (while (re-search-forward regexp end t)
13157 (let ((element (org-element-at-point)))
13158 (when (eq (org-element-type element) 'drawer)
13159 (let ((cend (org-element-property :contents-end element)))
13160 (when (and (not org-log-states-order-reversed) cend)
13161 (goto-char cend)))
13162 (throw 'exit nil))))
13163 ;; No drawer found. Create one, if permitted.
13164 (when create
13165 (unless (bolp) (insert "\n"))
13166 (let ((beg (point)))
13167 (insert ":" drawer ":\n:END:\n")
13168 (org-indent-region beg (point))
13169 (org-flag-region
13170 (line-end-position -1) (1- (point)) t 'org-hide-drawer))
13171 (end-of-line -1)))))
13173 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13174 (skip-chars-forward " \t\n")
13175 (beginning-of-line)
13176 (unless org-log-states-order-reversed
13177 (org-skip-over-state-notes)
13178 (skip-chars-backward " \t\n")
13179 (forward-line)))))
13180 (if (bolp) (point) (line-beginning-position 2))))
13182 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13183 "Set up the post command hook to take a note.
13184 If this is about to TODO state change, the new state is expected in STATE.
13185 HOW is an indicator what kind of note should be created.
13186 EXTRA is additional text that will be inserted into the notes buffer."
13187 (move-marker org-log-note-marker (point))
13188 (setq org-log-note-purpose purpose
13189 org-log-note-state state
13190 org-log-note-previous-state prev-state
13191 org-log-note-how how
13192 org-log-note-extra extra
13193 org-log-note-effective-time (org-current-effective-time))
13194 (add-hook 'post-command-hook 'org-add-log-note 'append))
13196 (defun org-skip-over-state-notes ()
13197 "Skip past the list of State notes in an entry."
13198 (when (ignore-errors (goto-char (org-in-item-p)))
13199 (let* ((struct (org-list-struct))
13200 (prevs (org-list-prevs-alist struct))
13201 (regexp
13202 (concat "[ \t]*- +"
13203 (replace-regexp-in-string
13204 " +" " +"
13205 (org-replace-escapes
13206 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13207 `(("%d" . ,org-ts-regexp-inactive)
13208 ("%D" . ,org-ts-regexp)
13209 ("%s" . "\\(?:\"\\S-+\"\\)?")
13210 ("%S" . "\\(?:\"\\S-+\"\\)?")
13211 ("%t" . ,org-ts-regexp-inactive)
13212 ("%T" . ,org-ts-regexp)
13213 ("%u" . ".*?")
13214 ("%U" . ".*?")))))))
13215 (while (looking-at-p regexp)
13216 (goto-char (or (org-list-get-next-item (point) struct prevs)
13217 (org-list-get-item-end (point) struct)))))))
13219 (defun org-add-log-note (&optional _purpose)
13220 "Pop up a window for taking a note, and add this note later."
13221 (remove-hook 'post-command-hook 'org-add-log-note)
13222 (setq org-log-note-window-configuration (current-window-configuration))
13223 (delete-other-windows)
13224 (move-marker org-log-note-return-to (point))
13225 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13226 (goto-char org-log-note-marker)
13227 (org-switch-to-buffer-other-window "*Org Note*")
13228 (erase-buffer)
13229 (if (memq org-log-note-how '(time state))
13230 (org-store-log-note)
13231 (let ((org-inhibit-startup t)) (org-mode))
13232 (insert (format "# Insert note for %s.
13233 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13234 (cl-case org-log-note-purpose
13235 (clock-out "stopped clock")
13236 (done "closed todo item")
13237 (reschedule "rescheduling")
13238 (delschedule "no longer scheduled")
13239 (redeadline "changing deadline")
13240 (deldeadline "removing deadline")
13241 (refile "refiling")
13242 (note "this entry")
13243 (state
13244 (format "state change from \"%s\" to \"%s\""
13245 (or org-log-note-previous-state "")
13246 (or org-log-note-state "")))
13247 (t (error "This should not happen")))))
13248 (when org-log-note-extra (insert org-log-note-extra))
13249 (setq-local org-finish-function 'org-store-log-note)
13250 (run-hooks 'org-log-buffer-setup-hook)))
13252 (defvar org-note-abort nil) ; dynamically scoped
13253 (defun org-store-log-note ()
13254 "Finish taking a log note, and insert it to where it belongs."
13255 (let ((txt (prog1 (buffer-string)
13256 (kill-buffer)))
13257 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13258 lines)
13259 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13260 (setq txt (replace-match "" t t txt)))
13261 (when (string-match "\\s-+\\'" txt)
13262 (setq txt (replace-match "" t t txt)))
13263 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13264 (when (org-string-nw-p note)
13265 (setq note
13266 (org-replace-escapes
13267 note
13268 (list (cons "%u" (user-login-name))
13269 (cons "%U" user-full-name)
13270 (cons "%t" (format-time-string
13271 (org-time-stamp-format 'long 'inactive)
13272 org-log-note-effective-time))
13273 (cons "%T" (format-time-string
13274 (org-time-stamp-format 'long nil)
13275 org-log-note-effective-time))
13276 (cons "%d" (format-time-string
13277 (org-time-stamp-format nil 'inactive)
13278 org-log-note-effective-time))
13279 (cons "%D" (format-time-string
13280 (org-time-stamp-format nil nil)
13281 org-log-note-effective-time))
13282 (cons "%s" (cond
13283 ((not org-log-note-state) "")
13284 ((string-match-p org-ts-regexp
13285 org-log-note-state)
13286 (format "\"[%s]\""
13287 (substring org-log-note-state 1 -1)))
13288 (t (format "\"%s\"" org-log-note-state))))
13289 (cons "%S"
13290 (cond
13291 ((not org-log-note-previous-state) "")
13292 ((string-match-p org-ts-regexp
13293 org-log-note-previous-state)
13294 (format "\"[%s]\""
13295 (substring
13296 org-log-note-previous-state 1 -1)))
13297 (t (format "\"%s\""
13298 org-log-note-previous-state)))))))
13299 (when lines (setq note (concat note " \\\\")))
13300 (push note lines))
13301 (when (and lines (not org-note-abort))
13302 (with-current-buffer (marker-buffer org-log-note-marker)
13303 (org-with-wide-buffer
13304 ;; Find location for the new note.
13305 (goto-char org-log-note-marker)
13306 (set-marker org-log-note-marker nil)
13307 ;; Note associated to a clock is to be located right after
13308 ;; the clock. Do not move point.
13309 (unless (eq org-log-note-purpose 'clock-out)
13310 (goto-char (org-log-beginning t)))
13311 ;; Make sure point is at the beginning of an empty line.
13312 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13313 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13314 ;; In an existing list, add a new item at the top level.
13315 ;; Otherwise, indent line like a regular one.
13316 (let ((itemp (org-in-item-p)))
13317 (if itemp
13318 (indent-line-to
13319 (let ((struct (save-excursion
13320 (goto-char itemp) (org-list-struct))))
13321 (org-list-get-ind (org-list-get-top-point struct) struct)))
13322 (org-indent-line)))
13323 (insert (org-list-bullet-string "-") (pop lines))
13324 (let ((ind (org-list-item-body-column (line-beginning-position))))
13325 (dolist (line lines)
13326 (insert "\n")
13327 (indent-line-to ind)
13328 (insert line)))
13329 (message "Note stored")
13330 (org-back-to-heading t))
13331 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13332 ;; from within `org-add-log-note' because `buffer-undo-list'
13333 ;; is then modified outside of `org-with-remote-undo'.
13334 (when (eq this-command 'org-agenda-todo)
13335 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13336 ;; Don't add undo information when called from `org-agenda-todo'.
13337 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13338 (set-window-configuration org-log-note-window-configuration)
13339 (with-current-buffer (marker-buffer org-log-note-return-to)
13340 (goto-char org-log-note-return-to))
13341 (move-marker org-log-note-return-to nil)
13342 (when org-log-post-message (message "%s" org-log-post-message))))
13344 (defun org-remove-empty-drawer-at (pos)
13345 "Remove an empty drawer at position POS.
13346 POS may also be a marker."
13347 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13348 (org-with-wide-buffer
13349 (goto-char pos)
13350 (let ((drawer (org-element-at-point)))
13351 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13352 (not (org-element-property :contents-begin drawer)))
13353 (delete-region (org-element-property :begin drawer)
13354 (progn (goto-char (org-element-property :end drawer))
13355 (skip-chars-backward " \r\t\n")
13356 (forward-line)
13357 (point))))))))
13359 (defvar org-ts-type nil)
13360 (defun org-sparse-tree (&optional arg type)
13361 "Create a sparse tree, prompt for the details.
13362 This command can create sparse trees. You first need to select the type
13363 of match used to create the tree:
13365 t Show all TODO entries.
13366 T Show entries with a specific TODO keyword.
13367 m Show entries selected by a tags/property match.
13368 p Enter a property name and its value (both with completion on existing
13369 names/values) and show entries with that property.
13370 r Show entries matching a regular expression (`/' can be used as well).
13371 b Show deadlines and scheduled items before a date.
13372 a Show deadlines and scheduled items after a date.
13373 d Show deadlines due within `org-deadline-warning-days'.
13374 D Show deadlines and scheduled items between a date range."
13375 (interactive "P")
13376 (setq type (or type org-sparse-tree-default-date-type))
13377 (setq org-ts-type type)
13378 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13379 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13380 \[c]ycle through date types: %s"
13381 (cl-case type
13382 (all "all timestamps")
13383 (scheduled "only scheduled")
13384 (deadline "only deadline")
13385 (active "only active timestamps")
13386 (inactive "only inactive timestamps")
13387 (closed "with a closed time-stamp")
13388 (otherwise "scheduled/deadline")))
13389 (let ((answer (read-char-exclusive)))
13390 (cl-case answer
13392 (org-sparse-tree
13394 (cadr
13395 (memq type '(nil all scheduled deadline active inactive closed)))))
13396 (?d (call-interactively 'org-check-deadlines))
13397 (?b (call-interactively 'org-check-before-date))
13398 (?a (call-interactively 'org-check-after-date))
13399 (?D (call-interactively 'org-check-dates-range))
13400 (?t (call-interactively 'org-show-todo-tree))
13401 (?T (org-show-todo-tree '(4)))
13402 (?m (call-interactively 'org-match-sparse-tree))
13403 ((?p ?P)
13404 (let* ((kwd (completing-read
13405 "Property: " (mapcar #'list (org-buffer-property-keys))))
13406 (value (completing-read
13407 "Value: " (mapcar #'list (org-property-values kwd)))))
13408 (unless (string-match "\\`{.*}\\'" value)
13409 (setq value (concat "\"" value "\"")))
13410 (org-match-sparse-tree arg (concat kwd "=" value))))
13411 ((?r ?R ?/) (call-interactively 'org-occur))
13412 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13414 (defvar-local org-occur-highlights nil
13415 "List of overlays used for occur matches.")
13416 (defvar-local org-occur-parameters nil
13417 "Parameters of the active org-occur calls.
13418 This is a list, each call to org-occur pushes as cons cell,
13419 containing the regular expression and the callback, onto the list.
13420 The list can contain several entries if `org-occur' has been called
13421 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13422 will only contain one set of parameters. When the highlights are
13423 removed (for example with `C-c C-c', or with the next edit (depending
13424 on `org-remove-highlights-with-change'), this variable is emptied
13425 as well.")
13427 (defun org-occur (regexp &optional keep-previous callback)
13428 "Make a compact tree which shows all matches of REGEXP.
13430 The tree will show the lines where the regexp matches, and any other context
13431 defined in `org-show-context-detail', which see.
13433 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13434 done by a previous call to `org-occur' will be kept, to allow stacking of
13435 calls to this command.
13437 Optional argument CALLBACK can be a function of no argument. In this case,
13438 it is called with point at the end of the match, match data being set
13439 accordingly. Current match is shown only if the return value is non-nil.
13440 The function must neither move point nor alter narrowing."
13441 (interactive "sRegexp: \nP")
13442 (when (equal regexp "")
13443 (user-error "Regexp cannot be empty"))
13444 (unless keep-previous
13445 (org-remove-occur-highlights nil nil t))
13446 (push (cons regexp callback) org-occur-parameters)
13447 (let ((cnt 0))
13448 (save-excursion
13449 (goto-char (point-min))
13450 (when (or (not keep-previous) ; do not want to keep
13451 (not org-occur-highlights)) ; no previous matches
13452 ;; hide everything
13453 (org-overview))
13454 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13455 (isearch-no-upper-case-p regexp t)
13456 org-occur-case-fold-search)))
13457 (while (re-search-forward regexp nil t)
13458 (when (or (not callback)
13459 (save-match-data (funcall callback)))
13460 (setq cnt (1+ cnt))
13461 (when org-highlight-sparse-tree-matches
13462 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13463 (org-show-context 'occur-tree)))))
13464 (when org-remove-highlights-with-change
13465 (add-hook 'before-change-functions 'org-remove-occur-highlights
13466 nil 'local))
13467 (unless org-sparse-tree-open-archived-trees
13468 (org-hide-archived-subtrees (point-min) (point-max)))
13469 (run-hooks 'org-occur-hook)
13470 (when (called-interactively-p 'interactive)
13471 (message "%d match(es) for regexp %s" cnt regexp))
13472 cnt))
13474 (defun org-occur-next-match (&optional n _reset)
13475 "Function for `next-error-function' to find sparse tree matches.
13476 N is the number of matches to move, when negative move backwards.
13477 This function always goes back to the starting point when no
13478 match is found."
13479 (let* ((limit (if (< n 0) (point-min) (point-max)))
13480 (search-func (if (< n 0)
13481 'previous-single-char-property-change
13482 'next-single-char-property-change))
13483 (n (abs n))
13484 (pos (point))
13486 (catch 'exit
13487 (while (setq p1 (funcall search-func (point) 'org-type))
13488 (when (equal p1 limit)
13489 (goto-char pos)
13490 (user-error "No more matches"))
13491 (when (equal (get-char-property p1 'org-type) 'org-occur)
13492 (setq n (1- n))
13493 (when (= n 0)
13494 (goto-char p1)
13495 (throw 'exit (point))))
13496 (goto-char p1))
13497 (goto-char p1)
13498 (user-error "No more matches"))))
13500 (defun org-highlight-new-match (beg end)
13501 "Highlight from BEG to END and mark the highlight is an occur headline."
13502 (let ((ov (make-overlay beg end)))
13503 (overlay-put ov 'face 'secondary-selection)
13504 (overlay-put ov 'org-type 'org-occur)
13505 (push ov org-occur-highlights)))
13507 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13508 "Remove the occur highlights from the buffer.
13509 BEG and END are ignored. If NOREMOVE is nil, remove this function
13510 from the `before-change-functions' in the current buffer."
13511 (interactive)
13512 (unless org-inhibit-highlight-removal
13513 (mapc #'delete-overlay org-occur-highlights)
13514 (setq org-occur-highlights nil)
13515 (setq org-occur-parameters nil)
13516 (unless noremove
13517 (remove-hook 'before-change-functions
13518 'org-remove-occur-highlights 'local))))
13520 ;;;; Priorities
13522 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13523 "Regular expression matching the priority indicator.")
13525 (defvar org-remove-priority-next-time nil)
13527 (defun org-priority-up ()
13528 "Increase the priority of the current item."
13529 (interactive)
13530 (org-priority 'up))
13532 (defun org-priority-down ()
13533 "Decrease the priority of the current item."
13534 (interactive)
13535 (org-priority 'down))
13537 (defun org-priority (&optional action show)
13538 "Change the priority of an item.
13540 When called interactively with a `\\[universal-argument]' prefix,
13541 show the priority in the minibuffer instead of changing it.
13543 When called programatically, ACTION can be `set', `up', `down',
13544 or a character."
13545 (interactive "P")
13546 (when show
13547 ;; Deprecation warning inserted for Org 9.2; once enough time has
13548 ;; passed the SHOW argument should be removed.
13549 (warn "`org-priority' called with deprecated SHOW argument"))
13550 (if (equal action '(4))
13551 (org-show-priority)
13552 (unless org-enable-priority-commands
13553 (user-error "Priority commands are disabled"))
13554 (setq action (or action 'set))
13555 (let (current new news have remove)
13556 (save-excursion
13557 (org-back-to-heading t)
13558 (when (looking-at org-priority-regexp)
13559 (setq current (string-to-char (match-string 2))
13560 have t))
13561 (cond
13562 ((eq action 'remove)
13563 (setq remove t new ?\ ))
13564 ((or (eq action 'set)
13565 (integerp action))
13566 (if (not (eq action 'set))
13567 (setq new action)
13568 (message "Priority %c-%c, SPC to remove: "
13569 org-highest-priority org-lowest-priority)
13570 (save-match-data
13571 (setq new (read-char-exclusive))))
13572 (when (and (= (upcase org-highest-priority) org-highest-priority)
13573 (= (upcase org-lowest-priority) org-lowest-priority))
13574 (setq new (upcase new)))
13575 (cond ((equal new ?\s) (setq remove t))
13576 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13577 (user-error "Priority must be between `%c' and `%c'"
13578 org-highest-priority org-lowest-priority))))
13579 ((eq action 'up)
13580 (setq new (if have
13581 (1- current) ; normal cycling
13582 ;; last priority was empty
13583 (if (eq last-command this-command)
13584 org-lowest-priority ; wrap around empty to lowest
13585 ;; default
13586 (if org-priority-start-cycle-with-default
13587 org-default-priority
13588 (1- org-default-priority))))))
13589 ((eq action 'down)
13590 (setq new (if have
13591 (1+ current) ; normal cycling
13592 ;; last priority was empty
13593 (if (eq last-command this-command)
13594 org-highest-priority ; wrap around empty to highest
13595 ;; default
13596 (if org-priority-start-cycle-with-default
13597 org-default-priority
13598 (1+ org-default-priority))))))
13599 (t (user-error "Invalid action")))
13600 (when (or (< (upcase new) org-highest-priority)
13601 (> (upcase new) org-lowest-priority))
13602 (if (and (memq action '(up down))
13603 (not have) (not (eq last-command this-command)))
13604 ;; `new' is from default priority
13605 (error
13606 "The default can not be set, see `org-default-priority' why")
13607 ;; normal cycling: `new' is beyond highest/lowest priority
13608 ;; and is wrapped around to the empty priority
13609 (setq remove t)))
13610 (setq news (format "%c" new))
13611 (if have
13612 (if remove
13613 (replace-match "" t t nil 1)
13614 (replace-match news t t nil 2))
13615 (if remove
13616 (user-error "No priority cookie found in line")
13617 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13618 (if (match-end 2)
13619 (progn
13620 (goto-char (match-end 2))
13621 (insert " [#" news "]"))
13622 (goto-char (match-beginning 3))
13623 (insert "[#" news "] "))))
13624 (org-align-tags))
13625 (if remove
13626 (message "Priority removed")
13627 (message "Priority of current item set to %s" news)))))
13629 (defun org-show-priority ()
13630 "Show the priority of the current item.
13631 This priority is composed of the main priority given with the [#A] cookies,
13632 and by additional input from the age of a schedules or deadline entry."
13633 (interactive)
13634 (let ((pri (if (eq major-mode 'org-agenda-mode)
13635 (org-get-at-bol 'priority)
13636 (save-excursion
13637 (save-match-data
13638 (beginning-of-line)
13639 (and (looking-at org-heading-regexp)
13640 (org-get-priority (match-string 0))))))))
13641 (message "Priority is %d" (if pri pri -1000))))
13643 (defun org-get-priority (s)
13644 "Find priority cookie and return priority."
13645 (save-match-data
13646 (if (functionp org-get-priority-function)
13647 (funcall org-get-priority-function)
13648 (if (not (string-match org-priority-regexp s))
13649 (* 1000 (- org-lowest-priority org-default-priority))
13650 (* 1000 (- org-lowest-priority
13651 (string-to-char (match-string 2 s))))))))
13653 ;;;; Tags
13655 (defvar org-agenda-archives-mode)
13656 (defvar org-map-continue-from nil
13657 "Position from where mapping should continue.
13658 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13660 (defvar org-scanner-tags nil
13661 "The current tag list while the tags scanner is running.")
13663 (defvar org-trust-scanner-tags nil
13664 "Should `org-get-tags' use the tags for the scanner.
13665 This is for internal dynamical scoping only.
13666 When this is non-nil, the function `org-get-tags' will return the value
13667 of `org-scanner-tags' instead of building the list by itself. This
13668 can lead to large speed-ups when the tags scanner is used in a file with
13669 many entries, and when the list of tags is retrieved, for example to
13670 obtain a list of properties. Building the tags list for each entry in such
13671 a file becomes an N^2 operation - but with this variable set, it scales
13672 as N.")
13674 (defvar org--matcher-tags-todo-only nil)
13676 (defun org-scan-tags (action matcher todo-only &optional start-level)
13677 "Scan headline tags with inheritance and produce output ACTION.
13679 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13680 or `agenda' to produce an entry list for an agenda view. It can also be
13681 a Lisp form or a function that should be called at each matched headline, in
13682 this case the return value is a list of all return values from these calls.
13684 MATCHER is a function accepting three arguments, returning
13685 a non-nil value whenever a given set of tags qualifies a headline
13686 for inclusion. See `org-make-tags-matcher' for more information.
13687 As a special case, it can also be set to t (respectively nil) in
13688 order to match all (respectively none) headline.
13690 When TODO-ONLY is non-nil, only lines with a TODO keyword are
13691 included in the output.
13693 START-LEVEL can be a string with asterisks, reducing the scope to
13694 headlines matching this string."
13695 (require 'org-agenda)
13696 (let* ((re (concat "^"
13697 (if start-level
13698 ;; Get the correct level to match
13699 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13700 org-outline-regexp)
13701 " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
13702 " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
13703 (props (list 'face 'default
13704 'done-face 'org-agenda-done
13705 'undone-face 'default
13706 'mouse-face 'highlight
13707 'org-not-done-regexp org-not-done-regexp
13708 'org-todo-regexp org-todo-regexp
13709 'org-complex-heading-regexp org-complex-heading-regexp
13710 'help-echo
13711 (format "mouse-2 or RET jump to Org file %S"
13712 (abbreviate-file-name
13713 (or (buffer-file-name (buffer-base-buffer))
13714 (buffer-name (buffer-base-buffer)))))))
13715 (org-map-continue-from nil)
13716 lspos tags tags-list
13717 (tags-alist (list (cons 0 org-file-tags)))
13718 (llast 0) rtn rtn1 level category i txt
13719 todo marker entry priority
13720 ts-date ts-date-type ts-date-pair)
13721 (unless (or (member action '(agenda sparse-tree)) (functionp action))
13722 (setq action (list 'lambda nil action)))
13723 (save-excursion
13724 (goto-char (point-min))
13725 (when (eq action 'sparse-tree)
13726 (org-overview)
13727 (org-remove-occur-highlights))
13728 (while (let (case-fold-search)
13729 (re-search-forward re nil t))
13730 (setq org-map-continue-from nil)
13731 (catch :skip
13732 ;; Ignore closing parts of inline tasks.
13733 (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
13734 (throw :skip t))
13735 (setq todo (and (match-end 1) (match-string-no-properties 1)))
13736 (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
13737 (goto-char (setq lspos (match-beginning 0)))
13738 (setq level (org-reduced-level (org-outline-level))
13739 category (org-get-category))
13740 (when (eq action 'agenda)
13741 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
13742 ts-date (car ts-date-pair)
13743 ts-date-type (cdr ts-date-pair)))
13744 (setq i llast llast level)
13745 ;; remove tag lists from same and sublevels
13746 (while (>= i level)
13747 (when (setq entry (assoc i tags-alist))
13748 (setq tags-alist (delete entry tags-alist)))
13749 (setq i (1- i)))
13750 ;; add the next tags
13751 (when tags
13752 (setq tags (org-split-string tags ":")
13753 tags-alist
13754 (cons (cons level tags) tags-alist)))
13755 ;; compile tags for current headline
13756 (setq tags-list
13757 (if org-use-tag-inheritance
13758 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13759 tags)
13760 org-scanner-tags tags-list)
13761 (when org-use-tag-inheritance
13762 (setcdr (car tags-alist)
13763 (mapcar (lambda (x)
13764 (setq x (copy-sequence x))
13765 (org-add-prop-inherited x))
13766 (cdar tags-alist))))
13767 (when (and tags org-use-tag-inheritance
13768 (or (not (eq t org-use-tag-inheritance))
13769 org-tags-exclude-from-inheritance))
13770 ;; Selective inheritance, remove uninherited ones.
13771 (setcdr (car tags-alist)
13772 (org-remove-uninherited-tags (cdar tags-alist))))
13773 (when (and
13775 ;; eval matcher only when the todo condition is OK
13776 (and (or (not todo-only) (member todo org-todo-keywords-1))
13777 (if (functionp matcher)
13778 (let ((case-fold-search t) (org-trust-scanner-tags t))
13779 (funcall matcher todo tags-list level))
13780 matcher))
13782 ;; Call the skipper, but return t if it does not
13783 ;; skip, so that the `and' form continues evaluating.
13784 (progn
13785 (unless (eq action 'sparse-tree) (org-agenda-skip))
13788 ;; Check if timestamps are deselecting this entry
13789 (or (not todo-only)
13790 (and (member todo org-todo-keywords-1)
13791 (or (not org-agenda-tags-todo-honor-ignore-options)
13792 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13794 ;; select this headline
13795 (cond
13796 ((eq action 'sparse-tree)
13797 (and org-highlight-sparse-tree-matches
13798 (org-get-heading) (match-end 0)
13799 (org-highlight-new-match
13800 (match-beginning 1) (match-end 1)))
13801 (org-show-context 'tags-tree))
13802 ((eq action 'agenda)
13803 (setq txt (org-agenda-format-item
13805 (concat
13806 (if (eq org-tags-match-list-sublevels 'indented)
13807 (make-string (1- level) ?.) "")
13808 (org-get-heading))
13809 (make-string level ?\s)
13810 category
13811 tags-list)
13812 priority (org-get-priority txt))
13813 (goto-char lspos)
13814 (setq marker (org-agenda-new-marker))
13815 (org-add-props txt props
13816 'org-marker marker 'org-hd-marker marker 'org-category category
13817 'todo-state todo
13818 'ts-date ts-date
13819 'priority priority
13820 'type (concat "tagsmatch" ts-date-type))
13821 (push txt rtn))
13822 ((functionp action)
13823 (setq org-map-continue-from nil)
13824 (save-excursion
13825 (setq rtn1 (funcall action))
13826 (push rtn1 rtn)))
13827 (t (user-error "Invalid action")))
13829 ;; if we are to skip sublevels, jump to end of subtree
13830 (unless org-tags-match-list-sublevels
13831 (org-end-of-subtree t)
13832 (backward-char 1))))
13833 ;; Get the correct position from where to continue
13834 (if org-map-continue-from
13835 (goto-char org-map-continue-from)
13836 (and (= (point) lspos) (end-of-line 1)))))
13837 (when (and (eq action 'sparse-tree)
13838 (not org-sparse-tree-open-archived-trees))
13839 (org-hide-archived-subtrees (point-min) (point-max)))
13840 (nreverse rtn)))
13842 (defun org-remove-uninherited-tags (tags)
13843 "Remove all tags that are not inherited from the list TAGS."
13844 (cond
13845 ((eq org-use-tag-inheritance t)
13846 (if org-tags-exclude-from-inheritance
13847 (org-delete-all org-tags-exclude-from-inheritance tags)
13848 tags))
13849 ((not org-use-tag-inheritance) nil)
13850 ((stringp org-use-tag-inheritance)
13851 (delq nil (mapcar
13852 (lambda (x)
13853 (if (and (string-match org-use-tag-inheritance x)
13854 (not (member x org-tags-exclude-from-inheritance)))
13855 x nil))
13856 tags)))
13857 ((listp org-use-tag-inheritance)
13858 (delq nil (mapcar
13859 (lambda (x)
13860 (if (member x org-use-tag-inheritance) x nil))
13861 tags)))))
13863 (defun org-match-sparse-tree (&optional todo-only match)
13864 "Create a sparse tree according to tags string MATCH.
13866 MATCH is a string with match syntax. It can contain a selection
13867 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
13868 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
13869 those. See the manual for details.
13871 If optional argument TODO-ONLY is non-nil, only select lines that
13872 are also TODO tasks."
13873 (interactive "P")
13874 (org-agenda-prepare-buffers (list (current-buffer)))
13875 (let ((org--matcher-tags-todo-only todo-only))
13876 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
13877 org--matcher-tags-todo-only)))
13879 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13881 (defvar org-cached-props nil)
13882 (defun org-cached-entry-get (pom property)
13883 (if (or (eq t org-use-property-inheritance)
13884 (and (stringp org-use-property-inheritance)
13885 (let ((case-fold-search t))
13886 (string-match-p org-use-property-inheritance property)))
13887 (and (listp org-use-property-inheritance)
13888 (member-ignore-case property org-use-property-inheritance)))
13889 ;; Caching is not possible, check it directly.
13890 (org-entry-get pom property 'inherit)
13891 ;; Get all properties, so we can do complicated checks easily.
13892 (cdr (assoc-string property
13893 (or org-cached-props
13894 (setq org-cached-props (org-entry-properties pom)))
13895 t))))
13897 (defun org-global-tags-completion-table (&optional files)
13898 "Return the list of all tags in all agenda buffer/files.
13899 Optional FILES argument is a list of files which can be used
13900 instead of the agenda files."
13901 (save-excursion
13902 (org-uniquify
13903 (delq nil
13904 (apply #'append
13905 (mapcar
13906 (lambda (file)
13907 (set-buffer (find-file-noselect file))
13908 (org--tag-add-to-alist
13909 (org-get-buffer-tags)
13910 (mapcar (lambda (x)
13911 (and (stringp (car-safe x))
13912 (list (car-safe x))))
13913 org-current-tag-alist)))
13914 (if (car-safe files) files
13915 (org-agenda-files))))))))
13917 (defun org-make-tags-matcher (match)
13918 "Create the TAGS/TODO matcher form for the selection string MATCH.
13920 Returns a cons of the selection string MATCH and a function
13921 implementing the matcher.
13923 The matcher is to be called at an Org entry, with point on the
13924 headline, and returns non-nil if the entry matches the selection
13925 string MATCH. It must be called with three arguments: the TODO
13926 keyword at the entry (or nil if none), the list of all tags at
13927 the entry including inherited ones and the reduced level of the
13928 headline. Additionally, the category of the entry, if any, must
13929 be specified as the text property `org-category' on the headline.
13931 This function sets the variable `org--matcher-tags-todo-only' to
13932 a non-nil value if the matcher restricts matching to TODO
13933 entries, otherwise it is not touched.
13935 See also `org-scan-tags'."
13936 (unless match
13937 ;; Get a new match request, with completion against the global
13938 ;; tags table and the local tags in current buffer.
13939 (let ((org-last-tags-completion-table
13940 (org--tag-add-to-alist
13941 (org-get-buffer-tags)
13942 (org-global-tags-completion-table))))
13943 (setq match
13944 (completing-read
13945 "Match: "
13946 'org-tags-completion-function nil nil nil 'org-tags-history))))
13948 (let ((match0 match)
13949 (re (concat
13950 "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
13951 "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
13952 "\\([<>=]\\{1,2\\}\\)"
13953 "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
13954 "\\|" org-tag-re "\\)"))
13955 (start 0)
13956 tagsmatch todomatch tagsmatcher todomatcher)
13958 ;; Expand group tags.
13959 (setq match (org-tags-expand match))
13961 ;; Check if there is a TODO part of this match, which would be the
13962 ;; part after a "/". To make sure that this slash is not part of
13963 ;; a property value to be matched against, we also check that
13964 ;; there is no / after that slash. First, find the last slash.
13965 (let ((s 0))
13966 (while (string-match "/+" match s)
13967 (setq start (match-beginning 0))
13968 (setq s (match-end 0))))
13969 (if (and (string-match "/+" match start)
13970 (not (string-match-p "\"" match start)))
13971 ;; Match contains also a TODO-matching request.
13972 (progn
13973 (setq tagsmatch (substring match 0 (match-beginning 0)))
13974 (setq todomatch (substring match (match-end 0)))
13975 (when (string-prefix-p "!" todomatch)
13976 (setq org--matcher-tags-todo-only t)
13977 (setq todomatch (substring todomatch 1)))
13978 (when (string-match "\\`\\s-*\\'" todomatch)
13979 (setq todomatch nil)))
13980 ;; Only matching tags.
13981 (setq tagsmatch match)
13982 (setq todomatch nil))
13984 ;; Make the tags matcher.
13985 (when (org-string-nw-p tagsmatch)
13986 (let ((orlist nil)
13987 (orterms (org-split-string tagsmatch "|"))
13988 term)
13989 (while (setq term (pop orterms))
13990 (while (and (equal (substring term -1) "\\") orterms)
13991 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
13992 (while (string-match re term)
13993 (let* ((rest (substring term (match-end 0)))
13994 (minus (and (match-end 1)
13995 (equal (match-string 1 term) "-")))
13996 (tag (save-match-data
13997 (replace-regexp-in-string
13998 "\\\\-" "-" (match-string 2 term))))
13999 (regexp (eq (string-to-char tag) ?{))
14000 (levelp (match-end 4))
14001 (propp (match-end 5))
14003 (cond
14004 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14005 (levelp
14006 `(,(org-op-to-function (match-string 3 term))
14007 level
14008 ,(string-to-number (match-string 4 term))))
14009 (propp
14010 (let* ((gv (pcase (upcase (match-string 5 term))
14011 ("CATEGORY"
14012 '(get-text-property (point) 'org-category))
14013 ("TODO" 'todo)
14014 (p `(org-cached-entry-get nil ,p))))
14015 (pv (match-string 7 term))
14016 (regexp (eq (string-to-char pv) ?{))
14017 (strp (eq (string-to-char pv) ?\"))
14018 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14019 (po (org-op-to-function (match-string 6 term)
14020 (if timep 'time strp))))
14021 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14022 (when timep (setq pv (org-matcher-time pv)))
14023 (cond ((and regexp (eq po '/=))
14024 `(not (string-match ,pv (or ,gv ""))))
14025 (regexp `(string-match ,pv (or ,gv "")))
14026 (strp `(,po (or ,gv "") ,pv))
14028 `(,po
14029 (string-to-number (or ,gv ""))
14030 ,(string-to-number pv))))))
14031 (t `(member ,tag tags-list)))))
14032 (push (if minus `(not ,mm) mm) tagsmatcher)
14033 (setq term rest)))
14034 (push `(and ,@tagsmatcher) orlist)
14035 (setq tagsmatcher nil))
14036 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14038 ;; Make the TODO matcher.
14039 (when (org-string-nw-p todomatch)
14040 (let ((orlist nil))
14041 (dolist (term (org-split-string todomatch "|"))
14042 (while (string-match re term)
14043 (let* ((minus (and (match-end 1)
14044 (equal (match-string 1 term) "-")))
14045 (kwd (match-string 2 term))
14046 (regexp (eq (string-to-char kwd) ?{))
14047 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14048 `(equal todo ,kwd))))
14049 (push (if minus `(not ,mm) mm) todomatcher))
14050 (setq term (substring term (match-end 0))))
14051 (push (if (> (length todomatcher) 1)
14052 (cons 'and todomatcher)
14053 (car todomatcher))
14054 orlist)
14055 (setq todomatcher nil))
14056 (setq todomatcher (cons 'or orlist))))
14058 ;; Return the string and function of the matcher. If no
14059 ;; tags-specific or todo-specific matcher exists, match
14060 ;; everything.
14061 (let ((matcher (if (and tagsmatcher todomatcher)
14062 `(and ,tagsmatcher ,todomatcher)
14063 (or tagsmatcher todomatcher t))))
14064 (when org--matcher-tags-todo-only
14065 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14066 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14068 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14069 "Expand group tags in MATCH.
14071 This replaces every group tag in MATCH with a regexp tag search.
14072 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14073 will be replaced like this:
14075 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14076 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14077 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14079 Replacing by a regexp preserves the structure of the match.
14080 E.g., this expansion
14082 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14084 will match anything tagged with \"Lab\" and \"Home\", or tagged
14085 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14087 A group tag in MATCH can contain regular expressions of its own.
14088 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14089 will be replaced like this:
14091 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14093 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14094 assumed to be a single group tag, and the function will return
14095 the list of tags in this group.
14097 When DOWNCASE is non-nil, expand downcased TAGS."
14098 (if org-group-tags
14099 (let* ((case-fold-search t)
14100 (stable org-mode-syntax-table)
14101 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14102 (taggroups (if downcased
14103 (mapcar (lambda (tg) (mapcar #'downcase tg))
14104 taggroups)
14105 taggroups))
14106 (taggroups-keys (mapcar #'car taggroups))
14107 (return-match (if downcased (downcase match) match))
14108 (count 0)
14109 (work-already-expanded tags-already-expanded)
14110 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14111 ;; @ and _ are allowed as word-components in tags.
14112 (modify-syntax-entry ?@ "w" stable)
14113 (modify-syntax-entry ?_ "w" stable)
14114 ;; Temporarily replace regexp-expressions in the match-expression.
14115 (while (string-match "{.+?}" return-match)
14116 (cl-incf count)
14117 (push (match-string 0 return-match) regexps-in-match)
14118 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14119 (while (and taggroups-keys
14120 (with-syntax-table stable
14121 (string-match
14122 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14123 (regexp-opt taggroups-keys) "\\>\\)")
14124 return-match)))
14125 (let* ((dir (match-string 1 return-match))
14126 (tag (match-string 2 return-match))
14127 (tag (if downcased (downcase tag) tag)))
14128 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14129 (member tag tags-already-expanded))
14130 (setq tags-in-group (assoc tag taggroups))
14131 (push tag work-already-expanded)
14132 ;; Recursively expand each tag in the group, if the tag hasn't
14133 ;; already been expanded. Restore the match-data after all recursive calls.
14134 (save-match-data
14135 (let (tags-expanded)
14136 (dolist (x (cdr tags-in-group))
14137 (if (and (member x taggroups-keys)
14138 (not (member x work-already-expanded)))
14139 (setq tags-expanded
14140 (delete-dups
14141 (append
14142 (org-tags-expand x t downcased
14143 work-already-expanded)
14144 tags-expanded)))
14145 (setq tags-expanded
14146 (append (list x) tags-expanded)))
14147 (setq work-already-expanded
14148 (delete-dups
14149 (append tags-expanded
14150 work-already-expanded))))
14151 (setq tags-in-group
14152 (delete-dups (cons (car tags-in-group)
14153 tags-expanded)))))
14154 ;; Filter tag-regexps from tags.
14155 (setq regexp-in-group-escaped
14156 (delq nil (mapcar (lambda (x)
14157 (if (stringp x)
14158 (and (equal "{" (substring x 0 1))
14159 (equal "}" (substring x -1))
14162 tags-in-group))
14163 regexp-in-group
14164 (mapcar (lambda (x)
14165 (substring x 1 -1))
14166 regexp-in-group-escaped)
14167 tags-in-group
14168 (delq nil (mapcar (lambda (x)
14169 (if (stringp x)
14170 (and (not (equal "{" (substring x 0 1)))
14171 (not (equal "}" (substring x -1)))
14174 tags-in-group)))
14175 ;; If single-as-list, do no more in the while-loop.
14176 (if (not single-as-list)
14177 (progn
14178 (when regexp-in-group
14179 (setq regexp-in-group
14180 (concat "\\|"
14181 (mapconcat 'identity regexp-in-group
14182 "\\|"))))
14183 (setq tags-in-group
14184 (concat dir
14185 "{\\<"
14186 (regexp-opt tags-in-group)
14187 "\\>"
14188 regexp-in-group
14189 "}"))
14190 (when (stringp tags-in-group)
14191 (org-add-props tags-in-group '(grouptag t)))
14192 (setq return-match
14193 (replace-match tags-in-group t t return-match)))
14194 (setq tags-in-group
14195 (append regexp-in-group-escaped tags-in-group))))
14196 (setq taggroups-keys (delete tag taggroups-keys))))
14197 ;; Add the regular expressions back into the match-expression again.
14198 (while regexps-in-match
14199 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14200 (pop regexps-in-match)
14201 return-match t t))
14202 (cl-decf count))
14203 (if single-as-list
14204 (if tags-in-group tags-in-group (list return-match))
14205 return-match))
14206 (if single-as-list
14207 (list (if downcased (downcase match) match))
14208 match)))
14210 (defun org-op-to-function (op &optional stringp)
14211 "Turn an operator into the appropriate function."
14212 (setq op
14213 (cond
14214 ((equal op "<" ) '(< org-string< org-time<))
14215 ((equal op ">" ) '(> org-string> org-time>))
14216 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14217 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14218 ((member op '("=" "==")) '(= string= org-time=))
14219 ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
14220 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14222 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14223 (defvar org-tags-overlay (make-overlay 1 1))
14224 (delete-overlay org-tags-overlay)
14226 (defun org-add-prop-inherited (s)
14227 (add-text-properties 0 (length s) '(inherited t) s)
14230 (defun org-toggle-tag (tag &optional onoff)
14231 "Toggle the tag TAG for the current line.
14232 If ONOFF is `on' or `off', don't toggle but set to this state."
14233 (save-excursion
14234 (org-back-to-heading t)
14235 (let ((current
14236 ;; Reverse the tags list so any new tag is appended to the
14237 ;; current list of tags.
14238 (nreverse (org-get-tags nil t)))
14239 res)
14240 (pcase onoff
14241 (`off (setq current (delete tag current)))
14242 ((or `on (guard (not (member tag current))))
14243 (setq res t)
14244 (cl-pushnew tag current :test #'equal))
14245 (_ (setq current (delete tag current))))
14246 (org-set-tags (nreverse current))
14247 res)))
14249 (defun org--align-tags-here (to-col)
14250 "Align tags on the current headline to TO-COL.
14251 Assume point is on a headline. Preserve point when aligning
14252 tags."
14253 (when (org-match-line org-tag-line-re)
14254 (let* ((tags-start (match-beginning 1))
14255 (blank-start (save-excursion
14256 (goto-char tags-start)
14257 (skip-chars-backward " \t")
14258 (point)))
14259 (new (max (if (>= to-col 0) to-col
14260 (- (abs to-col) (string-width (match-string 1))))
14261 ;; Introduce at least one space after the heading
14262 ;; or the stars.
14263 (save-excursion
14264 (goto-char blank-start)
14265 (1+ (current-column)))))
14266 (current
14267 (save-excursion (goto-char tags-start) (current-column)))
14268 (origin (point-marker))
14269 (column (current-column))
14270 (in-blank? (and (> origin blank-start) (<= origin tags-start))))
14271 (when (/= new current)
14272 (delete-region blank-start tags-start)
14273 (goto-char blank-start)
14274 (let ((indent-tabs-mode nil)) (indent-to new))
14275 ;; Try to move back to original position. If point was in the
14276 ;; blanks before the tags, ORIGIN marker is of no use because
14277 ;; it now points to BLANK-START. Use COLUMN instead.
14278 (if in-blank? (org-move-to-column column) (goto-char origin))))))
14280 (defun org-set-tags-command (&optional arg)
14281 "Set the tags for the current visible entry.
14283 When called with `\\[universal-argument]' prefix argument ARG, \
14284 realign all tags
14285 in the current buffer. If a region is active, set tags for
14286 all headlines in the region.
14288 This function is for interactive use only;
14289 in Lisp code use `org-set-tags' instead."
14290 (interactive "P")
14291 (cond
14292 (arg (org-align-tags t))
14293 ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
14294 ;; Disable `org-loop-over-headlines-in-active-region' for
14295 ;; successive calls.
14296 (let (org-loop-over-headlines-in-active-region)
14297 (org-map-entries
14298 #'org-set-tags-command
14300 (if (eq org-loop-over-headlines-in-active-region 'start-level)
14301 'region-start-level
14302 'region)
14303 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
14305 (save-excursion
14306 (org-back-to-heading)
14307 (let* ((all-tags (org-get-tags))
14308 (table (setq org-last-tags-completion-table
14309 (org--tag-add-to-alist
14310 (and org-complete-tags-always-offer-all-agenda-tags
14311 (org-global-tags-completion-table
14312 (org-agenda-files)))
14313 (or org-current-tag-alist (org-get-buffer-tags)))))
14314 (current-tags
14315 (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
14316 all-tags))
14317 (inherited-tags
14318 (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
14319 all-tags))
14320 (tags
14321 (replace-regexp-in-string
14322 ;; Ignore all forbidden characters in tags.
14323 "[^[:alnum:]_@#%]+" ":"
14324 (if (or (eq t org-use-fast-tag-selection)
14325 (and org-use-fast-tag-selection
14326 (delq nil (mapcar #'cdr table))))
14327 (org-fast-tag-selection
14328 current-tags
14329 inherited-tags
14330 table
14331 (and org-fast-tag-selection-include-todo org-todo-key-alist))
14332 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14333 (org-trim (completing-read
14334 "Tags: "
14335 #'org-tags-completion-function
14336 nil nil (org-make-tag-string current-tags)
14337 'org-tags-history)))))))
14338 (org-set-tags tags))))))
14340 (defun org-align-tags (&optional all)
14341 "Align tags in current entry.
14342 When optional argument ALL is non-nil, align all tags in the
14343 visible part of the buffer."
14344 (let ((get-indent-column
14345 (lambda ()
14346 (let ((offset (if (bound-and-true-p org-indent-mode)
14347 (* (1- org-indent-indentation-per-level)
14348 (1- (org-current-level)))
14349 0)))
14350 (+ org-tags-column
14351 (if (> org-tags-column 0) (- offset) offset))))))
14352 (if (and (not all) (org-at-heading-p))
14353 (org--align-tags-here (funcall get-indent-column))
14354 (save-excursion
14355 (if all
14356 (while (re-search-forward org-tag-line-re nil t)
14357 (org--align-tags-here (funcall get-indent-column)))
14358 (org-back-to-heading t)
14359 (org--align-tags-here (funcall get-indent-column)))))))
14361 (defun org-set-tags (tags)
14362 "Set the tags of the current entry to TAGS, replacing current tags.
14364 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
14365 If TAGS is nil or the empty string, all tags are removed.
14367 This function assumes point is on a headline."
14368 (org-with-wide-buffer
14369 (let ((tags (pcase tags
14370 ((pred listp) tags)
14371 ((pred stringp) (split-string (org-trim tags) ":" t))
14372 (_ (error "Invalid tag specification: %S" tags))))
14373 (old-tags (org-get-tags nil t))
14374 (tags-change? nil))
14375 (when (functionp org-tags-sort-function)
14376 (setq tags (sort tags org-tags-sort-function)))
14377 (setq tags-change? (not (equal tags old-tags)))
14378 (when tags-change?
14379 ;; Delete previous tags and any trailing white space.
14380 (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
14381 (line-end-position)))
14382 (skip-chars-backward " \t")
14383 (delete-region (point) (line-end-position))
14384 ;; Deleting white spaces may break an otherwise empty headline.
14385 ;; Re-introduce one space in this case.
14386 (unless (org-at-heading-p) (insert " "))
14387 (when tags
14388 (save-excursion (insert " " (org-make-tag-string tags)))
14389 ;; When text is being inserted on an invisible region
14390 ;; boundary, it can be inadvertently sucked into
14391 ;; invisibility.
14392 (unless (org-invisible-p (line-beginning-position))
14393 (org-flag-region (point) (line-end-position) nil 'outline))))
14394 ;; Align tags, if any.
14395 (when tags (org-align-tags))
14396 (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
14398 (defun org-change-tag-in-region (beg end tag off)
14399 "Add or remove TAG for each entry in the region.
14400 This works in the agenda, and also in an Org buffer."
14401 (interactive
14402 (list (region-beginning) (region-end)
14403 (let ((org-last-tags-completion-table
14404 (if (derived-mode-p 'org-mode)
14405 (org--tag-add-to-alist
14406 (org-get-buffer-tags)
14407 (org-global-tags-completion-table))
14408 (org-global-tags-completion-table))))
14409 (completing-read
14410 "Tag: " 'org-tags-completion-function nil nil nil
14411 'org-tags-history))
14412 (progn
14413 (message "[s]et or [r]emove? ")
14414 (equal (read-char-exclusive) ?r))))
14415 (when (fboundp 'deactivate-mark) (deactivate-mark))
14416 (let ((agendap (equal major-mode 'org-agenda-mode))
14417 l1 l2 m buf pos newhead (cnt 0))
14418 (goto-char end)
14419 (setq l2 (1- (org-current-line)))
14420 (goto-char beg)
14421 (setq l1 (org-current-line))
14422 (cl-loop for l from l1 to l2 do
14423 (org-goto-line l)
14424 (setq m (get-text-property (point) 'org-hd-marker))
14425 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14426 (and agendap m))
14427 (setq buf (if agendap (marker-buffer m) (current-buffer))
14428 pos (if agendap m (point)))
14429 (with-current-buffer buf
14430 (save-excursion
14431 (save-restriction
14432 (goto-char pos)
14433 (setq cnt (1+ cnt))
14434 (org-toggle-tag tag (if off 'off 'on))
14435 (setq newhead (org-get-heading)))))
14436 (and agendap (org-agenda-change-all-lines newhead m))))
14437 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14439 (defun org-tags-completion-function (string _predicate &optional flag)
14440 "Complete tag STRING.
14441 FLAG specifies the type of completion operation to perform. This
14442 function is passed as a collection function to `completing-read',
14443 which see."
14444 (let ((completion-ignore-case nil) ;tags are case-sensitive
14445 (confirm (lambda (x) (stringp (car x))))
14446 (prefix ""))
14447 (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14448 (setq prefix (match-string 1 string))
14449 (setq string (match-string 2 string)))
14450 (pcase flag
14451 (`t (all-completions string org-last-tags-completion-table confirm))
14452 (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
14453 (`nil
14454 (pcase (try-completion string org-last-tags-completion-table confirm)
14455 ((and completion (pred stringp))
14456 (concat prefix
14457 completion
14458 (if (and org-add-colon-after-tag-completion
14459 (assoc completion org-last-tags-completion-table))
14461 "")))
14462 (completion completion)))
14463 (_ nil))))
14465 (defun org-fast-tag-insert (kwd tags face &optional end)
14466 "Insert KWD, and the TAGS, the latter with face FACE.
14467 Also insert END."
14468 (insert (format "%-12s" (concat kwd ":"))
14469 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14470 (or end "")))
14472 (defun org-fast-tag-show-exit (flag)
14473 (save-excursion
14474 (org-goto-line 3)
14475 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14476 (replace-match ""))
14477 (when flag
14478 (end-of-line 1)
14479 (org-move-to-column (- (window-width) 19) t)
14480 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14482 (defun org-set-current-tags-overlay (current prefix)
14483 "Add an overlay to CURRENT tag with PREFIX."
14484 (let ((s (org-make-tag-string current)))
14485 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14486 (org-overlay-display org-tags-overlay (concat prefix s))))
14488 (defvar org-last-tag-selection-key nil)
14489 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14490 "Fast tag selection with single keys.
14491 CURRENT is the current list of tags in the headline, INHERITED is the
14492 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14493 possibly with grouping information. TODO-TABLE is a similar table with
14494 TODO keywords, should these have keys assigned to them.
14495 If the keys are nil, a-z are automatically assigned.
14496 Returns the new tags string, or nil to not change the current settings."
14497 (let* ((fulltable (append table todo-table))
14498 (maxlen (if (null fulltable) 0
14499 (apply #'max
14500 (mapcar (lambda (x)
14501 (if (stringp (car x)) (string-width (car x))
14503 fulltable))))
14504 (buf (current-buffer))
14505 (expert (eq org-fast-tag-selection-single-key 'expert))
14506 (buffer-tags nil)
14507 (fwidth (+ maxlen 3 1 3))
14508 (ncol (/ (- (window-width) 4) fwidth))
14509 (i-face 'org-done)
14510 (c-face 'org-todo)
14511 tg cnt e c char c1 c2 ntable tbl rtn
14512 ov-start ov-end ov-prefix
14513 (exit-after-next org-fast-tag-selection-single-key)
14514 (done-keywords org-done-keywords)
14515 groups ingroup intaggroup)
14516 (save-excursion
14517 (beginning-of-line)
14518 (if (looking-at org-tag-line-re)
14519 (setq ov-start (match-beginning 1)
14520 ov-end (match-end 1)
14521 ov-prefix "")
14522 (setq ov-start (1- (point-at-eol))
14523 ov-end (1+ ov-start))
14524 (skip-chars-forward "^\n\r")
14525 (setq ov-prefix
14526 (concat
14527 (buffer-substring (1- (point)) (point))
14528 (if (> (current-column) org-tags-column)
14530 (make-string (- org-tags-column (current-column)) ?\ ))))))
14531 (move-overlay org-tags-overlay ov-start ov-end)
14532 (save-window-excursion
14533 (if expert
14534 (set-buffer (get-buffer-create " *Org tags*"))
14535 (delete-other-windows)
14536 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
14537 (org-switch-to-buffer-other-window " *Org tags*"))
14538 (erase-buffer)
14539 (setq-local org-done-keywords done-keywords)
14540 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14541 (org-fast-tag-insert "Current" current c-face "\n\n")
14542 (org-fast-tag-show-exit exit-after-next)
14543 (org-set-current-tags-overlay current ov-prefix)
14544 (setq tbl fulltable char ?a cnt 0)
14545 (while (setq e (pop tbl))
14546 (cond
14547 ((eq (car e) :startgroup)
14548 (push '() groups) (setq ingroup t)
14549 (unless (zerop cnt)
14550 (setq cnt 0)
14551 (insert "\n"))
14552 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14553 ((eq (car e) :endgroup)
14554 (setq ingroup nil cnt 0)
14555 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14556 ((eq (car e) :startgrouptag)
14557 (setq intaggroup t)
14558 (unless (zerop cnt)
14559 (setq cnt 0)
14560 (insert "\n"))
14561 (insert "[ "))
14562 ((eq (car e) :endgrouptag)
14563 (setq intaggroup nil cnt 0)
14564 (insert "]\n"))
14565 ((equal e '(:newline))
14566 (unless (zerop cnt)
14567 (setq cnt 0)
14568 (insert "\n")
14569 (setq e (car tbl))
14570 (while (equal (car tbl) '(:newline))
14571 (insert "\n")
14572 (setq tbl (cdr tbl)))))
14573 ((equal e '(:grouptags)) (insert " : "))
14575 (setq tg (copy-sequence (car e)) c2 nil)
14576 (if (cdr e)
14577 (setq c (cdr e))
14578 ;; automatically assign a character.
14579 (setq c1 (string-to-char
14580 (downcase (substring
14581 tg (if (= (string-to-char tg) ?@) 1 0)))))
14582 (if (or (rassoc c1 ntable) (rassoc c1 table))
14583 (while (or (rassoc char ntable) (rassoc char table))
14584 (setq char (1+ char)))
14585 (setq c2 c1))
14586 (setq c (or c2 char)))
14587 (when ingroup (push tg (car groups)))
14588 (setq tg (org-add-props tg nil 'face
14589 (cond
14590 ((not (assoc tg table))
14591 (org-get-todo-face tg))
14592 ((member tg current) c-face)
14593 ((member tg inherited) i-face))))
14594 (when (equal (caar tbl) :grouptags)
14595 (org-add-props tg nil 'face 'org-tag-group))
14596 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
14597 (insert "[" c "] " tg (make-string
14598 (- fwidth 4 (length tg)) ?\ ))
14599 (push (cons tg c) ntable)
14600 (when (= (cl-incf cnt) ncol)
14601 (insert "\n")
14602 (when (or ingroup intaggroup) (insert " "))
14603 (setq cnt 0)))))
14604 (setq ntable (nreverse ntable))
14605 (insert "\n")
14606 (goto-char (point-min))
14607 (unless expert (org-fit-window-to-buffer))
14608 (setq rtn
14609 (catch 'exit
14610 (while t
14611 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
14612 (if (not groups) "no " "")
14613 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14614 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14615 (setq org-last-tag-selection-key c)
14616 (cond
14617 ((= c ?\r) (throw 'exit t))
14618 ((= c ?!)
14619 (setq groups (not groups))
14620 (goto-char (point-min))
14621 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14622 ((= c ?\C-c)
14623 (if (not expert)
14624 (org-fast-tag-show-exit
14625 (setq exit-after-next (not exit-after-next)))
14626 (setq expert nil)
14627 (delete-other-windows)
14628 (set-window-buffer (split-window-vertically) " *Org tags*")
14629 (org-switch-to-buffer-other-window " *Org tags*")
14630 (org-fit-window-to-buffer)))
14631 ((or (= c ?\C-g)
14632 (and (= c ?q) (not (rassoc c ntable))))
14633 (delete-overlay org-tags-overlay)
14634 (setq quit-flag t))
14635 ((= c ?\ )
14636 (setq current nil)
14637 (when exit-after-next (setq exit-after-next 'now)))
14638 ((= c ?\t)
14639 (condition-case nil
14640 (setq tg (completing-read
14641 "Tag: "
14642 (or buffer-tags
14643 (with-current-buffer buf
14644 (setq buffer-tags
14645 (org-get-buffer-tags))))))
14646 (quit (setq tg "")))
14647 (when (string-match "\\S-" tg)
14648 (cl-pushnew (list tg) buffer-tags :test #'equal)
14649 (if (member tg current)
14650 (setq current (delete tg current))
14651 (push tg current)))
14652 (when exit-after-next (setq exit-after-next 'now)))
14653 ((setq e (rassoc c todo-table) tg (car e))
14654 (with-current-buffer buf
14655 (save-excursion (org-todo tg)))
14656 (when exit-after-next (setq exit-after-next 'now)))
14657 ((setq e (rassoc c ntable) tg (car e))
14658 (if (member tg current)
14659 (setq current (delete tg current))
14660 (cl-loop for g in groups do
14661 (when (member tg g)
14662 (dolist (x g) (setq current (delete x current)))))
14663 (push tg current))
14664 (when exit-after-next (setq exit-after-next 'now))))
14666 ;; Create a sorted list
14667 (setq current
14668 (sort current
14669 (lambda (a b)
14670 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14671 (when (eq exit-after-next 'now) (throw 'exit t))
14672 (goto-char (point-min))
14673 (beginning-of-line 2)
14674 (delete-region (point) (point-at-eol))
14675 (org-fast-tag-insert "Current" current c-face)
14676 (org-set-current-tags-overlay current ov-prefix)
14677 (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
14678 (while (re-search-forward tag-re nil t)
14679 (let ((tag (match-string 1)))
14680 (add-text-properties
14681 (match-beginning 1) (match-end 1)
14682 (list 'face
14683 (cond
14684 ((member tag current) c-face)
14685 ((member tag inherited) i-face)
14686 (t (get-text-property (match-beginning 1) '
14687 face))))))))
14688 (goto-char (point-min)))))
14689 (delete-overlay org-tags-overlay)
14690 (if rtn
14691 (mapconcat 'identity current ":")
14692 nil))))
14694 (defun org-make-tag-string (tags)
14695 "Return string associated to TAGS.
14696 TAGS is a list of strings."
14697 (if (null tags) ""
14698 (format ":%s:" (mapconcat #'identity tags ":"))))
14700 (defun org--get-local-tags ()
14701 "Return list of tags for the current headline.
14702 Assume point is at the beginning of the headline."
14703 (and (looking-at org-tag-line-re)
14704 (split-string (match-string-no-properties 2) ":" t)))
14706 (defun org-get-tags (&optional pos local)
14707 "Get the list of tags specified in the current headline.
14709 When argument POS is non-nil, retrieve tags for headline at POS.
14711 Accoring to `org-use-tags-inheritance', tags may be inherited
14712 from parent headlines, and from the whole document, through
14713 `org-file-tags'. However, when optional argument LOCAL is
14714 non-nil, only return tags really specified in the considered
14715 headline.
14717 Inherited tags have the `inherited' text property."
14718 (if (and org-trust-scanner-tags
14719 (or (not pos) (eq pos (point)))
14720 (not local))
14721 org-scanner-tags
14722 (org-with-point-at (or pos (point))
14723 (unless (org-before-first-heading-p)
14724 (org-back-to-heading t)
14725 (let ((ltags (org--get-local-tags)) itags)
14726 (if (or local (not org-use-tag-inheritance)) ltags
14727 (setq itags org-file-tags)
14728 (while (org-up-heading-safe)
14729 (setq itags (append (mapcar #'org-add-prop-inherited
14730 (org--get-local-tags))
14731 itags)))
14732 (delete-dups
14733 (append (org-remove-uninherited-tags itags) ltags))))))))
14735 (defun org-get-buffer-tags ()
14736 "Get a table of all tags used in the buffer, for completion."
14737 (org-with-point-at 1
14738 (let (tags)
14739 (while (re-search-forward org-tag-line-re nil t)
14740 (setq tags (nconc (split-string (match-string-no-properties 2) ":")
14741 tags)))
14742 (mapcar #'list (delete-dups (append org-file-tags tags))))))
14744 ;;;; The mapping API
14746 (defvar org-agenda-skip-comment-trees)
14747 (defvar org-agenda-skip-function)
14748 (defun org-map-entries (func &optional match scope &rest skip)
14749 "Call FUNC at each headline selected by MATCH in SCOPE.
14751 FUNC is a function or a lisp form. The function will be called without
14752 arguments, with the cursor positioned at the beginning of the headline.
14753 The return values of all calls to the function will be collected and
14754 returned as a list.
14756 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14757 does not need to preserve point. After evaluation, the cursor will be
14758 moved to the end of the line (presumably of the headline of the
14759 processed entry) and search continues from there. Under some
14760 circumstances, this may not produce the wanted results. For example,
14761 if you have removed (e.g. archived) the current (sub)tree it could
14762 mean that the next entry will be skipped entirely. In such cases, you
14763 can specify the position from where search should continue by making
14764 FUNC set the variable `org-map-continue-from' to the desired buffer
14765 position.
14767 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14768 Only headlines that are matched by this query will be considered during
14769 the iteration. When MATCH is nil or t, all headlines will be
14770 visited by the iteration.
14772 SCOPE determines the scope of this command. It can be any of:
14774 nil The current buffer, respecting the restriction if any
14775 tree The subtree started with the entry at point
14776 region The entries within the active region, if any
14777 region-start-level
14778 The entries within the active region, but only those at
14779 the same level than the first one.
14780 file The current buffer, without restriction
14781 file-with-archives
14782 The current buffer, and any archives associated with it
14783 agenda All agenda files
14784 agenda-with-archives
14785 All agenda files with any archive files associated with them
14786 \(file1 file2 ...)
14787 If this is a list, all files in the list will be scanned
14789 The remaining args are treated as settings for the skipping facilities of
14790 the scanner. The following items can be given here:
14792 archive skip trees with the archive tag
14793 comment skip trees with the COMMENT keyword
14794 function or Emacs Lisp form:
14795 will be used as value for `org-agenda-skip-function', so
14796 whenever the function returns a position, FUNC will not be
14797 called for that entry and search will continue from the
14798 position returned
14800 If your function needs to retrieve the tags including inherited tags
14801 at the *current* entry, you can use the value of the variable
14802 `org-scanner-tags' which will be much faster than getting the value
14803 with `org-get-tags'. If your function gets properties with
14804 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14805 to t around the call to `org-entry-properties' to get the same speedup.
14806 Note that if your function moves around to retrieve tags and properties at
14807 a *different* entry, you cannot use these techniques."
14808 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14809 (not (org-region-active-p)))
14810 (let* ((org-agenda-archives-mode nil) ; just to make sure
14811 (org-agenda-skip-archived-trees (memq 'archive skip))
14812 (org-agenda-skip-comment-trees (memq 'comment skip))
14813 (org-agenda-skip-function
14814 (car (org-delete-all '(comment archive) skip)))
14815 (org-tags-match-list-sublevels t)
14816 (start-level (eq scope 'region-start-level))
14817 matcher res
14818 org-todo-keywords-for-agenda
14819 org-done-keywords-for-agenda
14820 org-todo-keyword-alist-for-agenda
14821 org-tag-alist-for-agenda
14822 org--matcher-tags-todo-only)
14824 (cond
14825 ((eq match t) (setq matcher t))
14826 ((eq match nil) (setq matcher t))
14827 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14829 (save-excursion
14830 (save-restriction
14831 (cond ((eq scope 'tree)
14832 (org-back-to-heading t)
14833 (org-narrow-to-subtree)
14834 (setq scope nil))
14835 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14836 (org-region-active-p))
14837 ;; If needed, set start-level to a string like "2"
14838 (when start-level
14839 (save-excursion
14840 (goto-char (region-beginning))
14841 (unless (org-at-heading-p) (outline-next-heading))
14842 (setq start-level (org-current-level))))
14843 (narrow-to-region (region-beginning)
14844 (save-excursion
14845 (goto-char (region-end))
14846 (unless (and (bolp) (org-at-heading-p))
14847 (outline-next-heading))
14848 (point)))
14849 (setq scope nil)))
14851 (if (not scope)
14852 (progn
14853 (org-agenda-prepare-buffers
14854 (and buffer-file-name (list buffer-file-name)))
14855 (setq res
14856 (org-scan-tags
14857 func matcher org--matcher-tags-todo-only start-level)))
14858 ;; Get the right scope
14859 (cond
14860 ((and scope (listp scope) (symbolp (car scope)))
14861 (setq scope (eval scope)))
14862 ((eq scope 'agenda)
14863 (setq scope (org-agenda-files t)))
14864 ((eq scope 'agenda-with-archives)
14865 (setq scope (org-agenda-files t))
14866 (setq scope (org-add-archive-files scope)))
14867 ((eq scope 'file)
14868 (setq scope (and buffer-file-name (list buffer-file-name))))
14869 ((eq scope 'file-with-archives)
14870 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14871 (org-agenda-prepare-buffers scope)
14872 (dolist (file scope)
14873 (with-current-buffer (org-find-base-buffer-visiting file)
14874 (org-with-wide-buffer
14875 (goto-char (point-min))
14876 (setq res
14877 (append
14879 (org-scan-tags
14880 func matcher org--matcher-tags-todo-only)))))))))
14881 res)))
14883 ;;; Properties API
14885 (defconst org-special-properties
14886 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
14887 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
14888 "The special properties valid in Org mode.
14889 These are properties that are not defined in the property drawer,
14890 but in some other way.")
14892 (defconst org-default-properties
14893 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14894 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14895 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14896 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14897 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
14898 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14899 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14900 "Some properties that are used by Org mode for various purposes.
14901 Being in this list makes sure that they are offered for completion.")
14903 (defun org--valid-property-p (property)
14904 "Non nil when string PROPERTY is a valid property name."
14905 (not
14906 (or (equal property "")
14907 (string-match-p "\\s-" property))))
14909 (defun org--update-property-plist (key val props)
14910 "Associate KEY to VAL in alist PROPS.
14911 Modifications are made by side-effect. Return new alist."
14912 (let* ((appending (string= (substring key -1) "+"))
14913 (key (if appending (substring key 0 -1) key))
14914 (old (assoc-string key props t)))
14915 (if (not old) (cons (cons key val) props)
14916 (setcdr old (if appending (concat (cdr old) " " val) val))
14917 props)))
14919 (defun org-get-property-block (&optional beg force)
14920 "Return the (beg . end) range of the body of the property drawer.
14921 BEG is the beginning of the current subtree, or of the part
14922 before the first headline. If it is not given, it will be found.
14923 If the drawer does not exist, create it if FORCE is non-nil, or
14924 return nil."
14925 (org-with-wide-buffer
14926 (when beg (goto-char beg))
14927 (unless (org-before-first-heading-p)
14928 (let ((beg (cond (beg)
14929 ((or (not (featurep 'org-inlinetask))
14930 (org-inlinetask-in-task-p))
14931 (org-back-to-heading t))
14932 (t (org-with-limited-levels (org-back-to-heading t))))))
14933 (forward-line)
14934 (when (looking-at-p org-planning-line-re) (forward-line))
14935 (cond ((looking-at org-property-drawer-re)
14936 (forward-line)
14937 (cons (point) (progn (goto-char (match-end 0))
14938 (line-beginning-position))))
14939 (force
14940 (goto-char beg)
14941 (org-insert-property-drawer)
14942 (let ((pos (save-excursion (search-forward ":END:")
14943 (line-beginning-position))))
14944 (cons pos pos))))))))
14946 (defun org-at-property-p ()
14947 "Non-nil when point is inside a property drawer.
14948 See `org-property-re' for match data, if applicable."
14949 (save-excursion
14950 (beginning-of-line)
14951 (and (looking-at org-property-re)
14952 (let ((property-drawer (save-match-data (org-get-property-block))))
14953 (and property-drawer
14954 (>= (point) (car property-drawer))
14955 (< (point) (cdr property-drawer)))))))
14957 (defun org-property-action ()
14958 "Do an action on properties."
14959 (interactive)
14960 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14961 (let ((c (read-char-exclusive)))
14962 (cl-case c
14963 (?s (call-interactively #'org-set-property))
14964 (?d (call-interactively #'org-delete-property))
14965 (?D (call-interactively #'org-delete-property-globally))
14966 (?c (call-interactively #'org-compute-property-at-point))
14967 (otherwise (user-error "No such property action %c" c)))))
14969 (defun org-inc-effort ()
14970 "Increment the value of the effort property in the current entry."
14971 (interactive)
14972 (org-set-effort t))
14974 (defvar org-clock-effort) ; Defined in org-clock.el.
14975 (defvar org-clock-current-task) ; Defined in org-clock.el.
14976 (defun org-set-effort (&optional increment value)
14977 "Set the effort property of the current entry.
14978 If INCREMENT is non-nil, set the property to the next allowed
14979 value. Otherwise, if optional argument VALUE is provided, use
14980 it. Eventually, prompt for the new value if none of the previous
14981 variables is set."
14982 (interactive "P")
14983 (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
14984 (current (org-entry-get nil org-effort-property))
14985 (value
14986 (cond
14987 (increment
14988 (unless allowed (user-error "Allowed effort values are not set"))
14989 (or (cl-caadr (member (list current) allowed))
14990 (user-error "Unknown value %S among allowed values" current)))
14991 (value
14992 (if (stringp value) value
14993 (error "Invalid effort value: %S" value)))
14995 (let ((must-match
14996 (and allowed
14997 (not (get-text-property 0 'org-unrestricted
14998 (caar allowed))))))
14999 (completing-read "Effort: " allowed nil must-match))))))
15000 (unless (equal current value)
15001 (org-entry-put nil org-effort-property value))
15002 (org-refresh-property '((effort . identity)
15003 (effort-minutes . org-duration-to-minutes))
15004 value)
15005 (when (equal (org-get-heading t t t t)
15006 (bound-and-true-p org-clock-current-task))
15007 (setq org-clock-effort (org-get-at-bol 'effort))
15008 (org-clock-update-mode-line))
15009 (message "%s is now %s" org-effort-property value)))
15011 (defun org-entry-properties (&optional pom which)
15012 "Get all properties of the current entry.
15014 When POM is a buffer position, get all properties from the entry
15015 there instead.
15017 This includes the TODO keyword, the tags, time strings for
15018 deadline, scheduled, and clocking, and any additional properties
15019 defined in the entry.
15021 If WHICH is nil or `all', get all properties. If WHICH is
15022 `special' or `standard', only get that subclass. If WHICH is
15023 a string, only get that property.
15025 Return value is an alist. Keys are properties, as upcased
15026 strings."
15027 (org-with-point-at pom
15028 (when (and (derived-mode-p 'org-mode)
15029 (ignore-errors (org-back-to-heading t)))
15030 (catch 'exit
15031 (let* ((beg (point))
15032 (specific (and (stringp which) (upcase which)))
15033 (which (cond ((not specific) which)
15034 ((member specific org-special-properties) 'special)
15035 (t 'standard)))
15036 props)
15037 ;; Get the special properties, like TODO and TAGS.
15038 (when (memq which '(nil all special))
15039 (when (or (not specific) (string= specific "CLOCKSUM"))
15040 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15041 (when clocksum
15042 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15043 props)))
15044 (when specific (throw 'exit props)))
15045 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15046 (let ((clocksumt (get-text-property (point)
15047 :org-clock-minutes-today)))
15048 (when clocksumt
15049 (push (cons "CLOCKSUM_T"
15050 (org-duration-from-minutes clocksumt))
15051 props)))
15052 (when specific (throw 'exit props)))
15053 (when (or (not specific) (string= specific "ITEM"))
15054 (let ((case-fold-search nil))
15055 (when (looking-at org-complex-heading-regexp)
15056 (push (cons "ITEM"
15057 (let ((title (match-string-no-properties 4)))
15058 (if (org-string-nw-p title)
15059 (org-remove-tabs title)
15060 "")))
15061 props)))
15062 (when specific (throw 'exit props)))
15063 (when (or (not specific) (string= specific "TODO"))
15064 (let ((case-fold-search nil))
15065 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15066 (push (cons "TODO" (match-string-no-properties 2)) props)))
15067 (when specific (throw 'exit props)))
15068 (when (or (not specific) (string= specific "PRIORITY"))
15069 (push (cons "PRIORITY"
15070 (if (looking-at org-priority-regexp)
15071 (match-string-no-properties 2)
15072 (char-to-string org-default-priority)))
15073 props)
15074 (when specific (throw 'exit props)))
15075 (when (or (not specific) (string= specific "FILE"))
15076 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15077 props)
15078 (when specific (throw 'exit props)))
15079 (when (or (not specific) (string= specific "TAGS"))
15080 (let ((tags (org-get-tags nil t)))
15081 (when tags
15082 (push (cons "TAGS" (org-make-tag-string tags))
15083 props)))
15084 (when specific (throw 'exit props)))
15085 (when (or (not specific) (string= specific "ALLTAGS"))
15086 (let ((tags (org-get-tags)))
15087 (when tags
15088 (push (cons "ALLTAGS" (org-make-tag-string tags))
15089 props)))
15090 (when specific (throw 'exit props)))
15091 (when (or (not specific) (string= specific "BLOCKED"))
15092 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15093 (when specific (throw 'exit props)))
15094 (when (or (not specific)
15095 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15096 (forward-line)
15097 (when (looking-at-p org-planning-line-re)
15098 (end-of-line)
15099 (let ((bol (line-beginning-position))
15100 ;; Backward compatibility: time keywords used to
15101 ;; be configurable (before 8.3). Make sure we
15102 ;; get the correct keyword.
15103 (key-assoc `(("CLOSED" . ,org-closed-string)
15104 ("DEADLINE" . ,org-deadline-string)
15105 ("SCHEDULED" . ,org-scheduled-string))))
15106 (dolist (pair (if specific (list (assoc specific key-assoc))
15107 key-assoc))
15108 (save-excursion
15109 (when (search-backward (cdr pair) bol t)
15110 (goto-char (match-end 0))
15111 (skip-chars-forward " \t")
15112 (and (looking-at org-ts-regexp-both)
15113 (push (cons (car pair)
15114 (match-string-no-properties 0))
15115 props)))))))
15116 (when specific (throw 'exit props)))
15117 (when (or (not specific)
15118 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15119 (let ((find-ts
15120 (lambda (end ts)
15121 ;; Fix next time-stamp before END. TS is the
15122 ;; list of time-stamps found so far.
15123 (let ((ts ts)
15124 (regexp (cond
15125 ((string= specific "TIMESTAMP")
15126 org-ts-regexp)
15127 ((string= specific "TIMESTAMP_IA")
15128 org-ts-regexp-inactive)
15129 ((assoc "TIMESTAMP_IA" ts)
15130 org-ts-regexp)
15131 ((assoc "TIMESTAMP" ts)
15132 org-ts-regexp-inactive)
15133 (t org-ts-regexp-both))))
15134 (catch 'next
15135 (while (re-search-forward regexp end t)
15136 (backward-char)
15137 (let ((object (org-element-context)))
15138 ;; Accept to match timestamps in node
15139 ;; properties, too.
15140 (when (memq (org-element-type object)
15141 '(node-property timestamp))
15142 (let ((type
15143 (org-element-property :type object)))
15144 (cond
15145 ((and (memq type '(active active-range))
15146 (not (equal specific "TIMESTAMP_IA")))
15147 (unless (assoc "TIMESTAMP" ts)
15148 (push (cons "TIMESTAMP"
15149 (org-element-property
15150 :raw-value object))
15152 (when specific (throw 'exit ts))))
15153 ((and (memq type '(inactive inactive-range))
15154 (not (string= specific "TIMESTAMP")))
15155 (unless (assoc "TIMESTAMP_IA" ts)
15156 (push (cons "TIMESTAMP_IA"
15157 (org-element-property
15158 :raw-value object))
15160 (when specific (throw 'exit ts))))))
15161 ;; Both timestamp types are found,
15162 ;; move to next part.
15163 (when (= (length ts) 2) (throw 'next ts)))))
15164 ts)))))
15165 (goto-char beg)
15166 ;; First look for timestamps within headline.
15167 (let ((ts (funcall find-ts (line-end-position) nil)))
15168 (if (= (length ts) 2) (setq props (nconc ts props))
15169 ;; Then find timestamps in the section, skipping
15170 ;; planning line.
15171 (let ((end (save-excursion (outline-next-heading))))
15172 (forward-line)
15173 (when (looking-at-p org-planning-line-re) (forward-line))
15174 (setq props (nconc (funcall find-ts end ts) props))))))))
15175 ;; Get the standard properties, like :PROP:.
15176 (when (memq which '(nil all standard))
15177 ;; If we are looking after a specific property, delegate
15178 ;; to `org-entry-get', which is faster. However, make an
15179 ;; exception for "CATEGORY", since it can be also set
15180 ;; through keywords (i.e. #+CATEGORY).
15181 (if (and specific (not (equal specific "CATEGORY")))
15182 (let ((value (org-entry-get beg specific nil t)))
15183 (throw 'exit (and value (list (cons specific value)))))
15184 (let ((range (org-get-property-block beg)))
15185 (when range
15186 (let ((end (cdr range)) seen-base)
15187 (goto-char (car range))
15188 ;; Unlike to `org--update-property-plist', we
15189 ;; handle the case where base values is found
15190 ;; after its extension. We also forbid standard
15191 ;; properties to be named as special properties.
15192 (while (re-search-forward org-property-re end t)
15193 (let* ((key (upcase (match-string-no-properties 2)))
15194 (extendp (string-match-p "\\+\\'" key))
15195 (key-base (if extendp (substring key 0 -1) key))
15196 (value (match-string-no-properties 3)))
15197 (cond
15198 ((member-ignore-case key-base org-special-properties))
15199 (extendp
15200 (setq props
15201 (org--update-property-plist key value props)))
15202 ((member key seen-base))
15203 (t (push key seen-base)
15204 (let ((p (assoc-string key props t)))
15205 (if p (setcdr p (concat value " " (cdr p)))
15206 (push (cons key value) props))))))))))))
15207 (unless (assoc "CATEGORY" props)
15208 (push (cons "CATEGORY" (org-get-category beg)) props)
15209 (when (string= specific "CATEGORY") (throw 'exit props)))
15210 ;; Return value.
15211 props)))))
15213 (defun org--property-local-values (property literal-nil)
15214 "Return value for PROPERTY in current entry.
15215 Value is a list whose car is the base value for PROPERTY and cdr
15216 a list of accumulated values. Return nil if neither is found in
15217 the entry. Also return nil when PROPERTY is set to \"nil\",
15218 unless LITERAL-NIL is non-nil."
15219 (let ((range (org-get-property-block)))
15220 (when range
15221 (goto-char (car range))
15222 (let* ((case-fold-search t)
15223 (end (cdr range))
15224 (value
15225 ;; Base value.
15226 (save-excursion
15227 (let ((v (and (re-search-forward
15228 (org-re-property property nil t) end t)
15229 (match-string-no-properties 3))))
15230 (list (if literal-nil v (org-not-nil v)))))))
15231 ;; Find additional values.
15232 (let* ((property+ (org-re-property (concat property "+") nil t)))
15233 (while (re-search-forward property+ end t)
15234 (push (match-string-no-properties 3) value)))
15235 ;; Return final values.
15236 (and (not (equal value '(nil))) (nreverse value))))))
15238 (defun org--property-global-value (property literal-nil)
15239 "Return value for PROPERTY in current buffer.
15240 Return value is a string. Return nil if property is not set
15241 globally. Also return nil when PROPERTY is set to \"nil\",
15242 unless LITERAL-NIL is non-nil."
15243 (let ((global
15244 (cdr (or (assoc-string property org-file-properties t)
15245 (assoc-string property org-global-properties t)
15246 (assoc-string property org-global-properties-fixed t)))))
15247 (if literal-nil global (org-not-nil global))))
15249 (defun org-entry-get (pom property &optional inherit literal-nil)
15250 "Get value of PROPERTY for entry or content at point-or-marker POM.
15252 If INHERIT is non-nil and the entry does not have the property,
15253 then also check higher levels of the hierarchy. If INHERIT is
15254 the symbol `selective', use inheritance only if the setting in
15255 `org-use-property-inheritance' selects PROPERTY for inheritance.
15257 If the property is present but empty, the return value is the
15258 empty string. If the property is not present at all, nil is
15259 returned. In any other case, return the value as a string.
15260 Search is case-insensitive.
15262 If LITERAL-NIL is set, return the string value \"nil\" as
15263 a string, do not interpret it as the list atom nil. This is used
15264 for inheritance when a \"nil\" value can supersede a non-nil
15265 value higher up the hierarchy."
15266 (org-with-point-at pom
15267 (cond
15268 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15269 ;; We need a special property. Use `org-entry-properties' to
15270 ;; retrieve it, but specify the wanted property.
15271 (cdr (assoc-string property (org-entry-properties nil property))))
15272 ((and inherit
15273 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15274 (org-entry-get-with-inheritance property literal-nil))
15276 (let* ((local (org--property-local-values property literal-nil))
15277 (value (and local (mapconcat #'identity (delq nil local) " "))))
15278 (if literal-nil value (org-not-nil value)))))))
15280 (defun org-property-or-variable-value (var &optional inherit)
15281 "Check if there is a property fixing the value of VAR.
15282 If yes, return this value. If not, return the current value of the variable."
15283 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15284 (if (and prop (stringp prop) (string-match "\\S-" prop))
15285 (read prop)
15286 (symbol-value var))))
15288 (defun org-entry-delete (pom property)
15289 "Delete PROPERTY from entry at point-or-marker POM.
15290 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15291 non-nil when a property was removed."
15292 (org-with-point-at pom
15293 (pcase (org-get-property-block)
15294 (`(,begin . ,origin)
15295 (let* ((end (copy-marker origin))
15296 (re (org-re-property
15297 (concat (regexp-quote property) "\\+?") t t)))
15298 (goto-char begin)
15299 (while (re-search-forward re end t)
15300 (delete-region (match-beginning 0) (line-beginning-position 2)))
15301 ;; If drawer is empty, remove it altogether.
15302 (when (= begin end)
15303 (delete-region (line-beginning-position 0)
15304 (line-beginning-position 2)))
15305 ;; Return non-nil if some property was removed.
15306 (prog1 (/= end origin) (set-marker end nil))))
15307 (_ nil))))
15309 ;; Multi-values properties are properties that contain multiple values
15310 ;; These values are assumed to be single words, separated by whitespace.
15311 (defun org-entry-add-to-multivalued-property (pom property value)
15312 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15313 (let* ((old (org-entry-get pom property))
15314 (values (and old (split-string old))))
15315 (setq value (org-entry-protect-space value))
15316 (unless (member value values)
15317 (setq values (append values (list value)))
15318 (org-entry-put pom property (mapconcat #'identity values " ")))))
15320 (defun org-entry-remove-from-multivalued-property (pom property value)
15321 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15322 (let* ((old (org-entry-get pom property))
15323 (values (and old (split-string old))))
15324 (setq value (org-entry-protect-space value))
15325 (when (member value values)
15326 (setq values (delete value values))
15327 (org-entry-put pom property (mapconcat #'identity values " ")))))
15329 (defun org-entry-member-in-multivalued-property (pom property value)
15330 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15331 (let* ((old (org-entry-get pom property))
15332 (values (and old (split-string old))))
15333 (setq value (org-entry-protect-space value))
15334 (member value values)))
15336 (defun org-entry-get-multivalued-property (pom property)
15337 "Return a list of values in a multivalued property."
15338 (let* ((value (org-entry-get pom property))
15339 (values (and value (split-string value))))
15340 (mapcar #'org-entry-restore-space values)))
15342 (defun org-entry-put-multivalued-property (pom property &rest values)
15343 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15344 VALUES should be a list of strings. Spaces will be protected."
15345 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15346 (let* ((value (org-entry-get pom property))
15347 (values (and value (split-string value))))
15348 (mapcar #'org-entry-restore-space values)))
15350 (defun org-entry-protect-space (s)
15351 "Protect spaces and newline in string S."
15352 (while (string-match " " s)
15353 (setq s (replace-match "%20" t t s)))
15354 (while (string-match "\n" s)
15355 (setq s (replace-match "%0A" t t s)))
15358 (defun org-entry-restore-space (s)
15359 "Restore spaces and newline in string S."
15360 (while (string-match "%20" s)
15361 (setq s (replace-match " " t t s)))
15362 (while (string-match "%0A" s)
15363 (setq s (replace-match "\n" t t s)))
15366 (defvar org-entry-property-inherited-from (make-marker)
15367 "Marker pointing to the entry from where a property was inherited.
15368 Each call to `org-entry-get-with-inheritance' will set this marker to the
15369 location of the entry where the inheritance search matched. If there was
15370 no match, the marker will point nowhere.
15371 Note that also `org-entry-get' calls this function, if the INHERIT flag
15372 is set.")
15374 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15375 "Get PROPERTY of entry or content at point, search higher levels if needed.
15376 The search will stop at the first ancestor which has the property defined.
15377 If the value found is \"nil\", return nil to show that the property
15378 should be considered as undefined (this is the meaning of nil here).
15379 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15380 (move-marker org-entry-property-inherited-from nil)
15381 (org-with-wide-buffer
15382 (let (value)
15383 (catch 'exit
15384 (while t
15385 (let ((v (org--property-local-values property literal-nil)))
15386 (when v
15387 (setq value
15388 (concat (mapconcat #'identity (delq nil v) " ")
15389 (and value " ")
15390 value)))
15391 (cond
15392 ((car v)
15393 (org-back-to-heading t)
15394 (move-marker org-entry-property-inherited-from (point))
15395 (throw 'exit nil))
15396 ((org-up-heading-safe))
15398 (let ((global (org--property-global-value property literal-nil)))
15399 (cond ((not global))
15400 (value (setq value (concat global " " value)))
15401 (t (setq value global))))
15402 (throw 'exit nil))))))
15403 (if literal-nil value (org-not-nil value)))))
15405 (defvar org-property-changed-functions nil
15406 "Hook called when the value of a property has changed.
15407 Each hook function should accept two arguments, the name of the property
15408 and the new value.")
15410 (defun org-entry-put (pom property value)
15411 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15413 If the value is nil, it is converted to the empty string. If it
15414 is not a string, an error is raised. Also raise an error on
15415 invalid property names.
15417 PROPERTY can be any regular property (see
15418 `org-special-properties'). It can also be \"TODO\",
15419 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15421 For the last two properties, VALUE may have any of the special
15422 values \"earlier\" and \"later\". The function then increases or
15423 decreases scheduled or deadline date by one day."
15424 (cond ((null value) (setq value ""))
15425 ((not (stringp value)) (error "Properties values should be strings"))
15426 ((not (org--valid-property-p property))
15427 (user-error "Invalid property name: \"%s\"" property)))
15428 (org-with-point-at pom
15429 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15430 (org-back-to-heading t)
15431 (org-with-limited-levels (org-back-to-heading t)))
15432 (let ((beg (point)))
15433 (cond
15434 ((equal property "TODO")
15435 (cond ((not (org-string-nw-p value)) (setq value 'none))
15436 ((not (member value org-todo-keywords-1))
15437 (user-error "\"%s\" is not a valid TODO state" value)))
15438 (org-todo value)
15439 (org-align-tags))
15440 ((equal property "PRIORITY")
15441 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15442 (org-align-tags))
15443 ((equal property "SCHEDULED")
15444 (forward-line)
15445 (if (and (looking-at-p org-planning-line-re)
15446 (re-search-forward
15447 org-scheduled-time-regexp (line-end-position) t))
15448 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15449 ((string= value "later") (org-timestamp-change 1 'day))
15450 ((string= value "") (org-schedule '(4)))
15451 (t (org-schedule nil value)))
15452 (if (member value '("earlier" "later" ""))
15453 (call-interactively #'org-schedule)
15454 (org-schedule nil value))))
15455 ((equal property "DEADLINE")
15456 (forward-line)
15457 (if (and (looking-at-p org-planning-line-re)
15458 (re-search-forward
15459 org-deadline-time-regexp (line-end-position) t))
15460 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15461 ((string= value "later") (org-timestamp-change 1 'day))
15462 ((string= value "") (org-deadline '(4)))
15463 (t (org-deadline nil value)))
15464 (if (member value '("earlier" "later" ""))
15465 (call-interactively #'org-deadline)
15466 (org-deadline nil value))))
15467 ((member property org-special-properties)
15468 (error "The %s property cannot be set with `org-entry-put'" property))
15470 (let* ((range (org-get-property-block beg 'force))
15471 (end (cdr range))
15472 (case-fold-search t))
15473 (goto-char (car range))
15474 (if (re-search-forward (org-re-property property nil t) end t)
15475 (progn (delete-region (match-beginning 0) (match-end 0))
15476 (goto-char (match-beginning 0)))
15477 (goto-char end)
15478 (insert "\n")
15479 (backward-char))
15480 (insert ":" property ":")
15481 (when value (insert " " value))
15482 (org-indent-line)))))
15483 (run-hook-with-args 'org-property-changed-functions property value)))
15485 (defun org-buffer-property-keys (&optional specials defaults columns)
15486 "Get all property keys in the current buffer.
15488 When SPECIALS is non-nil, also list the special properties that
15489 reflect things like tags and TODO state.
15491 When DEFAULTS is non-nil, also include properties that has
15492 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
15493 DESCRIPTION, LOCATION, and LOGGING and others.
15495 When COLUMNS in non-nil, also include property names given in
15496 COLUMN formats in the current buffer."
15497 (let ((case-fold-search t)
15498 (props (append
15499 (and specials org-special-properties)
15500 (and defaults (cons org-effort-property org-default-properties))
15501 nil)))
15502 (org-with-wide-buffer
15503 (goto-char (point-min))
15504 (while (re-search-forward org-property-start-re nil t)
15505 (catch :skip
15506 (let ((range (org-get-property-block)))
15507 (unless range (throw :skip nil))
15508 (goto-char (car range))
15509 (let ((begin (car range))
15510 (end (cdr range)))
15511 ;; Make sure that found property block is not located
15512 ;; before current point, as it would generate an infloop.
15513 ;; It can happen, for example, in the following
15514 ;; situation:
15516 ;; * Headline
15517 ;; :PROPERTIES:
15518 ;; ...
15519 ;; :END:
15520 ;; *************** Inlinetask
15521 ;; #+BEGIN_EXAMPLE
15522 ;; :PROPERTIES:
15523 ;; #+END_EXAMPLE
15525 (if (< begin (point)) (throw :skip nil) (goto-char begin))
15526 (while (< (point) end)
15527 (let ((p (progn (looking-at org-property-re)
15528 (match-string-no-properties 2))))
15529 ;; Only add true property name, not extension symbol.
15530 (push (if (not (string-match-p "\\+\\'" p)) p
15531 (substring p 0 -1))
15532 props))
15533 (forward-line))))
15534 (outline-next-heading)))
15535 (when columns
15536 (goto-char (point-min))
15537 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
15538 (let ((element (org-element-at-point)))
15539 (when (memq (org-element-type element) '(keyword node-property))
15540 (let ((value (org-element-property :value element))
15541 (start 0))
15542 (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
15543 \\(?:{[^}]+}\\)?"
15544 value start)
15545 (setq start (match-end 0))
15546 (let ((p (match-string-no-properties 1 value)))
15547 (unless (member-ignore-case p org-special-properties)
15548 (push p props))))))))))
15549 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
15551 (defun org-property-values (key)
15552 "List all non-nil values of property KEY in current buffer."
15553 (org-with-wide-buffer
15554 (goto-char (point-min))
15555 (let ((case-fold-search t)
15556 (re (org-re-property key))
15557 values)
15558 (while (re-search-forward re nil t)
15559 (push (org-entry-get (point) key) values))
15560 (delete-dups values))))
15562 (defun org-insert-property-drawer ()
15563 "Insert a property drawer into the current entry."
15564 (org-with-wide-buffer
15565 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15566 (org-back-to-heading t)
15567 (org-with-limited-levels (org-back-to-heading t)))
15568 (forward-line)
15569 (when (looking-at-p org-planning-line-re) (forward-line))
15570 (unless (looking-at-p org-property-drawer-re)
15571 ;; Make sure we start editing a line from current entry, not from
15572 ;; next one. It prevents extending text properties or overlays
15573 ;; belonging to the latter.
15574 (when (bolp) (backward-char))
15575 (let ((begin (1+ (point)))
15576 (inhibit-read-only t))
15577 (insert "\n:PROPERTIES:\n:END:")
15578 (when (eobp) (insert "\n"))
15579 (org-indent-region begin (point))))))
15581 (defun org-insert-drawer (&optional arg drawer)
15582 "Insert a drawer at point.
15584 When optional argument ARG is non-nil, insert a property drawer.
15586 Optional argument DRAWER, when non-nil, is a string representing
15587 drawer's name. Otherwise, the user is prompted for a name.
15589 If a region is active, insert the drawer around that region
15590 instead.
15592 Point is left between drawer's boundaries."
15593 (interactive "P")
15594 (let* ((drawer (if arg "PROPERTIES"
15595 (or drawer (read-from-minibuffer "Drawer: ")))))
15596 (cond
15597 ;; With C-u, fall back on `org-insert-property-drawer'
15598 (arg (org-insert-property-drawer))
15599 ;; Check validity of suggested drawer's name.
15600 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
15601 (user-error "Invalid drawer name"))
15602 ;; With an active region, insert a drawer at point.
15603 ((not (org-region-active-p))
15604 (progn
15605 (unless (bolp) (insert "\n"))
15606 (insert (format ":%s:\n\n:END:\n" drawer))
15607 (forward-line -2)))
15608 ;; Otherwise, insert the drawer at point
15610 (let ((rbeg (region-beginning))
15611 (rend (copy-marker (region-end))))
15612 (unwind-protect
15613 (progn
15614 (goto-char rbeg)
15615 (beginning-of-line)
15616 (when (save-excursion
15617 (re-search-forward org-outline-regexp-bol rend t))
15618 (user-error "Drawers cannot contain headlines"))
15619 ;; Position point at the beginning of the first
15620 ;; non-blank line in region. Insert drawer's opening
15621 ;; there, then indent it.
15622 (org-skip-whitespace)
15623 (beginning-of-line)
15624 (insert ":" drawer ":\n")
15625 (forward-line -1)
15626 (indent-for-tab-command)
15627 ;; Move point to the beginning of the first blank line
15628 ;; after the last non-blank line in region. Insert
15629 ;; drawer's closing, then indent it.
15630 (goto-char rend)
15631 (skip-chars-backward " \r\t\n")
15632 (insert "\n:END:")
15633 (deactivate-mark t)
15634 (indent-for-tab-command)
15635 (unless (eolp) (insert "\n")))
15636 ;; Clear marker, whatever the outcome of insertion is.
15637 (set-marker rend nil)))))))
15639 (defvar org-property-set-functions-alist nil
15640 "Property set function alist.
15641 Each entry should have the following format:
15643 (PROPERTY . READ-FUNCTION)
15645 The read function will be called with the same argument as
15646 `org-completing-read'.")
15648 (defun org-set-property-function (property)
15649 "Get the function that should be used to set PROPERTY.
15650 This is computed according to `org-property-set-functions-alist'."
15651 (or (cdr (assoc property org-property-set-functions-alist))
15652 'org-completing-read))
15654 (defun org-read-property-value (property &optional pom)
15655 "Read value for PROPERTY, as a string.
15656 When optional argument POM is non-nil, completion uses additional
15657 information, i.e., allowed or existing values at point or marker
15658 POM."
15659 (let* ((completion-ignore-case t)
15660 (allowed
15661 (or (org-property-get-allowed-values nil property 'table)
15662 (and pom (org-property-get-allowed-values pom property 'table))))
15663 (current (org-entry-get nil property))
15664 (prompt (format "%s value%s: "
15665 property
15666 (if (org-string-nw-p current)
15667 (format " [%s]" current)
15668 "")))
15669 (set-function (org-set-property-function property)))
15670 (org-trim
15671 (if allowed
15672 (funcall set-function
15673 prompt allowed nil
15674 (not (get-text-property 0 'org-unrestricted (caar allowed))))
15675 (let ((all (mapcar #'list
15676 (append (org-property-values property)
15677 (and pom
15678 (org-with-point-at pom
15679 (org-property-values property)))))))
15680 (funcall set-function prompt all nil nil "" nil current))))))
15682 (defvar org-last-set-property nil)
15683 (defvar org-last-set-property-value nil)
15684 (defun org-read-property-name ()
15685 "Read a property name."
15686 (let ((completion-ignore-case t)
15687 (default-prop (or (and (org-at-property-p)
15688 (match-string-no-properties 2))
15689 org-last-set-property)))
15690 (org-completing-read
15691 (concat "Property"
15692 (if default-prop (concat " [" default-prop "]") "")
15693 ": ")
15694 (mapcar #'list (org-buffer-property-keys nil t t))
15695 nil nil nil nil default-prop)))
15697 (defun org-set-property-and-value (use-last)
15698 "Allow to set [PROPERTY]: [value] direction from prompt.
15699 When use-default, don't even ask, just use the last
15700 \"[PROPERTY]: [value]\" string from the history."
15701 (interactive "P")
15702 (let* ((completion-ignore-case t)
15703 (pv (or (and use-last org-last-set-property-value)
15704 (org-completing-read
15705 "Enter a \"[Property]: [value]\" pair: "
15706 nil nil nil nil nil
15707 org-last-set-property-value)))
15708 prop val)
15709 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15710 (setq prop (match-string 1 pv)
15711 val (match-string 2 pv))
15712 (org-set-property prop val))))
15714 (defun org-set-property (property value)
15715 "In the current entry, set PROPERTY to VALUE.
15717 When called interactively, this will prompt for a property name, offering
15718 completion on existing and default properties. And then it will prompt
15719 for a value, offering completion either on allowed values (via an inherited
15720 xxx_ALL property) or on existing values in other instances of this property
15721 in the current file.
15723 Throw an error when trying to set a property with an invalid name."
15724 (interactive (list nil nil))
15725 (let ((property (or property (org-read-property-name))))
15726 ;; `org-entry-put' also makes the following check, but this one
15727 ;; avoids polluting `org-last-set-property' and
15728 ;; `org-last-set-property-value' needlessly.
15729 (unless (org--valid-property-p property)
15730 (user-error "Invalid property name: \"%s\"" property))
15731 (let ((value (or value (org-read-property-value property)))
15732 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
15733 (setq org-last-set-property property)
15734 (setq org-last-set-property-value (concat property ": " value))
15735 ;; Possibly postprocess the inserted value:
15736 (when fn (setq value (funcall fn value)))
15737 (unless (equal (org-entry-get nil property) value)
15738 (org-entry-put nil property value)))))
15740 (defun org-find-property (property &optional value)
15741 "Find first entry in buffer that sets PROPERTY.
15743 When optional argument VALUE is non-nil, only consider an entry
15744 if it contains PROPERTY set to this value. If PROPERTY should be
15745 explicitly set to nil, use string \"nil\" for VALUE.
15747 Return position where the entry begins, or nil if there is no
15748 such entry. If narrowing is in effect, only search the visible
15749 part of the buffer."
15750 (save-excursion
15751 (goto-char (point-min))
15752 (let ((case-fold-search t)
15753 (re (org-re-property property nil (not value) value)))
15754 (catch 'exit
15755 (while (re-search-forward re nil t)
15756 (when (if value (org-at-property-p)
15757 (org-entry-get (point) property nil t))
15758 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
15760 (defun org-delete-property (property)
15761 "In the current entry, delete PROPERTY."
15762 (interactive
15763 (let* ((completion-ignore-case t)
15764 (cat (org-entry-get (point) "CATEGORY"))
15765 (props0 (org-entry-properties nil 'standard))
15766 (props (if cat props0
15767 (delete `("CATEGORY" . ,(org-get-category)) props0)))
15768 (prop (if (< 1 (length props))
15769 (completing-read "Property: " props nil t)
15770 (caar props))))
15771 (list prop)))
15772 (if (not property)
15773 (message "No property to delete in this entry")
15774 (org-entry-delete nil property)
15775 (message "Property \"%s\" deleted" property)))
15777 (defun org-delete-property-globally (property)
15778 "Remove PROPERTY globally, from all entries.
15779 This function ignores narrowing, if any."
15780 (interactive
15781 (let* ((completion-ignore-case t)
15782 (prop (completing-read
15783 "Globally remove property: "
15784 (mapcar #'list (org-buffer-property-keys)))))
15785 (list prop)))
15786 (org-with-wide-buffer
15787 (goto-char (point-min))
15788 (let ((count 0)
15789 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
15790 (while (re-search-forward re nil t)
15791 (when (org-entry-delete (point) property) (cl-incf count)))
15792 (message "Property \"%s\" removed from %d entries" property count))))
15794 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15796 (defun org-compute-property-at-point ()
15797 "Compute the property at point.
15798 This looks for an enclosing column format, extracts the operator and
15799 then applies it to the property in the column format's scope."
15800 (interactive)
15801 (unless (org-at-property-p)
15802 (user-error "Not at a property"))
15803 (let ((prop (match-string-no-properties 2)))
15804 (org-columns-get-format-and-top-level)
15805 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
15806 (user-error "No operator defined for property %s" prop))
15807 (org-columns-compute prop)))
15809 (defvar org-property-allowed-value-functions nil
15810 "Hook for functions supplying allowed values for a specific property.
15811 The functions must take a single argument, the name of the property, and
15812 return a flat list of allowed values. If \":ETC\" is one of
15813 the values, this means that these values are intended as defaults for
15814 completion, but that other values should be allowed too.
15815 The functions must return nil if they are not responsible for this
15816 property.")
15818 (defun org-property-get-allowed-values (pom property &optional table)
15819 "Get allowed values for the property PROPERTY.
15820 When TABLE is non-nil, return an alist that can directly be used for
15821 completion."
15822 (let (vals)
15823 (cond
15824 ((equal property "TODO")
15825 (setq vals (org-with-point-at pom
15826 (append org-todo-keywords-1 '("")))))
15827 ((equal property "PRIORITY")
15828 (let ((n org-lowest-priority))
15829 (while (>= n org-highest-priority)
15830 (push (char-to-string n) vals)
15831 (setq n (1- n)))))
15832 ((equal property "CATEGORY"))
15833 ((member property org-special-properties))
15834 ((setq vals (run-hook-with-args-until-success
15835 'org-property-allowed-value-functions property)))
15837 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15838 (when (and vals (string-match "\\S-" vals))
15839 (setq vals (car (read-from-string (concat "(" vals ")"))))
15840 (setq vals (mapcar (lambda (x)
15841 (cond ((stringp x) x)
15842 ((numberp x) (number-to-string x))
15843 ((symbolp x) (symbol-name x))
15844 (t "???")))
15845 vals)))))
15846 (when (member ":ETC" vals)
15847 (setq vals (remove ":ETC" vals))
15848 (org-add-props (car vals) '(org-unrestricted t)))
15849 (if table (mapcar 'list vals) vals)))
15851 (defun org-property-previous-allowed-value (&optional _previous)
15852 "Switch to the next allowed value for this property."
15853 (interactive)
15854 (org-property-next-allowed-value t))
15856 (defun org-property-next-allowed-value (&optional previous)
15857 "Switch to the next allowed value for this property."
15858 (interactive)
15859 (unless (org-at-property-p)
15860 (user-error "Not at a property"))
15861 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15862 (key (match-string 2))
15863 (value (match-string 3))
15864 (allowed (or (org-property-get-allowed-values (point) key)
15865 (and (member value '("[ ]" "[-]" "[X]"))
15866 '("[ ]" "[X]"))))
15867 (heading (save-match-data (nth 4 (org-heading-components))))
15868 nval)
15869 (unless allowed
15870 (user-error "Allowed values for this property have not been defined"))
15871 (when previous (setq allowed (reverse allowed)))
15872 (when (member value allowed)
15873 (setq nval (car (cdr (member value allowed)))))
15874 (setq nval (or nval (car allowed)))
15875 (when (equal nval value)
15876 (user-error "Only one allowed value for this property"))
15877 (org-at-property-p)
15878 (replace-match (concat " :" key ": " nval) t t)
15879 (org-indent-line)
15880 (beginning-of-line 1)
15881 (skip-chars-forward " \t")
15882 (when (equal prop org-effort-property)
15883 (org-refresh-property
15884 '((effort . identity)
15885 (effort-minutes . org-duration-to-minutes))
15886 nval)
15887 (when (string= org-clock-current-task heading)
15888 (setq org-clock-effort nval)
15889 (org-clock-update-mode-line)))
15890 (run-hook-with-args 'org-property-changed-functions key nval)))
15892 (defun org-find-olp (path &optional this-buffer)
15893 "Return a marker pointing to the entry at outline path OLP.
15894 If anything goes wrong, throw an error.
15895 You can wrap this call to catch the error like this:
15897 (condition-case msg
15898 (org-mobile-locate-entry (match-string 4))
15899 (error (nth 1 msg)))
15901 The return value will then be either a string with the error message,
15902 or a marker if everything is OK.
15904 If THIS-BUFFER is set, the outline path does not contain a file,
15905 only headings."
15906 (let* ((file (if this-buffer buffer-file-name (pop path)))
15907 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15908 (level 1)
15909 (lmin 1)
15910 (lmax 1)
15911 end found flevel)
15912 (unless buffer (error "File not found :%s" file))
15913 (with-current-buffer buffer
15914 (unless (derived-mode-p 'org-mode)
15915 (error "Buffer %s needs to be in Org mode" buffer))
15916 (org-with-wide-buffer
15917 (goto-char (point-min))
15918 (dolist (heading path)
15919 (let ((re (format org-complex-heading-regexp-format
15920 (regexp-quote heading)))
15921 (cnt 0))
15922 (while (re-search-forward re end t)
15923 (setq level (- (match-end 1) (match-beginning 1)))
15924 (when (and (>= level lmin) (<= level lmax))
15925 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15926 (when (= cnt 0)
15927 (error "Heading not found on level %d: %s" lmax heading))
15928 (when (> cnt 1)
15929 (error "Heading not unique on level %d: %s" lmax heading))
15930 (goto-char found)
15931 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15932 (setq end (save-excursion (org-end-of-subtree t t)))))
15933 (when (org-at-heading-p)
15934 (point-marker))))))
15936 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15937 "Find node HEADING in BUFFER.
15938 Return a marker to the heading if it was found, or nil if not.
15939 If POS-ONLY is set, return just the position instead of a marker.
15941 The heading text must match exact, but it may have a TODO keyword,
15942 a priority cookie and tags in the standard locations."
15943 (with-current-buffer (or buffer (current-buffer))
15944 (org-with-wide-buffer
15945 (goto-char (point-min))
15946 (let (case-fold-search)
15947 (when (re-search-forward
15948 (format org-complex-heading-regexp-format
15949 (regexp-quote heading)) nil t)
15950 (if pos-only
15951 (match-beginning 0)
15952 (move-marker (make-marker) (match-beginning 0))))))))
15954 (defun org-find-exact-heading-in-directory (heading &optional dir)
15955 "Find Org node headline HEADING in all \".org\" files in directory DIR.
15956 When the target headline is found, return a marker to this location."
15957 (let ((files (directory-files (or dir default-directory)
15958 t "\\`[^.#].*\\.org\\'"))
15959 visiting m buffer)
15960 (catch 'found
15961 (dolist (file files)
15962 (message "trying %s" file)
15963 (setq visiting (org-find-base-buffer-visiting file))
15964 (setq buffer (or visiting (find-file-noselect file)))
15965 (setq m (org-find-exact-headline-in-buffer
15966 heading buffer))
15967 (when (and (not m) (not visiting)) (kill-buffer buffer))
15968 (and m (throw 'found m))))))
15970 (defun org-find-entry-with-id (ident)
15971 "Locate the entry that contains the ID property with exact value IDENT.
15972 IDENT can be a string, a symbol or a number, this function will search for
15973 the string representation of it.
15974 Return the position where this entry starts, or nil if there is no such entry."
15975 (interactive "sID: ")
15976 (let ((id (cond
15977 ((stringp ident) ident)
15978 ((symbolp ident) (symbol-name ident))
15979 ((numberp ident) (number-to-string ident))
15980 (t (error "IDENT %s must be a string, symbol or number" ident)))))
15981 (org-with-wide-buffer (org-find-property "ID" id))))
15983 ;;;; Timestamps
15985 (defvar org-last-changed-timestamp nil)
15986 (defvar org-last-inserted-timestamp nil
15987 "The last time stamp inserted with `org-insert-time-stamp'.")
15989 (defun org-time-stamp (arg &optional inactive)
15990 "Prompt for a date/time and insert a time stamp.
15992 If the user specifies a time like HH:MM or if this command is
15993 called with at least one prefix argument, the time stamp contains
15994 the date and the time. Otherwise, only the date is included.
15996 All parts of a date not specified by the user are filled in from
15997 the timestamp at point, if any, or the current date/time
15998 otherwise.
16000 If there is already a timestamp at the cursor, it is replaced.
16002 With two universal prefix arguments, insert an active timestamp
16003 with the current time without prompting the user.
16005 When called from lisp, the timestamp is inactive if INACTIVE is
16006 non-nil."
16007 (interactive "P")
16008 (let* ((ts (cond
16009 ((org-at-date-range-p t)
16010 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16011 ((org-at-timestamp-p 'lax) (match-string 0))))
16012 ;; Default time is either the timestamp at point or today.
16013 ;; When entering a range, only the range start is considered.
16014 (default-time (if (not ts) (current-time)
16015 (apply #'encode-time (org-parse-time-string ts))))
16016 (default-input (and ts (org-get-compact-tod ts)))
16017 (repeater (and ts
16018 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16019 (match-string 0 ts)))
16020 org-time-was-given
16021 org-end-time-was-given
16022 (time
16023 (and (if (equal arg '(16)) (current-time)
16024 ;; Preserve `this-command' and `last-command'.
16025 (let ((this-command this-command)
16026 (last-command last-command))
16027 (org-read-date
16028 arg 'totime nil nil default-time default-input
16029 inactive))))))
16030 (cond
16031 ((and ts
16032 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16033 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16034 (insert "--")
16035 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16037 ;; Make sure we're on a timestamp. When in the middle of a date
16038 ;; range, move arbitrarily to range end.
16039 (unless (org-at-timestamp-p 'lax)
16040 (skip-chars-forward "-")
16041 (org-at-timestamp-p 'lax))
16042 (replace-match "")
16043 (setq org-last-changed-timestamp
16044 (org-insert-time-stamp
16045 time (or org-time-was-given arg)
16046 inactive nil nil (list org-end-time-was-given)))
16047 (when repeater
16048 (backward-char)
16049 (insert " " repeater)
16050 (setq org-last-changed-timestamp
16051 (concat (substring org-last-inserted-timestamp 0 -1)
16052 " " repeater ">")))
16053 (message "Timestamp updated"))
16054 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16055 (t (org-insert-time-stamp
16056 time (or org-time-was-given arg) inactive nil nil
16057 (list org-end-time-was-given))))))
16059 ;; FIXME: can we use this for something else, like computing time differences?
16060 (defun org-get-compact-tod (s)
16061 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16062 (let* ((t1 (match-string 1 s))
16063 (h1 (string-to-number (match-string 2 s)))
16064 (m1 (string-to-number (match-string 3 s)))
16065 (t2 (and (match-end 4) (match-string 5 s)))
16066 (h2 (and t2 (string-to-number (match-string 6 s))))
16067 (m2 (and t2 (string-to-number (match-string 7 s))))
16068 dh dm)
16069 (if (not t2)
16071 (setq dh (- h2 h1) dm (- m2 m1))
16072 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16073 (concat t1 "+" (number-to-string dh)
16074 (and (/= 0 dm) (format ":%02d" dm)))))))
16076 (defun org-time-stamp-inactive (&optional arg)
16077 "Insert an inactive time stamp.
16079 An inactive time stamp is enclosed in square brackets instead of angle
16080 brackets. It is inactive in the sense that it does not trigger agenda entries,
16081 does not link to the calendar and cannot be changed with the S-cursor keys.
16082 So these are more for recording a certain time/date.
16084 If the user specifies a time like HH:MM or if this command is called with
16085 at least one prefix argument, the time stamp contains the date and the time.
16086 Otherwise, only the date is included.
16088 When called with two universal prefix arguments, insert an active time stamp
16089 with the current time without prompting the user."
16090 (interactive "P")
16091 (org-time-stamp arg 'inactive))
16093 (defvar org-date-ovl (make-overlay 1 1))
16094 (overlay-put org-date-ovl 'face 'org-date-selected)
16095 (delete-overlay org-date-ovl)
16097 (defvar org-ans1) ; dynamically scoped parameter
16098 (defvar org-ans2) ; dynamically scoped parameter
16100 (defvar org-plain-time-of-day-regexp) ; defined below
16102 (defvar org-overriding-default-time nil) ; dynamically scoped
16103 (defvar org-read-date-overlay nil)
16104 (defvar org-dcst nil) ; dynamically scoped
16105 (defvar org-read-date-history nil)
16106 (defvar org-read-date-final-answer nil)
16107 (defvar org-read-date-analyze-futurep nil)
16108 (defvar org-read-date-analyze-forced-year nil)
16109 (defvar org-read-date-inactive)
16111 (defvar org-read-date-minibuffer-local-map
16112 (let* ((map (make-sparse-keymap)))
16113 (set-keymap-parent map minibuffer-local-map)
16114 (org-defkey map (kbd ".")
16115 (lambda () (interactive)
16116 ;; Are we at the beginning of the prompt?
16117 (if (looking-back "^[^:]+: "
16118 (let ((inhibit-field-text-motion t))
16119 (line-beginning-position)))
16120 (org-eval-in-calendar '(calendar-goto-today))
16121 (insert "."))))
16122 (org-defkey map (kbd "C-.")
16123 (lambda () (interactive)
16124 (org-eval-in-calendar '(calendar-goto-today))))
16125 (org-defkey map (kbd "M-S-<left>")
16126 (lambda () (interactive)
16127 (org-eval-in-calendar '(calendar-backward-month 1))))
16128 (org-defkey map (kbd "ESC S-<left>")
16129 (lambda () (interactive)
16130 (org-eval-in-calendar '(calendar-backward-month 1))))
16131 (org-defkey map (kbd "M-S-<right>")
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(calendar-forward-month 1))))
16134 (org-defkey map (kbd "ESC S-<right>")
16135 (lambda () (interactive)
16136 (org-eval-in-calendar '(calendar-forward-month 1))))
16137 (org-defkey map (kbd "M-S-<up>")
16138 (lambda () (interactive)
16139 (org-eval-in-calendar '(calendar-backward-year 1))))
16140 (org-defkey map (kbd "ESC S-<up>")
16141 (lambda () (interactive)
16142 (org-eval-in-calendar '(calendar-backward-year 1))))
16143 (org-defkey map (kbd "M-S-<down>")
16144 (lambda () (interactive)
16145 (org-eval-in-calendar '(calendar-forward-year 1))))
16146 (org-defkey map (kbd "ESC S-<down>")
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(calendar-forward-year 1))))
16149 (org-defkey map (kbd "S-<up>")
16150 (lambda () (interactive)
16151 (org-eval-in-calendar '(calendar-backward-week 1))))
16152 (org-defkey map (kbd "S-<down>")
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(calendar-forward-week 1))))
16155 (org-defkey map (kbd "S-<left>")
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(calendar-backward-day 1))))
16158 (org-defkey map (kbd "S-<right>")
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(calendar-forward-day 1))))
16161 (org-defkey map (kbd "!")
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(diary-view-entries))
16164 (message "")))
16165 (org-defkey map (kbd ">")
16166 (lambda () (interactive)
16167 (org-eval-in-calendar '(calendar-scroll-left 1))))
16168 (org-defkey map (kbd "<")
16169 (lambda () (interactive)
16170 (org-eval-in-calendar '(calendar-scroll-right 1))))
16171 (org-defkey map (kbd "C-v")
16172 (lambda () (interactive)
16173 (org-eval-in-calendar
16174 '(calendar-scroll-left-three-months 1))))
16175 (org-defkey map (kbd "M-v")
16176 (lambda () (interactive)
16177 (org-eval-in-calendar
16178 '(calendar-scroll-right-three-months 1))))
16179 map)
16180 "Keymap for minibuffer commands when using `org-read-date'.")
16182 (defvar org-def)
16183 (defvar org-defdecode)
16184 (defvar org-with-time)
16186 (defvar calendar-setup) ; Dynamically scoped.
16187 (defun org-read-date (&optional with-time to-time from-string prompt
16188 default-time default-input inactive)
16189 "Read a date, possibly a time, and make things smooth for the user.
16190 The prompt will suggest to enter an ISO date, but you can also enter anything
16191 which will at least partially be understood by `parse-time-string'.
16192 Unrecognized parts of the date will default to the current day, month, year,
16193 hour and minute. If this command is called to replace a timestamp at point,
16194 or to enter the second timestamp of a range, the default time is taken
16195 from the existing stamp. Furthermore, the command prefers the future,
16196 so if you are giving a date where the year is not given, and the day-month
16197 combination is already past in the current year, it will assume you
16198 mean next year. For details, see the manual. A few examples:
16200 3-2-5 --> 2003-02-05
16201 feb 15 --> currentyear-02-15
16202 2/15 --> currentyear-02-15
16203 sep 12 9 --> 2009-09-12
16204 12:45 --> today 12:45
16205 22 sept 0:34 --> currentyear-09-22 0:34
16206 12 --> currentyear-currentmonth-12
16207 Fri --> nearest Friday after today
16208 -Tue --> last Tuesday
16209 etc.
16211 Furthermore you can specify a relative date by giving, as the *first* thing
16212 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16213 change in days weeks, months, years.
16214 With a single plus or minus, the date is relative to today. With a double
16215 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16216 +4d --> four days from today
16217 +4 --> same as above
16218 +2w --> two weeks from today
16219 ++5 --> five days from default date
16221 The function understands only English month and weekday abbreviations.
16223 While prompting, a calendar is popped up - you can also select the
16224 date with the mouse (button 1). The calendar shows a period of three
16225 months. To scroll it to other months, use the keys `>' and `<'.
16226 If you don't like the calendar, turn it off with
16227 (setq org-read-date-popup-calendar nil)
16229 With optional argument TO-TIME, the date will immediately be converted
16230 to an internal time.
16231 With an optional argument WITH-TIME, the prompt will suggest to
16232 also insert a time. Note that when WITH-TIME is not set, you can
16233 still enter a time, and this function will inform the calling routine
16234 about this change. The calling routine may then choose to change the
16235 format used to insert the time stamp into the buffer to include the time.
16236 With optional argument FROM-STRING, read from this string instead from
16237 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16238 the time/date that is used for everything that is not specified by the
16239 user."
16240 (require 'parse-time)
16241 (let* ((org-with-time with-time)
16242 (org-time-stamp-rounding-minutes
16243 (if (equal org-with-time '(16))
16244 '(0 0)
16245 org-time-stamp-rounding-minutes))
16246 (org-dcst org-display-custom-times)
16247 (ct (org-current-time))
16248 (org-def (or org-overriding-default-time default-time ct))
16249 (org-defdecode (decode-time org-def))
16250 (cur-frame (selected-frame))
16251 (mouse-autoselect-window nil) ; Don't let the mouse jump
16252 (calendar-setup
16253 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16254 (calendar-move-hook nil)
16255 (calendar-view-diary-initially-flag nil)
16256 (calendar-view-holidays-initially-flag nil)
16257 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16258 ;; Rationalize `org-def' and `org-defdecode', if required.
16259 (when (< (nth 2 org-defdecode) org-extend-today-until)
16260 (setf (nth 2 org-defdecode) -1)
16261 (setf (nth 1 org-defdecode) 59)
16262 (setq org-def (apply #'encode-time org-defdecode))
16263 (setq org-defdecode (decode-time org-def)))
16264 (let* ((timestr (format-time-string
16265 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16266 org-def))
16267 (prompt (concat (if prompt (concat prompt " ") "")
16268 (format "Date+time [%s]: " timestr))))
16269 (cond
16270 (from-string (setq ans from-string))
16271 (org-read-date-popup-calendar
16272 (save-excursion
16273 (save-window-excursion
16274 (calendar)
16275 (when (eq calendar-setup 'calendar-only)
16276 (setq cal-frame
16277 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16278 (select-frame cal-frame))
16279 (org-eval-in-calendar '(setq cursor-type nil) t)
16280 (unwind-protect
16281 (progn
16282 (calendar-forward-day (- (time-to-days org-def)
16283 (calendar-absolute-from-gregorian
16284 (calendar-current-date))))
16285 (org-eval-in-calendar nil t)
16286 (let* ((old-map (current-local-map))
16287 (map (copy-keymap calendar-mode-map))
16288 (minibuffer-local-map
16289 (copy-keymap org-read-date-minibuffer-local-map)))
16290 (org-defkey map (kbd "RET") 'org-calendar-select)
16291 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16292 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16293 (unwind-protect
16294 (progn
16295 (use-local-map map)
16296 (setq org-read-date-inactive inactive)
16297 (add-hook 'post-command-hook 'org-read-date-display)
16298 (setq org-ans0
16299 (read-string prompt
16300 default-input
16301 'org-read-date-history
16302 nil))
16303 ;; org-ans0: from prompt
16304 ;; org-ans1: from mouse click
16305 ;; org-ans2: from calendar motion
16306 (setq ans
16307 (concat org-ans0 " " (or org-ans1 org-ans2))))
16308 (remove-hook 'post-command-hook 'org-read-date-display)
16309 (use-local-map old-map)
16310 (when org-read-date-overlay
16311 (delete-overlay org-read-date-overlay)
16312 (setq org-read-date-overlay nil)))))
16313 (bury-buffer "*Calendar*")
16314 (when cal-frame
16315 (delete-frame cal-frame)
16316 (select-frame-set-input-focus cur-frame))))))
16318 (t ; Naked prompt only
16319 (unwind-protect
16320 (setq ans (read-string prompt default-input
16321 'org-read-date-history timestr))
16322 (when org-read-date-overlay
16323 (delete-overlay org-read-date-overlay)
16324 (setq org-read-date-overlay nil))))))
16326 (setq final (org-read-date-analyze ans org-def org-defdecode))
16328 (when org-read-date-analyze-forced-year
16329 (message "Year was forced into %s"
16330 (if org-read-date-force-compatible-dates
16331 "compatible range (1970-2037)"
16332 "range representable on this machine"))
16333 (ding))
16335 ;; One round trip to get rid of 34th of August and stuff like that....
16336 (setq final (decode-time (apply 'encode-time final)))
16338 (setq org-read-date-final-answer ans)
16340 (if to-time
16341 (apply 'encode-time final)
16342 (if (and (boundp 'org-time-was-given) org-time-was-given)
16343 (format "%04d-%02d-%02d %02d:%02d"
16344 (nth 5 final) (nth 4 final) (nth 3 final)
16345 (nth 2 final) (nth 1 final))
16346 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16348 (defun org-read-date-display ()
16349 "Display the current date prompt interpretation in the minibuffer."
16350 (when org-read-date-display-live
16351 (when org-read-date-overlay
16352 (delete-overlay org-read-date-overlay))
16353 (when (minibufferp (current-buffer))
16354 (save-excursion
16355 (end-of-line 1)
16356 (while (not (equal (buffer-substring
16357 (max (point-min) (- (point) 4)) (point))
16358 " "))
16359 (insert " ")))
16360 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16361 " " (or org-ans1 org-ans2)))
16362 (org-end-time-was-given nil)
16363 (f (org-read-date-analyze ans org-def org-defdecode))
16364 (fmts (if org-dcst
16365 org-time-stamp-custom-formats
16366 org-time-stamp-formats))
16367 (fmt (if (or org-with-time
16368 (and (boundp 'org-time-was-given) org-time-was-given))
16369 (cdr fmts)
16370 (car fmts)))
16371 (txt (format-time-string fmt (apply 'encode-time f)))
16372 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16373 (txt (concat "=> " txt)))
16374 (when (and org-end-time-was-given
16375 (string-match org-plain-time-of-day-regexp txt))
16376 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16377 org-end-time-was-given
16378 (substring txt (match-end 0)))))
16379 (when org-read-date-analyze-futurep
16380 (setq txt (concat txt " (=>F)")))
16381 (setq org-read-date-overlay
16382 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16383 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16385 (defun org-read-date-analyze (ans def defdecode)
16386 "Analyze the combined answer of the date prompt."
16387 ;; FIXME: cleanup and comment
16388 ;; Pass `current-time' result to `decode-time' (instead of calling
16389 ;; without arguments) so that only `current-time' has to be
16390 ;; overridden in tests.
16391 (let ((org-def def)
16392 (org-defdecode defdecode)
16393 (nowdecode (decode-time (current-time)))
16394 delta deltan deltaw deltadef year month day
16395 hour minute second wday pm h2 m2 tl wday1
16396 iso-year iso-weekday iso-week iso-date futurep kill-year)
16397 (setq org-read-date-analyze-futurep nil
16398 org-read-date-analyze-forced-year nil)
16399 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16400 (setq ans "+0"))
16402 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16403 (setq ans (replace-match "" t t ans)
16404 deltan (car delta)
16405 deltaw (nth 1 delta)
16406 deltadef (nth 2 delta)))
16408 ;; Check if there is an iso week date in there. If yes, store the
16409 ;; info and postpone interpreting it until the rest of the parsing
16410 ;; is done.
16411 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16412 (setq iso-year (when (match-end 1)
16413 (org-small-year-to-year
16414 (string-to-number (match-string 1 ans))))
16415 iso-weekday (when (match-end 3)
16416 (string-to-number (match-string 3 ans)))
16417 iso-week (string-to-number (match-string 2 ans)))
16418 (setq ans (replace-match "" t t ans)))
16420 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16421 (when (string-match
16422 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16423 (setq year (if (match-end 2)
16424 (string-to-number (match-string 2 ans))
16425 (progn (setq kill-year t)
16426 (string-to-number (format-time-string "%Y"))))
16427 month (string-to-number (match-string 3 ans))
16428 day (string-to-number (match-string 4 ans)))
16429 (setq year (org-small-year-to-year year))
16430 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16431 t nil ans)))
16433 ;; Help matching dotted european dates
16434 (when (string-match
16435 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16436 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16437 (setq kill-year t)
16438 (string-to-number (format-time-string "%Y")))
16439 day (string-to-number (match-string 1 ans))
16440 month (string-to-number (match-string 2 ans))
16441 ans (replace-match (format "%04d-%02d-%02d" year month day)
16442 t nil ans)))
16444 ;; Help matching american dates, like 5/30 or 5/30/7
16445 (when (string-match
16446 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16447 (setq year (if (match-end 4)
16448 (string-to-number (match-string 4 ans))
16449 (progn (setq kill-year t)
16450 (string-to-number (format-time-string "%Y"))))
16451 month (string-to-number (match-string 1 ans))
16452 day (string-to-number (match-string 2 ans)))
16453 (setq year (org-small-year-to-year year))
16454 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16455 t nil ans)))
16456 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16457 ;; If there is a time with am/pm, and *no* time without it, we convert
16458 ;; so that matching will be successful.
16459 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16460 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16461 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16462 (setq hour (string-to-number (match-string 1 ans))
16463 minute (if (match-end 3)
16464 (string-to-number (match-string 3 ans))
16466 pm (equal ?p
16467 (string-to-char (downcase (match-string 4 ans)))))
16468 (if (and (= hour 12) (not pm))
16469 (setq hour 0)
16470 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16471 (setq ans (replace-match (format "%02d:%02d" hour minute)
16472 t t ans))))
16474 ;; Check if a time range is given as a duration
16475 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16476 (setq hour (string-to-number (match-string 1 ans))
16477 h2 (+ hour (string-to-number (match-string 3 ans)))
16478 minute (string-to-number (match-string 2 ans))
16479 m2 (+ minute (if (match-end 5) (string-to-number
16480 (match-string 5 ans))0)))
16481 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16482 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16483 t t ans)))
16485 ;; Check if there is a time range
16486 (when (boundp 'org-end-time-was-given)
16487 (setq org-time-was-given nil)
16488 (when (and (string-match org-plain-time-of-day-regexp ans)
16489 (match-end 8))
16490 (setq org-end-time-was-given (match-string 8 ans))
16491 (setq ans (concat (substring ans 0 (match-beginning 7))
16492 (substring ans (match-end 7))))))
16494 (setq tl (parse-time-string ans)
16495 day (or (nth 3 tl) (nth 3 org-defdecode))
16496 month
16497 (cond ((nth 4 tl))
16498 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16499 ;; Day was specified. Make sure DAY+MONTH
16500 ;; combination happens in the future.
16501 ((nth 3 tl)
16502 (setq futurep t)
16503 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
16504 (nth 4 nowdecode)))
16505 (t (nth 4 org-defdecode)))
16506 year
16507 (cond ((and (not kill-year) (nth 5 tl)))
16508 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
16509 ;; Month was guessed in the future and is at least
16510 ;; equal to NOWDECODE's. Fix year accordingly.
16511 (futurep
16512 (if (or (> month (nth 4 nowdecode))
16513 (>= day (nth 3 nowdecode)))
16514 (nth 5 nowdecode)
16515 (1+ (nth 5 nowdecode))))
16516 ;; Month was specified. Make sure MONTH+YEAR
16517 ;; combination happens in the future.
16518 ((nth 4 tl)
16519 (setq futurep t)
16520 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
16521 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
16522 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
16523 (t (nth 5 nowdecode))))
16524 (t (nth 5 org-defdecode)))
16525 hour (or (nth 2 tl) (nth 2 org-defdecode))
16526 minute (or (nth 1 tl) (nth 1 org-defdecode))
16527 second (or (nth 0 tl) 0)
16528 wday (nth 6 tl))
16530 (when (and (eq org-read-date-prefer-future 'time)
16531 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16532 (equal day (nth 3 nowdecode))
16533 (equal month (nth 4 nowdecode))
16534 (equal year (nth 5 nowdecode))
16535 (nth 2 tl)
16536 (or (< (nth 2 tl) (nth 2 nowdecode))
16537 (and (= (nth 2 tl) (nth 2 nowdecode))
16538 (nth 1 tl)
16539 (< (nth 1 tl) (nth 1 nowdecode)))))
16540 (setq day (1+ day)
16541 futurep t))
16543 ;; Special date definitions below
16544 (cond
16545 (iso-week
16546 ;; There was an iso week
16547 (require 'cal-iso)
16548 (setq futurep nil)
16549 (setq year (or iso-year year)
16550 day (or iso-weekday wday 1)
16551 wday nil ; to make sure that the trigger below does not match
16552 iso-date (calendar-gregorian-from-absolute
16553 (calendar-iso-to-absolute
16554 (list iso-week day year))))
16555 ; FIXME: Should we also push ISO weeks into the future?
16556 ; (when (and org-read-date-prefer-future
16557 ; (not iso-year)
16558 ; (< (calendar-absolute-from-gregorian iso-date)
16559 ; (time-to-days (current-time))))
16560 ; (setq year (1+ year)
16561 ; iso-date (calendar-gregorian-from-absolute
16562 ; (calendar-iso-to-absolute
16563 ; (list iso-week day year)))))
16564 (setq month (car iso-date)
16565 year (nth 2 iso-date)
16566 day (nth 1 iso-date)))
16567 (deltan
16568 (setq futurep nil)
16569 (unless deltadef
16570 ;; Pass `current-time' result to `decode-time' (instead of
16571 ;; calling without arguments) so that only `current-time' has
16572 ;; to be overridden in tests.
16573 (let ((now (decode-time (current-time))))
16574 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16575 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16576 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16577 ((equal deltaw "m") (setq month (+ month deltan)))
16578 ((equal deltaw "y") (setq year (+ year deltan)))))
16579 ((and wday (not (nth 3 tl)))
16580 ;; Weekday was given, but no day, so pick that day in the week
16581 ;; on or after the derived date.
16582 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16583 (unless (equal wday wday1)
16584 (setq day (+ day (% (- wday wday1 -7) 7))))))
16585 (when (and (boundp 'org-time-was-given)
16586 (nth 2 tl))
16587 (setq org-time-was-given t))
16588 (when (< year 100) (setq year (+ 2000 year)))
16589 ;; Check of the date is representable
16590 (if org-read-date-force-compatible-dates
16591 (progn
16592 (when (< year 1970)
16593 (setq year 1970 org-read-date-analyze-forced-year t))
16594 (when (> year 2037)
16595 (setq year 2037 org-read-date-analyze-forced-year t)))
16596 (condition-case nil
16597 (ignore (encode-time second minute hour day month year))
16598 (error
16599 (setq year (nth 5 org-defdecode))
16600 (setq org-read-date-analyze-forced-year t))))
16601 (setq org-read-date-analyze-futurep futurep)
16602 (list second minute hour day month year)))
16604 (defvar parse-time-weekdays)
16605 (defun org-read-date-get-relative (s today default)
16606 "Check string S for special relative date string.
16607 TODAY and DEFAULT are internal times, for today and for a default.
16608 Return shift list (N what def-flag)
16609 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16610 N is the number of WHATs to shift.
16611 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16612 the DEFAULT date rather than TODAY."
16613 (require 'parse-time)
16614 (when (and
16615 (string-match
16616 (concat
16617 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16618 "\\([0-9]+\\)?"
16619 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16620 "\\([ \t]\\|$\\)") s)
16621 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16622 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16623 (string-to-char (substring (match-string 1 s) -1))
16624 ?+))
16625 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16626 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16627 (what (if (match-end 3) (match-string 3 s) "d"))
16628 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16629 (date (if rel default today))
16630 (wday (nth 6 (decode-time date)))
16631 delta)
16632 (if wday1
16633 (progn
16634 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16635 (when (= delta 0) (setq delta 7))
16636 (when (= dir ?-)
16637 (setq delta (- delta 7))
16638 (when (= delta 0) (setq delta -7)))
16639 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16640 (list delta "d" rel))
16641 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16643 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16644 "Turn a user-specified date into the internal representation.
16645 The internal representation needed by the calendar is (month day year).
16646 This is a wrapper to handle the brain-dead convention in calendar that
16647 user function argument order change dependent on argument order."
16648 (pcase calendar-date-style
16649 (`american (list arg1 arg2 arg3))
16650 (`european (list arg2 arg1 arg3))
16651 (`iso (list arg2 arg3 arg1))))
16653 (defun org-eval-in-calendar (form &optional keepdate)
16654 "Eval FORM in the calendar window and return to current window.
16655 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
16656 (let ((sf (selected-frame))
16657 (sw (selected-window)))
16658 (select-window (get-buffer-window "*Calendar*" t))
16659 (eval form)
16660 (when (and (not keepdate) (calendar-cursor-to-date))
16661 (let* ((date (calendar-cursor-to-date))
16662 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16663 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16664 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16665 (select-window sw)
16666 (select-frame-set-input-focus sf)))
16668 (defun org-calendar-select ()
16669 "Return to `org-read-date' with the date currently selected.
16670 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16671 (interactive)
16672 (when (calendar-cursor-to-date)
16673 (let* ((date (calendar-cursor-to-date))
16674 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16675 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16676 (when (active-minibuffer-window) (exit-minibuffer))))
16678 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16679 "Insert a date stamp for the date given by the internal TIME.
16680 See `format-time-string' for the format of TIME.
16681 WITH-HM means use the stamp format that includes the time of the day.
16682 INACTIVE means use square brackets instead of angular ones, so that the
16683 stamp will not contribute to the agenda.
16684 PRE and POST are optional strings to be inserted before and after the
16685 stamp.
16686 The command returns the inserted time stamp."
16687 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16688 stamp)
16689 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16690 (insert-before-markers (or pre ""))
16691 (when (listp extra)
16692 (setq extra (car extra))
16693 (if (and (stringp extra)
16694 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16695 (setq extra (format "-%02d:%02d"
16696 (string-to-number (match-string 1 extra))
16697 (string-to-number (match-string 2 extra))))
16698 (setq extra nil)))
16699 (when extra
16700 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16701 (insert-before-markers (setq stamp (format-time-string fmt time)))
16702 (insert-before-markers (or post ""))
16703 (setq org-last-inserted-timestamp stamp)))
16705 (defun org-toggle-time-stamp-overlays ()
16706 "Toggle the use of custom time stamp formats."
16707 (interactive)
16708 (setq org-display-custom-times (not org-display-custom-times))
16709 (unless org-display-custom-times
16710 (let ((p (point-min)) (bmp (buffer-modified-p)))
16711 (while (setq p (next-single-property-change p 'display))
16712 (when (and (get-text-property p 'display)
16713 (eq (get-text-property p 'face) 'org-date))
16714 (remove-text-properties
16715 p (setq p (next-single-property-change p 'display))
16716 '(display t))))
16717 (set-buffer-modified-p bmp)))
16718 (org-restart-font-lock)
16719 (setq org-table-may-need-update t)
16720 (if org-display-custom-times
16721 (message "Time stamps are overlaid with custom format")
16722 (message "Time stamp overlays removed")))
16724 (defun org-display-custom-time (beg end)
16725 "Overlay modified time stamp format over timestamp between BEG and END."
16726 (let* ((ts (buffer-substring beg end))
16727 t1 with-hm tf time str (off 0))
16728 (save-match-data
16729 (setq t1 (org-parse-time-string ts t))
16730 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16731 (setq off (- (match-end 0) (match-beginning 0)))))
16732 (setq end (- end off))
16733 (setq with-hm (and (nth 1 t1) (nth 2 t1))
16734 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16735 time (org-fix-decoded-time t1)
16736 str (org-add-props
16737 (format-time-string
16738 (substring tf 1 -1) (apply 'encode-time time))
16739 nil 'mouse-face 'highlight))
16740 (put-text-property beg end 'display str)))
16742 (defun org-fix-decoded-time (time)
16743 "Set 0 instead of nil for the first 6 elements of time.
16744 Don't touch the rest."
16745 (let ((n 0))
16746 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16748 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16749 "Difference between TIMESTAMP-STRING and now in days.
16750 If SECONDS is non-nil, return the difference in seconds."
16751 (let ((fdiff (if seconds #'float-time #'time-to-days)))
16752 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16753 (funcall fdiff (current-time)))))
16755 (defun org-deadline-close-p (timestamp-string &optional ndays)
16756 "Is the time in TIMESTAMP-STRING close to the current date?"
16757 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16758 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
16759 (not (org-entry-is-done-p))))
16761 (defun org-get-wdays (ts &optional delay zero-delay)
16762 "Get the deadline lead time appropriate for timestring TS.
16763 When DELAY is non-nil, get the delay time for scheduled items
16764 instead of the deadline lead time. When ZERO-DELAY is non-nil
16765 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16766 don't try to find the delay cookie in the scheduled timestamp."
16767 (let ((tv (if delay org-scheduled-delay-days
16768 org-deadline-warning-days)))
16769 (cond
16770 ((or (and delay (< tv 0))
16771 (and delay zero-delay (<= tv 0))
16772 (and (not delay) (<= tv 0)))
16773 ;; Enforce this value no matter what
16774 (- tv))
16775 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16776 ;; lead time is specified.
16777 (floor (* (string-to-number (match-string 1 ts))
16778 (cdr (assoc (match-string 2 ts)
16779 '(("d" . 1) ("w" . 7)
16780 ("m" . 30.4) ("y" . 365.25)
16781 ("h" . 0.041667)))))))
16782 ;; go for the default.
16783 (t tv))))
16785 (defun org-calendar-select-mouse (ev)
16786 "Return to `org-read-date' with the date currently selected.
16787 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16788 (interactive "e")
16789 (mouse-set-point ev)
16790 (when (calendar-cursor-to-date)
16791 (let* ((date (calendar-cursor-to-date))
16792 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16793 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16794 (when (active-minibuffer-window) (exit-minibuffer))))
16796 (defun org-check-deadlines (ndays)
16797 "Check if there are any deadlines due or past due.
16798 A deadline is considered due if it happens within `org-deadline-warning-days'
16799 days from today's date. If the deadline appears in an entry marked DONE,
16800 it is not shown. A numeric prefix argument NDAYS can be used to test that
16801 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
16802 are shown."
16803 (interactive "P")
16804 (let* ((org-warn-days
16805 (cond
16806 ((equal ndays '(4)) 100000)
16807 (ndays (prefix-numeric-value ndays))
16808 (t (abs org-deadline-warning-days))))
16809 (case-fold-search nil)
16810 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16811 (callback
16812 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
16813 (message "%d deadlines past-due or due within %d days"
16814 (org-occur regexp nil callback)
16815 org-warn-days)))
16817 (defsubst org-re-timestamp (type)
16818 "Return a regexp for timestamp TYPE.
16819 Allowed values for TYPE are:
16821 all: all timestamps
16822 active: only active timestamps (<...>)
16823 inactive: only inactive timestamps ([...])
16824 scheduled: only scheduled timestamps
16825 deadline: only deadline timestamps
16826 closed: only closed time-stamps
16828 When TYPE is nil, fall back on returning a regexp that matches
16829 both scheduled and deadline timestamps."
16830 (cl-case type
16831 (all org-ts-regexp-both)
16832 (active org-ts-regexp)
16833 (inactive org-ts-regexp-inactive)
16834 (scheduled org-scheduled-time-regexp)
16835 (deadline org-deadline-time-regexp)
16836 (closed org-closed-time-regexp)
16837 (otherwise
16838 (concat "\\<"
16839 (regexp-opt (list org-deadline-string org-scheduled-string))
16840 " *<\\([^>]+\\)>"))))
16842 (defun org-check-before-date (d)
16843 "Check if there are deadlines or scheduled entries before date D."
16844 (interactive (list (org-read-date)))
16845 (let* ((case-fold-search nil)
16846 (regexp (org-re-timestamp org-ts-type))
16847 (ts-type org-ts-type)
16848 (callback
16849 (lambda ()
16850 (let ((match (match-string 1)))
16851 (and (if (memq ts-type '(active inactive all))
16852 (eq (org-element-type (save-excursion
16853 (backward-char)
16854 (org-element-context)))
16855 'timestamp)
16856 (org-at-planning-p))
16857 (time-less-p
16858 (org-time-string-to-time match)
16859 (org-time-string-to-time d)))))))
16860 (message "%d entries before %s"
16861 (org-occur regexp nil callback)
16862 d)))
16864 (defun org-check-after-date (d)
16865 "Check if there are deadlines or scheduled entries after date D."
16866 (interactive (list (org-read-date)))
16867 (let* ((case-fold-search nil)
16868 (regexp (org-re-timestamp org-ts-type))
16869 (ts-type org-ts-type)
16870 (callback
16871 (lambda ()
16872 (let ((match (match-string 1)))
16873 (and (if (memq ts-type '(active inactive all))
16874 (eq (org-element-type (save-excursion
16875 (backward-char)
16876 (org-element-context)))
16877 'timestamp)
16878 (org-at-planning-p))
16879 (not (time-less-p
16880 (org-time-string-to-time match)
16881 (org-time-string-to-time d))))))))
16882 (message "%d entries after %s"
16883 (org-occur regexp nil callback)
16884 d)))
16886 (defun org-check-dates-range (start-date end-date)
16887 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16888 (interactive (list (org-read-date nil nil nil "Range starts")
16889 (org-read-date nil nil nil "Range end")))
16890 (let ((case-fold-search nil)
16891 (regexp (org-re-timestamp org-ts-type))
16892 (callback
16893 (let ((type org-ts-type))
16894 (lambda ()
16895 (let ((match (match-string 1)))
16896 (and
16897 (if (memq type '(active inactive all))
16898 (eq (org-element-type (save-excursion
16899 (backward-char)
16900 (org-element-context)))
16901 'timestamp)
16902 (org-at-planning-p))
16903 (not (time-less-p
16904 (org-time-string-to-time match)
16905 (org-time-string-to-time start-date)))
16906 (time-less-p
16907 (org-time-string-to-time match)
16908 (org-time-string-to-time end-date))))))))
16909 (message "%d entries between %s and %s"
16910 (org-occur regexp nil callback) start-date end-date)))
16912 (defun org-evaluate-time-range (&optional to-buffer)
16913 "Evaluate a time range by computing the difference between start and end.
16914 Normally the result is just printed in the echo area, but with prefix arg
16915 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16916 If the time range is actually in a table, the result is inserted into the
16917 next column.
16918 For time difference computation, a year is assumed to be exactly 365
16919 days in order to avoid rounding problems."
16920 (interactive "P")
16922 (org-clock-update-time-maybe)
16923 (save-excursion
16924 (unless (org-at-date-range-p t)
16925 (goto-char (point-at-bol))
16926 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16927 (unless (org-at-date-range-p t)
16928 (user-error "Not at a time-stamp range, and none found in current line")))
16929 (let* ((ts1 (match-string 1))
16930 (ts2 (match-string 2))
16931 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16932 (match-end (match-end 0))
16933 (time1 (org-time-string-to-time ts1))
16934 (time2 (org-time-string-to-time ts2))
16935 (t1 (float-time time1))
16936 (t2 (float-time time2))
16937 (diff (abs (- t2 t1)))
16938 (negative (< (- t2 t1) 0))
16939 ;; (ys (floor (* 365 24 60 60)))
16940 (ds (* 24 60 60))
16941 (hs (* 60 60))
16942 (fy "%dy %dd %02d:%02d")
16943 (fy1 "%dy %dd")
16944 (fd "%dd %02d:%02d")
16945 (fd1 "%dd")
16946 (fh "%02d:%02d")
16947 y d h m align)
16948 (if havetime
16949 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16951 d (floor (/ diff ds)) diff (mod diff ds)
16952 h (floor (/ diff hs)) diff (mod diff hs)
16953 m (floor (/ diff 60)))
16954 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16956 d (floor (+ (/ diff ds) 0.5))
16957 h 0 m 0))
16958 (if (not to-buffer)
16959 (message "%s" (org-make-tdiff-string y d h m))
16960 (if (org-at-table-p)
16961 (progn
16962 (goto-char match-end)
16963 (setq align t)
16964 (and (looking-at " *|") (goto-char (match-end 0))))
16965 (goto-char match-end))
16966 (when (looking-at
16967 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16968 (replace-match ""))
16969 (when negative (insert " -"))
16970 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16971 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16972 (insert " " (format fh h m))))
16973 (when align (org-table-align))
16974 (message "Time difference inserted")))))
16976 (defun org-make-tdiff-string (y d h m)
16977 (let ((fmt "")
16978 (l nil))
16979 (when (> y 0)
16980 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
16981 (push y l))
16982 (when (> d 0)
16983 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
16984 (push d l))
16985 (when (> h 0)
16986 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
16987 (push h l))
16988 (when (> m 0)
16989 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
16990 (push m l))
16991 (apply 'format fmt (nreverse l))))
16993 (defun org-time-string-to-time (s)
16994 "Convert timestamp string S into internal time."
16995 (apply #'encode-time (org-parse-time-string s)))
16997 (defun org-time-string-to-seconds (s)
16998 "Convert a timestamp string S into a number of seconds."
16999 (float-time (org-time-string-to-time s)))
17001 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17003 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17004 "Convert time stamp S to an absolute day number.
17006 If DAYNR in non-nil, and there is a specifier for a cyclic time
17007 stamp, get the closest date to DAYNR. If PREFER is
17008 `past' (respectively `future') return a date past (respectively
17009 after) or equal to DAYNR.
17011 POS is the location of time stamp S, as a buffer position in
17012 BUFFER.
17014 Diary sexp timestamps are matched against DAYNR, when non-nil.
17015 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17016 signaled."
17017 (cond
17018 ((string-match "\\`%%\\((.*)\\)" s)
17019 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17020 ;; only able to match individual dates. If it fails, raise an
17021 ;; error.
17022 (if (and daynr
17023 (org-diary-sexp-entry
17024 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17025 daynr
17026 (signal 'org-diary-sexp-no-match (list s))))
17027 (daynr (org-closest-date s daynr prefer))
17028 (t (time-to-days
17029 (condition-case errdata
17030 (apply #'encode-time (org-parse-time-string s))
17031 (error (error "Bad timestamp `%s'%s\nError was: %s"
17033 (if (not (and buffer pos)) ""
17034 (format-message " at %d in buffer `%s'" pos buffer))
17035 (cdr errdata))))))))
17037 (defun org-days-to-iso-week (days)
17038 "Return the iso week number."
17039 (require 'cal-iso)
17040 (car (calendar-iso-from-absolute days)))
17042 (defun org-small-year-to-year (year)
17043 "Convert 2-digit years into 4-digit years.
17044 YEAR is expanded into one of the 30 next years, if possible, or
17045 into a past one. Any year larger than 99 is returned unchanged."
17046 (if (>= year 100) year
17047 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17048 (century (/ current 100))
17049 (offset (- year (% current 100))))
17050 (cond ((> offset 30) (+ (* (1- century) 100) year))
17051 ((> offset -70) (+ (* century 100) year))
17052 (t (+ (* (1+ century) 100) year))))))
17054 (defun org-time-from-absolute (d)
17055 "Return the time corresponding to date D.
17056 D may be an absolute day number, or a calendar-type list (month day year)."
17057 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17058 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17060 (defvar org-agenda-current-date)
17061 (defun org-calendar-holiday ()
17062 "List of holidays, for Diary display in Org mode."
17063 (require 'holidays)
17064 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17065 (and hl (mapconcat #'identity hl "; "))))
17067 (defun org-diary-sexp-entry (sexp entry d)
17068 "Process a SEXP diary ENTRY for date D."
17069 (require 'diary-lib)
17070 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17071 ;; dynamically.
17072 (let* ((sexp `(let ((entry ,entry)
17073 (date ',d))
17074 ,(car (read-from-string sexp))))
17075 (result (if calendar-debug-sexp (eval sexp)
17076 (condition-case nil
17077 (eval sexp)
17078 (error
17079 (beep)
17080 (message "Bad sexp at line %d in %s: %s"
17081 (org-current-line)
17082 (buffer-file-name) sexp)
17083 (sleep-for 2))))))
17084 (cond ((stringp result) (split-string result "; "))
17085 ((and (consp result)
17086 (not (consp (cdr result)))
17087 (stringp (cdr result))) (cdr result))
17088 ((and (consp result)
17089 (stringp (car result))) result)
17090 (result entry))))
17092 (defun org-diary-to-ical-string (frombuf)
17093 "Get iCalendar entries from diary entries in buffer FROMBUF.
17094 This uses the icalendar.el library."
17095 (let* ((tmpdir temporary-file-directory)
17096 (tmpfile (make-temp-name
17097 (expand-file-name "orgics" tmpdir)))
17098 buf rtn b e)
17099 (with-current-buffer frombuf
17100 (icalendar-export-region (point-min) (point-max) tmpfile)
17101 (setq buf (find-buffer-visiting tmpfile))
17102 (set-buffer buf)
17103 (goto-char (point-min))
17104 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17105 (setq b (match-beginning 0)))
17106 (goto-char (point-max))
17107 (when (re-search-backward "^END:VEVENT" nil t)
17108 (setq e (match-end 0)))
17109 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17110 (kill-buffer buf)
17111 (delete-file tmpfile)
17112 rtn))
17114 (defun org-closest-date (start current prefer)
17115 "Return closest date to CURRENT starting from START.
17117 CURRENT and START are both time stamps.
17119 When PREFER is `past', return a date that is either CURRENT or
17120 past. When PREFER is `future', return a date that is either
17121 CURRENT or future.
17123 Only time stamps with a repeater are modified. Any other time
17124 stamp stay unchanged. In any case, return value is an absolute
17125 day number."
17126 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17127 ;; No repeater. Do not shift time stamp.
17128 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17129 (let ((value (string-to-number (match-string 1 start)))
17130 (type (match-string 2 start)))
17131 (if (= 0 value)
17132 ;; Repeater with a 0-value is considered as void.
17133 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17134 (let* ((base (org-date-to-gregorian start))
17135 (target (org-date-to-gregorian current))
17136 (sday (calendar-absolute-from-gregorian base))
17137 (cday (calendar-absolute-from-gregorian target))
17138 n1 n2)
17139 ;; If START is already past CURRENT, just return START.
17140 (if (<= cday sday) sday
17141 ;; Compute closest date before (N1) and closest date past
17142 ;; (N2) CURRENT.
17143 (pcase type
17144 ("h"
17145 (let ((missing-hours
17146 (mod (+ (- (* 24 (- cday sday))
17147 (nth 2 (org-parse-time-string start)))
17148 org-extend-today-until)
17149 value)))
17150 (setf n1 (if (= missing-hours 0) cday
17151 (- cday (1+ (/ missing-hours 24)))))
17152 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17153 ((or "d" "w")
17154 (let ((value (if (equal type "w") (* 7 value) value)))
17155 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17156 (setf n2 (+ n1 value))))
17157 ("m"
17158 (let* ((add-months
17159 (lambda (d n)
17160 ;; Add N months to gregorian date D, i.e.,
17161 ;; a list (MONTH DAY YEAR). Return a valid
17162 ;; gregorian date.
17163 (let ((m (+ (nth 0 d) n)))
17164 (list (mod m 12)
17165 (nth 1 d)
17166 (+ (/ m 12) (nth 2 d))))))
17167 (months ; Complete months to TARGET.
17168 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17169 (- (nth 0 target) (nth 0 base))
17170 ;; If START's day is greater than
17171 ;; TARGET's, remove incomplete month.
17172 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17173 value)
17174 value))
17175 (before (funcall add-months base months)))
17176 (setf n1 (calendar-absolute-from-gregorian before))
17177 (setf n2
17178 (calendar-absolute-from-gregorian
17179 (funcall add-months before value)))))
17181 (let* ((d (nth 1 base))
17182 (m (nth 0 base))
17183 (y (nth 2 base))
17184 (years ; Complete years to TARGET.
17185 (* (/ (- (nth 2 target)
17187 ;; If START's month and day are
17188 ;; greater than TARGET's, remove
17189 ;; incomplete year.
17190 (if (or (> (nth 0 target) m)
17191 (and (= (nth 0 target) m)
17192 (> (nth 1 target) d)))
17195 value)
17196 value))
17197 (before (list m d (+ y years))))
17198 (setf n1 (calendar-absolute-from-gregorian before))
17199 (setf n2 (calendar-absolute-from-gregorian
17200 (list m d (+ (nth 2 before) value)))))))
17201 ;; Handle PREFER parameter, if any.
17202 (cond
17203 ((eq prefer 'past) (if (= cday n2) n2 n1))
17204 ((eq prefer 'future) (if (= cday n1) n1 n2))
17205 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17207 (defun org-date-to-gregorian (d)
17208 "Turn any specification of date D into a Gregorian date for the calendar."
17209 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17210 ((and (listp d) (= (length d) 3)) d)
17211 ((stringp d)
17212 (let ((d (org-parse-time-string d)))
17213 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17214 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17216 (defun org-timestamp-up (&optional arg)
17217 "Increase the date item at the cursor by one.
17218 If the cursor is on the year, change the year. If it is on the month,
17219 the day or the time, change that. If the cursor is on the enclosing
17220 bracket, change the timestamp type.
17221 With prefix ARG, change by that many units."
17222 (interactive "p")
17223 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17225 (defun org-timestamp-down (&optional arg)
17226 "Decrease the date item at the cursor by one.
17227 If the cursor is on the year, change the year. If it is on the month,
17228 the day or the time, change that. If the cursor is on the enclosing
17229 bracket, change the timestamp type.
17230 With prefix ARG, change by that many units."
17231 (interactive "p")
17232 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17234 (defun org-timestamp-up-day (&optional arg)
17235 "Increase the date in the time stamp by one day.
17236 With prefix ARG, change that many days."
17237 (interactive "p")
17238 (if (and (not (org-at-timestamp-p 'lax))
17239 (org-at-heading-p))
17240 (org-todo 'up)
17241 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17243 (defun org-timestamp-down-day (&optional arg)
17244 "Decrease the date in the time stamp by one day.
17245 With prefix ARG, change that many days."
17246 (interactive "p")
17247 (if (and (not (org-at-timestamp-p 'lax))
17248 (org-at-heading-p))
17249 (org-todo 'down)
17250 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17252 (defun org-at-timestamp-p (&optional extended)
17253 "Non-nil if point is inside a timestamp.
17255 By default, the function only consider syntactically valid active
17256 timestamps. However, the caller may have a broader definition
17257 for timestamps. As a consequence, optional argument EXTENDED can
17258 be set to the following values
17260 `inactive'
17262 Include also syntactically valid inactive timestamps.
17264 `agenda'
17266 Include timestamps allowed in Agenda, i.e., those in
17267 properties drawers, planning lines and clock lines.
17269 `lax'
17271 Ignore context. The function matches any part of the
17272 document looking like a timestamp. This includes comments,
17273 example blocks...
17275 For backward-compatibility with Org 9.0, every other non-nil
17276 value is equivalent to `inactive'.
17278 When at a timestamp, return the position of the point as a symbol
17279 among `bracket', `after', `year', `month', `hour', `minute',
17280 `day' or a number of character from the last know part of the
17281 time stamp.
17283 When matching, the match groups are the following:
17284 group 1: year
17285 group 2: month
17286 group 3: day number
17287 group 4: day name
17288 group 5: hours, if any
17289 group 6: minutes, if any"
17290 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17291 (pos (point))
17292 (match?
17293 (let ((boundaries (org-in-regexp regexp)))
17294 (save-match-data
17295 (cond ((null boundaries) nil)
17296 ((eq extended 'lax) t)
17298 (or (and (eq extended 'agenda)
17299 (or (org-at-planning-p)
17300 (org-at-property-p)
17301 (and (bound-and-true-p
17302 org-agenda-include-inactive-timestamps)
17303 (org-at-clock-log-p))))
17304 (eq 'timestamp
17305 (save-excursion
17306 (when (= pos (cdr boundaries)) (forward-char -1))
17307 (org-element-type (org-element-context)))))))))))
17308 (cond
17309 ((not match?) nil)
17310 ((= pos (match-beginning 0)) 'bracket)
17311 ;; Distinguish location right before the closing bracket from
17312 ;; right after it.
17313 ((= pos (1- (match-end 0))) 'bracket)
17314 ((= pos (match-end 0)) 'after)
17315 ((org-pos-in-match-range pos 2) 'year)
17316 ((org-pos-in-match-range pos 3) 'month)
17317 ((org-pos-in-match-range pos 7) 'hour)
17318 ((org-pos-in-match-range pos 8) 'minute)
17319 ((or (org-pos-in-match-range pos 4)
17320 (org-pos-in-match-range pos 5)) 'day)
17321 ((and (> pos (or (match-end 8) (match-end 5)))
17322 (< pos (match-end 0)))
17323 (- pos (or (match-end 8) (match-end 5))))
17324 (t 'day))))
17326 (defun org-toggle-timestamp-type ()
17327 "Toggle the type (<active> or [inactive]) of a time stamp."
17328 (interactive)
17329 (when (org-at-timestamp-p 'lax)
17330 (let ((beg (match-beginning 0)) (end (match-end 0))
17331 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17332 (save-excursion
17333 (goto-char beg)
17334 (while (re-search-forward "[][<>]" end t)
17335 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17336 t t)))
17337 (message "Timestamp is now %sactive"
17338 (if (equal (char-after beg) ?<) "" "in")))))
17340 (defun org-at-clock-log-p ()
17341 "Non-nil if point is on a clock log line."
17342 (and (org-match-line org-clock-line-re)
17343 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17345 (defvar org-clock-history) ; defined in org-clock.el
17346 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17347 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17348 "Change the date in the time stamp at point.
17349 The date will be changed by N times WHAT. WHAT can be `day', `month',
17350 `year', `minute', `second'. If WHAT is not given, the cursor position
17351 in the timestamp determines what will be changed.
17352 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17353 (let ((origin (point))
17354 (timestamp? (org-at-timestamp-p 'lax))
17355 origin-cat
17356 with-hm inactive
17357 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17358 extra rem
17359 ts time time0 fixnext clrgx)
17360 (unless timestamp? (user-error "Not at a timestamp"))
17361 (if (and (not what) (eq timestamp? 'bracket))
17362 (org-toggle-timestamp-type)
17363 ;; Point isn't on brackets. Remember the part of the time-stamp
17364 ;; the point was in. Indeed, size of time-stamps may change,
17365 ;; but point must be kept in the same category nonetheless.
17366 (setq origin-cat timestamp?)
17367 (when (and (not what) (not (eq timestamp? 'day))
17368 org-display-custom-times
17369 (get-text-property (point) 'display)
17370 (not (get-text-property (1- (point)) 'display)))
17371 (setq timestamp? 'day))
17372 (setq timestamp? (or what timestamp?)
17373 inactive (= (char-after (match-beginning 0)) ?\[)
17374 ts (match-string 0))
17375 (replace-match "")
17376 (when (string-match
17377 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17379 (setq extra (match-string 1 ts))
17380 (when suppress-tmp-delay
17381 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17382 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17383 (setq with-hm t))
17384 (setq time0 (org-parse-time-string ts))
17385 (when (and updown
17386 (eq timestamp? 'minute)
17387 (not current-prefix-arg))
17388 ;; This looks like s-up and s-down. Change by one rounding step.
17389 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17390 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17391 (setcar (cdr time0) (+ (nth 1 time0)
17392 (if (> n 0) (- rem) (- dm rem))))))
17393 (setq time
17394 (apply #'encode-time
17395 (or (car time0) 0)
17396 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17397 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17398 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17399 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17400 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17401 (nthcdr 6 time0)))
17402 (when (and (memq timestamp? '(hour minute))
17403 extra
17404 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17405 (setq extra (org-modify-ts-extra
17406 extra
17407 (if (eq timestamp? 'hour) 2 5)
17408 n dm)))
17409 (when (integerp timestamp?)
17410 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17411 (when (eq what 'calendar)
17412 (let ((cal-date (org-get-date-from-calendar)))
17413 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17414 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17415 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17416 (setcar time0 (or (car time0) 0))
17417 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17418 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17419 (setq time (apply 'encode-time time0))))
17420 ;; Insert the new time-stamp, and ensure point stays in the same
17421 ;; category as before (i.e. not after the last position in that
17422 ;; category).
17423 (let ((pos (point)))
17424 ;; Stay before inserted string. `save-excursion' is of no use.
17425 (setq org-last-changed-timestamp
17426 (org-insert-time-stamp time with-hm inactive nil nil extra))
17427 (goto-char pos))
17428 (save-match-data
17429 (looking-at org-ts-regexp3)
17430 (goto-char
17431 (pcase origin-cat
17432 ;; `day' category ends before `hour' if any, or at the end
17433 ;; of the day name.
17434 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17435 (`hour (min (match-end 7) origin))
17436 (`minute (min (1- (match-end 8)) origin))
17437 ((pred integerp) (min (1- (match-end 0)) origin))
17438 ;; Point was right after the time-stamp. However, the
17439 ;; time-stamp length might have changed, so refer to
17440 ;; (match-end 0) instead.
17441 (`after (match-end 0))
17442 ;; `year' and `month' have both fixed size: point couldn't
17443 ;; have moved into another part.
17444 (_ origin))))
17445 ;; Update clock if on a CLOCK line.
17446 (org-clock-update-time-maybe)
17447 ;; Maybe adjust the closest clock in `org-clock-history'
17448 (when org-clock-adjust-closest
17449 (if (not (and (org-at-clock-log-p)
17450 (< 1 (length (delq nil (mapcar 'marker-position
17451 org-clock-history))))))
17452 (message "No clock to adjust")
17453 (cond ((save-excursion ; fix previous clock?
17454 (re-search-backward org-ts-regexp0 nil t)
17455 (looking-back (concat org-clock-string " \\[")
17456 (line-beginning-position)))
17457 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17458 ((save-excursion ; fix next clock?
17459 (re-search-backward org-ts-regexp0 nil t)
17460 (looking-at (concat org-ts-regexp0 "\\] =>")))
17461 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17462 (save-window-excursion
17463 ;; Find closest clock to point, adjust the previous/next one in history
17464 (let* ((p (save-excursion (org-back-to-heading t)))
17465 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17466 (clfixnth
17467 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17468 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17469 (if (not clfixpos)
17470 (message "No clock to adjust")
17471 (save-excursion
17472 (org-goto-marker-or-bmk clfixpos)
17473 (org-show-subtree)
17474 (when (re-search-forward clrgx nil t)
17475 (goto-char (match-beginning 1))
17476 (let (org-clock-adjust-closest)
17477 (org-timestamp-change n timestamp? updown))
17478 (message "Clock adjusted in %s for heading: %s"
17479 (file-name-nondirectory (buffer-file-name))
17480 (org-get-heading t t)))))))))
17481 ;; Try to recenter the calendar window, if any.
17482 (when (and org-calendar-follow-timestamp-change
17483 (get-buffer-window "*Calendar*" t)
17484 (memq timestamp? '(day month year)))
17485 (org-recenter-calendar (time-to-days time))))))
17487 (defun org-modify-ts-extra (s pos n dm)
17488 "Change the different parts of the lead-time and repeat fields in timestamp."
17489 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17490 ng h m new rem)
17491 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17492 (cond
17493 ((or (org-pos-in-match-range pos 2)
17494 (org-pos-in-match-range pos 3))
17495 (setq m (string-to-number (match-string 3 s))
17496 h (string-to-number (match-string 2 s)))
17497 (if (org-pos-in-match-range pos 2)
17498 (setq h (+ h n))
17499 (setq n (* dm (with-no-warnings (signum n))))
17500 (unless (= 0 (setq rem (% m dm)))
17501 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17502 (setq m (+ m n)))
17503 (when (< m 0) (setq m (+ m 60) h (1- h)))
17504 (when (> m 59) (setq m (- m 60) h (1+ h)))
17505 (setq h (mod h 24))
17506 (setq ng 1 new (format "-%02d:%02d" h m)))
17507 ((org-pos-in-match-range pos 6)
17508 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17509 ((org-pos-in-match-range pos 5)
17510 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17512 ((org-pos-in-match-range pos 9)
17513 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17514 ((org-pos-in-match-range pos 8)
17515 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17517 (when ng
17518 (setq s (concat
17519 (substring s 0 (match-beginning ng))
17521 (substring s (match-end ng))))))
17524 (defun org-recenter-calendar (d)
17525 "If the calendar is visible, recenter it to date D."
17526 (let ((cwin (get-buffer-window "*Calendar*" t)))
17527 (when cwin
17528 (let ((calendar-move-hook nil))
17529 (with-selected-window cwin
17530 (calendar-goto-date
17531 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
17533 (defun org-goto-calendar (&optional arg)
17534 "Go to the Emacs calendar at the current date.
17535 If there is a time stamp in the current line, go to that date.
17536 A prefix ARG can be used to force the current date."
17537 (interactive "P")
17538 (let ((calendar-move-hook nil)
17539 (calendar-view-holidays-initially-flag nil)
17540 (calendar-view-diary-initially-flag nil)
17541 diff)
17542 (when (or (org-at-timestamp-p 'lax)
17543 (org-match-line (concat ".*" org-ts-regexp)))
17544 (let ((d1 (time-to-days (current-time)))
17545 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
17546 (setq diff (- d2 d1))))
17547 (calendar)
17548 (calendar-goto-today)
17549 (when (and diff (not arg)) (calendar-forward-day diff))))
17551 (defun org-get-date-from-calendar ()
17552 "Return a list (month day year) of date at point in calendar."
17553 (with-current-buffer "*Calendar*"
17554 (save-match-data
17555 (calendar-cursor-to-date))))
17557 (defun org-date-from-calendar ()
17558 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17559 If there is already a time stamp at the cursor position, update it."
17560 (interactive)
17561 (if (org-at-timestamp-p 'lax)
17562 (org-timestamp-change 0 'calendar)
17563 (let ((cal-date (org-get-date-from-calendar)))
17564 (org-insert-time-stamp
17565 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17567 (defcustom org-image-actual-width t
17568 "Should we use the actual width of images when inlining them?
17570 When set to t, always use the image width.
17572 When set to a number, use imagemagick (when available) to set
17573 the image's width to this value.
17575 When set to a number in a list, try to get the width from any
17576 #+ATTR.* keyword if it matches a width specification like
17578 #+ATTR_HTML: :width 300px
17580 and fall back on that number if none is found.
17582 When set to nil, try to get the width from an #+ATTR.* keyword
17583 and fall back on the original width if none is found.
17585 This requires Emacs >= 24.1, build with imagemagick support."
17586 :group 'org-appearance
17587 :version "24.4"
17588 :package-version '(Org . "8.0")
17589 :type '(choice
17590 (const :tag "Use the image width" t)
17591 (integer :tag "Use a number of pixels")
17592 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17593 (const :tag "Use #+ATTR* or don't resize" nil)))
17595 (defcustom org-agenda-inhibit-startup nil
17596 "Inhibit startup when preparing agenda buffers.
17597 When this variable is t, the initialization of the Org agenda
17598 buffers is inhibited: e.g. the visibility state is not set, the
17599 tables are not re-aligned, etc."
17600 :type 'boolean
17601 :version "24.3"
17602 :group 'org-agenda)
17604 (defcustom org-agenda-ignore-properties nil
17605 "Avoid updating text properties when building the agenda.
17606 Properties are used to prepare buffers for effort estimates,
17607 appointments, statistics and subtree-local categories.
17608 If you don't use these in the agenda, you can add them to this
17609 list and agenda building will be a bit faster.
17610 The value is a list, with zero or more of the symbols `effort', `appt',
17611 `stats' or `category'."
17612 :type '(set :greedy t
17613 (const effort)
17614 (const appt)
17615 (const stats)
17616 (const category))
17617 :version "26.1"
17618 :package-version '(Org . "8.3")
17619 :group 'org-agenda)
17621 ;;;; Files
17623 (defun org-save-all-org-buffers ()
17624 "Save all Org buffers without user confirmation."
17625 (interactive)
17626 (message "Saving all Org buffers...")
17627 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17628 (when (featurep 'org-id) (org-id-locations-save))
17629 (message "Saving all Org buffers... done"))
17631 (defun org-revert-all-org-buffers ()
17632 "Revert all Org buffers.
17633 Prompt for confirmation when there are unsaved changes.
17634 Be sure you know what you are doing before letting this function
17635 overwrite your changes.
17637 This function is useful in a setup where one tracks Org files
17638 with a version control system, to revert on one machine after pulling
17639 changes from another. I believe the procedure must be like this:
17641 1. M-x org-save-all-org-buffers
17642 2. Pull changes from the other machine, resolve conflicts
17643 3. M-x org-revert-all-org-buffers"
17644 (interactive)
17645 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17646 (user-error "Abort"))
17647 (save-excursion
17648 (save-window-excursion
17649 (dolist (b (buffer-list))
17650 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17651 (with-current-buffer b buffer-file-name))
17652 (pop-to-buffer-same-window b)
17653 (revert-buffer t 'no-confirm)))
17654 (when (and (featurep 'org-id) org-id-track-globally)
17655 (org-id-locations-load)))))
17657 ;;;; Agenda files
17659 ;;;###autoload
17660 (defun org-switchb (&optional arg)
17661 "Switch between Org buffers.
17663 With `\\[universal-argument]' prefix, restrict available buffers to files.
17665 With `\\[universal-argument] \\[universal-argument]' \
17666 prefix, restrict available buffers to agenda files."
17667 (interactive "P")
17668 (let ((blist (org-buffer-list
17669 (cond ((equal arg '(4)) 'files)
17670 ((equal arg '(16)) 'agenda)))))
17671 (pop-to-buffer-same-window
17672 (completing-read "Org buffer: "
17673 (mapcar #'list (mapcar #'buffer-name blist))
17674 nil t))))
17676 (defun org-buffer-list (&optional predicate exclude-tmp)
17677 "Return a list of Org buffers.
17678 PREDICATE can be `export', `files' or `agenda'.
17680 export restrict the list to Export buffers.
17681 files restrict the list to buffers visiting Org files.
17682 agenda restrict the list to buffers visiting agenda files.
17684 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17685 (let* ((bfn nil)
17686 (agenda-files (and (eq predicate 'agenda)
17687 (mapcar 'file-truename (org-agenda-files t))))
17688 (filter
17689 (cond
17690 ((eq predicate 'files)
17691 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17692 ((eq predicate 'export)
17693 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
17694 ((eq predicate 'agenda)
17695 (lambda (b)
17696 (with-current-buffer b
17697 (and (derived-mode-p 'org-mode)
17698 (setq bfn (buffer-file-name b))
17699 (member (file-truename bfn) agenda-files)))))
17700 (t (lambda (b) (with-current-buffer b
17701 (or (derived-mode-p 'org-mode)
17702 (string-match "\\*Org .*Export"
17703 (buffer-name b)))))))))
17704 (delq nil
17705 (mapcar
17706 (lambda(b)
17707 (if (and (funcall filter b)
17708 (or (not exclude-tmp)
17709 (not (string-match "tmp" (buffer-name b)))))
17711 nil))
17712 (buffer-list)))))
17714 (defun org-agenda-files (&optional unrestricted archives)
17715 "Get the list of agenda files.
17716 Optional UNRESTRICTED means return the full list even if a restriction
17717 is currently in place.
17718 When ARCHIVES is t, include all archive files that are really being
17719 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17720 `org-agenda-archives-mode' is t."
17721 (let ((files
17722 (cond
17723 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17724 ((stringp org-agenda-files) (org-read-agenda-file-list))
17725 ((listp org-agenda-files) org-agenda-files)
17726 (t (error "Invalid value of `org-agenda-files'")))))
17727 (setq files (apply 'append
17728 (mapcar (lambda (f)
17729 (if (file-directory-p f)
17730 (directory-files
17731 f t org-agenda-file-regexp)
17732 (list f)))
17733 files)))
17734 (when org-agenda-skip-unavailable-files
17735 (setq files (delq nil
17736 (mapcar (function
17737 (lambda (file)
17738 (and (file-readable-p file) file)))
17739 files))))
17740 (when (or (eq archives t)
17741 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17742 (setq files (org-add-archive-files files)))
17743 files))
17745 (defun org-agenda-file-p (&optional file)
17746 "Return non-nil, if FILE is an agenda file.
17747 If FILE is omitted, use the file associated with the current
17748 buffer."
17749 (let ((fname (or file (buffer-file-name))))
17750 (and fname
17751 (member (file-truename fname)
17752 (mapcar #'file-truename (org-agenda-files t))))))
17754 (defun org-edit-agenda-file-list ()
17755 "Edit the list of agenda files.
17756 Depending on setup, this either uses customize to edit the variable
17757 `org-agenda-files', or it visits the file that is holding the list. In the
17758 latter case, the buffer is set up in a way that saving it automatically kills
17759 the buffer and restores the previous window configuration."
17760 (interactive)
17761 (if (stringp org-agenda-files)
17762 (let ((cw (current-window-configuration)))
17763 (find-file org-agenda-files)
17764 (setq-local org-window-configuration cw)
17765 (add-hook 'after-save-hook
17766 (lambda ()
17767 (set-window-configuration
17768 (prog1 org-window-configuration
17769 (kill-buffer (current-buffer))))
17770 (org-install-agenda-files-menu)
17771 (message "New agenda file list installed"))
17772 nil 'local)
17773 (message "%s" (substitute-command-keys
17774 "Edit list and finish with \\[save-buffer]")))
17775 (customize-variable 'org-agenda-files)))
17777 (defun org-store-new-agenda-file-list (list)
17778 "Set new value for the agenda file list and save it correctly."
17779 (if (stringp org-agenda-files)
17780 (let ((fe (org-read-agenda-file-list t)) b u)
17781 (while (setq b (find-buffer-visiting org-agenda-files))
17782 (kill-buffer b))
17783 (with-temp-file org-agenda-files
17784 (insert
17785 (mapconcat
17786 (lambda (f) ;; Keep un-expanded entries.
17787 (if (setq u (assoc f fe))
17788 (cdr u)
17790 list "\n")
17791 "\n")))
17792 (let ((org-mode-hook nil) (org-inhibit-startup t)
17793 (org-insert-mode-line-in-empty-file nil))
17794 (setq org-agenda-files list)
17795 (customize-save-variable 'org-agenda-files org-agenda-files))))
17797 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17798 "Read the list of agenda files from a file.
17799 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17800 filenames, used by `org-store-new-agenda-file-list' to write back
17801 un-expanded file names."
17802 (when (file-directory-p org-agenda-files)
17803 (error "`org-agenda-files' cannot be a single directory"))
17804 (when (stringp org-agenda-files)
17805 (with-temp-buffer
17806 (insert-file-contents org-agenda-files)
17807 (mapcar
17808 (lambda (f)
17809 (let ((e (expand-file-name (substitute-in-file-name f)
17810 org-directory)))
17811 (if pair-with-expansion
17812 (cons e f)
17813 e)))
17814 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17816 ;;;###autoload
17817 (defun org-cycle-agenda-files ()
17818 "Cycle through the files in `org-agenda-files'.
17819 If the current buffer visits an agenda file, find the next one in the list.
17820 If the current buffer does not, find the first agenda file."
17821 (interactive)
17822 (let* ((fs (or (org-agenda-files t)
17823 (user-error "No agenda files")))
17824 (files (copy-sequence fs))
17825 (tcf (and buffer-file-name (file-truename buffer-file-name)))
17826 file)
17827 (when tcf
17828 (while (and (setq file (pop files))
17829 (not (equal (file-truename file) tcf)))))
17830 (find-file (car (or files fs)))
17831 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
17833 (defun org-agenda-file-to-front (&optional to-end)
17834 "Move/add the current file to the top of the agenda file list.
17835 If the file is not present in the list, it is added to the front. If it is
17836 present, it is moved there. With optional argument TO-END, add/move to the
17837 end of the list."
17838 (interactive "P")
17839 (let ((org-agenda-skip-unavailable-files nil)
17840 (file-alist (mapcar (lambda (x)
17841 (cons (file-truename x) x))
17842 (org-agenda-files t)))
17843 (ctf (file-truename
17844 (or buffer-file-name
17845 (user-error "Please save the current buffer to a file"))))
17846 x had)
17847 (setq x (assoc ctf file-alist) had x)
17849 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17850 (if to-end
17851 (setq file-alist (append (delq x file-alist) (list x)))
17852 (setq file-alist (cons x (delq x file-alist))))
17853 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17854 (org-install-agenda-files-menu)
17855 (message "File %s to %s of agenda file list"
17856 (if had "moved" "added") (if to-end "end" "front"))))
17858 (defun org-remove-file (&optional file)
17859 "Remove current file from the list of files in variable `org-agenda-files'.
17860 These are the files which are being checked for agenda entries.
17861 Optional argument FILE means use this file instead of the current."
17862 (interactive)
17863 (let* ((org-agenda-skip-unavailable-files nil)
17864 (file (or file buffer-file-name
17865 (user-error "Current buffer does not visit a file")))
17866 (true-file (file-truename file))
17867 (afile (abbreviate-file-name file))
17868 (files (delq nil (mapcar
17869 (lambda (x)
17870 (unless (equal true-file
17871 (file-truename x))
17873 (org-agenda-files t)))))
17874 (if (not (= (length files) (length (org-agenda-files t))))
17875 (progn
17876 (org-store-new-agenda-file-list files)
17877 (org-install-agenda-files-menu)
17878 (message "Removed from Org Agenda list: %s" afile))
17879 (message "File was not in list: %s (not removed)" afile))))
17881 (defun org-file-menu-entry (file)
17882 (vector file (list 'find-file file) t))
17884 (defun org-check-agenda-file (file)
17885 "Make sure FILE exists. If not, ask user what to do."
17886 (unless (file-exists-p file)
17887 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17888 (abbreviate-file-name file))
17889 (let ((r (downcase (read-char-exclusive))))
17890 (cond
17891 ((equal r ?r)
17892 (org-remove-file file)
17893 (throw 'nextfile t))
17894 (t (user-error "Abort"))))))
17896 (defun org-get-agenda-file-buffer (file)
17897 "Get an agenda buffer visiting FILE.
17898 If the buffer needs to be created, add it to the list of buffers
17899 which might be released later."
17900 (let ((buf (org-find-base-buffer-visiting file)))
17901 (if buf
17902 buf ; just return it
17903 ;; Make a new buffer and remember it
17904 (setq buf (find-file-noselect file))
17905 (when buf (push buf org-agenda-new-buffers))
17906 buf)))
17908 (defun org-release-buffers (blist)
17909 "Release all buffers in list, asking the user for confirmation when needed.
17910 When a buffer is unmodified, it is just killed. When modified, it is saved
17911 \(if the user agrees) and then killed."
17912 (let (file)
17913 (dolist (buf blist)
17914 (setq file (buffer-file-name buf))
17915 (when (and (buffer-modified-p buf)
17916 file
17917 (y-or-n-p (format "Save file %s? " file)))
17918 (with-current-buffer buf (save-buffer)))
17919 (kill-buffer buf))))
17921 (defun org-agenda-prepare-buffers (files)
17922 "Create buffers for all agenda files, protect archived trees and comments."
17923 (interactive)
17924 (let ((pa '(:org-archived t))
17925 (pc '(:org-comment t))
17926 (pall '(:org-archived t :org-comment t))
17927 (inhibit-read-only t)
17928 (org-inhibit-startup org-agenda-inhibit-startup)
17929 (rea (org-make-tag-string (list org-archive-tag)))
17930 re pos)
17931 (setq org-tag-alist-for-agenda nil
17932 org-tag-groups-alist-for-agenda nil)
17933 (save-excursion
17934 (save-restriction
17935 (dolist (file files)
17936 (catch 'nextfile
17937 (if (bufferp file)
17938 (set-buffer file)
17939 (org-check-agenda-file file)
17940 (set-buffer (org-get-agenda-file-buffer file)))
17941 (widen)
17942 (org-set-regexps-and-options 'tags-only)
17943 (setq pos (point))
17944 (or (memq 'category org-agenda-ignore-properties)
17945 (org-refresh-category-properties))
17946 (or (memq 'stats org-agenda-ignore-properties)
17947 (org-refresh-stats-properties))
17948 (or (memq 'effort org-agenda-ignore-properties)
17949 (org-refresh-effort-properties))
17950 (or (memq 'appt org-agenda-ignore-properties)
17951 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
17952 (setq org-todo-keywords-for-agenda
17953 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17954 (setq org-done-keywords-for-agenda
17955 (append org-done-keywords-for-agenda org-done-keywords))
17956 (setq org-todo-keyword-alist-for-agenda
17957 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17958 (setq org-tag-alist-for-agenda
17959 (org--tag-add-to-alist
17960 org-tag-alist-for-agenda
17961 org-current-tag-alist))
17962 ;; Merge current file's tag groups into global
17963 ;; `org-tag-groups-alist-for-agenda'.
17964 (when org-group-tags
17965 (dolist (alist org-tag-groups-alist)
17966 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
17967 (if old
17968 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
17969 (push alist org-tag-groups-alist-for-agenda)))))
17970 (with-silent-modifications
17971 (save-excursion
17972 (remove-text-properties (point-min) (point-max) pall)
17973 (when org-agenda-skip-archived-trees
17974 (goto-char (point-min))
17975 (while (re-search-forward rea nil t)
17976 (when (org-at-heading-p t)
17977 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17978 (goto-char (point-min))
17979 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
17980 (while (re-search-forward re nil t)
17981 (when (save-match-data (org-in-commented-heading-p t))
17982 (add-text-properties
17983 (match-beginning 0) (org-end-of-subtree t) pc)))))
17984 (goto-char pos)))))
17985 (setq org-todo-keywords-for-agenda
17986 (org-uniquify org-todo-keywords-for-agenda))
17987 (setq org-todo-keyword-alist-for-agenda
17988 (org-uniquify org-todo-keyword-alist-for-agenda))))
17991 ;;;; CDLaTeX minor mode
17993 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17994 "Keymap for the minor `org-cdlatex-mode'.")
17996 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
17997 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
17998 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
17999 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
18000 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
18002 (defvar org-cdlatex-texmathp-advice-is-done nil
18003 "Flag remembering if we have applied the advice to texmathp already.")
18005 (define-minor-mode org-cdlatex-mode
18006 "Toggle the minor `org-cdlatex-mode'.
18007 This mode supports entering LaTeX environment and math in LaTeX fragments
18008 in Org mode.
18009 \\{org-cdlatex-mode-map}"
18010 nil " OCDL" nil
18011 (when org-cdlatex-mode
18012 (require 'cdlatex)
18013 (run-hooks 'cdlatex-mode-hook)
18014 (cdlatex-compute-tables))
18015 (unless org-cdlatex-texmathp-advice-is-done
18016 (setq org-cdlatex-texmathp-advice-is-done t)
18017 (defadvice texmathp (around org-math-always-on activate)
18018 "Always return t in Org buffers.
18019 This is because we want to insert math symbols without dollars even outside
18020 the LaTeX math segments. If Org mode thinks that point is actually inside
18021 an embedded LaTeX fragment, let `texmathp' do its job.
18022 `\\[org-cdlatex-mode-map]'"
18023 (interactive)
18024 (let (p)
18025 (cond
18026 ((not (derived-mode-p 'org-mode)) ad-do-it)
18027 ((eq this-command 'cdlatex-math-symbol)
18028 (setq ad-return-value t
18029 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18031 (let ((p (org-inside-LaTeX-fragment-p)))
18032 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18033 (setq ad-return-value t
18034 texmathp-why '("Org mode embedded math" . 0))
18035 (when p ad-do-it)))))))))
18037 (defun turn-on-org-cdlatex ()
18038 "Unconditionally turn on `org-cdlatex-mode'."
18039 (org-cdlatex-mode 1))
18041 (defun org-try-cdlatex-tab ()
18042 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18043 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18044 - inside a LaTeX fragment, or
18045 - after the first word in a line, where an abbreviation expansion could
18046 insert a LaTeX environment."
18047 (when org-cdlatex-mode
18048 (cond
18049 ;; Before any word on the line: No expansion possible.
18050 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18051 ;; Just after first word on the line: Expand it. Make sure it
18052 ;; cannot happen on headlines, though.
18053 ((save-excursion
18054 (skip-chars-backward "a-zA-Z0-9*")
18055 (skip-chars-backward " \t")
18056 (and (bolp) (not (org-at-heading-p))))
18057 (cdlatex-tab) t)
18058 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18060 (defun org-cdlatex-underscore-caret (&optional _arg)
18061 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18062 Revert to the normal definition outside of these fragments."
18063 (interactive "P")
18064 (if (org-inside-LaTeX-fragment-p)
18065 (call-interactively 'cdlatex-sub-superscript)
18066 (let (org-cdlatex-mode)
18067 (call-interactively (key-binding (vector last-input-event))))))
18069 (defun org-cdlatex-math-modify (&optional _arg)
18070 "Execute `cdlatex-math-modify' in LaTeX fragments.
18071 Revert to the normal definition outside of these fragments."
18072 (interactive "P")
18073 (if (org-inside-LaTeX-fragment-p)
18074 (call-interactively 'cdlatex-math-modify)
18075 (let (org-cdlatex-mode)
18076 (call-interactively (key-binding (vector last-input-event))))))
18078 (defun org-cdlatex-environment-indent (&optional environment item)
18079 "Execute `cdlatex-environment' and indent the inserted environment.
18081 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18083 The inserted environment is indented to current indentation
18084 unless point is at the beginning of the line, in which the
18085 environment remains unintended."
18086 (interactive)
18087 ;; cdlatex-environment always return nil. Therefore, capture output
18088 ;; first and determine if an environment was selected.
18089 (let* ((beg (point-marker))
18090 (end (copy-marker (point) t))
18091 (inserted (progn
18092 (ignore-errors (cdlatex-environment environment item))
18093 (< beg end)))
18094 ;; Figure out how many lines to move forward after the
18095 ;; environment has been inserted.
18096 (lines (when inserted
18097 (save-excursion
18098 (- (cl-loop while (< beg (point))
18099 with x = 0
18100 do (forward-line -1)
18101 (cl-incf x)
18102 finally return x)
18103 (if (progn (goto-char beg)
18104 (and (progn (skip-chars-forward " \t") (eolp))
18105 (progn (skip-chars-backward " \t") (bolp))))
18106 1 0)))))
18107 (env (org-trim (delete-and-extract-region beg end))))
18108 (when inserted
18109 ;; Get indentation of next line unless at column 0.
18110 (let ((ind (if (bolp) 0
18111 (save-excursion
18112 (org-return-indent)
18113 (prog1 (current-indentation)
18114 (when (progn (skip-chars-forward " \t") (eolp))
18115 (delete-region beg (point)))))))
18116 (bol (progn (skip-chars-backward " \t") (bolp))))
18117 ;; Insert a newline before environment unless at column zero
18118 ;; to "escape" the current line. Insert a newline if
18119 ;; something is one the same line as \end{ENVIRONMENT}.
18120 (insert
18121 (concat (unless bol "\n") env
18122 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18123 (unless (zerop ind)
18124 (save-excursion
18125 (goto-char beg)
18126 (while (< (point) end)
18127 (unless (eolp) (indent-line-to ind))
18128 (forward-line))))
18129 (goto-char beg)
18130 (forward-line lines)
18131 (indent-line-to ind)))
18132 (set-marker beg nil)
18133 (set-marker end nil)))
18136 ;;;; LaTeX fragments
18138 (defun org-inside-LaTeX-fragment-p ()
18139 "Test if point is inside a LaTeX fragment.
18140 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18141 sequence appearing also before point.
18142 Even though the matchers for math are configurable, this function assumes
18143 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18144 delimiters are skipped when they have been removed by customization.
18145 The return value is nil, or a cons cell with the delimiter and the
18146 position of this delimiter.
18148 This function does a reasonably good job, but can locally be fooled by
18149 for example currency specifications. For example it will assume being in
18150 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18151 fragments that are properly closed, but during editing, we have to live
18152 with the uncertainty caused by missing closing delimiters. This function
18153 looks only before point, not after."
18154 (catch 'exit
18155 (let ((pos (point))
18156 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18157 (lim (save-excursion (org-backward-paragraph) (point)))
18158 dd-on str (start 0) m re)
18159 (goto-char pos)
18160 (when dodollar
18161 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18162 re (nth 1 (assoc "$" org-latex-regexps)))
18163 (while (string-match re str start)
18164 (cond
18165 ((= (match-end 0) (length str))
18166 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18167 ((= (match-end 0) (- (length str) 5))
18168 (throw 'exit nil))
18169 (t (setq start (match-end 0))))))
18170 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18171 (goto-char pos)
18172 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18173 (and (match-beginning 2) (throw 'exit nil))
18174 ;; count $$
18175 (while (re-search-backward "\\$\\$" lim t)
18176 (setq dd-on (not dd-on)))
18177 (goto-char pos)
18178 (when dd-on (cons "$$" m))))))
18180 (defun org-inside-latex-macro-p ()
18181 "Is point inside a LaTeX macro or its arguments?"
18182 (save-match-data
18183 (org-in-regexp
18184 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18186 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18187 "Build an overlay between BEG and END using IMAGE file.
18188 Argument IMAGETYPE is the extension of the displayed image,
18189 as a string. It defaults to \"png\"."
18190 (let ((ov (make-overlay beg end))
18191 (imagetype (or (intern imagetype) 'png)))
18192 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18193 (overlay-put ov 'evaporate t)
18194 (overlay-put ov
18195 'modification-hooks
18196 (list (lambda (o _flag _beg _end &optional _l)
18197 (delete-overlay o))))
18198 (overlay-put ov
18199 'display
18200 (list 'image :type imagetype :file image :ascent 'center))))
18202 (defun org--list-latex-overlays (&optional beg end)
18203 "List all Org LaTeX overlays in current buffer.
18204 Limit to overlays between BEG and END when those are provided."
18205 (cl-remove-if-not
18206 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18207 (overlays-in (or beg (point-min)) (or end (point-max)))))
18209 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18210 "Remove all overlays with LaTeX fragment images in current buffer.
18211 When optional arguments BEG and END are non-nil, remove all
18212 overlays between them instead. Return a non-nil value when some
18213 overlays were removed, nil otherwise."
18214 (let ((overlays (org--list-latex-overlays beg end)))
18215 (mapc #'delete-overlay overlays)
18216 overlays))
18218 (defun org-toggle-latex-fragment (&optional arg)
18219 "Preview the LaTeX fragment at point, or all locally or globally.
18221 If the cursor is on a LaTeX fragment, create the image and overlay
18222 it over the source code, if there is none. Remove it otherwise.
18223 If there is no fragment at point, display all fragments in the
18224 current section.
18226 With prefix ARG, preview or clear image for all fragments in the
18227 current subtree or in the whole buffer when used before the first
18228 headline. With a prefix ARG `\\[universal-argument] \
18229 \\[universal-argument]' preview or clear images
18230 for all fragments in the buffer."
18231 (interactive "P")
18232 (when (display-graphic-p)
18233 (catch 'exit
18234 (save-excursion
18235 (let (beg end msg)
18236 (cond
18237 ((or (equal arg '(16))
18238 (and (equal arg '(4))
18239 (org-with-limited-levels (org-before-first-heading-p))))
18240 (if (org-remove-latex-fragment-image-overlays)
18241 (progn (message "LaTeX fragments images removed from buffer")
18242 (throw 'exit nil))
18243 (setq msg "Creating images for buffer...")))
18244 ((equal arg '(4))
18245 (org-with-limited-levels (org-back-to-heading t))
18246 (setq beg (point))
18247 (setq end (progn (org-end-of-subtree t) (point)))
18248 (if (org-remove-latex-fragment-image-overlays beg end)
18249 (progn
18250 (message "LaTeX fragment images removed from subtree")
18251 (throw 'exit nil))
18252 (setq msg "Creating images for subtree...")))
18253 ((let ((datum (org-element-context)))
18254 (when (memq (org-element-type datum)
18255 '(latex-environment latex-fragment))
18256 (setq beg (org-element-property :begin datum))
18257 (setq end (org-element-property :end datum))
18258 (if (org-remove-latex-fragment-image-overlays beg end)
18259 (progn (message "LaTeX fragment image removed")
18260 (throw 'exit nil))
18261 (setq msg "Creating image...")))))
18263 (org-with-limited-levels
18264 (setq beg (if (org-at-heading-p) (line-beginning-position)
18265 (outline-previous-heading)
18266 (point)))
18267 (setq end (progn (outline-next-heading) (point)))
18268 (if (org-remove-latex-fragment-image-overlays beg end)
18269 (progn
18270 (message "LaTeX fragment images removed from section")
18271 (throw 'exit nil))
18272 (setq msg "Creating images for section...")))))
18273 (let ((file (buffer-file-name (buffer-base-buffer))))
18274 (org-format-latex
18275 (concat org-preview-latex-image-directory "org-ltximg")
18276 beg end
18277 ;; Emacs cannot overlay images from remote hosts. Create
18278 ;; it in `temporary-file-directory' instead.
18279 (if (or (not file) (file-remote-p file))
18280 temporary-file-directory
18281 default-directory)
18282 'overlays msg 'forbuffer org-preview-latex-default-process))
18283 (message (concat msg "done")))))))
18285 (defun org-format-latex
18286 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18287 "Replace LaTeX fragments with links to an image.
18289 The function takes care of creating the replacement image.
18291 Only consider fragments between BEG and END when those are
18292 provided.
18294 When optional argument OVERLAYS is non-nil, display the image on
18295 top of the fragment instead of replacing it.
18297 PROCESSING-TYPE is the conversion method to use, as a symbol.
18299 Some of the options can be changed using the variable
18300 `org-format-latex-options', which see."
18301 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18302 (unless (eq processing-type 'verbatim)
18303 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18304 (cnt 0)
18305 checkdir-flag)
18306 (goto-char (or beg (point-min)))
18307 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18308 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18309 (overlay-recenter (or end (point-max))))
18310 (while (re-search-forward math-regexp end t)
18311 (unless (and overlays
18312 (eq (get-char-property (point) 'org-overlay-type)
18313 'org-latex-overlay))
18314 (let* ((context (org-element-context))
18315 (type (org-element-type context)))
18316 (when (memq type '(latex-environment latex-fragment))
18317 (let ((block-type (eq type 'latex-environment))
18318 (value (org-element-property :value context))
18319 (beg (org-element-property :begin context))
18320 (end (save-excursion
18321 (goto-char (org-element-property :end context))
18322 (skip-chars-backward " \r\t\n")
18323 (point))))
18324 (cond
18325 ((eq processing-type 'mathjax)
18326 ;; Prepare for MathJax processing.
18327 (if (not (string-match "\\`\\$\\$?" value))
18328 (goto-char end)
18329 (delete-region beg end)
18330 (if (string= (match-string 0 value) "$$")
18331 (insert "\\[" (substring value 2 -2) "\\]")
18332 (insert "\\(" (substring value 1 -1) "\\)"))))
18333 ((assq processing-type org-preview-latex-process-alist)
18334 ;; Process to an image.
18335 (cl-incf cnt)
18336 (goto-char beg)
18337 (let* ((processing-info
18338 (cdr (assq processing-type org-preview-latex-process-alist)))
18339 (face (face-at-point))
18340 ;; Get the colors from the face at point.
18342 (let ((color (plist-get org-format-latex-options
18343 :foreground)))
18344 (if (and forbuffer (eq color 'auto))
18345 (face-attribute face :foreground nil 'default)
18346 color)))
18348 (let ((color (plist-get org-format-latex-options
18349 :background)))
18350 (if (and forbuffer (eq color 'auto))
18351 (face-attribute face :background nil 'default)
18352 color)))
18353 (hash (sha1 (prin1-to-string
18354 (list org-format-latex-header
18355 org-latex-default-packages-alist
18356 org-latex-packages-alist
18357 org-format-latex-options
18358 forbuffer value fg bg))))
18359 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18360 (absprefix (expand-file-name prefix dir))
18361 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18362 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18363 (sep (and block-type "\n\n"))
18364 (link (concat sep "[[file:" linkfile "]]" sep))
18365 (options
18366 (org-combine-plists
18367 org-format-latex-options
18368 `(:foreground ,fg :background ,bg))))
18369 (when msg (message msg cnt))
18370 (unless checkdir-flag ; Ensure the directory exists.
18371 (setq checkdir-flag t)
18372 (let ((todir (file-name-directory absprefix)))
18373 (unless (file-directory-p todir)
18374 (make-directory todir t))))
18375 (unless (file-exists-p movefile)
18376 (org-create-formula-image
18377 value movefile options forbuffer processing-type))
18378 (if overlays
18379 (progn
18380 (dolist (o (overlays-in beg end))
18381 (when (eq (overlay-get o 'org-overlay-type)
18382 'org-latex-overlay)
18383 (delete-overlay o)))
18384 (org--format-latex-make-overlay beg end movefile imagetype)
18385 (goto-char end))
18386 (delete-region beg end)
18387 (insert
18388 (org-add-props link
18389 (list 'org-latex-src
18390 (replace-regexp-in-string "\"" "" value)
18391 'org-latex-src-embed-type
18392 (if block-type 'paragraph 'character)))))))
18393 ((eq processing-type 'mathml)
18394 ;; Process to MathML.
18395 (unless (org-format-latex-mathml-available-p)
18396 (user-error "LaTeX to MathML converter not configured"))
18397 (cl-incf cnt)
18398 (when msg (message msg cnt))
18399 (goto-char beg)
18400 (delete-region beg end)
18401 (insert (org-format-latex-as-mathml
18402 value block-type prefix dir)))
18404 (error "Unknown conversion process %s for LaTeX fragments"
18405 processing-type)))))))))))
18407 (defun org-create-math-formula (latex-frag &optional mathml-file)
18408 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18409 Use `org-latex-to-mathml-convert-command'. If the conversion is
18410 sucessful, return the portion between \"<math...> </math>\"
18411 elements otherwise return nil. When MATHML-FILE is specified,
18412 write the results in to that file. When invoked as an
18413 interactive command, prompt for LATEX-FRAG, with initial value
18414 set to the current active region and echo the results for user
18415 inspection."
18416 (interactive (list (let ((frag (when (org-region-active-p)
18417 (buffer-substring-no-properties
18418 (region-beginning) (region-end)))))
18419 (read-string "LaTeX Fragment: " frag nil frag))))
18420 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18421 (let* ((tmp-in-file
18422 (let ((file (file-relative-name
18423 (make-temp-name (expand-file-name "ltxmathml-in")))))
18424 (write-region latex-frag nil file)
18425 file))
18426 (tmp-out-file (file-relative-name
18427 (make-temp-name (expand-file-name "ltxmathml-out"))))
18428 (cmd (format-spec
18429 org-latex-to-mathml-convert-command
18430 `((?j . ,(and org-latex-to-mathml-jar-file
18431 (shell-quote-argument
18432 (expand-file-name
18433 org-latex-to-mathml-jar-file))))
18434 (?I . ,(shell-quote-argument tmp-in-file))
18435 (?i . ,latex-frag)
18436 (?o . ,(shell-quote-argument tmp-out-file)))))
18437 mathml shell-command-output)
18438 (when (called-interactively-p 'any)
18439 (unless (org-format-latex-mathml-available-p)
18440 (user-error "LaTeX to MathML converter not configured")))
18441 (message "Running %s" cmd)
18442 (setq shell-command-output (shell-command-to-string cmd))
18443 (setq mathml
18444 (when (file-readable-p tmp-out-file)
18445 (with-current-buffer (find-file-noselect tmp-out-file t)
18446 (goto-char (point-min))
18447 (when (re-search-forward
18448 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
18449 (regexp-quote
18450 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
18451 nil t)
18452 (prog1 (match-string 0) (kill-buffer))))))
18453 (cond
18454 (mathml
18455 (setq mathml
18456 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18457 (when mathml-file
18458 (write-region mathml nil mathml-file))
18459 (when (called-interactively-p 'any)
18460 (message mathml)))
18461 ((message "LaTeX to MathML conversion failed")
18462 (message shell-command-output)))
18463 (delete-file tmp-in-file)
18464 (when (file-exists-p tmp-out-file)
18465 (delete-file tmp-out-file))
18466 mathml))
18468 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18469 prefix &optional dir)
18470 "Use `org-create-math-formula' but check local cache first."
18471 (let* ((absprefix (expand-file-name prefix dir))
18472 (print-length nil) (print-level nil)
18473 (formula-id (concat
18474 "formula-"
18475 (sha1
18476 (prin1-to-string
18477 (list latex-frag
18478 org-latex-to-mathml-convert-command)))))
18479 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18480 (formula-cache-dir (file-name-directory formula-cache)))
18482 (unless (file-directory-p formula-cache-dir)
18483 (make-directory formula-cache-dir t))
18485 (unless (file-exists-p formula-cache)
18486 (org-create-math-formula latex-frag formula-cache))
18488 (if (file-exists-p formula-cache)
18489 ;; Successful conversion. Return the link to MathML file.
18490 (org-add-props
18491 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18492 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18493 'org-latex-src-embed-type (if latex-frag-type
18494 'paragraph 'character)))
18495 ;; Failed conversion. Return the LaTeX fragment verbatim
18496 latex-frag)))
18498 (defun org--get-display-dpi ()
18499 "Get the DPI of the display.
18500 The function assumes that the display has the same pixel width in
18501 the horizontal and vertical directions."
18502 (if (display-graphic-p)
18503 (round (/ (display-pixel-height)
18504 (/ (display-mm-height) 25.4)))
18505 (error "Attempt to calculate the dpi of a non-graphic display")))
18507 (defun org-create-formula-image
18508 (string tofile options buffer &optional processing-type)
18509 "Create an image from LaTeX source using external processes.
18511 The LaTeX STRING is saved to a temporary LaTeX file, then
18512 converted to an image file by process PROCESSING-TYPE defined in
18513 `org-preview-latex-process-alist'. A nil value defaults to
18514 `org-preview-latex-default-process'.
18516 The generated image file is eventually moved to TOFILE.
18518 The OPTIONS argument controls the size, foreground color and
18519 background color of the generated image.
18521 When BUFFER non-nil, this function is used for LaTeX previewing.
18522 Otherwise, it is used to deal with LaTeX snippets showed in
18523 a HTML file."
18524 (let* ((processing-type (or processing-type
18525 org-preview-latex-default-process))
18526 (processing-info
18527 (cdr (assq processing-type org-preview-latex-process-alist)))
18528 (programs (plist-get processing-info :programs))
18529 (error-message (or (plist-get processing-info :message) ""))
18530 (use-xcolor (plist-get processing-info :use-xcolor))
18531 (image-input-type (plist-get processing-info :image-input-type))
18532 (image-output-type (plist-get processing-info :image-output-type))
18533 (post-clean (or (plist-get processing-info :post-clean)
18534 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
18535 ".svg" ".png" ".jpg" ".jpeg" ".out")))
18536 (latex-header
18537 (or (plist-get processing-info :latex-header)
18538 (org-latex-make-preamble
18539 (org-export-get-environment (org-export-get-backend 'latex))
18540 org-format-latex-header
18541 'snippet)))
18542 (latex-compiler (plist-get processing-info :latex-compiler))
18543 (image-converter (plist-get processing-info :image-converter))
18544 (tmpdir temporary-file-directory)
18545 (texfilebase (make-temp-name
18546 (expand-file-name "orgtex" tmpdir)))
18547 (texfile (concat texfilebase ".tex"))
18548 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
18549 '(1.0 . 1.0)))
18550 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
18551 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
18552 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
18553 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18554 "Black"))
18555 (bg (or (plist-get options (if buffer :background :html-background))
18556 "Transparent"))
18557 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
18558 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
18559 (dolist (program programs)
18560 (org-check-external-command program error-message))
18561 (if use-xcolor
18562 (progn (if (eq fg 'default)
18563 (setq fg (org-latex-color :foreground))
18564 (setq fg (org-latex-color-format fg)))
18565 (if (eq bg 'default)
18566 (setq bg (org-latex-color :background))
18567 (setq bg (org-latex-color-format
18568 (if (string= bg "Transparent") "white" bg))))
18569 (with-temp-file texfile
18570 (insert latex-header)
18571 (insert "\n\\begin{document}\n"
18572 "\\definecolor{fg}{rgb}{" fg "}\n"
18573 "\\definecolor{bg}{rgb}{" bg "}\n"
18574 "\n\\pagecolor{bg}\n"
18575 "\n{\\color{fg}\n"
18576 string
18577 "\n}\n"
18578 "\n\\end{document}\n")))
18579 (if (eq fg 'default)
18580 (setq fg (org-dvipng-color :foreground))
18581 (unless (string= fg "Transparent")
18582 (setq fg (org-dvipng-color-format fg))))
18583 (if (eq bg 'default)
18584 (setq bg (org-dvipng-color :background))
18585 (unless (string= bg "Transparent")
18586 (setq bg (org-dvipng-color-format bg))))
18587 (with-temp-file texfile
18588 (insert latex-header)
18589 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18591 (let* ((err-msg (format "Please adjust `%s' part of \
18592 `org-preview-latex-process-alist'."
18593 processing-type))
18594 (image-input-file
18595 (org-compile-file
18596 texfile latex-compiler image-input-type err-msg log-buf))
18597 (image-output-file
18598 (org-compile-file
18599 image-input-file image-converter image-output-type err-msg log-buf
18600 `((?F . ,(shell-quote-argument fg))
18601 (?B . ,(shell-quote-argument bg))
18602 (?D . ,(shell-quote-argument (format "%s" dpi)))
18603 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
18604 (copy-file image-output-file tofile 'replace)
18605 (dolist (e post-clean)
18606 (when (file-exists-p (concat texfilebase e))
18607 (delete-file (concat texfilebase e))))
18608 image-output-file)))
18610 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18611 "Fill a LaTeX header template TPL.
18612 In the template, the following place holders will be recognized:
18614 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18615 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18616 [PACKAGES] \\usepackage statements for PKG
18617 [NO-PACKAGES] do not include PKG
18618 [EXTRA] the string EXTRA
18619 [NO-EXTRA] do not include EXTRA
18621 For backward compatibility, if both the positive and the negative place
18622 holder is missing, the positive one (without the \"NO-\") will be
18623 assumed to be present at the end of the template.
18624 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18625 EXTRA is a string.
18626 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18627 (let (rpl (end ""))
18628 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18629 (setq rpl (if (or (match-end 1) (not def-pkg))
18630 "" (org-latex-packages-to-string def-pkg snippets-p t))
18631 tpl (replace-match rpl t t tpl))
18632 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18634 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18635 (setq rpl (if (or (match-end 1) (not pkg))
18636 "" (org-latex-packages-to-string pkg snippets-p t))
18637 tpl (replace-match rpl t t tpl))
18638 (when pkg (setq end
18639 (concat end "\n"
18640 (org-latex-packages-to-string pkg snippets-p)))))
18642 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18643 (setq rpl (if (or (match-end 1) (not extra))
18644 "" (concat extra "\n"))
18645 tpl (replace-match rpl t t tpl))
18646 (when (and extra (string-match "\\S-" extra))
18647 (setq end (concat end "\n" extra))))
18649 (if (string-match "\\S-" end)
18650 (concat tpl "\n" end)
18651 tpl)))
18653 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18654 "Turn an alist of packages into a string with the \\usepackage macros."
18655 (setq pkg (mapconcat (lambda(p)
18656 (cond
18657 ((stringp p) p)
18658 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18659 (format "%% Package %s omitted" (cadr p)))
18660 ((equal "" (car p))
18661 (format "\\usepackage{%s}" (cadr p)))
18663 (format "\\usepackage[%s]{%s}"
18664 (car p) (cadr p)))))
18666 "\n"))
18667 (if newline (concat pkg "\n") pkg))
18669 (defun org-dvipng-color (attr)
18670 "Return a RGB color specification for dvipng."
18671 (org-dvipng-color-format (face-attribute 'default attr nil)))
18673 (defun org-dvipng-color-format (color-name)
18674 "Convert COLOR-NAME to a RGB color value for dvipng."
18675 (apply #'format "rgb %s %s %s"
18676 (mapcar 'org-normalize-color
18677 (color-values color-name))))
18679 (defun org-latex-color (attr)
18680 "Return a RGB color for the LaTeX color package."
18681 (org-latex-color-format (face-attribute 'default attr nil)))
18683 (defun org-latex-color-format (color-name)
18684 "Convert COLOR-NAME to a RGB color value."
18685 (apply #'format "%s,%s,%s"
18686 (mapcar 'org-normalize-color
18687 (color-values color-name))))
18689 (defun org-normalize-color (value)
18690 "Return string to be used as color value for an RGB component."
18691 (format "%g" (/ value 65535.0)))
18694 ;; Image display
18696 (defvar-local org-inline-image-overlays nil)
18698 (defun org-toggle-inline-images (&optional include-linked)
18699 "Toggle the display of inline images.
18700 INCLUDE-LINKED is passed to `org-display-inline-images'."
18701 (interactive "P")
18702 (if org-inline-image-overlays
18703 (progn
18704 (org-remove-inline-images)
18705 (when (called-interactively-p 'interactive)
18706 (message "Inline image display turned off")))
18707 (org-display-inline-images include-linked)
18708 (when (called-interactively-p 'interactive)
18709 (message (if org-inline-image-overlays
18710 (format "%d images displayed inline"
18711 (length org-inline-image-overlays))
18712 "No images to display inline")))))
18714 (defun org-redisplay-inline-images ()
18715 "Refresh the display of inline images."
18716 (interactive)
18717 (if (not org-inline-image-overlays)
18718 (org-toggle-inline-images)
18719 (org-toggle-inline-images)
18720 (org-toggle-inline-images)))
18722 (defun org-display-inline-images (&optional include-linked refresh beg end)
18723 "Display inline images.
18725 An inline image is a link which follows either of these
18726 conventions:
18728 1. Its path is a file with an extension matching return value
18729 from `image-file-name-regexp' and it has no contents.
18731 2. Its description consists in a single link of the previous
18732 type.
18734 When optional argument INCLUDE-LINKED is non-nil, also links with
18735 a text description part will be inlined. This can be nice for
18736 a quick look at those images, but it does not reflect what
18737 exported files will look like.
18739 When optional argument REFRESH is non-nil, refresh existing
18740 images between BEG and END. This will create new image displays
18741 only if necessary. BEG and END default to the buffer
18742 boundaries."
18743 (interactive "P")
18744 (when (display-graphic-p)
18745 (unless refresh
18746 (org-remove-inline-images)
18747 (when (fboundp 'clear-image-cache) (clear-image-cache)))
18748 (org-with-wide-buffer
18749 (goto-char (or beg (point-min)))
18750 (let* ((case-fold-search t)
18751 (file-extension-re (image-file-name-regexp))
18752 (link-abbrevs (mapcar #'car
18753 (append org-link-abbrev-alist-local
18754 org-link-abbrev-alist)))
18755 ;; Check absolute, relative file names and explicit
18756 ;; "file:" links. Also check link abbreviations since
18757 ;; some might expand to "file" links.
18758 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
18759 (if (not link-abbrevs) ""
18760 (format "\\|\\(?:%s:\\)"
18761 (regexp-opt link-abbrevs))))))
18762 (while (re-search-forward file-types-re end t)
18763 (let ((link (save-match-data (org-element-context))))
18764 ;; Check if we're at an inline image, i.e., an image file
18765 ;; link without a description (unless INCLUDE-LINKED is
18766 ;; non-nil).
18767 (when (and (equal "file" (org-element-property :type link))
18768 (or include-linked
18769 (null (org-element-contents link)))
18770 (string-match-p file-extension-re
18771 (org-element-property :path link)))
18772 (let ((file (expand-file-name
18773 (org-link-unescape
18774 (org-element-property :path link)))))
18775 (when (file-exists-p file)
18776 (let ((width
18777 ;; Apply `org-image-actual-width' specifications.
18778 (cond
18779 ((not (image-type-available-p 'imagemagick)) nil)
18780 ((eq org-image-actual-width t) nil)
18781 ((listp org-image-actual-width)
18783 ;; First try to find a width among
18784 ;; attributes associated to the paragraph
18785 ;; containing link.
18786 (let ((paragraph
18787 (let ((e link))
18788 (while (and (setq e (org-element-property
18789 :parent e))
18790 (not (eq (org-element-type e)
18791 'paragraph))))
18792 e)))
18793 (when paragraph
18794 (save-excursion
18795 (goto-char (org-element-property :begin paragraph))
18796 (when
18797 (re-search-forward
18798 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
18799 (org-element-property
18800 :post-affiliated paragraph)
18802 (string-to-number (match-string 1))))))
18803 ;; Otherwise, fall-back to provided number.
18804 (car org-image-actual-width)))
18805 ((numberp org-image-actual-width)
18806 org-image-actual-width)))
18807 (old (get-char-property-and-overlay
18808 (org-element-property :begin link)
18809 'org-image-overlay)))
18810 (if (and (car-safe old) refresh)
18811 (image-refresh (overlay-get (cdr old) 'display))
18812 (let ((image (create-image file
18813 (and width 'imagemagick)
18815 :width width)))
18816 (when image
18817 (let ((ov (make-overlay
18818 (org-element-property :begin link)
18819 (progn
18820 (goto-char
18821 (org-element-property :end link))
18822 (skip-chars-backward " \t")
18823 (point)))))
18824 (overlay-put ov 'display image)
18825 (overlay-put ov 'face 'default)
18826 (overlay-put ov 'org-image-overlay t)
18827 (overlay-put
18828 ov 'modification-hooks
18829 (list 'org-display-inline-remove-overlay))
18830 (push ov org-inline-image-overlays)))))))))))))))
18832 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
18833 "Remove inline-display overlay if a corresponding region is modified."
18834 (let ((inhibit-modification-hooks t))
18835 (when (and ov after)
18836 (delete ov org-inline-image-overlays)
18837 (delete-overlay ov))))
18839 (defun org-remove-inline-images ()
18840 "Remove inline display of images."
18841 (interactive)
18842 (mapc #'delete-overlay org-inline-image-overlays)
18843 (setq org-inline-image-overlays nil))
18846 ;;; Key bindings
18848 (defun org-remap (map &rest commands)
18849 "In MAP, remap the functions given in COMMANDS.
18850 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18851 (let (new old)
18852 (while commands
18853 (setq old (pop commands) new (pop commands))
18854 (org-defkey map (vector 'remap old) new))))
18856 ;;;; Outline functions that can be remapped in Org
18857 (define-key org-mode-map [remap outline-mark-subtree] #'org-mark-subtree)
18858 (define-key org-mode-map [remap outline-show-subtree] #'org-show-subtree)
18859 (define-key org-mode-map [remap outline-forward-same-level]
18860 #'org-forward-heading-same-level)
18861 (define-key org-mode-map [remap outline-backward-same-level]
18862 #'org-backward-heading-same-level)
18863 (define-key org-mode-map [remap outline-show-branches]
18864 #'org-kill-note-or-show-branches)
18865 (define-key org-mode-map [remap outline-promote] #'org-promote-subtree)
18866 (define-key org-mode-map [remap outline-demote] #'org-demote-subtree)
18867 (define-key org-mode-map [remap outline-insert-heading] #'org-ctrl-c-ret)
18868 (define-key org-mode-map [remap outline-next-visible-heading]
18869 #'org-next-visible-heading)
18870 (define-key org-mode-map [remap outline-previous-visible-heading]
18871 #'org-previous-visible-heading)
18872 (define-key org-mode-map [remap show-children] #'org-show-children)
18874 ;;;; Make `C-c C-x' a prefix key
18875 (org-defkey org-mode-map (kbd "C-c C-x") (make-sparse-keymap))
18877 ;;;; TAB key with modifiers
18878 (org-defkey org-mode-map (kbd "C-i") #'org-cycle)
18879 (org-defkey org-mode-map (kbd "<tab>") #'org-cycle)
18880 (org-defkey org-mode-map (kbd "C-<tab>") #'org-force-cycle-archived)
18881 (org-defkey org-mode-map (kbd "M-<tab>") #'pcomplete)
18882 (org-defkey org-mode-map (kbd "ESC <tab>") #'pcomplete)
18884 (org-defkey org-mode-map (kbd "<S-iso-leftab>") #'org-shifttab)
18885 (org-defkey org-mode-map (kbd "S-<tab>") #'org-shifttab)
18886 (define-key org-mode-map (kbd "<backtab>") #'org-shifttab)
18888 ;;;; RET key with modifiers
18889 (org-defkey org-mode-map (kbd "S-<return>") #'org-table-copy-down)
18890 (org-defkey org-mode-map (kbd "M-S-<return>") #'org-insert-todo-heading)
18891 (org-defkey org-mode-map (kbd "ESC S-<return>") #'org-insert-todo-heading)
18892 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
18893 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18895 ;;;; Cursor keys with modifiers
18896 (org-defkey org-mode-map (kbd "M-<left>") #'org-metaleft)
18897 (org-defkey org-mode-map (kbd "M-<right>") #'org-metaright)
18898 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18899 (org-defkey org-mode-map (kbd "M-<up>") #'org-metaup)
18900 (org-defkey org-mode-map (kbd "ESC <up>") #'org-metaup)
18901 (org-defkey org-mode-map (kbd "M-<down>") #'org-metadown)
18902 (org-defkey org-mode-map (kbd "ESC <down>") #'org-metadown)
18904 (org-defkey org-mode-map (kbd "C-M-S-<right>") #'org-increase-number-at-point)
18905 (org-defkey org-mode-map (kbd "C-M-S-<left>") #'org-decrease-number-at-point)
18906 (org-defkey org-mode-map (kbd "M-S-<left>") #'org-shiftmetaleft)
18907 (org-defkey org-mode-map (kbd "ESC S-<left>") #'org-shiftmetaleft)
18908 (org-defkey org-mode-map (kbd "M-S-<right>") #'org-shiftmetaright)
18909 (org-defkey org-mode-map (kbd "ESC S-<right>") #'org-shiftmetaright)
18910 (org-defkey org-mode-map (kbd "M-S-<up>") #'org-shiftmetaup)
18911 (org-defkey org-mode-map (kbd "ESC S-<up>") #'org-shiftmetaup)
18912 (org-defkey org-mode-map (kbd "M-S-<down>") #'org-shiftmetadown)
18913 (org-defkey org-mode-map (kbd "ESC S-<down>") #'org-shiftmetadown)
18915 (org-defkey org-mode-map (kbd "S-<up>") #'org-shiftup)
18916 (org-defkey org-mode-map (kbd "S-<down>") #'org-shiftdown)
18917 (org-defkey org-mode-map (kbd "S-<left>") #'org-shiftleft)
18918 (org-defkey org-mode-map (kbd "S-<right>") #'org-shiftright)
18920 (org-defkey org-mode-map (kbd "C-S-<right>") #'org-shiftcontrolright)
18921 (org-defkey org-mode-map (kbd "C-S-<left>") #'org-shiftcontrolleft)
18922 (org-defkey org-mode-map (kbd "C-S-<up>") #'org-shiftcontrolup)
18923 (org-defkey org-mode-map (kbd "C-S-<down>") #'org-shiftcontroldown)
18925 ;;;; Babel keys
18926 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18927 (pcase-dolist (`(,key . ,def) org-babel-key-bindings)
18928 (define-key org-babel-map key def))
18930 ;;;; Extra keys for TTY access.
18932 ;; We only set them when really needed because otherwise the
18933 ;; menus don't show the simple keys
18935 (when (or org-use-extra-keys (not window-system))
18936 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-table-copy-down)
18937 (org-defkey org-mode-map (kbd "C-c C-x m") #'org-meta-return)
18938 (org-defkey org-mode-map (kbd "C-c C-x M") #'org-insert-todo-heading)
18939 (org-defkey org-mode-map (kbd "C-c C-x RET") #'org-meta-return)
18940 (org-defkey org-mode-map (kbd "ESC RET") #'org-meta-return)
18941 (org-defkey org-mode-map (kbd "ESC <left>") #'org-metaleft)
18942 (org-defkey org-mode-map (kbd "C-c C-x l") #'org-metaleft)
18943 (org-defkey org-mode-map (kbd "ESC <right>") #'org-metaright)
18944 (org-defkey org-mode-map (kbd "C-c C-x r") #'org-metaright)
18945 (org-defkey org-mode-map (kbd "C-c C-x u") #'org-metaup)
18946 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-metadown)
18947 (org-defkey org-mode-map (kbd "C-c C-x L") #'org-shiftmetaleft)
18948 (org-defkey org-mode-map (kbd "C-c C-x R") #'org-shiftmetaright)
18949 (org-defkey org-mode-map (kbd "C-c C-x U") #'org-shiftmetaup)
18950 (org-defkey org-mode-map (kbd "C-c C-x D") #'org-shiftmetadown)
18951 (org-defkey org-mode-map (kbd "C-c <up>") #'org-shiftup)
18952 (org-defkey org-mode-map (kbd "C-c <down>") #'org-shiftdown)
18953 (org-defkey org-mode-map (kbd "C-c <left>") #'org-shiftleft)
18954 (org-defkey org-mode-map (kbd "C-c <right>") #'org-shiftright)
18955 (org-defkey org-mode-map (kbd "C-c C-x <right>") #'org-shiftcontrolright)
18956 (org-defkey org-mode-map (kbd "C-c C-x <left>") #'org-shiftcontrolleft))
18958 ;;;; Narrow map
18959 (org-defkey narrow-map "s" #'org-narrow-to-subtree)
18960 (org-defkey narrow-map "b" #'org-narrow-to-block)
18961 (org-defkey narrow-map "e" #'org-narrow-to-element)
18963 ;;;; Remap usual Emacs bindings
18964 (org-remap org-mode-map
18965 'self-insert-command 'org-self-insert-command
18966 'delete-char 'org-delete-char
18967 'delete-backward-char 'org-delete-backward-char
18968 'kill-line 'org-kill-line
18969 'open-line 'org-open-line
18970 'yank 'org-yank
18971 'comment-dwim 'org-comment-dwim
18972 'move-beginning-of-line 'org-beginning-of-line
18973 'move-end-of-line 'org-end-of-line
18974 'forward-paragraph 'org-forward-paragraph
18975 'backward-paragraph 'org-backward-paragraph
18976 'backward-sentence 'org-backward-sentence
18977 'forward-sentence 'org-forward-sentence
18978 'fill-paragraph 'org-fill-paragraph
18979 'delete-indentation 'org-delete-indentation
18980 'transpose-words 'org-transpose-words)
18982 ;;;; All the other keys
18983 (org-defkey org-mode-map (kbd "|") #'org-force-self-insert)
18984 (org-defkey org-mode-map (kbd "C-c C-a") #'org-show-all)
18985 (org-defkey org-mode-map (kbd "C-c C-r") #'org-reveal)
18986 (org-defkey org-mode-map (kbd "C-M-t") #'org-transpose-element)
18987 (org-defkey org-mode-map (kbd "M-}") #'org-forward-element)
18988 (org-defkey org-mode-map (kbd "ESC }") #'org-forward-element)
18989 (org-defkey org-mode-map (kbd "M-{") #'org-backward-element)
18990 (org-defkey org-mode-map (kbd "ESC {") #'org-backward-element)
18991 (org-defkey org-mode-map (kbd "C-c C-^") #'org-up-element)
18992 (org-defkey org-mode-map (kbd "C-c C-_") #'org-down-element)
18993 (org-defkey org-mode-map (kbd "C-c C-f") #'org-forward-heading-same-level)
18994 (org-defkey org-mode-map (kbd "C-c C-b") #'org-backward-heading-same-level)
18995 (org-defkey org-mode-map (kbd "C-c M-f") #'org-next-block)
18996 (org-defkey org-mode-map (kbd "C-c M-b") #'org-previous-block)
18997 (org-defkey org-mode-map (kbd "C-c $") #'org-archive-subtree)
18998 (org-defkey org-mode-map (kbd "C-c C-x C-s") #'org-archive-subtree)
18999 (org-defkey org-mode-map (kbd "C-c C-x C-a") #'org-archive-subtree-default)
19000 (org-defkey org-mode-map (kbd "C-c C-x d") #'org-insert-drawer)
19001 (org-defkey org-mode-map (kbd "C-c C-x a") #'org-toggle-archive-tag)
19002 (org-defkey org-mode-map (kbd "C-c C-x A") #'org-archive-to-archive-sibling)
19003 (org-defkey org-mode-map (kbd "C-c C-x b") #'org-tree-to-indirect-buffer)
19004 (org-defkey org-mode-map (kbd "C-c C-x q") #'org-toggle-tags-groups)
19005 (org-defkey org-mode-map (kbd "C-c C-j") #'org-goto)
19006 (org-defkey org-mode-map (kbd "C-c C-t") #'org-todo)
19007 (org-defkey org-mode-map (kbd "C-c C-q") #'org-set-tags-command)
19008 (org-defkey org-mode-map (kbd "C-c C-s") #'org-schedule)
19009 (org-defkey org-mode-map (kbd "C-c C-d") #'org-deadline)
19010 (org-defkey org-mode-map (kbd "C-c ;") #'org-toggle-comment)
19011 (org-defkey org-mode-map (kbd "C-c C-w") #'org-refile)
19012 (org-defkey org-mode-map (kbd "C-c M-w") #'org-copy)
19013 (org-defkey org-mode-map (kbd "C-c /") #'org-sparse-tree) ;minor-mode reserved
19014 (org-defkey org-mode-map (kbd "C-c \\") #'org-match-sparse-tree) ;minor-mode r.
19015 (org-defkey org-mode-map (kbd "C-c RET") #'org-ctrl-c-ret)
19016 (org-defkey org-mode-map (kbd "C-c C-x c") #'org-clone-subtree-with-time-shift)
19017 (org-defkey org-mode-map (kbd "C-c C-x v") #'org-copy-visible)
19018 (org-defkey org-mode-map (kbd "C-<return>") #'org-insert-heading-respect-content)
19019 (org-defkey org-mode-map (kbd "C-S-<return>") #'org-insert-todo-heading-respect-content)
19020 (org-defkey org-mode-map (kbd "C-c C-x C-n") #'org-next-link)
19021 (org-defkey org-mode-map (kbd "C-c C-x C-p") #'org-previous-link)
19022 (org-defkey org-mode-map (kbd "C-c C-l") #'org-insert-link)
19023 (org-defkey org-mode-map (kbd "C-c M-l") #'org-insert-last-stored-link)
19024 (org-defkey org-mode-map (kbd "C-c C-M-l") #'org-insert-all-links)
19025 (org-defkey org-mode-map (kbd "C-c C-o") #'org-open-at-point)
19026 (org-defkey org-mode-map (kbd "C-c %") #'org-mark-ring-push)
19027 (org-defkey org-mode-map (kbd "C-c &") #'org-mark-ring-goto)
19028 (org-defkey org-mode-map (kbd "C-c C-z") #'org-add-note) ;alternative binding
19029 (org-defkey org-mode-map (kbd "C-c .") #'org-time-stamp) ;minor-mode reserved
19030 (org-defkey org-mode-map (kbd "C-c !") #'org-time-stamp-inactive) ;minor-mode r.
19031 (org-defkey org-mode-map (kbd "C-c ,") #'org-priority) ;minor-mode reserved
19032 (org-defkey org-mode-map (kbd "C-c C-y") #'org-evaluate-time-range)
19033 (org-defkey org-mode-map (kbd "C-c >") #'org-goto-calendar)
19034 (org-defkey org-mode-map (kbd "C-c <") #'org-date-from-calendar)
19035 (org-defkey org-mode-map (kbd "C-,") #'org-cycle-agenda-files)
19036 (org-defkey org-mode-map (kbd "C-'") #'org-cycle-agenda-files)
19037 (org-defkey org-mode-map (kbd "C-c [") #'org-agenda-file-to-front)
19038 (org-defkey org-mode-map (kbd "C-c ]") #'org-remove-file)
19039 (org-defkey org-mode-map (kbd "C-c C-x <") #'org-agenda-set-restriction-lock)
19040 (org-defkey org-mode-map (kbd "C-c C-x >") #'org-agenda-remove-restriction-lock)
19041 (org-defkey org-mode-map (kbd "C-c -") #'org-ctrl-c-minus)
19042 (org-defkey org-mode-map (kbd "C-c *") #'org-ctrl-c-star)
19043 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19044 (org-defkey org-mode-map (kbd "C-c ^") #'org-sort)
19045 (org-defkey org-mode-map (kbd "C-c C-c") #'org-ctrl-c-ctrl-c)
19046 (org-defkey org-mode-map (kbd "C-c C-k") #'org-kill-note-or-show-branches)
19047 (org-defkey org-mode-map (kbd "C-c #") #'org-update-statistics-cookies)
19048 (org-defkey org-mode-map (kbd "RET") #'org-return)
19049 (org-defkey org-mode-map (kbd "C-j") #'org-return-indent)
19050 (org-defkey org-mode-map (kbd "C-c ?") #'org-table-field-info)
19051 (org-defkey org-mode-map (kbd "C-c SPC") #'org-table-blank-field)
19052 (org-defkey org-mode-map (kbd "C-c +") #'org-table-sum)
19053 (org-defkey org-mode-map (kbd "C-c =") #'org-table-eval-formula)
19054 (org-defkey org-mode-map (kbd "C-c '") #'org-edit-special)
19055 (org-defkey org-mode-map (kbd "C-c `") #'org-table-edit-field)
19056 (org-defkey org-mode-map (kbd "C-c \" a") #'orgtbl-ascii-plot)
19057 (org-defkey org-mode-map (kbd "C-c \" g") #'org-plot/gnuplot)
19058 (org-defkey org-mode-map (kbd "C-c |") #'org-table-create-or-convert-from-region)
19059 (org-defkey org-mode-map (kbd "C-#") #'org-table-rotate-recalc-marks)
19060 (org-defkey org-mode-map (kbd "C-c ~") #'org-table-create-with-table.el)
19061 (org-defkey org-mode-map (kbd "C-c C-a") #'org-attach)
19062 (org-defkey org-mode-map (kbd "C-c }") #'org-table-toggle-coordinate-overlays)
19063 (org-defkey org-mode-map (kbd "C-c {") #'org-table-toggle-formula-debugger)
19064 (org-defkey org-mode-map (kbd "C-c C-e") #'org-export-dispatch)
19065 (org-defkey org-mode-map (kbd "C-c :") #'org-toggle-fixed-width)
19066 (org-defkey org-mode-map (kbd "C-c C-x C-f") #'org-emphasize)
19067 (org-defkey org-mode-map (kbd "C-c C-x f") #'org-footnote-action)
19068 (org-defkey org-mode-map (kbd "C-c @") #'org-mark-subtree)
19069 (org-defkey org-mode-map (kbd "M-h") #'org-mark-element)
19070 (org-defkey org-mode-map (kbd "ESC h") #'org-mark-element)
19071 (org-defkey org-mode-map (kbd "C-c C-*") #'org-list-make-subtree)
19073 (org-defkey org-mode-map (kbd "C-c C-x C-w") #'org-cut-special)
19074 (org-defkey org-mode-map (kbd "C-c C-x M-w") #'org-copy-special)
19075 (org-defkey org-mode-map (kbd "C-c C-x C-y") #'org-paste-special)
19077 (org-defkey org-mode-map (kbd "C-c C-x C-t") #'org-toggle-time-stamp-overlays)
19078 (org-defkey org-mode-map (kbd "C-c C-x C-i") #'org-clock-in)
19079 (org-defkey org-mode-map (kbd "C-c C-x C-x") #'org-clock-in-last)
19080 (org-defkey org-mode-map (kbd "C-c C-x C-z") #'org-resolve-clocks)
19081 (org-defkey org-mode-map (kbd "C-c C-x C-o") #'org-clock-out)
19082 (org-defkey org-mode-map (kbd "C-c C-x C-j") #'org-clock-goto)
19083 (org-defkey org-mode-map (kbd "C-c C-x C-q") #'org-clock-cancel)
19084 (org-defkey org-mode-map (kbd "C-c C-x C-d") #'org-clock-display)
19085 (org-defkey org-mode-map (kbd "C-c C-x C-r") #'org-clock-report)
19086 (org-defkey org-mode-map (kbd "C-c C-x C-u") #'org-dblock-update)
19087 (org-defkey org-mode-map (kbd "C-c C-x C-l") #'org-toggle-latex-fragment)
19088 (org-defkey org-mode-map (kbd "C-c C-x C-v") #'org-toggle-inline-images)
19089 (org-defkey org-mode-map (kbd "C-c C-x C-M-v") #'org-redisplay-inline-images)
19090 (org-defkey org-mode-map (kbd "C-c C-x \\") #'org-toggle-pretty-entities)
19091 (org-defkey org-mode-map (kbd "C-c C-x C-b") #'org-toggle-checkbox)
19092 (org-defkey org-mode-map (kbd "C-c C-x p") #'org-set-property)
19093 (org-defkey org-mode-map (kbd "C-c C-x P") #'org-set-property-and-value)
19094 (org-defkey org-mode-map (kbd "C-c C-x e") #'org-set-effort)
19095 (org-defkey org-mode-map (kbd "C-c C-x E") #'org-inc-effort)
19096 (org-defkey org-mode-map (kbd "C-c C-x o") #'org-toggle-ordered-property)
19097 (org-defkey org-mode-map (kbd "C-c C-x i") #'org-columns-insert-dblock)
19098 (org-defkey org-mode-map (kbd "C-c C-,") #'org-insert-structure-template)
19099 (org-defkey org-mode-map (kbd "C-c C-x .") #'org-timer)
19100 (org-defkey org-mode-map (kbd "C-c C-x -") #'org-timer-item)
19101 (org-defkey org-mode-map (kbd "C-c C-x 0") #'org-timer-start)
19102 (org-defkey org-mode-map (kbd "C-c C-x _") #'org-timer-stop)
19103 (org-defkey org-mode-map (kbd "C-c C-x ;") #'org-timer-set-timer)
19104 (org-defkey org-mode-map (kbd "C-c C-x ,") #'org-timer-pause-or-continue)
19106 (define-key org-mode-map (kbd "C-c C-x C-c") #'org-columns)
19108 (define-key org-mode-map (kbd "C-c C-x !") #'org-reload)
19110 (define-key org-mode-map (kbd "C-c C-x g") #'org-feed-update-all)
19111 (define-key org-mode-map (kbd "C-c C-x G") #'org-feed-goto-inbox)
19113 (define-key org-mode-map (kbd "C-c C-x [") #'org-reftex-citation)
19116 ;;; Speed commands
19118 (defconst org-speed-commands-default
19120 ("Outline Navigation")
19121 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19122 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19123 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19124 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19125 ("F" . org-next-block)
19126 ("B" . org-previous-block)
19127 ("u" . (org-speed-move-safe 'outline-up-heading))
19128 ("j" . org-goto)
19129 ("g" . (org-refile t))
19130 ("Outline Visibility")
19131 ("c" . org-cycle)
19132 ("C" . org-shifttab)
19133 (" " . org-display-outline-path)
19134 ("s" . org-toggle-narrow-to-subtree)
19135 ("k" . org-cut-subtree)
19136 ("=" . org-columns)
19137 ("Outline Structure Editing")
19138 ("U" . org-metaup)
19139 ("D" . org-metadown)
19140 ("r" . org-metaright)
19141 ("l" . org-metaleft)
19142 ("R" . org-shiftmetaright)
19143 ("L" . org-shiftmetaleft)
19144 ("i" . (progn (forward-char 1) (call-interactively
19145 'org-insert-heading-respect-content)))
19146 ("^" . org-sort)
19147 ("w" . org-refile)
19148 ("a" . org-archive-subtree-default-with-confirmation)
19149 ("@" . org-mark-subtree)
19150 ("#" . org-toggle-comment)
19151 ("Clock Commands")
19152 ("I" . org-clock-in)
19153 ("O" . org-clock-out)
19154 ("Meta Data Editing")
19155 ("t" . org-todo)
19156 ("," . (org-priority))
19157 ("0" . (org-priority ?\ ))
19158 ("1" . (org-priority ?A))
19159 ("2" . (org-priority ?B))
19160 ("3" . (org-priority ?C))
19161 (":" . org-set-tags-command)
19162 ("e" . org-set-effort)
19163 ("E" . org-inc-effort)
19164 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19165 (org-entry-put (point) "APPT_WARNTIME" m)))
19166 ("Agenda Views etc")
19167 ("v" . org-agenda)
19168 ("/" . org-sparse-tree)
19169 ("Misc")
19170 ("o" . org-open-at-point)
19171 ("?" . org-speed-command-help)
19172 ("<" . (org-agenda-set-restriction-lock 'subtree))
19173 (">" . (org-agenda-remove-restriction-lock))
19175 "The default speed commands.")
19177 (defun org-print-speed-command (e)
19178 (if (> (length (car e)) 1)
19179 (progn
19180 (princ "\n")
19181 (princ (car e))
19182 (princ "\n")
19183 (princ (make-string (length (car e)) ?-))
19184 (princ "\n"))
19185 (princ (car e))
19186 (princ " ")
19187 (if (symbolp (cdr e))
19188 (princ (symbol-name (cdr e)))
19189 (prin1 (cdr e)))
19190 (princ "\n")))
19192 (defun org-speed-command-help ()
19193 "Show the available speed commands."
19194 (interactive)
19195 (if (not org-use-speed-commands)
19196 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19197 (with-output-to-temp-buffer "*Help*"
19198 (princ "User-defined Speed commands\n===========================\n")
19199 (mapc #'org-print-speed-command org-speed-commands-user)
19200 (princ "\n")
19201 (princ "Built-in Speed commands\n=======================\n")
19202 (mapc #'org-print-speed-command org-speed-commands-default))
19203 (with-current-buffer "*Help*"
19204 (setq truncate-lines t))))
19206 (defun org-speed-move-safe (cmd)
19207 "Execute CMD, but make sure that the cursor always ends up in a headline.
19208 If not, return to the original position and throw an error."
19209 (interactive)
19210 (let ((pos (point)))
19211 (call-interactively cmd)
19212 (unless (and (bolp) (org-at-heading-p))
19213 (goto-char pos)
19214 (error "Boundary reached while executing %s" cmd))))
19216 (defvar org-self-insert-command-undo-counter 0)
19218 (defvar org-table-auto-blank-field) ; defined in org-table.el
19219 (defvar org-speed-command nil)
19221 (defun org-speed-command-activate (keys)
19222 "Hook for activating single-letter speed commands.
19223 `org-speed-commands-default' specifies a minimal command set.
19224 Use `org-speed-commands-user' for further customization."
19225 (when (or (and (bolp) (looking-at org-outline-regexp))
19226 (and (functionp org-use-speed-commands)
19227 (funcall org-use-speed-commands)))
19228 (cdr (assoc keys (append org-speed-commands-user
19229 org-speed-commands-default)))))
19231 (defun org-babel-speed-command-activate (keys)
19232 "Hook for activating single-letter code block commands."
19233 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19234 (cdr (assoc keys org-babel-key-bindings))))
19236 (defcustom org-speed-command-hook
19237 '(org-speed-command-activate org-babel-speed-command-activate)
19238 "Hook for activating speed commands at strategic locations.
19239 Hook functions are called in sequence until a valid handler is
19240 found.
19242 Each hook takes a single argument, a user-pressed command key
19243 which is also a `self-insert-command' from the global map.
19245 Within the hook, examine the cursor position and the command key
19246 and return nil or a valid handler as appropriate. Handler could
19247 be one of an interactive command, a function, or a form.
19249 Set `org-use-speed-commands' to non-nil value to enable this
19250 hook. The default setting is `org-speed-command-activate'."
19251 :group 'org-structure
19252 :version "24.1"
19253 :type 'hook)
19255 (defun org-self-insert-command (N)
19256 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19257 If the cursor is in a table looking at whitespace, the whitespace is
19258 overwritten, and the table is not marked as requiring realignment."
19259 (interactive "p")
19260 (org-check-before-invisible-edit 'insert)
19261 (cond
19262 ((and org-use-speed-commands
19263 (let ((kv (this-command-keys-vector)))
19264 (setq org-speed-command
19265 (run-hook-with-args-until-success
19266 'org-speed-command-hook
19267 (make-string 1 (aref kv (1- (length kv))))))))
19268 (cond
19269 ((commandp org-speed-command)
19270 (setq this-command org-speed-command)
19271 (call-interactively org-speed-command))
19272 ((functionp org-speed-command)
19273 (funcall org-speed-command))
19274 ((and org-speed-command (listp org-speed-command))
19275 (eval org-speed-command))
19276 (t (let (org-use-speed-commands)
19277 (call-interactively 'org-self-insert-command)))))
19278 ((and
19279 (= N 1)
19280 (not (org-region-active-p))
19281 (org-at-table-p)
19282 (progn
19283 ;; Check if we blank the field, and if that triggers align.
19284 (and (featurep 'org-table)
19285 org-table-auto-blank-field
19286 (memq last-command
19287 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19288 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19289 ;; Got extra space, this field does not determine
19290 ;; column width.
19291 (let (org-table-may-need-update) (org-table-blank-field))
19292 ;; No extra space, this field may determine column
19293 ;; width.
19294 (org-table-blank-field)))
19296 (looking-at "[^|\n]* |"))
19297 ;; There is room for insertion without re-aligning the table.
19298 (self-insert-command N)
19299 (org-table-with-shrunk-field
19300 (save-excursion
19301 (skip-chars-forward "^|")
19302 ;; Do not delete last space, which is
19303 ;; `org-table-separator-space', but the regular space before
19304 ;; it.
19305 (delete-region (- (point) 2) (1- (point))))))
19307 (setq org-table-may-need-update t)
19308 (self-insert-command N)
19309 (org-fix-tags-on-the-fly)
19310 (when org-self-insert-cluster-for-undo
19311 (if (not (eq last-command 'org-self-insert-command))
19312 (setq org-self-insert-command-undo-counter 1)
19313 (if (>= org-self-insert-command-undo-counter 20)
19314 (setq org-self-insert-command-undo-counter 1)
19315 (and (> org-self-insert-command-undo-counter 0)
19316 buffer-undo-list (listp buffer-undo-list)
19317 (not (cadr buffer-undo-list)) ; remove nil entry
19318 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19319 (setq org-self-insert-command-undo-counter
19320 (1+ org-self-insert-command-undo-counter))))))))
19322 (defun org-check-before-invisible-edit (kind)
19323 "Check is editing if kind KIND would be dangerous with invisible text around.
19324 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19325 ;; First, try to get out of here as quickly as possible, to reduce overhead
19326 (when (and org-catch-invisible-edits
19327 (or (not (boundp 'visible-mode)) (not visible-mode))
19328 (or (get-char-property (point) 'invisible)
19329 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19330 ;; OK, we need to take a closer look. Do not consider
19331 ;; invisibility obtained through text properties (e.g., link
19332 ;; fontification), as it cannot be toggled.
19333 (let* ((invisible-at-point
19334 (pcase (get-char-property-and-overlay (point) 'invisible)
19335 (`(,_ . ,(and (pred overlayp) o)) o)))
19336 ;; Assume that point cannot land in the middle of an
19337 ;; overlay, or between two overlays.
19338 (invisible-before-point
19339 (and (not invisible-at-point)
19340 (not (bobp))
19341 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19342 (`(,_ . ,(and (pred overlayp) o)) o))))
19343 (border-and-ok-direction
19345 ;; Check if we are acting predictably before invisible
19346 ;; text.
19347 (and invisible-at-point
19348 (memq kind '(insert delete-backward)))
19349 ;; Check if we are acting predictably after invisible text
19350 ;; This works not well, and I have turned it off. It seems
19351 ;; better to always show and stop after invisible text.
19352 ;; (and (not invisible-at-point) invisible-before-point
19353 ;; (memq kind '(insert delete)))
19355 (when (or invisible-at-point invisible-before-point)
19356 (when (eq org-catch-invisible-edits 'error)
19357 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19358 (if (and org-custom-properties-overlays
19359 (y-or-n-p "Display invisible properties in this buffer? "))
19360 (org-toggle-custom-properties-visibility)
19361 ;; Make the area visible
19362 (save-excursion
19363 (when invisible-before-point
19364 (goto-char
19365 (previous-single-char-property-change (point) 'invisible)))
19366 ;; Remove whatever overlay is currently making yet-to-be
19367 ;; edited text invisible. Also remove nested invisibility
19368 ;; related overlays.
19369 (delete-overlay (or invisible-at-point invisible-before-point))
19370 (let ((origin (if invisible-at-point (point) (1- (point)))))
19371 (while (pcase (get-char-property-and-overlay origin 'invisible)
19372 (`(,_ . ,(and (pred overlayp) o))
19373 (delete-overlay o)
19374 t)))))
19375 (cond
19376 ((eq org-catch-invisible-edits 'show)
19377 ;; That's it, we do the edit after showing
19378 (message
19379 "Unfolding invisible region around point before editing")
19380 (sit-for 1))
19381 ((and (eq org-catch-invisible-edits 'smart)
19382 border-and-ok-direction)
19383 (message "Unfolding invisible region around point before editing"))
19385 ;; Don't do the edit, make the user repeat it in full visibility
19386 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19388 (defun org-fix-tags-on-the-fly ()
19389 "Align tags in headline at point.
19390 Unlike `org-align-tags', this function does nothing if point is
19391 either not currently on a tagged headline or on a tag."
19392 (when (and (org-match-line org-tag-line-re)
19393 (< (point) (match-beginning 1)))
19394 (org-align-tags)))
19396 (defun org-delete-backward-char (N)
19397 "Like `delete-backward-char', insert whitespace at field end in tables.
19398 When deleting backwards, in tables this function will insert whitespace in
19399 front of the next \"|\" separator, to keep the table aligned. The table will
19400 still be marked for re-alignment if the field did fill the entire column,
19401 because, in this case the deletion might narrow the column."
19402 (interactive "p")
19403 (save-match-data
19404 (org-check-before-invisible-edit 'delete-backward)
19405 (if (and (= N 1)
19406 (not overwrite-mode)
19407 (not (org-region-active-p))
19408 (not (eq (char-before) ?|))
19409 (save-excursion (skip-chars-backward " \t") (not (bolp)))
19410 (looking-at-p ".*?|")
19411 (org-at-table-p))
19412 (progn (forward-char -1) (org-delete-char 1))
19413 (backward-delete-char N)
19414 (org-fix-tags-on-the-fly))))
19416 (defun org-delete-char (N)
19417 "Like `delete-char', but insert whitespace at field end in tables.
19418 When deleting characters, in tables this function will insert whitespace in
19419 front of the next \"|\" separator, to keep the table aligned. The table will
19420 still be marked for re-alignment if the field did fill the entire column,
19421 because, in this case the deletion might narrow the column."
19422 (interactive "p")
19423 (save-match-data
19424 (org-check-before-invisible-edit 'delete)
19425 (cond
19426 ((or (/= N 1)
19427 (eq (char-after) ?|)
19428 (save-excursion (skip-chars-backward " \t") (bolp))
19429 (not (org-at-table-p)))
19430 (delete-char N)
19431 (org-fix-tags-on-the-fly))
19432 ((looking-at ".\\(.*?\\)|")
19433 (let* ((update? org-table-may-need-update)
19434 (noalign (looking-at-p ".*? |")))
19435 (delete-char 1)
19436 (org-table-with-shrunk-field
19437 (save-excursion
19438 ;; Last space is `org-table-separator-space', so insert
19439 ;; a regular one before it instead.
19440 (goto-char (- (match-end 0) 2))
19441 (insert " ")))
19442 ;; If there were two spaces at the end, this field does not
19443 ;; determine the width of the column.
19444 (when noalign (setq org-table-may-need-update update?))))
19446 (delete-char N)))))
19448 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
19449 (put 'org-self-insert-command 'delete-selection
19450 (lambda ()
19451 (not (run-hook-with-args-until-success
19452 'self-insert-uses-region-functions))))
19453 (put 'orgtbl-self-insert-command 'delete-selection
19454 (lambda ()
19455 (not (run-hook-with-args-until-success
19456 'self-insert-uses-region-functions))))
19457 (put 'org-delete-char 'delete-selection 'supersede)
19458 (put 'org-delete-backward-char 'delete-selection 'supersede)
19459 (put 'org-yank 'delete-selection 'yank)
19461 ;; Make `flyspell-mode' delay after some commands
19462 (put 'org-self-insert-command 'flyspell-delayed t)
19463 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19464 (put 'org-delete-char 'flyspell-delayed t)
19465 (put 'org-delete-backward-char 'flyspell-delayed t)
19467 ;; Make pabbrev-mode expand after Org mode commands
19468 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19469 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19471 (defun org-transpose-words ()
19472 "Transpose words for Org.
19473 This uses the `org-mode-transpose-word-syntax-table' syntax
19474 table, which interprets characters in `org-emphasis-alist' as
19475 word constituents."
19476 (interactive)
19477 (with-syntax-table org-mode-transpose-word-syntax-table
19478 (call-interactively 'transpose-words)))
19480 (defvar org-ctrl-c-ctrl-c-hook nil
19481 "Hook for functions attaching themselves to `C-c C-c'.
19483 This can be used to add additional functionality to the C-c C-c
19484 key which executes context-dependent commands. This hook is run
19485 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19486 run after the last test.
19488 Each function will be called with no arguments. The function
19489 must check if the context is appropriate for it to act. If yes,
19490 it should do its thing and then return a non-nil value. If the
19491 context is wrong, just do nothing and return nil.")
19493 (defvar org-ctrl-c-ctrl-c-final-hook nil
19494 "Hook for functions attaching themselves to `C-c C-c'.
19496 This can be used to add additional functionality to the C-c C-c
19497 key which executes context-dependent commands. This hook is run
19498 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19499 before the first test.
19501 Each function will be called with no arguments. The function
19502 must check if the context is appropriate for it to act. If yes,
19503 it should do its thing and then return a non-nil value. If the
19504 context is wrong, just do nothing and return nil.")
19506 (defvar org-tab-first-hook nil
19507 "Hook for functions to attach themselves to TAB.
19508 See `org-ctrl-c-ctrl-c-hook' for more information.
19509 This hook runs as the first action when TAB is pressed, even before
19510 `org-cycle' messes around with the `outline-regexp' to cater for
19511 inline tasks and plain list item folding.
19512 If any function in this hook returns t, any other actions that
19513 would have been caused by TAB (such as table field motion or visibility
19514 cycling) will not occur.")
19516 (defvar org-tab-after-check-for-table-hook nil
19517 "Hook for functions to attach themselves to TAB.
19518 See `org-ctrl-c-ctrl-c-hook' for more information.
19519 This hook runs after it has been established that the cursor is not in a
19520 table, but before checking if the cursor is in a headline or if global cycling
19521 should be done.
19522 If any function in this hook returns t, not other actions like visibility
19523 cycling will be done.")
19525 (defvar org-tab-after-check-for-cycling-hook nil
19526 "Hook for functions to attach themselves to TAB.
19527 See `org-ctrl-c-ctrl-c-hook' for more information.
19528 This hook runs after it has been established that not table field motion and
19529 not visibility should be done because of current context. This is probably
19530 the place where a package like yasnippets can hook in.")
19532 (defvar org-tab-before-tab-emulation-hook nil
19533 "Hook for functions to attach themselves to TAB.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.
19535 This hook runs after every other options for TAB have been exhausted, but
19536 before indentation and \t insertion takes place.")
19538 (defvar org-metaleft-hook nil
19539 "Hook for functions attaching themselves to `M-left'.
19540 See `org-ctrl-c-ctrl-c-hook' for more information.")
19541 (defvar org-metaright-hook nil
19542 "Hook for functions attaching themselves to `M-right'.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-metaup-hook nil
19545 "Hook for functions attaching themselves to `M-up'.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-metadown-hook nil
19548 "Hook for functions attaching themselves to `M-down'.
19549 See `org-ctrl-c-ctrl-c-hook' for more information.")
19550 (defvar org-shiftmetaleft-hook nil
19551 "Hook for functions attaching themselves to `M-S-left'.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.")
19553 (defvar org-shiftmetaright-hook nil
19554 "Hook for functions attaching themselves to `M-S-right'.
19555 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defvar org-shiftmetaup-hook nil
19557 "Hook for functions attaching themselves to `M-S-up'.
19558 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defvar org-shiftmetadown-hook nil
19560 "Hook for functions attaching themselves to `M-S-down'.
19561 See `org-ctrl-c-ctrl-c-hook' for more information.")
19562 (defvar org-metareturn-hook nil
19563 "Hook for functions attaching themselves to `M-RET'.
19564 See `org-ctrl-c-ctrl-c-hook' for more information.")
19565 (defvar org-shiftup-hook nil
19566 "Hook for functions attaching themselves to `S-up'.
19567 See `org-ctrl-c-ctrl-c-hook' for more information.")
19568 (defvar org-shiftup-final-hook nil
19569 "Hook for functions attaching themselves to `S-up'.
19570 This one runs after all other options except shift-select have been excluded.
19571 See `org-ctrl-c-ctrl-c-hook' for more information.")
19572 (defvar org-shiftdown-hook nil
19573 "Hook for functions attaching themselves to `S-down'.
19574 See `org-ctrl-c-ctrl-c-hook' for more information.")
19575 (defvar org-shiftdown-final-hook nil
19576 "Hook for functions attaching themselves to `S-down'.
19577 This one runs after all other options except shift-select have been excluded.
19578 See `org-ctrl-c-ctrl-c-hook' for more information.")
19579 (defvar org-shiftleft-hook nil
19580 "Hook for functions attaching themselves to `S-left'.
19581 See `org-ctrl-c-ctrl-c-hook' for more information.")
19582 (defvar org-shiftleft-final-hook nil
19583 "Hook for functions attaching themselves to `S-left'.
19584 This one runs after all other options except shift-select have been excluded.
19585 See `org-ctrl-c-ctrl-c-hook' for more information.")
19586 (defvar org-shiftright-hook nil
19587 "Hook for functions attaching themselves to `S-right'.
19588 See `org-ctrl-c-ctrl-c-hook' for more information.")
19589 (defvar org-shiftright-final-hook nil
19590 "Hook for functions attaching themselves to `S-right'.
19591 This one runs after all other options except shift-select have been excluded.
19592 See `org-ctrl-c-ctrl-c-hook' for more information.")
19594 (defun org-modifier-cursor-error ()
19595 "Throw an error, a modified cursor command was applied in wrong context."
19596 (user-error "This command is active in special context like tables, headlines or items"))
19598 (defun org-shiftselect-error ()
19599 "Throw an error because Shift-Cursor command was applied in wrong context."
19600 (if (and (boundp 'shift-select-mode) shift-select-mode)
19601 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
19602 (user-error "This command works only in special context like headlines or timestamps")))
19604 (defun org-call-for-shift-select (cmd)
19605 (let ((this-command-keys-shift-translated t))
19606 (call-interactively cmd)))
19608 (defun org-shifttab (&optional arg)
19609 "Global visibility cycling or move to previous table field.
19610 Call `org-table-previous-field' within a table.
19611 When ARG is nil, cycle globally through visibility states.
19612 When ARG is a numeric prefix, show contents of this level."
19613 (interactive "P")
19614 (cond
19615 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19616 ((integerp arg)
19617 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19618 (message "Content view to level: %d" arg)
19619 (org-content (prefix-numeric-value arg2))
19620 (org-cycle-show-empty-lines t)
19621 (setq org-cycle-global-status 'overview)))
19622 (t (call-interactively 'org-global-cycle))))
19624 (defun org-shiftmetaleft ()
19625 "Promote subtree or delete table column.
19626 Calls `org-promote-subtree', `org-outdent-item-tree', or
19627 `org-table-delete-column', depending on context. See the
19628 individual commands for more information."
19629 (interactive)
19630 (cond
19631 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19632 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19633 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19634 ((if (not (org-region-active-p)) (org-at-item-p)
19635 (save-excursion (goto-char (region-beginning))
19636 (org-at-item-p)))
19637 (call-interactively 'org-outdent-item-tree))
19638 (t (org-modifier-cursor-error))))
19640 (defun org-shiftmetaright ()
19641 "Demote subtree or insert table column.
19642 Calls `org-demote-subtree', `org-indent-item-tree', or
19643 `org-table-insert-column', depending on context. See the
19644 individual commands for more information."
19645 (interactive)
19646 (cond
19647 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19648 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19649 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19650 ((if (not (org-region-active-p)) (org-at-item-p)
19651 (save-excursion (goto-char (region-beginning))
19652 (org-at-item-p)))
19653 (call-interactively 'org-indent-item-tree))
19654 (t (org-modifier-cursor-error))))
19656 (defun org-shiftmetaup (&optional _arg)
19657 "Drag the line at point up.
19658 In a table, kill the current row.
19659 On a clock timestamp, update the value of the timestamp like `S-<up>'
19660 but also adjust the previous clocked item in the clock history.
19661 Everywhere else, drag the line at point up."
19662 (interactive "P")
19663 (cond
19664 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19665 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19666 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19667 (call-interactively 'org-timestamp-up)))
19668 (t (call-interactively 'org-drag-line-backward))))
19670 (defun org-shiftmetadown (&optional _arg)
19671 "Drag the line at point down.
19672 In a table, insert an empty row at the current line.
19673 On a clock timestamp, update the value of the timestamp like `S-<down>'
19674 but also adjust the previous clocked item in the clock history.
19675 Everywhere else, drag the line at point down."
19676 (interactive "P")
19677 (cond
19678 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19679 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19680 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19681 (call-interactively 'org-timestamp-down)))
19682 (t (call-interactively 'org-drag-line-forward))))
19684 (defsubst org-hidden-tree-error ()
19685 (user-error
19686 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19688 (defun org-metaleft (&optional _arg)
19689 "Promote heading, list item at point or move table column left.
19691 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
19692 depending on context. With no specific context, calls the Emacs
19693 default `backward-word'. See the individual commands for more
19694 information.
19696 This function runs the hook `org-metaleft-hook' as a first step,
19697 and returns at first non-nil value."
19698 (interactive "P")
19699 (cond
19700 ((run-hook-with-args-until-success 'org-metaleft-hook))
19701 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19702 ((org-with-limited-levels
19703 (or (org-at-heading-p)
19704 (and (org-region-active-p)
19705 (save-excursion
19706 (goto-char (region-beginning))
19707 (org-at-heading-p)))))
19708 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19709 (call-interactively 'org-do-promote))
19710 ;; At an inline task.
19711 ((org-at-heading-p)
19712 (call-interactively 'org-inlinetask-promote))
19713 ((or (org-at-item-p)
19714 (and (org-region-active-p)
19715 (save-excursion
19716 (goto-char (region-beginning))
19717 (org-at-item-p))))
19718 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19719 (call-interactively 'org-outdent-item))
19720 (t (call-interactively 'backward-word))))
19722 (defun org-metaright (&optional _arg)
19723 "Demote heading, list item at point or move table column right.
19725 In front of a drawer or a block keyword, indent it correctly.
19727 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
19728 `org-indent-drawer' or `org-indent-block' depending on context.
19729 With no specific context, calls the Emacs default `forward-word'.
19730 See the individual commands for more information.
19732 This function runs the hook `org-metaright-hook' as a first step,
19733 and returns at first non-nil value."
19734 (interactive "P")
19735 (cond
19736 ((run-hook-with-args-until-success 'org-metaright-hook))
19737 ((org-at-table-p) (call-interactively 'org-table-move-column))
19738 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19739 ((org-at-block-p) (call-interactively 'org-indent-block))
19740 ((org-with-limited-levels
19741 (or (org-at-heading-p)
19742 (and (org-region-active-p)
19743 (save-excursion
19744 (goto-char (region-beginning))
19745 (org-at-heading-p)))))
19746 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19747 (call-interactively 'org-do-demote))
19748 ;; At an inline task.
19749 ((org-at-heading-p)
19750 (call-interactively 'org-inlinetask-demote))
19751 ((or (org-at-item-p)
19752 (and (org-region-active-p)
19753 (save-excursion
19754 (goto-char (region-beginning))
19755 (org-at-item-p))))
19756 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19757 (call-interactively 'org-indent-item))
19758 (t (call-interactively 'forward-word))))
19760 (defun org-check-for-hidden (what)
19761 "Check if there are hidden headlines/items in the current visual line.
19762 WHAT can be either `headlines' or `items'. If the current line is
19763 an outline or item heading and it has a folded subtree below it,
19764 this function returns t, nil otherwise."
19765 (let ((re (cond
19766 ((eq what 'headlines) org-outline-regexp-bol)
19767 ((eq what 'items) (org-item-beginning-re))
19768 (t (error "This should not happen"))))
19769 beg end)
19770 (save-excursion
19771 (catch 'exit
19772 (unless (org-region-active-p)
19773 (setq beg (point-at-bol))
19774 (beginning-of-line 2)
19775 (while (and (not (eobp)) ;; this is like `next-line'
19776 (get-char-property (1- (point)) 'invisible))
19777 (beginning-of-line 2))
19778 (setq end (point))
19779 (goto-char beg)
19780 (goto-char (point-at-eol))
19781 (setq end (max end (point)))
19782 (while (re-search-forward re end t)
19783 (when (get-char-property (match-beginning 0) 'invisible)
19784 (throw 'exit t))))
19785 nil))))
19787 (defun org-metaup (&optional _arg)
19788 "Move subtree up or move table row up.
19789 Calls `org-move-subtree-up' or `org-table-move-row' or
19790 `org-move-item-up', depending on context. See the individual commands
19791 for more information."
19792 (interactive "P")
19793 (cond
19794 ((run-hook-with-args-until-success 'org-metaup-hook))
19795 ((org-region-active-p)
19796 (let* ((a (save-excursion
19797 (goto-char (min (region-beginning) (region-end)))
19798 (line-beginning-position)))
19799 (b (save-excursion
19800 (goto-char (max (region-beginning) (region-end)))
19801 (if (bolp) (1- (point)) (line-end-position))))
19802 (c (save-excursion
19803 (goto-char a)
19804 (move-beginning-of-line 0)
19805 (point)))
19806 (d (save-excursion
19807 (goto-char a)
19808 (move-end-of-line 0)
19809 (point))))
19810 (transpose-regions a b c d)
19811 (goto-char c)))
19812 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19813 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19814 ((org-at-item-p) (call-interactively 'org-move-item-up))
19815 (t (org-drag-element-backward))))
19817 (defun org-metadown (&optional _arg)
19818 "Move subtree down or move table row down.
19819 Calls `org-move-subtree-down' or `org-table-move-row' or
19820 `org-move-item-down', depending on context. See the individual
19821 commands for more information."
19822 (interactive "P")
19823 (cond
19824 ((run-hook-with-args-until-success 'org-metadown-hook))
19825 ((org-region-active-p)
19826 (let* ((a (save-excursion
19827 (goto-char (min (region-beginning) (region-end)))
19828 (line-beginning-position)))
19829 (b (save-excursion
19830 (goto-char (max (region-beginning) (region-end)))
19831 (if (bolp) (1- (point)) (line-end-position))))
19832 (c (save-excursion
19833 (goto-char b)
19834 (move-beginning-of-line (if (bolp) 1 2))
19835 (point)))
19836 (d (save-excursion
19837 (goto-char b)
19838 (move-end-of-line (if (bolp) 1 2))
19839 (point))))
19840 (transpose-regions a b c d)
19841 (goto-char d)))
19842 ((org-at-table-p) (call-interactively 'org-table-move-row))
19843 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19844 ((org-at-item-p) (call-interactively 'org-move-item-down))
19845 (t (org-drag-element-forward))))
19847 (defun org-shiftup (&optional arg)
19848 "Increase item in timestamp or increase priority of current headline.
19849 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19850 depending on context. See the individual commands for more information."
19851 (interactive "P")
19852 (cond
19853 ((run-hook-with-args-until-success 'org-shiftup-hook))
19854 ((and org-support-shift-select (org-region-active-p))
19855 (org-call-for-shift-select 'previous-line))
19856 ((org-at-timestamp-p 'lax)
19857 (call-interactively (if org-edit-timestamp-down-means-later
19858 'org-timestamp-down 'org-timestamp-up)))
19859 ((and (not (eq org-support-shift-select 'always))
19860 org-enable-priority-commands
19861 (org-at-heading-p))
19862 (call-interactively 'org-priority-up))
19863 ((and (not org-support-shift-select) (org-at-item-p))
19864 (call-interactively 'org-previous-item))
19865 ((org-clocktable-try-shift 'up arg))
19866 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19867 (org-support-shift-select
19868 (org-call-for-shift-select 'previous-line))
19869 (t (org-shiftselect-error))))
19871 (defun org-shiftdown (&optional arg)
19872 "Decrease item in timestamp or decrease priority of current headline.
19873 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19874 depending on context. See the individual commands for more information."
19875 (interactive "P")
19876 (cond
19877 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19878 ((and org-support-shift-select (org-region-active-p))
19879 (org-call-for-shift-select 'next-line))
19880 ((org-at-timestamp-p 'lax)
19881 (call-interactively (if org-edit-timestamp-down-means-later
19882 'org-timestamp-up 'org-timestamp-down)))
19883 ((and (not (eq org-support-shift-select 'always))
19884 org-enable-priority-commands
19885 (org-at-heading-p))
19886 (call-interactively 'org-priority-down))
19887 ((and (not org-support-shift-select) (org-at-item-p))
19888 (call-interactively 'org-next-item))
19889 ((org-clocktable-try-shift 'down arg))
19890 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19891 (org-support-shift-select
19892 (org-call-for-shift-select 'next-line))
19893 (t (org-shiftselect-error))))
19895 (defun org-shiftright (&optional arg)
19896 "Cycle the thing at point or in the current line, depending on context.
19897 Depending on context, this does one of the following:
19899 - switch a timestamp at point one day into the future
19900 - on a headline, switch to the next TODO keyword.
19901 - on an item, switch entire list to the next bullet type
19902 - on a property line, switch to the next allowed value
19903 - on a clocktable definition line, move time block into the future"
19904 (interactive "P")
19905 (cond
19906 ((run-hook-with-args-until-success 'org-shiftright-hook))
19907 ((and org-support-shift-select (org-region-active-p))
19908 (org-call-for-shift-select 'forward-char))
19909 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
19910 ((and (not (eq org-support-shift-select 'always))
19911 (org-at-heading-p))
19912 (let ((org-inhibit-logging
19913 (not org-treat-S-cursor-todo-selection-as-state-change))
19914 (org-inhibit-blocking
19915 (not org-treat-S-cursor-todo-selection-as-state-change)))
19916 (org-call-with-arg 'org-todo 'right)))
19917 ((or (and org-support-shift-select
19918 (not (eq org-support-shift-select 'always))
19919 (org-at-item-bullet-p))
19920 (and (not org-support-shift-select) (org-at-item-p)))
19921 (org-call-with-arg 'org-cycle-list-bullet nil))
19922 ((and (not (eq org-support-shift-select 'always))
19923 (org-at-property-p))
19924 (call-interactively 'org-property-next-allowed-value))
19925 ((org-clocktable-try-shift 'right arg))
19926 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19927 (org-support-shift-select
19928 (org-call-for-shift-select 'forward-char))
19929 (t (org-shiftselect-error))))
19931 (defun org-shiftleft (&optional arg)
19932 "Cycle the thing at point or in the current line, depending on context.
19933 Depending on context, this does one of the following:
19935 - switch a timestamp at point one day into the past
19936 - on a headline, switch to the previous TODO keyword.
19937 - on an item, switch entire list to the previous bullet type
19938 - on a property line, switch to the previous allowed value
19939 - on a clocktable definition line, move time block into the past"
19940 (interactive "P")
19941 (cond
19942 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19943 ((and org-support-shift-select (org-region-active-p))
19944 (org-call-for-shift-select 'backward-char))
19945 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
19946 ((and (not (eq org-support-shift-select 'always))
19947 (org-at-heading-p))
19948 (let ((org-inhibit-logging
19949 (not org-treat-S-cursor-todo-selection-as-state-change))
19950 (org-inhibit-blocking
19951 (not org-treat-S-cursor-todo-selection-as-state-change)))
19952 (org-call-with-arg 'org-todo 'left)))
19953 ((or (and org-support-shift-select
19954 (not (eq org-support-shift-select 'always))
19955 (org-at-item-bullet-p))
19956 (and (not org-support-shift-select) (org-at-item-p)))
19957 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19958 ((and (not (eq org-support-shift-select 'always))
19959 (org-at-property-p))
19960 (call-interactively 'org-property-previous-allowed-value))
19961 ((org-clocktable-try-shift 'left arg))
19962 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19963 (org-support-shift-select
19964 (org-call-for-shift-select 'backward-char))
19965 (t (org-shiftselect-error))))
19967 (defun org-shiftcontrolright ()
19968 "Switch to next TODO set."
19969 (interactive)
19970 (cond
19971 ((and org-support-shift-select (org-region-active-p))
19972 (org-call-for-shift-select 'forward-word))
19973 ((and (not (eq org-support-shift-select 'always))
19974 (org-at-heading-p))
19975 (org-call-with-arg 'org-todo 'nextset))
19976 (org-support-shift-select
19977 (org-call-for-shift-select 'forward-word))
19978 (t (org-shiftselect-error))))
19980 (defun org-shiftcontrolleft ()
19981 "Switch to previous TODO set."
19982 (interactive)
19983 (cond
19984 ((and org-support-shift-select (org-region-active-p))
19985 (org-call-for-shift-select 'backward-word))
19986 ((and (not (eq org-support-shift-select 'always))
19987 (org-at-heading-p))
19988 (org-call-with-arg 'org-todo 'previousset))
19989 (org-support-shift-select
19990 (org-call-for-shift-select 'backward-word))
19991 (t (org-shiftselect-error))))
19993 (defun org-shiftcontrolup (&optional n)
19994 "Change timestamps synchronously up in CLOCK log lines.
19995 Optional argument N tells to change by that many units."
19996 (interactive "P")
19997 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
19998 (let (org-support-shift-select)
19999 (org-clock-timestamps-up n))
20000 (user-error "Not at a clock log")))
20002 (defun org-shiftcontroldown (&optional n)
20003 "Change timestamps synchronously down in CLOCK log lines.
20004 Optional argument N tells to change by that many units."
20005 (interactive "P")
20006 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20007 (let (org-support-shift-select)
20008 (org-clock-timestamps-down n))
20009 (user-error "Not at a clock log")))
20011 (defun org-increase-number-at-point (&optional inc)
20012 "Increment the number at point.
20013 With an optional prefix numeric argument INC, increment using
20014 this numeric value."
20015 (interactive "p")
20016 (if (not (number-at-point))
20017 (user-error "Not on a number")
20018 (unless inc (setq inc 1))
20019 (let ((pos (point))
20020 (beg (skip-chars-backward "-+^/*0-9eE."))
20021 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20022 (setq nap (buffer-substring-no-properties
20023 (+ pos beg) (+ pos beg end)))
20024 (delete-region (+ pos beg) (+ pos beg end))
20025 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20026 (when (org-at-table-p)
20027 (org-table-align)
20028 (org-table-end-of-field 1))))
20030 (defun org-decrease-number-at-point (&optional inc)
20031 "Decrement the number at point.
20032 With an optional prefix numeric argument INC, decrement using
20033 this numeric value."
20034 (interactive "p")
20035 (org-increase-number-at-point (- (or inc 1))))
20037 (defun org-ctrl-c-ret ()
20038 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20039 (interactive)
20040 (cond
20041 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20042 (t (call-interactively 'org-insert-heading))))
20044 (defun org-find-visible ()
20045 (let ((s (point)))
20046 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20047 (get-char-property s 'invisible)))
20049 (defun org-find-invisible ()
20050 (let ((s (point)))
20051 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20052 (not (get-char-property s 'invisible))))
20055 (defun org-copy-visible (beg end)
20056 "Copy the visible parts of the region."
20057 (interactive "r")
20058 (let ((result ""))
20059 (while (/= beg end)
20060 (when (get-char-property beg 'invisible)
20061 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20062 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20063 (setq result (concat result (buffer-substring beg next)))
20064 (setq beg next)))
20065 (setq deactivate-mark t)
20066 (kill-new result)
20067 (message "Visible strings have been copied to the kill ring.")))
20069 (defun org-copy-special ()
20070 "Copy region in table or copy current subtree.
20071 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20072 context. See the individual commands for more information."
20073 (interactive)
20074 (call-interactively
20075 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20077 (defun org-cut-special ()
20078 "Cut region in table or cut current subtree.
20079 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20080 context. See the individual commands for more information."
20081 (interactive)
20082 (call-interactively
20083 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20085 (defun org-paste-special (arg)
20086 "Paste rectangular region into table, or past subtree relative to level.
20087 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20088 See the individual commands for more information."
20089 (interactive "P")
20090 (if (org-at-table-p)
20091 (org-table-paste-rectangle)
20092 (org-paste-subtree arg)))
20094 (defun org-edit-special (&optional arg)
20095 "Call a special editor for the element at point.
20096 When at a table, call the formula editor with `org-table-edit-formulas'.
20097 When in a source code block, call `org-edit-src-code'.
20098 When in a fixed-width region, call `org-edit-fixed-width-region'.
20099 When in an export block, call `org-edit-export-block'.
20100 When in a LaTeX environment, call `org-edit-latex-environment'.
20101 When at an #+INCLUDE keyword, visit the included file.
20102 When at a footnote reference, call `org-edit-footnote-reference'.
20103 When at an active timestamp, call `org-time-stamp'.
20104 When at an inactive timestamp, call `org-time-stamp-inactive'.
20105 On a link, call `ffap' to visit the link at point.
20106 Otherwise, return a user error."
20107 (interactive "P")
20108 (let ((element (org-element-at-point)))
20109 (barf-if-buffer-read-only)
20110 (pcase (org-element-type element)
20111 (`src-block
20112 (if (not arg) (org-edit-src-code)
20113 (let* ((info (org-babel-get-src-block-info))
20114 (lang (nth 0 info))
20115 (params (nth 2 info))
20116 (session (cdr (assq :session params))))
20117 (if (not session) (org-edit-src-code)
20118 ;; At a src-block with a session and function called with
20119 ;; an ARG: switch to the buffer related to the inferior
20120 ;; process.
20121 (switch-to-buffer
20122 (funcall (intern (concat "org-babel-prep-session:" lang))
20123 session params))))))
20124 (`keyword
20125 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20126 (org-open-link-from-string
20127 (format "[[%s]]"
20128 (expand-file-name
20129 (let ((value (org-element-property :value element)))
20130 (cond ((org-file-url-p value)
20131 (user-error "The file is specified as a URL, cannot be edited"))
20132 ((not (org-string-nw-p value))
20133 (user-error "No file to edit"))
20134 ((string-match "\\`\"\\(.*?\\)\"" value)
20135 (match-string 1 value))
20136 ((string-match "\\`[^ \t\"]\\S-*" value)
20137 (match-string 0 value))
20138 (t (user-error "No valid file specified")))))))
20139 (user-error "No special environment to edit here")))
20140 (`table
20141 (if (eq (org-element-property :type element) 'table.el)
20142 (org-edit-table.el)
20143 (call-interactively 'org-table-edit-formulas)))
20144 ;; Only Org tables contain `table-row' type elements.
20145 (`table-row (call-interactively 'org-table-edit-formulas))
20146 (`example-block (org-edit-src-code))
20147 (`export-block (org-edit-export-block))
20148 (`fixed-width (org-edit-fixed-width-region))
20149 (`latex-environment (org-edit-latex-environment))
20151 ;; No notable element at point. Though, we may be at a link or
20152 ;; a footnote reference, which are objects. Thus, scan deeper.
20153 (let ((context (org-element-context element)))
20154 (pcase (org-element-type context)
20155 (`footnote-reference (org-edit-footnote-reference))
20156 (`inline-src-block (org-edit-inline-src-code))
20157 (`timestamp (if (eq 'inactive (org-element-property :type context))
20158 (call-interactively #'org-time-stamp-inactive)
20159 (call-interactively #'org-time-stamp)))
20160 (`link (call-interactively #'ffap))
20161 (_ (user-error "No special environment to edit here"))))))))
20163 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20164 (defun org-ctrl-c-ctrl-c (&optional arg)
20165 "Set tags in headline, or update according to changed information at point.
20167 This command does many different things, depending on context:
20169 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20170 this is what we do.
20172 - If the cursor is on a statistics cookie, update it.
20174 - If the cursor is in a headline, prompt for tags and insert them
20175 into the current line, aligned to `org-tags-column'. When called
20176 with prefix arg, realign all tags in the current buffer.
20178 - If the cursor is in one of the special #+KEYWORD lines, this
20179 triggers scanning the buffer for these lines and updating the
20180 information.
20182 - If the cursor is inside a table, realign the table. This command
20183 works even if the automatic table editor has been turned off.
20185 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20186 the entire table.
20188 - If the cursor is at a footnote reference or definition, jump to
20189 the corresponding definition or references, respectively.
20191 - If the cursor is a the beginning of a dynamic block, update it.
20193 - If the current buffer is a capture buffer, close note and file it.
20195 - If the cursor is on a <<<target>>>, update radio targets and
20196 corresponding links in this buffer.
20198 - If the cursor is on a numbered item in a plain list, renumber the
20199 ordered list.
20201 - If the cursor is on a checkbox, toggle it.
20203 - If the cursor is on a code block, evaluate it. The variable
20204 `org-confirm-babel-evaluate' can be used to control prompting
20205 before code block evaluation, by default every code block
20206 evaluation requires confirmation. Code block evaluation can be
20207 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20208 (interactive "P")
20209 (cond
20210 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20211 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20212 (org-remove-occur-highlights)
20213 (message "Temporary highlights/overlays removed from current buffer"))
20214 ((and (local-variable-p 'org-finish-function)
20215 (fboundp org-finish-function))
20216 (funcall org-finish-function))
20217 ((org-babel-hash-at-point))
20218 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20220 (let* ((context
20221 (org-element-lineage
20222 (org-element-context)
20223 ;; Limit to supported contexts.
20224 '(babel-call clock dynamic-block footnote-definition
20225 footnote-reference inline-babel-call inline-src-block
20226 inlinetask item keyword node-property paragraph
20227 plain-list planning property-drawer radio-target
20228 src-block statistics-cookie table table-cell table-row
20229 timestamp)
20231 (type (org-element-type context)))
20232 ;; For convenience: at the first line of a paragraph on the same
20233 ;; line as an item, apply function on that item instead.
20234 (when (eq type 'paragraph)
20235 (let ((parent (org-element-property :parent context)))
20236 (when (and (eq (org-element-type parent) 'item)
20237 (= (line-beginning-position)
20238 (org-element-property :begin parent)))
20239 (setq context parent)
20240 (setq type 'item))))
20241 ;; Act according to type of element or object at point.
20243 ;; Do nothing on a blank line, except if it is contained in
20244 ;; a source block. Hence, we first check if point is in such
20245 ;; a block and then if it is at a blank line.
20246 (pcase type
20247 ((or `inline-src-block `src-block)
20248 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20249 (org-babel-eval-wipe-error-buffer)
20250 (org-babel-execute-src-block
20251 current-prefix-arg (org-babel-get-src-block-info nil context))))
20252 ((guard (org-match-line "[ \t]*$"))
20253 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20254 (user-error
20255 (substitute-command-keys
20256 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20257 ((or `babel-call `inline-babel-call)
20258 (let ((info (org-babel-lob-get-info context)))
20259 (when info (org-babel-execute-src-block nil info))))
20260 (`clock (org-clock-update-time-maybe))
20261 (`dynamic-block
20262 (save-excursion
20263 (goto-char (org-element-property :post-affiliated context))
20264 (org-update-dblock)))
20265 (`footnote-definition
20266 (goto-char (org-element-property :post-affiliated context))
20267 (call-interactively 'org-footnote-action))
20268 (`footnote-reference (call-interactively #'org-footnote-action))
20269 ((or `headline `inlinetask)
20270 (save-excursion (goto-char (org-element-property :begin context))
20271 (call-interactively #'org-set-tags-command)))
20272 (`item
20273 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20274 ;; unconditionally, whereas `C-u' will toggle its presence.
20275 ;; Without a universal argument, if the item has a checkbox,
20276 ;; toggle it. Otherwise repair the list.
20277 (let* ((box (org-element-property :checkbox context))
20278 (struct (org-element-property :structure context))
20279 (old-struct (copy-tree struct))
20280 (parents (org-list-parents-alist struct))
20281 (prevs (org-list-prevs-alist struct))
20282 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20283 (org-list-set-checkbox
20284 (org-element-property :begin context) struct
20285 (cond ((equal arg '(16)) "[-]")
20286 ((and (not box) (equal arg '(4))) "[ ]")
20287 ((or (not box) (equal arg '(4))) nil)
20288 ((eq box 'on) "[ ]")
20289 (t "[X]")))
20290 ;; Mimic `org-list-write-struct' but with grabbing a return
20291 ;; value from `org-list-struct-fix-box'.
20292 (org-list-struct-fix-ind struct parents 2)
20293 (org-list-struct-fix-item-end struct)
20294 (org-list-struct-fix-bul struct prevs)
20295 (org-list-struct-fix-ind struct parents)
20296 (let ((block-item
20297 (org-list-struct-fix-box struct parents prevs orderedp)))
20298 (if (and box (equal struct old-struct))
20299 (if (equal arg '(16))
20300 (message "Checkboxes already reset")
20301 (user-error "Cannot toggle this checkbox: %s"
20302 (if (eq box 'on)
20303 "all subitems checked"
20304 "unchecked subitems")))
20305 (org-list-struct-apply-struct struct old-struct)
20306 (org-update-checkbox-count-maybe))
20307 (when block-item
20308 (message "Checkboxes were removed due to empty box at line %d"
20309 (org-current-line block-item))))))
20310 (`keyword
20311 (let ((org-inhibit-startup-visibility-stuff t)
20312 (org-startup-align-all-tables nil))
20313 (when (boundp 'org-table-coordinate-overlays)
20314 (mapc #'delete-overlay org-table-coordinate-overlays)
20315 (setq org-table-coordinate-overlays nil))
20316 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20317 (message "Local setup has been refreshed"))
20318 (`plain-list
20319 ;; At a plain list, with a double C-u argument, set
20320 ;; checkboxes of each item to "[-]", whereas a single one
20321 ;; will toggle their presence according to the state of the
20322 ;; first item in the list. Without an argument, repair the
20323 ;; list.
20324 (let* ((begin (org-element-property :contents-begin context))
20325 (struct (org-element-property :structure context))
20326 (old-struct (copy-tree struct))
20327 (first-box (save-excursion
20328 (goto-char begin)
20329 (looking-at org-list-full-item-re)
20330 (match-string-no-properties 3)))
20331 (new-box (cond ((equal arg '(16)) "[-]")
20332 ((equal arg '(4)) (unless first-box "[ ]"))
20333 ((equal first-box "[X]") "[ ]")
20334 (t "[X]"))))
20335 (cond
20336 (arg
20337 (dolist (pos
20338 (org-list-get-all-items
20339 begin struct (org-list-prevs-alist struct)))
20340 (org-list-set-checkbox pos struct new-box)))
20341 ((and first-box (eq (point) begin))
20342 ;; For convenience, when point is at bol on the first
20343 ;; item of the list and no argument is provided, simply
20344 ;; toggle checkbox of that item, if any.
20345 (org-list-set-checkbox begin struct new-box)))
20346 (when (equal
20347 (org-list-write-struct
20348 struct (org-list-parents-alist struct) old-struct)
20349 old-struct)
20350 (message "Cannot update this checkbox"))
20351 (org-update-checkbox-count-maybe)))
20352 ((or `property-drawer `node-property)
20353 (call-interactively #'org-property-action))
20354 (`radio-target
20355 (call-interactively #'org-update-radio-target-regexp))
20356 (`statistics-cookie
20357 (call-interactively #'org-update-statistics-cookies))
20358 ((or `table `table-cell `table-row)
20359 ;; At a table, recalculate every field and align it. Also
20360 ;; send the table if necessary. If the table has
20361 ;; a `table.el' type, just give up. At a table row or cell,
20362 ;; maybe recalculate line but always align table.
20363 (if (eq (org-element-property :type context) 'table.el)
20364 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20365 Use `\\[org-edit-special]' to edit table.el tables"))
20366 (if (or (eq type 'table)
20367 ;; Check if point is at a TBLFM line.
20368 (and (eq type 'table-row)
20369 (= (point) (org-element-property :end context))))
20370 (save-excursion
20371 (if (org-at-TBLFM-p)
20372 (progn (require 'org-table)
20373 (org-table-calc-current-TBLFM))
20374 (goto-char (org-element-property :contents-begin context))
20375 (org-call-with-arg 'org-table-recalculate (or arg t))
20376 (orgtbl-send-table 'maybe)))
20377 (org-table-maybe-eval-formula)
20378 (cond (arg (call-interactively #'org-table-recalculate))
20379 ((org-table-maybe-recalculate-line))
20380 (t (org-table-align))))))
20381 ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
20382 (org-timestamp-change 0 'day))
20383 ((and `nil (guard (org-at-heading-p)))
20384 ;; When point is on an unsupported object type, we can miss
20385 ;; the fact that it also is at a heading. Handle it here.
20386 (call-interactively #'org-set-tags-command))
20387 ((guard
20388 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20390 (user-error
20391 (substitute-command-keys
20392 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20394 (defun org-mode-restart ()
20395 (interactive)
20396 (let ((indent-status (bound-and-true-p org-indent-mode)))
20397 (funcall major-mode)
20398 (hack-local-variables)
20399 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20400 (org-indent-mode -1))
20401 (org-reset-file-cache))
20402 (message "%s restarted" major-mode))
20404 (defun org-kill-note-or-show-branches ()
20405 "Abort storing current note, or call `outline-show-branches'."
20406 (interactive)
20407 (if (not org-finish-function)
20408 (save-excursion
20409 (save-restriction
20410 (org-narrow-to-subtree)
20411 (org-flag-subtree t)
20412 (call-interactively 'outline-show-branches)
20413 (org-hide-archived-subtrees (point-min) (point-max))))
20414 (let ((org-note-abort t))
20415 (funcall org-finish-function))))
20417 (defun org-delete-indentation (&optional arg)
20418 "Join current line to previous and fix whitespace at join.
20420 If previous line is a headline add to headline title. Otherwise
20421 the function calls `delete-indentation'.
20423 With a non-nil optional argument, join it to the following one."
20424 (interactive "*P")
20425 (if (save-excursion
20426 (beginning-of-line (if arg 1 0))
20427 (let ((case-fold-search nil))
20428 (looking-at org-complex-heading-regexp)))
20429 ;; At headline.
20430 (let ((tags-column (when (match-beginning 5)
20431 (save-excursion (goto-char (match-beginning 5))
20432 (current-column))))
20433 (string (concat " " (progn (when arg (forward-line 1))
20434 (org-trim (delete-and-extract-region
20435 (line-beginning-position)
20436 (line-end-position)))))))
20437 (unless (bobp) (delete-region (point) (1- (point))))
20438 (goto-char (or (match-end 4)
20439 (match-beginning 5)
20440 (match-end 0)))
20441 (skip-chars-backward " \t")
20442 (save-excursion (insert string))
20443 ;; Adjust alignment of tags.
20444 (cond
20445 ((not tags-column)) ;no tags
20446 (org-auto-align-tags (org-align-tags))
20447 (t (org--align-tags-here tags-column)))) ;preserve tags column
20448 (delete-indentation arg)))
20450 (defun org-open-line (n)
20451 "Insert a new row in tables, call `open-line' elsewhere.
20452 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20453 As a special case, when a document starts with a table, allow to
20454 call `open-line' on the very first character."
20455 (interactive "*p")
20456 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20457 (org-table-insert-row)
20458 (open-line n)))
20460 (defun org-return (&optional indent)
20461 "Goto next table row or insert a newline.
20463 Calls `org-table-next-row' or `newline', depending on context.
20465 When optional INDENT argument is non-nil, call
20466 `newline-and-indent' instead of `newline'.
20468 When `org-return-follows-link' is non-nil and point is on
20469 a timestamp or a link, call `org-open-at-point'. However, it
20470 will not happen if point is in a table or on a \"dead\"
20471 object (e.g., within a comment). In these case, you need to use
20472 `org-open-at-point' directly."
20473 (interactive)
20474 (let ((context (if org-return-follows-link (org-element-context)
20475 (org-element-at-point))))
20476 (cond
20477 ;; In a table, call `org-table-next-row'. However, before first
20478 ;; column or after last one, split the table.
20479 ((or (and (eq (org-element-type context) 'table)
20480 (>= (point) (org-element-property :contents-begin context))
20481 (< (point) (org-element-property :contents-end context)))
20482 (org-element-lineage context '(table-row table-cell) t))
20483 (if (or (looking-at-p "[ \t]*$")
20484 (save-excursion (skip-chars-backward " \t") (bolp)))
20485 (insert "\n")
20486 (org-table-justify-field-maybe)
20487 (call-interactively #'org-table-next-row)))
20488 ;; On a link or a timestamp, call `org-open-at-point' if
20489 ;; `org-return-follows-link' allows it. Tolerate fuzzy
20490 ;; locations, e.g., in a comment, as `org-open-at-point'.
20491 ((and org-return-follows-link
20492 (or (and (eq 'link (org-element-type context))
20493 ;; Ensure point is not on the white spaces after
20494 ;; the link.
20495 (let ((origin (point)))
20496 (org-with-point-at (org-element-property :end context)
20497 (skip-chars-backward " \t")
20498 (> (point) origin))))
20499 (org-in-regexp org-ts-regexp-both nil t)
20500 (org-in-regexp org-tsr-regexp-both nil t)
20501 (org-in-regexp org-any-link-re nil t)))
20502 (call-interactively #'org-open-at-point))
20503 ;; Insert newline in heading, but preserve tags.
20504 ((and (not (bolp))
20505 (save-excursion (beginning-of-line)
20506 (let ((case-fold-search nil))
20507 (looking-at org-complex-heading-regexp))))
20508 ;; At headline. Split line. However, if point is on keyword,
20509 ;; priority cookie or tags, do not break any of them: add
20510 ;; a newline after the headline instead.
20511 (let ((tags-column (and (match-beginning 5)
20512 (save-excursion (goto-char (match-beginning 5))
20513 (current-column))))
20514 (string
20515 (when (and (match-end 4) (org-point-in-group (point) 4))
20516 (delete-and-extract-region (point) (match-end 4)))))
20517 ;; Adjust tag alignment.
20518 (cond
20519 ((not (and tags-column string)))
20520 (org-auto-align-tags (org-align-tags))
20521 (t (org--align-tags-here tags-column))) ;preserve tags column
20522 (end-of-line)
20523 (org-show-entry)
20524 (if indent (newline-and-indent) (newline))
20525 (when string (save-excursion (insert (org-trim string))))))
20526 ;; In a list, make sure indenting keeps trailing text within.
20527 ((and indent
20528 (not (eolp))
20529 (org-element-lineage context '(item)))
20530 (let ((trailing-data
20531 (delete-and-extract-region (point) (line-end-position))))
20532 (newline-and-indent)
20533 (save-excursion (insert trailing-data))))
20535 ;; Do not auto-fill when point is in an Org property drawer.
20536 (let ((auto-fill-function (and (not (org-at-property-p))
20537 auto-fill-function)))
20538 (if indent
20539 (newline-and-indent)
20540 (newline)))))))
20542 (defun org-return-indent ()
20543 "Goto next table row or insert a newline and indent.
20544 Calls `org-table-next-row' or `newline-and-indent', depending on
20545 context. See the individual commands for more information."
20546 (interactive)
20547 (org-return t))
20549 (defun org-ctrl-c-tab (&optional _arg)
20550 "Toggle columns width in a table, or show children.
20551 Call `org-table-toggle-column-width' if point is in a table.
20552 Otherwise, call `org-show-children'."
20553 (interactive "p")
20554 (call-interactively
20555 (if (org-at-table-p) #'org-table-toggle-column-width
20556 #'org-show-children)))
20558 (defun org-ctrl-c-star ()
20559 "Compute table, or change heading status of lines.
20560 Calls `org-table-recalculate' or `org-toggle-heading',
20561 depending on context."
20562 (interactive)
20563 (cond
20564 ((org-at-table-p)
20565 (call-interactively 'org-table-recalculate))
20567 ;; Convert all lines in region to list items
20568 (call-interactively 'org-toggle-heading))))
20570 (defun org-ctrl-c-minus ()
20571 "Insert separator line in table or modify bullet status of line.
20572 Also turns a plain line or a region of lines into list items.
20573 Calls `org-table-insert-hline', `org-toggle-item', or
20574 `org-cycle-list-bullet', depending on context."
20575 (interactive)
20576 (cond
20577 ((org-at-table-p)
20578 (call-interactively 'org-table-insert-hline))
20579 ((org-region-active-p)
20580 (call-interactively 'org-toggle-item))
20581 ((org-in-item-p)
20582 (call-interactively 'org-cycle-list-bullet))
20584 (call-interactively 'org-toggle-item))))
20586 (defun org-toggle-heading (&optional nstars)
20587 "Convert headings to normal text, or items or text to headings.
20588 If there is no active region, only convert the current line.
20590 With a `\\[universal-argument]' prefix, convert the whole list at
20591 point into heading.
20593 In a region:
20595 - If the first non blank line is a headline, remove the stars
20596 from all headlines in the region.
20598 - If it is a normal line, turn each and every normal line (i.e.,
20599 not an heading or an item) in the region into headings. If you
20600 want to convert only the first line of this region, use one
20601 universal prefix argument.
20603 - If it is a plain list item, turn all plain list items into headings.
20605 When converting a line into a heading, the number of stars is chosen
20606 such that the lines become children of the current entry. However,
20607 when a numeric prefix argument is given, its value determines the
20608 number of stars to add."
20609 (interactive "P")
20610 (let ((skip-blanks
20611 (function
20612 ;; Return beginning of first non-blank line, starting from
20613 ;; line at POS.
20614 (lambda (pos)
20615 (save-excursion
20616 (goto-char pos)
20617 (while (org-at-comment-p) (forward-line))
20618 (skip-chars-forward " \r\t\n")
20619 (point-at-bol)))))
20620 beg end toggled)
20621 ;; Determine boundaries of changes. If a universal prefix has
20622 ;; been given, put the list in a region. If region ends at a bol,
20623 ;; do not consider the last line to be in the region.
20625 (when (and current-prefix-arg (org-at-item-p))
20626 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
20627 (org-mark-element))
20629 (if (org-region-active-p)
20630 (setq beg (funcall skip-blanks (region-beginning))
20631 end (copy-marker (save-excursion
20632 (goto-char (region-end))
20633 (if (bolp) (point) (point-at-eol)))))
20634 (setq beg (funcall skip-blanks (point-at-bol))
20635 end (copy-marker (point-at-eol))))
20636 ;; Ensure inline tasks don't count as headings.
20637 (org-with-limited-levels
20638 (save-excursion
20639 (goto-char beg)
20640 (cond
20641 ;; Case 1. Started at an heading: de-star headings.
20642 ((org-at-heading-p)
20643 (while (< (point) end)
20644 (when (org-at-heading-p t)
20645 (looking-at org-outline-regexp) (replace-match "")
20646 (setq toggled t))
20647 (forward-line)))
20648 ;; Case 2. Started at an item: change items into headlines.
20649 ;; One star will be added by `org-list-to-subtree'.
20650 ((org-at-item-p)
20651 (while (< (point) end)
20652 (when (org-at-item-p)
20653 ;; Pay attention to cases when region ends before list.
20654 (let* ((struct (org-list-struct))
20655 (list-end
20656 (min (org-list-get-bottom-point struct) (1+ end))))
20657 (save-restriction
20658 (narrow-to-region (point) list-end)
20659 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
20660 (setq toggled t))
20661 (forward-line)))
20662 ;; Case 3. Started at normal text: make every line an heading,
20663 ;; skipping headlines and items.
20664 (t (let* ((stars
20665 (make-string
20666 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20667 (add-stars
20668 (cond (nstars "") ; stars from prefix only
20669 ((equal stars "") "*") ; before first heading
20670 (org-odd-levels-only "**") ; inside heading, odd
20671 (t "*"))) ; inside heading, oddeven
20672 (rpl (concat stars add-stars " "))
20673 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
20674 (while (< (point) (if (equal nstars '(4)) lend end))
20675 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20676 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20677 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20678 (forward-line)))))))
20679 (unless toggled (message "Cannot toggle heading from here"))))
20681 (defun org-meta-return (&optional arg)
20682 "Insert a new heading or wrap a region in a table.
20683 Calls `org-insert-heading', `org-insert-item' or
20684 `org-table-wrap-region', depending on context. When called with
20685 an argument, unconditionally call `org-insert-heading'."
20686 (interactive "P")
20687 (org-check-before-invisible-edit 'insert)
20688 (or (run-hook-with-args-until-success 'org-metareturn-hook)
20689 (call-interactively (cond (arg #'org-insert-heading)
20690 ((org-at-table-p) #'org-table-wrap-region)
20691 ((org-in-item-p) #'org-insert-item)
20692 (t #'org-insert-heading)))))
20694 ;;; Menu entries
20696 (defsubst org-in-subtree-not-table-p ()
20697 "Are we in a subtree and not in a table?"
20698 (and (not (org-before-first-heading-p))
20699 (not (org-at-table-p))))
20701 ;; Define the Org mode menus
20702 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20703 '("Tbl"
20704 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20705 ["Next Field" org-cycle (org-at-table-p)]
20706 ["Previous Field" org-shifttab (org-at-table-p)]
20707 ["Next Row" org-return (org-at-table-p)]
20708 "--"
20709 ["Blank Field" org-table-blank-field (org-at-table-p)]
20710 ["Edit Field" org-table-edit-field (org-at-table-p)]
20711 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20712 "--"
20713 ("Column"
20714 ["Move Column Left" org-metaleft (org-at-table-p)]
20715 ["Move Column Right" org-metaright (org-at-table-p)]
20716 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20717 ["Insert Column" org-shiftmetaright (org-at-table-p)]
20718 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
20719 ("Row"
20720 ["Move Row Up" org-metaup (org-at-table-p)]
20721 ["Move Row Down" org-metadown (org-at-table-p)]
20722 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20723 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20724 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20725 "--"
20726 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20727 ("Rectangle"
20728 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20729 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20730 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20731 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20732 "--"
20733 ("Calculate"
20734 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20735 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20736 ["Edit Formulas" org-edit-special (org-at-table-p)]
20737 "--"
20738 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20739 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20740 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20741 "--"
20742 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20743 "--"
20744 ["Sum Column/Rectangle" org-table-sum
20745 (or (org-at-table-p) (org-region-active-p))]
20746 ["Which Column?" org-table-current-column (org-at-table-p)])
20747 ["Debug Formulas"
20748 org-table-toggle-formula-debugger
20749 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
20750 ["Show Col/Row Numbers"
20751 org-table-toggle-coordinate-overlays
20752 :style toggle
20753 :selected (bound-and-true-p org-table-overlay-coordinates)]
20754 "--"
20755 ["Create" org-table-create (not (org-at-table-p))]
20756 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20757 ["Import from File" org-table-import (not (org-at-table-p))]
20758 ["Export to File" org-table-export (org-at-table-p)]
20759 "--"
20760 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
20761 "--"
20762 ("Plot"
20763 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
20764 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
20766 (easy-menu-define org-org-menu org-mode-map "Org menu"
20767 '("Org"
20768 ("Show/Hide"
20769 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20770 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20771 ["Sparse Tree..." org-sparse-tree t]
20772 ["Reveal Context" org-reveal t]
20773 ["Show All" org-show-all t]
20774 "--"
20775 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20776 "--"
20777 ["New Heading" org-insert-heading t]
20778 ("Navigate Headings"
20779 ["Up" outline-up-heading t]
20780 ["Next" outline-next-visible-heading t]
20781 ["Previous" outline-previous-visible-heading t]
20782 ["Next Same Level" outline-forward-same-level t]
20783 ["Previous Same Level" outline-backward-same-level t]
20784 "--"
20785 ["Jump" org-goto t])
20786 ("Edit Structure"
20787 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20788 "--"
20789 ["Move Subtree Up" org-metaup (org-at-heading-p)]
20790 ["Move Subtree Down" org-metadown (org-at-heading-p)]
20791 "--"
20792 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20793 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20794 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20795 "--"
20796 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20797 "--"
20798 ["Copy visible text" org-copy-visible t]
20799 "--"
20800 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20801 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20802 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20803 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20804 "--"
20805 ["Sort Region/Children" org-sort t]
20806 "--"
20807 ["Convert to odd levels" org-convert-to-odd-levels t]
20808 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20809 ("Editing"
20810 ["Emphasis..." org-emphasize t]
20811 ["Edit Source Example" org-edit-special t]
20812 "--"
20813 ["Footnote new/jump" org-footnote-action t]
20814 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20815 ("Archive"
20816 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20817 "--"
20818 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
20819 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20820 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20822 "--"
20823 ("Hyperlinks"
20824 ["Store Link (Global)" org-store-link t]
20825 ["Find existing link to here" org-occur-link-in-agenda-files t]
20826 ["Insert Link" org-insert-link t]
20827 ["Follow Link" org-open-at-point t]
20828 "--"
20829 ["Next link" org-next-link t]
20830 ["Previous link" org-previous-link t]
20831 "--"
20832 ["Descriptive Links"
20833 org-toggle-link-display
20834 :style radio
20835 :selected org-descriptive-links
20837 ["Literal Links"
20838 org-toggle-link-display
20839 :style radio
20840 :selected (not org-descriptive-links)])
20841 "--"
20842 ("TODO Lists"
20843 ["TODO/DONE/-" org-todo t]
20844 ("Select keyword"
20845 ["Next keyword" org-shiftright (org-at-heading-p)]
20846 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20847 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20848 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20849 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20850 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20851 ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
20852 "--"
20853 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20854 :selected org-enforce-todo-dependencies :style toggle :active t]
20855 "Settings for tree at point"
20856 ["Do Children sequentially" org-toggle-ordered-property :style radio
20857 :selected (org-entry-get nil "ORDERED")
20858 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20859 ["Do Children parallel" org-toggle-ordered-property :style radio
20860 :selected (not (org-entry-get nil "ORDERED"))
20861 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20862 "--"
20863 ["Set Priority" org-priority t]
20864 ["Priority Up" org-shiftup t]
20865 ["Priority Down" org-shiftdown t]
20866 "--"
20867 ["Get news from all feeds" org-feed-update-all t]
20868 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20869 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20870 ("TAGS and Properties"
20871 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20872 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20873 "--"
20874 ["Set property" org-set-property (not (org-before-first-heading-p))]
20875 ["Column view of properties" org-columns t]
20876 ["Insert Column View DBlock" org-columns-insert-dblock t])
20877 ("Dates and Scheduling"
20878 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20879 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20880 ("Change Date"
20881 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
20882 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
20883 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
20884 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
20885 ["Compute Time Range" org-evaluate-time-range t]
20886 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20887 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20888 "--"
20889 ["Custom time format" org-toggle-time-stamp-overlays
20890 :style radio :selected org-display-custom-times]
20891 "--"
20892 ["Goto Calendar" org-goto-calendar t]
20893 ["Date from Calendar" org-date-from-calendar t]
20894 "--"
20895 ["Start/Restart Timer" org-timer-start t]
20896 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20897 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20898 ["Insert Timer String" org-timer t]
20899 ["Insert Timer Item" org-timer-item t])
20900 ("Logging work"
20901 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20902 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20903 ["Clock out" org-clock-out t]
20904 ["Clock cancel" org-clock-cancel t]
20905 "--"
20906 ["Mark as default task" org-clock-mark-default-task t]
20907 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20908 ["Goto running clock" org-clock-goto t]
20909 "--"
20910 ["Display times" org-clock-display t]
20911 ["Create clock table" org-clock-report t]
20912 "--"
20913 ["Record DONE time"
20914 (progn (setq org-log-done (not org-log-done))
20915 (message "Switching to %s will %s record a timestamp"
20916 (car org-done-keywords)
20917 (if org-log-done "automatically" "not")))
20918 :style toggle :selected org-log-done])
20919 "--"
20920 ["Agenda Command..." org-agenda t]
20921 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20922 ("File List for Agenda")
20923 ("Special views current file"
20924 ["TODO Tree" org-show-todo-tree t]
20925 ["Check Deadlines" org-check-deadlines t]
20926 ["Tags/Property tree" org-match-sparse-tree t])
20927 "--"
20928 ["Export/Publish..." org-export-dispatch t]
20929 ("LaTeX"
20930 ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
20931 :style toggle :selected org-cdlatex-mode]
20932 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20933 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20934 ["Modify math symbol" org-cdlatex-math-modify
20935 (org-inside-LaTeX-fragment-p)]
20936 ["Insert citation" org-reftex-citation t])
20937 "--"
20938 ("MobileOrg"
20939 ["Push Files and Views" org-mobile-push t]
20940 ["Get Captured and Flagged" org-mobile-pull t]
20941 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "\\[org-agenda] ?"]
20942 "--"
20943 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20944 "--"
20945 ("Documentation"
20946 ["Show Version" org-version t]
20947 ["Info Documentation" org-info t]
20948 ["Browse Org News" org-browse-news t])
20949 ("Customize"
20950 ["Browse Org Group" org-customize t]
20951 "--"
20952 ["Expand This Menu" org-create-customize-menu
20953 (fboundp 'customize-menu-create)])
20954 ["Send bug report" org-submit-bug-report t]
20955 "--"
20956 ("Refresh/Reload"
20957 ["Refresh setup current buffer" org-mode-restart t]
20958 ["Reload Org (after update)" org-reload t]
20959 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
20961 (defun org-info (&optional node)
20962 "Read documentation for Org in the info system.
20963 With optional NODE, go directly to that node."
20964 (interactive)
20965 (info (format "(org)%s" (or node ""))))
20967 (defun org-browse-news ()
20968 "Browse the news for the latest major release."
20969 (interactive)
20970 (browse-url "https://orgmode.org/Changes.html"))
20972 ;;;###autoload
20973 (defun org-submit-bug-report ()
20974 "Submit a bug report on Org via mail.
20976 Don't hesitate to report any problems or inaccurate documentation.
20978 If you don't have setup sending mail from (X)Emacs, please copy the
20979 output buffer into your mail program, as it gives us important
20980 information about your Org version and configuration."
20981 (interactive)
20982 (require 'reporter)
20983 (defvar reporter-prompt-for-summary-p)
20984 (org-load-modules-maybe)
20985 (org-require-autoloaded-modules)
20986 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20987 (reporter-submit-bug-report
20988 "emacs-orgmode@gnu.org"
20989 (org-version nil 'full)
20990 (let (list)
20991 (save-window-excursion
20992 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20993 (delete-other-windows)
20994 (erase-buffer)
20995 (insert "You are about to submit a bug report to the Org mailing list.
20997 We would like to add your full Org and Outline configuration to the
20998 bug report. This greatly simplifies the work of the maintainer and
20999 other experts on the mailing list.
21001 HOWEVER, some variables you have customized may contain private
21002 information. The names of customers, colleagues, or friends, might
21003 appear in the form of file names, tags, todo states, or search strings.
21004 If you answer yes to the prompt, you might want to check and remove
21005 such private information before sending the email.")
21006 (add-text-properties (point-min) (point-max) '(face org-warning))
21007 (when (yes-or-no-p "Include your Org configuration ")
21008 (mapatoms
21009 (lambda (v)
21010 (and (boundp v)
21011 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21012 (or (and (symbol-value v)
21013 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21014 (and
21015 (get v 'custom-type) (get v 'standard-value)
21016 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21017 (push v list)))))
21018 (kill-buffer (get-buffer "*Warn about privacy*"))
21019 list))
21020 nil nil
21021 "Remember to cover the basics, that is, what you expected to happen and
21022 what in fact did happen. You don't know how to make a good report? See
21024 https://orgmode.org/manual/Feedback.html#Feedback
21026 Your bug report will be posted to the Org mailing list.
21027 ------------------------------------------------------------------------")
21028 (save-excursion
21029 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21030 (replace-match "\\1Bug: \\3 [\\2]")))))
21033 (defun org-install-agenda-files-menu ()
21034 (let ((bl (buffer-list)))
21035 (save-excursion
21036 (while bl
21037 (set-buffer (pop bl))
21038 (when (derived-mode-p 'org-mode) (setq bl nil)))
21039 (when (derived-mode-p 'org-mode)
21040 (easy-menu-change
21041 '("Org") "File List for Agenda"
21042 (append
21043 (list
21044 ["Edit File List" (org-edit-agenda-file-list) t]
21045 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21046 ["Remove Current File from List" org-remove-file t]
21047 ["Cycle through agenda files" org-cycle-agenda-files t]
21048 ["Occur in all agenda files" org-occur-in-agenda-files t]
21049 "--")
21050 (mapcar 'org-file-menu-entry
21051 ;; Prevent initialization from failing.
21052 (ignore-errors (org-agenda-files t)))))))))
21054 ;;;; Documentation
21056 (defun org-require-autoloaded-modules ()
21057 (interactive)
21058 (mapc #'require
21059 '(org-agenda org-archive org-attach org-clock org-colview org-id
21060 org-table org-timer)))
21062 ;;;###autoload
21063 (defun org-reload (&optional uncompiled)
21064 "Reload all Org Lisp files.
21065 With prefix arg UNCOMPILED, load the uncompiled versions."
21066 (interactive "P")
21067 (require 'loadhist)
21068 (let* ((org-dir (org-find-library-dir "org"))
21069 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21070 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21071 (remove-re (format "\\`%s\\'"
21072 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21073 (feats (delete-dups
21074 (mapcar 'file-name-sans-extension
21075 (mapcar 'file-name-nondirectory
21076 (delq nil
21077 (mapcar 'feature-file
21078 features))))))
21079 (lfeat (append
21080 (sort
21081 (setq feats
21082 (delq nil (mapcar
21083 (lambda (f)
21084 (if (and (string-match feature-re f)
21085 (not (string-match remove-re f)))
21086 f nil))
21087 feats)))
21088 'string-lessp)
21089 (list "org-version" "org")))
21090 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21091 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21092 load-uncore load-misses)
21093 (setq load-misses
21094 (delq 't
21095 (mapcar (lambda (f)
21096 (or (org-load-noerror-mustsuffix (concat org-dir f))
21097 (and (string= org-dir contrib-dir)
21098 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21099 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21100 (add-to-list 'load-uncore f 'append)
21103 lfeat)))
21104 (when load-uncore
21105 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21106 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21107 (if load-misses
21108 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21109 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21110 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21112 ;;;###autoload
21113 (defun org-customize ()
21114 "Call the customize function with org as argument."
21115 (interactive)
21116 (org-load-modules-maybe)
21117 (org-require-autoloaded-modules)
21118 (customize-browse 'org))
21120 (defun org-create-customize-menu ()
21121 "Create a full customization menu for Org mode, insert it into the menu."
21122 (interactive)
21123 (org-load-modules-maybe)
21124 (org-require-autoloaded-modules)
21125 (if (fboundp 'customize-menu-create)
21126 (progn
21127 (easy-menu-change
21128 '("Org") "Customize"
21129 `(["Browse Org group" org-customize t]
21130 "--"
21131 ,(customize-menu-create 'org)
21132 ["Set" Custom-set t]
21133 ["Save" Custom-save t]
21134 ["Reset to Current" Custom-reset-current t]
21135 ["Reset to Saved" Custom-reset-saved t]
21136 ["Reset to Standard Settings" Custom-reset-standard t]))
21137 (message "\"Org\"-menu now contains full customization menu"))
21138 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21140 ;;;; Miscellaneous stuff
21142 ;;; Generally useful functions
21144 (defun org-link-display-format (s)
21145 "Replace links in string S with their description.
21146 If there is no description, use the link target."
21147 (save-match-data
21148 (replace-regexp-in-string
21149 org-bracket-link-analytic-regexp
21150 (lambda (m)
21151 (if (match-end 5) (match-string 5 m)
21152 (concat (match-string 1 m) (match-string 3 m))))
21153 s nil t)))
21155 (defun org-toggle-link-display ()
21156 "Toggle the literal or descriptive display of links."
21157 (interactive)
21158 (if org-descriptive-links
21159 (remove-from-invisibility-spec '(org-link))
21160 (add-to-invisibility-spec '(org-link)))
21161 (org-restart-font-lock)
21162 (setq org-descriptive-links (not org-descriptive-links)))
21164 (defun org-in-clocktable-p ()
21165 "Check if the cursor is in a clocktable."
21166 (let ((pos (point)) start)
21167 (save-excursion
21168 (end-of-line 1)
21169 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21170 (setq start (match-beginning 0))
21171 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21172 (>= (match-end 0) pos)
21173 start))))
21175 (defun org-in-verbatim-emphasis ()
21176 (save-match-data
21177 (and (org-in-regexp org-verbatim-re 2)
21178 (>= (point) (match-beginning 3))
21179 (<= (point) (match-end 4)))))
21181 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21182 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21183 (if (and marker (marker-buffer marker)
21184 (buffer-live-p (marker-buffer marker)))
21185 (progn
21186 (pop-to-buffer-same-window (marker-buffer marker))
21187 (when (or (> marker (point-max)) (< marker (point-min)))
21188 (widen))
21189 (goto-char marker)
21190 (org-show-context 'org-goto))
21191 (if bookmark
21192 (bookmark-jump bookmark)
21193 (error "Cannot find location"))))
21195 (defun org-quote-csv-field (s)
21196 "Quote field for inclusion in CSV material."
21197 (if (string-match "[\",]" s)
21198 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21201 (defun org-force-self-insert (N)
21202 "Needed to enforce self-insert under remapping."
21203 (interactive "p")
21204 (self-insert-command N))
21206 (defun org-fill-template (template alist)
21207 "Find each %key of ALIST in TEMPLATE and replace it."
21208 (let ((case-fold-search nil))
21209 (dolist (entry (sort (copy-sequence alist)
21210 (lambda (a b) (< (length (car a)) (length (car b))))))
21211 (setq template
21212 (replace-regexp-in-string
21213 (concat "%" (regexp-quote (car entry)))
21214 (or (cdr entry) "") template t t)))
21215 template))
21217 (defun org-quote-vert (s)
21218 "Replace \"|\" with \"\\vert\"."
21219 (while (string-match "|" s)
21220 (setq s (replace-match "\\vert" t t s)))
21223 (defun org-uuidgen-p (s)
21224 "Is S an ID created by UUIDGEN?"
21225 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21227 (defun org-in-src-block-p (&optional inside)
21228 "Whether point is in a code source block.
21229 When INSIDE is non-nil, don't consider we are within a source
21230 block when point is at #+BEGIN_SRC or #+END_SRC."
21231 (let ((case-fold-search t))
21232 (or (and (eq (get-char-property (point) 'src-block) t))
21233 (and (not inside)
21234 (save-match-data
21235 (save-excursion
21236 (beginning-of-line)
21237 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21239 (defun org-context ()
21240 "Return a list of contexts of the current cursor position.
21241 If several contexts apply, all are returned.
21242 Each context entry is a list with a symbol naming the context, and
21243 two positions indicating start and end of the context. Possible
21244 contexts are:
21246 :headline anywhere in a headline
21247 :headline-stars on the leading stars in a headline
21248 :todo-keyword on a TODO keyword (including DONE) in a headline
21249 :tags on the TAGS in a headline
21250 :priority on the priority cookie in a headline
21251 :item on the first line of a plain list item
21252 :item-bullet on the bullet/number of a plain list item
21253 :checkbox on the checkbox in a plain list item
21254 :table in an Org table
21255 :table-special on a special filed in a table
21256 :table-table in a table.el table
21257 :clocktable in a clocktable
21258 :src-block in a source block
21259 :link on a hyperlink
21260 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21261 :target on a <<target>>
21262 :radio-target on a <<<radio-target>>>
21263 :latex-fragment on a LaTeX fragment
21264 :latex-preview on a LaTeX fragment with overlaid preview image
21266 This function expects the position to be visible because it uses font-lock
21267 faces as a help to recognize the following contexts: :table-special, :link,
21268 and :keyword."
21269 (let* ((f (get-text-property (point) 'face))
21270 (faces (if (listp f) f (list f)))
21271 (case-fold-search t)
21272 (p (point)) clist o)
21273 ;; First the large context
21274 (cond
21275 ((org-at-heading-p t)
21276 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21277 (when (progn
21278 (beginning-of-line 1)
21279 (looking-at org-todo-line-tags-regexp))
21280 (push (org-point-in-group p 1 :headline-stars) clist)
21281 (push (org-point-in-group p 2 :todo-keyword) clist)
21282 (push (org-point-in-group p 4 :tags) clist))
21283 (goto-char p)
21284 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21285 (when (looking-at "\\[#[A-Z0-9]\\]")
21286 (push (org-point-in-group p 0 :priority) clist)))
21288 ((org-at-item-p)
21289 (push (org-point-in-group p 2 :item-bullet) clist)
21290 (push (list :item (point-at-bol)
21291 (save-excursion (org-end-of-item) (point)))
21292 clist)
21293 (and (org-at-item-checkbox-p)
21294 (push (org-point-in-group p 0 :checkbox) clist)))
21296 ((org-at-table-p)
21297 (push (list :table (org-table-begin) (org-table-end)) clist)
21298 (when (memq 'org-formula faces)
21299 (push (list :table-special
21300 (previous-single-property-change p 'face)
21301 (next-single-property-change p 'face)) clist)))
21302 ((org-at-table-p 'any)
21303 (push (list :table-table) clist)))
21304 (goto-char p)
21306 (let ((case-fold-search t))
21307 ;; New the "medium" contexts: clocktables, source blocks
21308 (cond ((org-in-clocktable-p)
21309 (push (list :clocktable
21310 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21311 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21312 (match-beginning 1))
21313 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21314 (match-end 0))) clist))
21315 ((org-in-src-block-p)
21316 (push (list :src-block
21317 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21318 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21319 (match-beginning 1))
21320 (and (search-forward "#+END_SRC" nil t)
21321 (match-beginning 0))) clist))))
21322 (goto-char p)
21324 ;; Now the small context
21325 (cond
21326 ((org-at-timestamp-p)
21327 (push (org-point-in-group p 0 :timestamp) clist))
21328 ((memq 'org-link faces)
21329 (push (list :link
21330 (previous-single-property-change p 'face)
21331 (next-single-property-change p 'face)) clist))
21332 ((memq 'org-special-keyword faces)
21333 (push (list :keyword
21334 (previous-single-property-change p 'face)
21335 (next-single-property-change p 'face)) clist))
21336 ((org-at-target-p)
21337 (push (org-point-in-group p 0 :target) clist)
21338 (goto-char (1- (match-beginning 0)))
21339 (when (looking-at org-radio-target-regexp)
21340 (push (org-point-in-group p 0 :radio-target) clist))
21341 (goto-char p))
21342 ((setq o (cl-some
21343 (lambda (o)
21344 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
21346 (overlays-at (point))))
21347 (push (list :latex-fragment
21348 (overlay-start o) (overlay-end o)) clist)
21349 (push (list :latex-preview
21350 (overlay-start o) (overlay-end o)) clist))
21351 ((org-inside-LaTeX-fragment-p)
21352 ;; FIXME: positions wrong.
21353 (push (list :latex-fragment (point) (point)) clist)))
21355 (setq clist (nreverse (delq nil clist)))
21356 clist))
21358 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21359 "Non-nil when point is between matches of START-RE and END-RE.
21361 Also return a non-nil value when point is on one of the matches.
21363 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21364 buffer positions. Default values are the positions of headlines
21365 surrounding the point.
21367 The functions returns a cons cell whose car (resp. cdr) is the
21368 position before START-RE (resp. after END-RE)."
21369 (save-match-data
21370 (let ((pos (point))
21371 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21372 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21373 beg end)
21374 (save-excursion
21375 ;; Point is on a block when on START-RE or if START-RE can be
21376 ;; found before it...
21377 (and (or (org-in-regexp start-re)
21378 (re-search-backward start-re limit-up t))
21379 (setq beg (match-beginning 0))
21380 ;; ... and END-RE after it...
21381 (goto-char (match-end 0))
21382 (re-search-forward end-re limit-down t)
21383 (> (setq end (match-end 0)) pos)
21384 ;; ... without another START-RE in-between.
21385 (goto-char (match-beginning 0))
21386 (not (re-search-backward start-re (1+ beg) t))
21387 ;; Return value.
21388 (cons beg end))))))
21390 (defun org-in-block-p (names)
21391 "Non-nil when point belongs to a block whose name belongs to NAMES.
21393 NAMES is a list of strings containing names of blocks.
21395 Return first block name matched, or nil. Beware that in case of
21396 nested blocks, the returned name may not belong to the closest
21397 block from point."
21398 (save-match-data
21399 (catch 'exit
21400 (let ((case-fold-search t)
21401 (lim-up (save-excursion (outline-previous-heading)))
21402 (lim-down (save-excursion (outline-next-heading))))
21403 (dolist (name names)
21404 (let ((n (regexp-quote name)))
21405 (when (org-between-regexps-p
21406 (concat "^[ \t]*#\\+begin_" n)
21407 (concat "^[ \t]*#\\+end_" n)
21408 lim-up lim-down)
21409 (throw 'exit n)))))
21410 nil)))
21412 (defun org-occur-in-agenda-files (regexp &optional _nlines)
21413 "Call `multi-occur' with buffers for all agenda files."
21414 (interactive "sOrg-files matching: ")
21415 (let* ((files (org-agenda-files))
21416 (tnames (mapcar #'file-truename files))
21417 (extra org-agenda-text-search-extra-files))
21418 (when (eq (car extra) 'agenda-archives)
21419 (setq extra (cdr extra))
21420 (setq files (org-add-archive-files files)))
21421 (dolist (f extra)
21422 (unless (member (file-truename f) tnames)
21423 (unless (member f files) (setq files (append files (list f))))
21424 (setq tnames (append tnames (list (file-truename f))))))
21425 (multi-occur
21426 (mapcar (lambda (x)
21427 (with-current-buffer
21428 ;; FIXME: Why not just (find-file-noselect x)?
21429 ;; Is it to avoid the "revert buffer" prompt?
21430 (or (get-file-buffer x) (find-file-noselect x))
21431 (widen)
21432 (current-buffer)))
21433 files)
21434 regexp)))
21436 (add-hook 'occur-mode-find-occurrence-hook
21437 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
21439 (defun org-occur-link-in-agenda-files ()
21440 "Create a link and search for it in the agendas.
21441 The link is not stored in `org-stored-links', it is just created
21442 for the search purpose."
21443 (interactive)
21444 (let ((link (condition-case nil
21445 (org-store-link nil)
21446 (error "Unable to create a link to here"))))
21447 (org-occur-in-agenda-files (regexp-quote link))))
21449 (defun org-back-over-empty-lines ()
21450 "Move backwards over whitespace, to the beginning of the first empty line.
21451 Returns the number of empty lines passed."
21452 (let ((pos (point)))
21453 (if (cdr (assq 'heading org-blank-before-new-entry))
21454 (skip-chars-backward " \t\n\r")
21455 (unless (eobp)
21456 (forward-line -1)))
21457 (beginning-of-line 2)
21458 (goto-char (min (point) pos))
21459 (count-lines (point) pos)))
21461 (defun org-replace-escapes (string table)
21462 "Replace %-escapes in STRING with values in TABLE.
21463 TABLE is an association list with keys like \"%a\" and string values.
21464 The sequences in STRING may contain normal field width and padding information,
21465 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21466 so values can contain further %-escapes if they are define later in TABLE."
21467 (let ((tbl (copy-alist table))
21468 (case-fold-search nil)
21469 (pchg 0)
21470 re rpl)
21471 (dolist (e tbl)
21472 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21473 (when (and (cdr e) (string-match re (cdr e)))
21474 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21475 (safe "SREF"))
21476 (add-text-properties 0 3 (list 'sref sref) safe)
21477 (setcdr e (replace-match safe t t (cdr e)))))
21478 (while (string-match re string)
21479 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21480 (cdr e)))
21481 (setq string (replace-match rpl t t string))))
21482 (while (setq pchg (next-property-change pchg string))
21483 (let ((sref (get-text-property pchg 'sref string)))
21484 (when (and sref (string-match "SREF" string pchg))
21485 (setq string (replace-match sref t t string)))))
21486 string))
21488 ;;; TODO: Only called once, from ox-odt which should probably use
21489 ;;; org-export-inline-image-p or something.
21490 (defun org-file-image-p (file)
21491 "Return non-nil if FILE is an image."
21492 (save-match-data
21493 (string-match (image-file-name-regexp) file)))
21495 (defun org-get-cursor-date (&optional with-time)
21496 "Return the date at cursor in as a time.
21497 This works in the calendar and in the agenda, anywhere else it just
21498 returns the current time.
21499 If WITH-TIME is non-nil, returns the time of the event at point (in
21500 the agenda) or the current time of the day."
21501 (let (date day defd tp hod mod)
21502 (when with-time
21503 (setq tp (get-text-property (point) 'time))
21504 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21505 (setq hod (string-to-number (match-string 1 tp))
21506 mod (string-to-number (match-string 2 tp))))
21507 (or tp (let ((now (decode-time)))
21508 (setq hod (nth 2 now)
21509 mod (nth 1 now)))))
21510 (cond
21511 ((eq major-mode 'calendar-mode)
21512 (setq date (calendar-cursor-to-date)
21513 defd (encode-time 0 (or mod 0) (or hod 0)
21514 (nth 1 date) (nth 0 date) (nth 2 date))))
21515 ((eq major-mode 'org-agenda-mode)
21516 (setq day (get-text-property (point) 'day))
21517 (when day
21518 (setq date (calendar-gregorian-from-absolute day)
21519 defd (encode-time 0 (or mod 0) (or hod 0)
21520 (nth 1 date) (nth 0 date) (nth 2 date))))))
21521 (or defd (current-time))))
21523 (defun org-mark-subtree (&optional up)
21524 "Mark the current subtree.
21525 This puts point at the start of the current subtree, and mark at
21526 the end. If a numeric prefix UP is given, move up into the
21527 hierarchy of headlines by UP levels before marking the subtree."
21528 (interactive "P")
21529 (org-with-limited-levels
21530 (cond ((org-at-heading-p) (beginning-of-line))
21531 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21532 (t (outline-previous-visible-heading 1))))
21533 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
21534 (if (called-interactively-p 'any)
21535 (call-interactively 'org-mark-element)
21536 (org-mark-element)))
21538 ;;; Indentation
21540 (defvar org-element-greater-elements)
21541 (defun org--get-expected-indentation (element contentsp)
21542 "Expected indentation column for current line, according to ELEMENT.
21543 ELEMENT is an element containing point. CONTENTSP is non-nil
21544 when indentation is to be computed according to contents of
21545 ELEMENT."
21546 (let ((type (org-element-type element))
21547 (start (org-element-property :begin element))
21548 (post-affiliated (org-element-property :post-affiliated element)))
21549 (org-with-wide-buffer
21550 (cond
21551 (contentsp
21552 (cl-case type
21553 ((diary-sexp footnote-definition) 0)
21554 ((headline inlinetask nil)
21555 (if (not org-adapt-indentation) 0
21556 (let ((level (org-current-level)))
21557 (if level (1+ level) 0))))
21558 ((item plain-list) (org-list-item-body-column post-affiliated))
21560 (goto-char start)
21561 (current-indentation))))
21562 ((memq type '(headline inlinetask nil))
21563 (if (org-match-line "[ \t]*$")
21564 (org--get-expected-indentation element t)
21566 ((memq type '(diary-sexp footnote-definition)) 0)
21567 ;; First paragraph of a footnote definition or an item.
21568 ;; Indent like parent.
21569 ((< (line-beginning-position) start)
21570 (org--get-expected-indentation
21571 (org-element-property :parent element) t))
21572 ;; At first line: indent according to previous sibling, if any,
21573 ;; ignoring footnote definitions and inline tasks, or parent's
21574 ;; contents.
21575 ((= (line-beginning-position) start)
21576 (catch 'exit
21577 (while t
21578 (if (= (point-min) start) (throw 'exit 0)
21579 (goto-char (1- start))
21580 (let* ((previous (org-element-at-point))
21581 (parent previous))
21582 (while (and parent (<= (org-element-property :end parent) start))
21583 (setq previous parent
21584 parent (org-element-property :parent parent)))
21585 (cond
21586 ((not previous) (throw 'exit 0))
21587 ((> (org-element-property :end previous) start)
21588 (throw 'exit (org--get-expected-indentation previous t)))
21589 ((memq (org-element-type previous)
21590 '(footnote-definition inlinetask))
21591 (setq start (org-element-property :begin previous)))
21592 (t (goto-char (org-element-property :begin previous))
21593 (throw 'exit
21594 (if (bolp) (current-indentation)
21595 ;; At first paragraph in an item or
21596 ;; a footnote definition.
21597 (org--get-expected-indentation
21598 (org-element-property :parent previous) t))))))))))
21599 ;; Otherwise, move to the first non-blank line above.
21601 (beginning-of-line)
21602 (let ((pos (point)))
21603 (skip-chars-backward " \r\t\n")
21604 (cond
21605 ;; Two blank lines end a footnote definition or a plain
21606 ;; list. When we indent an empty line after them, the
21607 ;; containing list or footnote definition is over, so it
21608 ;; qualifies as a previous sibling. Therefore, we indent
21609 ;; like its first line.
21610 ((and (memq type '(footnote-definition plain-list))
21611 (> (count-lines (point) pos) 2))
21612 (goto-char start)
21613 (current-indentation))
21614 ;; Line above is the first one of a paragraph at the
21615 ;; beginning of an item or a footnote definition. Indent
21616 ;; like parent.
21617 ((< (line-beginning-position) start)
21618 (org--get-expected-indentation
21619 (org-element-property :parent element) t))
21620 ;; Line above is the beginning of an element, i.e., point
21621 ;; was originally on the blank lines between element's start
21622 ;; and contents.
21623 ((= (line-beginning-position) post-affiliated)
21624 (org--get-expected-indentation element t))
21625 ;; POS is after contents in a greater element. Indent like
21626 ;; the beginning of the element.
21627 ((and (memq type org-element-greater-elements)
21628 (let ((cend (org-element-property :contents-end element)))
21629 (and cend (<= cend pos))))
21630 ;; As a special case, if point is at the end of a footnote
21631 ;; definition or an item, indent like the very last element
21632 ;; within. If that last element is an item, indent like
21633 ;; its contents.
21634 (if (memq type '(footnote-definition item plain-list))
21635 (let ((last (org-element-at-point)))
21636 (goto-char pos)
21637 (org--get-expected-indentation
21638 last (eq (org-element-type last) 'item)))
21639 (goto-char start)
21640 (current-indentation)))
21641 ;; In any other case, indent like the current line.
21642 (t (current-indentation)))))))))
21644 (defun org--align-node-property ()
21645 "Align node property at point.
21646 Alignment is done according to `org-property-format', which see."
21647 (when (save-excursion
21648 (beginning-of-line)
21649 (looking-at org-property-re))
21650 (replace-match
21651 (concat (match-string 4)
21652 (org-trim
21653 (format org-property-format (match-string 1) (match-string 3))))
21654 t t)))
21656 (defun org-indent-line ()
21657 "Indent line depending on context.
21659 Indentation is done according to the following rules:
21661 - Footnote definitions, diary sexps, headlines and inline tasks
21662 have to start at column 0.
21664 - On the very first line of an element, consider, in order, the
21665 next rules until one matches:
21667 1. If there's a sibling element before, ignoring footnote
21668 definitions and inline tasks, indent like its first line.
21670 2. If element has a parent, indent like its contents. More
21671 precisely, if parent is an item, indent after the
21672 description part, if any, or the bullet (see
21673 `org-list-description-max-indent'). Else, indent like
21674 parent's first line.
21676 3. Otherwise, indent relatively to current level, if
21677 `org-adapt-indentation' is non-nil, or to left margin.
21679 - On a blank line at the end of an element, indent according to
21680 the type of the element. More precisely
21682 1. If element is a plain list, an item, or a footnote
21683 definition, indent like the very last element within.
21685 2. If element is a paragraph, indent like its last non blank
21686 line.
21688 3. Otherwise, indent like its very first line.
21690 - In the code part of a source block, use language major mode
21691 to indent current line if `org-src-tab-acts-natively' is
21692 non-nil. If it is nil, do nothing.
21694 - Otherwise, indent like the first non-blank line above.
21696 The function doesn't indent an item as it could break the whole
21697 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
21698 `\\[org-shiftmetaright]'.
21700 Also align node properties according to `org-property-format'."
21701 (interactive)
21702 (cond
21703 ((org-at-heading-p) 'noindent)
21705 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
21706 (type (org-element-type element)))
21707 (cond ((and (memq type '(plain-list item))
21708 (= (line-beginning-position)
21709 (org-element-property :post-affiliated element)))
21710 'noindent)
21711 ((and (eq type 'latex-environment)
21712 (>= (point) (org-element-property :post-affiliated element))
21713 (< (point) (org-with-wide-buffer
21714 (goto-char (org-element-property :end element))
21715 (skip-chars-backward " \r\t\n")
21716 (line-beginning-position 2))))
21717 'noindent)
21718 ((and (eq type 'src-block)
21719 org-src-tab-acts-natively
21720 (> (line-beginning-position)
21721 (org-element-property :post-affiliated element))
21722 (< (line-beginning-position)
21723 (org-with-wide-buffer
21724 (goto-char (org-element-property :end element))
21725 (skip-chars-backward " \r\t\n")
21726 (line-beginning-position))))
21727 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
21729 (let ((column (org--get-expected-indentation element nil)))
21730 ;; Preserve current column.
21731 (if (<= (current-column) (current-indentation))
21732 (indent-line-to column)
21733 (save-excursion (indent-line-to column))))
21734 ;; Align node property. Also preserve current column.
21735 (when (eq type 'node-property)
21736 (let ((column (current-column)))
21737 (org--align-node-property)
21738 (org-move-to-column column)))))))))
21740 (defun org-indent-region (start end)
21741 "Indent each non-blank line in the region.
21742 Called from a program, START and END specify the region to
21743 indent. The function will not indent contents of example blocks,
21744 verse blocks and export blocks as leading white spaces are
21745 assumed to be significant there."
21746 (interactive "r")
21747 (save-excursion
21748 (goto-char start)
21749 (skip-chars-forward " \r\t\n")
21750 (unless (eobp) (beginning-of-line))
21751 (let ((indent-to
21752 (lambda (ind pos)
21753 ;; Set IND as indentation for all lines between point and
21754 ;; POS. Blank lines are ignored. Leave point after POS
21755 ;; once done.
21756 (let ((limit (copy-marker pos)))
21757 (while (< (point) limit)
21758 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
21759 (forward-line))
21760 (set-marker limit nil))))
21761 (end (copy-marker end)))
21762 (while (< (point) end)
21763 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
21764 (let* ((element (org-element-at-point))
21765 (type (org-element-type element))
21766 (element-end (copy-marker (org-element-property :end element)))
21767 (ind (org--get-expected-indentation element nil)))
21768 (cond
21769 ;; Element indented as a single block. Example blocks
21770 ;; preserving indentation are a special case since the
21771 ;; "contents" must not be indented whereas the block
21772 ;; boundaries can.
21773 ((or (memq type '(export-block latex-environment))
21774 (and (eq type 'example-block)
21775 (not
21776 (or org-src-preserve-indentation
21777 (org-element-property :preserve-indent element)))))
21778 (let ((offset (- ind (current-indentation))))
21779 (unless (zerop offset)
21780 (indent-rigidly (org-element-property :begin element)
21781 (org-element-property :end element)
21782 offset)))
21783 (goto-char element-end))
21784 ;; Elements indented line wise. Be sure to exclude
21785 ;; example blocks (preserving indentation) and source
21786 ;; blocks from this category as they are treated
21787 ;; specially later.
21788 ((or (memq type '(paragraph table table-row))
21789 (not (or (org-element-property :contents-begin element)
21790 (memq type '(example-block src-block)))))
21791 (when (eq type 'node-property)
21792 (org--align-node-property)
21793 (beginning-of-line))
21794 (funcall indent-to ind (min element-end end)))
21795 ;; Elements consisting of three parts: before the
21796 ;; contents, the contents, and after the contents. The
21797 ;; contents are treated specially, according to the
21798 ;; element type, or not indented at all. Other parts are
21799 ;; indented as a single block.
21801 (let* ((post (copy-marker
21802 (org-element-property :post-affiliated element)))
21803 (cbeg
21804 (copy-marker
21805 (cond
21806 ((not (org-element-property :contents-begin element))
21807 ;; Fake contents for source blocks.
21808 (org-with-wide-buffer
21809 (goto-char post)
21810 (line-beginning-position 2)))
21811 ((memq type '(footnote-definition item plain-list))
21812 ;; Contents in these elements could start on
21813 ;; the same line as the beginning of the
21814 ;; element. Make sure we start indenting
21815 ;; from the second line.
21816 (org-with-wide-buffer
21817 (goto-char post)
21818 (end-of-line)
21819 (skip-chars-forward " \r\t\n")
21820 (if (eobp) (point) (line-beginning-position))))
21821 (t (org-element-property :contents-begin element)))))
21822 (cend (copy-marker
21823 (or (org-element-property :contents-end element)
21824 ;; Fake contents for source blocks.
21825 (org-with-wide-buffer
21826 (goto-char element-end)
21827 (skip-chars-backward " \r\t\n")
21828 (line-beginning-position)))
21829 t)))
21830 ;; Do not change items indentation individually as it
21831 ;; might break the list as a whole. On the other
21832 ;; hand, when at a plain list, indent it as a whole.
21833 (cond ((eq type 'plain-list)
21834 (let ((offset (- ind (current-indentation))))
21835 (unless (zerop offset)
21836 (indent-rigidly (org-element-property :begin element)
21837 (org-element-property :end element)
21838 offset))
21839 (goto-char cbeg)))
21840 ((eq type 'item) (goto-char cbeg))
21841 (t (funcall indent-to ind (min cbeg end))))
21842 (when (< (point) end)
21843 (cl-case type
21844 ((example-block verse-block))
21845 (src-block
21846 ;; In a source block, indent source code
21847 ;; according to language major mode, but only if
21848 ;; `org-src-tab-acts-natively' is non-nil.
21849 (when (and (< (point) end) org-src-tab-acts-natively)
21850 (ignore-errors
21851 (org-babel-do-in-edit-buffer
21852 (indent-region (point-min) (point-max))))))
21853 (t (org-indent-region (point) (min cend end))))
21854 (goto-char (min cend end))
21855 (when (< (point) end)
21856 (funcall indent-to ind (min element-end end))))
21857 (set-marker post nil)
21858 (set-marker cbeg nil)
21859 (set-marker cend nil))))
21860 (set-marker element-end nil))))
21861 (set-marker end nil))))
21863 (defun org-indent-drawer ()
21864 "Indent the drawer at point."
21865 (interactive)
21866 (unless (save-excursion
21867 (beginning-of-line)
21868 (looking-at-p org-drawer-regexp))
21869 (user-error "Not at a drawer"))
21870 (let ((element (org-element-at-point)))
21871 (unless (memq (org-element-type element) '(drawer property-drawer))
21872 (user-error "Not at a drawer"))
21873 (org-with-wide-buffer
21874 (org-indent-region (org-element-property :begin element)
21875 (org-element-property :end element))))
21876 (message "Drawer at point indented"))
21878 (defun org-indent-block ()
21879 "Indent the block at point."
21880 (interactive)
21881 (unless (save-excursion
21882 (beginning-of-line)
21883 (let ((case-fold-search t))
21884 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
21885 (user-error "Not at a block"))
21886 (let ((element (org-element-at-point)))
21887 (unless (memq (org-element-type element)
21888 '(comment-block center-block dynamic-block example-block
21889 export-block quote-block special-block
21890 src-block verse-block))
21891 (user-error "Not at a block"))
21892 (org-with-wide-buffer
21893 (org-indent-region (org-element-property :begin element)
21894 (org-element-property :end element))))
21895 (message "Block at point indented"))
21898 ;;; Filling
21900 ;; We use our own fill-paragraph and auto-fill functions.
21902 ;; `org-fill-paragraph' relies on adaptive filling and context
21903 ;; checking. Appropriate `fill-prefix' is computed with
21904 ;; `org-adaptive-fill-function'.
21906 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21907 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21908 ;; `org-adaptive-fill-function' value. Internally,
21909 ;; `org-comment-line-break-function' breaks the line.
21911 ;; `org-setup-filling' installs filling and auto-filling related
21912 ;; variables during `org-mode' initialization.
21914 (defun org-setup-filling ()
21915 (require 'org-element)
21916 ;; Prevent auto-fill from inserting unwanted new items.
21917 (when (boundp 'fill-nobreak-predicate)
21918 (setq-local
21919 fill-nobreak-predicate
21920 (org-uniquify
21921 (append fill-nobreak-predicate
21922 '(org-fill-line-break-nobreak-p
21923 org-fill-n-macro-as-item-nobreak-p
21924 org-fill-paragraph-with-timestamp-nobreak-p)))))
21925 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
21926 (setq-local paragraph-start paragraph-ending)
21927 (setq-local paragraph-separate paragraph-ending))
21928 (setq-local fill-paragraph-function 'org-fill-paragraph)
21929 (setq-local auto-fill-inhibit-regexp nil)
21930 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
21931 (setq-local normal-auto-fill-function 'org-auto-fill-function)
21932 (setq-local comment-line-break-function 'org-comment-line-break-function))
21934 (defun org-fill-line-break-nobreak-p ()
21935 "Non-nil when a new line at point would create an Org line break."
21936 (save-excursion
21937 (skip-chars-backward "[ \t]")
21938 (skip-chars-backward "\\\\")
21939 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21941 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21942 "Non-nil when a new line at point would split a timestamp."
21943 (and (org-at-timestamp-p 'lax)
21944 (not (looking-at org-ts-regexp-both))))
21946 (defun org-fill-n-macro-as-item-nobreak-p ()
21947 "Non-nil when a new line at point would create a new list."
21948 ;; During export, a "n" macro followed by a dot or a closing
21949 ;; parenthesis can end up being parsed as a new list item.
21950 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
21952 (defvar orgtbl-line-start-regexp) ; From org-table.el
21953 (defun org-adaptive-fill-function ()
21954 "Compute a fill prefix for the current line.
21955 Return fill prefix, as a string, or nil if current line isn't
21956 meant to be filled. For convenience, if `adaptive-fill-regexp'
21957 matches in paragraphs or comments, use it."
21958 (org-with-wide-buffer
21959 (unless (org-at-heading-p)
21960 (let* ((p (line-beginning-position))
21961 (element (save-excursion
21962 (beginning-of-line)
21963 (org-element-at-point)))
21964 (type (org-element-type element))
21965 (post-affiliated (org-element-property :post-affiliated element)))
21966 (unless (< p post-affiliated)
21967 (cl-case type
21968 (comment
21969 (save-excursion
21970 (beginning-of-line)
21971 (looking-at "[ \t]*")
21972 (concat (match-string 0) "# ")))
21973 (footnote-definition "")
21974 ((item plain-list)
21975 (make-string (org-list-item-body-column post-affiliated) ?\s))
21976 (paragraph
21977 ;; Fill prefix is usually the same as the current line,
21978 ;; unless the paragraph is at the beginning of an item.
21979 (let ((parent (org-element-property :parent element)))
21980 (save-excursion
21981 (beginning-of-line)
21982 (cond ((eq (org-element-type parent) 'item)
21983 (make-string (org-list-item-body-column
21984 (org-element-property :begin parent))
21985 ?\s))
21986 ((and adaptive-fill-regexp
21987 ;; Locally disable
21988 ;; `adaptive-fill-function' to let
21989 ;; `fill-context-prefix' handle
21990 ;; `adaptive-fill-regexp' variable.
21991 (let (adaptive-fill-function)
21992 (fill-context-prefix
21993 post-affiliated
21994 (org-element-property :end element)))))
21995 ((looking-at "[ \t]+") (match-string 0))
21996 (t "")))))
21997 (comment-block
21998 ;; Only fill contents if P is within block boundaries.
21999 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22000 (forward-line)
22001 (point)))
22002 (cend (save-excursion
22003 (goto-char (org-element-property :end element))
22004 (skip-chars-backward " \r\t\n")
22005 (line-beginning-position))))
22006 (when (and (>= p cbeg) (< p cend))
22007 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22008 (match-string 0)
22009 ""))))))))))
22011 (defun org-fill-element (&optional justify)
22012 "Fill element at point, when applicable.
22014 This function only applies to comment blocks, comments, example
22015 blocks and paragraphs. Also, as a special case, re-align table
22016 when point is at one.
22018 If JUSTIFY is non-nil (interactively, with prefix argument),
22019 justify as well. If `sentence-end-double-space' is non-nil, then
22020 period followed by one space does not end a sentence, so don't
22021 break a line there. The variable `fill-column' controls the
22022 width for filling.
22024 For convenience, when point is at a plain list, an item or
22025 a footnote definition, try to fill the first paragraph within."
22026 (with-syntax-table org-mode-transpose-word-syntax-table
22027 ;; Move to end of line in order to get the first paragraph within
22028 ;; a plain list or a footnote definition.
22029 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22030 ;; First check if point is in a blank line at the beginning of
22031 ;; the buffer. In that case, ignore filling.
22032 (cl-case (org-element-type element)
22033 ;; Use major mode filling function is source blocks.
22034 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22035 ;; Align Org tables, leave table.el tables as-is.
22036 (table-row (org-table-align) t)
22037 (table
22038 (when (eq (org-element-property :type element) 'org)
22039 (save-excursion
22040 (goto-char (org-element-property :post-affiliated element))
22041 (org-table-align)))
22043 (paragraph
22044 ;; Paragraphs may contain `line-break' type objects.
22045 (let ((beg (max (point-min)
22046 (org-element-property :contents-begin element)))
22047 (end (min (point-max)
22048 (org-element-property :contents-end element))))
22049 ;; Do nothing if point is at an affiliated keyword.
22050 (if (< (line-end-position) beg) t
22051 ;; Fill paragraph, taking line breaks into account.
22052 (save-excursion
22053 (goto-char beg)
22054 (let ((cuts (list beg)))
22055 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22056 (when (eq 'line-break
22057 (org-element-type
22058 (save-excursion (backward-char)
22059 (org-element-context))))
22060 (push (point) cuts)))
22061 (dolist (c (delq end cuts))
22062 (fill-region-as-paragraph c end justify)
22063 (setq end c))))
22064 t)))
22065 ;; Contents of `comment-block' type elements should be
22066 ;; filled as plain text, but only if point is within block
22067 ;; markers.
22068 (comment-block
22069 (let* ((case-fold-search t)
22070 (beg (save-excursion
22071 (goto-char (org-element-property :begin element))
22072 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22073 (forward-line)
22074 (point)))
22075 (end (save-excursion
22076 (goto-char (org-element-property :end element))
22077 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22078 (line-beginning-position))))
22079 (if (or (< (point) beg) (> (point) end)) t
22080 (fill-region-as-paragraph
22081 (save-excursion (end-of-line)
22082 (re-search-backward "^[ \t]*$" beg 'move)
22083 (line-beginning-position))
22084 (save-excursion (beginning-of-line)
22085 (re-search-forward "^[ \t]*$" end 'move)
22086 (line-beginning-position))
22087 justify))))
22088 ;; Fill comments.
22089 (comment
22090 (let ((begin (org-element-property :post-affiliated element))
22091 (end (org-element-property :end element)))
22092 (when (and (>= (point) begin) (<= (point) end))
22093 (let ((begin (save-excursion
22094 (end-of-line)
22095 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22096 (progn (forward-line) (point))
22097 begin)))
22098 (end (save-excursion
22099 (end-of-line)
22100 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22101 (1- (line-beginning-position))
22102 (skip-chars-backward " \r\t\n")
22103 (line-end-position)))))
22104 ;; Do not fill comments when at a blank line.
22105 (when (> end begin)
22106 (let ((fill-prefix
22107 (save-excursion
22108 (beginning-of-line)
22109 (looking-at "[ \t]*#")
22110 (let ((comment-prefix (match-string 0)))
22111 (goto-char (match-end 0))
22112 (if (looking-at adaptive-fill-regexp)
22113 (concat comment-prefix (match-string 0))
22114 (concat comment-prefix " "))))))
22115 (save-excursion
22116 (fill-region-as-paragraph begin end justify))))))
22118 ;; Ignore every other element.
22119 (otherwise t)))))
22121 (defun org-fill-paragraph (&optional justify region)
22122 "Fill element at point, when applicable.
22124 This function only applies to comment blocks, comments, example
22125 blocks and paragraphs. Also, as a special case, re-align table
22126 when point is at one.
22128 For convenience, when point is at a plain list, an item or
22129 a footnote definition, try to fill the first paragraph within.
22131 If JUSTIFY is non-nil (interactively, with prefix argument),
22132 justify as well. If `sentence-end-double-space' is non-nil, then
22133 period followed by one space does not end a sentence, so don't
22134 break a line there. The variable `fill-column' controls the
22135 width for filling.
22137 The REGION argument is non-nil if called interactively; in that
22138 case, if Transient Mark mode is enabled and the mark is active,
22139 fill each of the elements in the active region, instead of just
22140 filling the current element."
22141 (interactive (progn
22142 (barf-if-buffer-read-only)
22143 (list (when current-prefix-arg 'full) t)))
22144 (cond
22145 ((and region transient-mark-mode mark-active
22146 (not (eq (region-beginning) (region-end))))
22147 (let ((origin (point-marker))
22148 (start (region-beginning)))
22149 (unwind-protect
22150 (progn
22151 (goto-char (region-end))
22152 (while (> (point) start)
22153 (org-backward-paragraph)
22154 (org-fill-element justify)))
22155 (goto-char origin)
22156 (set-marker origin nil))))
22157 (t (org-fill-element justify))))
22159 (defun org-auto-fill-function ()
22160 "Auto-fill function."
22161 ;; Check if auto-filling is meaningful.
22162 (let ((fc (current-fill-column)))
22163 (when (and fc (> (current-column) fc))
22164 (let* ((fill-prefix (org-adaptive-fill-function))
22165 ;; Enforce empty fill prefix, if required. Otherwise, it
22166 ;; will be computed again.
22167 (adaptive-fill-mode (not (equal fill-prefix ""))))
22168 (when fill-prefix (do-auto-fill))))))
22170 (defun org-comment-line-break-function (&optional soft)
22171 "Break line at point and indent, continuing comment if within one.
22172 The inserted newline is marked hard if variable
22173 `use-hard-newlines' is true, unless optional argument SOFT is
22174 non-nil."
22175 (if soft (insert-and-inherit ?\n) (newline 1))
22176 (save-excursion (forward-char -1) (delete-horizontal-space))
22177 (delete-horizontal-space)
22178 (indent-to-left-margin)
22179 (insert-before-markers-and-inherit fill-prefix))
22182 ;;; Fixed Width Areas
22184 (defun org-toggle-fixed-width ()
22185 "Toggle fixed-width markup.
22187 Add or remove fixed-width markup on current line, whenever it
22188 makes sense. Return an error otherwise.
22190 If a region is active and if it contains only fixed-width areas
22191 or blank lines, remove all fixed-width markup in it. If the
22192 region contains anything else, convert all non-fixed-width lines
22193 to fixed-width ones.
22195 Blank lines at the end of the region are ignored unless the
22196 region only contains such lines."
22197 (interactive)
22198 (if (not (org-region-active-p))
22199 ;; No region:
22201 ;; Remove fixed width marker only in a fixed-with element.
22203 ;; Add fixed width maker in paragraphs, in blank lines after
22204 ;; elements or at the beginning of a headline or an inlinetask,
22205 ;; and before any one-line elements (e.g., a clock).
22206 (progn
22207 (beginning-of-line)
22208 (let* ((element (org-element-at-point))
22209 (type (org-element-type element)))
22210 (cond
22211 ((and (eq type 'fixed-width)
22212 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
22213 (replace-match
22214 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
22215 ((and (memq type '(babel-call clock comment diary-sexp headline
22216 horizontal-rule keyword paragraph
22217 planning))
22218 (<= (org-element-property :post-affiliated element) (point)))
22219 (skip-chars-forward " \t")
22220 (insert ": "))
22221 ((and (looking-at-p "[ \t]*$")
22222 (or (eq type 'inlinetask)
22223 (save-excursion
22224 (skip-chars-forward " \r\t\n")
22225 (<= (org-element-property :end element) (point)))))
22226 (delete-region (point) (line-end-position))
22227 (org-indent-line)
22228 (insert ": "))
22229 (t (user-error "Cannot insert a fixed-width line here")))))
22230 ;; Region active.
22231 (let* ((begin (save-excursion
22232 (goto-char (region-beginning))
22233 (line-beginning-position)))
22234 (end (copy-marker
22235 (save-excursion
22236 (goto-char (region-end))
22237 (unless (eolp) (beginning-of-line))
22238 (if (save-excursion (re-search-backward "\\S-" begin t))
22239 (progn (skip-chars-backward " \r\t\n") (point))
22240 (point)))))
22241 (all-fixed-width-p
22242 (catch 'not-all-p
22243 (save-excursion
22244 (goto-char begin)
22245 (skip-chars-forward " \r\t\n")
22246 (when (eobp) (throw 'not-all-p nil))
22247 (while (< (point) end)
22248 (let ((element (org-element-at-point)))
22249 (if (eq (org-element-type element) 'fixed-width)
22250 (goto-char (org-element-property :end element))
22251 (throw 'not-all-p nil))))
22252 t))))
22253 (if all-fixed-width-p
22254 (save-excursion
22255 (goto-char begin)
22256 (while (< (point) end)
22257 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
22258 (replace-match
22259 "" nil nil nil
22260 (if (= (line-end-position) (match-end 0)) 0 1)))
22261 (forward-line)))
22262 (let ((min-ind (point-max)))
22263 ;; Find minimum indentation across all lines.
22264 (save-excursion
22265 (goto-char begin)
22266 (if (not (save-excursion (re-search-forward "\\S-" end t)))
22267 (setq min-ind 0)
22268 (catch 'zerop
22269 (while (< (point) end)
22270 (unless (looking-at-p "[ \t]*$")
22271 (let ((ind (current-indentation)))
22272 (setq min-ind (min min-ind ind))
22273 (when (zerop ind) (throw 'zerop t))))
22274 (forward-line)))))
22275 ;; Loop over all lines and add fixed-width markup everywhere
22276 ;; but in fixed-width lines.
22277 (save-excursion
22278 (goto-char begin)
22279 (while (< (point) end)
22280 (cond
22281 ((org-at-heading-p)
22282 (insert ": ")
22283 (forward-line)
22284 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
22285 (insert ":")
22286 (forward-line)))
22287 ((looking-at-p "[ \t]*:\\( \\|$\\)")
22288 (let* ((element (org-element-at-point))
22289 (element-end (org-element-property :end element)))
22290 (if (eq (org-element-type element) 'fixed-width)
22291 (progn (goto-char element-end)
22292 (skip-chars-backward " \r\t\n")
22293 (forward-line))
22294 (let ((limit (min end element-end)))
22295 (while (< (point) limit)
22296 (org-move-to-column min-ind t)
22297 (insert ": ")
22298 (forward-line))))))
22300 (org-move-to-column min-ind t)
22301 (insert ": ")
22302 (forward-line)))))))
22303 (set-marker end nil))))
22306 ;;; Blocks
22308 (defun org-block-map (function &optional start end)
22309 "Call FUNCTION at the head of all source blocks in the current buffer.
22310 Optional arguments START and END can be used to limit the range."
22311 (let ((start (or start (point-min)))
22312 (end (or end (point-max))))
22313 (save-excursion
22314 (goto-char start)
22315 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
22316 (save-excursion
22317 (save-match-data
22318 (goto-char (match-beginning 0))
22319 (funcall function)))))))
22321 (defun org-next-block (arg &optional backward block-regexp)
22322 "Jump to the next block.
22324 With a prefix argument ARG, jump forward ARG many blocks.
22326 When BACKWARD is non-nil, jump to the previous block.
22328 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
22329 Match data is set according to this regexp when the function
22330 returns.
22332 Return point at beginning of the opening line of found block.
22333 Throw an error if no block is found."
22334 (interactive "p")
22335 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
22336 (case-fold-search t)
22337 (search-fn (if backward #'re-search-backward #'re-search-forward))
22338 (count (or arg 1))
22339 (origin (point))
22340 last-element)
22341 (if backward (beginning-of-line) (end-of-line))
22342 (while (and (> count 0) (funcall search-fn re nil t))
22343 (let ((element (save-excursion
22344 (goto-char (match-beginning 0))
22345 (save-match-data (org-element-at-point)))))
22346 (when (and (memq (org-element-type element)
22347 '(center-block comment-block dynamic-block
22348 example-block export-block quote-block
22349 special-block src-block verse-block))
22350 (<= (match-beginning 0)
22351 (org-element-property :post-affiliated element)))
22352 (setq last-element element)
22353 (cl-decf count))))
22354 (if (= count 0)
22355 (prog1 (goto-char (org-element-property :post-affiliated last-element))
22356 (save-match-data (org-show-context)))
22357 (goto-char origin)
22358 (user-error "No %s code blocks" (if backward "previous" "further")))))
22360 (defun org-previous-block (arg &optional block-regexp)
22361 "Jump to the previous block.
22362 With a prefix argument ARG, jump backward ARG many source blocks.
22363 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22364 (interactive "p")
22365 (org-next-block arg t block-regexp))
22368 ;;; Comments
22370 ;; Org comments syntax is quite complex. It requires the entire line
22371 ;; to be just a comment. Also, even with the right syntax at the
22372 ;; beginning of line, some elements (e.g., verse-block or
22373 ;; example-block) don't accept comments. Usual Emacs comment commands
22374 ;; cannot cope with those requirements. Therefore, Org replaces them.
22376 ;; Org still relies on `comment-dwim', but cannot trust
22377 ;; `comment-only-p'. So, `comment-region-function' and
22378 ;; `uncomment-region-function' both point
22379 ;; to`org-comment-or-uncomment-region'. Eventually,
22380 ;; `org-insert-comment' takes care of insertion of comments at the
22381 ;; beginning of line.
22383 ;; `org-setup-comments-handling' install comments related variables
22384 ;; during `org-mode' initialization.
22386 (defun org-setup-comments-handling ()
22387 (interactive)
22388 (setq-local comment-use-syntax nil)
22389 (setq-local comment-start "# ")
22390 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22391 (setq-local comment-insert-comment-function 'org-insert-comment)
22392 (setq-local comment-region-function 'org-comment-or-uncomment-region)
22393 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
22395 (defun org-insert-comment ()
22396 "Insert an empty comment above current line.
22397 If the line is empty, insert comment at its beginning. When
22398 point is within a source block, comment according to the related
22399 major mode."
22400 (if (let ((element (org-element-at-point)))
22401 (and (eq (org-element-type element) 'src-block)
22402 (< (save-excursion
22403 (goto-char (org-element-property :post-affiliated element))
22404 (line-end-position))
22405 (point))
22406 (> (save-excursion
22407 (goto-char (org-element-property :end element))
22408 (skip-chars-backward " \r\t\n")
22409 (line-beginning-position))
22410 (point))))
22411 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
22412 (beginning-of-line)
22413 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
22414 (open-line 1))
22415 (org-indent-line)
22416 (insert "# ")))
22418 (defvar comment-empty-lines) ; From newcomment.el.
22419 (defun org-comment-or-uncomment-region (beg end &rest _)
22420 "Comment or uncomment each non-blank line in the region.
22421 Uncomment each non-blank line between BEG and END if it only
22422 contains commented lines. Otherwise, comment them. If region is
22423 strictly within a source block, use appropriate comment syntax."
22424 (if (let ((element (org-element-at-point)))
22425 (and (eq (org-element-type element) 'src-block)
22426 (< (save-excursion
22427 (goto-char (org-element-property :post-affiliated element))
22428 (line-end-position))
22429 beg)
22430 (>= (save-excursion
22431 (goto-char (org-element-property :end element))
22432 (skip-chars-backward " \r\t\n")
22433 (line-beginning-position))
22434 end)))
22435 ;; Translate region boundaries for the Org buffer to the source
22436 ;; buffer.
22437 (let ((offset (- end beg)))
22438 (save-excursion
22439 (goto-char beg)
22440 (org-babel-do-in-edit-buffer
22441 (comment-or-uncomment-region (point) (+ offset (point))))))
22442 (save-restriction
22443 ;; Restrict region
22444 (narrow-to-region (save-excursion (goto-char beg)
22445 (skip-chars-forward " \r\t\n" end)
22446 (line-beginning-position))
22447 (save-excursion (goto-char end)
22448 (skip-chars-backward " \r\t\n" beg)
22449 (line-end-position)))
22450 (let ((uncommentp
22451 ;; UNCOMMENTP is non-nil when every non blank line between
22452 ;; BEG and END is a comment.
22453 (save-excursion
22454 (goto-char (point-min))
22455 (while (and (not (eobp))
22456 (let ((element (org-element-at-point)))
22457 (and (eq (org-element-type element) 'comment)
22458 (goto-char (min (point-max)
22459 (org-element-property
22460 :end element)))))))
22461 (eobp))))
22462 (if uncommentp
22463 ;; Only blank lines and comments in region: uncomment it.
22464 (save-excursion
22465 (goto-char (point-min))
22466 (while (not (eobp))
22467 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22468 (replace-match "" nil nil nil 1))
22469 (forward-line)))
22470 ;; Comment each line in region.
22471 (let ((min-indent (point-max)))
22472 ;; First find the minimum indentation across all lines.
22473 (save-excursion
22474 (goto-char (point-min))
22475 (while (and (not (eobp)) (not (zerop min-indent)))
22476 (unless (looking-at "[ \t]*$")
22477 (setq min-indent (min min-indent (current-indentation))))
22478 (forward-line)))
22479 ;; Then loop over all lines.
22480 (save-excursion
22481 (goto-char (point-min))
22482 (while (not (eobp))
22483 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22484 ;; Don't get fooled by invisible text (e.g. link path)
22485 ;; when moving to column MIN-INDENT.
22486 (let ((buffer-invisibility-spec nil))
22487 (org-move-to-column min-indent t))
22488 (insert comment-start))
22489 (forward-line)))))))))
22491 (defun org-comment-dwim (_arg)
22492 "Call the comment command you mean.
22493 Call `org-toggle-comment' if on a heading, otherwise call
22494 `comment-dwim', within a source edit buffer if needed."
22495 (interactive "*P")
22496 (cond ((org-at-heading-p)
22497 (call-interactively #'org-toggle-comment))
22498 ((org-in-src-block-p)
22499 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
22500 (t (call-interactively #'comment-dwim))))
22503 ;;; Timestamps API
22505 ;; This section contains tools to operate on, or create, timestamp
22506 ;; objects, as returned by, e.g. `org-element-context'.
22508 (defun org-timestamp-from-string (s)
22509 "Convert Org timestamp S, as a string, into a timestamp object.
22510 Return nil if S is not a valid timestamp string."
22511 (when (org-string-nw-p s)
22512 (with-temp-buffer
22513 (save-excursion (insert s))
22514 (org-element-timestamp-parser))))
22516 (defun org-timestamp-from-time (time &optional with-time inactive)
22517 "Convert a time value into a timestamp object.
22519 TIME is an Emacs internal time representation, as returned, e.g.,
22520 by `current-time'.
22522 When optional argument WITH-TIME is non-nil, return a timestamp
22523 object with a time part, i.e., with hours and minutes.
22525 Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
22526 return an active timestamp."
22527 (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
22528 (org-element-create 'timestamp
22529 (list :type (if inactive 'inactive 'active)
22530 :year-start year
22531 :month-start month
22532 :day-start day
22533 :hour-start (and with-time hour)
22534 :minute-start (and with-time minute)))))
22536 (defun org-timestamp-to-time (timestamp &optional end)
22537 "Convert TIMESTAMP object into an Emacs internal time value.
22538 Use end of date range or time range when END is non-nil.
22539 Otherwise, use its start."
22540 (apply #'encode-time
22541 (cons 0
22542 (mapcar
22543 (lambda (prop) (or (org-element-property prop timestamp) 0))
22544 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22545 '(:minute-start :hour-start :day-start :month-start
22546 :year-start))))))
22548 (defun org-timestamp-has-time-p (timestamp)
22549 "Non-nil when TIMESTAMP has a time specified."
22550 (org-element-property :hour-start timestamp))
22552 (defun org-timestamp-format (timestamp format &optional end utc)
22553 "Format a TIMESTAMP object into a string.
22555 FORMAT is a format specifier to be passed to
22556 `format-time-string'.
22558 When optional argument END is non-nil, use end of date-range or
22559 time-range, if possible.
22561 When optional argument UTC is non-nil, time is be expressed as
22562 Universal Time."
22563 (format-time-string format (org-timestamp-to-time timestamp end)
22564 (and utc t)))
22566 (defun org-timestamp-split-range (timestamp &optional end)
22567 "Extract a TIMESTAMP object from a date or time range.
22569 END, when non-nil, means extract the end of the range.
22570 Otherwise, extract its start.
22572 Return a new timestamp object."
22573 (let ((type (org-element-property :type timestamp)))
22574 (if (memq type '(active inactive diary)) timestamp
22575 (let ((split-ts (org-element-copy timestamp)))
22576 ;; Set new type.
22577 (org-element-put-property
22578 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22579 ;; Copy start properties over end properties if END is
22580 ;; non-nil. Otherwise, copy end properties over `start' ones.
22581 (let ((p-alist '((:minute-start . :minute-end)
22582 (:hour-start . :hour-end)
22583 (:day-start . :day-end)
22584 (:month-start . :month-end)
22585 (:year-start . :year-end))))
22586 (dolist (p-cell p-alist)
22587 (org-element-put-property
22588 split-ts
22589 (funcall (if end #'car #'cdr) p-cell)
22590 (org-element-property
22591 (funcall (if end #'cdr #'car) p-cell) split-ts)))
22592 ;; Eventually refresh `:raw-value'.
22593 (org-element-put-property split-ts :raw-value nil)
22594 (org-element-put-property
22595 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22597 (defun org-timestamp-translate (timestamp &optional boundary)
22598 "Translate TIMESTAMP object to custom format.
22600 Format string is defined in `org-time-stamp-custom-formats',
22601 which see.
22603 When optional argument BOUNDARY is non-nil, it is either the
22604 symbol `start' or `end'. In this case, only translate the
22605 starting or ending part of TIMESTAMP if it is a date or time
22606 range. Otherwise, translate both parts.
22608 Return timestamp as-is if `org-display-custom-times' is nil or if
22609 it has a `diary' type."
22610 (let ((type (org-element-property :type timestamp)))
22611 (if (or (not org-display-custom-times) (eq type 'diary))
22612 (org-element-interpret-data timestamp)
22613 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
22614 org-time-stamp-custom-formats)))
22615 (if (and (not boundary) (memq type '(active-range inactive-range)))
22616 (concat (org-timestamp-format timestamp fmt)
22617 "--"
22618 (org-timestamp-format timestamp fmt t))
22619 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
22621 ;;; Other stuff
22623 (defvar reftex-docstruct-symbol)
22624 (defvar org--rds)
22626 (defun org-reftex-citation ()
22627 "Use reftex-citation to insert a citation into the buffer.
22628 This looks for a line like
22630 #+BIBLIOGRAPHY: foo plain option:-d
22632 and derives from it that foo.bib is the bibliography file relevant
22633 for this document. It then installs the necessary environment for RefTeX
22634 to work in this buffer and calls `reftex-citation' to insert a citation
22635 into the buffer.
22637 Export of such citations to both LaTeX and HTML is handled by the contributed
22638 package ox-bibtex by Taru Karttunen."
22639 (interactive)
22640 (let ((reftex-docstruct-symbol 'org--rds)
22641 org--rds bib)
22642 (org-with-wide-buffer
22643 (let ((case-fold-search t)
22644 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
22645 (if (not (save-excursion
22646 (or (re-search-forward re nil t)
22647 (re-search-backward re nil t))))
22648 (user-error "No bibliography defined in file")
22649 (setq bib (concat (match-string 1) ".bib")
22650 org--rds (list (list 'bib bib))))))
22651 (call-interactively 'reftex-citation)))
22653 ;;;; Functions extending outline functionality
22655 (defun org-beginning-of-line (&optional n)
22656 "Go to the beginning of the current visible line.
22658 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22659 symbol `reversed', on the first attempt move to where the
22660 headline text starts, and only move to beginning of line when the
22661 cursor is already before the start of the text of the headline.
22663 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
22664 start of the text on the second attempt.
22666 With argument N not nil or 1, move forward N - 1 lines first."
22667 (interactive "^p")
22668 (let ((origin (point))
22669 (special (pcase org-special-ctrl-a/e
22670 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
22671 deactivate-mark)
22672 ;; First move to a visible line.
22673 (if (bound-and-true-p visual-line-mode)
22674 (beginning-of-visual-line n)
22675 (move-beginning-of-line n)
22676 ;; `move-beginning-of-line' may leave point after invisible
22677 ;; characters if line starts with such of these (e.g., with
22678 ;; a link at column 0). Really move to the beginning of the
22679 ;; current visible line.
22680 (beginning-of-line))
22681 (cond
22682 ;; No special behavior. Point is already at the beginning of
22683 ;; a line, logical or visual.
22684 ((not special))
22685 ;; `beginning-of-visual-line' left point before logical beginning
22686 ;; of line: point is at the beginning of a visual line. Bail
22687 ;; out.
22688 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
22689 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
22690 ;; At a headline, special position is before the title, but
22691 ;; after any TODO keyword or priority cookie.
22692 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22693 (line-end-position)))
22694 (bol (point)))
22695 (if (eq special 'reversed)
22696 (when (and (= origin bol) (eq last-command this-command))
22697 (goto-char refpos))
22698 (when (or (> origin refpos) (= origin bol))
22699 (goto-char refpos)))))
22700 ((and (looking-at org-list-full-item-re)
22701 (memq (org-element-type (save-match-data (org-element-at-point)))
22702 '(item plain-list)))
22703 ;; Set special position at first white space character after
22704 ;; bullet, and check-box, if any.
22705 (let ((after-bullet
22706 (let ((box (match-end 3)))
22707 (cond ((not box) (match-end 1))
22708 ((eq (char-after box) ?\s) (1+ box))
22709 (t box)))))
22710 (if (eq special 'reversed)
22711 (when (and (= (point) origin) (eq last-command this-command))
22712 (goto-char after-bullet))
22713 (when (or (> origin after-bullet) (= (point) origin))
22714 (goto-char after-bullet)))))
22715 ;; No special context. Point is already at beginning of line.
22716 (t nil))))
22718 (defun org-end-of-line (&optional n)
22719 "Go to the end of the line, but before ellipsis, if any.
22721 If this is a headline, and `org-special-ctrl-a/e' is not nil or
22722 symbol `reversed', ignore tags on the first attempt, and only
22723 move to after the tags when the cursor is already beyond the end
22724 of the headline.
22726 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
22727 on the second attempt.
22729 With argument N not nil or 1, move forward N - 1 lines first."
22730 (interactive "^p")
22731 (let ((origin (point))
22732 (special (pcase org-special-ctrl-a/e
22733 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
22734 deactivate-mark)
22735 ;; First move to a visible line.
22736 (if (bound-and-true-p visual-line-mode)
22737 (beginning-of-visual-line n)
22738 (move-beginning-of-line n))
22739 (cond
22740 ;; At a headline, with tags.
22741 ((and special
22742 (save-excursion
22743 (beginning-of-line)
22744 (let ((case-fold-search nil))
22745 (looking-at org-complex-heading-regexp)))
22746 (match-end 5))
22747 (let ((tags (save-excursion
22748 (goto-char (match-beginning 5))
22749 (skip-chars-backward " \t")
22750 (point)))
22751 (visual-end (and (bound-and-true-p visual-line-mode)
22752 (save-excursion
22753 (end-of-visual-line)
22754 (point)))))
22755 ;; If `end-of-visual-line' brings us before end of line or
22756 ;; even tags, i.e., the headline spans over multiple visual
22757 ;; lines, move there.
22758 (cond ((and visual-end
22759 (< visual-end tags)
22760 (<= origin visual-end))
22761 (goto-char visual-end))
22762 ((eq special 'reversed)
22763 (if (and (= origin (line-end-position))
22764 (eq this-command last-command))
22765 (goto-char tags)
22766 (end-of-line)))
22768 (if (or (< origin tags) (= origin (line-end-position)))
22769 (goto-char tags)
22770 (end-of-line))))))
22771 ((bound-and-true-p visual-line-mode)
22772 (let ((bol (line-beginning-position)))
22773 (end-of-visual-line)
22774 ;; If `end-of-visual-line' gets us past the ellipsis at the
22775 ;; end of a line, backtrack and use `end-of-line' instead.
22776 (when (/= bol (line-beginning-position))
22777 (goto-char bol)
22778 (end-of-line))))
22779 (t (end-of-line)))))
22781 (defun org-backward-sentence (&optional _arg)
22782 "Go to beginning of sentence, or beginning of table field.
22783 This will call `backward-sentence' or `org-table-beginning-of-field',
22784 depending on context."
22785 (interactive)
22786 (let* ((element (org-element-at-point))
22787 (contents-begin (org-element-property :contents-begin element))
22788 (table (org-element-lineage element '(table) t)))
22789 (if (and table
22790 (> (point) contents-begin)
22791 (<= (point) (org-element-property :contents-end table)))
22792 (call-interactively #'org-table-beginning-of-field)
22793 (save-restriction
22794 (when (and contents-begin
22795 (< (point-min) contents-begin)
22796 (> (point) contents-begin))
22797 (narrow-to-region contents-begin
22798 (org-element-property :contents-end element)))
22799 (call-interactively #'backward-sentence)))))
22801 (defun org-forward-sentence (&optional _arg)
22802 "Go to end of sentence, or end of table field.
22803 This will call `forward-sentence' or `org-table-end-of-field',
22804 depending on context."
22805 (interactive)
22806 (if (and (org-at-heading-p)
22807 (save-restriction (skip-chars-forward " \t") (not (eolp))))
22808 (save-restriction
22809 (narrow-to-region (line-beginning-position) (line-end-position))
22810 (call-interactively #'forward-sentence))
22811 (let* ((element (org-element-at-point))
22812 (contents-end (org-element-property :contents-end element))
22813 (table (org-element-lineage element '(table) t)))
22814 (if (and table
22815 (>= (point) (org-element-property :contents-begin table))
22816 (< (point) contents-end))
22817 (call-interactively #'org-table-end-of-field)
22818 (save-restriction
22819 (when (and contents-end
22820 (> (point-max) contents-end)
22821 ;; Skip blank lines between elements.
22822 (< (org-element-property :end element)
22823 (save-excursion (goto-char contents-end)
22824 (skip-chars-forward " \r\t\n"))))
22825 (narrow-to-region (org-element-property :contents-begin element)
22826 contents-end))
22827 ;; End of heading is considered as the end of a sentence.
22828 (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
22829 (call-interactively #'forward-sentence)))))))
22831 (defun org-kill-line (&optional _arg)
22832 "Kill line, to tags or end of line."
22833 (interactive)
22834 (cond
22835 ((or (not org-special-ctrl-k)
22836 (bolp)
22837 (not (org-at-heading-p)))
22838 (when (and (get-char-property (line-end-position) 'invisible)
22839 org-ctrl-k-protect-subtree
22840 (or (eq org-ctrl-k-protect-subtree 'error)
22841 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
22842 (user-error
22843 (substitute-command-keys
22844 "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
22845 (call-interactively
22846 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22847 ((org-match-line org-tag-line-re)
22848 (let ((end (save-excursion
22849 (goto-char (match-beginning 1))
22850 (skip-chars-backward " \t")
22851 (point))))
22852 (if (<= end (point)) ;on tags part
22853 (kill-region (point) (line-end-position))
22854 (kill-region (point) end)))
22855 (org-align-tags))
22856 (t (kill-region (point) (line-end-position)))))
22858 (defun org-yank (&optional arg)
22859 "Yank. If the kill is a subtree, treat it specially.
22860 This command will look at the current kill and check if is a single
22861 subtree, or a series of subtrees[1]. If it passes the test, and if the
22862 cursor is at the beginning of a line or after the stars of a currently
22863 empty headline, then the yank is handled specially. How exactly depends
22864 on the value of the following variables.
22866 `org-yank-folded-subtrees'
22867 By default, this variable is non-nil, which results in
22868 subtree(s) being folded after insertion, except if doing so
22869 would swallow text after the yanked text.
22871 `org-yank-adjusted-subtrees'
22872 When non-nil (the default value is nil), the subtree will be
22873 promoted or demoted in order to fit into the local outline tree
22874 structure, which means that the level will be adjusted so that it
22875 becomes the smaller one of the two *visible* surrounding headings.
22877 Any prefix to this command will cause `yank' to be called directly with
22878 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
22879 will just
22880 plainly yank the text as it is.
22882 \[1] The test checks if the first non-white line is a heading
22883 and if there are no other headings with fewer stars."
22884 (interactive "P")
22885 (org-yank-generic 'yank arg))
22887 (defun org-yank-generic (command arg)
22888 "Perform some yank-like command.
22890 This function implements the behavior described in the `org-yank'
22891 documentation. However, it has been generalized to work for any
22892 interactive command with similar behavior."
22894 ;; pretend to be command COMMAND
22895 (setq this-command command)
22897 (if arg
22898 (call-interactively command)
22900 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22901 (and (org-kill-is-subtree-p)
22902 (or (bolp)
22903 (and (looking-at "[ \t]*$")
22904 (string-match
22905 "\\`\\*+\\'"
22906 (buffer-substring (point-at-bol) (point)))))))
22907 swallowp)
22908 (cond
22909 ((and subtreep org-yank-folded-subtrees)
22910 (let ((beg (point))
22911 end)
22912 (if (and subtreep org-yank-adjusted-subtrees)
22913 (org-paste-subtree nil nil 'for-yank)
22914 (call-interactively command))
22916 (setq end (point))
22917 (goto-char beg)
22918 (when (and (bolp) subtreep
22919 (not (setq swallowp
22920 (org-yank-folding-would-swallow-text beg end))))
22921 (org-with-limited-levels
22922 (or (looking-at org-outline-regexp)
22923 (re-search-forward org-outline-regexp-bol end t))
22924 (while (and (< (point) end) (looking-at org-outline-regexp))
22925 (outline-hide-subtree)
22926 (org-cycle-show-empty-lines 'folded)
22927 (condition-case nil
22928 (outline-forward-same-level 1)
22929 (error (goto-char end))))))
22930 (when swallowp
22931 (message
22932 "Inserted text not folded because that would swallow text"))
22934 (goto-char end)
22935 (skip-chars-forward " \t\n\r")
22936 (beginning-of-line 1)
22937 (push-mark beg 'nomsg)))
22938 ((and subtreep org-yank-adjusted-subtrees)
22939 (let ((beg (point-at-bol)))
22940 (org-paste-subtree nil nil 'for-yank)
22941 (push-mark beg 'nomsg)))
22943 (call-interactively command))))))
22945 (defun org-yank-folding-would-swallow-text (beg end)
22946 "Would hide-subtree at BEG swallow any text after END?"
22947 (let (level)
22948 (org-with-limited-levels
22949 (save-excursion
22950 (goto-char beg)
22951 (when (or (looking-at org-outline-regexp)
22952 (re-search-forward org-outline-regexp-bol end t))
22953 (setq level (org-outline-level)))
22954 (goto-char end)
22955 (skip-chars-forward " \t\r\n\v\f")
22956 (not (or (eobp)
22957 (and (bolp) (looking-at-p org-outline-regexp)
22958 (<= (org-outline-level) level))))))))
22960 (defun org-back-to-heading (&optional invisible-ok)
22961 "Call `outline-back-to-heading', but provide a better error message."
22962 (condition-case nil
22963 (outline-back-to-heading invisible-ok)
22964 (error (error "Before first headline at position %d in buffer %s"
22965 (point) (current-buffer)))))
22967 (defun org-before-first-heading-p ()
22968 "Before first heading?"
22969 (org-with-limited-levels
22970 (save-excursion
22971 (end-of-line)
22972 (null (re-search-backward org-outline-regexp-bol nil t)))))
22974 (defun org-at-heading-p (&optional ignored)
22975 (outline-on-heading-p t))
22977 (defun org-in-commented-heading-p (&optional no-inheritance)
22978 "Non-nil if point is under a commented heading.
22979 This function also checks ancestors of the current headline,
22980 unless optional argument NO-INHERITANCE is non-nil."
22981 (cond
22982 ((org-before-first-heading-p) nil)
22983 ((let ((headline (nth 4 (org-heading-components))))
22984 (and headline
22985 (let ((case-fold-search nil))
22986 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
22987 headline)))))
22988 (no-inheritance nil)
22990 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
22992 (defun org-at-comment-p nil
22993 "Is cursor in a commented line?"
22994 (save-excursion
22995 (save-match-data
22996 (beginning-of-line)
22997 (looking-at "^[ \t]*# "))))
22999 (defun org-at-drawer-p nil
23000 "Is cursor at a drawer keyword?"
23001 (save-excursion
23002 (move-beginning-of-line 1)
23003 (looking-at org-drawer-regexp)))
23005 (defun org-at-block-p nil
23006 "Is cursor at a block keyword?"
23007 (save-excursion
23008 (move-beginning-of-line 1)
23009 (looking-at org-block-regexp)))
23011 (defun org-point-at-end-of-empty-headline ()
23012 "If point is at the end of an empty headline, return t, else nil.
23013 If the heading only contains a TODO keyword, it is still still considered
23014 empty."
23015 (let ((case-fold-search nil))
23016 (and (looking-at "[ \t]*$")
23017 org-todo-line-regexp
23018 (save-excursion
23019 (beginning-of-line)
23020 (looking-at org-todo-line-regexp)
23021 (string= (match-string 3) "")))))
23023 (defun org-at-heading-or-item-p ()
23024 (or (org-at-heading-p) (org-at-item-p)))
23026 (defun org-at-target-p ()
23027 (or (org-in-regexp org-radio-target-regexp)
23028 (org-in-regexp org-target-regexp)))
23030 (defun org-up-heading-all (arg)
23031 "Move to the heading line of which the present line is a subheading.
23032 This function considers both visible and invisible heading lines.
23033 With argument, move up ARG levels."
23034 (outline-up-heading arg t))
23036 (defun org-up-heading-safe ()
23037 "Move to the heading line of which the present line is a subheading.
23038 This version will not throw an error. It will return the level of the
23039 headline found, or nil if no higher level is found.
23041 Also, this function will be a lot faster than `outline-up-heading',
23042 because it relies on stars being the outline starters. This can really
23043 make a significant difference in outlines with very many siblings."
23044 (when (ignore-errors (org-back-to-heading t))
23045 (let ((level-up (1- (funcall outline-level))))
23046 (and (> level-up 0)
23047 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23048 (funcall outline-level)))))
23050 (defun org-first-sibling-p ()
23051 "Is this heading the first child of its parents?"
23052 (interactive)
23053 (let ((re org-outline-regexp-bol)
23054 level l)
23055 (unless (org-at-heading-p t)
23056 (user-error "Not at a heading"))
23057 (setq level (funcall outline-level))
23058 (save-excursion
23059 (if (not (re-search-backward re nil t))
23061 (setq l (funcall outline-level))
23062 (< l level)))))
23064 (defun org-goto-sibling (&optional previous)
23065 "Goto the next sibling, even if it is invisible.
23066 When PREVIOUS is set, go to the previous sibling instead. Returns t
23067 when a sibling was found. When none is found, return nil and don't
23068 move point."
23069 (let ((fun (if previous 're-search-backward 're-search-forward))
23070 (pos (point))
23071 (re org-outline-regexp-bol)
23072 level l)
23073 (when (ignore-errors (org-back-to-heading t))
23074 (setq level (funcall outline-level))
23075 (catch 'exit
23076 (or previous (forward-char 1))
23077 (while (funcall fun re nil t)
23078 (setq l (funcall outline-level))
23079 (when (< l level) (goto-char pos) (throw 'exit nil))
23080 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23081 (goto-char pos)
23082 nil))))
23084 (defun org-show-siblings ()
23085 "Show all siblings of the current headline."
23086 (save-excursion
23087 (while (org-goto-sibling) (org-flag-heading nil)))
23088 (save-excursion
23089 (while (org-goto-sibling 'previous)
23090 (org-flag-heading nil))))
23092 (defun org-goto-first-child ()
23093 "Goto the first child, even if it is invisible.
23094 Return t when a child was found. Otherwise don't move point and
23095 return nil."
23096 (let (level (pos (point)) (re org-outline-regexp-bol))
23097 (when (ignore-errors (org-back-to-heading t))
23098 (setq level (outline-level))
23099 (forward-char 1)
23100 (if (and (re-search-forward re nil t) (> (outline-level) level))
23101 (progn (goto-char (match-beginning 0)) t)
23102 (goto-char pos) nil))))
23104 (defun org-show-hidden-entry ()
23105 "Show an entry where even the heading is hidden."
23106 (save-excursion
23107 (org-show-entry)))
23109 (defun org-flag-heading (flag &optional entry)
23110 "Flag the current heading. FLAG non-nil means make invisible.
23111 When ENTRY is non-nil, show the entire entry."
23112 (save-excursion
23113 (org-back-to-heading t)
23114 ;; Check if we should show the entire entry
23115 (if (not entry)
23116 (org-flag-region
23117 (line-end-position 0) (line-end-position) flag 'outline)
23118 (org-show-entry)
23119 (save-excursion
23120 (and (outline-next-heading)
23121 (org-flag-heading nil))))))
23123 (defun org-get-next-sibling ()
23124 "Move to next heading of the same level, and return point.
23125 If there is no such heading, return nil.
23126 This is like outline-next-sibling, but invisible headings are ok."
23127 (let ((level (funcall outline-level)))
23128 (outline-next-heading)
23129 (while (and (not (eobp)) (> (funcall outline-level) level))
23130 (outline-next-heading))
23131 (unless (or (eobp) (< (funcall outline-level) level))
23132 (point))))
23134 (defun org-get-last-sibling ()
23135 "Move to previous heading of the same level, and return point.
23136 If there is no such heading, return nil."
23137 (let ((opoint (point))
23138 (level (funcall outline-level)))
23139 (outline-previous-heading)
23140 (when (and (/= (point) opoint) (outline-on-heading-p t))
23141 (while (and (> (funcall outline-level) level)
23142 (not (bobp)))
23143 (outline-previous-heading))
23144 (unless (< (funcall outline-level) level)
23145 (point)))))
23147 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23148 "Goto to the end of a subtree."
23149 ;; This contains an exact copy of the original function, but it uses
23150 ;; `org-back-to-heading', to make it work also in invisible
23151 ;; trees. And is uses an invisible-ok argument.
23152 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23153 ;; Furthermore, when used inside Org, finding the end of a large subtree
23154 ;; with many children and grandchildren etc, this can be much faster
23155 ;; than the outline version.
23156 (org-back-to-heading invisible-ok)
23157 (let ((first t)
23158 (level (funcall outline-level)))
23159 (if (and (derived-mode-p 'org-mode) (< level 1000))
23160 ;; A true heading (not a plain list item), in Org
23161 ;; This means we can easily find the end by looking
23162 ;; only for the right number of stars. Using a regexp to do
23163 ;; this is so much faster than using a Lisp loop.
23164 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23165 (forward-char 1)
23166 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23167 ;; something else, do it the slow way
23168 (while (and (not (eobp))
23169 (or first (> (funcall outline-level) level)))
23170 (setq first nil)
23171 (outline-next-heading)))
23172 (unless to-heading
23173 (when (memq (preceding-char) '(?\n ?\^M))
23174 ;; Go to end of line before heading
23175 (forward-char -1)
23176 (when (memq (preceding-char) '(?\n ?\^M))
23177 ;; leave blank line before heading
23178 (forward-char -1)))))
23179 (point))
23181 (defun org-end-of-meta-data (&optional full)
23182 "Skip planning line and properties drawer in current entry.
23183 When optional argument FULL is non-nil, also skip empty lines,
23184 clocking lines and regular drawers at the beginning of the
23185 entry."
23186 (org-back-to-heading t)
23187 (forward-line)
23188 (when (looking-at-p org-planning-line-re) (forward-line))
23189 (when (looking-at org-property-drawer-re)
23190 (goto-char (match-end 0))
23191 (forward-line))
23192 (when (and full (not (org-at-heading-p)))
23193 (catch 'exit
23194 (let ((end (save-excursion (outline-next-heading) (point)))
23195 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
23196 (while (not (eobp))
23197 (cond ((looking-at-p org-drawer-regexp)
23198 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
23199 (forward-line)
23200 (throw 'exit t)))
23201 ((looking-at-p re) (forward-line))
23202 (t (throw 'exit t))))))))
23204 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23205 "Move forward to the ARG'th subheading at same level as this one.
23206 Stop at the first and last subheadings of a superior heading.
23207 Normally this only looks at visible headings, but when INVISIBLE-OK is
23208 non-nil it will also look at invisible ones."
23209 (interactive "p")
23210 (let ((backward? (and arg (< arg 0))))
23211 (if (org-before-first-heading-p)
23212 (if backward? (goto-char (point-min)) (outline-next-heading))
23213 (org-back-to-heading invisible-ok)
23214 (unless backward? (end-of-line)) ;do not match current headline
23215 (let ((level (- (match-end 0) (match-beginning 0) 1))
23216 (f (if backward? #'re-search-backward #'re-search-forward))
23217 (count (if arg (abs arg) 1))
23218 (result (point)))
23219 (while (and (> count 0)
23220 (funcall f org-outline-regexp-bol nil 'move))
23221 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23222 (cond ((< l level) (setq count 0))
23223 ((and (= l level)
23224 (or invisible-ok
23225 (not (org-invisible-p
23226 (line-beginning-position)))))
23227 (cl-decf count)
23228 (when (= l level) (setq result (point)))))))
23229 (goto-char result))
23230 (beginning-of-line))))
23232 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23233 "Move backward to the ARG'th subheading at same level as this one.
23234 Stop at the first and last subheadings of a superior heading."
23235 (interactive "p")
23236 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23238 (defun org-next-visible-heading (arg)
23239 "Move to the next visible heading.
23241 This function wraps `outline-next-visible-heading' with
23242 `org-with-limited-levels' in order to skip over inline tasks and
23243 respect customization of `org-odd-levels-only'."
23244 (interactive "p")
23245 (org-with-limited-levels
23246 (outline-next-visible-heading arg)))
23248 (defun org-previous-visible-heading (arg)
23249 "Move to the previous visible heading.
23251 This function wraps `outline-previous-visible-heading' with
23252 `org-with-limited-levels' in order to skip over inline tasks and
23253 respect customization of `org-odd-levels-only'."
23254 (interactive "p")
23255 (org-with-limited-levels
23256 (outline-previous-visible-heading arg)))
23258 (defun org-forward-paragraph ()
23259 "Move forward to beginning of next paragraph or equivalent.
23261 The function moves point to the beginning of the next visible
23262 structural element, which can be a paragraph, a table, a list
23263 item, etc. It also provides some special moves for convenience:
23265 - On an affiliated keyword, jump to the beginning of the
23266 relative element.
23267 - On an item or a footnote definition, move to the second
23268 element inside, if any.
23269 - On a table or a property drawer, jump after it.
23270 - On a verse or source block, stop after blank lines."
23271 (interactive)
23272 (unless (eobp)
23273 (let* ((deactivate-mark nil)
23274 (element (org-element-at-point))
23275 (type (org-element-type element))
23276 (post-affiliated (org-element-property :post-affiliated element))
23277 (contents-begin (org-element-property :contents-begin element))
23278 (contents-end (org-element-property :contents-end element))
23279 (end (let ((end (org-element-property :end element)) (parent element))
23280 (while (and (setq parent (org-element-property :parent parent))
23281 (= (org-element-property :contents-end parent) end))
23282 (setq end (org-element-property :end parent)))
23283 end)))
23284 (cond ((not element)
23285 (skip-chars-forward " \r\t\n")
23286 (or (eobp) (beginning-of-line)))
23287 ;; On affiliated keywords, move to element's beginning.
23288 ((< (point) post-affiliated)
23289 (goto-char post-affiliated))
23290 ;; At a table row, move to the end of the table. Similarly,
23291 ;; at a node property, move to the end of the property
23292 ;; drawer.
23293 ((memq type '(node-property table-row))
23294 (goto-char (org-element-property
23295 :end (org-element-property :parent element))))
23296 ((memq type '(property-drawer table)) (goto-char end))
23297 ;; Consider blank lines as separators in verse and source
23298 ;; blocks to ease editing.
23299 ((memq type '(src-block verse-block))
23300 (when (eq type 'src-block)
23301 (setq contents-end
23302 (save-excursion (goto-char end)
23303 (skip-chars-backward " \r\t\n")
23304 (line-beginning-position))))
23305 (beginning-of-line)
23306 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
23307 (if (not (re-search-forward "^[ \t]*$" contents-end t))
23308 (goto-char end)
23309 (skip-chars-forward " \r\t\n")
23310 (if (= (point) contents-end) (goto-char end)
23311 (beginning-of-line))))
23312 ;; With no contents, just skip element.
23313 ((not contents-begin) (goto-char end))
23314 ;; If contents are invisible, skip the element altogether.
23315 ((org-invisible-p (line-end-position))
23316 (cl-case type
23317 (headline
23318 (org-with-limited-levels (outline-next-visible-heading 1)))
23319 ;; At a plain list, make sure we move to the next item
23320 ;; instead of skipping the whole list.
23321 (plain-list (forward-char)
23322 (org-forward-paragraph))
23323 (otherwise (goto-char end))))
23324 ((>= (point) contents-end) (goto-char end))
23325 ((>= (point) contents-begin)
23326 ;; This can only happen on paragraphs and plain lists.
23327 (cl-case type
23328 (paragraph (goto-char end))
23329 ;; At a plain list, try to move to second element in
23330 ;; first item, if possible.
23331 (plain-list (end-of-line)
23332 (org-forward-paragraph))))
23333 ;; When contents start on the middle of a line (e.g. in
23334 ;; items and footnote definitions), try to reach first
23335 ;; element starting after current line.
23336 ((> (line-end-position) contents-begin)
23337 (end-of-line)
23338 (org-forward-paragraph))
23339 (t (goto-char contents-begin))))))
23341 (defun org-backward-paragraph ()
23342 "Move backward to start of previous paragraph or equivalent.
23344 The function moves point to the beginning of the current
23345 structural element, which can be a paragraph, a table, a list
23346 item, etc., or to the beginning of the previous visible one if
23347 point is already there. It also provides some special moves for
23348 convenience:
23350 - On an affiliated keyword, jump to the first one.
23351 - On a table or a property drawer, move to its beginning.
23352 - On comment, example, export, src and verse blocks, stop
23353 before blank lines."
23354 (interactive)
23355 (unless (bobp)
23356 (let* ((deactivate-mark nil)
23357 (element (org-element-at-point))
23358 (type (org-element-type element))
23359 (contents-end (org-element-property :contents-end element))
23360 (post-affiliated (org-element-property :post-affiliated element))
23361 (begin (org-element-property :begin element))
23362 (special? ;blocks handled specially
23363 (memq type '(comment-block example-block export-block src-block
23364 verse-block)))
23365 (contents-begin
23366 (if special?
23367 ;; These types have no proper contents. Fake line
23368 ;; below the block opening line as contents beginning.
23369 (save-excursion (goto-char begin) (line-beginning-position 2))
23370 (org-element-property :contents-begin element))))
23371 (cond
23372 ((not element) (goto-char (point-min)))
23373 ((= (point) begin)
23374 (backward-char)
23375 (org-backward-paragraph))
23376 ((<= (point) post-affiliated) (goto-char begin))
23377 ;; Special behavior: on a table or a property drawer, move to
23378 ;; its beginning.
23379 ((memq type '(node-property table-row))
23380 (goto-char (org-element-property
23381 :post-affiliated (org-element-property :parent element))))
23382 (special?
23383 (if (<= (point) contents-begin) (goto-char post-affiliated)
23384 ;; Inside a verse block, see blank lines as paragraph
23385 ;; separators.
23386 (let ((origin (point)))
23387 (skip-chars-backward " \r\t\n" contents-begin)
23388 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
23389 (skip-chars-forward " \r\t\n" origin)
23390 (if (= (point) origin) (goto-char contents-begin)
23391 (beginning-of-line))))))
23392 ((eq type 'paragraph) (goto-char contents-begin)
23393 ;; When at first paragraph in an item or a footnote definition,
23394 ;; move directly to beginning of line.
23395 (let ((parent-contents
23396 (org-element-property
23397 :contents-begin (org-element-property :parent element))))
23398 (when (and parent-contents (= parent-contents contents-begin))
23399 (beginning-of-line))))
23400 ;; At the end of a greater element, move to the beginning of
23401 ;; the last element within.
23402 ((and contents-end (>= (point) contents-end))
23403 (goto-char (1- contents-end))
23404 (org-backward-paragraph))
23405 (t (goto-char (or post-affiliated begin))))
23406 ;; Ensure we never leave point invisible.
23407 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
23409 (defun org-forward-element ()
23410 "Move forward by one element.
23411 Move to the next element at the same level, when possible."
23412 (interactive)
23413 (cond ((eobp) (user-error "Cannot move further down"))
23414 ((org-with-limited-levels (org-at-heading-p))
23415 (let ((origin (point)))
23416 (goto-char (org-end-of-subtree nil t))
23417 (unless (org-with-limited-levels (org-at-heading-p))
23418 (goto-char origin)
23419 (user-error "Cannot move further down"))))
23421 (let* ((elem (org-element-at-point))
23422 (end (org-element-property :end elem))
23423 (parent (org-element-property :parent elem)))
23424 (cond ((and parent (= (org-element-property :contents-end parent) end))
23425 (goto-char (org-element-property :end parent)))
23426 ((integer-or-marker-p end) (goto-char end))
23427 (t (message "No element at point")))))))
23429 (defun org-backward-element ()
23430 "Move backward by one element.
23431 Move to the previous element at the same level, when possible."
23432 (interactive)
23433 (cond ((bobp) (user-error "Cannot move further up"))
23434 ((org-with-limited-levels (org-at-heading-p))
23435 ;; At a headline, move to the previous one, if any, or stay
23436 ;; here.
23437 (let ((origin (point)))
23438 (org-with-limited-levels (org-backward-heading-same-level 1))
23439 ;; When current headline has no sibling above, move to its
23440 ;; parent.
23441 (when (= (point) origin)
23442 (or (org-with-limited-levels (org-up-heading-safe))
23443 (progn (goto-char origin)
23444 (user-error "Cannot move further up"))))))
23446 (let* ((elem (org-element-at-point))
23447 (beg (org-element-property :begin elem)))
23448 (cond
23449 ;; Move to beginning of current element if point isn't
23450 ;; there already.
23451 ((null beg) (message "No element at point"))
23452 ((/= (point) beg) (goto-char beg))
23453 (t (goto-char beg)
23454 (skip-chars-backward " \r\t\n")
23455 (unless (bobp)
23456 (let ((prev (org-element-at-point)))
23457 (goto-char (org-element-property :begin prev))
23458 (while (and (setq prev (org-element-property :parent prev))
23459 (<= (org-element-property :end prev) beg))
23460 (goto-char (org-element-property :begin prev)))))))))))
23462 (defun org-up-element ()
23463 "Move to upper element."
23464 (interactive)
23465 (if (org-with-limited-levels (org-at-heading-p))
23466 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23467 (let* ((elem (org-element-at-point))
23468 (parent (org-element-property :parent elem)))
23469 (if parent (goto-char (org-element-property :begin parent))
23470 (if (org-with-limited-levels (org-before-first-heading-p))
23471 (user-error "No surrounding element")
23472 (org-with-limited-levels (org-back-to-heading)))))))
23474 (defun org-down-element ()
23475 "Move to inner element."
23476 (interactive)
23477 (let ((element (org-element-at-point)))
23478 (cond
23479 ((memq (org-element-type element) '(plain-list table))
23480 (goto-char (org-element-property :contents-begin element))
23481 (forward-char))
23482 ((memq (org-element-type element) org-element-greater-elements)
23483 ;; If contents are hidden, first disclose them.
23484 (when (org-invisible-p (line-end-position)) (org-cycle))
23485 (goto-char (or (org-element-property :contents-begin element)
23486 (user-error "No content for this element"))))
23487 (t (user-error "No inner element")))))
23489 (defun org-drag-element-backward ()
23490 "Move backward element at point."
23491 (interactive)
23492 (let ((elem (or (org-element-at-point)
23493 (user-error "No element at point"))))
23494 (if (eq (org-element-type elem) 'headline)
23495 ;; Preserve point when moving a whole tree, even if point was
23496 ;; on blank lines below the headline.
23497 (let ((offset (skip-chars-backward " \t\n")))
23498 (unwind-protect (org-move-subtree-up)
23499 (forward-char (- offset))))
23500 (let ((prev-elem
23501 (save-excursion
23502 (goto-char (org-element-property :begin elem))
23503 (skip-chars-backward " \r\t\n")
23504 (unless (bobp)
23505 (let* ((beg (org-element-property :begin elem))
23506 (prev (org-element-at-point))
23507 (up prev))
23508 (while (and (setq up (org-element-property :parent up))
23509 (<= (org-element-property :end up) beg))
23510 (setq prev up))
23511 prev)))))
23512 ;; Error out if no previous element or previous element is
23513 ;; a parent of the current one.
23514 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23515 (user-error "Cannot drag element backward")
23516 (let ((pos (point)))
23517 (org-element-swap-A-B prev-elem elem)
23518 (goto-char (+ (org-element-property :begin prev-elem)
23519 (- pos (org-element-property :begin elem))))))))))
23521 (defun org-drag-element-forward ()
23522 "Move forward element at point."
23523 (interactive)
23524 (let* ((pos (point))
23525 (elem (or (org-element-at-point)
23526 (user-error "No element at point"))))
23527 (when (= (point-max) (org-element-property :end elem))
23528 (user-error "Cannot drag element forward"))
23529 (goto-char (org-element-property :end elem))
23530 (let ((next-elem (org-element-at-point)))
23531 (when (or (org-element-nested-p elem next-elem)
23532 (and (eq (org-element-type next-elem) 'headline)
23533 (not (eq (org-element-type elem) 'headline))))
23534 (goto-char pos)
23535 (user-error "Cannot drag element forward"))
23536 ;; Compute new position of point: it's shifted by NEXT-ELEM
23537 ;; body's length (without final blanks) and by the length of
23538 ;; blanks between ELEM and NEXT-ELEM.
23539 (let ((size-next (- (save-excursion
23540 (goto-char (org-element-property :end next-elem))
23541 (skip-chars-backward " \r\t\n")
23542 (forward-line)
23543 ;; Small correction if buffer doesn't end
23544 ;; with a newline character.
23545 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23546 (org-element-property :begin next-elem)))
23547 (size-blank (- (org-element-property :end elem)
23548 (save-excursion
23549 (goto-char (org-element-property :end elem))
23550 (skip-chars-backward " \r\t\n")
23551 (forward-line)
23552 (point)))))
23553 (org-element-swap-A-B elem next-elem)
23554 (goto-char (+ pos size-next size-blank))))))
23556 (defun org-drag-line-forward (arg)
23557 "Drag the line at point ARG lines forward."
23558 (interactive "p")
23559 (dotimes (_ (abs arg))
23560 (let ((c (current-column)))
23561 (if (< 0 arg)
23562 (progn
23563 (beginning-of-line 2)
23564 (transpose-lines 1)
23565 (beginning-of-line 0))
23566 (transpose-lines 1)
23567 (beginning-of-line -1))
23568 (org-move-to-column c))))
23570 (defun org-drag-line-backward (arg)
23571 "Drag the line at point ARG lines backward."
23572 (interactive "p")
23573 (org-drag-line-forward (- arg)))
23575 (defun org-mark-element ()
23576 "Put point at beginning of this element, mark at end.
23578 Interactively, if this command is repeated or (in Transient Mark
23579 mode) if the mark is active, it marks the next element after the
23580 ones already marked."
23581 (interactive)
23582 (let (deactivate-mark)
23583 (if (and (called-interactively-p 'any)
23584 (or (and (eq last-command this-command) (mark t))
23585 (and transient-mark-mode mark-active)))
23586 (set-mark
23587 (save-excursion
23588 (goto-char (mark))
23589 (goto-char (org-element-property :end (org-element-at-point)))))
23590 (let ((element (org-element-at-point)))
23591 (end-of-line)
23592 (push-mark (org-element-property :end element) t t)
23593 (goto-char (org-element-property :begin element))))))
23595 (defun org-narrow-to-element ()
23596 "Narrow buffer to current element."
23597 (interactive)
23598 (let ((elem (org-element-at-point)))
23599 (cond
23600 ((eq (car elem) 'headline)
23601 (narrow-to-region
23602 (org-element-property :begin elem)
23603 (org-element-property :end elem)))
23604 ((memq (car elem) org-element-greater-elements)
23605 (narrow-to-region
23606 (org-element-property :contents-begin elem)
23607 (org-element-property :contents-end elem)))
23609 (narrow-to-region
23610 (org-element-property :begin elem)
23611 (org-element-property :end elem))))))
23613 (defun org-transpose-element ()
23614 "Transpose current and previous elements, keeping blank lines between.
23615 Point is moved after both elements."
23616 (interactive)
23617 (org-skip-whitespace)
23618 (let ((end (org-element-property :end (org-element-at-point))))
23619 (org-drag-element-backward)
23620 (goto-char end)))
23622 (defun org-unindent-buffer ()
23623 "Un-indent the visible part of the buffer.
23624 Relative indentation (between items, inside blocks, etc.) isn't
23625 modified."
23626 (interactive)
23627 (unless (eq major-mode 'org-mode)
23628 (user-error "Cannot un-indent a buffer not in Org mode"))
23629 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
23630 (unindent-tree
23631 (lambda (contents)
23632 (dolist (element (reverse contents))
23633 (if (memq (org-element-type element) '(headline section))
23634 (funcall unindent-tree (org-element-contents element))
23635 (save-excursion
23636 (save-restriction
23637 (narrow-to-region
23638 (org-element-property :begin element)
23639 (org-element-property :end element))
23640 (org-do-remove-indentation))))))))
23641 (funcall unindent-tree (org-element-contents parse-tree))))
23643 (defun org-make-options-regexp (kwds &optional extra)
23644 "Make a regular expression for keyword lines.
23645 KWDS is a list of keywords, as strings. Optional argument EXTRA,
23646 when non-nil, is a regexp matching keywords names."
23647 (concat "^[ \t]*#\\+\\("
23648 (regexp-opt kwds)
23649 (and extra (concat (and kwds "\\|") extra))
23650 "\\):[ \t]*\\(.*\\)"))
23653 ;;; Finish up
23655 (add-hook 'org-mode-hook ;remove overlays when changing major mode
23656 (lambda () (add-hook 'change-major-mode-hook
23657 'org-show-all 'append 'local)))
23659 (provide 'org)
23661 (run-hooks 'org-load-hook)
23663 ;;; org.el ends here