Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobd374882a6303977e1e46111b40c76d05ed3aceec
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function
133 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
134 (declare-function org-element-at-point "org-element" ())
135 (declare-function org-element-cache-refresh "org-element" (pos))
136 (declare-function org-element-cache-reset "org-element" (&optional all))
137 (declare-function org-element-contents "org-element" (element))
138 (declare-function org-element-context "org-element" (&optional element))
139 (declare-function org-element-copy "org-element" (datum))
140 (declare-function org-element-interpret-data "org-element" (data))
141 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
142 (declare-function org-element-link-parser "org-element" ())
143 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
144 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-put-property "org-element" (element property value))
147 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
148 (declare-function org-element-type "org-element" (element))
149 (declare-function org-element-update-syntax "org-element" ())
150 (declare-function org-id-find-id-file "org-id" (id))
151 (declare-function org-id-get-create "org-id" (&optional force))
152 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
153 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
154 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
155 (declare-function org-plot/gnuplot "org-plot" (&optional params))
156 (declare-function org-table-align "org-table" ())
157 (declare-function org-table-begin "org-table" (&optional table-type))
158 (declare-function org-table-beginning-of-field "org-table" (&optional n))
159 (declare-function org-table-blank-field "org-table" ())
160 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
161 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
162 (declare-function org-table-cut-region "org-table" (beg end))
163 (declare-function org-table-edit-field "org-table" (arg))
164 (declare-function org-table-end "org-table" (&optional table-type))
165 (declare-function org-table-end-of-field "org-table" (&optional n))
166 (declare-function org-table-insert-row "org-table" (&optional arg))
167 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
168 (declare-function org-table-maybe-eval-formula "org-table" ())
169 (declare-function org-table-maybe-recalculate-line "org-table" ())
170 (declare-function org-table-next-row "org-table" ())
171 (declare-function org-table-paste-rectangle "org-table" ())
172 (declare-function org-table-recalculate "org-table" (&optional all noalign))
173 (declare-function
174 org-table-sort-lines "org-table"
175 (&optional with-case sorting-type getkey-func compare-func interactive?))
176 (declare-function org-table-wrap-region "org-table" (arg))
177 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
178 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
179 (declare-function orgtbl-mode "org-table" (&optional arg))
180 (declare-function org-export-get-backend "ox" (name))
181 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
182 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
184 (defvar ffap-url-regexp) ;Silence byte-compiler
186 (defsubst org-uniquify (list)
187 "Non-destructively remove duplicate elements from LIST."
188 (let ((res (copy-sequence list))) (delete-dups res)))
190 (defsubst org-get-at-bol (property)
191 "Get text property PROPERTY at the beginning of line."
192 (get-text-property (point-at-bol) property))
194 (defsubst org-trim (s &optional keep-lead)
195 "Remove whitespace at the beginning and the end of string S.
196 When optional argument KEEP-LEAD is non-nil, removing blank lines
197 at the beginning of the string does not affect leading indentation."
198 (replace-regexp-in-string
199 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
200 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
202 ;; load languages based on value of `org-babel-load-languages'
203 (defvar org-babel-load-languages)
205 ;;;###autoload
206 (defun org-babel-do-load-languages (sym value)
207 "Load the languages defined in `org-babel-load-languages'."
208 (set-default sym value)
209 (dolist (pair org-babel-load-languages)
210 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
211 (if active
212 (require (intern (concat "ob-" lang)))
213 (funcall 'fmakunbound
214 (intern (concat "org-babel-execute:" lang)))
215 (funcall 'fmakunbound
216 (intern (concat "org-babel-expand-body:" lang)))))))
218 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
219 ;;;###autoload
220 (defun org-babel-load-file (file &optional compile)
221 "Load Emacs Lisp source code blocks in the Org FILE.
222 This function exports the source code using `org-babel-tangle'
223 and then loads the resulting file using `load-file'. With prefix
224 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
225 file to byte-code before it is loaded."
226 (interactive "fFile to load: \nP")
227 (let* ((age (lambda (file)
228 (float-time
229 (time-subtract (current-time)
230 (nth 5 (or (file-attributes (file-truename file))
231 (file-attributes file)))))))
232 (base-name (file-name-sans-extension file))
233 (exported-file (concat base-name ".el")))
234 ;; tangle if the Org file is newer than the elisp file
235 (unless (and (file-exists-p exported-file)
236 (> (funcall age file) (funcall age exported-file)))
237 ;; Tangle-file traversal returns reversed list of tangled files
238 ;; and we want to evaluate the first target.
239 (setq exported-file
240 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
241 (message "%s %s"
242 (if compile
243 (progn (byte-compile-file exported-file 'load)
244 "Compiled and loaded")
245 (progn (load-file exported-file) "Loaded"))
246 exported-file)))
248 (defcustom org-babel-load-languages '((emacs-lisp . t))
249 "Languages which can be evaluated in Org buffers.
250 This list can be used to load support for any of the languages
251 below, note that each language will depend on a different set of
252 system executables and/or Emacs modes. When a language is
253 \"loaded\", then code blocks in that language can be evaluated
254 with `org-babel-execute-src-block' bound by default to C-c
255 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
256 be set to remove code block evaluation from the C-c C-c
257 keybinding. By default only Emacs Lisp (which has no
258 requirements) is loaded."
259 :group 'org-babel
260 :set 'org-babel-do-load-languages
261 :version "24.1"
262 :type '(alist :tag "Babel Languages"
263 :key-type
264 (choice
265 (const :tag "Awk" awk)
266 (const :tag "C" C)
267 (const :tag "R" R)
268 (const :tag "Asymptote" asymptote)
269 (const :tag "Calc" calc)
270 (const :tag "Clojure" clojure)
271 (const :tag "CSS" css)
272 (const :tag "Ditaa" ditaa)
273 (const :tag "Dot" dot)
274 (const :tag "Emacs Lisp" emacs-lisp)
275 (const :tag "Forth" forth)
276 (const :tag "Fortran" fortran)
277 (const :tag "Gnuplot" gnuplot)
278 (const :tag "Haskell" haskell)
279 (const :tag "hledger" hledger)
280 (const :tag "IO" io)
281 (const :tag "J" J)
282 (const :tag "Java" java)
283 (const :tag "Javascript" js)
284 (const :tag "LaTeX" latex)
285 (const :tag "Ledger" ledger)
286 (const :tag "Lilypond" lilypond)
287 (const :tag "Lisp" lisp)
288 (const :tag "Makefile" makefile)
289 (const :tag "Maxima" maxima)
290 (const :tag "Matlab" matlab)
291 (const :tag "Mscgen" mscgen)
292 (const :tag "Ocaml" ocaml)
293 (const :tag "Octave" octave)
294 (const :tag "Org" org)
295 (const :tag "Perl" perl)
296 (const :tag "Pico Lisp" picolisp)
297 (const :tag "PlantUML" plantuml)
298 (const :tag "Python" python)
299 (const :tag "Ruby" ruby)
300 (const :tag "Sass" sass)
301 (const :tag "Scala" scala)
302 (const :tag "Scheme" scheme)
303 (const :tag "Screen" screen)
304 (const :tag "Shell Script" shell)
305 (const :tag "Shen" shen)
306 (const :tag "Sql" sql)
307 (const :tag "Sqlite" sqlite)
308 (const :tag "Stan" stan)
309 (const :tag "ebnf2ps" ebnf2ps))
310 :value-type (boolean :tag "Activate" :value t)))
312 ;;;; Customization variables
313 (defcustom org-clone-delete-id nil
314 "Remove ID property of clones of a subtree.
315 When non-nil, clones of a subtree don't inherit the ID property.
316 Otherwise they inherit the ID property with a new unique
317 identifier."
318 :type 'boolean
319 :version "24.1"
320 :group 'org-id)
322 ;;; Version
323 (org-check-version)
325 ;;;###autoload
326 (defun org-version (&optional here full message)
327 "Show the Org version.
328 Interactively, or when MESSAGE is non-nil, show it in echo area.
329 With prefix argument, or when HERE is non-nil, insert it at point.
330 In non-interactive uses, a reduced version string is output unless
331 FULL is given."
332 (interactive (list current-prefix-arg t (not current-prefix-arg)))
333 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
334 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
335 (load-suffixes (list ".el"))
336 (org-install-dir
337 (ignore-errors (org-find-library-dir "org-loaddefs"))))
338 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
339 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
340 (let* ((load-suffixes save-load-suffixes)
341 (release (org-release))
342 (git-version (org-git-version))
343 (version (format "Org mode version %s (%s @ %s)"
344 release
345 git-version
346 (if org-install-dir
347 (if (string= org-dir org-install-dir)
348 org-install-dir
349 (concat "mixed installation! "
350 org-install-dir
351 " and "
352 org-dir))
353 "org-loaddefs.el can not be found!")))
354 (version1 (if full version release)))
355 (when here (insert version1))
356 (when message (message "%s" version1))
357 version1)))
359 (defconst org-version (org-version))
362 ;;; Syntax Constants
364 ;;;; Block
366 (defconst org-block-regexp
367 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
368 "Regular expression for hiding blocks.")
370 (defconst org-dblock-start-re
371 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
372 "Matches the start line of a dynamic block, with parameters.")
374 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
375 "Matches the end of a dynamic block.")
377 ;;;; Clock and Planning
379 (defconst org-clock-string "CLOCK:"
380 "String used as prefix for timestamps clocking work hours on an item.")
382 (defvar org-closed-string "CLOSED:"
383 "String used as the prefix for timestamps logging closing a TODO entry.")
385 (defvar org-deadline-string "DEADLINE:"
386 "String to mark deadline entries.
387 \\<org-mode-map>
388 A deadline is this string, followed by a time stamp. It must be
389 a word, terminated by a colon. You can insert a schedule keyword
390 and a timestamp with `\\[org-deadline]'.")
392 (defvar org-scheduled-string "SCHEDULED:"
393 "String to mark scheduled TODO entries.
394 \\<org-mode-map>
395 A schedule is this string, followed by a time stamp. It must be
396 a word, terminated by a colon. You can insert a schedule keyword
397 and a timestamp with `\\[org-schedule]'.")
399 (defconst org-ds-keyword-length
400 (+ 2
401 (apply #'max
402 (mapcar #'length
403 (list org-deadline-string org-scheduled-string
404 org-clock-string org-closed-string))))
405 "Maximum length of the DEADLINE and SCHEDULED keywords.")
407 (defconst org-planning-line-re
408 (concat "^[ \t]*"
409 (regexp-opt
410 (list org-closed-string org-deadline-string org-scheduled-string)
412 "Matches a line with planning info.
413 Matched keyword is in group 1.")
415 (defconst org-clock-line-re
416 (concat "^[ \t]*" org-clock-string)
417 "Matches a line with clock info.")
419 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
420 "Matches the DEADLINE keyword.")
422 (defconst org-deadline-time-regexp
423 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
424 "Matches the DEADLINE keyword together with a time stamp.")
426 (defconst org-deadline-time-hour-regexp
427 (concat "\\<" org-deadline-string
428 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
429 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
431 (defconst org-deadline-line-regexp
432 (concat "\\<\\(" org-deadline-string "\\).*")
433 "Matches the DEADLINE keyword and the rest of the line.")
435 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
436 "Matches the SCHEDULED keyword.")
438 (defconst org-scheduled-time-regexp
439 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
440 "Matches the SCHEDULED keyword together with a time stamp.")
442 (defconst org-scheduled-time-hour-regexp
443 (concat "\\<" org-scheduled-string
444 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
445 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
447 (defconst org-closed-time-regexp
448 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
449 "Matches the CLOSED keyword together with a time stamp.")
451 (defconst org-keyword-time-regexp
452 (concat "\\<"
453 (regexp-opt
454 (list org-scheduled-string org-deadline-string org-closed-string
455 org-clock-string)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 4 keywords, together with the time stamp.")
460 (defconst org-keyword-time-not-clock-regexp
461 (concat
462 "\\<"
463 (regexp-opt
464 (list org-scheduled-string org-deadline-string org-closed-string) t)
465 " *[[<]\\([^]>]+\\)[]>]")
466 "Matches any of the 3 keywords, together with the time stamp.")
468 (defconst org-maybe-keyword-time-regexp
469 (concat "\\(\\<"
470 (regexp-opt
471 (list org-scheduled-string org-deadline-string org-closed-string
472 org-clock-string)
474 "\\)?"
475 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
476 "\\|"
477 "<%%([^\r\n>]*>\\)")
478 "Matches a timestamp, possibly preceded by a keyword.")
480 (defconst org-all-time-keywords
481 (mapcar (lambda (w) (substring w 0 -1))
482 (list org-scheduled-string org-deadline-string
483 org-clock-string org-closed-string))
484 "List of time keywords.")
486 ;;;; Drawer
488 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
489 "Matches first or last line of a hidden block.
490 Group 1 contains drawer's name or \"END\".")
492 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
493 "Regular expression matching the first line of a property drawer.")
495 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
496 "Regular expression matching the last line of a property drawer.")
498 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
499 "Regular expression matching the first line of a clock drawer.")
501 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
502 "Regular expression matching the last line of a clock drawer.")
504 (defconst org-property-drawer-re
505 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
506 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
507 "[ \t]*:END:[ \t]*$")
508 "Matches an entire property drawer.")
510 (defconst org-clock-drawer-re
511 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
512 org-clock-drawer-end-re "\\)\n?")
513 "Matches an entire clock drawer.")
515 ;;;; Headline
517 (defconst org-heading-keyword-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline with some keyword.
520 This regexp will match the headline of any node which has the
521 exact keyword that is put into the format. The keyword isn't in
522 any group by default, but the stars and the body are.")
524 (defconst org-heading-keyword-maybe-regexp-format
525 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
526 "Printf format for a regexp matching a headline, possibly with some keyword.
527 This regexp can match any headline with the specified keyword, or
528 without a keyword. The keyword isn't in any group by default,
529 but the stars and the body are.")
531 (defconst org-archive-tag "ARCHIVE"
532 "The tag that marks a subtree as archived.
533 An archived subtree does not open during visibility cycling, and does
534 not contribute to the agenda listings.")
536 (eval-and-compile
537 (defconst org-comment-string "COMMENT"
538 "Entries starting with this keyword will never be exported.
539 \\<org-mode-map>
540 An entry can be toggled between COMMENT and normal with
541 `\\[org-toggle-comment]'."))
544 ;;;; LaTeX Environments and Fragments
546 (defconst org-latex-regexps
547 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
548 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
549 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
550 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
551 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
552 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
553 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
554 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
555 "Regular expressions for matching embedded LaTeX.")
557 ;;;; Node Property
559 (defconst org-effort-property "Effort"
560 "The property that is being used to keep track of effort estimates.
561 Effort estimates given in this property need to have the format H:MM.")
563 ;;;; Table
565 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
566 "Detect an org-type or table-type table.")
568 (defconst org-table-line-regexp "^[ \t]*|"
569 "Detect an org-type table line.")
571 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
572 "Detect an org-type table line.")
574 (defconst org-table-hline-regexp "^[ \t]*|-"
575 "Detect an org-type table hline.")
577 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
578 "Detect a table-type table hline.")
580 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
581 "Detect the first line outside a table when searching from within it.
582 This works for both table types.")
584 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
585 "Detect a #+TBLFM line.")
587 ;;;; Timestamp
589 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
590 "Regular expression for fast time stamp matching.")
592 (defconst org-ts-regexp-inactive
593 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
594 "Regular expression for fast inactive time stamp matching.")
596 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
597 "Regular expression for fast time stamp matching.")
599 (defconst org-ts-regexp0
600 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
601 "Regular expression matching time strings for analysis.
602 This one does not require the space after the date, so it can be used
603 on a string that terminates immediately after the date.")
605 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
606 "Regular expression matching time strings for analysis.")
608 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
609 "Regular expression matching time stamps, with groups.")
611 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
612 "Regular expression matching time stamps (also [..]), with groups.")
614 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
615 "Regular expression matching a time stamp range.")
617 (defconst org-tr-regexp-both
618 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
619 "Regular expression matching a time stamp range.")
621 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
622 org-ts-regexp "\\)?")
623 "Regular expression matching a time stamp or time stamp range.")
625 (defconst org-tsr-regexp-both
626 (concat org-ts-regexp-both "\\(--?-?"
627 org-ts-regexp-both "\\)?")
628 "Regular expression matching a time stamp or time stamp range.
629 The time stamps may be either active or inactive.")
631 (defconst org-repeat-re
632 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
633 "Regular expression for specifying repeated events.
634 After a match, group 1 contains the repeat expression.")
636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
637 "Formats for `format-time-string' which are used for time stamps.")
640 ;;; The custom variables
642 (defgroup org nil
643 "Outline-based notes management and organizer."
644 :tag "Org"
645 :group 'outlines
646 :group 'calendar)
648 (defcustom org-mode-hook nil
649 "Mode hook for Org mode, run after the mode was turned on."
650 :group 'org
651 :type 'hook)
653 (defcustom org-load-hook nil
654 "Hook that is run after org.el has been loaded."
655 :group 'org
656 :type 'hook)
658 (defcustom org-log-buffer-setup-hook nil
659 "Hook that is run after an Org log buffer is created."
660 :group 'org
661 :version "24.1"
662 :type 'hook)
664 (defvar org-modules) ; defined below
665 (defvar org-modules-loaded nil
666 "Have the modules been loaded already?")
668 (defun org-load-modules-maybe (&optional force)
669 "Load all extensions listed in `org-modules'."
670 (when (or force (not org-modules-loaded))
671 (dolist (ext org-modules)
672 (condition-case nil (require ext)
673 (error (message "Problems while trying to load feature `%s'" ext))))
674 (setq org-modules-loaded t)))
676 (defun org-set-modules (var value)
677 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
678 (set var value)
679 (when (featurep 'org)
680 (org-load-modules-maybe 'force)
681 (org-element-cache-reset 'all)))
683 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
684 "Modules that should always be loaded together with org.el.
686 If a description starts with <C>, the file is not part of Emacs
687 and loading it will require that you have downloaded and properly
688 installed the Org mode distribution.
690 You can also use this system to load external packages (i.e. neither Org
691 core modules, nor modules from the CONTRIB directory). Just add symbols
692 to the end of the list. If the package is called org-xyz.el, then you need
693 to add the symbol `xyz', and the package must have a call to:
695 (provide \\='org-xyz)
697 For export specific modules, see also `org-export-backends'."
698 :group 'org
699 :set 'org-set-modules
700 :version "24.4"
701 :package-version '(Org . "8.0")
702 :type
703 '(set :greedy t
704 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
705 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
706 (const :tag " crypt: Encryption of subtrees" org-crypt)
707 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
708 (const :tag " docview: Links to doc-view buffers" org-docview)
709 (const :tag " eww: Store link to url of eww" org-eww)
710 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
711 (const :tag " habit: Track your consistency with habits" org-habit)
712 (const :tag " id: Global IDs for identifying entries" org-id)
713 (const :tag " info: Links to Info nodes" org-info)
714 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
715 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
716 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
717 (const :tag " mouse: Additional mouse support" org-mouse)
718 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
719 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
720 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
722 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
723 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
724 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
725 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
726 (const :tag "C collector: Collect properties into tables" org-collector)
727 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
728 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
729 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
730 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
731 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
732 (const :tag "C eval: Include command output as text" org-eval)
733 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
734 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
735 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
736 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
737 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
738 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
739 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
740 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
741 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
742 (const :tag "C man: Support for links to manpages in Org mode" org-man)
743 (const :tag "C mew: Links to Mew folders/messages" org-mew)
744 (const :tag "C mtags: Support for muse-like tags" org-mtags)
745 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
746 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
747 (const :tag "C registry: A registry for Org links" org-registry)
748 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
749 (const :tag "C secretary: Team management with org-mode" org-secretary)
750 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
751 (const :tag "C toc: Table of contents for Org buffer" org-toc)
752 (const :tag "C track: Keep up with Org mode development" org-track)
753 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
754 (const :tag "C vm: Links to VM folders/messages" org-vm)
755 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
756 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
757 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
759 (defvar org-export-registered-backends) ; From ox.el.
760 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
761 (declare-function org-export-backend-name "ox" (backend) t)
762 (defcustom org-export-backends '(ascii html icalendar latex odt)
763 "List of export back-ends that should be always available.
765 If a description starts with <C>, the file is not part of Emacs
766 and loading it will require that you have downloaded and properly
767 installed the Org mode distribution.
769 Unlike to `org-modules', libraries in this list will not be
770 loaded along with Org, but only once the export framework is
771 needed.
773 This variable needs to be set before org.el is loaded. If you
774 need to make a change while Emacs is running, use the customize
775 interface or run the following code, where VAL stands for the new
776 value of the variable, after updating it:
778 (progn
779 (setq org-export-registered-backends
780 (cl-remove-if-not
781 (lambda (backend)
782 (let ((name (org-export-backend-name backend)))
783 (or (memq name val)
784 (catch \\='parentp
785 (dolist (b val)
786 (and (org-export-derived-backend-p b name)
787 (throw \\='parentp t)))))))
788 org-export-registered-backends))
789 (let ((new-list (mapcar #\\='org-export-backend-name
790 org-export-registered-backends)))
791 (dolist (backend val)
792 (cond
793 ((not (load (format \"ox-%s\" backend) t t))
794 (message \"Problems while trying to load export back-end \\=`%s\\='\"
795 backend))
796 ((not (memq backend new-list)) (push backend new-list))))
797 (set-default \\='org-export-backends new-list)))
799 Adding a back-end to this list will also pull the back-end it
800 depends on, if any."
801 :group 'org
802 :group 'org-export
803 :version "26.1"
804 :package-version '(Org . "9.0")
805 :initialize 'custom-initialize-set
806 :set (lambda (var val)
807 (if (not (featurep 'ox)) (set-default var val)
808 ;; Any back-end not required anymore (not present in VAL and not
809 ;; a parent of any back-end in the new value) is removed from the
810 ;; list of registered back-ends.
811 (setq org-export-registered-backends
812 (cl-remove-if-not
813 (lambda (backend)
814 (let ((name (org-export-backend-name backend)))
815 (or (memq name val)
816 (catch 'parentp
817 (dolist (b val)
818 (and (org-export-derived-backend-p b name)
819 (throw 'parentp t)))))))
820 org-export-registered-backends))
821 ;; Now build NEW-LIST of both new back-ends and required
822 ;; parents.
823 (let ((new-list (mapcar #'org-export-backend-name
824 org-export-registered-backends)))
825 (dolist (backend val)
826 (cond
827 ((not (load (format "ox-%s" backend) t t))
828 (message "Problems while trying to load export back-end `%s'"
829 backend))
830 ((not (memq backend new-list)) (push backend new-list))))
831 ;; Set VAR to that list with fixed dependencies.
832 (set-default var new-list))))
833 :type '(set :greedy t
834 (const :tag " ascii Export buffer to ASCII format" ascii)
835 (const :tag " beamer Export buffer to Beamer presentation" beamer)
836 (const :tag " html Export buffer to HTML format" html)
837 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
838 (const :tag " latex Export buffer to LaTeX format" latex)
839 (const :tag " man Export buffer to MAN format" man)
840 (const :tag " md Export buffer to Markdown format" md)
841 (const :tag " odt Export buffer to ODT format" odt)
842 (const :tag " org Export buffer to Org format" org)
843 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
844 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
845 (const :tag "C deck Export buffer to deck.js presentations" deck)
846 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
847 (const :tag "C groff Export buffer to Groff format" groff)
848 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
849 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
850 (const :tag "C s5 Export buffer to s5 presentations" s5)
851 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
853 (eval-after-load 'ox
854 '(dolist (backend org-export-backends)
855 (condition-case nil (require (intern (format "ox-%s" backend)))
856 (error (message "Problems while trying to load export back-end `%s'"
857 backend)))))
859 (defcustom org-support-shift-select nil
860 "Non-nil means make shift-cursor commands select text when possible.
861 \\<org-mode-map>\
863 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
864 start selecting a region, or enlarge regions started in this way.
865 In Org mode, in special contexts, these same keys are used for
866 other purposes, important enough to compete with shift selection.
867 Org tries to balance these needs by supporting `shift-select-mode'
868 outside these special contexts, under control of this variable.
870 The default of this variable is nil, to avoid confusing behavior. Shifted
871 cursor keys will then execute Org commands in the following contexts:
872 - on a headline, changing TODO state (left/right) and priority (up/down)
873 - on a time stamp, changing the time
874 - in a plain list item, changing the bullet type
875 - in a property definition line, switching between allowed values
876 - in the BEGIN line of a clock table (changing the time block).
877 Outside these contexts, the commands will throw an error.
879 When this variable is t and the cursor is not in a special
880 context, Org mode will support shift-selection for making and
881 enlarging regions. To make this more effective, the bullet
882 cycling will no longer happen anywhere in an item line, but only
883 if the cursor is exactly on the bullet.
885 If you set this variable to the symbol `always', then the keys
886 will not be special in headlines, property lines, and item lines,
887 to make shift selection work there as well. If this is what you
888 want, you can use the following alternative commands:
889 `\\[org-todo]' and `\\[org-priority]' \
890 to change TODO state and priority,
891 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
892 can be used to switch TODO sets,
893 `\\[org-ctrl-c-minus]' to cycle item bullet types,
894 and properties can be edited by hand or in column view.
896 However, when the cursor is on a timestamp, shift-cursor commands
897 will still edit the time stamp - this is just too good to give up."
898 :group 'org
899 :type '(choice
900 (const :tag "Never" nil)
901 (const :tag "When outside special context" t)
902 (const :tag "Everywhere except timestamps" always)))
904 (defcustom org-loop-over-headlines-in-active-region nil
905 "Shall some commands act upon headlines in the active region?
907 When set to t, some commands will be performed in all headlines
908 within the active region.
910 When set to `start-level', some commands will be performed in all
911 headlines within the active region, provided that these headlines
912 are of the same level than the first one.
914 When set to a string, those commands will be performed on the
915 matching headlines within the active region. Such string must be
916 a tags/property/todo match as it is used in the agenda tags view.
918 The list of commands is: `org-schedule', `org-deadline',
919 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
920 `org-archive-to-archive-sibling'. The archiving commands skip
921 already archived entries."
922 :type '(choice (const :tag "Don't loop" nil)
923 (const :tag "All headlines in active region" t)
924 (const :tag "In active region, headlines at the same level than the first one" start-level)
925 (string :tag "Tags/Property/Todo matcher"))
926 :version "24.1"
927 :group 'org-todo
928 :group 'org-archive)
930 (defgroup org-startup nil
931 "Options concerning startup of Org mode."
932 :tag "Org Startup"
933 :group 'org)
935 (defcustom org-startup-folded t
936 "Non-nil means entering Org mode will switch to OVERVIEW.
938 This can also be configured on a per-file basis by adding one of
939 the following lines anywhere in the buffer:
941 #+STARTUP: fold (or `overview', this is equivalent)
942 #+STARTUP: nofold (or `showall', this is equivalent)
943 #+STARTUP: content
944 #+STARTUP: showeverything
946 Set `org-agenda-inhibit-startup' to a non-nil value if you want
947 to ignore this option when Org opens agenda files for the first
948 time."
949 :group 'org-startup
950 :type '(choice
951 (const :tag "nofold: show all" nil)
952 (const :tag "fold: overview" t)
953 (const :tag "content: all headlines" content)
954 (const :tag "show everything, even drawers" showeverything)))
956 (defcustom org-startup-truncated t
957 "Non-nil means entering Org mode will set `truncate-lines'.
958 This is useful since some lines containing links can be very long and
959 uninteresting. Also tables look terrible when wrapped.
961 The variable `org-startup-truncated' allows to configure
962 truncation for Org mode different to the other modes that use the
963 variable `truncate-lines' and as a shortcut instead of putting
964 the variable `truncate-lines' into the `org-mode-hook'. If one
965 wants to configure truncation for Org mode not statically but
966 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
967 the variable `truncate-lines' has to be used because in such a
968 case it is too late to set the variable `org-startup-truncated'."
969 :group 'org-startup
970 :type 'boolean)
972 (defcustom org-startup-indented nil
973 "Non-nil means turn on `org-indent-mode' on startup.
974 This can also be configured on a per-file basis by adding one of
975 the following lines anywhere in the buffer:
977 #+STARTUP: indent
978 #+STARTUP: noindent"
979 :group 'org-structure
980 :type '(choice
981 (const :tag "Not" nil)
982 (const :tag "Globally (slow on startup in large files)" t)))
984 (defcustom org-use-sub-superscripts t
985 "Non-nil means interpret \"_\" and \"^\" for display.
987 If you want to control how Org exports those characters, see
988 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
989 used to be an alias for `org-export-with-sub-superscripts' in
990 Org <8.0, it is not anymore.
992 When this option is turned on, you can use TeX-like syntax for
993 sub- and superscripts within the buffer. Several characters after
994 \"_\" or \"^\" will be considered as a single item - so grouping
995 with {} is normally not needed. For example, the following things
996 will be parsed as single sub- or superscripts:
998 10^24 or 10^tau several digits will be considered 1 item.
999 10^-12 or 10^-tau a leading sign with digits or a word
1000 x^2-y^3 will be read as x^2 - y^3, because items are
1001 terminated by almost any nonword/nondigit char.
1002 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1004 Still, ambiguity is possible. So when in doubt, use {} to enclose
1005 the sub/superscript. If you set this variable to the symbol `{}',
1006 the braces are *required* in order to trigger interpretations as
1007 sub/superscript. This can be helpful in documents that need \"_\"
1008 frequently in plain text."
1009 :group 'org-startup
1010 :version "24.4"
1011 :package-version '(Org . "8.0")
1012 :type '(choice
1013 (const :tag "Always interpret" t)
1014 (const :tag "Only with braces" {})
1015 (const :tag "Never interpret" nil)))
1017 (defcustom org-startup-with-beamer-mode nil
1018 "Non-nil means turn on `org-beamer-mode' on startup.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1022 #+STARTUP: beamer"
1023 :group 'org-startup
1024 :version "24.1"
1025 :type 'boolean)
1027 (defcustom org-startup-align-all-tables nil
1028 "Non-nil means align all tables when visiting a file.
1029 This is useful when the column width in tables is forced with <N> cookies
1030 in table fields. Such tables will look correct only after the first re-align.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: align
1034 #+STARTUP: noalign"
1035 :group 'org-startup
1036 :type 'boolean)
1038 (defcustom org-startup-with-inline-images nil
1039 "Non-nil means show inline images when loading a new Org file.
1040 This can also be configured on a per-file basis by adding one of
1041 the following lines anywhere in the buffer:
1042 #+STARTUP: inlineimages
1043 #+STARTUP: noinlineimages"
1044 :group 'org-startup
1045 :version "24.1"
1046 :type 'boolean)
1048 (defcustom org-startup-with-latex-preview nil
1049 "Non-nil means preview LaTeX fragments when loading a new Org file.
1051 This can also be configured on a per-file basis by adding one of
1052 the following lines anywhere in the buffer:
1053 #+STARTUP: latexpreview
1054 #+STARTUP: nolatexpreview"
1055 :group 'org-startup
1056 :version "24.4"
1057 :package-version '(Org . "8.0")
1058 :type 'boolean)
1060 (defcustom org-insert-mode-line-in-empty-file nil
1061 "Non-nil means insert the first line setting Org mode in empty files.
1062 When the function `org-mode' is called interactively in an empty file, this
1063 normally means that the file name does not automatically trigger Org mode.
1064 To ensure that the file will always be in Org mode in the future, a
1065 line enforcing Org mode will be inserted into the buffer, if this option
1066 has been set."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (defcustom org-replace-disputed-keys nil
1071 "Non-nil means use alternative key bindings for some keys.
1072 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1073 These keys are also used by other packages like shift-selection-mode'
1074 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1075 If you want to use Org mode together with one of these other modes,
1076 or more generally if you would like to move some Org mode commands to
1077 other keys, set this variable and configure the keys with the variable
1078 `org-disputed-keys'.
1080 This option is only relevant at load-time of Org mode, and must be set
1081 *before* org.el is loaded. Changing it requires a restart of Emacs to
1082 become effective."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defcustom org-use-extra-keys nil
1087 "Non-nil means use extra key sequence definitions for certain commands.
1088 This happens automatically if `window-system' is nil. This
1089 variable lets you do the same manually. You must set it before
1090 loading Org."
1091 :group 'org-startup
1092 :type 'boolean)
1094 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1096 (defcustom org-disputed-keys
1097 '(([(shift up)] . [(meta p)])
1098 ([(shift down)] . [(meta n)])
1099 ([(shift left)] . [(meta -)])
1100 ([(shift right)] . [(meta +)])
1101 ([(control shift right)] . [(meta shift +)])
1102 ([(control shift left)] . [(meta shift -)]))
1103 "Keys for which Org mode and other modes compete.
1104 This is an alist, cars are the default keys, second element specifies
1105 the alternative to use when `org-replace-disputed-keys' is t.
1107 Keys can be specified in any syntax supported by `define-key'.
1108 The value of this option takes effect only at Org mode startup,
1109 therefore you'll have to restart Emacs to apply it after changing."
1110 :group 'org-startup
1111 :type 'alist)
1113 (defun org-key (key)
1114 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1115 Or return the original if not disputed."
1116 (when org-replace-disputed-keys
1117 (let* ((nkey (key-description key))
1118 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1119 org-disputed-keys)))
1120 (setq key (if x (cdr x) key))))
1121 key)
1123 (defun org-defkey (keymap key def)
1124 "Define a key, possibly translated, as returned by `org-key'."
1125 (define-key keymap (org-key key) def))
1127 (defcustom org-ellipsis nil
1128 "The ellipsis to use in the Org mode outline.
1130 When nil, just use the standard three dots.
1131 When a string, use that string instead.
1133 The change affects only Org mode (which will then use its own display table).
1134 Changing this requires executing `\\[org-mode]' in a buffer to become
1135 effective."
1136 :group 'org-startup
1137 :type '(choice (const :tag "Default" nil)
1138 (string :tag "String" :value "...#"))
1139 :safe #'string-or-null-p)
1141 (defvar org-display-table nil
1142 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1144 (defgroup org-keywords nil
1145 "Keywords in Org mode."
1146 :tag "Org Keywords"
1147 :group 'org)
1149 (defcustom org-closed-keep-when-no-todo nil
1150 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1151 :group 'org-todo
1152 :group 'org-keywords
1153 :version "24.4"
1154 :package-version '(Org . "8.0")
1155 :type 'boolean)
1157 (defgroup org-structure nil
1158 "Options concerning the general structure of Org files."
1159 :tag "Org Structure"
1160 :group 'org)
1162 (defgroup org-reveal-location nil
1163 "Options about how to make context of a location visible."
1164 :tag "Org Reveal Location"
1165 :group 'org-structure)
1167 (defcustom org-show-context-detail '((agenda . local)
1168 (bookmark-jump . lineage)
1169 (isearch . lineage)
1170 (default . ancestors))
1171 "Alist between context and visibility span when revealing a location.
1173 \\<org-mode-map>Some actions may move point into invisible
1174 locations. As a consequence, Org always expose a neighborhood
1175 around point. How much is shown depends on the initial action,
1176 or context. Valid contexts are
1178 agenda when exposing an entry from the agenda
1179 org-goto when using the command `org-goto' (`\\[org-goto]')
1180 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1181 tags-tree when constructing a sparse tree based on tags matches
1182 link-search when exposing search matches associated with a link
1183 mark-goto when exposing the jump goal of a mark
1184 bookmark-jump when exposing a bookmark location
1185 isearch when exiting from an incremental search
1186 default default for all contexts not set explicitly
1188 Allowed visibility spans are
1190 minimal show current headline; if point is not on headline,
1191 also show entry
1193 local show current headline, entry and next headline
1195 ancestors show current headline and its direct ancestors; if
1196 point is not on headline, also show entry
1198 lineage show current headline, its direct ancestors and all
1199 their children; if point is not on headline, also show
1200 entry and first child
1202 tree show current headline, its direct ancestors and all
1203 their children; if point is not on headline, also show
1204 entry and all children
1206 canonical show current headline, its direct ancestors along with
1207 their entries and children; if point is not located on
1208 the headline, also show current entry and all children
1210 As special cases, a nil or t value means show all contexts in
1211 `minimal' or `canonical' view, respectively.
1213 Some views can make displayed information very compact, but also
1214 make it harder to edit the location of the match. In such
1215 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1216 more context."
1217 :group 'org-reveal-location
1218 :version "26.1"
1219 :package-version '(Org . "9.0")
1220 :type '(choice
1221 (const :tag "Canonical" t)
1222 (const :tag "Minimal" nil)
1223 (repeat :greedy t :tag "Individual contexts"
1224 (cons
1225 (choice :tag "Context"
1226 (const agenda)
1227 (const org-goto)
1228 (const occur-tree)
1229 (const tags-tree)
1230 (const link-search)
1231 (const mark-goto)
1232 (const bookmark-jump)
1233 (const isearch)
1234 (const default))
1235 (choice :tag "Detail level"
1236 (const minimal)
1237 (const local)
1238 (const ancestors)
1239 (const lineage)
1240 (const tree)
1241 (const canonical))))))
1243 (defcustom org-indirect-buffer-display 'other-window
1244 "How should indirect tree buffers be displayed?
1246 This applies to indirect buffers created with the commands
1247 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1249 Valid values are:
1250 current-window Display in the current window
1251 other-window Just display in another window.
1252 dedicated-frame Create one new frame, and re-use it each time.
1253 new-frame Make a new frame each time. Note that in this case
1254 previously-made indirect buffers are kept, and you need to
1255 kill these buffers yourself."
1256 :group 'org-structure
1257 :group 'org-agenda-windows
1258 :type '(choice
1259 (const :tag "In current window" current-window)
1260 (const :tag "In current frame, other window" other-window)
1261 (const :tag "Each time a new frame" new-frame)
1262 (const :tag "One dedicated frame" dedicated-frame)))
1264 (defcustom org-use-speed-commands nil
1265 "Non-nil means activate single letter commands at beginning of a headline.
1266 This may also be a function to test for appropriate locations where speed
1267 commands should be active.
1269 For example, to activate speed commands when the point is on any
1270 star at the beginning of the headline, you can do this:
1272 (setq org-use-speed-commands
1273 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1274 :group 'org-structure
1275 :type '(choice
1276 (const :tag "Never" nil)
1277 (const :tag "At beginning of headline stars" t)
1278 (function)))
1280 (defcustom org-speed-commands-user nil
1281 "Alist of additional speed commands.
1282 This list will be checked before `org-speed-commands-default'
1283 when the variable `org-use-speed-commands' is non-nil
1284 and when the cursor is at the beginning of a headline.
1285 The car if each entry is a string with a single letter, which must
1286 be assigned to `self-insert-command' in the global map.
1287 The cdr is either a command to be called interactively, a function
1288 to be called, or a form to be evaluated.
1289 An entry that is just a list with a single string will be interpreted
1290 as a descriptive headline that will be added when listing the speed
1291 commands in the Help buffer using the `?' speed command."
1292 :group 'org-structure
1293 :type '(repeat :value ("k" . ignore)
1294 (choice :value ("k" . ignore)
1295 (list :tag "Descriptive Headline" (string :tag "Headline"))
1296 (cons :tag "Letter and Command"
1297 (string :tag "Command letter")
1298 (choice
1299 (function)
1300 (sexp))))))
1302 (defcustom org-bookmark-names-plist
1303 '(:last-capture "org-capture-last-stored"
1304 :last-refile "org-refile-last-stored"
1305 :last-capture-marker "org-capture-last-stored-marker")
1306 "Names for bookmarks automatically set by some Org commands.
1307 This can provide strings as names for a number of bookmarks Org sets
1308 automatically. The following keys are currently implemented:
1309 :last-capture
1310 :last-capture-marker
1311 :last-refile
1312 When a key does not show up in the property list, the corresponding bookmark
1313 is not set."
1314 :group 'org-structure
1315 :type 'plist)
1317 (defgroup org-cycle nil
1318 "Options concerning visibility cycling in Org mode."
1319 :tag "Org Cycle"
1320 :group 'org-structure)
1322 (defcustom org-cycle-skip-children-state-if-no-children t
1323 "Non-nil means skip CHILDREN state in entries that don't have any."
1324 :group 'org-cycle
1325 :type 'boolean)
1327 (defcustom org-cycle-max-level nil
1328 "Maximum level which should still be subject to visibility cycling.
1329 Levels higher than this will, for cycling, be treated as text, not a headline.
1330 When `org-odd-levels-only' is set, a value of N in this variable actually
1331 means 2N-1 stars as the limiting headline.
1332 When nil, cycle all levels.
1333 Note that the limiting level of cycling is also influenced by
1334 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1335 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1336 than its value."
1337 :group 'org-cycle
1338 :type '(choice
1339 (const :tag "No limit" nil)
1340 (integer :tag "Maximum level")))
1342 (defcustom org-hide-block-startup nil
1343 "Non-nil means entering Org mode will fold all blocks.
1344 This can also be set in on a per-file basis with
1346 #+STARTUP: hideblocks
1347 #+STARTUP: showblocks"
1348 :group 'org-startup
1349 :group 'org-cycle
1350 :type 'boolean)
1352 (defcustom org-cycle-global-at-bob nil
1353 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1355 This makes it possible to do global cycling without having to use `S-TAB'
1356 or `\\[universal-argument] TAB'. For this special case to work, the first \
1357 line of the buffer
1358 must not be a headline -- it may be empty or some other text.
1360 When used in this way, `org-cycle-hook' is disabled temporarily to make
1361 sure the cursor stays at the beginning of the buffer.
1363 When this option is nil, don't do anything special at the beginning of
1364 the buffer."
1365 :group 'org-cycle
1366 :type 'boolean)
1368 (defcustom org-cycle-level-after-item/entry-creation t
1369 "Non-nil means cycle entry level or item indentation in new empty entries.
1371 When the cursor is at the end of an empty headline, i.e., with only stars
1372 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1373 and then all possible ancestor states, before returning to the original state.
1374 This makes data entry extremely fast: M-RET to create a new headline,
1375 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1377 When the cursor is at the end of an empty plain list item, one TAB will
1378 make it a subitem, two or more tabs will back up to make this an item
1379 higher up in the item hierarchy."
1380 :group 'org-cycle
1381 :type 'boolean)
1383 (defcustom org-cycle-emulate-tab t
1384 "Where should `org-cycle' emulate TAB.
1385 nil Never
1386 white Only in completely white lines
1387 whitestart Only at the beginning of lines, before the first non-white char
1388 t Everywhere except in headlines
1389 exc-hl-bol Everywhere except at the start of a headline
1390 If TAB is used in a place where it does not emulate TAB, the current subtree
1391 visibility is cycled."
1392 :group 'org-cycle
1393 :type '(choice (const :tag "Never" nil)
1394 (const :tag "Only in completely white lines" white)
1395 (const :tag "Before first char in a line" whitestart)
1396 (const :tag "Everywhere except in headlines" t)
1397 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1399 (defcustom org-cycle-separator-lines 2
1400 "Number of empty lines needed to keep an empty line between collapsed trees.
1401 If you leave an empty line between the end of a subtree and the following
1402 headline, this empty line is hidden when the subtree is folded.
1403 Org mode will leave (exactly) one empty line visible if the number of
1404 empty lines is equal or larger to the number given in this variable.
1405 So the default 2 means at least 2 empty lines after the end of a subtree
1406 are needed to produce free space between a collapsed subtree and the
1407 following headline.
1409 If the number is negative, and the number of empty lines is at least -N,
1410 all empty lines are shown.
1412 Special case: when 0, never leave empty lines in collapsed view."
1413 :group 'org-cycle
1414 :type 'integer)
1415 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1417 (defcustom org-pre-cycle-hook nil
1418 "Hook that is run before visibility cycling is happening.
1419 The function(s) in this hook must accept a single argument which indicates
1420 the new state that will be set right after running this hook. The
1421 argument is a symbol. Before a global state change, it can have the values
1422 `overview', `content', or `all'. Before a local state change, it can have
1423 the values `folded', `children', or `subtree'."
1424 :group 'org-cycle
1425 :type 'hook)
1427 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1428 org-cycle-hide-drawers
1429 org-cycle-show-empty-lines
1430 org-optimize-window-after-visibility-change)
1431 "Hook that is run after `org-cycle' has changed the buffer visibility.
1432 The function(s) in this hook must accept a single argument which indicates
1433 the new state that was set by the most recent `org-cycle' command. The
1434 argument is a symbol. After a global state change, it can have the values
1435 `overview', `contents', or `all'. After a local state change, it can have
1436 the values `folded', `children', or `subtree'."
1437 :group 'org-cycle
1438 :type 'hook
1439 :version "26.1"
1440 :package-version '(Org . "8.3"))
1442 (defgroup org-edit-structure nil
1443 "Options concerning structure editing in Org mode."
1444 :tag "Org Edit Structure"
1445 :group 'org-structure)
1447 (defcustom org-odd-levels-only nil
1448 "Non-nil means skip even levels and only use odd levels for the outline.
1449 This has the effect that two stars are being added/taken away in
1450 promotion/demotion commands. It also influences how levels are
1451 handled by the exporters.
1452 Changing it requires restart of `font-lock-mode' to become effective
1453 for fontification also in regions already fontified.
1454 You may also set this on a per-file basis by adding one of the following
1455 lines to the buffer:
1457 #+STARTUP: odd
1458 #+STARTUP: oddeven"
1459 :group 'org-edit-structure
1460 :group 'org-appearance
1461 :type 'boolean)
1463 (defcustom org-adapt-indentation t
1464 "Non-nil means adapt indentation to outline node level.
1466 When this variable is set, Org assumes that you write outlines by
1467 indenting text in each node to align with the headline (after the
1468 stars). The following issues are influenced by this variable:
1470 - The indentation is increased by one space in a demotion
1471 command, and decreased by one in a promotion command. However,
1472 in the latter case, if shifting some line in the entry body
1473 would alter document structure (e.g., insert a new headline),
1474 indentation is not changed at all.
1476 - Property drawers and planning information is inserted indented
1477 when this variable is set. When nil, they will not be indented.
1479 - TAB indents a line relative to current level. The lines below
1480 a headline will be indented when this variable is set.
1482 Note that this is all about true indentation, by adding and
1483 removing space characters. See also `org-indent.el' which does
1484 level-dependent indentation in a virtual way, i.e. at display
1485 time in Emacs."
1486 :group 'org-edit-structure
1487 :type 'boolean)
1489 (defcustom org-special-ctrl-a/e nil
1490 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1492 When t, `C-a' will bring back the cursor to the beginning of the
1493 headline text, i.e. after the stars and after a possible TODO
1494 keyword. In an item, this will be the position after bullet and
1495 check-box, if any. When the cursor is already at that position,
1496 another `C-a' will bring it to the beginning of the line.
1498 `C-e' will jump to the end of the headline, ignoring the presence
1499 of tags in the headline. A second `C-e' will then jump to the
1500 true end of the line, after any tags. This also means that, when
1501 this variable is non-nil, `C-e' also will never jump beyond the
1502 end of the heading of a folded section, i.e. not after the
1503 ellipses.
1505 When set to the symbol `reversed', the first `C-a' or `C-e' works
1506 normally, going to the true line boundary first. Only a directly
1507 following, identical keypress will bring the cursor to the
1508 special positions.
1510 This may also be a cons cell where the behavior for `C-a' and
1511 `C-e' is set separately."
1512 :group 'org-edit-structure
1513 :type '(choice
1514 (const :tag "off" nil)
1515 (const :tag "on: after stars/bullet and before tags first" t)
1516 (const :tag "reversed: true line boundary first" reversed)
1517 (cons :tag "Set C-a and C-e separately"
1518 (choice :tag "Special C-a"
1519 (const :tag "off" nil)
1520 (const :tag "on: after stars/bullet first" t)
1521 (const :tag "reversed: before stars/bullet first" reversed))
1522 (choice :tag "Special C-e"
1523 (const :tag "off" nil)
1524 (const :tag "on: before tags first" t)
1525 (const :tag "reversed: after tags first" reversed)))))
1526 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1528 (defcustom org-special-ctrl-k nil
1529 "Non-nil means `C-k' will behave specially in headlines.
1530 When nil, `C-k' will call the default `kill-line' command.
1531 When t, the following will happen while the cursor is in the headline:
1533 - When the cursor is at the beginning of a headline, kill the entire
1534 line and possible the folded subtree below the line.
1535 - When in the middle of the headline text, kill the headline up to the tags.
1536 - When after the headline text, kill the tags."
1537 :group 'org-edit-structure
1538 :type 'boolean)
1540 (defcustom org-ctrl-k-protect-subtree nil
1541 "Non-nil means, do not delete a hidden subtree with C-k.
1542 When set to the symbol `error', simply throw an error when C-k is
1543 used to kill (part-of) a headline that has hidden text behind it.
1544 Any other non-nil value will result in a query to the user, if it is
1545 OK to kill that hidden subtree. When nil, kill without remorse."
1546 :group 'org-edit-structure
1547 :version "24.1"
1548 :type '(choice
1549 (const :tag "Do not protect hidden subtrees" nil)
1550 (const :tag "Protect hidden subtrees with a security query" t)
1551 (const :tag "Never kill a hidden subtree with C-k" error)))
1553 (defcustom org-special-ctrl-o t
1554 "Non-nil means, make `C-o' insert a row in tables."
1555 :group 'org-edit-structure
1556 :type 'boolean)
1558 (defcustom org-catch-invisible-edits nil
1559 "Check if in invisible region before inserting or deleting a character.
1560 Valid values are:
1562 nil Do not check, so just do invisible edits.
1563 error Throw an error and do nothing.
1564 show Make point visible, and do the requested edit.
1565 show-and-error Make point visible, then throw an error and abort the edit.
1566 smart Make point visible, and do insertion/deletion if it is
1567 adjacent to visible text and the change feels predictable.
1568 Never delete a previously invisible character or add in the
1569 middle or right after an invisible region. Basically, this
1570 allows insertion and backward-delete right before ellipses.
1571 FIXME: maybe in this case we should not even show?"
1572 :group 'org-edit-structure
1573 :version "24.1"
1574 :type '(choice
1575 (const :tag "Do not check" nil)
1576 (const :tag "Throw error when trying to edit" error)
1577 (const :tag "Unhide, but do not do the edit" show-and-error)
1578 (const :tag "Show invisible part and do the edit" show)
1579 (const :tag "Be smart and do the right thing" smart)))
1581 (defcustom org-yank-folded-subtrees t
1582 "Non-nil means when yanking subtrees, fold them.
1583 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1584 it starts with a heading and all other headings in it are either children
1585 or siblings, then fold all the subtrees. However, do this only if no
1586 text after the yank would be swallowed into a folded tree by this action."
1587 :group 'org-edit-structure
1588 :type 'boolean)
1590 (defcustom org-yank-adjusted-subtrees nil
1591 "Non-nil means when yanking subtrees, adjust the level.
1592 With this setting, `org-paste-subtree' is used to insert the subtree, see
1593 this function for details."
1594 :group 'org-edit-structure
1595 :type 'boolean)
1597 (defcustom org-M-RET-may-split-line '((default . t))
1598 "Non-nil means M-RET will split the line at the cursor position.
1599 When nil, it will go to the end of the line before making a
1600 new line.
1601 You may also set this option in a different way for different
1602 contexts. Valid contexts are:
1604 headline when creating a new headline
1605 item when creating a new item
1606 table in a table field
1607 default the value to be used for all contexts not explicitly
1608 customized"
1609 :group 'org-structure
1610 :group 'org-table
1611 :type '(choice
1612 (const :tag "Always" t)
1613 (const :tag "Never" nil)
1614 (repeat :greedy t :tag "Individual contexts"
1615 (cons
1616 (choice :tag "Context"
1617 (const headline)
1618 (const item)
1619 (const table)
1620 (const default))
1621 (boolean)))))
1624 (defcustom org-insert-heading-respect-content nil
1625 "Non-nil means insert new headings after the current subtree.
1626 \\<org-mode-map>
1627 When nil, the new heading is created directly after the current line.
1628 The commands `\\[org-insert-heading-respect-content]' and \
1629 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1630 for the duration of the command."
1631 :group 'org-structure
1632 :type 'boolean)
1634 (defcustom org-blank-before-new-entry '((heading . auto)
1635 (plain-list-item . auto))
1636 "Should `org-insert-heading' leave a blank line before new heading/item?
1637 The value is an alist, with `heading' and `plain-list-item' as CAR,
1638 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1639 which case Org will look at the surrounding headings/items and try to
1640 make an intelligent decision whether to insert a blank line or not."
1641 :group 'org-edit-structure
1642 :type '(list
1643 (cons (const heading)
1644 (choice (const :tag "Never" nil)
1645 (const :tag "Always" t)
1646 (const :tag "Auto" auto)))
1647 (cons (const plain-list-item)
1648 (choice (const :tag "Never" nil)
1649 (const :tag "Always" t)
1650 (const :tag "Auto" auto)))))
1652 (defcustom org-insert-heading-hook nil
1653 "Hook being run after inserting a new heading."
1654 :group 'org-edit-structure
1655 :type 'hook)
1657 (defcustom org-enable-fixed-width-editor t
1658 "Non-nil means lines starting with \":\" are treated as fixed-width.
1659 This currently only means they are never auto-wrapped.
1660 When nil, such lines will be treated like ordinary lines."
1661 :group 'org-edit-structure
1662 :type 'boolean)
1664 (defcustom org-goto-auto-isearch t
1665 "Non-nil means typing characters in `org-goto' starts incremental search.
1666 When nil, you can use these keybindings to navigate the buffer:
1668 q Quit the org-goto interface
1669 n Go to the next visible heading
1670 p Go to the previous visible heading
1671 f Go one heading forward on same level
1672 b Go one heading backward on same level
1673 u Go one heading up"
1674 :group 'org-edit-structure
1675 :type 'boolean)
1677 (defgroup org-sparse-trees nil
1678 "Options concerning sparse trees in Org mode."
1679 :tag "Org Sparse Trees"
1680 :group 'org-structure)
1682 (defcustom org-highlight-sparse-tree-matches t
1683 "Non-nil means highlight all matches that define a sparse tree.
1684 The highlights will automatically disappear the next time the buffer is
1685 changed by an edit command."
1686 :group 'org-sparse-trees
1687 :type 'boolean)
1689 (defcustom org-remove-highlights-with-change t
1690 "Non-nil means any change to the buffer will remove temporary highlights.
1691 \\<org-mode-map>\
1692 Such highlights are created by `org-occur' and `org-clock-display'.
1693 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1694 to get rid of the highlights.
1695 The highlights created by `org-toggle-latex-fragment' always need
1696 `\\[org-toggle-latex-fragment]' to be removed."
1697 :group 'org-sparse-trees
1698 :group 'org-time
1699 :type 'boolean)
1701 (defcustom org-occur-case-fold-search t
1702 "Non-nil means `org-occur' should be case-insensitive.
1703 If set to `smart' the search will be case-insensitive only if it
1704 doesn't specify any upper case character."
1705 :group 'org-sparse-trees
1706 :version "26.1"
1707 :type '(choice
1708 (const :tag "Case-sensitive" nil)
1709 (const :tag "Case-insensitive" t)
1710 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1712 (defcustom org-occur-hook '(org-first-headline-recenter)
1713 "Hook that is run after `org-occur' has constructed a sparse tree.
1714 This can be used to recenter the window to show as much of the structure
1715 as possible."
1716 :group 'org-sparse-trees
1717 :type 'hook)
1719 (defgroup org-imenu-and-speedbar nil
1720 "Options concerning imenu and speedbar in Org mode."
1721 :tag "Org Imenu and Speedbar"
1722 :group 'org-structure)
1724 (defcustom org-imenu-depth 2
1725 "The maximum level for Imenu access to Org headlines.
1726 This also applied for speedbar access."
1727 :group 'org-imenu-and-speedbar
1728 :type 'integer)
1730 (defgroup org-table nil
1731 "Options concerning tables in Org mode."
1732 :tag "Org Table"
1733 :group 'org)
1735 (defcustom org-enable-table-editor 'optimized
1736 "Non-nil means lines starting with \"|\" are handled by the table editor.
1737 When nil, such lines will be treated like ordinary lines.
1739 When equal to the symbol `optimized', the table editor will be optimized to
1740 do the following:
1741 - Automatic overwrite mode in front of whitespace in table fields.
1742 This makes the structure of the table stay in tact as long as the edited
1743 field does not exceed the column width.
1744 - Minimize the number of realigns. Normally, the table is aligned each time
1745 TAB or RET are pressed to move to another field. With optimization this
1746 happens only if changes to a field might have changed the column width.
1747 Optimization requires replacing the functions `self-insert-command',
1748 `delete-char', and `backward-delete-char' in Org buffers, with a
1749 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1750 good at guessing when a re-align will be necessary, but you can always
1751 force one with `\\[org-ctrl-c-ctrl-c]'.
1753 If you would like to use the optimized version in Org mode, but the
1754 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1756 This variable can be used to turn on and off the table editor during a session,
1757 but in order to toggle optimization, a restart is required.
1759 See also the variable `org-table-auto-blank-field'."
1760 :group 'org-table
1761 :type '(choice
1762 (const :tag "off" nil)
1763 (const :tag "on" t)
1764 (const :tag "on, optimized" optimized)))
1766 (defcustom org-self-insert-cluster-for-undo nil
1767 "Non-nil means cluster self-insert commands for undo when possible.
1768 If this is set, then, like in the Emacs command loop, 20 consecutive
1769 characters will be undone together.
1770 This is configurable, because there is some impact on typing performance."
1771 :group 'org-table
1772 :type 'boolean)
1774 (defcustom org-table-tab-recognizes-table.el t
1775 "Non-nil means TAB will automatically notice a table.el table.
1776 When it sees such a table, it moves point into it and - if necessary -
1777 calls `table-recognize-table'."
1778 :group 'org-table-editing
1779 :type 'boolean)
1781 (defgroup org-link nil
1782 "Options concerning links in Org mode."
1783 :tag "Org Link"
1784 :group 'org)
1786 (defvar-local org-link-abbrev-alist-local nil
1787 "Buffer-local version of `org-link-abbrev-alist', which see.
1788 The value of this is taken from the #+LINK lines.")
1790 (defcustom org-link-parameters
1791 '(("doi" :follow org--open-doi-link)
1792 ("elisp" :follow org--open-elisp-link)
1793 ("file" :complete org-file-complete-link)
1794 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1795 ("help" :follow org--open-help-link)
1796 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1797 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1798 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1799 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1800 ("shell" :follow org--open-shell-link))
1801 "An alist of properties that defines all the links in Org mode.
1802 The key in each association is a string of the link type.
1803 Subsequent optional elements make up a p-list of link properties.
1805 :follow - A function that takes the link path as an argument.
1807 :export - A function that takes the link path, description and
1808 export-backend as arguments.
1810 :store - A function responsible for storing the link. See the
1811 function `org-store-link-functions'.
1813 :complete - A function that inserts a link with completion. The
1814 function takes one optional prefix arg.
1816 :face - A face for the link, or a function that returns a face.
1817 The function takes one argument which is the link path. The
1818 default face is `org-link'.
1820 :mouse-face - The mouse-face. The default is `highlight'.
1822 :display - `full' will not fold the link in descriptive
1823 display. Default is `org-link'.
1825 :help-echo - A string or function that takes (window object position)
1826 as arguments and returns a string.
1828 :keymap - A keymap that is active on the link. The default is
1829 `org-mouse-map'.
1831 :htmlize-link - A function for the htmlize-link. Defaults
1832 to (list :uri \"type:path\")
1834 :activate-func - A function to run at the end of font-lock
1835 activation. The function must accept (link-start link-end path bracketp)
1836 as arguments."
1837 :group 'org-link
1838 :type '(alist :tag "Link display parameters"
1839 :value-type plist)
1840 :version "26.1"
1841 :package-version '(Org . "9.1"))
1843 (defun org-link-get-parameter (type key)
1844 "Get TYPE link property for KEY.
1845 TYPE is a string and KEY is a plist keyword."
1846 (plist-get
1847 (cdr (assoc type org-link-parameters))
1848 key))
1850 (defun org-link-set-parameters (type &rest parameters)
1851 "Set link TYPE properties to PARAMETERS.
1852 PARAMETERS should be :key val pairs."
1853 (let ((data (assoc type org-link-parameters)))
1854 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1855 (push (cons type parameters) org-link-parameters)
1856 (org-make-link-regexps)
1857 (org-element-update-syntax))))
1859 (defun org-link-types ()
1860 "Return a list of known link types."
1861 (mapcar #'car org-link-parameters))
1863 (defcustom org-link-abbrev-alist nil
1864 "Alist of link abbreviations.
1865 The car of each element is a string, to be replaced at the start of a link.
1866 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1867 links in Org buffers can have an optional tag after a double colon, e.g.,
1869 [[linkkey:tag][description]]
1871 The `linkkey' must be a single word, starting with a letter, followed
1872 by letters, numbers, `-' or `_'.
1874 If REPLACE is a string, the tag will simply be appended to create the link.
1875 If the string contains \"%s\", the tag will be inserted there. If the string
1876 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1877 at that point (see the function `url-hexify-string'). If the string contains
1878 the specifier \"%(my-function)\", then the custom function `my-function' will
1879 be invoked: this function takes the tag as its only argument and must return
1880 a string.
1882 REPLACE may also be a function that will be called with the tag as the
1883 only argument to create the link, which should be returned as a string.
1885 See the manual for examples."
1886 :group 'org-link
1887 :type '(repeat
1888 (cons
1889 (string :tag "Protocol")
1890 (choice
1891 (string :tag "Format")
1892 (function)))))
1894 (defcustom org-descriptive-links t
1895 "Non-nil means Org will display descriptive links.
1896 E.g. [[http://orgmode.org][Org website]] will be displayed as
1897 \"Org Website\", hiding the link itself and just displaying its
1898 description. When set to nil, Org will display the full links
1899 literally.
1901 You can interactively set the value of this variable by calling
1902 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1903 :group 'org-link
1904 :type 'boolean)
1906 (defcustom org-link-file-path-type 'adaptive
1907 "How the path name in file links should be stored.
1908 Valid values are:
1910 relative Relative to the current directory, i.e. the directory of the file
1911 into which the link is being inserted.
1912 absolute Absolute path, if possible with ~ for home directory.
1913 noabbrev Absolute path, no abbreviation of home directory.
1914 adaptive Use relative path for files in the current directory and sub-
1915 directories of it. For other files, use an absolute path."
1916 :group 'org-link
1917 :type '(choice
1918 (const relative)
1919 (const absolute)
1920 (const noabbrev)
1921 (const adaptive)))
1923 (defvaralias 'org-activate-links 'org-highlight-links)
1924 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1925 "Types of links that should be highlighted in Org files.
1927 This is a list of symbols, each one of them leading to the
1928 highlighting of a certain link type.
1930 You can still open links that are not highlighted.
1932 In principle, it does not hurt to turn on highlighting for all
1933 link types. There may be a small gain when turning off unused
1934 link types. The types are:
1936 bracket The recommended [[link][description]] or [[link]] links with hiding.
1937 angle Links in angular brackets that may contain whitespace like
1938 <bbdb:Carsten Dominik>.
1939 plain Plain links in normal text, no whitespace, like http://google.com.
1940 radio Text that is matched by a radio target, see manual for details.
1941 tag Tag settings in a headline (link to tag search).
1942 date Time stamps (link to calendar).
1943 footnote Footnote labels.
1945 If you set this variable during an Emacs session, use `org-mode-restart'
1946 in the Org buffer so that the change takes effect."
1947 :group 'org-link
1948 :group 'org-appearance
1949 :type '(set :greedy t
1950 (const :tag "Double bracket links" bracket)
1951 (const :tag "Angular bracket links" angle)
1952 (const :tag "Plain text links" plain)
1953 (const :tag "Radio target matches" radio)
1954 (const :tag "Tags" tag)
1955 (const :tag "Timestamps" date)
1956 (const :tag "Footnotes" footnote)))
1958 (defcustom org-make-link-description-function nil
1959 "Function to use for generating link descriptions from links.
1960 When nil, the link location will be used. This function must take
1961 two parameters: the first one is the link, the second one is the
1962 description generated by `org-insert-link'. The function should
1963 return the description to use."
1964 :group 'org-link
1965 :type '(choice (const nil) (function)))
1967 (defgroup org-link-store nil
1968 "Options concerning storing links in Org mode."
1969 :tag "Org Store Link"
1970 :group 'org-link)
1972 (defcustom org-url-hexify-p t
1973 "When non-nil, hexify URL when creating a link."
1974 :type 'boolean
1975 :version "24.3"
1976 :group 'org-link-store)
1978 (defcustom org-email-link-description-format "Email %c: %.30s"
1979 "Format of the description part of a link to an email or usenet message.
1980 The following %-escapes will be replaced by corresponding information:
1982 %F full \"From\" field
1983 %f name, taken from \"From\" field, address if no name
1984 %T full \"To\" field
1985 %t first name in \"To\" field, address if no name
1986 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1987 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1988 %s subject
1989 %d date
1990 %m message-id.
1992 You may use normal field width specification between the % and the letter.
1993 This is for example useful to limit the length of the subject.
1995 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1996 :group 'org-link-store
1997 :type 'string)
1999 (defcustom org-from-is-user-regexp
2000 (let (r1 r2)
2001 (when (and user-mail-address (not (string= user-mail-address "")))
2002 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
2003 (when (and user-full-name (not (string= user-full-name "")))
2004 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
2005 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2006 "Regexp matched against the \"From:\" header of an email or usenet message.
2007 It should match if the message is from the user him/herself."
2008 :group 'org-link-store
2009 :type 'regexp)
2011 (defcustom org-context-in-file-links t
2012 "Non-nil means file links from `org-store-link' contain context.
2013 \\<org-mode-map>
2014 A search string will be added to the file name with :: as separator
2015 and used to find the context when the link is activated by the command
2016 `org-open-at-point'. When this option is t, the entire active region
2017 will be placed in the search string of the file link. If set to a
2018 positive integer, only the first n lines of context will be stored.
2020 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2021 \\[org-store-link]')
2022 negates this setting for the duration of the command."
2023 :group 'org-link-store
2024 :type '(choice boolean integer))
2026 (defcustom org-keep-stored-link-after-insertion nil
2027 "Non-nil means keep link in list for entire session.
2028 \\<org-mode-map>
2029 The command `org-store-link' adds a link pointing to the current
2030 location to an internal list. These links accumulate during a session.
2031 The command `org-insert-link' can be used to insert links into any
2032 Org file (offering completion for all stored links).
2034 When this option is nil, every link which has been inserted once using
2035 `\\[org-insert-link]' will be removed from the list, to make completing the \
2036 unused
2037 links more efficient."
2038 :group 'org-link-store
2039 :type 'boolean)
2041 (defgroup org-link-follow nil
2042 "Options concerning following links in Org mode."
2043 :tag "Org Follow Link"
2044 :group 'org-link)
2046 (defcustom org-link-translation-function nil
2047 "Function to translate links with different syntax to Org syntax.
2048 This can be used to translate links created for example by the Planner
2049 or emacs-wiki packages to Org syntax.
2050 The function must accept two parameters, a TYPE containing the link
2051 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2052 which is everything after the link protocol. It should return a cons
2053 with possibly modified values of type and path.
2054 Org contains a function for this, so if you set this variable to
2055 `org-translate-link-from-planner', you should be able follow many
2056 links created by planner."
2057 :group 'org-link-follow
2058 :type '(choice (const nil) (function)))
2060 (defcustom org-follow-link-hook nil
2061 "Hook that is run after a link has been followed."
2062 :group 'org-link-follow
2063 :type 'hook)
2065 (defcustom org-tab-follows-link nil
2066 "Non-nil means on links TAB will follow the link.
2067 Needs to be set before org.el is loaded.
2068 This really should not be used, it does not make sense, and the
2069 implementation is bad."
2070 :group 'org-link-follow
2071 :type 'boolean)
2073 (defcustom org-return-follows-link nil
2074 "Non-nil means on links RET will follow the link.
2075 In tables, the special behavior of RET has precedence."
2076 :group 'org-link-follow
2077 :type 'boolean)
2079 (defcustom org-mouse-1-follows-link
2080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2081 "Non-nil means mouse-1 on a link will follow the link.
2082 A longer mouse click will still set point. Needs to be set
2083 before org.el is loaded."
2084 :group 'org-link-follow
2085 :version "24.4"
2086 :package-version '(Org . "8.3")
2087 :type '(choice
2088 (const :tag "A double click follows the link" double)
2089 (const :tag "Unconditionally follow the link with mouse-1" t)
2090 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2092 (defcustom org-mark-ring-length 4
2093 "Number of different positions to be recorded in the ring.
2094 Changing this requires a restart of Emacs to work correctly."
2095 :group 'org-link-follow
2096 :type 'integer)
2098 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2099 "Non-nil means internal fuzzy links can only match headlines.
2101 When nil, the a fuzzy link may point to a target or a named
2102 construct in the document. When set to the special value
2103 `query-to-create', offer to create a new headline when none
2104 matched.
2106 Spaces and statistics cookies are ignored during heading searches."
2107 :group 'org-link-follow
2108 :version "24.1"
2109 :type '(choice
2110 (const :tag "Use fuzzy text search" nil)
2111 (const :tag "Match only exact headline" t)
2112 (const :tag "Match exact headline or query to create it"
2113 query-to-create))
2114 :safe #'symbolp)
2116 (defcustom org-link-frame-setup
2117 '((vm . vm-visit-folder-other-frame)
2118 (vm-imap . vm-visit-imap-folder-other-frame)
2119 (gnus . org-gnus-no-new-news)
2120 (file . find-file-other-window)
2121 (wl . wl-other-frame))
2122 "Setup the frame configuration for following links.
2123 When following a link with Emacs, it may often be useful to display
2124 this link in another window or frame. This variable can be used to
2125 set this up for the different types of links.
2126 For VM, use any of
2127 `vm-visit-folder'
2128 `vm-visit-folder-other-window'
2129 `vm-visit-folder-other-frame'
2130 For Gnus, use any of
2131 `gnus'
2132 `gnus-other-frame'
2133 `org-gnus-no-new-news'
2134 For FILE, use any of
2135 `find-file'
2136 `find-file-other-window'
2137 `find-file-other-frame'
2138 For Wanderlust use any of
2139 `wl'
2140 `wl-other-frame'
2141 For the calendar, use the variable `calendar-setup'.
2142 For BBDB, it is currently only possible to display the matches in
2143 another window."
2144 :group 'org-link-follow
2145 :type '(list
2146 (cons (const vm)
2147 (choice
2148 (const vm-visit-folder)
2149 (const vm-visit-folder-other-window)
2150 (const vm-visit-folder-other-frame)))
2151 (cons (const vm-imap)
2152 (choice
2153 (const vm-visit-imap-folder)
2154 (const vm-visit-imap-folder-other-window)
2155 (const vm-visit-imap-folder-other-frame)))
2156 (cons (const gnus)
2157 (choice
2158 (const gnus)
2159 (const gnus-other-frame)
2160 (const org-gnus-no-new-news)))
2161 (cons (const file)
2162 (choice
2163 (const find-file)
2164 (const find-file-other-window)
2165 (const find-file-other-frame)))
2166 (cons (const wl)
2167 (choice
2168 (const wl)
2169 (const wl-other-frame)))))
2171 (defcustom org-display-internal-link-with-indirect-buffer nil
2172 "Non-nil means use indirect buffer to display infile links.
2173 Activating internal links (from one location in a file to another location
2174 in the same file) normally just jumps to the location. When the link is
2175 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2176 is displayed in
2177 another window. When this option is set, the other window actually displays
2178 an indirect buffer clone of the current buffer, to avoid any visibility
2179 changes to the current buffer."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-non-existing-files nil
2184 "Non-nil means `org-open-file' will open non-existing files.
2185 When nil, an error will be generated.
2186 This variable applies only to external applications because they
2187 might choke on non-existing files. If the link is to a file that
2188 will be opened in Emacs, the variable is ignored."
2189 :group 'org-link-follow
2190 :type 'boolean)
2192 (defcustom org-open-directory-means-index-dot-org nil
2193 "Non-nil means a link to a directory really means to index.org.
2194 When nil, following a directory link will run dired or open a finder/explorer
2195 window on that directory."
2196 :group 'org-link-follow
2197 :type 'boolean)
2199 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2200 "Non-nil means ask for confirmation before executing shell links.
2201 Shell links can be dangerous: just think about a link
2203 [[shell:rm -rf ~/*][Google Search]]
2205 This link would show up in your Org document as \"Google Search\",
2206 but really it would remove your entire home directory.
2207 Therefore we advise against setting this variable to nil.
2208 Just change it to `y-or-n-p' if you want to confirm with a
2209 single keystroke rather than having to type \"yes\"."
2210 :group 'org-link-follow
2211 :type '(choice
2212 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2213 (const :tag "with y-or-n (faster)" y-or-n-p)
2214 (const :tag "no confirmation (dangerous)" nil)))
2215 (put 'org-confirm-shell-link-function
2216 'safe-local-variable
2217 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2219 (defcustom org-confirm-shell-link-not-regexp ""
2220 "A regexp to skip confirmation for shell links."
2221 :group 'org-link-follow
2222 :version "24.1"
2223 :type 'regexp)
2225 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2226 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2227 Elisp links can be dangerous: just think about a link
2229 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2231 This link would show up in your Org document as \"Google Search\",
2232 but really it would remove your entire home directory.
2233 Therefore we advise against setting this variable to nil.
2234 Just change it to `y-or-n-p' if you want to confirm with a
2235 single keystroke rather than having to type \"yes\"."
2236 :group 'org-link-follow
2237 :type '(choice
2238 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2239 (const :tag "with y-or-n (faster)" y-or-n-p)
2240 (const :tag "no confirmation (dangerous)" nil)))
2241 (put 'org-confirm-shell-link-function
2242 'safe-local-variable
2243 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2245 (defcustom org-confirm-elisp-link-not-regexp ""
2246 "A regexp to skip confirmation for Elisp links."
2247 :group 'org-link-follow
2248 :version "24.1"
2249 :type 'regexp)
2251 (defconst org-file-apps-defaults-gnu
2252 '((remote . emacs)
2253 (system . mailcap)
2254 (t . mailcap))
2255 "Default file applications on a UNIX or GNU/Linux system.
2256 See `org-file-apps'.")
2258 (defconst org-file-apps-defaults-macosx
2259 '((remote . emacs)
2260 (system . "open %s")
2261 ("ps.gz" . "gv %s")
2262 ("eps.gz" . "gv %s")
2263 ("dvi" . "xdvi %s")
2264 ("fig" . "xfig %s")
2265 (t . "open %s"))
2266 "Default file applications on a macOS system.
2267 The system \"open\" is known as a default, but we use X11 applications
2268 for some files for which the OS does not have a good default.
2269 See `org-file-apps'.")
2271 (defconst org-file-apps-defaults-windowsnt
2272 (list '(remote . emacs)
2273 (cons 'system (lambda (file _path)
2274 (with-no-warnings (w32-shell-execute "open" file))))
2275 (cons t (lambda (file _path)
2276 (with-no-warnings (w32-shell-execute "open" file)))))
2277 "Default file applications on a Windows NT system.
2278 The system \"open\" is used for most files.
2279 See `org-file-apps'.")
2281 (defcustom org-file-apps
2282 '((auto-mode . emacs)
2283 ("\\.mm\\'" . default)
2284 ("\\.x?html?\\'" . default)
2285 ("\\.pdf\\'" . default))
2286 "External applications for opening `file:path' items in a document.
2287 \\<org-mode-map>\
2289 Org mode uses system defaults for different file types, but
2290 you can use this variable to set the application for a given file
2291 extension. The entries in this list are cons cells where the car identifies
2292 files and the cdr the corresponding command.
2294 Possible values for the file identifier are:
2296 \"string\" A string as a file identifier can be interpreted in different
2297 ways, depending on its contents:
2299 - Alphanumeric characters only:
2300 Match links with this file extension.
2301 Example: (\"pdf\" . \"evince %s\")
2302 to open PDFs with evince.
2304 - Regular expression: Match links where the
2305 filename matches the regexp. If you want to
2306 use groups here, use shy groups.
2308 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2309 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2310 to open *.html and *.xhtml with firefox.
2312 - Regular expression which contains (non-shy) groups:
2313 Match links where the whole link, including \"::\", and
2314 anything after that, matches the regexp.
2315 In a custom command string, %1, %2, etc. are replaced with
2316 the parts of the link that were matched by the groups.
2317 For backwards compatibility, if a command string is given
2318 that does not use any of the group matches, this case is
2319 handled identically to the second one (i.e. match against
2320 file name only).
2321 In a custom function, you can access the group matches with
2322 (match-string n link).
2324 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2325 \"evince -p %1 %s\")
2326 to open [[file:document.pdf::5]] with evince at page 5.
2328 `directory' Matches a directory
2329 `remote' Matches a remote file, accessible through tramp or efs.
2330 Remote files most likely should be visited through Emacs
2331 because external applications cannot handle such paths.
2332 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2333 so all files Emacs knows how to handle. Using this with
2334 command `emacs' will open most files in Emacs. Beware that this
2335 will also open html files inside Emacs, unless you add
2336 (\"html\" . default) to the list as well.
2337 `system' The system command to open files, like `open' on Windows
2338 and macOS, and mailcap under GNU/Linux. This is the command
2339 that will be selected if you call `org-open-at-point' with a
2340 double prefix argument (`\\[universal-argument] \
2341 \\[universal-argument] \\[org-open-at-point]').
2342 t Default for files not matched by any of the other options.
2344 Possible values for the command are:
2346 `emacs' The file will be visited by the current Emacs process.
2347 `default' Use the default application for this file type, which is the
2348 association for t in the list, most likely in the system-specific
2349 part. This can be used to overrule an unwanted setting in the
2350 system-specific variable.
2351 `system' Use the system command for opening files, like \"open\".
2352 This command is specified by the entry whose car is `system'.
2353 Most likely, the system-specific version of this variable
2354 does define this command, but you can overrule/replace it
2355 here.
2356 `mailcap' Use command specified in the mailcaps.
2357 string A command to be executed by a shell; %s will be replaced
2358 by the path to the file.
2359 function A Lisp function, which will be called with two arguments:
2360 the file path and the original link string, without the
2361 \"file:\" prefix.
2363 For more examples, see the system specific constants
2364 `org-file-apps-defaults-macosx'
2365 `org-file-apps-defaults-windowsnt'
2366 `org-file-apps-defaults-gnu'."
2367 :group 'org-link-follow
2368 :type '(repeat
2369 (cons (choice :value ""
2370 (string :tag "Extension")
2371 (const :tag "System command to open files" system)
2372 (const :tag "Default for unrecognized files" t)
2373 (const :tag "Remote file" remote)
2374 (const :tag "Links to a directory" directory)
2375 (const :tag "Any files that have Emacs modes"
2376 auto-mode))
2377 (choice :value ""
2378 (const :tag "Visit with Emacs" emacs)
2379 (const :tag "Use default" default)
2380 (const :tag "Use the system command" system)
2381 (string :tag "Command")
2382 (function :tag "Function")))))
2384 (defcustom org-doi-server-url "http://dx.doi.org/"
2385 "The URL of the DOI server."
2386 :type 'string
2387 :version "24.3"
2388 :group 'org-link-follow)
2390 (defgroup org-refile nil
2391 "Options concerning refiling entries in Org mode."
2392 :tag "Org Refile"
2393 :group 'org)
2395 (defcustom org-directory "~/org"
2396 "Directory with Org files.
2397 This is just a default location to look for Org files. There is no need
2398 at all to put your files into this directory. It is used in the
2399 following situations:
2401 1. When a capture template specifies a target file that is not an
2402 absolute path. The path will then be interpreted relative to
2403 `org-directory'
2404 2. When the value of variable `org-agenda-files' is a single file, any
2405 relative paths in this file will be taken as relative to
2406 `org-directory'."
2407 :group 'org-refile
2408 :group 'org-capture
2409 :type 'directory)
2411 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2412 "Default target for storing notes.
2413 Used as a fall back file for org-capture.el, for templates that
2414 do not specify a target file."
2415 :group 'org-refile
2416 :group 'org-capture
2417 :type 'file)
2419 (defcustom org-goto-interface 'outline
2420 "The default interface to be used for `org-goto'.
2421 Allowed values are:
2422 outline The interface shows an outline of the relevant file
2423 and the correct heading is found by moving through
2424 the outline or by searching with incremental search.
2425 outline-path-completion Headlines in the current buffer are offered via
2426 completion. This is the interface also used by
2427 the refile command."
2428 :group 'org-refile
2429 :type '(choice
2430 (const :tag "Outline" outline)
2431 (const :tag "Outline-path-completion" outline-path-completion)))
2433 (defcustom org-goto-max-level 5
2434 "Maximum target level when running `org-goto' with refile interface."
2435 :group 'org-refile
2436 :type 'integer)
2438 (defcustom org-reverse-note-order nil
2439 "Non-nil means store new notes at the beginning of a file or entry.
2440 When nil, new notes will be filed to the end of a file or entry.
2441 This can also be a list with cons cells of regular expressions that
2442 are matched against file names, and values."
2443 :group 'org-capture
2444 :group 'org-refile
2445 :type '(choice
2446 (const :tag "Reverse always" t)
2447 (const :tag "Reverse never" nil)
2448 (repeat :tag "By file name regexp"
2449 (cons regexp boolean))))
2451 (defcustom org-log-refile nil
2452 "Information to record when a task is refiled.
2454 Possible values are:
2456 nil Don't add anything
2457 time Add a time stamp to the task
2458 note Prompt for a note and add it with template `org-log-note-headings'
2460 This option can also be set with on a per-file-basis with
2462 #+STARTUP: nologrefile
2463 #+STARTUP: logrefile
2464 #+STARTUP: lognoterefile
2466 You can have local logging settings for a subtree by setting the LOGGING
2467 property to one or more of these keywords.
2469 When bulk-refiling from the agenda, the value `note' is forbidden and
2470 will temporarily be changed to `time'."
2471 :group 'org-refile
2472 :group 'org-progress
2473 :version "24.1"
2474 :type '(choice
2475 (const :tag "No logging" nil)
2476 (const :tag "Record timestamp" time)
2477 (const :tag "Record timestamp with note." note)))
2479 (defcustom org-refile-targets nil
2480 "Targets for refiling entries with `\\[org-refile]'.
2481 This is a list of cons cells. Each cell contains:
2482 - a specification of the files to be considered, either a list of files,
2483 or a symbol whose function or variable value will be used to retrieve
2484 a file name or a list of file names. If you use `org-agenda-files' for
2485 that, all agenda files will be scanned for targets. Nil means consider
2486 headings in the current buffer.
2487 - A specification of how to find candidate refile targets. This may be
2488 any of:
2489 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2490 This tag has to be present in all target headlines, inheritance will
2491 not be considered.
2492 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2493 todo keyword.
2494 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2495 headlines that are refiling targets.
2496 - a cons cell (:level . N). Any headline of level N is considered a target.
2497 Note that, when `org-odd-levels-only' is set, level corresponds to
2498 order in hierarchy, not to the number of stars.
2499 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2500 Note that, when `org-odd-levels-only' is set, level corresponds to
2501 order in hierarchy, not to the number of stars.
2503 Each element of this list generates a set of possible targets.
2504 The union of these sets is presented (with completion) to
2505 the user by `org-refile'.
2507 You can set the variable `org-refile-target-verify-function' to a function
2508 to verify each headline found by the simple criteria above.
2510 When this variable is nil, all top-level headlines in the current buffer
2511 are used, equivalent to the value `((nil . (:level . 1))'."
2512 :group 'org-refile
2513 :type '(repeat
2514 (cons
2515 (choice :value org-agenda-files
2516 (const :tag "All agenda files" org-agenda-files)
2517 (const :tag "Current buffer" nil)
2518 (function) (variable) (file))
2519 (choice :tag "Identify target headline by"
2520 (cons :tag "Specific tag" (const :value :tag) (string))
2521 (cons :tag "TODO keyword" (const :value :todo) (string))
2522 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2523 (cons :tag "Level number" (const :value :level) (integer))
2524 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2526 (defcustom org-refile-target-verify-function nil
2527 "Function to verify if the headline at point should be a refile target.
2528 The function will be called without arguments, with point at the
2529 beginning of the headline. It should return t and leave point
2530 where it is if the headline is a valid target for refiling.
2532 If the target should not be selected, the function must return nil.
2533 In addition to this, it may move point to a place from where the search
2534 should be continued. For example, the function may decide that the entire
2535 subtree of the current entry should be excluded and move point to the end
2536 of the subtree."
2537 :group 'org-refile
2538 :type '(choice
2539 (const nil)
2540 (function)))
2542 (defcustom org-refile-use-cache nil
2543 "Non-nil means cache refile targets to speed up the process.
2544 \\<org-mode-map>\
2545 The cache for a particular file will be updated automatically when
2546 the buffer has been killed, or when any of the marker used for flagging
2547 refile targets no longer points at a live buffer.
2548 If you have added new entries to a buffer that might themselves be targets,
2549 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2550 if you find that easier, \
2551 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2552 \\[org-refile]'."
2553 :group 'org-refile
2554 :version "24.1"
2555 :type 'boolean)
2557 (defcustom org-refile-use-outline-path nil
2558 "Non-nil means provide refile targets as paths.
2559 So a level 3 headline will be available as level1/level2/level3.
2561 When the value is `file', also include the file name (without directory)
2562 into the path. In this case, you can also stop the completion after
2563 the file name, to get entries inserted as top level in the file.
2565 When `full-file-path', include the full file path.
2567 When `buffer-name', use the buffer name."
2568 :group 'org-refile
2569 :type '(choice
2570 (const :tag "Not" nil)
2571 (const :tag "Yes" t)
2572 (const :tag "Start with file name" file)
2573 (const :tag "Start with full file path" full-file-path)
2574 (const :tag "Start with buffer name" buffer-name)))
2576 (defcustom org-outline-path-complete-in-steps t
2577 "Non-nil means complete the outline path in hierarchical steps.
2578 When Org uses the refile interface to select an outline path (see
2579 `org-refile-use-outline-path'), the completion of the path can be
2580 done in a single go, or it can be done in steps down the headline
2581 hierarchy. Going in steps is probably the best if you do not use
2582 a special completion package like `ido' or `icicles'. However,
2583 when using these packages, going in one step can be very fast,
2584 while still showing the whole path to the entry."
2585 :group 'org-refile
2586 :type 'boolean)
2588 (defcustom org-refile-allow-creating-parent-nodes nil
2589 "Non-nil means allow the creation of new nodes as refile targets.
2590 New nodes are then created by adding \"/new node name\" to the completion
2591 of an existing node. When the value of this variable is `confirm',
2592 new node creation must be confirmed by the user (recommended).
2593 When nil, the completion must match an existing entry.
2595 Note that, if the new heading is not seen by the criteria
2596 listed in `org-refile-targets', multiple instances of the same
2597 heading would be created by trying again to file under the new
2598 heading."
2599 :group 'org-refile
2600 :type '(choice
2601 (const :tag "Never" nil)
2602 (const :tag "Always" t)
2603 (const :tag "Prompt for confirmation" confirm)))
2605 (defcustom org-refile-active-region-within-subtree nil
2606 "Non-nil means also refile active region within a subtree.
2608 By default `org-refile' doesn't allow refiling regions if they
2609 don't contain a set of subtrees, but it might be convenient to
2610 do so sometimes: in that case, the first line of the region is
2611 converted to a headline before refiling."
2612 :group 'org-refile
2613 :version "24.1"
2614 :type 'boolean)
2616 (defgroup org-todo nil
2617 "Options concerning TODO items in Org mode."
2618 :tag "Org TODO"
2619 :group 'org)
2621 (defgroup org-progress nil
2622 "Options concerning Progress logging in Org mode."
2623 :tag "Org Progress"
2624 :group 'org-time)
2626 (defvar org-todo-interpretation-widgets
2627 '((:tag "Sequence (cycling hits every state)" sequence)
2628 (:tag "Type (cycling directly to DONE)" type))
2629 "The available interpretation symbols for customizing `org-todo-keywords'.
2630 Interested libraries should add to this list.")
2632 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2633 "List of TODO entry keyword sequences and their interpretation.
2634 \\<org-mode-map>This is a list of sequences.
2636 Each sequence starts with a symbol, either `sequence' or `type',
2637 indicating if the keywords should be interpreted as a sequence of
2638 action steps, or as different types of TODO items. The first
2639 keywords are states requiring action - these states will select a headline
2640 for inclusion into the global TODO list Org produces. If one of the
2641 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2642 signify that no further action is necessary. If \"|\" is not found,
2643 the last keyword is treated as the only DONE state of the sequence.
2645 The command `\\[org-todo]' cycles an entry through these states, and one
2646 additional state where no keyword is present. For details about this
2647 cycling, see the manual.
2649 TODO keywords and interpretation can also be set on a per-file basis with
2650 the special #+SEQ_TODO and #+TYP_TODO lines.
2652 Each keyword can optionally specify a character for fast state selection
2653 \(in combination with the variable `org-use-fast-todo-selection')
2654 and specifiers for state change logging, using the same syntax that
2655 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2656 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2657 indicates to record a time stamp each time this state is selected.
2659 Each keyword may also specify if a timestamp or a note should be
2660 recorded when entering or leaving the state, by adding additional
2661 characters in the parenthesis after the keyword. This looks like this:
2662 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2663 record only the time of the state change. With X and Y being either
2664 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2665 Y when leaving the state if and only if the *target* state does not
2666 define X. You may omit any of the fast-selection key or X or /Y,
2667 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2669 For backward compatibility, this variable may also be just a list
2670 of keywords. In this case the interpretation (sequence or type) will be
2671 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2672 :group 'org-todo
2673 :group 'org-keywords
2674 :type '(choice
2675 (repeat :tag "Old syntax, just keywords"
2676 (string :tag "Keyword"))
2677 (repeat :tag "New syntax"
2678 (cons
2679 (choice
2680 :tag "Interpretation"
2681 ;;Quick and dirty way to see
2682 ;;`org-todo-interpretations'. This takes the
2683 ;;place of item arguments
2684 :convert-widget
2685 (lambda (widget)
2686 (widget-put widget
2687 :args (mapcar
2688 (lambda (x)
2689 (widget-convert
2690 (cons 'const x)))
2691 org-todo-interpretation-widgets))
2692 widget))
2693 (repeat
2694 (string :tag "Keyword"))))))
2696 (defvar-local org-todo-keywords-1 nil
2697 "All TODO and DONE keywords active in a buffer.")
2698 (defvar org-todo-keywords-for-agenda nil)
2699 (defvar org-done-keywords-for-agenda nil)
2700 (defvar org-todo-keyword-alist-for-agenda nil)
2701 (defvar org-tag-alist-for-agenda nil
2702 "Alist of all tags from all agenda files.")
2703 (defvar org-tag-groups-alist-for-agenda nil
2704 "Alist of all groups tags from all current agenda files.")
2705 (defvar-local org-tag-groups-alist nil)
2706 (defvar org-agenda-contributing-files nil)
2707 (defvar-local org-current-tag-alist nil
2708 "Alist of all tag groups in current buffer.
2709 This variable takes into consideration `org-tag-alist',
2710 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2711 (defvar-local org-not-done-keywords nil)
2712 (defvar-local org-done-keywords nil)
2713 (defvar-local org-todo-heads nil)
2714 (defvar-local org-todo-sets nil)
2715 (defvar-local org-todo-log-states nil)
2716 (defvar-local org-todo-kwd-alist nil)
2717 (defvar-local org-todo-key-alist nil)
2718 (defvar-local org-todo-key-trigger nil)
2720 (defcustom org-todo-interpretation 'sequence
2721 "Controls how TODO keywords are interpreted.
2722 This variable is in principle obsolete and is only used for
2723 backward compatibility, if the interpretation of todo keywords is
2724 not given already in `org-todo-keywords'. See that variable for
2725 more information."
2726 :group 'org-todo
2727 :group 'org-keywords
2728 :type '(choice (const sequence)
2729 (const type)))
2731 (defcustom org-use-fast-todo-selection t
2732 "\\<org-mode-map>\
2733 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2734 This variable describes if and under what circumstances the cycling
2735 mechanism for TODO keywords will be replaced by a single-key, direct
2736 selection scheme.
2738 When nil, fast selection is never used.
2740 When the symbol `prefix', it will be used when `org-todo' is called
2741 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2742 in an Org buffer, and
2743 `\\[universal-argument] t' in an agenda buffer.
2745 When t, fast selection is used by default. In this case, the prefix
2746 argument forces cycling instead.
2748 In all cases, the special interface is only used if access keys have
2749 actually been assigned by the user, i.e. if keywords in the configuration
2750 are followed by a letter in parenthesis, like TODO(t)."
2751 :group 'org-todo
2752 :type '(choice
2753 (const :tag "Never" nil)
2754 (const :tag "By default" t)
2755 (const :tag "Only with C-u C-c C-t" prefix)))
2757 (defcustom org-provide-todo-statistics t
2758 "Non-nil means update todo statistics after insert and toggle.
2759 ALL-HEADLINES means update todo statistics by including headlines
2760 with no TODO keyword as well, counting them as not done.
2761 A list of TODO keywords means the same, but skip keywords that are
2762 not in this list.
2763 When set to a list of two lists, the first list contains keywords
2764 to consider as TODO keywords, the second list contains keywords
2765 to consider as DONE keywords.
2767 When this is set, todo statistics is updated in the parent of the
2768 current entry each time a todo state is changed."
2769 :group 'org-todo
2770 :type '(choice
2771 (const :tag "Yes, only for TODO entries" t)
2772 (const :tag "Yes, including all entries" all-headlines)
2773 (repeat :tag "Yes, for TODOs in this list"
2774 (string :tag "TODO keyword"))
2775 (list :tag "Yes, for TODOs and DONEs in these lists"
2776 (repeat (string :tag "TODO keyword"))
2777 (repeat (string :tag "DONE keyword")))
2778 (other :tag "No TODO statistics" nil)))
2780 (defcustom org-hierarchical-todo-statistics t
2781 "Non-nil means TODO statistics covers just direct children.
2782 When nil, all entries in the subtree are considered.
2783 This has only an effect if `org-provide-todo-statistics' is set.
2784 To set this to nil for only a single subtree, use a COOKIE_DATA
2785 property and include the word \"recursive\" into the value."
2786 :group 'org-todo
2787 :type 'boolean)
2789 (defcustom org-after-todo-state-change-hook nil
2790 "Hook which is run after the state of a TODO item was changed.
2791 The new state (a string with a TODO keyword, or nil) is available in the
2792 Lisp variable `org-state'."
2793 :group 'org-todo
2794 :type 'hook)
2796 (defvar org-blocker-hook nil
2797 "Hook for functions that are allowed to block a state change.
2799 Functions in this hook should not modify the buffer.
2800 Each function gets as its single argument a property list,
2801 see `org-trigger-hook' for more information about this list.
2803 If any of the functions in this hook returns nil, the state change
2804 is blocked.")
2806 (defvar org-trigger-hook nil
2807 "Hook for functions that are triggered by a state change.
2809 Each function gets as its single argument a property list with at
2810 least the following elements:
2812 (:type type-of-change :position pos-at-entry-start
2813 :from old-state :to new-state)
2815 Depending on the type, more properties may be present.
2817 This mechanism is currently implemented for:
2819 TODO state changes
2820 ------------------
2821 :type todo-state-change
2822 :from previous state (keyword as a string), or nil, or a symbol
2823 `todo' or `done', to indicate the general type of state.
2824 :to new state, like in :from")
2826 (defcustom org-enforce-todo-dependencies nil
2827 "Non-nil means undone TODO entries will block switching the parent to DONE.
2828 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2829 be blocked if any prior sibling is not yet done.
2830 Finally, if the parent is blocked because of ordered siblings of its own,
2831 the child will also be blocked."
2832 :set (lambda (var val)
2833 (set var val)
2834 (if val
2835 (add-hook 'org-blocker-hook
2836 'org-block-todo-from-children-or-siblings-or-parent)
2837 (remove-hook 'org-blocker-hook
2838 'org-block-todo-from-children-or-siblings-or-parent)))
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-enforce-todo-checkbox-dependencies nil
2843 "Non-nil means unchecked boxes will block switching the parent to DONE.
2844 When this is nil, checkboxes have no influence on switching TODO states.
2845 When non-nil, you first need to check off all check boxes before the TODO
2846 entry can be switched to DONE.
2847 This variable needs to be set before org.el is loaded, and you need to
2848 restart Emacs after a change to make the change effective. The only way
2849 to change is while Emacs is running is through the customize interface."
2850 :set (lambda (var val)
2851 (set var val)
2852 (if val
2853 (add-hook 'org-blocker-hook
2854 'org-block-todo-from-checkboxes)
2855 (remove-hook 'org-blocker-hook
2856 'org-block-todo-from-checkboxes)))
2857 :group 'org-todo
2858 :type 'boolean)
2860 (defcustom org-treat-insert-todo-heading-as-state-change nil
2861 "Non-nil means inserting a TODO heading is treated as state change.
2862 So when the command `\\[org-insert-todo-heading]' is used, state change
2863 logging will apply if appropriate. When nil, the new TODO item will
2864 be inserted directly, and no logging will take place."
2865 :group 'org-todo
2866 :type 'boolean)
2868 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2869 "Non-nil means switching TODO states with S-cursor counts as state change.
2870 This is the default behavior. However, setting this to nil allows a
2871 convenient way to select a TODO state and bypass any logging associated
2872 with that."
2873 :group 'org-todo
2874 :type 'boolean)
2876 (defcustom org-todo-state-tags-triggers nil
2877 "Tag changes that should be triggered by TODO state changes.
2878 This is a list. Each entry is
2880 (state-change (tag . flag) .......)
2882 State-change can be a string with a state, and empty string to indicate the
2883 state that has no TODO keyword, or it can be one of the symbols `todo'
2884 or `done', meaning any not-done or done state, respectively."
2885 :group 'org-todo
2886 :group 'org-tags
2887 :type '(repeat
2888 (cons (choice :tag "When changing to"
2889 (const :tag "Not-done state" todo)
2890 (const :tag "Done state" done)
2891 (string :tag "State"))
2892 (repeat
2893 (cons :tag "Tag action"
2894 (string :tag "Tag")
2895 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2897 (defcustom org-log-done nil
2898 "Information to record when a task moves to the DONE state.
2900 Possible values are:
2902 nil Don't add anything, just change the keyword
2903 time Add a time stamp to the task
2904 note Prompt for a note and add it with template `org-log-note-headings'
2906 This option can also be set with on a per-file-basis with
2908 #+STARTUP: nologdone
2909 #+STARTUP: logdone
2910 #+STARTUP: lognotedone
2912 You can have local logging settings for a subtree by setting the LOGGING
2913 property to one or more of these keywords."
2914 :group 'org-todo
2915 :group 'org-progress
2916 :type '(choice
2917 (const :tag "No logging" nil)
2918 (const :tag "Record CLOSED timestamp" time)
2919 (const :tag "Record CLOSED timestamp with note." note)))
2921 ;; Normalize old uses of org-log-done.
2922 (cond
2923 ((eq org-log-done t) (setq org-log-done 'time))
2924 ((and (listp org-log-done) (memq 'done org-log-done))
2925 (setq org-log-done 'note)))
2927 (defcustom org-log-reschedule nil
2928 "Information to record when the scheduling date of a tasks is modified.
2930 Possible values are:
2932 nil Don't add anything, just change the date
2933 time Add a time stamp to the task
2934 note Prompt for a note and add it with template `org-log-note-headings'
2936 This option can also be set with on a per-file-basis with
2938 #+STARTUP: nologreschedule
2939 #+STARTUP: logreschedule
2940 #+STARTUP: lognotereschedule"
2941 :group 'org-todo
2942 :group 'org-progress
2943 :type '(choice
2944 (const :tag "No logging" nil)
2945 (const :tag "Record timestamp" time)
2946 (const :tag "Record timestamp with note." note)))
2948 (defcustom org-log-redeadline nil
2949 "Information to record when the deadline date of a tasks is modified.
2951 Possible values are:
2953 nil Don't add anything, just change the date
2954 time Add a time stamp to the task
2955 note Prompt for a note and add it with template `org-log-note-headings'
2957 This option can also be set with on a per-file-basis with
2959 #+STARTUP: nologredeadline
2960 #+STARTUP: logredeadline
2961 #+STARTUP: lognoteredeadline
2963 You can have local logging settings for a subtree by setting the LOGGING
2964 property to one or more of these keywords."
2965 :group 'org-todo
2966 :group 'org-progress
2967 :type '(choice
2968 (const :tag "No logging" nil)
2969 (const :tag "Record timestamp" time)
2970 (const :tag "Record timestamp with note." note)))
2972 (defcustom org-log-note-clock-out nil
2973 "Non-nil means record a note when clocking out of an item.
2974 This can also be configured on a per-file basis by adding one of
2975 the following lines anywhere in the buffer:
2977 #+STARTUP: lognoteclock-out
2978 #+STARTUP: nolognoteclock-out"
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type 'boolean)
2983 (defcustom org-log-done-with-time t
2984 "Non-nil means the CLOSED time stamp will contain date and time.
2985 When nil, only the date will be recorded."
2986 :group 'org-progress
2987 :type 'boolean)
2989 (defcustom org-log-note-headings
2990 '((done . "CLOSING NOTE %t")
2991 (state . "State %-12s from %-12S %t")
2992 (note . "Note taken on %t")
2993 (reschedule . "Rescheduled from %S on %t")
2994 (delschedule . "Not scheduled, was %S on %t")
2995 (redeadline . "New deadline from %S on %t")
2996 (deldeadline . "Removed deadline, was %S on %t")
2997 (refile . "Refiled on %t")
2998 (clock-out . ""))
2999 "Headings for notes added to entries.
3001 The value is an alist, with the car being a symbol indicating the
3002 note context, and the cdr is the heading to be used. The heading
3003 may also be the empty string. The following placeholders can be
3004 used:
3006 %t a time stamp.
3007 %T an active time stamp instead the default inactive one
3008 %d a short-format time stamp.
3009 %D an active short-format time stamp.
3010 %s the new TODO state or time stamp (inactive), in double quotes.
3011 %S the old TODO state or time stamp (inactive), in double quotes.
3012 %u the user name.
3013 %U full user name.
3015 In fact, it is not a good idea to change the `state' entry,
3016 because Agenda Log mode depends on the format of these entries."
3017 :group 'org-todo
3018 :group 'org-progress
3019 :type '(list :greedy t
3020 (cons (const :tag "Heading when closing an item" done) string)
3021 (cons (const :tag
3022 "Heading when changing todo state (todo sequence only)"
3023 state) string)
3024 (cons (const :tag "Heading when just taking a note" note) string)
3025 (cons (const :tag "Heading when rescheduling" reschedule) string)
3026 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3027 (cons (const :tag "Heading when changing deadline" redeadline) string)
3028 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3029 (cons (const :tag "Heading when refiling" refile) string)
3030 (cons (const :tag "Heading when clocking out" clock-out) string)))
3032 (unless (assq 'note org-log-note-headings)
3033 (push '(note . "%t") org-log-note-headings))
3035 (defcustom org-log-into-drawer nil
3036 "Non-nil means insert state change notes and time stamps into a drawer.
3037 When nil, state changes notes will be inserted after the headline and
3038 any scheduling and clock lines, but not inside a drawer.
3040 The value of this variable should be the name of the drawer to use.
3041 LOGBOOK is proposed as the default drawer for this purpose, you can
3042 also set this to a string to define the drawer of your choice.
3044 A value of t is also allowed, representing \"LOGBOOK\".
3046 A value of t or nil can also be set with on a per-file-basis with
3048 #+STARTUP: logdrawer
3049 #+STARTUP: nologdrawer
3051 If this variable is set, `org-log-state-notes-insert-after-drawers'
3052 will be ignored.
3054 You can set the property LOG_INTO_DRAWER to overrule this setting for
3055 a subtree.
3057 Do not check directly this variable in a Lisp program. Call
3058 function `org-log-into-drawer' instead."
3059 :group 'org-todo
3060 :group 'org-progress
3061 :type '(choice
3062 (const :tag "Not into a drawer" nil)
3063 (const :tag "LOGBOOK" t)
3064 (string :tag "Other")))
3066 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3068 (defun org-log-into-drawer ()
3069 "Name of the log drawer, as a string, or nil.
3070 This is the value of `org-log-into-drawer'. However, if the
3071 current entry has or inherits a LOG_INTO_DRAWER property, it will
3072 be used instead of the default value."
3073 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3074 (cond ((equal p "nil") nil)
3075 ((equal p "t") "LOGBOOK")
3076 ((stringp p) p)
3077 (p "LOGBOOK")
3078 ((stringp org-log-into-drawer) org-log-into-drawer)
3079 (org-log-into-drawer "LOGBOOK"))))
3081 (defcustom org-log-state-notes-insert-after-drawers nil
3082 "Non-nil means insert state change notes after any drawers in entry.
3083 Only the drawers that *immediately* follow the headline and the
3084 deadline/scheduled line are skipped.
3085 When nil, insert notes right after the heading and perhaps the line
3086 with deadline/scheduling if present.
3088 This variable will have no effect if `org-log-into-drawer' is
3089 set."
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-log-states-order-reversed t
3095 "Non-nil means the latest state note will be directly after heading.
3096 When nil, the state change notes will be ordered according to time.
3098 This option can also be set with on a per-file-basis with
3100 #+STARTUP: logstatesreversed
3101 #+STARTUP: nologstatesreversed"
3102 :group 'org-todo
3103 :group 'org-progress
3104 :type 'boolean)
3106 (defcustom org-todo-repeat-to-state nil
3107 "The TODO state to which a repeater should return the repeating task.
3108 By default this is the first task in a TODO sequence, or the previous state
3109 in a TODO_TYP set. But you can specify another task here.
3110 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3111 :group 'org-todo
3112 :version "24.1"
3113 :type '(choice (const :tag "Head of sequence" nil)
3114 (string :tag "Specific state")))
3116 (defcustom org-log-repeat 'time
3117 "Non-nil means record moving through the DONE state when triggering repeat.
3118 An auto-repeating task is immediately switched back to TODO when
3119 marked DONE. If you are not logging state changes (by adding \"@\"
3120 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3121 record a closing note, there will be no record of the task moving
3122 through DONE. This variable forces taking a note anyway.
3124 nil Don't force a record
3125 time Record a time stamp
3126 note Prompt for a note and add it with template `org-log-note-headings'
3128 This option can also be set with on a per-file-basis with
3130 #+STARTUP: nologrepeat
3131 #+STARTUP: logrepeat
3132 #+STARTUP: lognoterepeat
3134 You can have local logging settings for a subtree by setting the LOGGING
3135 property to one or more of these keywords."
3136 :group 'org-todo
3137 :group 'org-progress
3138 :type '(choice
3139 (const :tag "Don't force a record" nil)
3140 (const :tag "Force recording the DONE state" time)
3141 (const :tag "Force recording a note with the DONE state" note)))
3144 (defgroup org-priorities nil
3145 "Priorities in Org mode."
3146 :tag "Org Priorities"
3147 :group 'org-todo)
3149 (defcustom org-enable-priority-commands t
3150 "Non-nil means priority commands are active.
3151 When nil, these commands will be disabled, so that you never accidentally
3152 set a priority."
3153 :group 'org-priorities
3154 :type 'boolean)
3156 (defcustom org-highest-priority ?A
3157 "The highest priority of TODO items. A character like ?A, ?B etc.
3158 Must have a smaller ASCII number than `org-lowest-priority'."
3159 :group 'org-priorities
3160 :type 'character)
3162 (defcustom org-lowest-priority ?C
3163 "The lowest priority of TODO items. A character like ?A, ?B etc.
3164 Must have a larger ASCII number than `org-highest-priority'."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-default-priority ?B
3169 "The default priority of TODO items.
3170 This is the priority an item gets if no explicit priority is given.
3171 When starting to cycle on an empty priority the first step in the cycle
3172 depends on `org-priority-start-cycle-with-default'. The resulting first
3173 step priority must not exceed the range from `org-highest-priority' to
3174 `org-lowest-priority' which means that `org-default-priority' has to be
3175 in this range exclusive or inclusive the range boundaries. Else the
3176 first step refuses to set the default and the second will fall back
3177 to (depending on the command used) the highest or lowest priority."
3178 :group 'org-priorities
3179 :type 'character)
3181 (defcustom org-priority-start-cycle-with-default t
3182 "Non-nil means start with default priority when starting to cycle.
3183 When this is nil, the first step in the cycle will be (depending on the
3184 command used) one higher or lower than the default priority.
3185 See also `org-default-priority'."
3186 :group 'org-priorities
3187 :type 'boolean)
3189 (defcustom org-get-priority-function nil
3190 "Function to extract the priority from a string.
3191 The string is normally the headline. If this is nil Org computes the
3192 priority from the priority cookie like [#A] in the headline. It returns
3193 an integer, increasing by 1000 for each priority level.
3194 The user can set a different function here, which should take a string
3195 as an argument and return the numeric priority."
3196 :group 'org-priorities
3197 :version "24.1"
3198 :type '(choice
3199 (const nil)
3200 (function)))
3202 (defgroup org-time nil
3203 "Options concerning time stamps and deadlines in Org mode."
3204 :tag "Org Time"
3205 :group 'org)
3207 (defcustom org-time-stamp-rounding-minutes '(0 5)
3208 "Number of minutes to round time stamps to.
3209 \\<org-mode-map>\
3210 These are two values, the first applies when first creating a time stamp.
3211 The second applies when changing it with the commands `S-up' and `S-down'.
3212 When changing the time stamp, this means that it will change in steps
3213 of N minutes, as given by the second value.
3215 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3216 numbers should be factors of 60, so for example 5, 10, 15.
3218 When this is larger than 1, you can still force an exact time stamp by using
3219 a double prefix argument to a time stamp command like \
3220 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3221 and by using a prefix arg to `S-up/down' to specify the exact number
3222 of minutes to shift."
3223 :group 'org-time
3224 :get (lambda (var) ; Make sure both elements are there
3225 (if (integerp (default-value var))
3226 (list (default-value var) 5)
3227 (default-value var)))
3228 :type '(list
3229 (integer :tag "when inserting times")
3230 (integer :tag "when modifying times")))
3232 ;; Normalize old customizations of this variable.
3233 (when (integerp org-time-stamp-rounding-minutes)
3234 (setq org-time-stamp-rounding-minutes
3235 (list org-time-stamp-rounding-minutes
3236 org-time-stamp-rounding-minutes)))
3238 (defcustom org-display-custom-times nil
3239 "Non-nil means overlay custom formats over all time stamps.
3240 The formats are defined through the variable `org-time-stamp-custom-formats'.
3241 To turn this on on a per-file basis, insert anywhere in the file:
3242 #+STARTUP: customtime"
3243 :group 'org-time
3244 :set 'set-default
3245 :type 'sexp)
3246 (make-variable-buffer-local 'org-display-custom-times)
3248 (defcustom org-time-stamp-custom-formats
3249 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3250 "Custom formats for time stamps. See `format-time-string' for the syntax.
3251 These are overlaid over the default ISO format if the variable
3252 `org-display-custom-times' is set. Time like %H:%M should be at the
3253 end of the second format. The custom formats are also honored by export
3254 commands, if custom time display is turned on at the time of export."
3255 :group 'org-time
3256 :type 'sexp)
3258 (defun org-time-stamp-format (&optional long inactive)
3259 "Get the right format for a time string."
3260 (let ((f (if long (cdr org-time-stamp-formats)
3261 (car org-time-stamp-formats))))
3262 (if inactive
3263 (concat "[" (substring f 1 -1) "]")
3264 f)))
3266 (defcustom org-deadline-warning-days 14
3267 "Number of days before expiration during which a deadline becomes active.
3268 This variable governs the display in sparse trees and in the agenda.
3269 When 0 or negative, it means use this number (the absolute value of it)
3270 even if a deadline has a different individual lead time specified.
3272 Custom commands can set this variable in the options section."
3273 :group 'org-time
3274 :group 'org-agenda-daily/weekly
3275 :type 'integer)
3277 (defcustom org-scheduled-delay-days 0
3278 "Number of days before a scheduled item becomes active.
3279 This variable governs the display in sparse trees and in the agenda.
3280 The default value (i.e. 0) means: don't delay scheduled item.
3281 When negative, it means use this number (the absolute value of it)
3282 even if a scheduled item has a different individual delay time
3283 specified.
3285 Custom commands can set this variable in the options section."
3286 :group 'org-time
3287 :group 'org-agenda-daily/weekly
3288 :version "24.4"
3289 :package-version '(Org . "8.0")
3290 :type 'integer)
3292 (defcustom org-read-date-prefer-future t
3293 "Non-nil means assume future for incomplete date input from user.
3294 This affects the following situations:
3295 1. The user gives a month but not a year.
3296 For example, if it is April and you enter \"feb 2\", this will be read
3297 as Feb 2, *next* year. \"May 5\", however, will be this year.
3298 2. The user gives a day, but no month.
3299 For example, if today is the 15th, and you enter \"3\", Org will read
3300 this as the third of *next* month. However, if you enter \"17\",
3301 it will be considered as *this* month.
3303 If you set this variable to the symbol `time', then also the following
3304 will work:
3306 3. If the user gives a time.
3307 If the time is before now, it will be interpreted as tomorrow.
3309 Currently none of this works for ISO week specifications.
3311 When this option is nil, the current day, month and year will always be
3312 used as defaults.
3314 See also `org-agenda-jump-prefer-future'."
3315 :group 'org-time
3316 :type '(choice
3317 (const :tag "Never" nil)
3318 (const :tag "Check month and day" t)
3319 (const :tag "Check month, day, and time" time)))
3321 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3322 "Should the agenda jump command prefer the future for incomplete dates?
3323 The default is to do the same as configured in `org-read-date-prefer-future'.
3324 But you can also set a deviating value here.
3325 This may t or nil, or the symbol `org-read-date-prefer-future'."
3326 :group 'org-agenda
3327 :group 'org-time
3328 :version "24.1"
3329 :type '(choice
3330 (const :tag "Use org-read-date-prefer-future"
3331 org-read-date-prefer-future)
3332 (const :tag "Never" nil)
3333 (const :tag "Always" t)))
3335 (defcustom org-read-date-force-compatible-dates t
3336 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3338 Depending on the system Emacs is running on, certain dates cannot
3339 be represented with the type used internally to represent time.
3340 Dates between 1970-1-1 and 2038-1-1 can always be represented
3341 correctly. Some systems allow for earlier dates, some for later,
3342 some for both. One way to find out it to insert any date into an
3343 Org buffer, putting the cursor on the year and hitting S-up and
3344 S-down to test the range.
3346 When this variable is set to t, the date/time prompt will not let
3347 you specify dates outside the 1970-2037 range, so it is certain that
3348 these dates will work in whatever version of Emacs you are
3349 running, and also that you can move a file from one Emacs implementation
3350 to another. WHenever Org is forcing the year for you, it will display
3351 a message and beep.
3353 When this variable is nil, Org will check if the date is
3354 representable in the specific Emacs implementation you are using.
3355 If not, it will force a year, usually the current year, and beep
3356 to remind you. Currently this setting is not recommended because
3357 the likelihood that you will open your Org files in an Emacs that
3358 has limited date range is not negligible.
3360 A workaround for this problem is to use diary sexp dates for time
3361 stamps outside of this range."
3362 :group 'org-time
3363 :version "24.1"
3364 :type 'boolean)
3366 (defcustom org-read-date-display-live t
3367 "Non-nil means display current interpretation of date prompt live.
3368 This display will be in an overlay, in the minibuffer."
3369 :group 'org-time
3370 :type 'boolean)
3372 (defcustom org-read-date-popup-calendar t
3373 "Non-nil means pop up a calendar when prompting for a date.
3374 In the calendar, the date can be selected with mouse-1. However, the
3375 minibuffer will also be active, and you can simply enter the date as well.
3376 When nil, only the minibuffer will be available."
3377 :group 'org-time
3378 :type 'boolean)
3379 (defvaralias 'org-popup-calendar-for-date-prompt
3380 'org-read-date-popup-calendar)
3382 (defcustom org-extend-today-until 0
3383 "The hour when your day really ends. Must be an integer.
3384 This has influence for the following applications:
3385 - When switching the agenda to \"today\". It it is still earlier than
3386 the time given here, the day recognized as TODAY is actually yesterday.
3387 - When a date is read from the user and it is still before the time given
3388 here, the current date and time will be assumed to be yesterday, 23:59.
3389 Also, timestamps inserted in capture templates follow this rule.
3391 IMPORTANT: This is a feature whose implementation is and likely will
3392 remain incomplete. Really, it is only here because past midnight seems to
3393 be the favorite working time of John Wiegley :-)"
3394 :group 'org-time
3395 :type 'integer)
3397 (defcustom org-use-effective-time nil
3398 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3399 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3400 \"effective time\" of any timestamps between midnight and 8am will be
3401 23:59 of the previous day."
3402 :group 'org-time
3403 :version "24.1"
3404 :type 'boolean)
3406 (defcustom org-use-last-clock-out-time-as-effective-time nil
3407 "When non-nil, use the last clock out time for `org-todo'.
3408 Note that this option has precedence over the combined use of
3409 `org-use-effective-time' and `org-extend-today-until'."
3410 :group 'org-time
3411 :version "24.4"
3412 :package-version '(Org . "8.0")
3413 :type 'boolean)
3415 (defcustom org-edit-timestamp-down-means-later nil
3416 "Non-nil means S-down will increase the time in a time stamp.
3417 When nil, S-up will increase."
3418 :group 'org-time
3419 :type 'boolean)
3421 (defcustom org-calendar-follow-timestamp-change t
3422 "Non-nil means make the calendar window follow timestamp changes.
3423 When a timestamp is modified and the calendar window is visible, it will be
3424 moved to the new date."
3425 :group 'org-time
3426 :type 'boolean)
3428 (defgroup org-tags nil
3429 "Options concerning tags in Org mode."
3430 :tag "Org Tags"
3431 :group 'org)
3433 (defcustom org-tag-alist nil
3434 "Default tags available in Org files.
3436 The value of this variable is an alist. Associations either:
3438 (TAG)
3439 (TAG . SELECT)
3440 (SPECIAL)
3442 where TAG is a tag as a string, SELECT is character, used to
3443 select that tag through the fast tag selection interface, and
3444 SPECIAL is one of the following keywords: `:startgroup',
3445 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3446 `:newline'. These keywords are used to define a hierarchy of
3447 tags. See manual for details.
3449 When this variable is nil, Org mode bases tag input on what is
3450 already in the buffer. The value can be overridden locally by
3451 using a TAGS keyword, e.g.,
3453 #+TAGS: tag1 tag2
3455 See also `org-tag-persistent-alist' to sidestep this behavior."
3456 :group 'org-tags
3457 :type '(repeat
3458 (choice
3459 (cons (string :tag "Tag name")
3460 (character :tag "Access char"))
3461 (const :tag "Start radio group" (:startgroup))
3462 (const :tag "Start tag group, non distinct" (:startgrouptag))
3463 (const :tag "Group tags delimiter" (:grouptags))
3464 (const :tag "End radio group" (:endgroup))
3465 (const :tag "End tag group, non distinct" (:endgrouptag))
3466 (const :tag "New line" (:newline)))))
3468 (defcustom org-tag-persistent-alist nil
3469 "Tags always available in Org files.
3471 The value of this variable is an alist. Associations either:
3473 (TAG)
3474 (TAG . SELECT)
3475 (SPECIAL)
3477 where TAG is a tag as a string, SELECT is a character, used to
3478 select that tag through the fast tag selection interface, and
3479 SPECIAL is one of the following keywords: `:startgroup',
3480 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3481 `:newline'. These keywords are used to define a hierarchy of
3482 tags. See manual for details.
3484 Unlike to `org-tag-alist', tags defined in this variable do not
3485 depend on a local TAGS keyword. Instead, to disable these tags
3486 on a per-file basis, insert anywhere in the file:
3488 #+STARTUP: noptag"
3489 :group 'org-tags
3490 :type '(repeat
3491 (choice
3492 (cons (string :tag "Tag name")
3493 (character :tag "Access char"))
3494 (const :tag "Start radio group" (:startgroup))
3495 (const :tag "Start tag group, non distinct" (:startgrouptag))
3496 (const :tag "Group tags delimiter" (:grouptags))
3497 (const :tag "End radio group" (:endgroup))
3498 (const :tag "End tag group, non distinct" (:endgrouptag))
3499 (const :tag "New line" (:newline)))))
3501 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3502 "If non-nil, always offer completion for all tags of all agenda files.
3503 Instead of customizing this variable directly, you might want to
3504 set it locally for capture buffers, because there no list of
3505 tags in that file can be created dynamically (there are none).
3507 (add-hook \\='org-capture-mode-hook
3508 (lambda ()
3509 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3510 :group 'org-tags
3511 :version "24.1"
3512 :type 'boolean)
3514 (defvar org-file-tags nil
3515 "List of tags that can be inherited by all entries in the file.
3516 The tags will be inherited if the variable `org-use-tag-inheritance'
3517 says they should be.
3518 This variable is populated from #+FILETAGS lines.")
3520 (defcustom org-use-fast-tag-selection 'auto
3521 "Non-nil means use fast tag selection scheme.
3522 This is a special interface to select and deselect tags with single keys.
3523 When nil, fast selection is never used.
3524 When the symbol `auto', fast selection is used if and only if selection
3525 characters for tags have been configured, either through the variable
3526 `org-tag-alist' or through a #+TAGS line in the buffer.
3527 When t, fast selection is always used and selection keys are assigned
3528 automatically if necessary."
3529 :group 'org-tags
3530 :type '(choice
3531 (const :tag "Always" t)
3532 (const :tag "Never" nil)
3533 (const :tag "When selection characters are configured" auto)))
3535 (defcustom org-fast-tag-selection-single-key nil
3536 "Non-nil means fast tag selection exits after first change.
3537 When nil, you have to press RET to exit it.
3538 During fast tag selection, you can toggle this flag with `C-c'.
3539 This variable can also have the value `expert'. In this case, the window
3540 displaying the tags menu is not even shown, until you press C-c again."
3541 :group 'org-tags
3542 :type '(choice
3543 (const :tag "No" nil)
3544 (const :tag "Yes" t)
3545 (const :tag "Expert" expert)))
3547 (defvar org-fast-tag-selection-include-todo nil
3548 "Non-nil means fast tags selection interface will also offer TODO states.
3549 This is an undocumented feature, you should not rely on it.")
3551 (defcustom org-tags-column -77
3552 "The column to which tags should be indented in a headline.
3553 If this number is positive, it specifies the column. If it is negative,
3554 it means that the tags should be flushright to that column. For example,
3555 -80 works well for a normal 80 character screen.
3556 When 0, place tags directly after headline text, with only one space in
3557 between."
3558 :group 'org-tags
3559 :type 'integer)
3561 (defcustom org-auto-align-tags t
3562 "Non-nil keeps tags aligned when modifying headlines.
3563 Some operations (i.e. demoting) change the length of a headline and
3564 therefore shift the tags around. With this option turned on, after
3565 each such operation the tags are again aligned to `org-tags-column'."
3566 :group 'org-tags
3567 :type 'boolean)
3569 (defcustom org-use-tag-inheritance t
3570 "Non-nil means tags in levels apply also for sublevels.
3571 When nil, only the tags directly given in a specific line apply there.
3572 This may also be a list of tags that should be inherited, or a regexp that
3573 matches tags that should be inherited. Additional control is possible
3574 with the variable `org-tags-exclude-from-inheritance' which gives an
3575 explicit list of tags to be excluded from inheritance, even if the value of
3576 `org-use-tag-inheritance' would select it for inheritance.
3578 If this option is t, a match early-on in a tree can lead to a large
3579 number of matches in the subtree when constructing the agenda or creating
3580 a sparse tree. If you only want to see the first match in a tree during
3581 a search, check out the variable `org-tags-match-list-sublevels'."
3582 :group 'org-tags
3583 :type '(choice
3584 (const :tag "Not" nil)
3585 (const :tag "Always" t)
3586 (repeat :tag "Specific tags" (string :tag "Tag"))
3587 (regexp :tag "Tags matched by regexp")))
3589 (defcustom org-tags-exclude-from-inheritance nil
3590 "List of tags that should never be inherited.
3591 This is a way to exclude a few tags from inheritance. For way to do
3592 the opposite, to actively allow inheritance for selected tags,
3593 see the variable `org-use-tag-inheritance'."
3594 :group 'org-tags
3595 :type '(repeat (string :tag "Tag")))
3597 (defun org-tag-inherit-p (tag)
3598 "Check if TAG is one that should be inherited."
3599 (cond
3600 ((member tag org-tags-exclude-from-inheritance) nil)
3601 ((eq org-use-tag-inheritance t) t)
3602 ((not org-use-tag-inheritance) nil)
3603 ((stringp org-use-tag-inheritance)
3604 (string-match org-use-tag-inheritance tag))
3605 ((listp org-use-tag-inheritance)
3606 (member tag org-use-tag-inheritance))
3607 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3609 (defcustom org-tags-match-list-sublevels t
3610 "Non-nil means list also sublevels of headlines matching a search.
3611 This variable applies to tags/property searches, and also to stuck
3612 projects because this search is based on a tags match as well.
3614 When set to the symbol `indented', sublevels are indented with
3615 leading dots.
3617 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3618 the sublevels of a headline matching a tag search often also match
3619 the same search. Listing all of them can create very long lists.
3620 Setting this variable to nil causes subtrees of a match to be skipped.
3622 This variable is semi-obsolete and probably should always be true. It
3623 is better to limit inheritance to certain tags using the variables
3624 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3625 :group 'org-tags
3626 :type '(choice
3627 (const :tag "No, don't list them" nil)
3628 (const :tag "Yes, do list them" t)
3629 (const :tag "List them, indented with leading dots" indented)))
3631 (defcustom org-tags-sort-function nil
3632 "When set, tags are sorted using this function as a comparator."
3633 :group 'org-tags
3634 :type '(choice
3635 (const :tag "No sorting" nil)
3636 (const :tag "Alphabetical" string<)
3637 (const :tag "Reverse alphabetical" string>)
3638 (function :tag "Custom function" nil)))
3640 (defvar org-tags-history nil
3641 "History of minibuffer reads for tags.")
3642 (defvar org-last-tags-completion-table nil
3643 "The last used completion table for tags.")
3644 (defvar org-after-tags-change-hook nil
3645 "Hook that is run after the tags in a line have changed.")
3647 (defgroup org-properties nil
3648 "Options concerning properties in Org mode."
3649 :tag "Org Properties"
3650 :group 'org)
3652 (defcustom org-property-format "%-10s %s"
3653 "How property key/value pairs should be formatted by `indent-line'.
3654 When `indent-line' hits a property definition, it will format the line
3655 according to this format, mainly to make sure that the values are
3656 lined-up with respect to each other."
3657 :group 'org-properties
3658 :type 'string)
3660 (defcustom org-properties-postprocess-alist nil
3661 "Alist of properties and functions to adjust inserted values.
3662 Elements of this alist must be of the form
3664 ([string] [function])
3666 where [string] must be a property name and [function] must be a
3667 lambda expression: this lambda expression must take one argument,
3668 the value to adjust, and return the new value as a string.
3670 For example, this element will allow the property \"Remaining\"
3671 to be updated wrt the relation between the \"Effort\" property
3672 and the clock summary:
3674 ((\"Remaining\" (lambda(value)
3675 (let ((clocksum (org-clock-sum-current-item))
3676 (effort (org-duration-to-minutes
3677 (org-entry-get (point) \"Effort\"))))
3678 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3679 :group 'org-properties
3680 :version "24.1"
3681 :type '(alist :key-type (string :tag "Property")
3682 :value-type (function :tag "Function")))
3684 (defcustom org-use-property-inheritance nil
3685 "Non-nil means properties apply also for sublevels.
3687 This setting is chiefly used during property searches. Turning it on can
3688 cause significant overhead when doing a search, which is why it is not
3689 on by default.
3691 When nil, only the properties directly given in the current entry count.
3692 When t, every property is inherited. The value may also be a list of
3693 properties that should have inheritance, or a regular expression matching
3694 properties that should be inherited.
3696 However, note that some special properties use inheritance under special
3697 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3698 and the properties ending in \"_ALL\" when they are used as descriptor
3699 for valid values of a property.
3701 Note for programmers:
3702 When querying an entry with `org-entry-get', you can control if inheritance
3703 should be used. By default, `org-entry-get' looks only at the local
3704 properties. You can request inheritance by setting the inherit argument
3705 to t (to force inheritance) or to `selective' (to respect the setting
3706 in this variable)."
3707 :group 'org-properties
3708 :type '(choice
3709 (const :tag "Not" nil)
3710 (const :tag "Always" t)
3711 (repeat :tag "Specific properties" (string :tag "Property"))
3712 (regexp :tag "Properties matched by regexp")))
3714 (defun org-property-inherit-p (property)
3715 "Return a non-nil value if PROPERTY should be inherited."
3716 (cond
3717 ((eq org-use-property-inheritance t) t)
3718 ((not org-use-property-inheritance) nil)
3719 ((stringp org-use-property-inheritance)
3720 (string-match org-use-property-inheritance property))
3721 ((listp org-use-property-inheritance)
3722 (member-ignore-case property org-use-property-inheritance))
3723 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3725 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3726 "The default column format, if no other format has been defined.
3727 This variable can be set on the per-file basis by inserting a line
3729 #+COLUMNS: %25ITEM ....."
3730 :group 'org-properties
3731 :type 'string)
3733 (defcustom org-columns-ellipses ".."
3734 "The ellipses to be used when a field in column view is truncated.
3735 When this is the empty string, as many characters as possible are shown,
3736 but then there will be no visual indication that the field has been truncated.
3737 When this is a string of length N, the last N characters of a truncated
3738 field are replaced by this string. If the column is narrower than the
3739 ellipses string, only part of the ellipses string will be shown."
3740 :group 'org-properties
3741 :type 'string)
3743 (defconst org-global-properties-fixed
3744 '(("VISIBILITY_ALL" . "folded children content all")
3745 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3746 "List of property/value pairs that can be inherited by any entry.
3748 These are fixed values, for the preset properties. The user variable
3749 that can be used to add to this list is `org-global-properties'.
3751 The entries in this list are cons cells where the car is a property
3752 name and cdr is a string with the value. If the value represents
3753 multiple items like an \"_ALL\" property, separate the items by
3754 spaces.")
3756 (defcustom org-global-properties nil
3757 "List of property/value pairs that can be inherited by any entry.
3759 This list will be combined with the constant `org-global-properties-fixed'.
3761 The entries in this list are cons cells where the car is a property
3762 name and cdr is a string with the value.
3764 You can set buffer-local values for the same purpose in the variable
3765 `org-file-properties' this by adding lines like
3767 #+PROPERTY: NAME VALUE"
3768 :group 'org-properties
3769 :type '(repeat
3770 (cons (string :tag "Property")
3771 (string :tag "Value"))))
3773 (defvar-local org-file-properties nil
3774 "List of property/value pairs that can be inherited by any entry.
3775 Valid for the current buffer.
3776 This variable is populated from #+PROPERTY lines.")
3778 (defgroup org-agenda nil
3779 "Options concerning agenda views in Org mode."
3780 :tag "Org Agenda"
3781 :group 'org)
3783 (defvar-local org-category nil
3784 "Variable used by org files to set a category for agenda display.
3785 Such files should use a file variable to set it, for example
3787 # -*- mode: org; org-category: \"ELisp\"
3789 or contain a special line
3791 #+CATEGORY: ELisp
3793 If the file does not specify a category, then file's base name
3794 is used instead.")
3795 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3797 (defcustom org-agenda-files nil
3798 "The files to be used for agenda display.
3800 If an entry is a directory, all files in that directory that are matched
3801 by `org-agenda-file-regexp' will be part of the file list.
3803 If the value of the variable is not a list but a single file name, then
3804 the list of agenda files is actually stored and maintained in that file,
3805 one agenda file per line. In this file paths can be given relative to
3806 `org-directory'. Tilde expansion and environment variable substitution
3807 are also made.
3809 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3810 and removed with `\\[org-remove-file]'."
3811 :group 'org-agenda
3812 :type '(choice
3813 (repeat :tag "List of files and directories" file)
3814 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3816 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3817 "Regular expression to match files for `org-agenda-files'.
3818 If any element in the list in that variable contains a directory instead
3819 of a normal file, all files in that directory that are matched by this
3820 regular expression will be included."
3821 :group 'org-agenda
3822 :type 'regexp)
3824 (defcustom org-agenda-text-search-extra-files nil
3825 "List of extra files to be searched by text search commands.
3826 These files will be searched in addition to the agenda files by the
3827 commands `org-search-view' (`\\[org-agenda] s') \
3828 and `org-occur-in-agenda-files'.
3829 Note that these files will only be searched for text search commands,
3830 not for the other agenda views like todo lists, tag searches or the weekly
3831 agenda. This variable is intended to list notes and possibly archive files
3832 that should also be searched by these two commands.
3833 In fact, if the first element in the list is the symbol `agenda-archives',
3834 then all archive files of all agenda files will be added to the search
3835 scope."
3836 :group 'org-agenda
3837 :type '(set :greedy t
3838 (const :tag "Agenda Archives" agenda-archives)
3839 (repeat :inline t (file))))
3841 (defvaralias 'org-agenda-multi-occur-extra-files
3842 'org-agenda-text-search-extra-files)
3844 (defcustom org-agenda-skip-unavailable-files nil
3845 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3846 A nil value means to remove them, after a query, from the list."
3847 :group 'org-agenda
3848 :type 'boolean)
3850 (defcustom org-calendar-to-agenda-key [?c]
3851 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3852 The command `org-calendar-goto-agenda' will be bound to this key. The
3853 default is the character `c' because then `c' can be used to switch back and
3854 forth between agenda and calendar."
3855 :group 'org-agenda
3856 :type 'sexp)
3858 (defcustom org-calendar-insert-diary-entry-key [?i]
3859 "The key to be installed in `calendar-mode-map' for adding diary entries.
3860 This option is irrelevant until `org-agenda-diary-file' has been configured
3861 to point to an Org file. When that is the case, the command
3862 `org-agenda-diary-entry' will be bound to the key given here, by default
3863 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3864 if you want to continue doing this, you need to change this to a different
3865 key."
3866 :group 'org-agenda
3867 :type 'sexp)
3869 (defcustom org-agenda-diary-file 'diary-file
3870 "File to which to add new entries with the `i' key in agenda and calendar.
3871 When this is the symbol `diary-file', the functionality in the Emacs
3872 calendar will be used to add entries to the `diary-file'. But when this
3873 points to a file, `org-agenda-diary-entry' will be used instead."
3874 :group 'org-agenda
3875 :type '(choice
3876 (const :tag "The standard Emacs diary file" diary-file)
3877 (file :tag "Special Org file diary entries")))
3879 (eval-after-load "calendar"
3880 '(progn
3881 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3882 'org-calendar-goto-agenda)
3883 (add-hook 'calendar-mode-hook
3884 (lambda ()
3885 (unless (eq org-agenda-diary-file 'diary-file)
3886 (define-key calendar-mode-map
3887 org-calendar-insert-diary-entry-key
3888 'org-agenda-diary-entry))))))
3890 (defgroup org-latex nil
3891 "Options for embedding LaTeX code into Org mode."
3892 :tag "Org LaTeX"
3893 :group 'org)
3895 (defcustom org-format-latex-options
3896 '(:foreground default :background default :scale 1.0
3897 :html-foreground "Black" :html-background "Transparent"
3898 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3899 "Options for creating images from LaTeX fragments.
3900 This is a property list with the following properties:
3901 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3902 `default' means use the foreground of the default face.
3903 `auto' means use the foreground from the text face.
3904 :background the background color, or \"Transparent\".
3905 `default' means use the background of the default face.
3906 `auto' means use the background from the text face.
3907 :scale a scaling factor for the size of the images, to get more pixels
3908 :html-foreground, :html-background, :html-scale
3909 the same numbers for HTML export.
3910 :matchers a list indicating which matchers should be used to
3911 find LaTeX fragments. Valid members of this list are:
3912 \"begin\" find environments
3913 \"$1\" find single characters surrounded by $.$
3914 \"$\" find math expressions surrounded by $...$
3915 \"$$\" find math expressions surrounded by $$....$$
3916 \"\\(\" find math expressions surrounded by \\(...\\)
3917 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3918 :group 'org-latex
3919 :type 'plist)
3921 (defcustom org-format-latex-signal-error t
3922 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3923 When nil, just push out a message."
3924 :group 'org-latex
3925 :version "24.1"
3926 :type 'boolean)
3928 (defcustom org-latex-to-mathml-jar-file nil
3929 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3930 Use this to specify additional executable file say a jar file.
3932 When using MathToWeb as the converter, specify the full-path to
3933 your mathtoweb.jar file."
3934 :group 'org-latex
3935 :version "24.1"
3936 :type '(choice
3937 (const :tag "None" nil)
3938 (file :tag "JAR file" :must-match t)))
3940 (defcustom org-latex-to-mathml-convert-command nil
3941 "Command to convert LaTeX fragments to MathML.
3942 Replace format-specifiers in the command as noted below and use
3943 `shell-command' to convert LaTeX to MathML.
3944 %j: Executable file in fully expanded form as specified by
3945 `org-latex-to-mathml-jar-file'.
3946 %I: Input LaTeX file in fully expanded form.
3947 %i: The latex fragment to be converted.
3948 %o: Output MathML file.
3950 This command is used by `org-create-math-formula'.
3952 When using MathToWeb as the converter, set this option to
3953 \"java -jar %j -unicode -force -df %o %I\".
3955 When using LaTeXML set this option to
3956 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3957 :group 'org-latex
3958 :version "24.1"
3959 :type '(choice
3960 (const :tag "None" nil)
3961 (string :tag "\nShell command")))
3963 (defcustom org-preview-latex-default-process 'dvipng
3964 "The default process to convert LaTeX fragments to image files.
3965 All available processes and theirs documents can be found in
3966 `org-preview-latex-process-alist', which see."
3967 :group 'org-latex
3968 :version "26.1"
3969 :package-version '(Org . "9.0")
3970 :type 'symbol)
3972 (defcustom org-preview-latex-process-alist
3973 '((dvipng
3974 :programs ("latex" "dvipng")
3975 :description "dvi > png"
3976 :message "you need to install the programs: latex and dvipng."
3977 :image-input-type "dvi"
3978 :image-output-type "png"
3979 :image-size-adjust (1.0 . 1.0)
3980 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3981 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3982 (dvisvgm
3983 :programs ("latex" "dvisvgm")
3984 :description "dvi > svg"
3985 :message "you need to install the programs: latex and dvisvgm."
3986 :use-xcolor t
3987 :image-input-type "dvi"
3988 :image-output-type "svg"
3989 :image-size-adjust (1.7 . 1.5)
3990 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3991 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3992 (imagemagick
3993 :programs ("latex" "convert")
3994 :description "pdf > png"
3995 :message "you need to install the programs: latex and imagemagick."
3996 :use-xcolor t
3997 :image-input-type "pdf"
3998 :image-output-type "png"
3999 :image-size-adjust (1.0 . 1.0)
4000 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4001 :image-converter
4002 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4003 "Definitions of external processes for LaTeX previewing.
4004 Org mode can use some external commands to generate TeX snippet's images for
4005 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4006 `org-create-formula-image' how to call them.
4008 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4009 PROPERTIES accepts the following attributes:
4011 :programs list of strings, required programs.
4012 :description string, describe the process.
4013 :message string, message it when required programs cannot be found.
4014 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4015 :image-output-type string, output file type of image converter (e.g., \"png\").
4016 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4017 deal with background and foreground color of image.
4018 Otherwise, dvipng style background and foregroud color
4019 format are generated. You may then refer to them in
4020 command options with \"%F\" and \"%B\".
4021 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4022 image size showed in buffer and the cdr element is for
4023 HTML file. This option is only useful for process
4024 developers, users should use variable
4025 `org-format-latex-options' instead.
4026 :post-clean list of strings, files matched are to be cleaned up once
4027 the image is generated. When nil, the files with \".dvi\",
4028 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4029 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4030 be cleaned up.
4031 :latex-header list of strings, the LaTeX header of the snippet file.
4032 When nil, the fallback value is used instead, which is
4033 controlled by `org-format-latex-header',
4034 `org-latex-default-packages-alist' and
4035 `org-latex-packages-alist', which see.
4036 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4037 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4038 replaced with values defined below.
4039 :image-converter list of image converter commands strings. Each of them is
4040 given to the shell and supports any of the following
4041 place-holders defined below.
4043 Place-holders used by `:image-converter' and `:latex-compiler':
4045 %f input file name
4046 %b base name of input file
4047 %o base directory of input file
4048 %O absolute output file name
4050 Place-holders only used by `:image-converter':
4052 %F foreground of image
4053 %B background of image
4054 %D dpi, which is used to adjust image size by some processing commands.
4055 %S the image size scale ratio, which is used to adjust image size by some
4056 processing commands."
4057 :group 'org-latex
4058 :version "26.1"
4059 :package-version '(Org . "9.0")
4060 :type '(alist :tag "LaTeX to image backends"
4061 :value-type (plist)))
4063 (defcustom org-preview-latex-image-directory "ltximg/"
4064 "Path to store latex preview images.
4065 A relative path here creates many directories relative to the
4066 processed org files paths. An absolute path puts all preview
4067 images at the same place."
4068 :group 'org-latex
4069 :version "26.1"
4070 :package-version '(Org . "9.0")
4071 :type 'string)
4073 (defun org-format-latex-mathml-available-p ()
4074 "Return t if `org-latex-to-mathml-convert-command' is usable."
4075 (save-match-data
4076 (when (and (boundp 'org-latex-to-mathml-convert-command)
4077 org-latex-to-mathml-convert-command)
4078 (let ((executable (car (split-string
4079 org-latex-to-mathml-convert-command))))
4080 (when (executable-find executable)
4081 (if (string-match
4082 "%j" org-latex-to-mathml-convert-command)
4083 (file-readable-p org-latex-to-mathml-jar-file)
4084 t))))))
4086 (defcustom org-format-latex-header "\\documentclass{article}
4087 \\usepackage[usenames]{color}
4088 \[PACKAGES]
4089 \[DEFAULT-PACKAGES]
4090 \\pagestyle{empty} % do not remove
4091 % The settings below are copied from fullpage.sty
4092 \\setlength{\\textwidth}{\\paperwidth}
4093 \\addtolength{\\textwidth}{-3cm}
4094 \\setlength{\\oddsidemargin}{1.5cm}
4095 \\addtolength{\\oddsidemargin}{-2.54cm}
4096 \\setlength{\\evensidemargin}{\\oddsidemargin}
4097 \\setlength{\\textheight}{\\paperheight}
4098 \\addtolength{\\textheight}{-\\headheight}
4099 \\addtolength{\\textheight}{-\\headsep}
4100 \\addtolength{\\textheight}{-\\footskip}
4101 \\addtolength{\\textheight}{-3cm}
4102 \\setlength{\\topmargin}{1.5cm}
4103 \\addtolength{\\topmargin}{-2.54cm}"
4104 "The document header used for processing LaTeX fragments.
4105 It is imperative that this header make sure that no page number
4106 appears on the page. The package defined in the variables
4107 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4108 will either replace the placeholder \"[PACKAGES]\" in this
4109 header, or they will be appended."
4110 :group 'org-latex
4111 :type 'string)
4113 (defun org-set-packages-alist (var val)
4114 "Set the packages alist and make sure it has 3 elements per entry."
4115 (set var (mapcar (lambda (x)
4116 (if (and (consp x) (= (length x) 2))
4117 (list (car x) (nth 1 x) t)
4119 val)))
4121 (defun org-get-packages-alist (var)
4122 "Get the packages alist and make sure it has 3 elements per entry."
4123 (mapcar (lambda (x)
4124 (if (and (consp x) (= (length x) 2))
4125 (list (car x) (nth 1 x) t)
4127 (default-value var)))
4129 (defcustom org-latex-default-packages-alist
4130 '(("AUTO" "inputenc" t ("pdflatex"))
4131 ("T1" "fontenc" t ("pdflatex"))
4132 ("" "graphicx" t)
4133 ("" "grffile" t)
4134 ("" "longtable" nil)
4135 ("" "wrapfig" nil)
4136 ("" "rotating" nil)
4137 ("normalem" "ulem" t)
4138 ("" "amsmath" t)
4139 ("" "textcomp" t)
4140 ("" "amssymb" t)
4141 ("" "capt-of" nil)
4142 ("" "hyperref" nil))
4143 "Alist of default packages to be inserted in the header.
4145 Change this only if one of the packages here causes an
4146 incompatibility with another package you are using.
4148 The packages in this list are needed by one part or another of
4149 Org mode to function properly:
4151 - inputenc, fontenc: for basic font and character selection
4152 - graphicx: for including images
4153 - grffile: allow periods and spaces in graphics file names
4154 - longtable: For multipage tables
4155 - wrapfig: for figure placement
4156 - rotating: for sideways figures and tables
4157 - ulem: for underline and strike-through
4158 - amsmath: for subscript and superscript and math environments
4159 - textcomp, amssymb: for various symbols used
4160 for interpreting the entities in `org-entities'. You can skip
4161 some of these packages if you don't use any of their symbols.
4162 - capt-of: for captions outside of floats
4163 - hyperref: for cross references
4165 Therefore you should not modify this variable unless you know
4166 what you are doing. The one reason to change it anyway is that
4167 you might be loading some other package that conflicts with one
4168 of the default packages. Each element is either a cell or
4169 a string.
4171 A cell is of the format
4173 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4175 If SNIPPET-FLAG is non-nil, the package also needs to be included
4176 when compiling LaTeX snippets into images for inclusion into
4177 non-LaTeX output. COMPILERS is a list of compilers that should
4178 include the package, see `org-latex-compiler'. If the document
4179 compiler is not in the list, and the list is non-nil, the package
4180 will not be inserted in the final document.
4182 A string will be inserted as-is in the header of the document."
4183 :group 'org-latex
4184 :group 'org-export-latex
4185 :set 'org-set-packages-alist
4186 :get 'org-get-packages-alist
4187 :version "26.1"
4188 :package-version '(Org . "8.3")
4189 :type '(repeat
4190 (choice
4191 (list :tag "options/package pair"
4192 (string :tag "options")
4193 (string :tag "package")
4194 (boolean :tag "Snippet"))
4195 (string :tag "A line of LaTeX"))))
4197 (defcustom org-latex-packages-alist nil
4198 "Alist of packages to be inserted in every LaTeX header.
4200 These will be inserted after `org-latex-default-packages-alist'.
4201 Each element is either a cell or a string.
4203 A cell is of the format:
4205 (\"options\" \"package\" SNIPPET-FLAG)
4207 SNIPPET-FLAG, when non-nil, indicates that this package is also
4208 needed when turning LaTeX snippets into images for inclusion into
4209 non-LaTeX output.
4211 A string will be inserted as-is in the header of the document.
4213 Make sure that you only list packages here which:
4215 - you want in every file;
4216 - do not conflict with the setup in `org-format-latex-header';
4217 - do not conflict with the default packages in
4218 `org-latex-default-packages-alist'."
4219 :group 'org-latex
4220 :group 'org-export-latex
4221 :set 'org-set-packages-alist
4222 :get 'org-get-packages-alist
4223 :type '(repeat
4224 (choice
4225 (list :tag "options/package pair"
4226 (string :tag "options")
4227 (string :tag "package")
4228 (boolean :tag "Snippet"))
4229 (string :tag "A line of LaTeX"))))
4231 (defgroup org-appearance nil
4232 "Settings for Org mode appearance."
4233 :tag "Org Appearance"
4234 :group 'org)
4236 (defcustom org-level-color-stars-only nil
4237 "Non-nil means fontify only the stars in each headline.
4238 When nil, the entire headline is fontified.
4239 Changing it requires restart of `font-lock-mode' to become effective
4240 also in regions already fontified."
4241 :group 'org-appearance
4242 :type 'boolean)
4244 (defcustom org-hide-leading-stars nil
4245 "Non-nil means hide the first N-1 stars in a headline.
4246 This works by using the face `org-hide' for these stars. This
4247 face is white for a light background, and black for a dark
4248 background. You may have to customize the face `org-hide' to
4249 make this work.
4250 Changing it requires restart of `font-lock-mode' to become effective
4251 also in regions already fontified.
4252 You may also set this on a per-file basis by adding one of the following
4253 lines to the buffer:
4255 #+STARTUP: hidestars
4256 #+STARTUP: showstars"
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-hidden-keywords nil
4261 "List of symbols corresponding to keywords to be hidden the org buffer.
4262 For example, a value \\='(title) for this list will make the document's title
4263 appear in the buffer without the initial #+TITLE: keyword."
4264 :group 'org-appearance
4265 :version "24.1"
4266 :type '(set (const :tag "#+AUTHOR" author)
4267 (const :tag "#+DATE" date)
4268 (const :tag "#+EMAIL" email)
4269 (const :tag "#+TITLE" title)))
4271 (defcustom org-custom-properties nil
4272 "List of properties (as strings) with a special meaning.
4273 The default use of these custom properties is to let the user
4274 hide them with `org-toggle-custom-properties-visibility'."
4275 :group 'org-properties
4276 :group 'org-appearance
4277 :version "24.3"
4278 :type '(repeat (string :tag "Property Name")))
4280 (defcustom org-fontify-done-headline nil
4281 "Non-nil means change the face of a headline if it is marked DONE.
4282 Normally, only the TODO/DONE keyword indicates the state of a headline.
4283 When this is non-nil, the headline after the keyword is set to the
4284 `org-headline-done' as an additional indication."
4285 :group 'org-appearance
4286 :type 'boolean)
4288 (defcustom org-fontify-emphasized-text t
4289 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4290 Changing this variable requires a restart of Emacs to take effect."
4291 :group 'org-appearance
4292 :type 'boolean)
4294 (defcustom org-fontify-whole-heading-line nil
4295 "Non-nil means fontify the whole line for headings.
4296 This is useful when setting a background color for the
4297 org-level-* faces."
4298 :group 'org-appearance
4299 :type 'boolean)
4301 (defcustom org-highlight-latex-and-related nil
4302 "Non-nil means highlight LaTeX related syntax in the buffer.
4303 When non nil, the value should be a list containing any of the
4304 following symbols:
4305 `latex' Highlight LaTeX snippets and environments.
4306 `script' Highlight subscript and superscript.
4307 `entities' Highlight entities."
4308 :group 'org-appearance
4309 :version "24.4"
4310 :package-version '(Org . "8.0")
4311 :type '(choice
4312 (const :tag "No highlighting" nil)
4313 (set :greedy t :tag "Highlight"
4314 (const :tag "LaTeX snippets and environments" latex)
4315 (const :tag "Subscript and superscript" script)
4316 (const :tag "Entities" entities))))
4318 (defcustom org-hide-emphasis-markers nil
4319 "Non-nil mean font-lock should hide the emphasis marker characters."
4320 :group 'org-appearance
4321 :type 'boolean)
4323 (defcustom org-hide-macro-markers nil
4324 "Non-nil mean font-lock should hide the brackets marking macro calls."
4325 :group 'org-appearance
4326 :type 'boolean)
4328 (defcustom org-pretty-entities nil
4329 "Non-nil means show entities as UTF8 characters.
4330 When nil, the \\name form remains in the buffer."
4331 :group 'org-appearance
4332 :version "24.1"
4333 :type 'boolean)
4335 (defcustom org-pretty-entities-include-sub-superscripts t
4336 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4337 :group 'org-appearance
4338 :version "24.1"
4339 :type 'boolean)
4341 (defvar org-emph-re nil
4342 "Regular expression for matching emphasis.
4343 After a match, the match groups contain these elements:
4344 0 The match of the full regular expression, including the characters
4345 before and after the proper match
4346 1 The character before the proper match, or empty at beginning of line
4347 2 The proper match, including the leading and trailing markers
4348 3 The leading marker like * or /, indicating the type of highlighting
4349 4 The text between the emphasis markers, not including the markers
4350 5 The character after the match, empty at the end of a line")
4352 (defvar org-verbatim-re nil
4353 "Regular expression for matching verbatim text.")
4355 (defvar org-emphasis-regexp-components) ; defined just below
4356 (defvar org-emphasis-alist) ; defined just below
4357 (defun org-set-emph-re (var val)
4358 "Set variable and compute the emphasis regular expression."
4359 (set var val)
4360 (when (and (boundp 'org-emphasis-alist)
4361 (boundp 'org-emphasis-regexp-components)
4362 org-emphasis-alist org-emphasis-regexp-components)
4363 (pcase-let*
4364 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4365 (body (if (<= nl 0) body
4366 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4367 (template
4368 (format (concat "\\([%s]\\|^\\)" ;before markers
4369 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4370 "\\([%s]\\|$\\)") ;after markers
4371 pre border border body border post)))
4372 (setq org-emph-re (format template "*/_+"))
4373 (setq org-verbatim-re (format template "=~")))))
4375 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4376 ;; set this option proved cumbersome. See this message/thread:
4377 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4378 (defvar org-emphasis-regexp-components
4379 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4380 "Components used to build the regular expression for emphasis.
4381 This is a list with five entries. Terminology: In an emphasis string
4382 like \" *strong word* \", we call the initial space PREMATCH, the final
4383 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4384 and \"trong wor\" is the body. The different components in this variable
4385 specify what is allowed/forbidden in each part:
4387 pre Chars allowed as prematch. Beginning of line will be allowed too.
4388 post Chars allowed as postmatch. End of line will be allowed too.
4389 border The chars *forbidden* as border characters.
4390 body-regexp A regexp like \".\" to match a body character. Don't use
4391 non-shy groups here, and don't allow newline here.
4392 newline The maximum number of newlines allowed in an emphasis exp.
4394 You need to reload Org or to restart Emacs after customizing this.")
4396 (defcustom org-emphasis-alist
4397 '(("*" bold)
4398 ("/" italic)
4399 ("_" underline)
4400 ("=" org-verbatim verbatim)
4401 ("~" org-code verbatim)
4402 ("+" (:strike-through t)))
4403 "Alist of characters and faces to emphasize text.
4404 Text starting and ending with a special character will be emphasized,
4405 for example *bold*, _underlined_ and /italic/. This variable sets the
4406 marker characters and the face to be used by font-lock for highlighting
4407 in Org buffers.
4409 You need to reload Org or to restart Emacs after customizing this."
4410 :group 'org-appearance
4411 :set 'org-set-emph-re
4412 :version "24.4"
4413 :package-version '(Org . "8.0")
4414 :type '(repeat
4415 (list
4416 (string :tag "Marker character")
4417 (choice
4418 (face :tag "Font-lock-face")
4419 (plist :tag "Face property list"))
4420 (option (const verbatim)))))
4422 (defvar org-protecting-blocks '("src" "example" "export")
4423 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4424 This is needed for font-lock setup.")
4426 ;;; Functions and variables from their packages
4427 ;; Declared here to avoid compiler warnings
4428 (defvar mark-active)
4430 ;; Various packages
4431 (declare-function calc-eval "calc" (str &optional separator &rest args))
4432 (declare-function calendar-forward-day "cal-move" (arg))
4433 (declare-function calendar-goto-date "cal-move" (date))
4434 (declare-function calendar-goto-today "cal-move" ())
4435 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4436 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4437 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4438 (declare-function cdlatex-tab "ext:cdlatex" ())
4439 (declare-function dired-get-filename
4440 "dired"
4441 (&optional localp no-error-if-not-filep))
4442 (declare-function iswitchb-read-buffer
4443 "iswitchb"
4444 (prompt &optional
4445 default require-match _predicate start matches-set))
4446 (declare-function org-agenda-change-all-lines
4447 "org-agenda"
4448 (newhead hdmarker &optional fixface just-this))
4449 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4450 "org-agenda"
4451 (&optional end))
4452 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4453 (declare-function org-agenda-format-item
4454 "org-agenda"
4455 (extra txt &optional level category tags dotime
4456 remove-re habitp))
4457 (declare-function org-agenda-maybe-redo "org-agenda" ())
4458 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4459 (declare-function org-agenda-save-markers-for-cut-and-paste
4460 "org-agenda"
4461 (beg end))
4462 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4463 (declare-function org-agenda-skip "org-agenda" ())
4464 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4465 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4466 (declare-function org-indent-mode "org-indent" (&optional arg))
4467 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4468 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4469 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4470 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4471 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4472 (declare-function parse-time-string "parse-time" (string))
4473 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4475 (defvar align-mode-rules-list)
4476 (defvar calc-embedded-close-formula)
4477 (defvar calc-embedded-open-formula)
4478 (defvar calc-embedded-open-mode)
4479 (defvar font-lock-unfontify-region-function)
4480 (defvar iswitchb-temp-buflist)
4481 (defvar org-agenda-tags-todo-honor-ignore-options)
4482 (defvar remember-data-file)
4483 (defvar texmathp-why)
4485 ;;;###autoload
4486 (defun turn-on-orgtbl ()
4487 "Unconditionally turn on `orgtbl-mode'."
4488 (require 'org-table)
4489 (orgtbl-mode 1))
4491 (defun org-at-table-p (&optional table-type)
4492 "Non-nil if the cursor is inside an Org table.
4493 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4494 If `org-enable-table-editor' is nil, return nil unconditionally."
4495 (and
4496 org-enable-table-editor
4497 (save-excursion
4498 (beginning-of-line)
4499 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4500 (or (not (derived-mode-p 'org-mode))
4501 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4502 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4504 (defun org-at-table.el-p ()
4505 "Non-nil when point is at a table.el table."
4506 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4507 (let ((element (org-element-at-point)))
4508 (and (eq (org-element-type element) 'table)
4509 (eq (org-element-property :type element) 'table.el)))))
4511 (defun org-at-table-hline-p ()
4512 "Non-nil when point is inside a hline in a table.
4513 Assume point is already in a table. If `org-enable-table-editor'
4514 is nil, return nil unconditionally."
4515 (and org-enable-table-editor
4516 (save-excursion
4517 (beginning-of-line)
4518 (looking-at org-table-hline-regexp))))
4520 (defun org-table-map-tables (function &optional quietly)
4521 "Apply FUNCTION to the start of all tables in the buffer."
4522 (org-with-wide-buffer
4523 (goto-char (point-min))
4524 (while (re-search-forward org-table-any-line-regexp nil t)
4525 (unless quietly
4526 (message "Mapping tables: %d%%"
4527 (floor (* 100.0 (point)) (buffer-size))))
4528 (beginning-of-line 1)
4529 (when (and (looking-at org-table-line-regexp)
4530 ;; Exclude tables in src/example/verbatim/clocktable blocks
4531 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4532 (save-excursion (funcall function))
4533 (or (looking-at org-table-line-regexp)
4534 (forward-char 1)))
4535 (re-search-forward org-table-any-border-regexp nil 1)))
4536 (unless quietly (message "Mapping tables: done")))
4538 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4539 (declare-function org-clock-update-mode-line "org-clock" ())
4540 (declare-function org-resolve-clocks "org-clock"
4541 (&optional also-non-dangling-p prompt last-valid))
4543 (defun org-at-TBLFM-p (&optional pos)
4544 "Non-nil when point (or POS) is in #+TBLFM line."
4545 (save-excursion
4546 (goto-char (or pos (point)))
4547 (beginning-of-line)
4548 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4549 (eq (org-element-type (org-element-at-point)) 'table))))
4551 (defvar org-clock-start-time)
4552 (defvar org-clock-marker (make-marker)
4553 "Marker recording the last clock-in.")
4554 (defvar org-clock-hd-marker (make-marker)
4555 "Marker recording the last clock-in, but the headline position.")
4556 (defvar org-clock-heading ""
4557 "The heading of the current clock entry.")
4558 (defun org-clock-is-active ()
4559 "Return the buffer where the clock is currently running.
4560 Return nil if no clock is running."
4561 (marker-buffer org-clock-marker))
4563 (defun org-check-running-clock ()
4564 "Check if the current buffer contains the running clock.
4565 If yes, offer to stop it and to save the buffer with the changes."
4566 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4567 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4568 (buffer-name))))
4569 (org-clock-out)
4570 (when (y-or-n-p "Save changed buffer?")
4571 (save-buffer))))
4573 (defun org-clocktable-try-shift (dir n)
4574 "Check if this line starts a clock table, if yes, shift the time block."
4575 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4576 (org-clocktable-shift dir n)))
4578 ;;;###autoload
4579 (defun org-clock-persistence-insinuate ()
4580 "Set up hooks for clock persistence."
4581 (require 'org-clock)
4582 (add-hook 'org-mode-hook 'org-clock-load)
4583 (add-hook 'kill-emacs-hook 'org-clock-save))
4585 (defgroup org-archive nil
4586 "Options concerning archiving in Org mode."
4587 :tag "Org Archive"
4588 :group 'org-structure)
4590 (defcustom org-archive-location "%s_archive::"
4591 "The location where subtrees should be archived.
4593 The value of this variable is a string, consisting of two parts,
4594 separated by a double-colon. The first part is a filename and
4595 the second part is a headline.
4597 When the filename is omitted, archiving happens in the same file.
4598 %s in the filename will be replaced by the current file
4599 name (without the directory part). Archiving to a different file
4600 is useful to keep archived entries from contributing to the
4601 Org Agenda.
4603 The archived entries will be filed as subtrees of the specified
4604 headline. When the headline is omitted, the subtrees are simply
4605 filed away at the end of the file, as top-level entries. Also in
4606 the heading you can use %s to represent the file name, this can be
4607 useful when using the same archive for a number of different files.
4609 Here are a few examples:
4610 \"%s_archive::\"
4611 If the current file is Projects.org, archive in file
4612 Projects.org_archive, as top-level trees. This is the default.
4614 \"::* Archived Tasks\"
4615 Archive in the current file, under the top-level headline
4616 \"* Archived Tasks\".
4618 \"~/org/archive.org::\"
4619 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4621 \"~/org/archive.org::* From %s\"
4622 Archive in file ~/org/archive.org (absolute path), under headlines
4623 \"From FILENAME\" where file name is the current file name.
4625 \"~/org/datetree.org::datetree/* Finished Tasks\"
4626 The \"datetree/\" string is special, signifying to archive
4627 items to the datetree. Items are placed in either the CLOSED
4628 date of the item, or the current date if there is no CLOSED date.
4629 The heading will be a subentry to the current date. There doesn't
4630 need to be a heading, but there always needs to be a slash after
4631 datetree. For example, to store archived items directly in the
4632 datetree, use \"~/org/datetree.org::datetree/\".
4634 \"basement::** Finished Tasks\"
4635 Archive in file ./basement (relative path), as level 3 trees
4636 below the level 2 heading \"** Finished Tasks\".
4638 You may set this option on a per-file basis by adding to the buffer a
4639 line like
4641 #+ARCHIVE: basement::** Finished Tasks
4643 You may also define it locally for a subtree by setting an ARCHIVE property
4644 in the entry. If such a property is found in an entry, or anywhere up
4645 the hierarchy, it will be used."
4646 :group 'org-archive
4647 :type 'string)
4649 (defcustom org-agenda-skip-archived-trees t
4650 "Non-nil means the agenda will skip any items located in archived trees.
4651 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4652 variable is no longer recommended, you should leave it at the value t.
4653 Instead, use the key `v' to cycle the archives-mode in the agenda."
4654 :group 'org-archive
4655 :group 'org-agenda-skip
4656 :type 'boolean)
4658 (defcustom org-columns-skip-archived-trees t
4659 "Non-nil means ignore archived trees when creating column view."
4660 :group 'org-archive
4661 :group 'org-properties
4662 :type 'boolean)
4664 (defcustom org-cycle-open-archived-trees nil
4665 "Non-nil means `org-cycle' will open archived trees.
4666 An archived tree is a tree marked with the tag ARCHIVE.
4667 When nil, archived trees will stay folded. You can still open them with
4668 normal outline commands like `show-all', but not with the cycling commands."
4669 :group 'org-archive
4670 :group 'org-cycle
4671 :type 'boolean)
4673 (defcustom org-sparse-tree-open-archived-trees nil
4674 "Non-nil means sparse tree construction shows matches in archived trees.
4675 When nil, matches in these trees are highlighted, but the trees are kept in
4676 collapsed state."
4677 :group 'org-archive
4678 :group 'org-sparse-trees
4679 :type 'boolean)
4681 (defcustom org-sparse-tree-default-date-type nil
4682 "The default date type when building a sparse tree.
4683 When this is nil, a date is a scheduled or a deadline timestamp.
4684 Otherwise, these types are allowed:
4686 all: all timestamps
4687 active: only active timestamps (<...>)
4688 inactive: only inactive timestamps ([...])
4689 scheduled: only scheduled timestamps
4690 deadline: only deadline timestamps"
4691 :type '(choice (const :tag "Scheduled or deadline" nil)
4692 (const :tag "All timestamps" all)
4693 (const :tag "Only active timestamps" active)
4694 (const :tag "Only inactive timestamps" inactive)
4695 (const :tag "Only scheduled timestamps" scheduled)
4696 (const :tag "Only deadline timestamps" deadline)
4697 (const :tag "Only closed timestamps" closed))
4698 :version "26.1"
4699 :package-version '(Org . "8.3")
4700 :group 'org-sparse-trees)
4702 (defun org-cycle-hide-archived-subtrees (state)
4703 "Re-hide all archived subtrees after a visibility state change."
4704 (when (and (not org-cycle-open-archived-trees)
4705 (not (memq state '(overview folded))))
4706 (save-excursion
4707 (let* ((globalp (memq state '(contents all)))
4708 (beg (if globalp (point-min) (point)))
4709 (end (if globalp (point-max) (org-end-of-subtree t))))
4710 (org-hide-archived-subtrees beg end)
4711 (goto-char beg)
4712 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4713 (message "%s" (substitute-command-keys
4714 "Subtree is archived and stays closed. Use \
4715 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4717 (defun org-force-cycle-archived ()
4718 "Cycle subtree even if it is archived."
4719 (interactive)
4720 (setq this-command 'org-cycle)
4721 (let ((org-cycle-open-archived-trees t))
4722 (call-interactively 'org-cycle)))
4724 (defun org-hide-archived-subtrees (beg end)
4725 "Re-hide all archived subtrees after a visibility state change."
4726 (org-with-wide-buffer
4727 (let ((case-fold-search nil)
4728 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4729 (goto-char beg)
4730 ;; Include headline point is currently on.
4731 (beginning-of-line)
4732 (while (and (< (point) end) (re-search-forward re end t))
4733 (when (member org-archive-tag (org-get-tags))
4734 (org-flag-subtree t)
4735 (org-end-of-subtree t))))))
4737 (declare-function outline-end-of-heading "outline" ())
4738 (declare-function outline-flag-region "outline" (from to flag))
4739 (defun org-flag-subtree (flag)
4740 (save-excursion
4741 (org-back-to-heading t)
4742 (outline-end-of-heading)
4743 (outline-flag-region (point)
4744 (progn (org-end-of-subtree t) (point))
4745 flag)))
4747 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4749 ;; Declare Column View Code
4751 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4752 (declare-function org-columns-compute "org-colview" (property))
4754 ;; Declare ID code
4756 (declare-function org-id-store-link "org-id")
4757 (declare-function org-id-locations-load "org-id")
4758 (declare-function org-id-locations-save "org-id")
4759 (defvar org-id-track-globally)
4761 ;;; Variables for pre-computed regular expressions, all buffer local
4763 (defvar-local org-todo-regexp nil
4764 "Matches any of the TODO state keywords.
4765 Since TODO keywords are case-sensitive, `case-fold-search' is
4766 expected to be bound to nil when matching against this regexp.")
4768 (defvar-local org-not-done-regexp nil
4769 "Matches any of the TODO state keywords except the last one.
4770 Since TODO keywords are case-sensitive, `case-fold-search' is
4771 expected to be bound to nil when matching against this regexp.")
4773 (defvar-local org-not-done-heading-regexp nil
4774 "Matches a TODO headline that is not done.
4775 Since TODO keywords are case-sensitive, `case-fold-search' is
4776 expected to be bound to nil when matching against this regexp.")
4778 (defvar-local org-todo-line-regexp nil
4779 "Matches a headline and puts TODO state into group 2 if present.
4780 Since TODO keywords are case-sensitive, `case-fold-search' is
4781 expected to be bound to nil when matching against this regexp.")
4783 (defvar-local org-complex-heading-regexp nil
4784 "Matches a headline and puts everything into groups:
4786 group 1: Stars
4787 group 2: The TODO keyword, maybe
4788 group 3: Priority cookie
4789 group 4: True headline
4790 group 5: Tags
4792 Since TODO keywords are case-sensitive, `case-fold-search' is
4793 expected to be bound to nil when matching against this regexp.")
4795 (defvar-local org-complex-heading-regexp-format nil
4796 "Printf format to make regexp to match an exact headline.
4797 This regexp will match the headline of any node which has the
4798 exact headline text that is put into the format, but may have any
4799 TODO state, priority and tags.")
4801 (defvar-local org-todo-line-tags-regexp nil
4802 "Matches a headline and puts TODO state into group 2 if present.
4803 Also put tags into group 4 if tags are present.")
4805 (defconst org-plain-time-of-day-regexp
4806 (concat
4807 "\\(\\<[012]?[0-9]"
4808 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4809 "\\(--?"
4810 "\\(\\<[012]?[0-9]"
4811 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4812 "\\)?")
4813 "Regular expression to match a plain time or time range.
4814 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4815 groups carry important information:
4816 0 the full match
4817 1 the first time, range or not
4818 8 the second time, if it is a range.")
4820 (defconst org-plain-time-extension-regexp
4821 (concat
4822 "\\(\\<[012]?[0-9]"
4823 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4824 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4825 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4826 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4827 groups carry important information:
4828 0 the full match
4829 7 hours of duration
4830 9 minutes of duration")
4832 (defconst org-stamp-time-of-day-regexp
4833 (concat
4834 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4835 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4836 "\\(--?"
4837 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4838 "Regular expression to match a timestamp time or time range.
4839 After a match, the following groups carry important information:
4840 0 the full match
4841 1 date plus weekday, for back referencing to make sure both times are on the same day
4842 2 the first time, range or not
4843 4 the second time, if it is a range.")
4845 (defconst org-startup-options
4846 '(("fold" org-startup-folded t)
4847 ("overview" org-startup-folded t)
4848 ("nofold" org-startup-folded nil)
4849 ("showall" org-startup-folded nil)
4850 ("showeverything" org-startup-folded showeverything)
4851 ("content" org-startup-folded content)
4852 ("indent" org-startup-indented t)
4853 ("noindent" org-startup-indented nil)
4854 ("hidestars" org-hide-leading-stars t)
4855 ("showstars" org-hide-leading-stars nil)
4856 ("odd" org-odd-levels-only t)
4857 ("oddeven" org-odd-levels-only nil)
4858 ("align" org-startup-align-all-tables t)
4859 ("noalign" org-startup-align-all-tables nil)
4860 ("inlineimages" org-startup-with-inline-images t)
4861 ("noinlineimages" org-startup-with-inline-images nil)
4862 ("latexpreview" org-startup-with-latex-preview t)
4863 ("nolatexpreview" org-startup-with-latex-preview nil)
4864 ("customtime" org-display-custom-times t)
4865 ("logdone" org-log-done time)
4866 ("lognotedone" org-log-done note)
4867 ("nologdone" org-log-done nil)
4868 ("lognoteclock-out" org-log-note-clock-out t)
4869 ("nolognoteclock-out" org-log-note-clock-out nil)
4870 ("logrepeat" org-log-repeat state)
4871 ("lognoterepeat" org-log-repeat note)
4872 ("logdrawer" org-log-into-drawer t)
4873 ("nologdrawer" org-log-into-drawer nil)
4874 ("logstatesreversed" org-log-states-order-reversed t)
4875 ("nologstatesreversed" org-log-states-order-reversed nil)
4876 ("nologrepeat" org-log-repeat nil)
4877 ("logreschedule" org-log-reschedule time)
4878 ("lognotereschedule" org-log-reschedule note)
4879 ("nologreschedule" org-log-reschedule nil)
4880 ("logredeadline" org-log-redeadline time)
4881 ("lognoteredeadline" org-log-redeadline note)
4882 ("nologredeadline" org-log-redeadline nil)
4883 ("logrefile" org-log-refile time)
4884 ("lognoterefile" org-log-refile note)
4885 ("nologrefile" org-log-refile nil)
4886 ("fninline" org-footnote-define-inline t)
4887 ("nofninline" org-footnote-define-inline nil)
4888 ("fnlocal" org-footnote-section nil)
4889 ("fnauto" org-footnote-auto-label t)
4890 ("fnprompt" org-footnote-auto-label nil)
4891 ("fnconfirm" org-footnote-auto-label confirm)
4892 ("fnplain" org-footnote-auto-label plain)
4893 ("fnadjust" org-footnote-auto-adjust t)
4894 ("nofnadjust" org-footnote-auto-adjust nil)
4895 ("constcgs" constants-unit-system cgs)
4896 ("constSI" constants-unit-system SI)
4897 ("noptag" org-tag-persistent-alist nil)
4898 ("hideblocks" org-hide-block-startup t)
4899 ("nohideblocks" org-hide-block-startup nil)
4900 ("beamer" org-startup-with-beamer-mode t)
4901 ("entitiespretty" org-pretty-entities t)
4902 ("entitiesplain" org-pretty-entities nil))
4903 "Variable associated with STARTUP options for org-mode.
4904 Each element is a list of three items: the startup options (as written
4905 in the #+STARTUP line), the corresponding variable, and the value to set
4906 this variable to if the option is found. An optional forth element PUSH
4907 means to push this value onto the list in the variable.")
4909 (defcustom org-group-tags t
4910 "When non-nil (the default), use group tags.
4911 This can be turned on/off through `org-toggle-tags-groups'."
4912 :group 'org-tags
4913 :group 'org-startup
4914 :type 'boolean)
4916 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4918 (defun org-toggle-tags-groups ()
4919 "Toggle support for group tags.
4920 Support for group tags is controlled by the option
4921 `org-group-tags', which is non-nil by default."
4922 (interactive)
4923 (setq org-group-tags (not org-group-tags))
4924 (cond ((and (derived-mode-p 'org-agenda-mode)
4925 org-group-tags)
4926 (org-agenda-redo))
4927 ((derived-mode-p 'org-mode)
4928 (let ((org-inhibit-startup t)) (org-mode))))
4929 (message "Groups tags support has been turned %s"
4930 (if org-group-tags "on" "off")))
4932 (defun org-set-regexps-and-options (&optional tags-only)
4933 "Precompute regular expressions used in the current buffer.
4934 When optional argument TAGS-ONLY is non-nil, only compute tags
4935 related expressions."
4936 (when (derived-mode-p 'org-mode)
4937 (let ((alist (org--setup-collect-keywords
4938 (org-make-options-regexp
4939 (append '("FILETAGS" "TAGS" "SETUPFILE")
4940 (and (not tags-only)
4941 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4942 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4943 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4944 ;; Startup options. Get this early since it does change
4945 ;; behavior for other options (e.g., tags).
4946 (let ((startup (cdr (assq 'startup alist))))
4947 (dolist (option startup)
4948 (let ((entry (assoc-string option org-startup-options t)))
4949 (when entry
4950 (let ((var (nth 1 entry))
4951 (val (nth 2 entry)))
4952 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4953 (unless (listp (symbol-value var))
4954 (set (make-local-variable var) nil))
4955 (add-to-list var val)))))))
4956 (setq-local org-file-tags
4957 (mapcar #'org-add-prop-inherited
4958 (cdr (assq 'filetags alist))))
4959 (setq org-current-tag-alist
4960 (append org-tag-persistent-alist
4961 (let ((tags (cdr (assq 'tags alist))))
4962 (if tags (org-tag-string-to-alist tags)
4963 org-tag-alist))))
4964 (setq org-tag-groups-alist
4965 (org-tag-alist-to-groups org-current-tag-alist))
4966 (unless tags-only
4967 ;; File properties.
4968 (setq-local org-file-properties (cdr (assq 'property alist)))
4969 ;; Archive location.
4970 (let ((archive (cdr (assq 'archive alist))))
4971 (when archive (setq-local org-archive-location archive)))
4972 ;; Category.
4973 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4974 (when cat
4975 (setq-local org-category (intern cat))
4976 (setq-local org-file-properties
4977 (org--update-property-plist
4978 "CATEGORY" cat org-file-properties))))
4979 ;; Columns.
4980 (let ((column (cdr (assq 'columns alist))))
4981 (when column (setq-local org-columns-default-format column)))
4982 ;; Constants.
4983 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4984 ;; Link abbreviations.
4985 (let ((links (cdr (assq 'link alist))))
4986 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4987 ;; Priorities.
4988 (let ((priorities (cdr (assq 'priorities alist))))
4989 (when priorities
4990 (setq-local org-highest-priority (nth 0 priorities))
4991 (setq-local org-lowest-priority (nth 1 priorities))
4992 (setq-local org-default-priority (nth 2 priorities))))
4993 ;; Scripts.
4994 (let ((scripts (assq 'scripts alist)))
4995 (when scripts
4996 (setq-local org-use-sub-superscripts (cdr scripts))))
4997 ;; TODO keywords.
4998 (setq-local org-todo-kwd-alist nil)
4999 (setq-local org-todo-key-alist nil)
5000 (setq-local org-todo-key-trigger nil)
5001 (setq-local org-todo-keywords-1 nil)
5002 (setq-local org-done-keywords nil)
5003 (setq-local org-todo-heads nil)
5004 (setq-local org-todo-sets nil)
5005 (setq-local org-todo-log-states nil)
5006 (let ((todo-sequences
5007 (or (nreverse (cdr (assq 'todo alist)))
5008 (let ((d (default-value 'org-todo-keywords)))
5009 (if (not (stringp (car d))) d
5010 ;; XXX: Backward compatibility code.
5011 (list (cons org-todo-interpretation d)))))))
5012 (dolist (sequence todo-sequences)
5013 (let* ((sequence (or (run-hook-with-args-until-success
5014 'org-todo-setup-filter-hook sequence)
5015 sequence))
5016 (sequence-type (car sequence))
5017 (keywords (cdr sequence))
5018 (sep (member "|" keywords))
5019 names alist)
5020 (dolist (k (remove "|" keywords))
5021 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5023 (error "Invalid TODO keyword %s" k))
5024 (let ((name (match-string 1 k))
5025 (key (match-string 2 k))
5026 (log (org-extract-log-state-settings k)))
5027 (push name names)
5028 (push (cons name (and key (string-to-char key))) alist)
5029 (when log (push log org-todo-log-states))))
5030 (let* ((names (nreverse names))
5031 (done (if sep (org-remove-keyword-keys (cdr sep))
5032 (last names)))
5033 (head (car names))
5034 (tail (list sequence-type head (car done) (org-last done))))
5035 (add-to-list 'org-todo-heads head 'append)
5036 (push names org-todo-sets)
5037 (setq org-done-keywords (append org-done-keywords done nil))
5038 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5039 (setq org-todo-key-alist
5040 (append org-todo-key-alist
5041 (and alist
5042 (append '((:startgroup))
5043 (nreverse alist)
5044 '((:endgroup))))))
5045 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5046 (setq org-todo-sets (nreverse org-todo-sets)
5047 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5048 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5049 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5050 ;; Compute the regular expressions and other local variables.
5051 ;; Using `org-outline-regexp-bol' would complicate them much,
5052 ;; because of the fixed white space at the end of that string.
5053 (unless org-done-keywords
5054 (setq org-done-keywords
5055 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5056 (setq org-not-done-keywords
5057 (org-delete-all org-done-keywords
5058 (copy-sequence org-todo-keywords-1))
5059 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5060 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5061 org-not-done-heading-regexp
5062 (format org-heading-keyword-regexp-format org-not-done-regexp)
5063 org-todo-line-regexp
5064 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5065 org-complex-heading-regexp
5066 (concat "^\\(\\*+\\)"
5067 "\\(?: +" org-todo-regexp "\\)?"
5068 "\\(?: +\\(\\[#.\\]\\)\\)?"
5069 "\\(?: +\\(.*?\\)\\)??"
5070 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5071 "[ \t]*$")
5072 org-complex-heading-regexp-format
5073 (concat "^\\(\\*+\\)"
5074 "\\(?: +" org-todo-regexp "\\)?"
5075 "\\(?: +\\(\\[#.\\]\\)\\)?"
5076 "\\(?: +"
5077 ;; Stats cookies can be stuck to body.
5078 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5079 "\\(%s\\)"
5080 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5081 "\\)"
5082 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5083 "[ \t]*$")
5084 org-todo-line-tags-regexp
5085 (concat "^\\(\\*+\\)"
5086 "\\(?: +" org-todo-regexp "\\)?"
5087 "\\(?: +\\(.*?\\)\\)??"
5088 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5089 "[ \t]*$"))
5090 (org-compute-latex-and-related-regexp)))))
5092 (defun org--setup-collect-keywords (regexp &optional files alist)
5093 "Return setup keywords values as an alist.
5095 REGEXP matches a subset of setup keywords. FILES is a list of
5096 file names already visited. It is used to avoid circular setup
5097 files. ALIST, when non-nil, is the alist computed so far.
5099 Return value contains the following keys: `archive', `category',
5100 `columns', `constants', `filetags', `link', `priorities',
5101 `property', `scripts', `startup', `tags' and `todo'."
5102 (org-with-wide-buffer
5103 (goto-char (point-min))
5104 (let ((case-fold-search t))
5105 (while (re-search-forward regexp nil t)
5106 (let ((element (org-element-at-point)))
5107 (when (eq (org-element-type element) 'keyword)
5108 (let ((key (org-element-property :key element))
5109 (value (org-element-property :value element)))
5110 (cond
5111 ((equal key "ARCHIVE")
5112 (when (org-string-nw-p value)
5113 (push (cons 'archive value) alist)))
5114 ((equal key "CATEGORY") (push (cons 'category value) alist))
5115 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5116 ((equal key "CONSTANTS")
5117 (let* ((constants (assq 'constants alist))
5118 (store (cdr constants)))
5119 (dolist (pair (org-split-string value))
5120 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5121 pair)
5122 (let* ((name (match-string 1 pair))
5123 (value (match-string 2 pair))
5124 (old (assoc name store)))
5125 (if old (setcdr old value)
5126 (push (cons name value) store)))))
5127 (if constants (setcdr constants store)
5128 (push (cons 'constants store) alist))))
5129 ((equal key "FILETAGS")
5130 (when (org-string-nw-p value)
5131 (let ((old (assq 'filetags alist))
5132 (new (apply #'nconc
5133 (mapcar (lambda (x) (org-split-string x ":"))
5134 (org-split-string value)))))
5135 (if old (setcdr old (append new (cdr old)))
5136 (push (cons 'filetags new) alist)))))
5137 ((equal key "LINK")
5138 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5139 (let ((links (assq 'link alist))
5140 (pair (cons (match-string-no-properties 1 value)
5141 (match-string-no-properties 2 value))))
5142 (if links (push pair (cdr links))
5143 (push (list 'link pair) alist)))))
5144 ((equal key "OPTIONS")
5145 (when (and (org-string-nw-p value)
5146 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5147 (push (cons 'scripts (read (match-string 1 value))) alist)))
5148 ((equal key "PRIORITIES")
5149 (push (cons 'priorities
5150 (let ((prio (org-split-string value)))
5151 (if (< (length prio) 3) '(?A ?C ?B)
5152 (mapcar #'string-to-char prio))))
5153 alist))
5154 ((equal key "PROPERTY")
5155 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5156 (let* ((property (assq 'property alist))
5157 (value (org--update-property-plist
5158 (match-string-no-properties 1 value)
5159 (match-string-no-properties 2 value)
5160 (cdr property))))
5161 (if property (setcdr property value)
5162 (push (cons 'property value) alist)))))
5163 ((equal key "STARTUP")
5164 (let ((startup (assq 'startup alist)))
5165 (if startup
5166 (setcdr startup
5167 (append (cdr startup) (org-split-string value)))
5168 (push (cons 'startup (org-split-string value)) alist))))
5169 ((equal key "TAGS")
5170 (let ((tag-cell (assq 'tags alist)))
5171 (if tag-cell
5172 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5173 (push (cons 'tags value) alist))))
5174 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5175 (let ((todo (assq 'todo alist))
5176 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5177 (org-split-string value))))
5178 (if todo (push value (cdr todo))
5179 (push (list 'todo value) alist))))
5180 ((equal key "SETUPFILE")
5181 (unless buffer-read-only ; Do not check in Gnus messages.
5182 (let ((f (and (org-string-nw-p value)
5183 (expand-file-name
5184 (org-unbracket-string "\"" "\"" value)))))
5185 (when (and f (file-readable-p f) (not (member f files)))
5186 (with-temp-buffer
5187 (setq default-directory (file-name-directory f))
5188 (insert-file-contents f)
5189 (setq alist
5190 ;; Fake Org mode to benefit from cache
5191 ;; without recurring needlessly.
5192 (let ((major-mode 'org-mode))
5193 (org--setup-collect-keywords
5194 regexp (cons f files) alist)))))))))))))))
5195 alist)
5197 (defun org-tag-string-to-alist (s)
5198 "Return tag alist associated to string S.
5199 S is a value for TAGS keyword or produced with
5200 `org-tag-alist-to-string'. Return value is an alist suitable for
5201 `org-tag-alist' or `org-tag-persistent-alist'."
5202 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5203 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5204 "\\|{.+?}\\)" ; regular expression
5205 "\\(?:(\\(.\\))\\)?\\'"))
5206 alist group-flag)
5207 (dolist (tokens lines (cdr (nreverse alist)))
5208 (push '(:newline) alist)
5209 (while tokens
5210 (let ((token (pop tokens)))
5211 (pcase token
5212 ("{"
5213 (push '(:startgroup) alist)
5214 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5215 ("}"
5216 (push '(:endgroup) alist)
5217 (setq group-flag nil))
5218 ("["
5219 (push '(:startgrouptag) alist)
5220 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5221 ("]"
5222 (push '(:endgrouptag) alist)
5223 (setq group-flag nil))
5224 (":"
5225 (push '(:grouptags) alist))
5226 ((guard (string-match tag-re token))
5227 (let ((tag (match-string 1 token))
5228 (key (and (match-beginning 2)
5229 (string-to-char (match-string 2 token)))))
5230 ;; Push all tags in groups, no matter if they already
5231 ;; appear somewhere else in the list.
5232 (when (or group-flag (not (assoc tag alist)))
5233 (push (cons tag key) alist))))))))))
5235 (defun org-tag-alist-to-string (alist &optional skip-key)
5236 "Return tag string associated to ALIST.
5238 ALIST is an alist, as defined in `org-tag-alist' or
5239 `org-tag-persistent-alist', or produced with
5240 `org-tag-string-to-alist'.
5242 Return value is a string suitable as a value for \"TAGS\"
5243 keyword.
5245 When optional argument SKIP-KEY is non-nil, skip selection keys
5246 next to tags."
5247 (mapconcat (lambda (token)
5248 (pcase token
5249 (`(:startgroup) "{")
5250 (`(:endgroup) "}")
5251 (`(:startgrouptag) "[")
5252 (`(:endgrouptag) "]")
5253 (`(:grouptags) ":")
5254 (`(:newline) "\\n")
5255 ((and
5256 (guard (not skip-key))
5257 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5258 (format "%s(%c)" tag key))
5259 (`(,(and tag (pred stringp)) . ,_) tag)
5260 (_ (user-error "Invalid tag token: %S" token))))
5261 alist
5262 " "))
5264 (defun org-tag-alist-to-groups (alist)
5265 "Return group alist from tag ALIST.
5266 ALIST is an alist, as defined in `org-tag-alist' or
5267 `org-tag-persistent-alist', or produced with
5268 `org-tag-string-to-alist'. Return value is an alist following
5269 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5270 a string, summarizing TAGS, as a list of strings."
5271 (let (groups group-status current-group)
5272 (dolist (token alist (nreverse groups))
5273 (pcase token
5274 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5275 (`(,(or :endgroup :endgrouptag))
5276 (when (eq group-status 'append)
5277 (push (nreverse current-group) groups))
5278 (setq group-status nil))
5279 (`(:grouptags) (setq group-status 'append))
5280 ((and `(,tag . ,_) (guard group-status))
5281 (if (eq group-status 'append) (push tag current-group)
5282 (setq current-group (list tag))))
5283 (_ nil)))))
5285 (defvar org--file-cache (make-hash-table :test #'equal)
5286 "Hash table to store contents of files referenced via a URL.
5287 This is the cache of file URLs read using `org-file-contents'.")
5289 (defun org-reset-file-cache ()
5290 "Reset the cache of files downloaded by `org-file-contents'."
5291 (clrhash org--file-cache))
5293 (defun org-file-url-p (file)
5294 "Non-nil if FILE is a URL."
5295 (require 'ffap)
5296 (string-match-p ffap-url-regexp file))
5298 (defun org-file-contents (file &optional noerror nocache)
5299 "Return the contents of FILE, as a string.
5301 FILE can be a file name or URL.
5303 If FILE is a URL, download the contents. If the URL contents are
5304 already cached in the `org--file-cache' hash table, the download step
5305 is skipped.
5307 If NOERROR is non-nil, ignore the error when unable to read the FILE
5308 from file or URL.
5310 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5311 is available. This option applies only if FILE is a URL."
5312 (let* ((is-url (org-file-url-p file))
5313 (cache (and is-url
5314 (not nocache)
5315 (gethash file org--file-cache))))
5316 (cond
5317 (cache)
5318 (is-url
5319 (with-current-buffer (url-retrieve-synchronously file)
5320 (goto-char (point-min))
5321 ;; Move point to after the url-retrieve header.
5322 (search-forward "\n\n" nil :move)
5323 ;; Search for the success code only in the url-retrieve header.
5324 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5325 ;; Update the cache `org--file-cache' and return contents.
5326 (puthash file
5327 (buffer-substring-no-properties (point) (point-max))
5328 org--file-cache)
5329 (funcall (if noerror #'message #'user-error)
5330 "Unable to fetch file from %S"
5331 file))))
5333 (with-temp-buffer
5334 (condition-case err
5335 (progn
5336 (insert-file-contents file)
5337 (buffer-string))
5338 (file-error
5339 (funcall (if noerror #'message #'user-error)
5340 (error-message-string err)))))))))
5342 (defun org-extract-log-state-settings (x)
5343 "Extract the log state setting from a TODO keyword string.
5344 This will extract info from a string like \"WAIT(w@/!)\"."
5345 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5346 (let ((kw (match-string 1 x))
5347 (log1 (and (match-end 3) (match-string 3 x)))
5348 (log2 (and (match-end 4) (match-string 4 x))))
5349 (and (or log1 log2)
5350 (list kw
5351 (and log1 (if (equal log1 "!") 'time 'note))
5352 (and log2 (if (equal log2 "!") 'time 'note)))))))
5354 (defun org-remove-keyword-keys (list)
5355 "Remove a pair of parenthesis at the end of each string in LIST."
5356 (mapcar (lambda (x)
5357 (if (string-match "(.*)$" x)
5358 (substring x 0 (match-beginning 0))
5360 list))
5362 (defun org-assign-fast-keys (alist)
5363 "Assign fast keys to a keyword-key alist.
5364 Respect keys that are already there."
5365 (let (new e (alt ?0))
5366 (while (setq e (pop alist))
5367 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5368 (cdr e)) ;; Key already assigned.
5369 (push e new)
5370 (let ((clist (string-to-list (downcase (car e))))
5371 (used (append new alist)))
5372 (when (= (car clist) ?@)
5373 (pop clist))
5374 (while (and clist (rassoc (car clist) used))
5375 (pop clist))
5376 (unless clist
5377 (while (rassoc alt used)
5378 (cl-incf alt)))
5379 (push (cons (car e) (or (car clist) alt)) new))))
5380 (nreverse new)))
5382 ;;; Some variables used in various places
5384 (defvar org-window-configuration nil
5385 "Used in various places to store a window configuration.")
5386 (defvar org-selected-window nil
5387 "Used in various places to store a window configuration.")
5388 (defvar org-finish-function nil
5389 "Function to be called when `C-c C-c' is used.
5390 This is for getting out of special buffers like capture.")
5391 (defvar org-last-state)
5393 ;; Defined somewhere in this file, but used before definition.
5394 (defvar org-entities) ;; defined in org-entities.el
5395 (defvar org-struct-menu)
5396 (defvar org-org-menu)
5397 (defvar org-tbl-menu)
5399 ;;;; Define the Org mode
5401 ;; We use a before-change function to check if a table might need
5402 ;; an update.
5403 (defvar org-table-may-need-update t
5404 "Indicates that a table might need an update.
5405 This variable is set by `org-before-change-function'.
5406 `org-table-align' sets it back to nil.")
5407 (defun org-before-change-function (_beg _end)
5408 "Every change indicates that a table might need an update."
5409 (setq org-table-may-need-update t))
5410 (defvar org-mode-map)
5411 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5412 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5413 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5414 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5415 (defvar org-table-buffer-is-an nil)
5417 (defvar bidi-paragraph-direction)
5418 (defvar buffer-face-mode-face)
5420 (require 'outline)
5422 ;; Other stuff we need.
5423 (require 'time-date)
5424 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5425 (require 'easymenu)
5426 (autoload 'easy-menu-add "easymenu")
5427 (require 'overlay)
5429 ;; (require 'org-macs) moved higher up in the file before it is first used
5430 (require 'org-entities)
5431 ;; (require 'org-compat) moved higher up in the file before it is first used
5432 (require 'org-faces)
5433 (require 'org-list)
5434 (require 'org-pcomplete)
5435 (require 'org-src)
5436 (require 'org-footnote)
5437 (require 'org-macro)
5439 ;; babel
5440 (require 'ob)
5442 ;;;###autoload
5443 (define-derived-mode org-mode outline-mode "Org"
5444 "Outline-based notes management and organizer, alias
5445 \"Carsten's outline-mode for keeping track of everything.\"
5447 Org mode develops organizational tasks around a NOTES file which
5448 contains information about projects as plain text. Org mode is
5449 implemented on top of Outline mode, which is ideal to keep the content
5450 of large files well structured. It supports ToDo items, deadlines and
5451 time stamps, which magically appear in the diary listing of the Emacs
5452 calendar. Tables are easily created with a built-in table editor.
5453 Plain text URL-like links connect to websites, emails (VM), Usenet
5454 messages (Gnus), BBDB entries, and any files related to the project.
5455 For printing and sharing of notes, an Org file (or a part of it)
5456 can be exported as a structured ASCII or HTML file.
5458 The following commands are available:
5460 \\{org-mode-map}"
5462 ;; Get rid of Outline menus, they are not needed
5463 ;; Need to do this here because define-derived-mode sets up
5464 ;; the keymap so late. Still, it is a waste to call this each time
5465 ;; we switch another buffer into Org mode.
5466 (define-key org-mode-map [menu-bar headings] 'undefined)
5467 (define-key org-mode-map [menu-bar hide] 'undefined)
5468 (define-key org-mode-map [menu-bar show] 'undefined)
5470 (org-load-modules-maybe)
5471 (org-install-agenda-files-menu)
5472 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5473 (add-to-invisibility-spec '(org-cwidth))
5474 (add-to-invisibility-spec '(org-hide-block . t))
5475 (setq-local outline-regexp org-outline-regexp)
5476 (setq-local outline-level 'org-outline-level)
5477 (setq bidi-paragraph-direction 'left-to-right)
5478 (when (and org-ellipsis
5479 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5480 (fboundp 'make-glyph-code))
5481 (unless org-display-table
5482 (setq org-display-table (make-display-table)))
5483 (set-display-table-slot
5484 org-display-table 4
5485 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5486 (if (stringp org-ellipsis) org-ellipsis "..."))))
5487 (setq buffer-display-table org-display-table))
5488 (org-set-regexps-and-options)
5489 (org-set-font-lock-defaults)
5490 (when (and org-tag-faces (not org-tags-special-faces-re))
5491 ;; tag faces set outside customize.... force initialization.
5492 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5493 ;; Calc embedded
5494 (setq-local calc-embedded-open-mode "# ")
5495 ;; Modify a few syntax entries
5496 (modify-syntax-entry ?@ "w")
5497 (modify-syntax-entry ?\" "\"")
5498 (modify-syntax-entry ?\\ "_")
5499 (modify-syntax-entry ?~ "_")
5500 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5501 ;; Activate before-change-function
5502 (setq-local org-table-may-need-update t)
5503 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5504 ;; Check for running clock before killing a buffer
5505 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5506 ;; Initialize macros templates.
5507 (org-macro-initialize-templates)
5508 ;; Initialize radio targets.
5509 (org-update-radio-target-regexp)
5510 ;; Indentation.
5511 (setq-local indent-line-function 'org-indent-line)
5512 (setq-local indent-region-function 'org-indent-region)
5513 ;; Filling and auto-filling.
5514 (org-setup-filling)
5515 ;; Comments.
5516 (org-setup-comments-handling)
5517 ;; Initialize cache.
5518 (org-element-cache-reset)
5519 ;; Beginning/end of defun
5520 (setq-local beginning-of-defun-function 'org-backward-element)
5521 (setq-local end-of-defun-function
5522 (lambda ()
5523 (if (not (org-at-heading-p))
5524 (org-forward-element)
5525 (org-forward-element)
5526 (forward-char -1))))
5527 ;; Next error for sparse trees
5528 (setq-local next-error-function 'org-occur-next-match)
5529 ;; Make sure dependence stuff works reliably, even for users who set it
5530 ;; too late :-(
5531 (if org-enforce-todo-dependencies
5532 (add-hook 'org-blocker-hook
5533 'org-block-todo-from-children-or-siblings-or-parent)
5534 (remove-hook 'org-blocker-hook
5535 'org-block-todo-from-children-or-siblings-or-parent))
5536 (if org-enforce-todo-checkbox-dependencies
5537 (add-hook 'org-blocker-hook
5538 'org-block-todo-from-checkboxes)
5539 (remove-hook 'org-blocker-hook
5540 'org-block-todo-from-checkboxes))
5542 ;; Align options lines
5543 (setq-local
5544 align-mode-rules-list
5545 '((org-in-buffer-settings
5546 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5547 (modes . '(org-mode)))))
5549 ;; Imenu
5550 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5552 ;; Make isearch reveal context
5553 (setq-local outline-isearch-open-invisible-function
5554 (lambda (&rest _) (org-show-context 'isearch)))
5556 ;; Setup the pcomplete hooks
5557 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5558 (setq-local pcomplete-command-name-function 'org-command-at-point)
5559 (setq-local pcomplete-default-completion-function 'ignore)
5560 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5561 (setq-local pcomplete-termination-string "")
5562 (setq-local buffer-face-mode-face 'org-default)
5564 ;; If empty file that did not turn on Org mode automatically, make
5565 ;; it to.
5566 (when (and org-insert-mode-line-in-empty-file
5567 (called-interactively-p 'any)
5568 (= (point-min) (point-max)))
5569 (insert "# -*- mode: org -*-\n\n"))
5570 (unless org-inhibit-startup
5571 (org-unmodified
5572 (when org-startup-with-beamer-mode (org-beamer-mode))
5573 (when org-startup-align-all-tables
5574 (org-table-map-tables #'org-table-align t))
5575 (when org-startup-with-inline-images (org-display-inline-images))
5576 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5577 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5578 (when org-startup-truncated (setq truncate-lines t))
5579 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5580 (org-refresh-effort-properties)))
5581 ;; Try to set `org-hide' face correctly.
5582 (let ((foreground (org-find-invisible-foreground)))
5583 (when foreground
5584 (set-face-foreground 'org-hide foreground))))
5586 ;; Update `customize-package-emacs-version-alist'
5587 (add-to-list 'customize-package-emacs-version-alist
5588 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5589 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5590 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5591 ("9.0" . "26.1")))
5593 (defvar org-mode-transpose-word-syntax-table
5594 (let ((st (make-syntax-table text-mode-syntax-table)))
5595 (dolist (c org-emphasis-alist st)
5596 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5598 (when (fboundp 'abbrev-table-put)
5599 (abbrev-table-put org-mode-abbrev-table
5600 :parents (list text-mode-abbrev-table)))
5602 (defun org-find-invisible-foreground ()
5603 (let ((candidates (remove
5604 "unspecified-bg"
5605 (nconc
5606 (list (face-background 'default)
5607 (face-background 'org-default))
5608 (mapcar
5609 (lambda (alist)
5610 (when (boundp alist)
5611 (cdr (assq 'background-color (symbol-value alist)))))
5612 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5613 (list (face-foreground 'org-hide))))))
5614 (car (remove nil candidates))))
5616 (defun org-current-time (&optional rounding-minutes past)
5617 "Current time, possibly rounded to ROUNDING-MINUTES.
5618 When ROUNDING-MINUTES is not an integer, fall back on the car of
5619 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5620 the rounding returns a past time."
5621 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5622 (car org-time-stamp-rounding-minutes)))
5623 (time (decode-time)) res)
5624 (if (< r 1)
5625 (current-time)
5626 (setq res
5627 (apply 'encode-time
5628 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5629 (nthcdr 2 time))))
5630 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5631 (seconds-to-time (- (float-time res) (* r 60)))
5632 res))))
5634 (defun org-today ()
5635 "Return today date, considering `org-extend-today-until'."
5636 (time-to-days
5637 (time-subtract (current-time)
5638 (list 0 (* 3600 org-extend-today-until) 0))))
5640 ;;;; Font-Lock stuff, including the activators
5642 (defvar org-mouse-map (make-sparse-keymap))
5643 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5644 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5645 (when org-mouse-1-follows-link
5646 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5647 (when org-tab-follows-link
5648 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5649 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5651 (require 'font-lock)
5653 (defconst org-non-link-chars "]\t\n\r<>")
5654 (defvar org-link-types-re nil
5655 "Matches a link that has a url-like prefix like \"http:\"")
5656 (defvar org-link-re-with-space nil
5657 "Matches a link with spaces, optional angular brackets around it.")
5658 (defvar org-link-re-with-space2 nil
5659 "Matches a link with spaces, optional angular brackets around it.")
5660 (defvar org-link-re-with-space3 nil
5661 "Matches a link with spaces, only for internal part in bracket links.")
5662 (defvar org-angle-link-re nil
5663 "Matches link with angular brackets, spaces are allowed.")
5664 (defvar org-plain-link-re nil
5665 "Matches plain link, without spaces.")
5666 (defvar org-bracket-link-regexp nil
5667 "Matches a link in double brackets.")
5668 (defvar org-bracket-link-analytic-regexp nil
5669 "Regular expression used to analyze links.
5670 Here is what the match groups contain after a match:
5671 1: http:
5672 2: http
5673 3: path
5674 4: [desc]
5675 5: desc")
5676 (defvar org-bracket-link-analytic-regexp++ nil
5677 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5678 (defvar org-any-link-re nil
5679 "Regular expression matching any link.")
5681 (defconst org-match-sexp-depth 3
5682 "Number of stacked braces for sub/superscript matching.")
5684 (defun org-create-multibrace-regexp (left right n)
5685 "Create a regular expression which will match a balanced sexp.
5686 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5687 as single character strings.
5688 The regexp returned will match the entire expression including the
5689 delimiters. It will also define a single group which contains the
5690 match except for the outermost delimiters. The maximum depth of
5691 stacked delimiters is N. Escaping delimiters is not possible."
5692 (let* ((nothing (concat "[^" left right "]*?"))
5693 (or "\\|")
5694 (re nothing)
5695 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5696 (while (> n 1)
5697 (setq n (1- n)
5698 re (concat re or next)
5699 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5700 (concat left "\\(" re "\\)" right)))
5702 (defconst org-match-substring-regexp
5703 (concat
5704 "\\(\\S-\\)\\([_^]\\)\\("
5705 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5706 "\\|"
5707 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5708 "\\|"
5709 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5710 "The regular expression matching a sub- or superscript.")
5712 (defconst org-match-substring-with-braces-regexp
5713 (concat
5714 "\\(\\S-\\)\\([_^]\\)"
5715 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5716 "The regular expression matching a sub- or superscript, forcing braces.")
5718 (defun org-make-link-regexps ()
5719 "Update the link regular expressions.
5720 This should be called after the variable `org-link-parameters' has changed."
5721 (let ((types-re (regexp-opt (org-link-types) t)))
5722 (setq org-link-types-re
5723 (concat "\\`" types-re ":")
5724 org-link-re-with-space
5725 (concat "<?" types-re ":"
5726 "\\([^" org-non-link-chars " ]"
5727 "[^" org-non-link-chars "]*"
5728 "[^" org-non-link-chars " ]\\)>?")
5729 org-link-re-with-space2
5730 (concat "<?" types-re ":"
5731 "\\([^" org-non-link-chars " ]"
5732 "[^\t\n\r]*"
5733 "[^" org-non-link-chars " ]\\)>?")
5734 org-link-re-with-space3
5735 (concat "<?" types-re ":"
5736 "\\([^" org-non-link-chars " ]"
5737 "[^\t\n\r]*\\)")
5738 org-angle-link-re
5739 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5740 types-re)
5741 org-plain-link-re
5742 (concat
5743 "\\<" types-re ":"
5744 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5745 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5746 org-bracket-link-regexp
5747 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5748 org-bracket-link-analytic-regexp
5749 (concat
5750 "\\[\\["
5751 "\\(" types-re ":\\)?"
5752 "\\([^]]+\\)"
5753 "\\]"
5754 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5755 "\\]")
5756 org-bracket-link-analytic-regexp++
5757 (concat
5758 "\\[\\["
5759 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5760 "\\([^]]+\\)"
5761 "\\]"
5762 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5763 "\\]")
5764 org-any-link-re
5765 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5766 org-angle-link-re "\\)\\|\\("
5767 org-plain-link-re "\\)"))))
5769 (org-make-link-regexps)
5771 (defvar org-emph-face nil)
5773 (defun org-do-emphasis-faces (limit)
5774 "Run through the buffer and emphasize strings."
5775 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5776 (car org-emphasis-regexp-components))))
5777 (catch :exit
5778 (while (re-search-forward quick-re limit t)
5779 (let* ((marker (match-string 2))
5780 (verbatim? (member marker '("~" "="))))
5781 (when (save-excursion
5782 (goto-char (match-beginning 0))
5783 ;; Do not match headline stars. Do not consider
5784 ;; stars of a headline as closing marker for bold
5785 ;; markup either.
5786 (and (not (looking-at-p org-outline-regexp-bol))
5787 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5788 (not (string-match-p
5789 (concat org-outline-regexp-bol "\\'")
5790 (match-string 0)))))
5791 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5792 (font-lock-prepend-text-property
5793 (match-beginning 2) (match-end 2) 'face face)
5794 (when verbatim?
5795 (org-remove-flyspell-overlays-in
5796 (match-beginning 0) (match-end 0)))
5797 (add-text-properties (match-beginning 2) (match-end 2)
5798 '(font-lock-multiline t org-emphasis t))
5799 (when org-hide-emphasis-markers
5800 (add-text-properties (match-end 4) (match-beginning 5)
5801 '(invisible org-link))
5802 (add-text-properties (match-beginning 3) (match-end 3)
5803 '(invisible org-link)))
5804 (throw :exit t))))))))
5806 (defun org-emphasize (&optional char)
5807 "Insert or change an emphasis, i.e. a font like bold or italic.
5808 If there is an active region, change that region to a new emphasis.
5809 If there is no region, just insert the marker characters and position
5810 the cursor between them.
5811 CHAR should be the marker character. If it is a space, it means to
5812 remove the emphasis of the selected region.
5813 If CHAR is not given (for example in an interactive call) it will be
5814 prompted for."
5815 (interactive)
5816 (let ((erc org-emphasis-regexp-components)
5817 (string "") beg end move s)
5818 (if (org-region-active-p)
5819 (setq beg (region-beginning)
5820 end (region-end)
5821 string (buffer-substring beg end))
5822 (setq move t))
5824 (unless char
5825 (message "Emphasis marker or tag: [%s]"
5826 (mapconcat #'car org-emphasis-alist ""))
5827 (setq char (read-char-exclusive)))
5828 (if (equal char ?\s)
5829 (setq s ""
5830 move nil)
5831 (unless (assoc (char-to-string char) org-emphasis-alist)
5832 (user-error "No such emphasis marker: \"%c\"" char))
5833 (setq s (char-to-string char)))
5834 (while (and (> (length string) 1)
5835 (equal (substring string 0 1) (substring string -1))
5836 (assoc (substring string 0 1) org-emphasis-alist))
5837 (setq string (substring string 1 -1)))
5838 (setq string (concat s string s))
5839 (when beg (delete-region beg end))
5840 (unless (or (bolp)
5841 (string-match (concat "[" (nth 0 erc) "\n]")
5842 (char-to-string (char-before (point)))))
5843 (insert " "))
5844 (unless (or (eobp)
5845 (string-match (concat "[" (nth 1 erc) "\n]")
5846 (char-to-string (char-after (point)))))
5847 (insert " ") (backward-char 1))
5848 (insert string)
5849 (and move (backward-char 1))))
5851 (defconst org-nonsticky-props
5852 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5854 (defsubst org-rear-nonsticky-at (pos)
5855 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5857 (defun org-activate-links (limit)
5858 "Add link properties to links.
5859 This includes angle, plain, and bracket links."
5860 (catch :exit
5861 (while (re-search-forward org-any-link-re limit t)
5862 (let* ((start (match-beginning 0))
5863 (end (match-end 0))
5864 (style (cond ((eq ?< (char-after start)) 'angle)
5865 ((eq ?\[ (char-after (1+ start))) 'bracket)
5866 (t 'plain))))
5867 (when (and (memq style org-highlight-links)
5868 ;; Do not confuse plain links with tags.
5869 (not (and (eq style 'plain)
5870 (let ((face (get-text-property
5871 (max (1- start) (point-min)) 'face)))
5872 (if (consp face) (memq 'org-tag face)
5873 (eq 'org-tag face))))))
5874 (let* ((link-object (save-excursion
5875 (goto-char start)
5876 (save-match-data (org-element-link-parser))))
5877 (link (org-element-property :raw-link link-object))
5878 (type (org-element-property :type link-object))
5879 (path (org-element-property :path link-object))
5880 (properties ;for link's visible part
5881 (list
5882 'face (pcase (org-link-get-parameter type :face)
5883 ((and (pred functionp) face) (funcall face path))
5884 ((and (pred facep) face) face)
5885 ((and (pred consp) face) face) ;anonymous
5886 (_ 'org-link))
5887 'mouse-face (or (org-link-get-parameter type :mouse-face)
5888 'highlight)
5889 'keymap (or (org-link-get-parameter type :keymap)
5890 org-mouse-map)
5891 'help-echo (pcase (org-link-get-parameter type :help-echo)
5892 ((and (pred stringp) echo) echo)
5893 ((and (pred functionp) echo) echo)
5894 (_ (concat "LINK: " link)))
5895 'htmlize-link (pcase (org-link-get-parameter type
5896 :htmlize-link)
5897 ((and (pred functionp) f) (funcall f))
5898 (_ `(:uri ,link)))
5899 'font-lock-multiline t)))
5900 (org-remove-flyspell-overlays-in start end)
5901 (org-rear-nonsticky-at end)
5902 (if (not (eq 'bracket style))
5903 (add-text-properties start end properties)
5904 ;; Handle invisible parts in bracket links.
5905 (remove-text-properties start end '(invisible nil))
5906 (let ((hidden
5907 (append `(invisible
5908 ,(or (org-link-get-parameter type :display)
5909 'org-link))
5910 properties))
5911 (visible-start (or (match-beginning 4) (match-beginning 2)))
5912 (visible-end (or (match-end 4) (match-end 2))))
5913 (add-text-properties start visible-start hidden)
5914 (add-text-properties visible-start visible-end properties)
5915 (add-text-properties visible-end end hidden)
5916 (org-rear-nonsticky-at visible-start)
5917 (org-rear-nonsticky-at visible-end)))
5918 (let ((f (org-link-get-parameter type :activate-func)))
5919 (when (functionp f)
5920 (funcall f start end path (eq style 'bracket))))
5921 (throw :exit t))))) ;signal success
5922 nil))
5924 (defun org-activate-code (limit)
5925 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5926 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5927 (remove-text-properties (match-beginning 0) (match-end 0)
5928 '(display t invisible t intangible t))
5931 (defcustom org-src-fontify-natively t
5932 "When non-nil, fontify code in code blocks.
5933 See also the `org-block' face."
5934 :type 'boolean
5935 :version "24.4"
5936 :package-version '(Org . "8.3")
5937 :group 'org-appearance
5938 :group 'org-babel)
5940 (defcustom org-allow-promoting-top-level-subtree nil
5941 "When non-nil, allow promoting a top level subtree.
5942 The leading star of the top level headline will be replaced
5943 by a #."
5944 :type 'boolean
5945 :version "24.1"
5946 :group 'org-appearance)
5948 (defun org-fontify-meta-lines-and-blocks (limit)
5949 (condition-case nil
5950 (org-fontify-meta-lines-and-blocks-1 limit)
5951 (error (message "org-mode fontification error in %S at %d"
5952 (current-buffer)
5953 (line-number-at-pos)))))
5955 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5956 "Fontify #+ lines and blocks."
5957 (let ((case-fold-search t))
5958 (when (re-search-forward
5959 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5960 limit t)
5961 (let ((beg (match-beginning 0))
5962 (block-start (match-end 0))
5963 (block-end nil)
5964 (lang (match-string 7))
5965 (beg1 (line-beginning-position 2))
5966 (dc1 (downcase (match-string 2)))
5967 (dc3 (downcase (match-string 3)))
5968 end end1 quoting block-type)
5969 (cond
5970 ((and (match-end 4) (equal dc3 "+begin"))
5971 ;; Truly a block
5972 (setq block-type (downcase (match-string 5))
5973 quoting (member block-type org-protecting-blocks))
5974 (when (re-search-forward
5975 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5976 nil t) ;; on purpose, we look further than LIMIT
5977 (setq end (min (point-max) (match-end 0))
5978 end1 (min (point-max) (1- (match-beginning 0))))
5979 (setq block-end (match-beginning 0))
5980 (when quoting
5981 (org-remove-flyspell-overlays-in beg1 end1)
5982 (remove-text-properties beg end
5983 '(display t invisible t intangible t)))
5984 (add-text-properties
5985 beg end '(font-lock-fontified t font-lock-multiline t))
5986 (add-text-properties beg beg1 '(face org-meta-line))
5987 (org-remove-flyspell-overlays-in beg beg1)
5988 (add-text-properties ; For end_src
5989 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5990 (org-remove-flyspell-overlays-in end1 end)
5991 (cond
5992 ((and lang (not (string= lang "")) org-src-fontify-natively)
5993 (org-src-font-lock-fontify-block lang block-start block-end)
5994 (add-text-properties beg1 block-end '(src-block t)))
5995 (quoting
5996 (add-text-properties beg1 (min (point-max) (1+ end1))
5997 (list 'face
5998 (list :inherit
5999 (let ((face-name
6000 (intern (format "org-block-%s" lang))))
6001 (append (and (facep face-name) (list face-name))
6002 '(org-block))))))) ; end of source block
6003 ((not org-fontify-quote-and-verse-blocks))
6004 ((string= block-type "quote")
6005 (add-face-text-property
6006 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6007 ((string= block-type "verse")
6008 (add-face-text-property
6009 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6010 (add-text-properties beg beg1 '(face org-block-begin-line))
6011 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6012 '(face org-block-end-line))
6014 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6015 (org-remove-flyspell-overlays-in
6016 (match-beginning 0)
6017 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6018 (add-text-properties
6019 beg (match-end 3)
6020 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6021 '(font-lock-fontified t invisible t)
6022 '(font-lock-fontified t face org-document-info-keyword)))
6023 (add-text-properties
6024 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6025 (if (string-equal dc1 "+title:")
6026 '(font-lock-fontified t face org-document-title)
6027 '(font-lock-fontified t face org-document-info))))
6028 ((string-prefix-p "+caption" dc1)
6029 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6030 (remove-text-properties (match-beginning 0) (match-end 0)
6031 '(display t invisible t intangible t))
6032 ;; Handle short captions.
6033 (save-excursion
6034 (beginning-of-line)
6035 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6036 (add-text-properties (line-beginning-position) (match-end 1)
6037 '(font-lock-fontified t face org-meta-line))
6038 (add-text-properties (match-end 0) (line-end-position)
6039 '(font-lock-fontified t face org-block))
6041 ((member dc3 '(" " ""))
6042 (org-remove-flyspell-overlays-in beg (match-end 0))
6043 (add-text-properties
6044 beg (match-end 0)
6045 '(font-lock-fontified t face font-lock-comment-face)))
6046 (t ;; just any other in-buffer setting, but not indented
6047 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6048 (remove-text-properties (match-beginning 0) (match-end 0)
6049 '(display t invisible t intangible t))
6050 (add-text-properties beg (match-end 0)
6051 '(font-lock-fontified t face org-meta-line))
6052 t))))))
6054 (defun org-fontify-drawers (limit)
6055 "Fontify drawers."
6056 (when (re-search-forward org-drawer-regexp limit t)
6057 (add-text-properties
6058 (match-beginning 0) (match-end 0)
6059 '(font-lock-fontified t face org-special-keyword))
6060 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6063 (defun org-fontify-macros (limit)
6064 "Fontify macros."
6065 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6066 (add-text-properties
6067 (match-beginning 0) (match-end 0)
6068 '(font-lock-fontified t face org-macro))
6069 (when org-hide-macro-markers
6070 (add-text-properties (match-end 2) (match-beginning 2)
6071 '(invisible t))
6072 (add-text-properties (match-beginning 1) (match-end 1)
6073 '(invisible t)))
6074 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6077 (defun org-activate-footnote-links (limit)
6078 "Add text properties for footnotes."
6079 (let ((fn (org-footnote-next-reference-or-definition limit)))
6080 (when fn
6081 (let* ((beg (nth 1 fn))
6082 (end (nth 2 fn))
6083 (label (car fn))
6084 (referencep (/= (line-beginning-position) beg)))
6085 (when (and referencep (nth 3 fn))
6086 (save-excursion
6087 (goto-char beg)
6088 (search-forward (or label "fn:"))
6089 (org-remove-flyspell-overlays-in beg (match-end 0))))
6090 (add-text-properties beg end
6091 (list 'mouse-face 'highlight
6092 'keymap org-mouse-map
6093 'help-echo
6094 (if referencep "Footnote reference"
6095 "Footnote definition")
6096 'font-lock-fontified t
6097 'font-lock-multiline t
6098 'face 'org-footnote))))))
6100 (defun org-activate-dates (limit)
6101 "Add text properties for dates."
6102 (when (and (re-search-forward org-tsr-regexp-both limit t)
6103 (not (equal (char-before (match-beginning 0)) 91)))
6104 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6105 (add-text-properties (match-beginning 0) (match-end 0)
6106 (list 'mouse-face 'highlight
6107 'keymap org-mouse-map))
6108 (org-rear-nonsticky-at (match-end 0))
6109 (when org-display-custom-times
6110 (if (match-end 3)
6111 (org-display-custom-time (match-beginning 3) (match-end 3))
6112 (org-display-custom-time (match-beginning 1) (match-end 1))))
6115 (defvar-local org-target-link-regexp nil
6116 "Regular expression matching radio targets in plain text.")
6118 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6119 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6120 border border border))
6121 "Regular expression matching a link target.")
6123 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6124 "Regular expression matching a radio target.")
6126 (defconst org-any-target-regexp
6127 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6128 "Regular expression matching any target.")
6130 (defun org-activate-target-links (limit)
6131 "Add text properties for target matches."
6132 (when org-target-link-regexp
6133 (let ((case-fold-search t))
6134 (when (re-search-forward org-target-link-regexp limit t)
6135 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6136 (add-text-properties (match-beginning 1) (match-end 1)
6137 (list 'mouse-face 'highlight
6138 'keymap org-mouse-map
6139 'help-echo "Radio target link"
6140 'org-linked-text t))
6141 (org-rear-nonsticky-at (match-end 1))
6142 t))))
6144 (defun org-update-radio-target-regexp ()
6145 "Find all radio targets in this file and update the regular expression.
6146 Also refresh fontification if needed."
6147 (interactive)
6148 (let ((old-regexp org-target-link-regexp)
6149 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6150 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6151 (targets
6152 (org-with-wide-buffer
6153 (goto-char (point-min))
6154 (let (rtn)
6155 (while (re-search-forward org-radio-target-regexp nil t)
6156 ;; Make sure point is really within the object.
6157 (backward-char)
6158 (let ((obj (org-element-context)))
6159 (when (eq (org-element-type obj) 'radio-target)
6160 (cl-pushnew (org-element-property :value obj) rtn
6161 :test #'equal))))
6162 rtn))))
6163 (setq org-target-link-regexp
6164 (and targets
6165 (concat before-re
6166 (mapconcat
6167 (lambda (x)
6168 (replace-regexp-in-string
6169 " +" "\\s-+" (regexp-quote x) t t))
6170 targets
6171 "\\|")
6172 after-re)))
6173 (unless (equal old-regexp org-target-link-regexp)
6174 ;; Clean-up cache.
6175 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6176 ((not org-target-link-regexp) old-regexp)
6178 (concat before-re
6179 (mapconcat
6180 (lambda (re)
6181 (substring re (length before-re)
6182 (- (length after-re))))
6183 (list old-regexp org-target-link-regexp)
6184 "\\|")
6185 after-re)))))
6186 (org-with-wide-buffer
6187 (goto-char (point-min))
6188 (while (re-search-forward regexp nil t)
6189 (org-element-cache-refresh (match-beginning 1)))))
6190 ;; Re fontify buffer.
6191 (when (memq 'radio org-highlight-links)
6192 (org-restart-font-lock)))))
6194 (defun org-hide-wide-columns (limit)
6195 (let (s e)
6196 (setq s (text-property-any (point) (or limit (point-max))
6197 'org-cwidth t))
6198 (when s
6199 (setq e (next-single-property-change s 'org-cwidth))
6200 (add-text-properties s e '(invisible org-cwidth))
6201 (goto-char e)
6202 t)))
6204 (defvar org-latex-and-related-regexp nil
6205 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6207 (defun org-compute-latex-and-related-regexp ()
6208 "Compute regular expression for LaTeX, entities and sub/superscript.
6209 Result depends on variable `org-highlight-latex-and-related'."
6210 (setq-local
6211 org-latex-and-related-regexp
6212 (let* ((re-sub
6213 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6214 ((eq org-use-sub-superscripts '{})
6215 (list org-match-substring-with-braces-regexp))
6216 (org-use-sub-superscripts (list org-match-substring-regexp))))
6217 (re-latex
6218 (when (memq 'latex org-highlight-latex-and-related)
6219 (let ((matchers (plist-get org-format-latex-options :matchers)))
6220 (delq nil
6221 (mapcar (lambda (x)
6222 (and (member (car x) matchers) (nth 1 x)))
6223 org-latex-regexps)))))
6224 (re-entities
6225 (when (memq 'entities org-highlight-latex-and-related)
6226 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6227 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6229 (defun org-do-latex-and-related (limit)
6230 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6231 LIMIT bounds the search for syntax to highlight. Stop at first
6232 highlighted object, if any. Return t if some highlighting was
6233 done, nil otherwise."
6234 (when (org-string-nw-p org-latex-and-related-regexp)
6235 (catch 'found
6236 (while (re-search-forward org-latex-and-related-regexp limit t)
6237 (unless
6238 (cl-some
6239 (lambda (f)
6240 (memq f '(org-code org-verbatim underline org-special-keyword)))
6241 (save-excursion
6242 (goto-char (1+ (match-beginning 0)))
6243 (face-at-point nil t)))
6244 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6245 '(?_ ?^))
6247 0)))
6248 (font-lock-prepend-text-property
6249 (+ offset (match-beginning 0)) (match-end 0)
6250 'face 'org-latex-and-related)
6251 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6252 '(font-lock-multiline t)))
6253 (throw 'found t)))
6254 nil)))
6256 (defun org-restart-font-lock ()
6257 "Restart `font-lock-mode', to force refontification."
6258 (when (and (boundp 'font-lock-mode) font-lock-mode)
6259 (font-lock-mode -1)
6260 (font-lock-mode 1)))
6262 (defun org-activate-tags (limit)
6263 (when (re-search-forward
6264 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6265 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6266 (add-text-properties (match-beginning 1) (match-end 1)
6267 (list 'mouse-face 'highlight
6268 'keymap org-mouse-map))
6269 (org-rear-nonsticky-at (match-end 1))
6272 (defun org-outline-level ()
6273 "Compute the outline level of the heading at point.
6275 If this is called at a normal headline, the level is the number
6276 of stars. Use `org-reduced-level' to remove the effect of
6277 `org-odd-levels'. Unlike to `org-current-level', this function
6278 takes into consideration inlinetasks."
6279 (org-with-wide-buffer
6280 (end-of-line)
6281 (if (re-search-backward org-outline-regexp-bol nil t)
6282 (1- (- (match-end 0) (match-beginning 0)))
6283 0)))
6285 (defvar org-font-lock-keywords nil)
6287 (defsubst org-re-property (property &optional literal allow-null value)
6288 "Return a regexp matching a PROPERTY line.
6290 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6291 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6292 non-nil, match properties even without a value.
6294 Match group 3 is set to the value when it exists. If there is no
6295 value and ALLOW-NULL is non-nil, it is set to the empty string.
6297 With optional argument VALUE, match only property lines with
6298 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6299 unless LITERAL is non-nil."
6300 (concat
6301 "^\\(?4:[ \t]*\\)"
6302 (format "\\(?1::\\(?2:%s\\):\\)"
6303 (if literal property (regexp-quote property)))
6304 (cond (value
6305 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6306 (if literal value (regexp-quote value))))
6307 (allow-null
6308 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6310 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6312 (defconst org-property-re
6313 (org-re-property "\\S-+" 'literal t)
6314 "Regular expression matching a property line.
6315 There are four matching groups:
6316 1: :PROPKEY: including the leading and trailing colon,
6317 2: PROPKEY without the leading and trailing colon,
6318 3: PROPVAL without leading or trailing spaces,
6319 4: the indentation of the current line,
6320 5: trailing whitespace.")
6322 (defvar org-font-lock-hook nil
6323 "Functions to be called for special font lock stuff.")
6325 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6327 (defvar org-font-lock-set-keywords-hook nil
6328 "Functions that can manipulate `org-font-lock-extra-keywords'.
6329 This is called after `org-font-lock-extra-keywords' is defined, but before
6330 it is installed to be used by font lock. This can be useful if something
6331 needs to be inserted at a specific position in the font-lock sequence.")
6333 (defun org-font-lock-hook (limit)
6334 "Run `org-font-lock-hook' within LIMIT."
6335 (run-hook-with-args 'org-font-lock-hook limit))
6337 (defun org-set-font-lock-defaults ()
6338 "Set font lock defaults for the current buffer."
6339 (let* ((em org-fontify-emphasized-text)
6340 (lk org-highlight-links)
6341 (org-font-lock-extra-keywords
6342 (list
6343 ;; Call the hook
6344 '(org-font-lock-hook)
6345 ;; Headlines
6346 `(,(if org-fontify-whole-heading-line
6347 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6348 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6349 (1 (org-get-level-face 1))
6350 (2 (org-get-level-face 2))
6351 (3 (org-get-level-face 3)))
6352 ;; Table lines
6353 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6354 (1 'org-table t))
6355 ;; Table internals
6356 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6357 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6358 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6359 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6360 ;; Drawers
6361 '(org-fontify-drawers)
6362 ;; Properties
6363 (list org-property-re
6364 '(1 'org-special-keyword t)
6365 '(3 'org-property-value t))
6366 ;; Link related fontification.
6367 '(org-activate-links)
6368 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6369 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6370 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6371 (when (memq 'footnote lk) '(org-activate-footnote-links))
6372 ;; Targets.
6373 (list org-any-target-regexp '(0 'org-target t))
6374 ;; Diary sexps.
6375 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6376 ;; Macro
6377 '(org-fontify-macros)
6378 '(org-hide-wide-columns (0 nil append))
6379 ;; TODO keyword
6380 (list (format org-heading-keyword-regexp-format
6381 org-todo-regexp)
6382 '(2 (org-get-todo-face 2) t))
6383 ;; DONE
6384 (if org-fontify-done-headline
6385 (list (format org-heading-keyword-regexp-format
6386 (concat
6387 "\\(?:"
6388 (mapconcat 'regexp-quote org-done-keywords "\\|")
6389 "\\)"))
6390 '(2 'org-headline-done t))
6391 nil)
6392 ;; Priorities
6393 '(org-font-lock-add-priority-faces)
6394 ;; Tags
6395 '(org-font-lock-add-tag-faces)
6396 ;; Tags groups
6397 (when (and org-group-tags org-tag-groups-alist)
6398 (list (concat org-outline-regexp-bol ".+\\(:"
6399 (regexp-opt (mapcar 'car org-tag-groups-alist))
6400 ":\\).*$")
6401 '(1 'org-tag-group prepend)))
6402 ;; Special keywords
6403 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6404 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6405 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6406 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6407 ;; Emphasis
6408 (when em '(org-do-emphasis-faces))
6409 ;; Checkboxes
6410 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6411 1 'org-checkbox prepend)
6412 (when (cdr (assq 'checkbox org-list-automatic-rules))
6413 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6414 (0 (org-get-checkbox-statistics-face) t)))
6415 ;; Description list items
6416 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6417 1 'org-list-dt prepend)
6418 ;; ARCHIVEd headings
6419 (list (concat
6420 org-outline-regexp-bol
6421 "\\(.*:" org-archive-tag ":.*\\)")
6422 '(1 'org-archived prepend))
6423 ;; Specials
6424 '(org-do-latex-and-related)
6425 '(org-fontify-entities)
6426 '(org-raise-scripts)
6427 ;; Code
6428 '(org-activate-code (1 'org-code t))
6429 ;; COMMENT
6430 (list (format
6431 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6432 org-todo-regexp
6433 org-comment-string)
6434 '(9 'org-special-keyword t))
6435 ;; Blocks and meta lines
6436 '(org-fontify-meta-lines-and-blocks))))
6437 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6438 (run-hooks 'org-font-lock-set-keywords-hook)
6439 ;; Now set the full font-lock-keywords
6440 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6441 (setq-local font-lock-defaults
6442 '(org-font-lock-keywords t nil nil backward-paragraph))
6443 (kill-local-variable 'font-lock-keywords)
6444 nil))
6446 (defun org-toggle-pretty-entities ()
6447 "Toggle the composition display of entities as UTF8 characters."
6448 (interactive)
6449 (setq-local org-pretty-entities (not org-pretty-entities))
6450 (org-restart-font-lock)
6451 (if org-pretty-entities
6452 (message "Entities are now displayed as UTF8 characters")
6453 (save-restriction
6454 (widen)
6455 (decompose-region (point-min) (point-max))
6456 (message "Entities are now displayed as plain text"))))
6458 (defvar-local org-custom-properties-overlays nil
6459 "List of overlays used for custom properties.")
6461 (defun org-toggle-custom-properties-visibility ()
6462 "Display or hide properties in `org-custom-properties'."
6463 (interactive)
6464 (if org-custom-properties-overlays
6465 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6466 (setq org-custom-properties-overlays nil))
6467 (when org-custom-properties
6468 (org-with-wide-buffer
6469 (goto-char (point-min))
6470 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6471 (while (re-search-forward regexp nil t)
6472 (let ((end (cdr (save-match-data (org-get-property-block)))))
6473 (when (and end (< (point) end))
6474 ;; Hide first custom property in current drawer.
6475 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6476 (overlay-put o 'invisible t)
6477 (overlay-put o 'org-custom-property t)
6478 (push o org-custom-properties-overlays))
6479 ;; Hide additional custom properties in the same drawer.
6480 (while (re-search-forward regexp end t)
6481 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6482 (overlay-put o 'invisible t)
6483 (overlay-put o 'org-custom-property t)
6484 (push o org-custom-properties-overlays)))))
6485 ;; Each entry is limited to a single property drawer.
6486 (outline-next-heading)))))))
6488 (defun org-fontify-entities (limit)
6489 "Find an entity to fontify."
6490 (let (ee)
6491 (when org-pretty-entities
6492 (catch 'match
6493 ;; "\_ "-family is left out on purpose. Only the first one,
6494 ;; i.e., "\_ ", could be fontified anyway, and it would be
6495 ;; confusing when adding a second white space character.
6496 (while (re-search-forward
6497 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6498 limit t)
6499 (when (and (not (org-at-comment-p))
6500 (setq ee (org-entity-get (match-string 1)))
6501 (= (length (nth 6 ee)) 1))
6502 (let* ((end (if (equal (match-string 2) "{}")
6503 (match-end 2)
6504 (match-end 1))))
6505 (add-text-properties
6506 (match-beginning 0) end
6507 (list 'font-lock-fontified t))
6508 (compose-region (match-beginning 0) end
6509 (nth 6 ee) nil)
6510 (backward-char 1)
6511 (throw 'match t))))
6512 nil))))
6514 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6515 "Fontify string S like in Org mode."
6516 (with-temp-buffer
6517 (insert s)
6518 (let ((org-odd-levels-only odd-levels))
6519 (org-mode)
6520 (org-font-lock-ensure)
6521 (buffer-string))))
6523 (defvar org-m nil)
6524 (defvar org-l nil)
6525 (defvar org-f nil)
6526 (defun org-get-level-face (n)
6527 "Get the right face for match N in font-lock matching of headlines."
6528 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6529 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6530 (if org-cycle-level-faces
6531 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6532 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6533 (cond
6534 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6535 ((eq n 2) org-f)
6536 (t (unless org-level-color-stars-only org-f))))
6538 (defun org-face-from-face-or-color (context inherit face-or-color)
6539 "Create a face list that inherits INHERIT, but sets the foreground color.
6540 When FACE-OR-COLOR is not a string, just return it."
6541 (if (stringp face-or-color)
6542 (list :inherit inherit
6543 (cdr (assoc context org-faces-easy-properties))
6544 face-or-color)
6545 face-or-color))
6547 (defun org-get-todo-face (kwd)
6548 "Get the right face for a TODO keyword KWD.
6549 If KWD is a number, get the corresponding match group."
6550 (when (numberp kwd) (setq kwd (match-string kwd)))
6551 (or (org-face-from-face-or-color
6552 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6553 (and (member kwd org-done-keywords) 'org-done)
6554 'org-todo))
6556 (defun org-get-priority-face (priority)
6557 "Get the right face for PRIORITY.
6558 PRIORITY is a character."
6559 (or (org-face-from-face-or-color
6560 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6561 'org-priority))
6563 (defun org-get-tag-face (tag)
6564 "Get the right face for TAG.
6565 If TAG is a number, get the corresponding match group."
6566 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6567 (or (org-face-from-face-or-color
6568 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6569 'org-tag)))
6571 (defun org-font-lock-add-priority-faces (limit)
6572 "Add the special priority faces."
6573 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6574 (add-text-properties
6575 (match-beginning 1) (match-end 1)
6576 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6577 'font-lock-fontified t))))
6579 (defun org-font-lock-add-tag-faces (limit)
6580 "Add the special tag faces."
6581 (when (and org-tag-faces org-tags-special-faces-re)
6582 (while (re-search-forward org-tags-special-faces-re limit t)
6583 (add-text-properties (match-beginning 1) (match-end 1)
6584 (list 'face (org-get-tag-face 1)
6585 'font-lock-fontified t))
6586 (backward-char 1))))
6588 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6589 "Remove fontification and activation overlays from links."
6590 (font-lock-default-unfontify-region beg end)
6591 (let* ((buffer-undo-list t)
6592 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6593 (inhibit-modification-hooks t)
6594 deactivate-mark buffer-file-name buffer-file-truename)
6595 (decompose-region beg end)
6596 (remove-text-properties beg end
6597 '(mouse-face t keymap t org-linked-text t
6598 invisible t intangible t
6599 org-emphasis t))
6600 (org-remove-font-lock-display-properties beg end)))
6602 (defconst org-script-display '(((raise -0.3) (height 0.7))
6603 ((raise 0.3) (height 0.7))
6604 ((raise -0.5))
6605 ((raise 0.5)))
6606 "Display properties for showing superscripts and subscripts.")
6608 (defun org-remove-font-lock-display-properties (beg end)
6609 "Remove specific display properties that have been added by font lock.
6610 The will remove the raise properties that are used to show superscripts
6611 and subscripts."
6612 (let (next prop)
6613 (while (< beg end)
6614 (setq next (next-single-property-change beg 'display nil end)
6615 prop (get-text-property beg 'display))
6616 (when (member prop org-script-display)
6617 (put-text-property beg next 'display nil))
6618 (setq beg next))))
6620 (defun org-raise-scripts (limit)
6621 "Add raise properties to sub/superscripts."
6622 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6623 (re-search-forward
6624 (if (eq org-use-sub-superscripts t)
6625 org-match-substring-regexp
6626 org-match-substring-with-braces-regexp)
6627 limit t))
6628 (let* ((pos (point)) table-p comment-p
6629 (mpos (match-beginning 3))
6630 (emph-p (get-text-property mpos 'org-emphasis))
6631 (link-p (get-text-property mpos 'mouse-face))
6632 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6633 (goto-char (point-at-bol))
6634 (setq table-p (looking-at-p org-table-dataline-regexp)
6635 comment-p (looking-at-p "^[ \t]*#[ +]"))
6636 (goto-char pos)
6637 ;; Handle a_b^c
6638 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6639 (unless (or comment-p emph-p link-p keyw-p)
6640 (put-text-property (match-beginning 3) (match-end 0)
6641 'display
6642 (if (equal (char-after (match-beginning 2)) ?^)
6643 (nth (if table-p 3 1) org-script-display)
6644 (nth (if table-p 2 0) org-script-display)))
6645 (add-text-properties (match-beginning 2) (match-end 2)
6646 (list 'invisible t
6647 'org-dwidth t 'org-dwidth-n 1))
6648 (if (and (eq (char-after (match-beginning 3)) ?{)
6649 (eq (char-before (match-end 3)) ?}))
6650 (progn
6651 (add-text-properties
6652 (match-beginning 3) (1+ (match-beginning 3))
6653 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6654 (add-text-properties
6655 (1- (match-end 3)) (match-end 3)
6656 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6657 t)))
6659 ;;;; Visibility cycling, including org-goto and indirect buffer
6661 ;;; Cycling
6663 (defvar-local org-cycle-global-status nil)
6664 (put 'org-cycle-global-status 'org-state t)
6665 (defvar-local org-cycle-subtree-status nil)
6666 (put 'org-cycle-subtree-status 'org-state t)
6668 (defvar org-inlinetask-min-level)
6670 (defun org-unlogged-message (&rest args)
6671 "Display a message, but avoid logging it in the *Messages* buffer."
6672 (let ((message-log-max nil))
6673 (apply 'message args)))
6675 ;;;###autoload
6676 (defun org-cycle (&optional arg)
6677 "TAB-action and visibility cycling for Org mode.
6679 This is the command invoked in Org mode by the `TAB' key. Its main
6680 purpose is outline visibility cycling, but it also invokes other actions
6681 in special contexts.
6683 When this function is called with a `\\[universal-argument]' prefix, rotate \
6684 the entire
6685 buffer through 3 states (global cycling)
6686 1. OVERVIEW: Show only top-level headlines.
6687 2. CONTENTS: Show all headlines of all levels, but no body text.
6688 3. SHOW ALL: Show everything.
6690 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6691 switch to the startup visibility,
6692 determined by the variable `org-startup-folded', and by any VISIBILITY
6693 properties in the buffer.
6695 With a `\\[universal-argument] \\[universal-argument] \
6696 \\[universal-argument]' prefix argument, show the entire buffer, including
6697 any drawers.
6699 When inside a table, re-align the table and move to the next field.
6701 When point is at the beginning of a headline, rotate the subtree started
6702 by this line through 3 different states (local cycling)
6703 1. FOLDED: Only the main headline is shown.
6704 2. CHILDREN: The main headline and the direct children are shown.
6705 From this state, you can move to one of the children
6706 and zoom in further.
6707 3. SUBTREE: Show the entire subtree, including body text.
6708 If there is no subtree, switch directly from CHILDREN to FOLDED.
6710 When point is at the beginning of an empty headline and the variable
6711 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6712 of the headline by demoting and promoting it to likely levels. This
6713 speeds up creation document structure by pressing `TAB' once or several
6714 times right after creating a new headline.
6716 When there is a numeric prefix, go up to a heading with level ARG, do
6717 a `show-subtree' and return to the previous cursor position. If ARG
6718 is negative, go up that many levels.
6720 When point is not at the beginning of a headline, execute the global
6721 binding for `TAB', which is re-indenting the line. See the option
6722 `org-cycle-emulate-tab' for details.
6724 As a special case, if point is at the beginning of the buffer and there is
6725 no headline in line 1, this function will act as if called with prefix arg
6726 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6727 prefix arg, but only
6728 if the variable `org-cycle-global-at-bob' is t."
6729 (interactive "P")
6730 (org-load-modules-maybe)
6731 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6732 (and org-cycle-level-after-item/entry-creation
6733 (or (org-cycle-level)
6734 (org-cycle-item-indentation))))
6735 (let* ((limit-level
6736 (or org-cycle-max-level
6737 (and (boundp 'org-inlinetask-min-level)
6738 org-inlinetask-min-level
6739 (1- org-inlinetask-min-level))))
6740 (nstars (and limit-level
6741 (if org-odd-levels-only
6742 (and limit-level (1- (* limit-level 2)))
6743 limit-level)))
6744 (org-outline-regexp
6745 (if (not (derived-mode-p 'org-mode))
6746 outline-regexp
6747 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6748 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6749 (not (looking-at org-outline-regexp))))
6750 (org-cycle-hook
6751 (if bob-special
6752 (delq 'org-optimize-window-after-visibility-change
6753 (copy-sequence org-cycle-hook))
6754 org-cycle-hook))
6755 (pos (point)))
6757 (cond
6759 ((equal arg '(16))
6760 (setq last-command 'dummy)
6761 (org-set-startup-visibility)
6762 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6764 ((equal arg '(64))
6765 (outline-show-all)
6766 (org-unlogged-message "Entire buffer visible, including drawers"))
6768 ((equal arg '(4)) (org-cycle-internal-global))
6770 ;; Try hiding block at point.
6771 ((org-hide-block-toggle-maybe))
6773 ;; Try cdlatex TAB completion
6774 ((org-try-cdlatex-tab))
6776 ;; Table: enter it or move to the next field.
6777 ((org-at-table-p 'any)
6778 (if (org-at-table.el-p)
6779 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6780 Use `\\[org-edit-special]' to edit table.el tables"))
6781 (if arg (org-table-edit-field t)
6782 (org-table-justify-field-maybe)
6783 (call-interactively 'org-table-next-field))))
6785 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6787 ;; Global cycling: delegate to `org-cycle-internal-global'.
6788 (bob-special (org-cycle-internal-global))
6790 ;; Drawers: delegate to `org-flag-drawer'.
6791 ((save-excursion
6792 (beginning-of-line 1)
6793 (looking-at org-drawer-regexp))
6794 (org-flag-drawer ; toggle block visibility
6795 (not (get-char-property (match-end 0) 'invisible))))
6797 ;; Show-subtree, ARG levels up from here.
6798 ((integerp arg)
6799 (save-excursion
6800 (org-back-to-heading)
6801 (outline-up-heading (if (< arg 0) (- arg)
6802 (- (funcall outline-level) arg)))
6803 (org-show-subtree)))
6805 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6806 ((and (featurep 'org-inlinetask)
6807 (org-inlinetask-at-task-p)
6808 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6809 (org-inlinetask-toggle-visibility))
6811 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6812 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6813 (save-excursion (move-beginning-of-line 1)
6814 (looking-at org-outline-regexp)))
6815 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6816 (org-cycle-internal-local))
6818 ;; From there: TAB emulation and template completion.
6819 (buffer-read-only (org-back-to-heading))
6821 ((run-hook-with-args-until-success
6822 'org-tab-after-check-for-cycling-hook))
6824 ((org-try-structure-completion))
6826 ((run-hook-with-args-until-success
6827 'org-tab-before-tab-emulation-hook))
6829 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6830 (or (not (bolp))
6831 (not (looking-at org-outline-regexp))))
6832 (call-interactively (global-key-binding "\t")))
6834 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6835 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6836 (or (and (eq org-cycle-emulate-tab 'white)
6837 (= (match-end 0) (point-at-eol)))
6838 (and (eq org-cycle-emulate-tab 'whitestart)
6839 (>= (match-end 0) pos))))
6841 (eq org-cycle-emulate-tab t))
6842 (call-interactively (global-key-binding "\t")))
6844 (t (save-excursion
6845 (org-back-to-heading)
6846 (org-cycle)))))))
6848 (defun org-cycle-internal-global ()
6849 "Do the global cycling action."
6850 ;; Hack to avoid display of messages for .org attachments in Gnus
6851 (let ((ga (string-match "\\*fontification" (buffer-name))))
6852 (cond
6853 ((and (eq last-command this-command)
6854 (eq org-cycle-global-status 'overview))
6855 ;; We just created the overview - now do table of contents
6856 ;; This can be slow in very large buffers, so indicate action
6857 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6858 (unless ga (org-unlogged-message "CONTENTS..."))
6859 (org-content)
6860 (unless ga (org-unlogged-message "CONTENTS...done"))
6861 (setq org-cycle-global-status 'contents)
6862 (run-hook-with-args 'org-cycle-hook 'contents))
6864 ((and (eq last-command this-command)
6865 (eq org-cycle-global-status 'contents))
6866 ;; We just showed the table of contents - now show everything
6867 (run-hook-with-args 'org-pre-cycle-hook 'all)
6868 (outline-show-all)
6869 (unless ga (org-unlogged-message "SHOW ALL"))
6870 (setq org-cycle-global-status 'all)
6871 (run-hook-with-args 'org-cycle-hook 'all))
6874 ;; Default action: go to overview
6875 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6876 (org-overview)
6877 (unless ga (org-unlogged-message "OVERVIEW"))
6878 (setq org-cycle-global-status 'overview)
6879 (run-hook-with-args 'org-cycle-hook 'overview)))))
6881 (defvar org-called-with-limited-levels nil
6882 "Non-nil when `org-with-limited-levels' is currently active.")
6884 (defun org-invisible-p (&optional pos)
6885 "Non-nil if the character after POS is invisible.
6886 If POS is nil, use `point' instead."
6887 (get-char-property (or pos (point)) 'invisible))
6889 (defun org-cycle-internal-local ()
6890 "Do the local cycling action."
6891 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6892 ;; First, determine end of headline (EOH), end of subtree or item
6893 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6894 (save-excursion
6895 (if (org-at-item-p)
6896 (progn
6897 (beginning-of-line)
6898 (setq struct (org-list-struct))
6899 (setq eoh (point-at-eol))
6900 (setq eos (org-list-get-item-end-before-blank (point) struct))
6901 (setq has-children (org-list-has-child-p (point) struct)))
6902 (org-back-to-heading)
6903 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6904 (setq eos (save-excursion (org-end-of-subtree t t)
6905 (when (bolp) (backward-char)) (point)))
6906 (setq has-children
6907 (or (save-excursion
6908 (let ((level (funcall outline-level)))
6909 (outline-next-heading)
6910 (and (org-at-heading-p t)
6911 (> (funcall outline-level) level))))
6912 (save-excursion
6913 (org-list-search-forward (org-item-beginning-re) eos t)))))
6914 ;; Determine end invisible part of buffer (EOL)
6915 (beginning-of-line 2)
6916 (while (and (not (eobp)) ;This is like `next-line'.
6917 (get-char-property (1- (point)) 'invisible))
6918 (goto-char (next-single-char-property-change (point) 'invisible))
6919 (and (eolp) (beginning-of-line 2)))
6920 (setq eol (point)))
6921 ;; Find out what to do next and set `this-command'
6922 (cond
6923 ((= eos eoh)
6924 ;; Nothing is hidden behind this heading
6925 (unless (org-before-first-heading-p)
6926 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6927 (org-unlogged-message "EMPTY ENTRY")
6928 (setq org-cycle-subtree-status nil)
6929 (save-excursion
6930 (goto-char eos)
6931 (outline-next-heading)
6932 (when (org-invisible-p) (org-flag-heading nil))))
6933 ((and (or (>= eol eos)
6934 (not (string-match "\\S-" (buffer-substring eol eos))))
6935 (or has-children
6936 (not (setq children-skipped
6937 org-cycle-skip-children-state-if-no-children))))
6938 ;; Entire subtree is hidden in one line: children view
6939 (unless (org-before-first-heading-p)
6940 (run-hook-with-args 'org-pre-cycle-hook 'children))
6941 (if (org-at-item-p)
6942 (org-list-set-item-visibility (point-at-bol) struct 'children)
6943 (org-show-entry)
6944 (org-with-limited-levels (org-show-children))
6945 ;; FIXME: This slows down the func way too much.
6946 ;; How keep drawers hidden in subtree anyway?
6947 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6948 ;; (org-cycle-hide-drawers 'subtree))
6950 ;; Fold every list in subtree to top-level items.
6951 (when (eq org-cycle-include-plain-lists 'integrate)
6952 (save-excursion
6953 (org-back-to-heading)
6954 (while (org-list-search-forward (org-item-beginning-re) eos t)
6955 (beginning-of-line 1)
6956 (let* ((struct (org-list-struct))
6957 (prevs (org-list-prevs-alist struct))
6958 (end (org-list-get-bottom-point struct)))
6959 (dolist (e (org-list-get-all-items (point) struct prevs))
6960 (org-list-set-item-visibility e struct 'folded))
6961 (goto-char (if (< end eos) end eos)))))))
6962 (org-unlogged-message "CHILDREN")
6963 (save-excursion
6964 (goto-char eos)
6965 (outline-next-heading)
6966 (when (org-invisible-p) (org-flag-heading nil)))
6967 (setq org-cycle-subtree-status 'children)
6968 (unless (org-before-first-heading-p)
6969 (run-hook-with-args 'org-cycle-hook 'children)))
6970 ((or children-skipped
6971 (and (eq last-command this-command)
6972 (eq org-cycle-subtree-status 'children)))
6973 ;; We just showed the children, or no children are there,
6974 ;; now show everything.
6975 (unless (org-before-first-heading-p)
6976 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6977 (outline-flag-region eoh eos nil)
6978 (org-unlogged-message
6979 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6980 (setq org-cycle-subtree-status 'subtree)
6981 (unless (org-before-first-heading-p)
6982 (run-hook-with-args 'org-cycle-hook 'subtree)))
6984 ;; Default action: hide the subtree.
6985 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6986 (outline-flag-region eoh eos t)
6987 (org-unlogged-message "FOLDED")
6988 (setq org-cycle-subtree-status 'folded)
6989 (unless (org-before-first-heading-p)
6990 (run-hook-with-args 'org-cycle-hook 'folded))))))
6992 ;;;###autoload
6993 (defun org-global-cycle (&optional arg)
6994 "Cycle the global visibility. For details see `org-cycle'.
6995 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6996 With a numeric prefix, show all headlines up to that level."
6997 (interactive "P")
6998 (let ((org-cycle-include-plain-lists
6999 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7000 (cond
7001 ((integerp arg)
7002 (outline-show-all)
7003 (outline-hide-sublevels arg)
7004 (setq org-cycle-global-status 'contents))
7005 ((equal arg '(4))
7006 (org-set-startup-visibility)
7007 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7009 (org-cycle '(4))))))
7011 (defun org-set-startup-visibility ()
7012 "Set the visibility required by startup options and properties."
7013 (cond
7014 ((eq org-startup-folded t)
7015 (org-overview))
7016 ((eq org-startup-folded 'content)
7017 (org-content))
7018 ((or (eq org-startup-folded 'showeverything)
7019 (eq org-startup-folded nil))
7020 (outline-show-all)))
7021 (unless (eq org-startup-folded 'showeverything)
7022 (when org-hide-block-startup (org-hide-block-all))
7023 (org-set-visibility-according-to-property 'no-cleanup)
7024 (org-cycle-hide-archived-subtrees 'all)
7025 (org-cycle-hide-drawers 'all)
7026 (org-cycle-show-empty-lines t)))
7028 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7029 "Switch subtree visibilities according to :VISIBILITY: property."
7030 (interactive)
7031 (org-with-wide-buffer
7032 (goto-char (point-min))
7033 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7034 (if (not (org-at-property-p)) (outline-next-heading)
7035 (let ((state (match-string 3)))
7036 (save-excursion
7037 (org-back-to-heading t)
7038 (outline-hide-subtree)
7039 (org-reveal)
7040 (cond
7041 ((equal state "folded")
7042 (outline-hide-subtree))
7043 ((equal state "children")
7044 (org-show-hidden-entry)
7045 (org-show-children))
7046 ((equal state "content")
7047 (save-excursion
7048 (save-restriction
7049 (org-narrow-to-subtree)
7050 (org-content))))
7051 ((member state '("all" "showall"))
7052 (outline-show-subtree)))))))
7053 (unless no-cleanup
7054 (org-cycle-hide-archived-subtrees 'all)
7055 (org-cycle-hide-drawers 'all)
7056 (org-cycle-show-empty-lines 'all))))
7058 ;; This function uses outline-regexp instead of the more fundamental
7059 ;; org-outline-regexp so that org-cycle-global works outside of Org
7060 ;; buffers, where outline-regexp is needed.
7061 (defun org-overview ()
7062 "Switch to overview mode, showing only top-level headlines.
7063 This shows all headlines with a level equal or greater than the level
7064 of the first headline in the buffer. This is important, because if the
7065 first headline is not level one, then (hide-sublevels 1) gives confusing
7066 results."
7067 (interactive)
7068 (save-excursion
7069 (let ((level
7070 (save-excursion
7071 (goto-char (point-min))
7072 (when (re-search-forward (concat "^" outline-regexp) nil t)
7073 (goto-char (match-beginning 0))
7074 (funcall outline-level)))))
7075 (and level (outline-hide-sublevels level)))))
7077 (defun org-content (&optional arg)
7078 "Show all headlines in the buffer, like a table of contents.
7079 With numerical argument N, show content up to level N."
7080 (interactive "P")
7081 (org-overview)
7082 (save-excursion
7083 ;; Visit all headings and show their offspring
7084 (and (integerp arg) (org-overview))
7085 (goto-char (point-max))
7086 (catch 'exit
7087 (while (and (progn (condition-case nil
7088 (outline-previous-visible-heading 1)
7089 (error (goto-char (point-min))))
7091 (looking-at org-outline-regexp))
7092 (if (integerp arg)
7093 (org-show-children (1- arg))
7094 (outline-show-branches))
7095 (when (bobp) (throw 'exit nil))))))
7097 (defun org-optimize-window-after-visibility-change (state)
7098 "Adjust the window after a change in outline visibility.
7099 This function is the default value of the hook `org-cycle-hook'."
7100 (when (get-buffer-window (current-buffer))
7101 (cond
7102 ((eq state 'content) nil)
7103 ((eq state 'all) nil)
7104 ((eq state 'folded) nil)
7105 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7106 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7108 (defun org-remove-empty-overlays-at (pos)
7109 "Remove outline overlays that do not contain non-white stuff."
7110 (dolist (o (overlays-at pos))
7111 (and (eq 'outline (overlay-get o 'invisible))
7112 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7113 (overlay-end o))))
7114 (delete-overlay o))))
7116 (defun org-clean-visibility-after-subtree-move ()
7117 "Fix visibility issues after moving a subtree."
7118 ;; First, find a reasonable region to look at:
7119 ;; Start two siblings above, end three below
7120 (let* ((beg (save-excursion
7121 (and (org-get-last-sibling)
7122 (org-get-last-sibling))
7123 (point)))
7124 (end (save-excursion
7125 (and (org-get-next-sibling)
7126 (org-get-next-sibling)
7127 (org-get-next-sibling))
7128 (if (org-at-heading-p)
7129 (point-at-eol)
7130 (point))))
7131 (level (looking-at "\\*+"))
7132 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7133 (save-excursion
7134 (save-restriction
7135 (narrow-to-region beg end)
7136 (when re
7137 ;; Properly fold already folded siblings
7138 (goto-char (point-min))
7139 (while (re-search-forward re nil t)
7140 (when (and (not (org-invisible-p))
7141 (save-excursion
7142 (goto-char (point-at-eol)) (org-invisible-p)))
7143 (outline-hide-entry))))
7144 (org-cycle-show-empty-lines 'overview)
7145 (org-cycle-hide-drawers 'overview)))))
7147 (defun org-cycle-show-empty-lines (state)
7148 "Show empty lines above all visible headlines.
7149 The region to be covered depends on STATE when called through
7150 `org-cycle-hook'. Lisp program can use t for STATE to get the
7151 entire buffer covered. Note that an empty line is only shown if there
7152 are at least `org-cycle-separator-lines' empty lines before the headline."
7153 (when (/= org-cycle-separator-lines 0)
7154 (save-excursion
7155 (let* ((n (abs org-cycle-separator-lines))
7156 (re (cond
7157 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7158 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7159 (t (let ((ns (number-to-string (- n 2))))
7160 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7161 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7162 beg end)
7163 (cond
7164 ((memq state '(overview contents t))
7165 (setq beg (point-min) end (point-max)))
7166 ((memq state '(children folded))
7167 (setq beg (point)
7168 end (progn (org-end-of-subtree t t)
7169 (line-beginning-position 2)))))
7170 (when beg
7171 (goto-char beg)
7172 (while (re-search-forward re end t)
7173 (unless (get-char-property (match-end 1) 'invisible)
7174 (let ((e (match-end 1))
7175 (b (if (>= org-cycle-separator-lines 0)
7176 (match-beginning 1)
7177 (save-excursion
7178 (goto-char (match-beginning 0))
7179 (skip-chars-backward " \t\n")
7180 (line-end-position)))))
7181 (outline-flag-region b e nil))))))))
7182 ;; Never hide empty lines at the end of the file.
7183 (save-excursion
7184 (goto-char (point-max))
7185 (outline-previous-heading)
7186 (outline-end-of-heading)
7187 (when (and (looking-at "[ \t\n]+")
7188 (= (match-end 0) (point-max)))
7189 (outline-flag-region (point) (match-end 0) nil))))
7191 (defun org-show-empty-lines-in-parent ()
7192 "Move to the parent and re-show empty lines before visible headlines."
7193 (save-excursion
7194 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7195 (org-cycle-show-empty-lines context))))
7197 (defun org-files-list ()
7198 "Return `org-agenda-files' list, plus all open Org files.
7199 This is useful for operations that need to scan all of a user's
7200 open and agenda-wise Org files."
7201 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7202 (dolist (buf (buffer-list))
7203 (with-current-buffer buf
7204 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7205 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7206 files))
7208 (defsubst org-entry-beginning-position ()
7209 "Return the beginning position of the current entry."
7210 (save-excursion (org-back-to-heading t) (point)))
7212 (defsubst org-entry-end-position ()
7213 "Return the end position of the current entry."
7214 (save-excursion (outline-next-heading) (point)))
7216 (defun org-cycle-hide-drawers (state &optional exceptions)
7217 "Re-hide all drawers after a visibility state change.
7218 When non-nil, optional argument EXCEPTIONS is a list of strings
7219 specifying which drawers should not be hidden."
7220 (when (and (derived-mode-p 'org-mode)
7221 (not (memq state '(overview folded contents))))
7222 (save-excursion
7223 (let* ((globalp (memq state '(contents all)))
7224 (beg (if globalp (point-min) (point)))
7225 (end (if globalp (point-max)
7226 (if (eq state 'children)
7227 (save-excursion (outline-next-heading) (point))
7228 (org-end-of-subtree t)))))
7229 (goto-char beg)
7230 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7231 (unless (member-ignore-case (match-string 1) exceptions)
7232 (let ((drawer (org-element-at-point)))
7233 (when (memq (org-element-type drawer) '(drawer property-drawer))
7234 (org-flag-drawer t drawer)
7235 ;; Make sure to skip drawer entirely or we might flag
7236 ;; it another time when matching its ending line with
7237 ;; `org-drawer-regexp'.
7238 (goto-char (org-element-property :end drawer))))))))))
7240 (defun org-flag-drawer (flag &optional element)
7241 "When FLAG is non-nil, hide the drawer we are at.
7242 Otherwise make it visible. When optional argument ELEMENT is
7243 a parsed drawer, as returned by `org-element-at-point', hide or
7244 show that drawer instead."
7245 (let ((drawer (or element
7246 (and (save-excursion
7247 (beginning-of-line)
7248 (looking-at-p org-drawer-regexp))
7249 (org-element-at-point)))))
7250 (when (memq (org-element-type drawer) '(drawer property-drawer))
7251 (let ((post (org-element-property :post-affiliated drawer)))
7252 (save-excursion
7253 (outline-flag-region
7254 (progn (goto-char post) (line-end-position))
7255 (progn (goto-char (org-element-property :end drawer))
7256 (skip-chars-backward " \r\t\n")
7257 (line-end-position))
7258 flag))
7259 ;; When the drawer is hidden away, make sure point lies in
7260 ;; a visible part of the buffer.
7261 (when (and flag (> (line-beginning-position) post))
7262 (goto-char post))))))
7264 (defun org-subtree-end-visible-p ()
7265 "Is the end of the current subtree visible?"
7266 (pos-visible-in-window-p
7267 (save-excursion (org-end-of-subtree t) (point))))
7269 (defun org-first-headline-recenter ()
7270 "Move cursor to the first headline and recenter the headline."
7271 (let ((window (get-buffer-window)))
7272 (when window
7273 (goto-char (point-min))
7274 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7275 (set-window-start window (line-beginning-position))))))
7277 ;;; Saving and restoring visibility
7279 (defun org-outline-overlay-data (&optional use-markers)
7280 "Return a list of the locations of all outline overlays.
7281 These are overlays with the `invisible' property value `outline'.
7282 The return value is a list of cons cells, with start and stop
7283 positions for each overlay.
7284 If USE-MARKERS is set, return the positions as markers."
7285 (let (beg end)
7286 (org-with-wide-buffer
7287 (delq nil
7288 (mapcar (lambda (o)
7289 (when (eq (overlay-get o 'invisible) 'outline)
7290 (setq beg (overlay-start o)
7291 end (overlay-end o))
7292 (and beg end (> end beg)
7293 (if use-markers
7294 (cons (copy-marker beg)
7295 (copy-marker end t))
7296 (cons beg end)))))
7297 (overlays-in (point-min) (point-max)))))))
7299 (defun org-set-outline-overlay-data (data)
7300 "Create visibility overlays for all positions in DATA.
7301 DATA should have been made by `org-outline-overlay-data'."
7302 (org-with-wide-buffer
7303 (outline-show-all)
7304 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7306 ;;; Folding of blocks
7308 (defvar-local org-hide-block-overlays nil
7309 "Overlays hiding blocks.")
7311 (defun org-block-map (function &optional start end)
7312 "Call FUNCTION at the head of all source blocks in the current buffer.
7313 Optional arguments START and END can be used to limit the range."
7314 (let ((start (or start (point-min)))
7315 (end (or end (point-max))))
7316 (save-excursion
7317 (goto-char start)
7318 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7319 (save-excursion
7320 (save-match-data
7321 (goto-char (match-beginning 0))
7322 (funcall function)))))))
7324 (defun org-hide-block-toggle-all ()
7325 "Toggle the visibility of all blocks in the current buffer."
7326 (org-block-map 'org-hide-block-toggle))
7328 (defun org-hide-block-all ()
7329 "Fold all blocks in the current buffer."
7330 (interactive)
7331 (org-show-block-all)
7332 (org-block-map 'org-hide-block-toggle-maybe))
7334 (defun org-show-block-all ()
7335 "Unfold all blocks in the current buffer."
7336 (interactive)
7337 (mapc #'delete-overlay org-hide-block-overlays)
7338 (setq org-hide-block-overlays nil))
7340 (defun org-hide-block-toggle-maybe ()
7341 "Toggle visibility of block at point.
7342 Unlike to `org-hide-block-toggle', this function does not throw
7343 an error. Return a non-nil value when toggling is successful."
7344 (interactive)
7345 (ignore-errors (org-hide-block-toggle)))
7347 (defun org-hide-block-toggle (&optional force)
7348 "Toggle the visibility of the current block.
7349 When optional argument FORCE is `off', make block visible. If it
7350 is non-nil, hide it unconditionally. Throw an error when not at
7351 a block. Return a non-nil value when toggling is successful."
7352 (interactive)
7353 (let ((element (org-element-at-point)))
7354 (unless (memq (org-element-type element)
7355 '(center-block comment-block dynamic-block example-block
7356 export-block quote-block special-block
7357 src-block verse-block))
7358 (user-error "Not at a block"))
7359 (let* ((start (save-excursion
7360 (goto-char (org-element-property :post-affiliated element))
7361 (line-end-position)))
7362 (end (save-excursion
7363 (goto-char (org-element-property :end element))
7364 (skip-chars-backward " \r\t\n")
7365 (line-end-position)))
7366 (overlays (overlays-at start)))
7367 (cond
7368 ;; Do nothing when not before or at the block opening line or
7369 ;; at the block closing line.
7370 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7371 ((and (not (eq force 'off))
7372 (not (memq t (mapcar
7373 (lambda (o)
7374 (eq (overlay-get o 'invisible) 'org-hide-block))
7375 overlays))))
7376 (let ((ov (make-overlay start end)))
7377 (overlay-put ov 'invisible 'org-hide-block)
7378 ;; Make the block accessible to `isearch'.
7379 (overlay-put
7380 ov 'isearch-open-invisible
7381 (lambda (ov)
7382 (when (memq ov org-hide-block-overlays)
7383 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7384 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7385 (delete-overlay ov))))
7386 (push ov org-hide-block-overlays)
7387 ;; When the block is hidden away, make sure point is left in
7388 ;; a visible part of the buffer.
7389 (when (> (line-beginning-position) start)
7390 (goto-char start)
7391 (beginning-of-line))
7392 ;; Signal successful toggling.
7394 ((or (not force) (eq force 'off))
7395 (dolist (ov overlays t)
7396 (when (memq ov org-hide-block-overlays)
7397 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7398 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7399 (delete-overlay ov))))))))
7401 ;; Remove overlays when changing major mode
7402 (add-hook 'org-mode-hook
7403 (lambda () (add-hook 'change-major-mode-hook
7404 'org-show-block-all 'append 'local)))
7406 ;;; Org-goto
7408 (defvar org-goto-window-configuration nil)
7409 (defvar org-goto-marker nil)
7410 (defvar org-goto-map)
7411 (defun org-goto-map ()
7412 "Set the keymap `org-goto'."
7413 (setq org-goto-map
7414 (let ((map (make-sparse-keymap)))
7415 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7416 mouse-drag-region universal-argument org-occur)))
7417 (dolist (cmd cmds)
7418 (substitute-key-definition cmd cmd map global-map)))
7419 (suppress-keymap map)
7420 (org-defkey map "\C-m" 'org-goto-ret)
7421 (org-defkey map [(return)] 'org-goto-ret)
7422 (org-defkey map [(left)] 'org-goto-left)
7423 (org-defkey map [(right)] 'org-goto-right)
7424 (org-defkey map [(control ?g)] 'org-goto-quit)
7425 (org-defkey map "\C-i" 'org-cycle)
7426 (org-defkey map [(tab)] 'org-cycle)
7427 (org-defkey map [(down)] 'outline-next-visible-heading)
7428 (org-defkey map [(up)] 'outline-previous-visible-heading)
7429 (if org-goto-auto-isearch
7430 (if (fboundp 'define-key-after)
7431 (define-key-after map [t] 'org-goto-local-auto-isearch)
7432 nil)
7433 (org-defkey map "q" 'org-goto-quit)
7434 (org-defkey map "n" 'outline-next-visible-heading)
7435 (org-defkey map "p" 'outline-previous-visible-heading)
7436 (org-defkey map "f" 'outline-forward-same-level)
7437 (org-defkey map "b" 'outline-backward-same-level)
7438 (org-defkey map "u" 'outline-up-heading))
7439 (org-defkey map "/" 'org-occur)
7440 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7441 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7442 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7443 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7444 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7445 map)))
7447 (defconst org-goto-help
7448 "Browse buffer copy, to find location or copy text.%s
7449 RET=jump to location C-g=quit and return to previous location
7450 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7452 (defvar org-goto-start-pos) ; dynamically scoped parameter
7454 (defun org-goto (&optional alternative-interface)
7455 "Look up a different location in the current file, keeping current visibility.
7457 When you want look-up or go to a different location in a
7458 document, the fastest way is often to fold the entire buffer and
7459 then dive into the tree. This method has the disadvantage, that
7460 the previous location will be folded, which may not be what you
7461 want.
7463 This command works around this by showing a copy of the current
7464 buffer in an indirect buffer, in overview mode. You can dive
7465 into the tree in that copy, use org-occur and incremental search
7466 to find a location. When pressing RET or `Q', the command
7467 returns to the original buffer in which the visibility is still
7468 unchanged. After RET it will also jump to the location selected
7469 in the indirect buffer and expose the headline hierarchy above.
7471 With a prefix argument, use the alternative interface: e.g., if
7472 `org-goto-interface' is `outline' use `outline-path-completion'."
7473 (interactive "P")
7474 (org-goto-map)
7475 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7476 (org-refile-use-outline-path t)
7477 (org-refile-target-verify-function nil)
7478 (interface
7479 (if (not alternative-interface)
7480 org-goto-interface
7481 (if (eq org-goto-interface 'outline)
7482 'outline-path-completion
7483 'outline)))
7484 (org-goto-start-pos (point))
7485 (selected-point
7486 (if (eq interface 'outline)
7487 (car (org-get-location (current-buffer) org-goto-help))
7488 (let ((pa (org-refile-get-location "Goto")))
7489 (org-refile-check-position pa)
7490 (nth 3 pa)))))
7491 (if selected-point
7492 (progn
7493 (org-mark-ring-push org-goto-start-pos)
7494 (goto-char selected-point)
7495 (when (or (org-invisible-p) (org-invisible-p2))
7496 (org-show-context 'org-goto)))
7497 (message "Quit"))))
7499 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7500 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7501 (defvar org-goto-local-auto-isearch-map) ; defined below
7503 (defun org-get-location (_buf help)
7504 "Let the user select a location in current buffer.
7505 This function uses a recursive edit. It returns the selected position
7506 or nil."
7507 (org-no-popups
7508 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7509 (isearch-hide-immediately nil)
7510 (isearch-search-fun-function
7511 (lambda () 'org-goto-local-search-headings))
7512 (org-goto-selected-point org-goto-exit-command))
7513 (save-excursion
7514 (save-window-excursion
7515 (delete-other-windows)
7516 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7517 (pop-to-buffer-same-window
7518 (condition-case nil
7519 (make-indirect-buffer (current-buffer) "*org-goto*")
7520 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7521 (with-output-to-temp-buffer "*Org Help*"
7522 (princ (format help (if org-goto-auto-isearch
7523 " Just type for auto-isearch."
7524 " n/p/f/b/u to navigate, q to quit."))))
7525 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7526 (setq buffer-read-only nil)
7527 (let ((org-startup-truncated t)
7528 (org-startup-folded nil)
7529 (org-startup-align-all-tables nil))
7530 (org-mode)
7531 (org-overview))
7532 (setq buffer-read-only t)
7533 (if (and (boundp 'org-goto-start-pos)
7534 (integer-or-marker-p org-goto-start-pos))
7535 (progn (goto-char org-goto-start-pos)
7536 (when (org-invisible-p)
7537 (org-show-set-visibility 'lineage)))
7538 (goto-char (point-min)))
7539 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7540 (message "Select location and press RET")
7541 (use-local-map org-goto-map)
7542 (recursive-edit)))
7543 (kill-buffer "*org-goto*")
7544 (cons org-goto-selected-point org-goto-exit-command))))
7546 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7547 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7548 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7549 (if (fboundp 'isearch-other-control-char)
7550 (progn
7551 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7552 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7553 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7554 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7555 (define-key org-goto-local-auto-isearch-map [return] nil))
7557 (defun org-goto-local-search-headings (string bound noerror)
7558 "Search and make sure that any matches are in headlines."
7559 (catch 'return
7560 (while (if isearch-forward
7561 (search-forward string bound noerror)
7562 (search-backward string bound noerror))
7563 (when (save-match-data
7564 (and (save-excursion
7565 (beginning-of-line)
7566 (looking-at org-complex-heading-regexp))
7567 (or (not (match-beginning 5))
7568 (< (point) (match-beginning 5)))))
7569 (throw 'return (point))))))
7571 (defun org-goto-local-auto-isearch ()
7572 "Start isearch."
7573 (interactive)
7574 (goto-char (point-min))
7575 (let ((keys (this-command-keys)))
7576 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7577 (isearch-mode t)
7578 (isearch-process-search-char (string-to-char keys)))))
7580 (defun org-goto-ret (&optional _arg)
7581 "Finish `org-goto' by going to the new location."
7582 (interactive "P")
7583 (setq org-goto-selected-point (point))
7584 (setq org-goto-exit-command 'return)
7585 (throw 'exit nil))
7587 (defun org-goto-left ()
7588 "Finish `org-goto' by going to the new location."
7589 (interactive)
7590 (if (org-at-heading-p)
7591 (progn
7592 (beginning-of-line 1)
7593 (setq org-goto-selected-point (point)
7594 org-goto-exit-command 'left)
7595 (throw 'exit nil))
7596 (user-error "Not on a heading")))
7598 (defun org-goto-right ()
7599 "Finish `org-goto' by going to the new location."
7600 (interactive)
7601 (if (org-at-heading-p)
7602 (progn
7603 (setq org-goto-selected-point (point)
7604 org-goto-exit-command 'right)
7605 (throw 'exit nil))
7606 (user-error "Not on a heading")))
7608 (defun org-goto-quit ()
7609 "Finish `org-goto' without cursor motion."
7610 (interactive)
7611 (setq org-goto-selected-point nil)
7612 (setq org-goto-exit-command 'quit)
7613 (throw 'exit nil))
7615 ;;; Indirect buffer display of subtrees
7617 (defvar org-indirect-dedicated-frame nil
7618 "This is the frame being used for indirect tree display.")
7619 (defvar org-last-indirect-buffer nil)
7621 (defun org-tree-to-indirect-buffer (&optional arg)
7622 "Create indirect buffer and narrow it to current subtree.
7624 With a numerical prefix ARG, go up to this level and then take that tree.
7625 If ARG is negative, go up that many levels.
7627 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7628 indirect buffer previously made with this command, to avoid proliferation of
7629 indirect buffers. However, when you call the command with a \
7630 `\\[universal-argument]' prefix, or
7631 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7632 so that you can work with several indirect buffers at the same time. If
7633 `org-indirect-buffer-display' is `dedicated-frame', the \
7634 `\\[universal-argument]' prefix also
7635 requests that a new frame be made for the new buffer, so that the dedicated
7636 frame is not changed."
7637 (interactive "P")
7638 (let ((cbuf (current-buffer))
7639 (cwin (selected-window))
7640 (pos (point))
7641 beg end level heading ibuf)
7642 (save-excursion
7643 (org-back-to-heading t)
7644 (when (numberp arg)
7645 (setq level (org-outline-level))
7646 (when (< arg 0) (setq arg (+ level arg)))
7647 (while (> (setq level (org-outline-level)) arg)
7648 (org-up-heading-safe)))
7649 (setq beg (point)
7650 heading (org-get-heading 'no-tags))
7651 (org-end-of-subtree t t)
7652 (when (org-at-heading-p) (backward-char 1))
7653 (setq end (point)))
7654 (when (and (buffer-live-p org-last-indirect-buffer)
7655 (not (eq org-indirect-buffer-display 'new-frame))
7656 (not arg))
7657 (kill-buffer org-last-indirect-buffer))
7658 (setq ibuf (org-get-indirect-buffer cbuf heading)
7659 org-last-indirect-buffer ibuf)
7660 (cond
7661 ((or (eq org-indirect-buffer-display 'new-frame)
7662 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7663 (select-frame (make-frame))
7664 (delete-other-windows)
7665 (pop-to-buffer-same-window ibuf)
7666 (org-set-frame-title heading))
7667 ((eq org-indirect-buffer-display 'dedicated-frame)
7668 (raise-frame
7669 (select-frame (or (and org-indirect-dedicated-frame
7670 (frame-live-p org-indirect-dedicated-frame)
7671 org-indirect-dedicated-frame)
7672 (setq org-indirect-dedicated-frame (make-frame)))))
7673 (delete-other-windows)
7674 (pop-to-buffer-same-window ibuf)
7675 (org-set-frame-title (concat "Indirect: " heading)))
7676 ((eq org-indirect-buffer-display 'current-window)
7677 (pop-to-buffer-same-window ibuf))
7678 ((eq org-indirect-buffer-display 'other-window)
7679 (pop-to-buffer ibuf))
7680 (t (error "Invalid value")))
7681 (narrow-to-region beg end)
7682 (outline-show-all)
7683 (goto-char pos)
7684 (run-hook-with-args 'org-cycle-hook 'all)
7685 (and (window-live-p cwin) (select-window cwin))))
7687 (defun org-get-indirect-buffer (&optional buffer heading)
7688 (setq buffer (or buffer (current-buffer)))
7689 (let ((n 1) (base (buffer-name buffer)) bname)
7690 (while (buffer-live-p
7691 (get-buffer
7692 (setq bname
7693 (concat base "-"
7694 (if heading (concat heading "-" (number-to-string n))
7695 (number-to-string n))))))
7696 (setq n (1+ n)))
7697 (condition-case nil
7698 (make-indirect-buffer buffer bname 'clone)
7699 (error (make-indirect-buffer buffer bname)))))
7701 (defun org-set-frame-title (title)
7702 "Set the title of the current frame to the string TITLE."
7703 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7705 ;;;; Structure editing
7707 ;;; Inserting headlines
7709 (defun org--line-empty-p (n)
7710 "Is the Nth next line empty?
7712 Counts the current line as N = 1 and the previous line as N = 0;
7713 see `beginning-of-line'."
7714 (save-excursion
7715 (and (not (bobp))
7716 (or (beginning-of-line n) t)
7717 (save-match-data
7718 (looking-at "[ \t]*$")))))
7720 (defun org-previous-line-empty-p ()
7721 "Is the previous line a blank line?
7722 When NEXT is non-nil, check the next line instead."
7723 (org--line-empty-p 0))
7725 (defun org-next-line-empty-p ()
7726 "Is the previous line a blank line?
7727 When NEXT is non-nil, check the next line instead."
7728 (org--line-empty-p 2))
7730 (defun org--blank-before-heading-p (&optional parent)
7731 "Non-nil when an empty line should precede a new heading here.
7732 When optional argument PARENT is non-nil, consider parent
7733 headline instead of current one."
7734 (pcase (assq 'heading org-blank-before-new-entry)
7735 (`(heading . auto)
7736 (save-excursion
7737 (org-with-limited-levels
7738 (unless (and (org-before-first-heading-p)
7739 (not (outline-next-heading)))
7740 (org-back-to-heading t)
7741 (when parent (org-up-heading-safe))
7742 (cond ((not (bobp))
7743 (org-previous-line-empty-p))
7744 ((outline-next-heading)
7745 (org-previous-line-empty-p))
7746 ;; Ignore trailing spaces on last buffer line.
7747 ((progn (skip-chars-backward " \t") (bolp))
7748 (org-previous-line-empty-p))
7749 (t nil))))))
7750 (`(heading . ,value) value)
7751 (_ nil)))
7753 (defun org-insert-heading (&optional arg invisible-ok top)
7754 "Insert a new heading or an item with the same depth at point.
7756 If point is at the beginning of a heading, insert a new heading
7757 or a new headline above the current one. When at the beginning
7758 of a regular line of text, turn it into a heading.
7760 If point is in the middle of a line, split it and create a new
7761 headline with the text in the current line after point (see
7762 `org-M-RET-may-split-line' on how to modify this behavior). As
7763 a special case, on a headline, splitting can only happen on the
7764 title itself. E.g., this excludes breaking stars or tags.
7766 With a `\\[universal-argument]' prefix, set \
7767 `org-insert-heading-respect-content' to
7768 a non-nil value for the duration of the command. This forces the
7769 insertion of a heading after the current subtree, independently
7770 on the location of point.
7772 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7773 insert the heading at the end of the tree
7774 above the current heading. For example, if point is within a
7775 2nd-level heading, then it will insert a 2nd-level heading at
7776 the end of the 1st-level parent subtree.
7778 When INVISIBLE-OK is set, stop at invisible headlines when going
7779 back. This is important for non-interactive uses of the
7780 command.
7782 When optional argument TOP is non-nil, insert a level 1 heading,
7783 unconditionally."
7784 (interactive "P")
7785 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7786 (level (org-current-level))
7787 (stars (make-string (if (and level (not top)) level 1) ?*)))
7788 (cond
7789 ((or org-insert-heading-respect-content
7790 (member arg '((4) (16)))
7791 (and (not invisible-ok)
7792 (invisible-p (max (1- (point)) (point-min)))))
7793 ;; Position point at the location of insertion.
7794 (if (not level) ;before first headline
7795 (org-with-limited-levels (outline-next-heading))
7796 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7797 ;; is nil.
7798 (org-with-limited-levels (org-back-to-heading invisible-ok))
7799 (cond ((equal arg '(16))
7800 (org-up-heading-safe)
7801 (org-end-of-subtree t t))
7803 (org-end-of-subtree t t))))
7804 (unless (bolp) (insert "\n")) ;ensure final newline
7805 (unless (and blank? (org-previous-line-empty-p))
7806 (org-N-empty-lines-before-current (if blank? 1 0)))
7807 (insert stars " \n")
7808 (forward-char -1))
7809 ;; At a headline...
7810 ((org-at-heading-p)
7811 (cond ((bolp)
7812 (when blank? (save-excursion (insert "\n")))
7813 (save-excursion (insert stars " \n"))
7814 (unless (and blank? (org-previous-line-empty-p))
7815 (org-N-empty-lines-before-current (if blank? 1 0)))
7816 (end-of-line))
7817 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7818 (org-match-line org-complex-heading-regexp)
7819 (org-pos-in-match-range (point) 4))
7820 ;; Grab the text that should moved to the new headline.
7821 ;; Preserve tags.
7822 (let ((split (delete-and-extract-region (point) (match-end 4))))
7823 (if (looking-at "[ \t]*$") (replace-match "")
7824 (org-set-tags nil t))
7825 (end-of-line)
7826 (when blank? (insert "\n"))
7827 (insert "\n" stars " ")
7828 (when (org-string-nw-p split) (insert split))
7829 (when (eobp) (save-excursion (insert "\n")))))
7831 (end-of-line)
7832 (when blank? (insert "\n"))
7833 (insert "\n" stars " ")
7834 (when (eobp) (save-excursion (insert "\n"))))))
7835 ;; On regular text, turn line into a headline or split, if
7836 ;; appropriate.
7837 ((bolp)
7838 (insert stars " ")
7839 (unless (and blank? (org-previous-line-empty-p))
7840 (org-N-empty-lines-before-current (if blank? 1 0))))
7842 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7843 (end-of-line))
7844 (insert "\n" stars " ")
7845 (unless (and blank? (org-previous-line-empty-p))
7846 (org-N-empty-lines-before-current (if blank? 1 0))))))
7847 (run-hooks 'org-insert-heading-hook))
7849 (defun org-N-empty-lines-before-current (n)
7850 "Make the number of empty lines before current exactly N.
7851 So this will delete or add empty lines."
7852 (let ((column (current-column)))
7853 (beginning-of-line)
7854 (unless (bobp)
7855 (let ((start (save-excursion
7856 (skip-chars-backward " \r\t\n")
7857 (line-end-position))))
7858 (delete-region start (line-end-position 0))))
7859 (insert (make-string n ?\n))
7860 (move-to-column column)))
7862 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7863 "Return the heading of the current entry, without the stars.
7864 When NO-TAGS is non-nil, don't include tags.
7865 When NO-TODO is non-nil, don't include TODO keywords.
7866 When NO-PRIORITY is non-nil, don't include priority cookie.
7867 When NO-COMMENT is non-nil, don't include COMMENT string."
7868 (save-excursion
7869 (org-back-to-heading t)
7870 (let ((case-fold-search nil))
7871 (looking-at org-complex-heading-regexp)
7872 (let ((todo (and (not no-todo) (match-string 2)))
7873 (priority (and (not no-priority) (match-string 3)))
7874 (headline (pcase (match-string 4)
7875 (`nil "")
7876 ((and (guard no-comment) h)
7877 (replace-regexp-in-string
7878 (eval-when-compile
7879 (format "\\`%s[ \t]+" org-comment-string))
7880 "" h))
7881 (h h)))
7882 (tags (and (not no-tags) (match-string 5))))
7883 (mapconcat #'identity
7884 (delq nil (list todo priority headline tags))
7885 " ")))))
7887 (defvar orgstruct-mode) ; defined below
7889 (defun org-heading-components ()
7890 "Return the components of the current heading.
7891 This is a list with the following elements:
7892 - the level as an integer
7893 - the reduced level, different if `org-odd-levels-only' is set.
7894 - the TODO keyword, or nil
7895 - the priority character, like ?A, or nil if no priority is given
7896 - the headline text itself, or the tags string if no headline text
7897 - the tags string, or nil."
7898 (save-excursion
7899 (org-back-to-heading t)
7900 (when (let (case-fold-search)
7901 (looking-at
7902 (if orgstruct-mode
7903 org-heading-regexp
7904 org-complex-heading-regexp)))
7905 (if orgstruct-mode
7906 (list (length (match-string 1))
7907 (org-reduced-level (length (match-string 1)))
7910 (match-string 2)
7911 nil)
7912 (list (length (match-string 1))
7913 (org-reduced-level (length (match-string 1)))
7914 (match-string-no-properties 2)
7915 (and (match-end 3) (aref (match-string 3) 2))
7916 (match-string-no-properties 4)
7917 (match-string-no-properties 5))))))
7919 (defun org-get-entry ()
7920 "Get the entry text, after heading, entire subtree."
7921 (save-excursion
7922 (org-back-to-heading t)
7923 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7925 (defun org-edit-headline (&optional heading)
7926 "Edit the current headline.
7927 Set it to HEADING when provided."
7928 (interactive)
7929 (org-with-wide-buffer
7930 (org-back-to-heading t)
7931 (let ((case-fold-search nil))
7932 (when (looking-at org-complex-heading-regexp)
7933 (let* ((old (match-string-no-properties 4))
7934 (new (save-match-data
7935 (org-trim (or heading (read-string "Edit: " old))))))
7936 (unless (equal old new)
7937 (if old (replace-match new t t nil 4)
7938 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7939 (insert " " new))
7940 (org-set-tags nil t)
7941 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7943 (defun org-insert-heading-after-current ()
7944 "Insert a new heading with same level as current, after current subtree."
7945 (interactive)
7946 (org-back-to-heading)
7947 (org-insert-heading)
7948 (org-move-subtree-down)
7949 (end-of-line 1))
7951 (defun org-insert-heading-respect-content (&optional invisible-ok)
7952 "Insert heading with `org-insert-heading-respect-content' set to t."
7953 (interactive)
7954 (org-insert-heading '(4) invisible-ok))
7956 (defun org-insert-todo-heading-respect-content (&optional force-state)
7957 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7958 (interactive)
7959 (org-insert-todo-heading force-state '(4)))
7961 (defun org-insert-todo-heading (arg &optional force-heading)
7962 "Insert a new heading with the same level and TODO state as current heading.
7964 If the heading has no TODO state, or if the state is DONE, use
7965 the first state (TODO by default). Also with one prefix arg,
7966 force first state. With two prefix args, force inserting at the
7967 end of the parent subtree.
7969 When called at a plain list item, insert a new item with an
7970 unchecked check box."
7971 (interactive "P")
7972 (when (or force-heading (not (org-insert-item 'checkbox)))
7973 (org-insert-heading (or (and (equal arg '(16)) '(16))
7974 force-heading))
7975 (save-excursion
7976 (org-back-to-heading)
7977 (outline-previous-heading)
7978 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7979 (let* ((new-mark-x
7980 (if (or (equal arg '(4))
7981 (not (match-beginning 2))
7982 (member (match-string 2) org-done-keywords))
7983 (car org-todo-keywords-1)
7984 (match-string 2)))
7985 (new-mark
7987 (run-hook-with-args-until-success
7988 'org-todo-get-default-hook new-mark-x nil)
7989 new-mark-x)))
7990 (beginning-of-line 1)
7991 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7992 (if org-treat-insert-todo-heading-as-state-change
7993 (org-todo new-mark)
7994 (insert new-mark " "))))
7995 (when org-provide-todo-statistics
7996 (org-update-parent-todo-statistics))))
7998 (defun org-insert-subheading (arg)
7999 "Insert a new subheading and demote it.
8000 Works for outline headings and for plain lists alike."
8001 (interactive "P")
8002 (org-insert-heading arg)
8003 (cond
8004 ((org-at-heading-p) (org-do-demote))
8005 ((org-at-item-p) (org-indent-item))))
8007 (defun org-insert-todo-subheading (arg)
8008 "Insert a new subheading with TODO keyword or checkbox and demote it.
8009 Works for outline headings and for plain lists alike."
8010 (interactive "P")
8011 (org-insert-todo-heading arg)
8012 (cond
8013 ((org-at-heading-p) (org-do-demote))
8014 ((org-at-item-p) (org-indent-item))))
8016 ;;; Promotion and Demotion
8018 (defvar org-after-demote-entry-hook nil
8019 "Hook run after an entry has been demoted.
8020 The cursor will be at the beginning of the entry.
8021 When a subtree is being demoted, the hook will be called for each node.")
8023 (defvar org-after-promote-entry-hook nil
8024 "Hook run after an entry has been promoted.
8025 The cursor will be at the beginning of the entry.
8026 When a subtree is being promoted, the hook will be called for each node.")
8028 (defun org-promote-subtree ()
8029 "Promote the entire subtree.
8030 See also `org-promote'."
8031 (interactive)
8032 (save-excursion
8033 (org-with-limited-levels (org-map-tree 'org-promote)))
8034 (org-fix-position-after-promote))
8036 (defun org-demote-subtree ()
8037 "Demote the entire subtree.
8038 See `org-demote' and `org-promote'."
8039 (interactive)
8040 (save-excursion
8041 (org-with-limited-levels (org-map-tree 'org-demote)))
8042 (org-fix-position-after-promote))
8044 (defun org-do-promote ()
8045 "Promote the current heading higher up the tree.
8046 If the region is active in `transient-mark-mode', promote all
8047 headings in the region."
8048 (interactive)
8049 (save-excursion
8050 (if (org-region-active-p)
8051 (org-map-region 'org-promote (region-beginning) (region-end))
8052 (org-promote)))
8053 (org-fix-position-after-promote))
8055 (defun org-do-demote ()
8056 "Demote the current heading lower down the tree.
8057 If the region is active in `transient-mark-mode', demote all
8058 headings in the region."
8059 (interactive)
8060 (save-excursion
8061 (if (org-region-active-p)
8062 (org-map-region 'org-demote (region-beginning) (region-end))
8063 (org-demote)))
8064 (org-fix-position-after-promote))
8066 (defun org-fix-position-after-promote ()
8067 "Fix cursor position and indentation after demoting/promoting."
8068 (let ((pos (point)))
8069 (when (save-excursion
8070 (beginning-of-line)
8071 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8072 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8073 (cond ((eobp) (insert " "))
8074 ((eolp) (insert " "))
8075 ((equal (char-after) ?\s) (forward-char 1))))))
8077 (defun org-current-level ()
8078 "Return the level of the current entry, or nil if before the first headline.
8079 The level is the number of stars at the beginning of the
8080 headline. Use `org-reduced-level' to remove the effect of
8081 `org-odd-levels'. Unlike to `org-outline-level', this function
8082 ignores inlinetasks."
8083 (let ((level (org-with-limited-levels (org-outline-level))))
8084 (and (> level 0) level)))
8086 (defun org-get-previous-line-level ()
8087 "Return the outline depth of the last headline before the current line.
8088 Returns 0 for the first headline in the buffer, and nil if before the
8089 first headline."
8090 (and (org-current-level)
8091 (or (and (/= (line-beginning-position) (point-min))
8092 (save-excursion (beginning-of-line 0) (org-current-level)))
8093 0)))
8095 (defun org-reduced-level (l)
8096 "Compute the effective level of a heading.
8097 This takes into account the setting of `org-odd-levels-only'."
8098 (cond
8099 ((zerop l) 0)
8100 (org-odd-levels-only (1+ (floor (/ l 2))))
8101 (t l)))
8103 (defun org-level-increment ()
8104 "Return the number of stars that will be added or removed at a
8105 time to headlines when structure editing, based on the value of
8106 `org-odd-levels-only'."
8107 (if org-odd-levels-only 2 1))
8109 (defun org-get-valid-level (level &optional change)
8110 "Rectify a level change under the influence of `org-odd-levels-only'.
8111 LEVEL is a current level, CHANGE is by how much the level should
8112 be modified. Even if CHANGE is nil, LEVEL may be returned
8113 modified because even level numbers will become the next higher
8114 odd number. Returns values greater than 0."
8115 (if org-odd-levels-only
8116 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8117 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8118 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8119 (max 1 (+ level (or change 0)))))
8121 (defun org-promote ()
8122 "Promote the current heading higher up the tree."
8123 (org-with-wide-buffer
8124 (org-back-to-heading t)
8125 (let* ((after-change-functions (remq 'flyspell-after-change-function
8126 after-change-functions))
8127 (level (save-match-data (funcall outline-level)))
8128 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8129 (diff (abs (- level (length up-head) -1))))
8130 (cond
8131 ((and (= level 1) org-allow-promoting-top-level-subtree)
8132 (replace-match "# " nil t))
8133 ((= level 1)
8134 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8135 (t (replace-match up-head nil t)))
8136 (unless (= level 1)
8137 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8138 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8139 (run-hooks 'org-after-promote-entry-hook))))
8141 (defun org-demote ()
8142 "Demote the current heading lower down the tree."
8143 (org-with-wide-buffer
8144 (org-back-to-heading t)
8145 (let* ((after-change-functions (remq 'flyspell-after-change-function
8146 after-change-functions))
8147 (level (save-match-data (funcall outline-level)))
8148 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8149 (diff (abs (- level (length down-head) -1))))
8150 (replace-match down-head nil t)
8151 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8152 (when org-adapt-indentation (org-fixup-indentation diff))
8153 (run-hooks 'org-after-demote-entry-hook))))
8155 (defun org-cycle-level ()
8156 "Cycle the level of an empty headline through possible states.
8157 This goes first to child, then to parent, level, then up the hierarchy.
8158 After top level, it switches back to sibling level."
8159 (interactive)
8160 (let ((org-adapt-indentation nil))
8161 (when (org-point-at-end-of-empty-headline)
8162 (setq this-command 'org-cycle-level) ; Only needed for caching
8163 (let ((cur-level (org-current-level))
8164 (prev-level (org-get-previous-line-level)))
8165 (cond
8166 ;; If first headline in file, promote to top-level.
8167 ((= prev-level 0)
8168 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8169 do (org-do-promote)))
8170 ;; If same level as prev, demote one.
8171 ((= prev-level cur-level)
8172 (org-do-demote))
8173 ;; If parent is top-level, promote to top level if not already.
8174 ((= prev-level 1)
8175 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8176 do (org-do-promote)))
8177 ;; If top-level, return to prev-level.
8178 ((= cur-level 1)
8179 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8180 do (org-do-demote)))
8181 ;; If less than prev-level, promote one.
8182 ((< cur-level prev-level)
8183 (org-do-promote))
8184 ;; If deeper than prev-level, promote until higher than
8185 ;; prev-level.
8186 ((> cur-level prev-level)
8187 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8188 do (org-do-promote))))
8189 t))))
8191 (defun org-map-tree (fun)
8192 "Call FUN for every heading underneath the current one."
8193 (org-back-to-heading t)
8194 (let ((level (funcall outline-level)))
8195 (save-excursion
8196 (funcall fun)
8197 (while (and (progn
8198 (outline-next-heading)
8199 (> (funcall outline-level) level))
8200 (not (eobp)))
8201 (funcall fun)))))
8203 (defun org-map-region (fun beg end)
8204 "Call FUN for every heading between BEG and END."
8205 (let ((org-ignore-region t))
8206 (save-excursion
8207 (setq end (copy-marker end))
8208 (goto-char beg)
8209 (when (and (re-search-forward org-outline-regexp-bol nil t)
8210 (< (point) end))
8211 (funcall fun))
8212 (while (and (progn
8213 (outline-next-heading)
8214 (< (point) end))
8215 (not (eobp)))
8216 (funcall fun)))))
8218 (defun org-fixup-indentation (diff)
8219 "Change the indentation in the current entry by DIFF.
8221 DIFF is an integer. Indentation is done according to the
8222 following rules:
8224 - Planning information and property drawers are always indented
8225 according to the new level of the headline;
8227 - Footnote definitions and their contents are ignored;
8229 - Inlinetasks' boundaries are not shifted;
8231 - Empty lines are ignored;
8233 - Other lines' indentation are shifted by DIFF columns, unless
8234 it would introduce a structural change in the document, in
8235 which case no shifting is done at all.
8237 Assume point is at a heading or an inlinetask beginning."
8238 (org-with-wide-buffer
8239 (narrow-to-region (line-beginning-position)
8240 (save-excursion
8241 (if (org-with-limited-levels (org-at-heading-p))
8242 (org-with-limited-levels (outline-next-heading))
8243 (org-inlinetask-goto-end))
8244 (point)))
8245 (forward-line)
8246 ;; Indent properly planning info and property drawer.
8247 (when (looking-at-p org-planning-line-re)
8248 (org-indent-line)
8249 (forward-line))
8250 (when (looking-at org-property-drawer-re)
8251 (goto-char (match-end 0))
8252 (forward-line)
8253 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8254 (catch 'no-shift
8255 (when (zerop diff) (throw 'no-shift nil))
8256 ;; If DIFF is negative, first check if a shift is possible at all
8257 ;; (e.g., it doesn't break structure). This can only happen if
8258 ;; some contents are not properly indented.
8259 (let ((case-fold-search t))
8260 (when (< diff 0)
8261 (let ((diff (- diff))
8262 (forbidden-re (concat org-outline-regexp
8263 "\\|"
8264 (substring org-footnote-definition-re 1))))
8265 (save-excursion
8266 (while (not (eobp))
8267 (cond
8268 ((looking-at-p "[ \t]*$") (forward-line))
8269 ((and (looking-at-p org-footnote-definition-re)
8270 (let ((e (org-element-at-point)))
8271 (and (eq (org-element-type e) 'footnote-definition)
8272 (goto-char (org-element-property :end e))))))
8273 ((looking-at-p org-outline-regexp) (forward-line))
8274 ;; Give up if shifting would move before column 0 or
8275 ;; if it would introduce a headline or a footnote
8276 ;; definition.
8278 (skip-chars-forward " \t")
8279 (let ((ind (current-column)))
8280 (when (or (< ind diff)
8281 (and (= ind diff) (looking-at-p forbidden-re)))
8282 (throw 'no-shift nil)))
8283 ;; Ignore contents of example blocks and source
8284 ;; blocks if their indentation is meant to be
8285 ;; preserved. Jump to block's closing line.
8286 (beginning-of-line)
8287 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8288 (let ((e (org-element-at-point)))
8289 (and (memq (org-element-type e)
8290 '(example-block src-block))
8291 (or org-src-preserve-indentation
8292 (org-element-property :preserve-indent e))
8293 (goto-char (org-element-property :end e))
8294 (progn (skip-chars-backward " \r\t\n")
8295 (beginning-of-line)
8296 t))))
8297 (forward-line))))))))
8298 ;; Shift lines but footnote definitions, inlinetasks boundaries
8299 ;; by DIFF. Also skip contents of source or example blocks
8300 ;; when indentation is meant to be preserved.
8301 (while (not (eobp))
8302 (cond
8303 ((and (looking-at-p org-footnote-definition-re)
8304 (let ((e (org-element-at-point)))
8305 (and (eq (org-element-type e) 'footnote-definition)
8306 (goto-char (org-element-property :end e))))))
8307 ((looking-at-p org-outline-regexp) (forward-line))
8308 ((looking-at-p "[ \t]*$") (forward-line))
8310 (indent-line-to (+ (org-get-indentation) diff))
8311 (beginning-of-line)
8312 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8313 (let ((e (org-element-at-point)))
8314 (and (memq (org-element-type e)
8315 '(example-block src-block))
8316 (or org-src-preserve-indentation
8317 (org-element-property :preserve-indent e))
8318 (goto-char (org-element-property :end e))
8319 (progn (skip-chars-backward " \r\t\n")
8320 (beginning-of-line)
8321 t))))
8322 (forward-line)))))))))
8324 (defun org-convert-to-odd-levels ()
8325 "Convert an Org file with all levels allowed to one with odd levels.
8326 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8327 level 5 etc."
8328 (interactive)
8329 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8330 (let ((outline-level 'org-outline-level)
8331 (org-odd-levels-only nil) n)
8332 (save-excursion
8333 (goto-char (point-min))
8334 (while (re-search-forward "^\\*\\*+ " nil t)
8335 (setq n (- (length (match-string 0)) 2))
8336 (while (>= (setq n (1- n)) 0)
8337 (org-demote))
8338 (end-of-line 1))))))
8340 (defun org-convert-to-oddeven-levels ()
8341 "Convert an Org file with only odd levels to one with odd/even levels.
8342 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8343 file contains a section with an even level, conversion would
8344 destroy the structure of the file. An error is signaled in this
8345 case."
8346 (interactive)
8347 (goto-char (point-min))
8348 ;; First check if there are no even levels
8349 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8350 (org-show-set-visibility 'canonical)
8351 (error "Not all levels are odd in this file. Conversion not possible"))
8352 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8353 (let ((outline-regexp org-outline-regexp)
8354 (outline-level 'org-outline-level)
8355 (org-odd-levels-only nil) n)
8356 (save-excursion
8357 (goto-char (point-min))
8358 (while (re-search-forward "^\\*\\*+ " nil t)
8359 (setq n (/ (1- (length (match-string 0))) 2))
8360 (while (>= (setq n (1- n)) 0)
8361 (org-promote))
8362 (end-of-line 1))))))
8364 (defun org-tr-level (n)
8365 "Make N odd if required."
8366 (if org-odd-levels-only (1+ (/ n 2)) n))
8368 ;;; Vertical tree motion, cutting and pasting of subtrees
8370 (defun org-move-subtree-up (&optional arg)
8371 "Move the current subtree up past ARG headlines of the same level."
8372 (interactive "p")
8373 (org-move-subtree-down (- (prefix-numeric-value arg))))
8375 (defun org-move-subtree-down (&optional arg)
8376 "Move the current subtree down past ARG headlines of the same level."
8377 (interactive "p")
8378 (setq arg (prefix-numeric-value arg))
8379 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8380 'org-get-last-sibling))
8381 (ins-point (make-marker))
8382 (cnt (abs arg))
8383 (col (current-column))
8384 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8385 ;; Select the tree
8386 (org-back-to-heading)
8387 (setq beg0 (point))
8388 (save-excursion
8389 (setq ne-beg (org-back-over-empty-lines))
8390 (setq beg (point)))
8391 (save-match-data
8392 (save-excursion (outline-end-of-heading)
8393 (setq folded (org-invisible-p)))
8394 (progn (org-end-of-subtree nil t)
8395 (unless (eobp) (backward-char))))
8396 (outline-next-heading)
8397 (setq ne-end (org-back-over-empty-lines))
8398 (setq end (point))
8399 (goto-char beg0)
8400 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8401 ;; include less whitespace
8402 (save-excursion
8403 (goto-char beg)
8404 (forward-line (- ne-beg ne-end))
8405 (setq beg (point))))
8406 ;; Find insertion point, with error handling
8407 (while (> cnt 0)
8408 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8409 (progn (goto-char beg0)
8410 (user-error "Cannot move past superior level or buffer limit")))
8411 (setq cnt (1- cnt)))
8412 (when (> arg 0)
8413 ;; Moving forward - still need to move over subtree
8414 (org-end-of-subtree t t)
8415 (save-excursion
8416 (org-back-over-empty-lines)
8417 (or (bolp) (newline))))
8418 (setq ne-ins (org-back-over-empty-lines))
8419 (move-marker ins-point (point))
8420 (setq txt (buffer-substring beg end))
8421 (org-save-markers-in-region beg end)
8422 (delete-region beg end)
8423 (org-remove-empty-overlays-at beg)
8424 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8425 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8426 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8427 (let ((bbb (point)))
8428 (insert-before-markers txt)
8429 (org-reinstall-markers-in-region bbb)
8430 (move-marker ins-point bbb))
8431 (or (bolp) (insert "\n"))
8432 (setq ins-end (point))
8433 (goto-char ins-point)
8434 (org-skip-whitespace)
8435 (when (and (< arg 0)
8436 (org-first-sibling-p)
8437 (> ne-ins ne-beg))
8438 ;; Move whitespace back to beginning
8439 (save-excursion
8440 (goto-char ins-end)
8441 (let ((kill-whole-line t))
8442 (kill-line (- ne-ins ne-beg)) (point)))
8443 (insert (make-string (- ne-ins ne-beg) ?\n)))
8444 (move-marker ins-point nil)
8445 (if folded
8446 (outline-hide-subtree)
8447 (org-show-entry)
8448 (org-show-children)
8449 (org-cycle-hide-drawers 'children))
8450 (org-clean-visibility-after-subtree-move)
8451 ;; move back to the initial column we were at
8452 (move-to-column col)))
8454 (defvar org-subtree-clip ""
8455 "Clipboard for cut and paste of subtrees.
8456 This is actually only a copy of the kill, because we use the normal kill
8457 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8459 (defvar org-subtree-clip-folded nil
8460 "Was the last copied subtree folded?
8461 This is used to fold the tree back after pasting.")
8463 (defun org-cut-subtree (&optional n)
8464 "Cut the current subtree into the clipboard.
8465 With prefix arg N, cut this many sequential subtrees.
8466 This is a short-hand for marking the subtree and then cutting it."
8467 (interactive "p")
8468 (org-copy-subtree n 'cut))
8470 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8471 "Copy the current subtree it in the clipboard.
8472 With prefix arg N, copy this many sequential subtrees.
8473 This is a short-hand for marking the subtree and then copying it.
8474 If CUT is non-nil, actually cut the subtree.
8475 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8476 of some markers in the region, even if CUT is non-nil. This is
8477 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8478 (interactive "p")
8479 (let (beg end folded (beg0 (point)))
8480 (if (called-interactively-p 'any)
8481 (org-back-to-heading nil) ; take what looks like a subtree
8482 (org-back-to-heading t)) ; take what is really there
8483 (setq beg (point))
8484 (skip-chars-forward " \t\r\n")
8485 (save-match-data
8486 (if nosubtrees
8487 (outline-next-heading)
8488 (save-excursion (outline-end-of-heading)
8489 (setq folded (org-invisible-p)))
8490 (ignore-errors (org-forward-heading-same-level (1- n) t))
8491 (org-end-of-subtree t t)))
8492 ;; Include the end of an inlinetask
8493 (when (and (featurep 'org-inlinetask)
8494 (looking-at-p (concat (org-inlinetask-outline-regexp)
8495 "END[ \t]*$")))
8496 (end-of-line))
8497 (setq end (point))
8498 (goto-char beg0)
8499 (when (> end beg)
8500 (setq org-subtree-clip-folded folded)
8501 (when (or cut force-store-markers)
8502 (org-save-markers-in-region beg end))
8503 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8504 (setq org-subtree-clip (current-kill 0))
8505 (message "%s: Subtree(s) with %d characters"
8506 (if cut "Cut" "Copied")
8507 (length org-subtree-clip)))))
8509 (defun org-paste-subtree (&optional level tree for-yank remove)
8510 "Paste the clipboard as a subtree, with modification of headline level.
8511 The entire subtree is promoted or demoted in order to match a new headline
8512 level.
8514 If the cursor is at the beginning of a headline, the same level as
8515 that headline is used to paste the tree.
8517 If not, the new level is derived from the *visible* headings
8518 before and after the insertion point, and taken to be the inferior headline
8519 level of the two. So if the previous visible heading is level 3 and the
8520 next is level 4 (or vice versa), level 4 will be used for insertion.
8521 This makes sure that the subtree remains an independent subtree and does
8522 not swallow low level entries.
8524 You can also force a different level, either by using a numeric prefix
8525 argument, or by inserting the heading marker by hand. For example, if the
8526 cursor is after \"*****\", then the tree will be shifted to level 5.
8528 If optional TREE is given, use this text instead of the kill ring.
8530 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8531 move back over whitespace before inserting, and move point to the end of
8532 the inserted text when done.
8534 When REMOVE is non-nil, remove the subtree from the clipboard."
8535 (interactive "P")
8536 (setq tree (or tree (and kill-ring (current-kill 0))))
8537 (unless (org-kill-is-subtree-p tree)
8538 (user-error "%s"
8539 (substitute-command-keys
8540 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8541 (org-with-limited-levels
8542 (let* ((visp (not (org-invisible-p)))
8543 (txt tree)
8544 (^re_ "\\(\\*+\\)[ \t]*")
8545 (old-level (if (string-match org-outline-regexp-bol txt)
8546 (- (match-end 0) (match-beginning 0) 1)
8547 -1))
8548 (force-level (cond (level (prefix-numeric-value level))
8549 ((and (looking-at "[ \t]*$")
8550 (string-match
8551 "^\\*+$" (buffer-substring
8552 (point-at-bol) (point))))
8553 (- (match-end 0) (match-beginning 0)))
8554 ((and (bolp)
8555 (looking-at org-outline-regexp))
8556 (- (match-end 0) (point) 1))))
8557 (previous-level (save-excursion
8558 (condition-case nil
8559 (progn
8560 (outline-previous-visible-heading 1)
8561 (if (looking-at ^re_)
8562 (- (match-end 0) (match-beginning 0) 1)
8564 (error 1))))
8565 (next-level (save-excursion
8566 (condition-case nil
8567 (progn
8568 (or (looking-at org-outline-regexp)
8569 (outline-next-visible-heading 1))
8570 (if (looking-at ^re_)
8571 (- (match-end 0) (match-beginning 0) 1)
8573 (error 1))))
8574 (new-level (or force-level (max previous-level next-level)))
8575 (shift (if (or (= old-level -1)
8576 (= new-level -1)
8577 (= old-level new-level))
8579 (- new-level old-level)))
8580 (delta (if (> shift 0) -1 1))
8581 (func (if (> shift 0) 'org-demote 'org-promote))
8582 (org-odd-levels-only nil)
8583 beg end newend)
8584 ;; Remove the forced level indicator
8585 (when force-level
8586 (delete-region (point-at-bol) (point)))
8587 ;; Paste
8588 (beginning-of-line (if (bolp) 1 2))
8589 (setq beg (point))
8590 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8591 (insert-before-markers txt)
8592 (unless (string-suffix-p "\n" txt) (insert "\n"))
8593 (setq newend (point))
8594 (org-reinstall-markers-in-region beg)
8595 (setq end (point))
8596 (goto-char beg)
8597 (skip-chars-forward " \t\n\r")
8598 (setq beg (point))
8599 (when (and (org-invisible-p) visp)
8600 (save-excursion (outline-show-heading)))
8601 ;; Shift if necessary
8602 (unless (= shift 0)
8603 (save-restriction
8604 (narrow-to-region beg end)
8605 (while (not (= shift 0))
8606 (org-map-region func (point-min) (point-max))
8607 (setq shift (+ delta shift)))
8608 (goto-char (point-min))
8609 (setq newend (point-max))))
8610 (when (or (called-interactively-p 'interactive) for-yank)
8611 (message "Clipboard pasted as level %d subtree" new-level))
8612 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8613 kill-ring
8614 (eq org-subtree-clip (current-kill 0))
8615 org-subtree-clip-folded)
8616 ;; The tree was folded before it was killed/copied
8617 (outline-hide-subtree))
8618 (and for-yank (goto-char newend))
8619 (and remove (setq kill-ring (cdr kill-ring))))))
8621 (defun org-kill-is-subtree-p (&optional txt)
8622 "Check if the current kill is an outline subtree, or a set of trees.
8623 Returns nil if kill does not start with a headline, or if the first
8624 headline level is not the largest headline level in the tree.
8625 So this will actually accept several entries of equal levels as well,
8626 which is OK for `org-paste-subtree'.
8627 If optional TXT is given, check this string instead of the current kill."
8628 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8629 (re (org-get-limited-outline-regexp))
8630 (^re (concat "^" re))
8631 (start-level (and kill
8632 (string-match
8633 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8634 kill)
8635 (- (match-end 2) (match-beginning 2) 1)))
8636 (start (1+ (or (match-beginning 2) -1))))
8637 (if (not start-level)
8638 (progn
8639 nil) ;; does not even start with a heading
8640 (catch 'exit
8641 (while (setq start (string-match ^re kill (1+ start)))
8642 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8643 (throw 'exit nil)))
8644 t))))
8646 (defvar org-markers-to-move nil
8647 "Markers that should be moved with a cut-and-paste operation.
8648 Those markers are stored together with their positions relative to
8649 the start of the region.")
8651 (defun org-save-markers-in-region (beg end)
8652 "Check markers in region.
8653 If these markers are between BEG and END, record their position relative
8654 to BEG, so that after moving the block of text, we can put the markers back
8655 into place.
8656 This function gets called just before an entry or tree gets cut from the
8657 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8658 called immediately, to move the markers with the entries."
8659 (setq org-markers-to-move nil)
8660 (when (featurep 'org-clock)
8661 (org-clock-save-markers-for-cut-and-paste beg end))
8662 (when (featurep 'org-agenda)
8663 (org-agenda-save-markers-for-cut-and-paste beg end)))
8665 (defun org-check-and-save-marker (marker beg end)
8666 "Check if MARKER is between BEG and END.
8667 If yes, remember the marker and the distance to BEG."
8668 (when (and (marker-buffer marker)
8669 (equal (marker-buffer marker) (current-buffer))
8670 (>= marker beg) (< marker end))
8671 (push (cons marker (- marker beg)) org-markers-to-move)))
8673 (defun org-reinstall-markers-in-region (beg)
8674 "Move all remembered markers to their position relative to BEG."
8675 (dolist (x org-markers-to-move)
8676 (move-marker (car x) (+ beg (cdr x))))
8677 (setq org-markers-to-move nil))
8679 (defun org-narrow-to-subtree ()
8680 "Narrow buffer to the current subtree."
8681 (interactive)
8682 (save-excursion
8683 (save-match-data
8684 (org-with-limited-levels
8685 (narrow-to-region
8686 (progn (org-back-to-heading t) (point))
8687 (progn (org-end-of-subtree t t)
8688 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8689 (point)))))))
8691 (defun org-narrow-to-block ()
8692 "Narrow buffer to the current block."
8693 (interactive)
8694 (let* ((case-fold-search t)
8695 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8696 "^[ \t]*#\\+end_.*")))
8697 (if blockp
8698 (narrow-to-region (car blockp) (cdr blockp))
8699 (user-error "Not in a block"))))
8701 (defun org-clone-subtree-with-time-shift (n &optional shift)
8702 "Clone the task (subtree) at point N times.
8703 The clones will be inserted as siblings.
8705 In interactive use, the user will be prompted for the number of
8706 clones to be produced. If the entry has a timestamp, the user
8707 will also be prompted for a time shift, which may be a repeater
8708 as used in time stamps, for example `+3d'. To disable this,
8709 you can call the function with a universal prefix argument.
8711 When a valid repeater is given and the entry contains any time
8712 stamps, the clones will become a sequence in time, with time
8713 stamps in the subtree shifted for each clone produced. If SHIFT
8714 is nil or the empty string, time stamps will be left alone. The
8715 ID property of the original subtree is removed.
8717 In each clone, all the CLOCK entries will be removed. This
8718 prevents Org from considering that the clocked times overlap.
8720 If the original subtree did contain time stamps with a repeater,
8721 the following will happen:
8722 - the repeater will be removed in each clone
8723 - an additional clone will be produced, with the current, unshifted
8724 date(s) in the entry.
8725 - the original entry will be placed *after* all the clones, with
8726 repeater intact.
8727 - the start days in the repeater in the original entry will be shifted
8728 to past the last clone.
8729 In this way you can spell out a number of instances of a repeating task,
8730 and still retain the repeater to cover future instances of the task.
8732 As described above, N+1 clones are produced when the original
8733 subtree has a repeater. Setting N to 0, then, can be used to
8734 remove the repeater from a subtree and create a shifted clone
8735 with the original repeater."
8736 (interactive "nNumber of clones to produce: ")
8737 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8738 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8739 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8740 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8741 (shift
8742 (or shift
8743 (if (and (not (equal current-prefix-arg '(4)))
8744 (save-excursion
8745 (goto-char beg)
8746 (re-search-forward org-ts-regexp-both end-of-tree t)))
8747 (read-from-minibuffer
8748 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8749 ""))) ;No time shift
8750 (doshift
8751 (and (org-string-nw-p shift)
8752 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8753 shift)
8754 (user-error "Invalid shift specification %s" shift)))))
8755 (goto-char end-of-tree)
8756 (unless (bolp) (insert "\n"))
8757 (let* ((end (point))
8758 (template (buffer-substring beg end))
8759 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8760 (shift-what (pcase (and doshift (match-string 2 shift))
8761 (`nil nil)
8762 ("d" 'day)
8763 ("w" (setq shift-n (* 7 shift-n)) 'day)
8764 ("m" 'month)
8765 ("y" 'year)
8766 (_ (error "Unsupported time unit"))))
8767 (nmin 1)
8768 (nmax n)
8769 (n-no-remove -1)
8770 (idprop (org-entry-get nil "ID")))
8771 (when (and doshift
8772 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8773 template))
8774 (delete-region beg end)
8775 (setq end beg)
8776 (setq nmin 0)
8777 (setq nmax (1+ nmax))
8778 (setq n-no-remove nmax))
8779 (goto-char end)
8780 (cl-loop for n from nmin to nmax do
8781 (insert
8782 ;; Prepare clone.
8783 (with-temp-buffer
8784 (insert template)
8785 (org-mode)
8786 (goto-char (point-min))
8787 (org-show-subtree)
8788 (and idprop (if org-clone-delete-id
8789 (org-entry-delete nil "ID")
8790 (org-id-get-create t)))
8791 (unless (= n 0)
8792 (while (re-search-forward org-clock-line-re nil t)
8793 (delete-region (line-beginning-position)
8794 (line-beginning-position 2)))
8795 (goto-char (point-min))
8796 (while (re-search-forward org-drawer-regexp nil t)
8797 (org-remove-empty-drawer-at (point))))
8798 (goto-char (point-min))
8799 (when doshift
8800 (while (re-search-forward org-ts-regexp-both nil t)
8801 (org-timestamp-change (* n shift-n) shift-what))
8802 (unless (= n n-no-remove)
8803 (goto-char (point-min))
8804 (while (re-search-forward org-ts-regexp nil t)
8805 (save-excursion
8806 (goto-char (match-beginning 0))
8807 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8808 (delete-region (match-beginning 1) (match-end 1)))))))
8809 (buffer-string)))))
8810 (goto-char beg)))
8812 ;;; Outline Sorting
8814 (defun org-sort (&optional with-case)
8815 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8816 Optional argument WITH-CASE means sort case-sensitively."
8817 (interactive "P")
8818 (org-call-with-arg
8819 (cond ((org-at-table-p) #'org-table-sort-lines)
8820 ((org-at-item-p) #'org-sort-list)
8821 (t #'org-sort-entries))
8822 with-case))
8824 (defun org-sort-remove-invisible (s)
8825 "Remove invisible part of links and emphasis markers from string S."
8826 (remove-text-properties 0 (length s) org-rm-props s)
8827 (replace-regexp-in-string
8828 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8829 (replace-regexp-in-string
8830 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8831 (org-link-display-format s)
8832 t t) t t))
8834 (defvar org-priority-regexp) ; defined later in the file
8836 (defvar org-after-sorting-entries-or-items-hook nil
8837 "Hook that is run after a bunch of entries or items have been sorted.
8838 When children are sorted, the cursor is in the parent line when this
8839 hook gets called. When a region or a plain list is sorted, the cursor
8840 will be in the first entry of the sorted region/list.")
8842 (defun org-sort-entries
8843 (&optional with-case sorting-type getkey-func compare-func property
8844 interactive?)
8845 "Sort entries on a certain level of an outline tree.
8846 If there is an active region, the entries in the region are sorted.
8847 Else, if the cursor is before the first entry, sort the top-level items.
8848 Else, the children of the entry at point are sorted.
8850 Sorting can be alphabetically, numerically, by date/time as given by
8851 a time stamp, by a property, by priority order, or by a custom function.
8853 The command prompts for the sorting type unless it has been given to the
8854 function through the SORTING-TYPE argument, which needs to be a character,
8855 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8856 the precise meaning of each character:
8858 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8859 c By creation time, which is assumed to be the first inactive time stamp
8860 at the beginning of a line.
8861 d By deadline date/time.
8862 k By clocking time.
8863 n Numerically, by converting the beginning of the entry/item to a number.
8864 o By order of TODO keywords.
8865 p By priority according to the cookie.
8866 r By the value of a property.
8867 s By scheduled date/time.
8868 t By date/time, either the first active time stamp in the entry, or, if
8869 none exist, by the first inactive one.
8871 Capital letters will reverse the sort order.
8873 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8874 called with point at the beginning of the record. It must return a
8875 value that is compatible with COMPARE-FUNC, the function used to
8876 compare entries.
8878 Comparing entries ignores case by default. However, with an optional argument
8879 WITH-CASE, the sorting considers case as well.
8881 Sorting is done against the visible part of the headlines, it ignores hidden
8882 links.
8884 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8886 A non-nil value for INTERACTIVE? is used to signal that this
8887 function is being called interactively."
8888 (interactive (list current-prefix-arg nil nil nil nil t))
8889 (let ((case-func (if with-case 'identity 'downcase))
8890 (cmstr
8891 ;; The clock marker is lost when using `sort-subr', let's
8892 ;; store the clocking string.
8893 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8894 (save-excursion
8895 (goto-char org-clock-marker)
8896 (buffer-substring-no-properties (line-beginning-position)
8897 (point)))))
8898 start beg end stars re re2
8899 txt what tmp)
8900 ;; Find beginning and end of region to sort
8901 (cond
8902 ((org-region-active-p)
8903 ;; we will sort the region
8904 (setq end (region-end)
8905 what "region")
8906 (goto-char (region-beginning))
8907 (unless (org-at-heading-p) (outline-next-heading))
8908 (setq start (point)))
8909 ((or (org-at-heading-p)
8910 (ignore-errors (progn (org-back-to-heading) t)))
8911 ;; we will sort the children of the current headline
8912 (org-back-to-heading)
8913 (setq start (point)
8914 end (progn (org-end-of-subtree t t)
8915 (or (bolp) (insert "\n"))
8916 (when (>= (org-back-over-empty-lines) 1)
8917 (forward-line 1))
8918 (point))
8919 what "children")
8920 (goto-char start)
8921 (outline-show-subtree)
8922 (outline-next-heading))
8924 ;; we will sort the top-level entries in this file
8925 (goto-char (point-min))
8926 (or (org-at-heading-p) (outline-next-heading))
8927 (setq start (point))
8928 (goto-char (point-max))
8929 (beginning-of-line 1)
8930 (when (looking-at ".*?\\S-")
8931 ;; File ends in a non-white line
8932 (end-of-line 1)
8933 (insert "\n"))
8934 (setq end (point-max))
8935 (setq what "top-level")
8936 (goto-char start)
8937 (outline-show-all)))
8939 (setq beg (point))
8940 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8942 (looking-at "\\(\\*+\\)")
8943 (setq stars (match-string 1)
8944 re (concat "^" (regexp-quote stars) " +")
8945 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8946 txt (buffer-substring beg end))
8947 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8948 (when (and (not (equal stars "*")) (string-match re2 txt))
8949 (user-error "Region to sort contains a level above the first entry"))
8951 (unless sorting-type
8952 (message
8953 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8954 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8955 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8956 what)
8957 (setq sorting-type (read-char-exclusive)))
8959 (unless getkey-func
8960 (and (= (downcase sorting-type) ?f)
8961 (setq getkey-func
8962 (or (and interactive?
8963 (org-read-function
8964 "Function for extracting keys: "))
8965 (error "Missing key extractor")))))
8967 (and (= (downcase sorting-type) ?r)
8968 (not property)
8969 (setq property
8970 (completing-read "Property: "
8971 (mapcar #'list (org-buffer-property-keys t))
8972 nil t)))
8974 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8975 (message "Sorting entries...")
8977 (save-restriction
8978 (narrow-to-region start end)
8979 (let ((dcst (downcase sorting-type))
8980 (case-fold-search nil)
8981 (now (current-time)))
8982 (sort-subr
8983 (/= dcst sorting-type)
8984 ;; This function moves to the beginning character of the "record" to
8985 ;; be sorted.
8986 (lambda nil
8987 (if (re-search-forward re nil t)
8988 (goto-char (match-beginning 0))
8989 (goto-char (point-max))))
8990 ;; This function moves to the last character of the "record" being
8991 ;; sorted.
8992 (lambda nil
8993 (save-match-data
8994 (condition-case nil
8995 (outline-forward-same-level 1)
8996 (error
8997 (goto-char (point-max))))))
8998 ;; This function returns the value that gets sorted against.
8999 (lambda nil
9000 (cond
9001 ((= dcst ?n)
9002 (if (looking-at org-complex-heading-regexp)
9003 (string-to-number (org-sort-remove-invisible (match-string 4)))
9004 nil))
9005 ((= dcst ?a)
9006 (if (looking-at org-complex-heading-regexp)
9007 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9008 nil))
9009 ((= dcst ?k)
9010 (or (get-text-property (point) :org-clock-minutes) 0))
9011 ((= dcst ?t)
9012 (let ((end (save-excursion (outline-next-heading) (point))))
9013 (if (or (re-search-forward org-ts-regexp end t)
9014 (re-search-forward org-ts-regexp-both end t))
9015 (org-time-string-to-seconds (match-string 0))
9016 (float-time now))))
9017 ((= dcst ?c)
9018 (let ((end (save-excursion (outline-next-heading) (point))))
9019 (if (re-search-forward
9020 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9021 end t)
9022 (org-time-string-to-seconds (match-string 0))
9023 (float-time now))))
9024 ((= dcst ?s)
9025 (let ((end (save-excursion (outline-next-heading) (point))))
9026 (if (re-search-forward org-scheduled-time-regexp end t)
9027 (org-time-string-to-seconds (match-string 1))
9028 (float-time now))))
9029 ((= dcst ?d)
9030 (let ((end (save-excursion (outline-next-heading) (point))))
9031 (if (re-search-forward org-deadline-time-regexp end t)
9032 (org-time-string-to-seconds (match-string 1))
9033 (float-time now))))
9034 ((= dcst ?p)
9035 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9036 (string-to-char (match-string 2))
9037 org-default-priority))
9038 ((= dcst ?r)
9039 (or (org-entry-get nil property) ""))
9040 ((= dcst ?o)
9041 (when (looking-at org-complex-heading-regexp)
9042 (let* ((m (match-string 2))
9043 (s (if (member m org-done-keywords) '- '+)))
9044 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9045 ((= dcst ?f)
9046 (if getkey-func
9047 (progn
9048 (setq tmp (funcall getkey-func))
9049 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9050 tmp)
9051 (error "Invalid key function `%s'" getkey-func)))
9052 (t (error "Invalid sorting type `%c'" sorting-type))))
9054 (cond
9055 ((= dcst ?a) 'string<)
9056 ((= dcst ?f)
9057 (or compare-func
9058 (and interactive?
9059 (org-read-function
9060 (concat "Function for comparing keys "
9061 "(empty for default `sort-subr' predicate): ")
9062 'allow-empty))))
9063 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9064 (run-hooks 'org-after-sorting-entries-or-items-hook)
9065 ;; Reset the clock marker if needed
9066 (when cmstr
9067 (save-excursion
9068 (goto-char start)
9069 (search-forward cmstr nil t)
9070 (move-marker org-clock-marker (point))))
9071 (message "Sorting entries...done")))
9073 ;;; The orgstruct minor mode
9075 ;; Define a minor mode which can be used in other modes in order to
9076 ;; integrate the Org mode structure editing commands.
9078 ;; This is really a hack, because the Org mode structure commands use
9079 ;; keys which normally belong to the major mode. Here is how it
9080 ;; works: The minor mode defines all the keys necessary to operate the
9081 ;; structure commands, but wraps the commands into a function which
9082 ;; tests if the cursor is currently at a headline or a plain list
9083 ;; item. If that is the case, the structure command is used,
9084 ;; temporarily setting many Org mode variables like regular
9085 ;; expressions for filling etc. However, when any of those keys is
9086 ;; used at a different location, function uses `key-binding' to look
9087 ;; up if the key has an associated command in another currently active
9088 ;; keymap (minor modes, major mode, global), and executes that
9089 ;; command. There might be problems if any of the keys is otherwise
9090 ;; used as a prefix key.
9092 (defcustom orgstruct-heading-prefix-regexp ""
9093 "Regexp that matches the custom prefix of Org headlines in
9094 orgstruct(++)-mode."
9095 :group 'org
9096 :version "24.4"
9097 :package-version '(Org . "8.3")
9098 :type 'regexp)
9099 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9101 (defcustom orgstruct-setup-hook nil
9102 "Hook run after orgstruct-mode-map is filled."
9103 :group 'org
9104 :version "24.4"
9105 :package-version '(Org . "8.0")
9106 :type 'hook)
9108 (defvar orgstruct-initialized nil)
9110 (defvar org-local-vars nil
9111 "List of local variables, for use by `orgstruct-mode'.")
9113 ;;;###autoload
9114 (define-minor-mode orgstruct-mode
9115 "Toggle the minor mode `orgstruct-mode'.
9116 This mode is for using Org mode structure commands in other
9117 modes. The following keys behave as if Org mode were active, if
9118 the cursor is on a headline, or on a plain list item (both as
9119 defined by Org mode)."
9120 nil " OrgStruct" (make-sparse-keymap)
9121 (funcall (if orgstruct-mode
9122 'add-to-invisibility-spec
9123 'remove-from-invisibility-spec)
9124 '(outline . t))
9125 (when orgstruct-mode
9126 (org-load-modules-maybe)
9127 (unless orgstruct-initialized
9128 (orgstruct-setup)
9129 (setq orgstruct-initialized t))))
9131 ;;;###autoload
9132 (defun turn-on-orgstruct ()
9133 "Unconditionally turn on `orgstruct-mode'."
9134 (orgstruct-mode 1))
9136 (defvar-local orgstruct-is-++ nil
9137 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9138 (defvar-local org-fb-vars nil)
9139 (defun orgstruct++-mode (&optional arg)
9140 "Toggle `orgstruct-mode', the enhanced version of it.
9141 In addition to setting orgstruct-mode, this also exports all
9142 indentation and autofilling variables from Org mode into the
9143 buffer. It will also recognize item context in multiline items."
9144 (interactive "P")
9145 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9146 (if (< arg 1)
9147 (progn (orgstruct-mode -1)
9148 (dolist (v org-fb-vars)
9149 (set (make-local-variable (car v))
9150 (if (eq (car-safe (cadr v)) 'quote)
9151 (cl-cadadr v)
9152 (nth 1 v)))))
9153 (orgstruct-mode 1)
9154 (setq org-fb-vars nil)
9155 (unless org-local-vars
9156 (setq org-local-vars (org-get-local-variables)))
9157 (let (var val)
9158 (dolist (x org-local-vars)
9159 (when (string-match
9160 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9161 \\|fill-prefix\\|indent-\\)"
9162 (symbol-name (car x)))
9163 (setq var (car x) val (nth 1 x))
9164 (push (list var `(quote ,(eval var))) org-fb-vars)
9165 (set (make-local-variable var)
9166 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9167 (setq-local orgstruct-is-++ t))))
9169 ;;;###autoload
9170 (defun turn-on-orgstruct++ ()
9171 "Unconditionally turn on `orgstruct++-mode'."
9172 (orgstruct++-mode 1))
9174 (defun orgstruct-error ()
9175 "Error when there is no default binding for a structure key."
9176 (interactive)
9177 (funcall (if (fboundp 'user-error)
9178 'user-error
9179 'error)
9180 "This key has no function outside structure elements"))
9182 (defun orgstruct-setup ()
9183 "Setup orgstruct keymap."
9184 (dolist (cell '((org-demote . t)
9185 (org-metaleft . t)
9186 (org-metaright . t)
9187 (org-promote . t)
9188 (org-shiftmetaleft . t)
9189 (org-shiftmetaright . t)
9190 org-backward-element
9191 org-backward-heading-same-level
9192 org-ctrl-c-ret
9193 org-ctrl-c-minus
9194 org-ctrl-c-star
9195 org-cycle
9196 org-force-cycle-archived
9197 org-forward-heading-same-level
9198 org-insert-heading
9199 org-insert-heading-respect-content
9200 org-kill-note-or-show-branches
9201 org-mark-subtree
9202 org-meta-return
9203 org-metadown
9204 org-metaup
9205 org-narrow-to-subtree
9206 org-promote-subtree
9207 org-reveal
9208 org-shiftdown
9209 org-shiftleft
9210 org-shiftmetadown
9211 org-shiftmetaup
9212 org-shiftright
9213 org-shifttab
9214 org-shifttab
9215 org-shiftup
9216 org-show-children
9217 org-show-subtree
9218 org-sort
9219 org-up-element
9220 outline-demote
9221 outline-next-visible-heading
9222 outline-previous-visible-heading
9223 outline-promote
9224 outline-up-heading))
9225 (let ((f (or (car-safe cell) cell))
9226 (disable-when-heading-prefix (cdr-safe cell)))
9227 (when (fboundp f)
9228 (let ((new-bindings))
9229 (dolist (binding (nconc (where-is-internal f org-mode-map)
9230 (where-is-internal f outline-mode-map)))
9231 (push binding new-bindings)
9232 ;; TODO use local-function-key-map
9233 (dolist (rep '(("<tab>" . "TAB")
9234 ("<return>" . "RET")
9235 ("<escape>" . "ESC")
9236 ("<delete>" . "DEL")))
9237 (setq binding (read-kbd-macro
9238 (let ((case-fold-search))
9239 (replace-regexp-in-string
9240 (regexp-quote (cdr rep))
9241 (car rep)
9242 (key-description binding)))))
9243 (cl-pushnew binding new-bindings :test 'equal)))
9244 (dolist (binding new-bindings)
9245 (let ((key (lookup-key orgstruct-mode-map binding)))
9246 (when (or (not key) (numberp key))
9247 (ignore-errors
9248 (org-defkey orgstruct-mode-map
9249 binding
9250 (orgstruct-make-binding
9251 f binding disable-when-heading-prefix))))))))))
9252 (run-hooks 'orgstruct-setup-hook))
9254 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9255 "Create a function for binding in the structure minor mode.
9256 FUN is the command to call inside a table. KEY is the key that
9257 should be checked in for a command to execute outside of tables.
9258 Non-nil `disable-when-heading-prefix' means to disable the command
9259 if `orgstruct-heading-prefix-regexp' is not empty."
9260 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9261 (let ((nname name)
9262 (i 0))
9263 (while (fboundp (intern nname))
9264 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9265 (setq name (intern nname)))
9266 (eval
9267 (let ((bindings '((org-heading-regexp
9268 (concat "^"
9269 orgstruct-heading-prefix-regexp
9270 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9271 (org-outline-regexp
9272 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9273 (org-outline-regexp-bol
9274 (concat "^" org-outline-regexp))
9275 (outline-regexp org-outline-regexp)
9276 (outline-heading-end-regexp "\n")
9277 (outline-level 'org-outline-level)
9278 (outline-heading-alist))))
9279 `(defun ,name (arg)
9280 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9281 "Outside of structure, run the binding of `"
9282 (key-description key) "'."
9283 (when disable-when-heading-prefix
9284 (concat
9285 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9286 "back to the default binding due to limitations of Org's implementation of\n"
9287 "`" (symbol-name fun) "'.")))
9288 (interactive "p")
9289 (let* ((disable
9290 ,(and disable-when-heading-prefix
9291 '(not (string= orgstruct-heading-prefix-regexp ""))))
9292 (fallback
9293 (or disable
9294 (not
9295 (let* ,bindings
9296 (org-context-p 'headline 'item
9297 ,(when (memq fun
9298 '(org-insert-heading
9299 org-insert-heading-respect-content
9300 org-meta-return))
9301 '(when orgstruct-is-++
9302 'item-body))))))))
9303 (if fallback
9304 (let* ((orgstruct-mode)
9305 (binding
9306 (let ((key ,key))
9307 (catch 'exit
9308 (dolist
9309 (rep
9310 '(nil
9311 ("<\\([^>]*\\)tab>" . "\\1TAB")
9312 ("<\\([^>]*\\)return>" . "\\1RET")
9313 ("<\\([^>]*\\)escape>" . "\\1ESC")
9314 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9315 nil)
9316 (when rep
9317 (setq key (read-kbd-macro
9318 (let ((case-fold-search))
9319 (replace-regexp-in-string
9320 (car rep)
9321 (cdr rep)
9322 (key-description key))))))
9323 (when (key-binding key)
9324 (throw 'exit (key-binding key))))))))
9325 (if (keymapp binding)
9326 (org-set-transient-map binding)
9327 (let ((func (or binding
9328 (unless disable
9329 'orgstruct-error))))
9330 (when func
9331 (call-interactively func)))))
9332 (org-run-like-in-org-mode
9333 (lambda ()
9334 (interactive)
9335 (let* ,bindings
9336 (call-interactively ',fun)))))))))
9337 name))
9339 (defun org-contextualize-keys (alist contexts)
9340 "Return valid elements in ALIST depending on CONTEXTS.
9342 `org-agenda-custom-commands' or `org-capture-templates' are the
9343 values used for ALIST, and `org-agenda-custom-commands-contexts'
9344 or `org-capture-templates-contexts' are the associated contexts
9345 definitions."
9346 (let ((contexts
9347 ;; normalize contexts
9348 (mapcar
9349 (lambda(c) (cond ((listp (cadr c))
9350 (list (car c) (car c) (nth 1 c)))
9351 ((string= "" (cadr c))
9352 (list (car c) (car c) (nth 2 c)))
9353 (t c)))
9354 contexts))
9355 (a alist) r s)
9356 ;; loop over all commands or templates
9357 (dolist (c a)
9358 (let (vrules repl)
9359 (cond
9360 ((not (assoc (car c) contexts))
9361 (push c r))
9362 ((and (assoc (car c) contexts)
9363 (setq vrules (org-contextualize-validate-key
9364 (car c) contexts)))
9365 (mapc (lambda (vr)
9366 (unless (equal (car vr) (cadr vr))
9367 (setq repl vr)))
9368 vrules)
9369 (if (not repl) (push c r)
9370 (push (cadr repl) s)
9371 (push
9372 (cons (car c)
9373 (cdr (or (assoc (cadr repl) alist)
9374 (error "Undefined key `%s' as contextual replacement for `%s'"
9375 (cadr repl) (car c)))))
9376 r))))))
9377 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9378 (delq
9380 (delete-dups
9381 (mapcar (lambda (x)
9382 (let ((tpl (car x)))
9383 (unless (delq
9385 (mapcar (lambda (y)
9386 (equal y tpl))
9388 x)))
9389 (reverse r))))))
9391 (defun org-contextualize-validate-key (key contexts)
9392 "Check CONTEXTS for agenda or capture KEY."
9393 (let (res)
9394 (dolist (r contexts)
9395 (dolist (rr (car (last r)))
9396 (when
9397 (and (equal key (car r))
9398 (if (functionp rr) (funcall rr)
9399 (or (and (eq (car rr) 'in-file)
9400 (buffer-file-name)
9401 (string-match (cdr rr) (buffer-file-name)))
9402 (and (eq (car rr) 'in-mode)
9403 (string-match (cdr rr) (symbol-name major-mode)))
9404 (and (eq (car rr) 'in-buffer)
9405 (string-match (cdr rr) (buffer-name)))
9406 (when (and (eq (car rr) 'not-in-file)
9407 (buffer-file-name))
9408 (not (string-match (cdr rr) (buffer-file-name))))
9409 (when (eq (car rr) 'not-in-mode)
9410 (not (string-match (cdr rr) (symbol-name major-mode))))
9411 (when (eq (car rr) 'not-in-buffer)
9412 (not (string-match (cdr rr) (buffer-name)))))))
9413 (push r res))))
9414 (delete-dups (delq nil res))))
9416 (defun org-context-p (&rest contexts)
9417 "Check if local context is any of CONTEXTS.
9418 Possible values in the list of contexts are `table', `headline', and `item'."
9419 (let ((pos (point)))
9420 (goto-char (point-at-bol))
9421 (prog1 (or (and (memq 'table contexts)
9422 (looking-at "[ \t]*|"))
9423 (and (memq 'headline contexts)
9424 (looking-at org-outline-regexp))
9425 (and (memq 'item contexts)
9426 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9427 (and (memq 'item-body contexts)
9428 (org-in-item-p)))
9429 (goto-char pos))))
9431 (defconst org-unique-local-variables
9432 '(org-element--cache
9433 org-element--cache-objects
9434 org-element--cache-sync-keys
9435 org-element--cache-sync-requests
9436 org-element--cache-sync-timer)
9437 "List of local variables that cannot be transferred to another buffer.")
9439 (defun org-get-local-variables ()
9440 "Return a list of all local variables in an Org mode buffer."
9441 (delq nil
9442 (mapcar
9443 (lambda (x)
9444 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9445 (name (car binding)))
9446 (and (not (get name 'org-state))
9447 (not (memq name org-unique-local-variables))
9448 (string-match-p
9449 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9450 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9451 (symbol-name name))
9452 binding)))
9453 (with-temp-buffer
9454 (org-mode)
9455 (buffer-local-variables)))))
9457 (defun org-clone-local-variables (from-buffer &optional regexp)
9458 "Clone local variables from FROM-BUFFER.
9459 Optional argument REGEXP selects variables to clone."
9460 (dolist (pair (buffer-local-variables from-buffer))
9461 (pcase pair
9462 (`(,name . ,value) ;ignore unbound variables
9463 (when (and (not (memq name org-unique-local-variables))
9464 (or (null regexp) (string-match-p regexp (symbol-name name))))
9465 (set (make-local-variable name) value))))))
9467 ;;;###autoload
9468 (defun org-run-like-in-org-mode (cmd)
9469 "Run a command, pretending that the current buffer is in Org mode.
9470 This will temporarily bind local variables that are typically bound in
9471 Org mode to the values they have in Org mode, and then interactively
9472 call CMD."
9473 (org-load-modules-maybe)
9474 (unless org-local-vars
9475 (setq org-local-vars (org-get-local-variables)))
9476 (let (binds)
9477 (dolist (var org-local-vars)
9478 (when (or (not (boundp (car var)))
9479 (eq (symbol-value (car var))
9480 (default-value (car var))))
9481 (push (list (car var) `(quote ,(cadr var))) binds)))
9482 (eval `(let ,binds
9483 (call-interactively (quote ,cmd))))))
9485 (defun org-get-category (&optional pos force-refresh)
9486 "Get the category applying to position POS."
9487 (save-match-data
9488 (when force-refresh (org-refresh-category-properties))
9489 (let ((pos (or pos (point))))
9490 (or (get-text-property pos 'org-category)
9491 (progn (org-refresh-category-properties)
9492 (get-text-property pos 'org-category))))))
9494 ;;; Refresh properties
9496 (defun org-refresh-properties (dprop tprop)
9497 "Refresh buffer text properties.
9498 DPROP is the drawer property and TPROP is either the
9499 corresponding text property to set, or an alist with each element
9500 being a text property (as a symbol) and a function to apply to
9501 the value of the drawer property."
9502 (let* ((case-fold-search t)
9503 (inhibit-read-only t)
9504 (inherit? (org-property-inherit-p dprop))
9505 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9506 (global (and inherit? (org--property-global-value dprop nil))))
9507 (org-with-silent-modifications
9508 (org-with-point-at 1
9509 ;; Set global values (e.g., values defined through
9510 ;; "#+PROPERTY:" keywords) to the whole buffer.
9511 (when global (put-text-property (point-min) (point-max) tprop global))
9512 ;; Set local values.
9513 (while (re-search-forward property-re nil t)
9514 (when (org-at-property-p)
9515 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9516 (outline-next-heading))))))
9518 (defun org-refresh-property (tprop p &optional inherit)
9519 "Refresh the buffer text property TPROP from the drawer property P.
9520 The refresh happens only for the current headline, or the whole
9521 sub-tree if optional argument INHERIT is non-nil."
9522 (unless (org-before-first-heading-p)
9523 (save-excursion
9524 (org-back-to-heading t)
9525 (let ((start (point))
9526 (end (save-excursion
9527 (if inherit (org-end-of-subtree t t)
9528 (or (outline-next-heading) (point-max))))))
9529 (if (symbolp tprop)
9530 ;; TPROP is a text property symbol.
9531 (put-text-property start end tprop p)
9532 ;; TPROP is an alist with (property . function) elements.
9533 (pcase-dolist (`(,prop . ,f) tprop)
9534 (put-text-property start end prop (funcall f p))))))))
9536 (defun org-refresh-category-properties ()
9537 "Refresh category text properties in the buffer."
9538 (let ((case-fold-search t)
9539 (inhibit-read-only t)
9540 (default-category
9541 (cond ((null org-category)
9542 (if buffer-file-name
9543 (file-name-sans-extension
9544 (file-name-nondirectory buffer-file-name))
9545 "???"))
9546 ((symbolp org-category) (symbol-name org-category))
9547 (t org-category))))
9548 (org-with-silent-modifications
9549 (org-with-wide-buffer
9550 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9551 ;; This is the default category for the buffer. If none is
9552 ;; found, fall-back to `org-category' or buffer file name.
9553 (put-text-property
9554 (point-min) (point-max)
9555 'org-category
9556 (catch 'buffer-category
9557 (goto-char (point-max))
9558 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9559 (let ((element (org-element-at-point)))
9560 (when (eq (org-element-type element) 'keyword)
9561 (throw 'buffer-category
9562 (org-element-property :value element)))))
9563 default-category))
9564 ;; Set sub-tree specific categories.
9565 (goto-char (point-min))
9566 (let ((regexp (org-re-property "CATEGORY")))
9567 (while (re-search-forward regexp nil t)
9568 (let ((value (match-string-no-properties 3)))
9569 (when (org-at-property-p)
9570 (put-text-property
9571 (save-excursion (org-back-to-heading t) (point))
9572 (save-excursion (org-end-of-subtree t t) (point))
9573 'org-category
9574 value)))))))))
9576 (defun org-refresh-stats-properties ()
9577 "Refresh stats text properties in the buffer."
9578 (org-with-silent-modifications
9579 (org-with-point-at 1
9580 (let ((regexp (concat org-outline-regexp-bol
9581 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9582 (while (re-search-forward regexp nil t)
9583 (let* ((numerator (string-to-number (match-string 1)))
9584 (denominator (and (match-end 2)
9585 (string-to-number (match-string 2))))
9586 (stats (cond ((not denominator) numerator) ;percent
9587 ((= denominator 0) 0)
9588 (t (/ (* numerator 100) denominator)))))
9589 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9590 'org-stats stats)))))))
9592 (defun org-refresh-effort-properties ()
9593 "Refresh effort properties"
9594 (org-refresh-properties
9595 org-effort-property
9596 '((effort . identity)
9597 (effort-minutes . org-duration-to-minutes))))
9599 ;;;; Link Stuff
9601 ;;; Link abbreviations
9603 (defun org-link-expand-abbrev (link)
9604 "Apply replacements as defined in `org-link-abbrev-alist'."
9605 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9606 (let* ((key (match-string 1 link))
9607 (as (or (assoc key org-link-abbrev-alist-local)
9608 (assoc key org-link-abbrev-alist)))
9609 (tag (and (match-end 2) (match-string 3 link)))
9610 rpl)
9611 (if (not as)
9612 link
9613 (setq rpl (cdr as))
9614 (cond
9615 ((symbolp rpl) (funcall rpl tag))
9616 ((string-match "%(\\([^)]+\\))" rpl)
9617 (replace-match
9618 (save-match-data
9619 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9620 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9621 ((string-match "%h" rpl)
9622 (replace-match (url-hexify-string (or tag "")) t t rpl))
9623 (t (concat rpl tag)))))
9624 link))
9626 ;;; Storing and inserting links
9628 (defvar org-insert-link-history nil
9629 "Minibuffer history for links inserted with `org-insert-link'.")
9631 (defvar org-stored-links nil
9632 "Contains the links stored with `org-store-link'.")
9634 (defvar org-store-link-plist nil
9635 "Plist with info about the most recently link created with `org-store-link'.")
9637 (defun org-store-link-functions ()
9638 "Return a list of functions that are called to create and store a link.
9639 The functions defined in the :store property of
9640 `org-link-parameters'.
9642 Each function will be called in turn until one returns a non-nil
9643 value. Each function should check if it is responsible for
9644 creating this link (for example by looking at the major mode).
9645 If not, it must exit and return nil. If yes, it should return
9646 a non-nil value after calling `org-store-link-props' with a list
9647 of properties and values. Special properties are:
9649 :type The link prefix, like \"http\". This must be given.
9650 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9651 This is obligatory as well.
9652 :description Optional default description for the second pair
9653 of brackets in an Org mode link. The user can still change
9654 this when inserting this link into an Org mode buffer.
9656 In addition to these, any additional properties can be specified
9657 and then used in capture templates."
9658 (cl-loop for link in org-link-parameters
9659 with store-func
9660 do (setq store-func (org-link-get-parameter (car link) :store))
9661 if store-func
9662 collect store-func))
9664 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9665 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9667 ;;;###autoload
9668 (defun org-store-link (arg)
9669 "Store an org-link to the current location.
9670 \\<org-mode-map>
9671 This link is added to `org-stored-links' and can later be inserted
9672 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9674 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9675 A single
9676 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9677 `org-gnus-prefer-web-links' for links to Usenet articles.
9679 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9680 skipping storing functions that are not
9681 part of Org core.
9683 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9684 prefix ARG forces storing a link for each line in the
9685 active region."
9686 (interactive "P")
9687 (org-load-modules-maybe)
9688 (if (and (equal arg '(64)) (org-region-active-p))
9689 (save-excursion
9690 (let ((end (region-end)))
9691 (goto-char (region-beginning))
9692 (set-mark (point))
9693 (while (< (point-at-eol) end)
9694 (move-end-of-line 1) (activate-mark)
9695 (let (current-prefix-arg)
9696 (call-interactively 'org-store-link))
9697 (move-beginning-of-line 2)
9698 (set-mark (point)))))
9699 (setq org-store-link-plist nil)
9700 (let (link cpltxt desc description search
9701 txt custom-id agenda-link sfuns sfunsn)
9702 (cond
9704 ;; Store a link using an external link type
9705 ((and (not (equal arg '(16)))
9706 (setq sfuns
9707 (delq
9708 nil (mapcar (lambda (f)
9709 (let (fs) (if (funcall f) (push f fs))))
9710 (org-store-link-functions)))
9711 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9712 (or (and (cdr sfuns)
9713 (funcall (intern
9714 (completing-read
9715 "Which function for creating the link? "
9716 sfunsn nil t (car sfunsn)))))
9717 (funcall (caar sfuns)))
9718 (setq link (plist-get org-store-link-plist :link)
9719 desc (or (plist-get org-store-link-plist
9720 :description)
9721 link))))
9723 ;; Store a link from a source code buffer.
9724 ((org-src-edit-buffer-p)
9725 (let ((coderef-format (org-src-coderef-format)))
9726 (cond ((save-excursion
9727 (beginning-of-line)
9728 (looking-at (org-src-coderef-regexp coderef-format)))
9729 (setq link (format "(%s)" (match-string-no-properties 3))))
9730 ((called-interactively-p 'any)
9731 (let ((label (read-string "Code line label: ")))
9732 (end-of-line)
9733 (setq link (format coderef-format label))
9734 (let ((gc (- 79 (length link))))
9735 (if (< (current-column) gc)
9736 (org-move-to-column gc t)
9737 (insert " ")))
9738 (insert link)
9739 (setq link (concat "(" label ")"))
9740 (setq desc nil)))
9741 (t (setq link nil)))))
9743 ;; We are in the agenda, link to referenced location
9744 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9745 (let ((m (or (get-text-property (point) 'org-hd-marker)
9746 (get-text-property (point) 'org-marker))))
9747 (when m
9748 (org-with-point-at m
9749 (setq agenda-link
9750 (if (called-interactively-p 'any)
9751 (call-interactively 'org-store-link)
9752 (org-store-link nil)))))))
9754 ((eq major-mode 'calendar-mode)
9755 (let ((cd (calendar-cursor-to-date)))
9756 (setq link
9757 (format-time-string
9758 (car org-time-stamp-formats)
9759 (apply 'encode-time
9760 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9761 nil nil nil))))
9762 (org-store-link-props :type "calendar" :date cd)))
9764 ((eq major-mode 'help-mode)
9765 (setq link (concat "help:" (save-excursion
9766 (goto-char (point-min))
9767 (looking-at "^[^ ]+")
9768 (match-string 0))))
9769 (org-store-link-props :type "help"))
9771 ((eq major-mode 'w3-mode)
9772 (setq cpltxt (if (and (buffer-name)
9773 (not (string-match "Untitled" (buffer-name))))
9774 (buffer-name)
9775 (url-view-url t))
9776 link (url-view-url t))
9777 (org-store-link-props :type "w3" :url (url-view-url t)))
9779 ((eq major-mode 'image-mode)
9780 (setq cpltxt (concat "file:"
9781 (abbreviate-file-name buffer-file-name))
9782 link cpltxt)
9783 (org-store-link-props :type "image" :file buffer-file-name))
9785 ;; In dired, store a link to the file of the current line
9786 ((derived-mode-p 'dired-mode)
9787 (let ((file (dired-get-filename nil t)))
9788 (setq file (if file
9789 (abbreviate-file-name
9790 (expand-file-name (dired-get-filename nil t)))
9791 ;; otherwise, no file so use current directory.
9792 default-directory))
9793 (setq cpltxt (concat "file:" file)
9794 link cpltxt)))
9796 ((setq search (run-hook-with-args-until-success
9797 'org-create-file-search-functions))
9798 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9799 "::" search))
9800 (setq cpltxt (or description link)))
9802 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9803 (org-with-limited-levels
9804 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9805 (cond
9806 ;; Store a link using the target at point
9807 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9808 (setq cpltxt
9809 (concat "file:"
9810 (abbreviate-file-name
9811 (buffer-file-name (buffer-base-buffer)))
9812 "::" (match-string 1))
9813 link cpltxt))
9814 ((and (featurep 'org-id)
9815 (or (eq org-id-link-to-org-use-id t)
9816 (and (called-interactively-p 'any)
9817 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9818 (and (eq org-id-link-to-org-use-id
9819 'create-if-interactive-and-no-custom-id)
9820 (not custom-id))))
9821 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9822 ;; Store a link using the ID at point
9823 (setq link (condition-case nil
9824 (prog1 (org-id-store-link)
9825 (setq desc (or (plist-get org-store-link-plist
9826 :description)
9827 "")))
9828 (error
9829 ;; Probably before first headline, link only to file
9830 (concat "file:"
9831 (abbreviate-file-name
9832 (buffer-file-name (buffer-base-buffer))))))))
9834 ;; Just link to current headline
9835 (setq cpltxt (concat "file:"
9836 (abbreviate-file-name
9837 (buffer-file-name (buffer-base-buffer)))))
9838 ;; Add a context search string
9839 (when (org-xor org-context-in-file-links
9840 (equal arg '(4)))
9841 (let* ((element (org-element-at-point))
9842 (name (org-element-property :name element)))
9843 (setq txt (cond
9844 ((org-at-heading-p) nil)
9845 (name)
9846 ((org-region-active-p)
9847 (buffer-substring (region-beginning) (region-end)))))
9848 (when (or (null txt) (string-match "\\S-" txt))
9849 (setq cpltxt
9850 (concat cpltxt "::"
9851 (condition-case nil
9852 (org-make-org-heading-search-string txt)
9853 (error "")))
9854 desc (or name
9855 (nth 4 (ignore-errors (org-heading-components)))
9856 "NONE")))))
9857 (when (string-match "::\\'" cpltxt)
9858 (setq cpltxt (substring cpltxt 0 -2)))
9859 (setq link cpltxt)))))
9861 ((buffer-file-name (buffer-base-buffer))
9862 ;; Just link to this file here.
9863 (setq cpltxt (concat "file:"
9864 (abbreviate-file-name
9865 (buffer-file-name (buffer-base-buffer)))))
9866 ;; Add a context string.
9867 (when (org-xor org-context-in-file-links
9868 (equal arg '(4)))
9869 (setq txt (if (org-region-active-p)
9870 (buffer-substring (region-beginning) (region-end))
9871 (buffer-substring (point-at-bol) (point-at-eol))))
9872 ;; Only use search option if there is some text.
9873 (when (string-match "\\S-" txt)
9874 (setq cpltxt
9875 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9876 desc "NONE")))
9877 (setq link cpltxt))
9879 ((called-interactively-p 'interactive)
9880 (user-error "No method for storing a link from this buffer"))
9882 (t (setq link nil)))
9884 ;; We're done setting link and desc, clean up
9885 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9886 (setq link (or link cpltxt)
9887 desc (or desc cpltxt))
9888 (cond ((not desc))
9889 ((equal desc "NONE") (setq desc nil))
9890 (t (setq desc
9891 (replace-regexp-in-string
9892 org-bracket-link-analytic-regexp
9893 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9894 desc))))
9895 ;; Return the link
9896 (if (not (and (or (called-interactively-p 'any)
9897 executing-kbd-macro)
9898 link))
9899 (or agenda-link (and link (org-make-link-string link desc)))
9900 (push (list link desc) org-stored-links)
9901 (message "Stored: %s" (or desc link))
9902 (when custom-id
9903 (setq link (concat "file:" (abbreviate-file-name
9904 (buffer-file-name)) "::#" custom-id))
9905 (push (list link desc) org-stored-links))
9906 (car org-stored-links)))))
9908 (defun org-store-link-props (&rest plist)
9909 "Store link properties, extract names, addresses and dates."
9910 (let ((x (plist-get plist :from)))
9911 (when x
9912 (let ((adr (mail-extract-address-components x)))
9913 (setq plist (plist-put plist :fromname (car adr)))
9914 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9915 (let ((x (plist-get plist :to)))
9916 (when x
9917 (let ((adr (mail-extract-address-components x)))
9918 (setq plist (plist-put plist :toname (car adr)))
9919 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9920 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9921 (when x
9922 (setq plist (plist-put plist :date-timestamp
9923 (format-time-string
9924 (org-time-stamp-format t) x)))
9925 (setq plist (plist-put plist :date-timestamp-inactive
9926 (format-time-string
9927 (org-time-stamp-format t t) x)))))
9928 (let ((from (plist-get plist :from))
9929 (to (plist-get plist :to)))
9930 (when (and from to org-from-is-user-regexp)
9931 (setq plist
9932 (plist-put plist :fromto
9933 (if (string-match org-from-is-user-regexp from)
9934 (concat "to %t")
9935 (concat "from %f"))))))
9936 (setq org-store-link-plist plist))
9938 (defun org-add-link-props (&rest plist)
9939 "Add these properties to the link property list."
9940 (let (key value)
9941 (while plist
9942 (setq key (pop plist) value (pop plist))
9943 (setq org-store-link-plist
9944 (plist-put org-store-link-plist key value)))))
9946 (defun org-email-link-description (&optional fmt)
9947 "Return the description part of an email link.
9948 This takes information from `org-store-link-plist' and formats it
9949 according to FMT (default from `org-email-link-description-format')."
9950 (setq fmt (or fmt org-email-link-description-format))
9951 (let* ((p org-store-link-plist)
9952 (to (plist-get p :toaddress))
9953 (from (plist-get p :fromaddress))
9954 (table
9955 (list
9956 (cons "%c" (plist-get p :fromto))
9957 (cons "%F" (plist-get p :from))
9958 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9959 (cons "%T" (plist-get p :to))
9960 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9961 (cons "%s" (plist-get p :subject))
9962 (cons "%d" (plist-get p :date))
9963 (cons "%m" (plist-get p :message-id)))))
9964 (when (string-match "%c" fmt)
9965 ;; Check if the user wrote this message
9966 (if (and org-from-is-user-regexp from to
9967 (save-match-data (string-match org-from-is-user-regexp from)))
9968 (setq fmt (replace-match "to %t" t t fmt))
9969 (setq fmt (replace-match "from %f" t t fmt))))
9970 (org-replace-escapes fmt table)))
9972 (defun org-make-org-heading-search-string (&optional string)
9973 "Make search string for the current headline or STRING."
9974 (let ((s (or string
9975 (and (derived-mode-p 'org-mode)
9976 (save-excursion
9977 (org-back-to-heading t)
9978 (org-element-property :raw-value (org-element-at-point))))))
9979 (lines org-context-in-file-links))
9980 (or string (setq s (concat "*" s))) ; Add * for headlines
9981 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9982 (when (and string (integerp lines) (> lines 0))
9983 (let ((slines (org-split-string s "\n")))
9984 (when (< lines (length slines))
9985 (setq s (mapconcat
9986 'identity
9987 (reverse (nthcdr (- (length slines) lines)
9988 (reverse slines))) "\n")))))
9989 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9991 (defun org-make-link-string (link &optional description)
9992 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9993 (unless (org-string-nw-p link) (error "Empty link"))
9994 (let ((uri (cond ((string-match org-link-types-re link)
9995 (concat (match-string 1 link)
9996 (org-link-escape (substring link (match-end 1)))))
9997 ;; For readability, url-encode internal links only
9998 ;; when absolutely needed (i.e, when they contain
9999 ;; square brackets). File links however, are
10000 ;; encoded since, e.g., spaces are significant.
10001 ((or (file-name-absolute-p link)
10002 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10003 (org-link-escape link))
10004 (t link)))
10005 (description
10006 (and (org-string-nw-p description)
10007 ;; Remove brackets from description, as they are fatal.
10008 (replace-regexp-in-string
10009 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10010 (org-trim description)))))
10011 (format "[[%s]%s]"
10013 (if description (format "[%s]" description) ""))))
10015 (defconst org-link-escape-chars
10016 ;;%20 %5B %5D %25
10017 '(?\s ?\[ ?\] ?%)
10018 "List of characters that should be escaped in a link when stored to Org.
10019 This is the list that is used for internal purposes.")
10021 (defun org-link-escape (text &optional table merge)
10022 "Return percent escaped representation of TEXT.
10023 TEXT is a string with the text to escape.
10024 Optional argument TABLE is a list with characters that should be
10025 escaped. When nil, `org-link-escape-chars' is used.
10026 If optional argument MERGE is set, merge TABLE into
10027 `org-link-escape-chars'."
10028 (let ((characters-to-encode
10029 (cond ((null table) org-link-escape-chars)
10030 (merge (append org-link-escape-chars table))
10031 (t table))))
10032 (mapconcat
10033 (lambda (c)
10034 (if (or (memq c characters-to-encode)
10035 (and org-url-hexify-p (or (< c 32) (> c 126))))
10036 (mapconcat (lambda (e) (format "%%%.2X" e))
10037 (or (encode-coding-char c 'utf-8)
10038 (error "Unable to percent escape character: %c" c))
10040 (char-to-string c)))
10041 text "")))
10043 (defun org-link-unescape (str)
10044 "Unhex hexified Unicode parts in string STR.
10045 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10046 reciprocal of `org-link-escape', which see."
10047 (if (org-string-nw-p str)
10048 (replace-regexp-in-string
10049 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10050 str))
10052 (defun org-link-unescape-compound (hex)
10053 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10054 Note: this function also decodes single byte encodings like
10055 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10056 (save-match-data
10057 (let* ((bytes (cdr (split-string hex "%")))
10058 (ret "")
10059 (eat 0)
10060 (sum 0))
10061 (while bytes
10062 (let* ((val (string-to-number (pop bytes) 16))
10063 (shift-xor
10064 (if (= 0 eat)
10065 (cond
10066 ((>= val 252) (cons 6 252))
10067 ((>= val 248) (cons 5 248))
10068 ((>= val 240) (cons 4 240))
10069 ((>= val 224) (cons 3 224))
10070 ((>= val 192) (cons 2 192))
10071 (t (cons 0 0)))
10072 (cons 6 128))))
10073 (when (>= val 192) (setq eat (car shift-xor)))
10074 (setq val (logxor val (cdr shift-xor)))
10075 (setq sum (+ (lsh sum (car shift-xor)) val))
10076 (when (> eat 0) (setq eat (- eat 1)))
10077 (cond
10078 ((= 0 eat) ;multi byte
10079 (setq ret (concat ret (char-to-string sum)))
10080 (setq sum 0))
10081 ((not bytes) ; single byte(s)
10082 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10083 ret)))
10085 (defun org-link-unescape-single-byte-sequence (hex)
10086 "Unhexify hex-encoded single byte character sequences."
10087 (mapconcat (lambda (byte)
10088 (char-to-string (string-to-number byte 16)))
10089 (cdr (split-string hex "%")) ""))
10091 (defun org-xor (a b)
10092 "Exclusive or."
10093 (if a (not b) b))
10095 (defun org-fixup-message-id-for-http (s)
10096 "Replace special characters in a message id, so it can be used in an http query."
10097 (when (string-match "%" s)
10098 (setq s (mapconcat (lambda (c)
10099 (if (eq c ?%)
10100 "%25"
10101 (char-to-string c)))
10102 s "")))
10103 (while (string-match "<" s)
10104 (setq s (replace-match "%3C" t t s)))
10105 (while (string-match ">" s)
10106 (setq s (replace-match "%3E" t t s)))
10107 (while (string-match "@" s)
10108 (setq s (replace-match "%40" t t s)))
10111 (defun org-link-prettify (link)
10112 "Return a human-readable representation of LINK.
10113 The car of LINK must be a raw link.
10114 The cdr of LINK must be either a link description or nil."
10115 (let ((desc (or (cadr link) "<no description>")))
10116 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10117 "<" (car link) ">")))
10119 ;;;###autoload
10120 (defun org-insert-link-global ()
10121 "Insert a link like Org mode does.
10122 This command can be called in any mode to insert a link in Org syntax."
10123 (interactive)
10124 (org-load-modules-maybe)
10125 (org-run-like-in-org-mode 'org-insert-link))
10127 (defun org-insert-all-links (arg &optional pre post)
10128 "Insert all links in `org-stored-links'.
10129 When a universal prefix, do not delete the links from `org-stored-links'.
10130 When `ARG' is a number, insert the last N link(s).
10131 `PRE' and `POST' are optional arguments to define a string to
10132 prepend or to append."
10133 (interactive "P")
10134 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10135 (links (copy-sequence org-stored-links))
10136 (pr (or pre "- "))
10137 (po (or post "\n"))
10138 (cnt 1) l)
10139 (if (null org-stored-links)
10140 (message "No link to insert")
10141 (while (and (or (listp arg) (>= arg cnt))
10142 (setq l (if (listp arg)
10143 (pop links)
10144 (pop org-stored-links))))
10145 (setq cnt (1+ cnt))
10146 (insert pr)
10147 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10148 (insert po)))))
10150 (defun org-insert-last-stored-link (arg)
10151 "Insert the last link stored in `org-stored-links'."
10152 (interactive "p")
10153 (org-insert-all-links arg "" "\n"))
10155 (defun org-link-fontify-links-to-this-file ()
10156 "Fontify links to the current file in `org-stored-links'."
10157 (let ((f (buffer-file-name)) a b)
10158 (setq a (mapcar (lambda(l)
10159 (let ((ll (car l)))
10160 (when (and (string-match "^file:\\(.+\\)::" ll)
10161 (equal f (expand-file-name (match-string 1 ll))))
10162 ll)))
10163 org-stored-links))
10164 (when (featurep 'org-id)
10165 (setq b (mapcar (lambda(l)
10166 (let ((ll (car l)))
10167 (when (and (string-match "^id:\\(.+\\)$" ll)
10168 (equal f (expand-file-name
10169 (or (org-id-find-id-file
10170 (match-string 1 ll)) ""))))
10171 ll)))
10172 org-stored-links)))
10173 (mapcar (lambda(l)
10174 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10175 (delq nil (append a b)))))
10177 (defvar org--links-history nil)
10178 (defun org-insert-link (&optional complete-file link-location default-description)
10179 "Insert a link. At the prompt, enter the link.
10181 Completion can be used to insert any of the link protocol prefixes in use.
10183 The history can be used to select a link previously stored with
10184 `org-store-link'. When the empty string is entered (i.e. if you just
10185 press `RET' at the prompt), the link defaults to the most recently
10186 stored link. As `SPC' triggers completion in the minibuffer, you need to
10187 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10189 You will also be prompted for a description, and if one is given, it will
10190 be displayed in the buffer instead of the link.
10192 If there is already a link at point, this command will allow you to edit
10193 link and description parts.
10195 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10196 file name can be
10197 selected using completion. The path to the file will be relative to the
10198 current directory if the file is in the current directory or a subdirectory.
10199 Otherwise, the link will be the absolute path as completed in the minibuffer
10200 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10201 option `org-link-file-path-type'.
10203 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10204 absolute path even if the file is in
10205 the current directory or below.
10207 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10208 prefix negates `org-keep-stored-link-after-insertion'.
10210 If `org-make-link-description-function' is non-nil, this function will be
10211 called with the link target, and the result will be the default
10212 link description.
10214 If the LINK-LOCATION parameter is non-nil, this value will be used as
10215 the link location instead of reading one interactively.
10217 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10218 as the default description."
10219 (interactive "P")
10220 (let* ((wcf (current-window-configuration))
10221 (origbuf (current-buffer))
10222 (region (when (org-region-active-p)
10223 (buffer-substring (region-beginning) (region-end))))
10224 (remove (and region (list (region-beginning) (region-end))))
10225 (desc region)
10226 (link link-location)
10227 (abbrevs org-link-abbrev-alist-local)
10228 entry all-prefixes auto-desc)
10229 (cond
10230 (link-location) ; specified by arg, just use it.
10231 ((org-in-regexp org-bracket-link-regexp 1)
10232 ;; We do have a link at point, and we are going to edit it.
10233 (setq remove (list (match-beginning 0) (match-end 0)))
10234 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10235 (setq link (read-string "Link: "
10236 (org-link-unescape
10237 (match-string-no-properties 1)))))
10238 ((or (org-in-regexp org-angle-link-re)
10239 (org-in-regexp org-plain-link-re))
10240 ;; Convert to bracket link
10241 (setq remove (list (match-beginning 0) (match-end 0))
10242 link (read-string "Link: "
10243 (org-unbracket-string "<" ">" (match-string 0)))))
10244 ((member complete-file '((4) (16)))
10245 ;; Completing read for file names.
10246 (setq link (org-file-complete-link complete-file)))
10248 ;; Read link, with completion for stored links.
10249 (org-link-fontify-links-to-this-file)
10250 (org-switch-to-buffer-other-window "*Org Links*")
10251 (with-current-buffer "*Org Links*"
10252 (erase-buffer)
10253 (insert "Insert a link.
10254 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10255 (when org-stored-links
10256 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10257 (insert (mapconcat 'org-link-prettify
10258 (reverse org-stored-links) "\n")))
10259 (goto-char (point-min)))
10260 (let ((cw (selected-window)))
10261 (select-window (get-buffer-window "*Org Links*" 'visible))
10262 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10263 (unless (pos-visible-in-window-p (point-max))
10264 (org-fit-window-to-buffer))
10265 (and (window-live-p cw) (select-window cw)))
10266 (setq all-prefixes (append (mapcar 'car abbrevs)
10267 (mapcar 'car org-link-abbrev-alist)
10268 (org-link-types)))
10269 (unwind-protect
10270 ;; Fake a link history, containing the stored links.
10271 (let ((org--links-history
10272 (append (mapcar #'car org-stored-links)
10273 org-insert-link-history)))
10274 (setq link
10275 (org-completing-read
10276 "Link: "
10277 (append
10278 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10279 (mapcar #'car org-stored-links))
10280 nil nil nil
10281 'org--links-history
10282 (caar org-stored-links)))
10283 (unless (org-string-nw-p link) (user-error "No link selected"))
10284 (dolist (l org-stored-links)
10285 (when (equal link (cadr l))
10286 (setq link (car l))
10287 (setq auto-desc t)))
10288 (when (or (member link all-prefixes)
10289 (and (equal ":" (substring link -1))
10290 (member (substring link 0 -1) all-prefixes)
10291 (setq link (substring link 0 -1))))
10292 (setq link (with-current-buffer origbuf
10293 (org-link-try-special-completion link)))))
10294 (set-window-configuration wcf)
10295 (kill-buffer "*Org Links*"))
10296 (setq entry (assoc link org-stored-links))
10297 (or entry (push link org-insert-link-history))
10298 (setq desc (or desc (nth 1 entry)))))
10300 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10301 (not org-keep-stored-link-after-insertion))
10302 (setq org-stored-links (delq (assoc link org-stored-links)
10303 org-stored-links)))
10305 (when (and (string-match org-plain-link-re link)
10306 (not (string-match org-ts-regexp link)))
10307 ;; URL-like link, normalize the use of angular brackets.
10308 (setq link (org-unbracket-string "<" ">" link)))
10310 ;; Check if we are linking to the current file with a search
10311 ;; option If yes, simplify the link by using only the search
10312 ;; option.
10313 (when (and buffer-file-name
10314 (let ((case-fold-search nil))
10315 (string-match "\\`file:\\(.+?\\)::" link)))
10316 (let ((path (match-string-no-properties 1 link))
10317 (search (substring-no-properties link (match-end 0))))
10318 (save-match-data
10319 (when (equal (file-truename buffer-file-name) (file-truename path))
10320 ;; We are linking to this same file, with a search option
10321 (setq link search)))))
10323 ;; Check if we can/should use a relative path. If yes, simplify the link
10324 (let ((case-fold-search nil))
10325 (when (string-match "\\`\\(file\\|docview\\):" link)
10326 (let* ((type (match-string-no-properties 0 link))
10327 (path (substring-no-properties link (match-end 0)))
10328 (origpath path))
10329 (cond
10330 ((or (eq org-link-file-path-type 'absolute)
10331 (equal complete-file '(16)))
10332 (setq path (abbreviate-file-name (expand-file-name path))))
10333 ((eq org-link-file-path-type 'noabbrev)
10334 (setq path (expand-file-name path)))
10335 ((eq org-link-file-path-type 'relative)
10336 (setq path (file-relative-name path)))
10338 (save-match-data
10339 (if (string-match (concat "^" (regexp-quote
10340 (expand-file-name
10341 (file-name-as-directory
10342 default-directory))))
10343 (expand-file-name path))
10344 ;; We are linking a file with relative path name.
10345 (setq path (substring (expand-file-name path)
10346 (match-end 0)))
10347 (setq path (abbreviate-file-name (expand-file-name path)))))))
10348 (setq link (concat type path))
10349 (when (equal desc origpath)
10350 (setq desc path)))))
10352 (if org-make-link-description-function
10353 (setq desc
10354 (or (condition-case nil
10355 (funcall org-make-link-description-function link desc)
10356 (error (progn (message "Can't get link description from `%s'"
10357 (symbol-name org-make-link-description-function))
10358 (sit-for 2) nil)))
10359 (read-string "Description: " default-description)))
10360 (if default-description (setq desc default-description)
10361 (setq desc (or (and auto-desc desc)
10362 (read-string "Description: " desc)))))
10364 (unless (string-match "\\S-" desc) (setq desc nil))
10365 (when remove (apply 'delete-region remove))
10366 (insert (org-make-link-string link desc))
10367 ;; Redisplay so as the new link has proper invisible characters.
10368 (sit-for 0)))
10370 (defun org-link-try-special-completion (type)
10371 "If there is completion support for link type TYPE, offer it."
10372 (let ((fun (org-link-get-parameter type :complete)))
10373 (if (functionp fun)
10374 (funcall fun)
10375 (read-string "Link (no completion support): " (concat type ":")))))
10377 (defun org-file-complete-link (&optional arg)
10378 "Create a file link using completion."
10379 (let ((file (read-file-name "File: "))
10380 (pwd (file-name-as-directory (expand-file-name ".")))
10381 (pwd1 (file-name-as-directory (abbreviate-file-name
10382 (expand-file-name ".")))))
10383 (cond ((equal arg '(16))
10384 (concat "file:"
10385 (abbreviate-file-name (expand-file-name file))))
10386 ((string-match
10387 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10388 (concat "file:" (match-string 1 file)))
10389 ((string-match
10390 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10391 (expand-file-name file))
10392 (concat "file:"
10393 (match-string 1 (expand-file-name file))))
10394 (t (concat "file:" file)))))
10396 (defun org-completing-read (&rest args)
10397 "Completing-read with SPACE being a normal character."
10398 (let ((enable-recursive-minibuffers t)
10399 (minibuffer-local-completion-map
10400 (copy-keymap minibuffer-local-completion-map)))
10401 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10402 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10403 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10404 'org-time-stamp-inactive)
10405 (apply #'completing-read args)))
10407 ;;; Opening/following a link
10409 (defvar org-link-search-failed nil)
10411 (defvar org-open-link-functions nil
10412 "Hook for functions finding a plain text link.
10413 These functions must take a single argument, the link content.
10414 They will be called for links that look like [[link text][description]]
10415 when LINK TEXT does not have a protocol like \"http:\" and does not look
10416 like a filename (e.g. \"./blue.png\").
10418 These functions will be called *before* Org attempts to resolve the
10419 link by doing text searches in the current buffer - so if you want a
10420 link \"[[target]]\" to still find \"<<target>>\", your function should
10421 handle this as a special case.
10423 When the function does handle the link, it must return a non-nil value.
10424 If it decides that it is not responsible for this link, it must return
10425 nil to indicate that that Org can continue with other options like
10426 exact and fuzzy text search.")
10428 (defun org-next-link (&optional search-backward)
10429 "Move forward to the next link.
10430 If the link is in hidden text, expose it."
10431 (interactive "P")
10432 (when (and org-link-search-failed (eq this-command last-command))
10433 (goto-char (point-min))
10434 (message "Link search wrapped back to beginning of buffer"))
10435 (setq org-link-search-failed nil)
10436 (let* ((pos (point))
10437 (ct (org-context))
10438 (a (assq :link ct))
10439 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10440 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10441 ((looking-at org-any-link-re)
10442 ;; Don't stay stuck at link without an org-link face
10443 (forward-char (if search-backward -1 1))))
10444 (if (funcall srch-fun org-any-link-re nil t)
10445 (progn
10446 (goto-char (match-beginning 0))
10447 (when (org-invisible-p) (org-show-context)))
10448 (goto-char pos)
10449 (setq org-link-search-failed t)
10450 (message "No further link found"))))
10452 (defun org-previous-link ()
10453 "Move backward to the previous link.
10454 If the link is in hidden text, expose it."
10455 (interactive)
10456 (funcall 'org-next-link t))
10458 (defun org-translate-link (s)
10459 "Translate a link string if a translation function has been defined."
10460 (with-temp-buffer
10461 (insert (org-trim s))
10462 (org-trim (org-element-interpret-data (org-element-context)))))
10464 (defun org-translate-link-from-planner (type path)
10465 "Translate a link from Emacs Planner syntax so that Org can follow it.
10466 This is still an experimental function, your mileage may vary."
10467 (cond
10468 ((member type '("http" "https" "news" "ftp"))
10469 ;; standard Internet links are the same.
10470 nil)
10471 ((and (equal type "irc") (string-match "^//" path))
10472 ;; Planner has two / at the beginning of an irc link, we have 1.
10473 ;; We should have zero, actually....
10474 (setq path (substring path 1)))
10475 ((and (equal type "lisp") (string-match "^/" path))
10476 ;; Planner has a slash, we do not.
10477 (setq type "elisp" path (substring path 1)))
10478 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10479 ;; A typical message link. Planner has the id after the final slash,
10480 ;; we separate it with a hash mark
10481 (setq path (concat (match-string 1 path) "#"
10482 (org-unbracket-string "<" ">" (match-string 2 path))))))
10483 (cons type path))
10485 (defun org-find-file-at-mouse (ev)
10486 "Open file link or URL at mouse."
10487 (interactive "e")
10488 (mouse-set-point ev)
10489 (org-open-at-point 'in-emacs))
10491 (defun org-open-at-mouse (ev)
10492 "Open file link or URL at mouse.
10493 See the docstring of `org-open-file' for details."
10494 (interactive "e")
10495 (mouse-set-point ev)
10496 (when (eq major-mode 'org-agenda-mode)
10497 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10498 (org-open-at-point))
10500 (defvar org-window-config-before-follow-link nil
10501 "The window configuration before following a link.
10502 This is saved in case the need arises to restore it.")
10504 ;;;###autoload
10505 (defun org-open-at-point-global ()
10506 "Follow a link or time-stamp like Org mode does.
10507 This command can be called in any mode to follow an external link
10508 or a time-stamp that has Org mode syntax. Its behavior is
10509 undefined when called on internal links (e.g., fuzzy links).
10510 Raise an error when there is nothing to follow. "
10511 (interactive)
10512 (cond ((org-in-regexp org-any-link-re)
10513 (org-open-link-from-string (match-string-no-properties 0)))
10514 ((or (org-in-regexp org-ts-regexp-both nil t)
10515 (org-in-regexp org-tsr-regexp-both nil t))
10516 (org-follow-timestamp-link))
10517 (t (user-error "No link found"))))
10519 ;;;###autoload
10520 (defun org-open-link-from-string (s &optional arg reference-buffer)
10521 "Open a link in the string S, as if it was in Org mode."
10522 (interactive "sLink: \nP")
10523 (let ((reference-buffer (or reference-buffer (current-buffer))))
10524 (with-temp-buffer
10525 (let ((org-inhibit-startup (not reference-buffer)))
10526 (org-mode)
10527 (insert s)
10528 (goto-char (point-min))
10529 (when reference-buffer
10530 (setq org-link-abbrev-alist-local
10531 (with-current-buffer reference-buffer
10532 org-link-abbrev-alist-local)))
10533 (org-open-at-point arg reference-buffer)))))
10535 (defvar org-open-at-point-functions nil
10536 "Hook that is run when following a link at point.
10538 Functions in this hook must return t if they identify and follow
10539 a link at point. If they don't find anything interesting at point,
10540 they must return nil.")
10542 (defvar org-link-search-inhibit-query nil)
10543 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10544 (defun org--open-doi-link (path)
10545 "Open a \"doi\" type link.
10546 PATH is a the path to search for, as a string."
10547 (browse-url (url-encode-url (concat org-doi-server-url path))))
10549 (defun org--open-elisp-link (path)
10550 "Open a \"elisp\" type link.
10551 PATH is the sexp to evaluate, as a string."
10552 (let ((cmd path))
10553 (if (or (and (org-string-nw-p
10554 org-confirm-elisp-link-not-regexp)
10555 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10556 (not org-confirm-elisp-link-function)
10557 (funcall org-confirm-elisp-link-function
10558 (format "Execute \"%s\" as elisp? "
10559 (org-add-props cmd nil 'face 'org-warning))))
10560 (message "%s => %s" cmd
10561 (if (eq (string-to-char cmd) ?\()
10562 (eval (read cmd))
10563 (call-interactively (read cmd))))
10564 (user-error "Abort"))))
10566 (defun org--open-help-link (path)
10567 "Open a \"help\" type link.
10568 PATH is a symbol name, as a string."
10569 (pcase (intern path)
10570 ((and (pred fboundp) variable) (describe-function variable))
10571 ((and (pred boundp) function) (describe-variable function))
10572 (name (user-error "Unknown function or variable: %s" name))))
10574 (defun org--open-shell-link (path)
10575 "Open a \"shell\" type link.
10576 PATH is the command to execute, as a string."
10577 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10578 (cmd path))
10579 (if (or (and (org-string-nw-p
10580 org-confirm-shell-link-not-regexp)
10581 (string-match
10582 org-confirm-shell-link-not-regexp cmd))
10583 (not org-confirm-shell-link-function)
10584 (funcall org-confirm-shell-link-function
10585 (format "Execute \"%s\" in shell? "
10586 (org-add-props cmd nil
10587 'face 'org-warning))))
10588 (progn
10589 (message "Executing %s" cmd)
10590 (shell-command cmd buf)
10591 (when (featurep 'midnight)
10592 (setq clean-buffer-list-kill-buffer-names
10593 (cons (buffer-name buf)
10594 clean-buffer-list-kill-buffer-names))))
10595 (user-error "Abort"))))
10597 (defun org-open-at-point (&optional arg reference-buffer)
10598 "Open link, timestamp, footnote or tags at point.
10600 When point is on a link, follow it. Normally, files will be
10601 opened by an appropriate application. If the optional prefix
10602 argument ARG is non-nil, Emacs will visit the file. With
10603 a double prefix argument, try to open outside of Emacs, in the
10604 application the system uses for this file type.
10606 When point is on a timestamp, open the agenda at the day
10607 specified.
10609 When point is a footnote definition, move to the first reference
10610 found. If it is on a reference, move to the associated
10611 definition.
10613 When point is on a headline, display a list of every link in the
10614 entry, so it is possible to pick one, or all, of them. If point
10615 is on a tag, call `org-tags-view' instead.
10617 When optional argument REFERENCE-BUFFER is non-nil, it should
10618 specify a buffer from where the link search should happen. This
10619 is used internally by `org-open-link-from-string'.
10621 On top of syntactically correct links, this function will also
10622 try to open links and time-stamps in comments, example
10623 blocks... i.e., whenever point is on something looking like
10624 a timestamp or a link."
10625 (interactive "P")
10626 ;; On a code block, open block's results.
10627 (unless (call-interactively 'org-babel-open-src-block-result)
10628 (org-load-modules-maybe)
10629 (setq org-window-config-before-follow-link (current-window-configuration))
10630 (org-remove-occur-highlights nil nil t)
10631 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10632 (let* ((context
10633 ;; Only consider supported types, even if they are not
10634 ;; the closest one.
10635 (org-element-lineage
10636 (org-element-context)
10637 '(clock footnote-definition footnote-reference headline
10638 inlinetask link timestamp)
10640 (type (org-element-type context))
10641 (value (org-element-property :value context)))
10642 (cond
10643 ;; On a headline or an inlinetask, but not on a timestamp,
10644 ;; a link, a footnote reference or on tags.
10645 ((and (memq type '(headline inlinetask))
10646 ;; Not on tags.
10647 (let ((case-fold-search nil))
10648 (and (org-match-line org-complex-heading-regexp)
10649 (or (not (match-beginning 5))
10650 (< (point) (match-beginning 5))))))
10651 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10652 (links (car data))
10653 (links-end (cdr data)))
10654 (if links
10655 (dolist (link (if (stringp links) (list links) links))
10656 (search-forward link nil links-end)
10657 (goto-char (match-beginning 0))
10658 (org-open-at-point))
10659 (require 'org-attach)
10660 (org-attach-reveal 'if-exists))))
10661 ;; On a footnote reference or at definition's label.
10662 ((or (eq type 'footnote-reference)
10663 (and (eq type 'footnote-definition)
10664 (save-excursion
10665 ;; Do not validate action when point is on the
10666 ;; spaces right after the footnote label, in
10667 ;; order to be on par with behaviour on links.
10668 (skip-chars-forward " \t")
10669 (let ((begin
10670 (org-element-property :contents-begin context)))
10671 (if begin (< (point) begin)
10672 (= (org-element-property :post-affiliated context)
10673 (line-beginning-position)))))))
10674 (org-footnote-action))
10675 ;; No valid context. Ignore catch-all types like `headline'.
10676 ;; If point is on something looking like a link or
10677 ;; a time-stamp, try opening it. It may be useful in
10678 ;; comments, example blocks...
10679 ((memq type '(footnote-definition headline inlinetask nil))
10680 (call-interactively #'org-open-at-point-global))
10681 ;; On a clock line, make sure point is on the timestamp
10682 ;; before opening it.
10683 ((and (eq type 'clock)
10684 value
10685 (>= (point) (org-element-property :begin value))
10686 (<= (point) (org-element-property :end value)))
10687 (org-follow-timestamp-link))
10688 ;; Do nothing on white spaces after an object.
10689 ((>= (point)
10690 (save-excursion
10691 (goto-char (org-element-property :end context))
10692 (skip-chars-backward " \t")
10693 (point)))
10694 (user-error "No link found"))
10695 ((eq type 'timestamp) (org-follow-timestamp-link))
10696 ;; On tags within a headline or an inlinetask.
10697 ((and (memq type '(headline inlinetask))
10698 (let ((case-fold-search nil))
10699 (save-excursion (beginning-of-line)
10700 (looking-at org-complex-heading-regexp))
10701 (and (match-beginning 5)
10702 (>= (point) (match-beginning 5)))))
10703 (org-tags-view arg (substring (match-string 5) 0 -1)))
10704 ((eq type 'link)
10705 (let ((type (org-element-property :type context))
10706 (path (org-link-unescape (org-element-property :path context))))
10707 ;; Switch back to REFERENCE-BUFFER needed when called in
10708 ;; a temporary buffer through `org-open-link-from-string'.
10709 (with-current-buffer (or reference-buffer (current-buffer))
10710 (cond
10711 ((equal type "file")
10712 (if (string-match "[*?{]" (file-name-nondirectory path))
10713 (dired path)
10714 ;; Look into `org-link-parameters' in order to find
10715 ;; a DEDICATED-FUNCTION to open file. The function
10716 ;; will be applied on raw link instead of parsed
10717 ;; link due to the limitation in `org-add-link-type'
10718 ;; ("open" function called with a single argument).
10719 ;; If no such function is found, fallback to
10720 ;; `org-open-file'.
10721 (let* ((option (org-element-property :search-option context))
10722 (app (org-element-property :application context))
10723 (dedicated-function
10724 (org-link-get-parameter
10725 (if app (concat type "+" app) type)
10726 :follow)))
10727 (if dedicated-function
10728 (funcall dedicated-function
10729 (concat path
10730 (and option (concat "::" option))))
10731 (apply #'org-open-file
10732 path
10733 (cond (arg)
10734 ((equal app "emacs") 'emacs)
10735 ((equal app "sys") 'system))
10736 (cond ((not option) nil)
10737 ((string-match-p "\\`[0-9]+\\'" option)
10738 (list (string-to-number option)))
10739 (t (list nil
10740 (org-link-unescape option)))))))))
10741 ((functionp (org-link-get-parameter type :follow))
10742 (funcall (org-link-get-parameter type :follow) path))
10743 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10744 (unless (run-hook-with-args-until-success
10745 'org-open-link-functions path)
10746 (if (not arg) (org-mark-ring-push)
10747 (switch-to-buffer-other-window
10748 (org-get-buffer-for-internal-link (current-buffer))))
10749 (let ((destination
10750 (org-with-wide-buffer
10751 (if (equal type "radio")
10752 (org-search-radio-target
10753 (org-element-property :path context))
10754 (org-link-search
10755 (if (member type '("custom-id" "coderef"))
10756 (org-element-property :raw-link context)
10757 path)
10758 ;; Prevent fuzzy links from matching
10759 ;; themselves.
10760 (and (equal type "fuzzy")
10761 (+ 2 (org-element-property :begin context)))))
10762 (point))))
10763 (unless (and (<= (point-min) destination)
10764 (>= (point-max) destination))
10765 (widen))
10766 (goto-char destination))))
10767 (t (browse-url-at-point))))))
10768 (t (user-error "No link found")))))
10769 (run-hook-with-args 'org-follow-link-hook)))
10771 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10772 "Offer links in the current entry and return the selected link.
10773 If there is only one link, return it.
10774 If NTH is an integer, return the NTH link found.
10775 If ZERO is a string, check also this string for a link, and if
10776 there is one, return it."
10777 (with-current-buffer buffer
10778 (org-with-wide-buffer
10779 (goto-char marker)
10780 (let ((cnt ?0)
10781 have-zero end links link c)
10782 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10783 (push (match-string 0 zero) links)
10784 (setq cnt (1- cnt) have-zero t))
10785 (save-excursion
10786 (org-back-to-heading t)
10787 (setq end (save-excursion (outline-next-heading) (point)))
10788 (while (re-search-forward org-any-link-re end t)
10789 (push (match-string 0) links))
10790 (setq links (org-uniquify (reverse links))))
10791 (cond
10792 ((null links)
10793 (message "No links"))
10794 ((equal (length links) 1)
10795 (setq link (car links)))
10796 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10797 (setq link (nth (if have-zero nth (1- nth)) links)))
10798 (t ; we have to select a link
10799 (save-excursion
10800 (save-window-excursion
10801 (delete-other-windows)
10802 (with-output-to-temp-buffer "*Select Link*"
10803 (dolist (l links)
10804 (cond
10805 ((not (string-match org-bracket-link-regexp l))
10806 (princ (format "[%c] %s\n" (cl-incf cnt)
10807 (org-unbracket-string "<" ">" l))))
10808 ((match-end 3)
10809 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10810 (match-string 3 l) (match-string 1 l))))
10811 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10812 (match-string 1 l)))))))
10813 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10814 (message "Select link to open, RET to open all:")
10815 (setq c (read-char-exclusive))
10816 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10817 (when (equal c ?q) (user-error "Abort"))
10818 (if (equal c ?\C-m)
10819 (setq link links)
10820 (setq nth (- c ?0))
10821 (when have-zero (setq nth (1+ nth)))
10822 (unless (and (integerp nth) (>= (length links) nth))
10823 (user-error "Invalid link selection"))
10824 (setq link (nth (1- nth) links)))))
10825 (cons link end)))))
10827 ;; TODO: These functions are deprecated since `org-open-at-point'
10828 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10829 (defun org-open-file-with-system (path)
10830 "Open file at PATH using the system way of opening it."
10831 (org-open-file path 'system))
10832 (defun org-open-file-with-emacs (path)
10833 "Open file at PATH in Emacs."
10834 (org-open-file path 'emacs))
10837 ;;; File search
10839 (defvar org-create-file-search-functions nil
10840 "List of functions to construct the right search string for a file link.
10841 These functions are called in turn with point at the location to
10842 which the link should point.
10844 A function in the hook should first test if it would like to
10845 handle this file type, for example by checking the `major-mode'
10846 or the file extension. If it decides not to handle this file, it
10847 should just return nil to give other functions a chance. If it
10848 does handle the file, it must return the search string to be used
10849 when following the link. The search string will be part of the
10850 file link, given after a double colon, and `org-open-at-point'
10851 will automatically search for it. If special measures must be
10852 taken to make the search successful, another function should be
10853 added to the companion hook `org-execute-file-search-functions',
10854 which see.
10856 A function in this hook may also use `setq' to set the variable
10857 `description' to provide a suggestion for the descriptive text to
10858 be used for this link when it gets inserted into an Org buffer
10859 with \\[org-insert-link].")
10861 (defvar org-execute-file-search-functions nil
10862 "List of functions to execute a file search triggered by a link.
10864 Functions added to this hook must accept a single argument, the
10865 search string that was part of the file link, the part after the
10866 double colon. The function must first check if it would like to
10867 handle this search, for example by checking the `major-mode' or
10868 the file extension. If it decides not to handle this search, it
10869 should just return nil to give other functions a chance. If it
10870 does handle the search, it must return a non-nil value to keep
10871 other functions from trying.
10873 Each function can access the current prefix argument through the
10874 variable `current-prefix-arg'. Note that a single prefix is used
10875 to force opening a link in Emacs, so it may be good to only use a
10876 numeric or double prefix to guide the search function.
10878 In case this is needed, a function in this hook can also restore
10879 the window configuration before `org-open-at-point' was called using:
10881 (set-window-configuration org-window-config-before-follow-link)")
10883 (defun org-search-radio-target (target)
10884 "Search a radio target matching TARGET in current buffer.
10885 White spaces are not significant."
10886 (let ((re (format "<<<%s>>>"
10887 (mapconcat #'regexp-quote
10888 (org-split-string target "[ \t\n]+")
10889 "[ \t]+\\(?:\n[ \t]*\\)?")))
10890 (origin (point)))
10891 (goto-char (point-min))
10892 (catch :radio-match
10893 (while (re-search-forward re nil t)
10894 (backward-char)
10895 (let ((object (org-element-context)))
10896 (when (eq (org-element-type object) 'radio-target)
10897 (goto-char (org-element-property :begin object))
10898 (org-show-context 'link-search)
10899 (throw :radio-match nil))))
10900 (goto-char origin)
10901 (user-error "No match for radio target: %s" target))))
10903 (defun org-link-search (s &optional avoid-pos stealth)
10904 "Search for a search string S.
10906 If S starts with \"#\", it triggers a custom ID search.
10908 If S is enclosed within parenthesis, it initiates a coderef
10909 search.
10911 If S is surrounded by forward slashes, it is interpreted as
10912 a regular expression. In Org mode files, this will create an
10913 `org-occur' sparse tree. In ordinary files, `occur' will be used
10914 to list matches. If the current buffer is in `dired-mode', grep
10915 will be used to search in all files.
10917 When AVOID-POS is given, ignore matches near that position.
10919 When optional argument STEALTH is non-nil, do not modify
10920 visibility around point, thus ignoring `org-show-context-detail'
10921 variable.
10923 Search is case-insensitive and ignores white spaces. Return type
10924 of matched result, which is either `dedicated' or `fuzzy'."
10925 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10926 (let* ((case-fold-search t)
10927 (origin (point))
10928 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10929 (starred (eq (string-to-char normalized) ?*))
10930 (words (split-string (if starred (substring s 1) s)))
10931 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10932 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10933 type)
10934 (cond
10935 ;; Check if there are any special search functions.
10936 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10937 ((eq (string-to-char s) ?#)
10938 ;; Look for a custom ID S if S starts with "#".
10939 (let* ((id (substring normalized 1))
10940 (match (org-find-property "CUSTOM_ID" id)))
10941 (if match (progn (goto-char match) (setf type 'dedicated))
10942 (error "No match for custom ID: %s" id))))
10943 ((string-match "\\`(\\(.*\\))\\'" normalized)
10944 ;; Look for coderef targets if S is enclosed within parenthesis.
10945 (let ((coderef (match-string-no-properties 1 normalized))
10946 (re (substring s-single-re 1 -1)))
10947 (goto-char (point-min))
10948 (catch :coderef-match
10949 (while (re-search-forward re nil t)
10950 (let ((element (org-element-at-point)))
10951 (when (and (memq (org-element-type element)
10952 '(example-block src-block))
10953 ;; Build proper regexp according to current
10954 ;; block's label format.
10955 (let ((label-fmt
10956 (regexp-quote
10957 (or (org-element-property :label-fmt element)
10958 org-coderef-label-format))))
10959 (save-excursion
10960 (beginning-of-line)
10961 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10962 (format label-fmt coderef))))))
10963 (setq type 'dedicated)
10964 (goto-char (match-beginning 1))
10965 (throw :coderef-match nil))))
10966 (goto-char origin)
10967 (error "No match for coderef: %s" coderef))))
10968 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10969 ;; Look for a regular expression.
10970 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10971 (match-string 1 s)))
10972 ;; From here, we handle fuzzy links.
10974 ;; Look for targets, only if not in a headline search.
10975 ((and (not starred)
10976 (let ((target (format "<<%s>>" s-multi-re)))
10977 (catch :target-match
10978 (goto-char (point-min))
10979 (while (re-search-forward target nil t)
10980 (backward-char)
10981 (let ((context (org-element-context)))
10982 (when (eq (org-element-type context) 'target)
10983 (setq type 'dedicated)
10984 (goto-char (org-element-property :begin context))
10985 (throw :target-match t))))
10986 nil))))
10987 ;; Look for elements named after S, only if not in a headline
10988 ;; search.
10989 ((and (not starred)
10990 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10991 (catch :name-match
10992 (goto-char (point-min))
10993 (while (re-search-forward name nil t)
10994 (let ((element (org-element-at-point)))
10995 (when (equal words
10996 (split-string
10997 (org-element-property :name element)))
10998 (setq type 'dedicated)
10999 (beginning-of-line)
11000 (throw :name-match t))))
11001 nil))))
11002 ;; Regular text search. Prefer headlines in Org mode buffers.
11003 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11004 ;; statistics cookies and tags.
11005 ((and (derived-mode-p 'org-mode)
11006 (let ((title-re
11007 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11008 org-outline-regexp-bol
11009 org-comment-string
11010 (mapconcat #'regexp-quote words ".+")))
11011 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11012 (comment-re (eval-when-compile
11013 (format "\\`%s[ \t]+" org-comment-string))))
11014 (goto-char (point-min))
11015 (catch :found
11016 (while (re-search-forward title-re nil t)
11017 (when (equal words
11018 (split-string
11019 (replace-regexp-in-string
11020 cookie-re ""
11021 (replace-regexp-in-string
11022 comment-re "" (org-get-heading t t t)))))
11023 (throw :found t)))
11024 nil)))
11025 (beginning-of-line)
11026 (setq type 'dedicated))
11027 ;; Offer to create non-existent headline depending on
11028 ;; `org-link-search-must-match-exact-headline'.
11029 ((and (derived-mode-p 'org-mode)
11030 (not org-link-search-inhibit-query)
11031 (eq org-link-search-must-match-exact-headline 'query-to-create)
11032 (yes-or-no-p "No match - create this as a new heading? "))
11033 (goto-char (point-max))
11034 (unless (bolp) (newline))
11035 (org-insert-heading nil t t)
11036 (insert s "\n")
11037 (beginning-of-line 0))
11038 ;; Only headlines are looked after. No need to process
11039 ;; further: throw an error.
11040 ((and (derived-mode-p 'org-mode)
11041 (or starred org-link-search-must-match-exact-headline))
11042 (goto-char origin)
11043 (error "No match for fuzzy expression: %s" normalized))
11044 ;; Regular text search.
11045 ((catch :fuzzy-match
11046 (goto-char (point-min))
11047 (while (re-search-forward s-multi-re nil t)
11048 ;; Skip match if it contains AVOID-POS or it is included in
11049 ;; a link with a description but outside the description.
11050 (unless (or (and avoid-pos
11051 (<= (match-beginning 0) avoid-pos)
11052 (> (match-end 0) avoid-pos))
11053 (and (save-match-data
11054 (org-in-regexp org-bracket-link-regexp))
11055 (match-beginning 3)
11056 (or (> (match-beginning 3) (point))
11057 (<= (match-end 3) (point)))
11058 (org-element-lineage
11059 (save-match-data (org-element-context))
11060 '(link) t)))
11061 (goto-char (match-beginning 0))
11062 (setq type 'fuzzy)
11063 (throw :fuzzy-match t)))
11064 nil))
11065 ;; All failed. Throw an error.
11066 (t (goto-char origin)
11067 (error "No match for fuzzy expression: %s" normalized)))
11068 ;; Disclose surroundings of match, if appropriate.
11069 (when (and (derived-mode-p 'org-mode) (not stealth))
11070 (org-show-context 'link-search))
11071 type))
11073 (defun org-get-buffer-for-internal-link (buffer)
11074 "Return a buffer to be used for displaying the link target of internal links."
11075 (cond
11076 ((not org-display-internal-link-with-indirect-buffer)
11077 buffer)
11078 ((string-suffix-p "(Clone)" (buffer-name buffer))
11079 (message "Buffer is already a clone, not making another one")
11080 ;; we also do not modify visibility in this case
11081 buffer)
11082 (t ; make a new indirect buffer for displaying the link
11083 (let* ((bn (buffer-name buffer))
11084 (ibn (concat bn "(Clone)"))
11085 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11086 (with-current-buffer ib (org-overview))
11087 ib))))
11089 (defun org-do-occur (regexp &optional cleanup)
11090 "Call the Emacs command `occur'.
11091 If CLEANUP is non-nil, remove the printout of the regular expression
11092 in the *Occur* buffer. This is useful if the regex is long and not useful
11093 to read."
11094 (occur regexp)
11095 (when cleanup
11096 (let ((cwin (selected-window)) win beg end)
11097 (when (setq win (get-buffer-window "*Occur*"))
11098 (select-window win))
11099 (goto-char (point-min))
11100 (when (re-search-forward "match[a-z]+" nil t)
11101 (setq beg (match-end 0))
11102 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11103 (setq end (1- (match-beginning 0)))))
11104 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11105 (goto-char (point-min))
11106 (select-window cwin))))
11108 ;;; The mark ring for links jumps
11110 (defvar org-mark-ring nil
11111 "Mark ring for positions before jumps in Org mode.")
11112 (defvar org-mark-ring-last-goto nil
11113 "Last position in the mark ring used to go back.")
11114 ;; Fill and close the ring
11115 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11116 (dotimes (_ org-mark-ring-length)
11117 (push (make-marker) org-mark-ring))
11118 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11119 org-mark-ring)
11121 (defun org-mark-ring-push (&optional pos buffer)
11122 "Put the current position or POS into the mark ring and rotate it."
11123 (interactive)
11124 (setq pos (or pos (point)))
11125 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11126 (move-marker (car org-mark-ring)
11127 (or pos (point))
11128 (or buffer (current-buffer)))
11129 (message "%s"
11130 (substitute-command-keys
11131 "Position saved to mark ring, go back with \
11132 `\\[org-mark-ring-goto]'.")))
11134 (defun org-mark-ring-goto (&optional n)
11135 "Jump to the previous position in the mark ring.
11136 With prefix arg N, jump back that many stored positions. When
11137 called several times in succession, walk through the entire ring.
11138 Org mode commands jumping to a different position in the current file,
11139 or to another Org file, automatically push the old position onto the ring."
11140 (interactive "p")
11141 (let (p m)
11142 (if (eq last-command this-command)
11143 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11144 (setq p org-mark-ring))
11145 (setq org-mark-ring-last-goto p)
11146 (setq m (car p))
11147 (pop-to-buffer-same-window (marker-buffer m))
11148 (goto-char m)
11149 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11151 (defun org-add-angle-brackets (s)
11152 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11153 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11156 ;;; Following specific links
11158 (defvar org-agenda-buffer-tmp-name)
11159 (defvar org-agenda-start-on-weekday)
11160 (defun org-follow-timestamp-link ()
11161 "Open an agenda view for the time-stamp date/range at point."
11162 (cond
11163 ((org-at-date-range-p t)
11164 (let ((org-agenda-start-on-weekday)
11165 (t1 (match-string 1))
11166 (t2 (match-string 2)) tt1 tt2)
11167 (setq tt1 (time-to-days (org-time-string-to-time t1))
11168 tt2 (time-to-days (org-time-string-to-time t2)))
11169 (let ((org-agenda-buffer-tmp-name
11170 (format "*Org Agenda(a:%s)"
11171 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11172 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11173 ((org-at-timestamp-p 'lax)
11174 (let ((org-agenda-buffer-tmp-name
11175 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11176 (org-agenda-list nil (time-to-days (org-time-string-to-time
11177 (substring (match-string 1) 0 10)))
11178 1)))
11179 (t (error "This should not happen"))))
11182 ;;; Following file links
11183 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11184 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11185 (declare-function mailcap-mime-info
11186 "mailcap" (string &optional request no-decode))
11187 (defvar org-wait nil)
11188 (defun org-open-file (path &optional in-emacs line search)
11189 "Open the file at PATH.
11190 First, this expands any special file name abbreviations. Then the
11191 configuration variable `org-file-apps' is checked if it contains an
11192 entry for this file type, and if yes, the corresponding command is launched.
11194 If no application is found, Emacs simply visits the file.
11196 With optional prefix argument IN-EMACS, Emacs will visit the file.
11197 With a double \\[universal-argument] \\[universal-argument] \
11198 prefix arg, Org tries to avoid opening in Emacs
11199 and to use an external application to visit the file.
11201 Optional LINE specifies a line to go to, optional SEARCH a string
11202 to search for. If LINE or SEARCH is given, the file will be
11203 opened in Emacs, unless an entry from org-file-apps that makes
11204 use of groups in a regexp matches.
11206 If you want to change the way frames are used when following a
11207 link, please customize `org-link-frame-setup'.
11209 If the file does not exist, an error is thrown."
11210 (let* ((file (if (equal path "")
11211 buffer-file-name
11212 (substitute-in-file-name (expand-file-name path))))
11213 (file-apps (append org-file-apps (org-default-apps)))
11214 (apps (cl-remove-if
11215 'org-file-apps-entry-match-against-dlink-p file-apps))
11216 (apps-dlink (cl-remove-if-not
11217 'org-file-apps-entry-match-against-dlink-p file-apps))
11218 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11219 (dirp (unless remp (file-directory-p file)))
11220 (file (if (and dirp org-open-directory-means-index-dot-org)
11221 (concat (file-name-as-directory file) "index.org")
11222 file))
11223 (a-m-a-p (assq 'auto-mode apps))
11224 (dfile (downcase file))
11225 ;; Reconstruct the original link from the PATH, LINE and
11226 ;; SEARCH args.
11227 (link (cond (line (concat file "::" (number-to-string line)))
11228 (search (concat file "::" search))
11229 (t file)))
11230 (dlink (downcase link))
11231 (ext
11232 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11233 (match-string 1 dfile)))
11234 (save-position-maybe
11235 (let ((old-buffer (current-buffer))
11236 (old-pos (point))
11237 (old-mode major-mode))
11238 (lambda ()
11239 (and (derived-mode-p 'org-mode)
11240 (eq old-mode 'org-mode)
11241 (or (not (eq old-buffer (current-buffer)))
11242 (not (eq old-pos (point))))
11243 (org-mark-ring-push old-pos old-buffer)))))
11244 cmd link-match-data)
11245 (cond
11246 ((member in-emacs '((16) system))
11247 (setq cmd (cdr (assq 'system apps))))
11248 (in-emacs (setq cmd 'emacs))
11250 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11251 (and dirp (cdr (assq 'directory apps)))
11252 ;; First, try matching against apps-dlink if we
11253 ;; get a match here, store the match data for
11254 ;; later.
11255 (let ((match (assoc-default dlink apps-dlink
11256 'string-match)))
11257 (if match
11258 (progn (setq link-match-data (match-data))
11259 match)
11260 (progn (setq in-emacs (or in-emacs line search))
11261 nil))) ; if we have no match in apps-dlink,
11262 ; always open the file in emacs if line or search
11263 ; is given (for backwards compatibility)
11264 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11265 'string-match)
11266 (cdr (assoc ext apps))
11267 (cdr (assq t apps))))))
11268 (when (eq cmd 'system)
11269 (setq cmd (cdr (assq 'system apps))))
11270 (when (eq cmd 'default)
11271 (setq cmd (cdr (assoc t apps))))
11272 (when (eq cmd 'mailcap)
11273 (require 'mailcap)
11274 (mailcap-parse-mailcaps)
11275 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11276 (command (mailcap-mime-info mime-type)))
11277 (if (stringp command)
11278 (setq cmd command)
11279 (setq cmd 'emacs))))
11280 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11281 (not (file-exists-p file))
11282 (not org-open-non-existing-files))
11283 (user-error "No such file: %s" file))
11284 (cond
11285 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11286 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11287 (while (string-match "['\"]%s['\"]" cmd)
11288 (setq cmd (replace-match "%s" t t cmd)))
11289 (setq cmd (replace-regexp-in-string
11290 "%s"
11291 (shell-quote-argument (convert-standard-filename file))
11293 nil t))
11295 ;; Replace "%1", "%2" etc. in command with group matches from regex
11296 (save-match-data
11297 (let ((match-index 1)
11298 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11299 (set-match-data link-match-data)
11300 (while (<= match-index number-of-groups)
11301 (let ((regex (concat "%" (number-to-string match-index)))
11302 (replace-with (match-string match-index dlink)))
11303 (while (string-match regex cmd)
11304 (setq cmd (replace-match replace-with t t cmd))))
11305 (setq match-index (+ match-index 1)))))
11307 (save-window-excursion
11308 (message "Running %s...done" cmd)
11309 (start-process-shell-command cmd nil cmd)
11310 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11311 ((or (stringp cmd)
11312 (eq cmd 'emacs))
11313 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11314 (widen)
11315 (cond (line (org-goto-line line)
11316 (when (derived-mode-p 'org-mode) (org-reveal)))
11317 (search (condition-case err
11318 (org-link-search search)
11319 ;; Save position before error-ing out so user
11320 ;; can easily move back to the original buffer.
11321 (error (funcall save-position-maybe)
11322 (error (nth 1 err)))))))
11323 ((functionp cmd)
11324 (save-match-data
11325 (set-match-data link-match-data)
11326 (condition-case nil
11327 (funcall cmd file link)
11328 ;; FIXME: Remove this check when most default installations
11329 ;; of Emacs have at least Org 9.0.
11330 ((debug wrong-number-of-arguments wrong-type-argument
11331 invalid-function)
11332 (user-error "Please see Org News for version 9.0 about \
11333 `org-file-apps'--Lisp error: %S" cmd)))))
11334 ((consp cmd)
11335 ;; FIXME: Remove this check when most default installations of
11336 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11337 ;; fall back to `org-link-frame-setup' for an old usage of
11338 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11339 (user-error "Please see Org News for version 9.0 about \
11340 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11341 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11342 (funcall save-position-maybe)))
11344 (defun org-file-apps-entry-match-against-dlink-p (entry)
11345 "This function returns non-nil if `entry' uses a regular
11346 expression which should be matched against the whole link by
11347 org-open-file.
11349 It assumes that is the case when the entry uses a regular
11350 expression which has at least one grouping construct and the
11351 action is either a lisp form or a command string containing
11352 `%1', i.e. using at least one subexpression match as a
11353 parameter."
11354 (let ((selector (car entry))
11355 (action (cdr entry)))
11356 (if (stringp selector)
11357 (and (> (regexp-opt-depth selector) 0)
11358 (or (and (stringp action)
11359 (string-match "%[0-9]" action))
11360 (consp action)))
11361 nil)))
11363 (defun org-default-apps ()
11364 "Return the default applications for this operating system."
11365 (cond
11366 ((eq system-type 'darwin)
11367 org-file-apps-defaults-macosx)
11368 ((eq system-type 'windows-nt)
11369 org-file-apps-defaults-windowsnt)
11370 (t org-file-apps-defaults-gnu)))
11372 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11373 "Convert extensions to regular expressions in the cars of LIST.
11374 Also, weed out any non-string entries, because the return value is used
11375 only for regexp matching.
11376 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11377 point to the symbol `emacs', indicating that the file should
11378 be opened in Emacs."
11379 (append
11380 (delq nil
11381 (mapcar (lambda (x)
11382 (unless (not (stringp (car x)))
11383 (if (string-match "\\W" (car x))
11385 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11386 list))
11387 (when add-auto-mode
11388 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11390 (defvar ange-ftp-name-format)
11391 (defun org-file-remote-p (file)
11392 "Test whether FILE specifies a location on a remote system.
11393 Return non-nil if the location is indeed remote.
11395 For example, the filename \"/user@host:/foo\" specifies a location
11396 on the system \"/user@host:\"."
11397 (cond ((fboundp 'file-remote-p)
11398 (file-remote-p file))
11399 ((fboundp 'tramp-handle-file-remote-p)
11400 (tramp-handle-file-remote-p file))
11401 ((and (boundp 'ange-ftp-name-format)
11402 (string-match (car ange-ftp-name-format) file))
11403 t)))
11406 ;;;; Refiling
11408 (defun org-get-org-file ()
11409 "Read a filename, with default directory `org-directory'."
11410 (let ((default (or org-default-notes-file remember-data-file)))
11411 (read-file-name (format "File name [%s]: " default)
11412 (file-name-as-directory org-directory)
11413 default)))
11415 (defun org-notes-order-reversed-p ()
11416 "Check if the current file should receive notes in reversed order."
11417 (cond
11418 ((not org-reverse-note-order) nil)
11419 ((eq t org-reverse-note-order) t)
11420 ((not (listp org-reverse-note-order)) nil)
11421 (t (catch 'exit
11422 (dolist (entry org-reverse-note-order)
11423 (when (string-match (car entry) buffer-file-name)
11424 (throw 'exit (cdr entry))))))))
11426 (defvar org-refile-target-table nil
11427 "The list of refile targets, created by `org-refile'.")
11429 (defvar org-agenda-new-buffers nil
11430 "Buffers created to visit agenda files.")
11432 (defvar org-refile-cache nil
11433 "Cache for refile targets.")
11435 (defvar org-refile-markers nil
11436 "All the markers used for caching refile locations.")
11438 (defun org-refile-marker (pos)
11439 "Get a new refile marker, but only if caching is in use."
11440 (if (not org-refile-use-cache)
11442 (let ((m (make-marker)))
11443 (move-marker m pos)
11444 (push m org-refile-markers)
11445 m)))
11447 (defun org-refile-cache-clear ()
11448 "Clear the refile cache and disable all the markers."
11449 (dolist (m org-refile-markers) (move-marker m nil))
11450 (setq org-refile-markers nil)
11451 (setq org-refile-cache nil)
11452 (message "Refile cache has been cleared"))
11454 (defun org-refile-cache-check-set (set)
11455 "Check if all the markers in the cache still have live buffers."
11456 (let (marker)
11457 (catch 'exit
11458 (while (and set (setq marker (nth 3 (pop set))))
11459 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11460 (when (and marker (null (marker-buffer marker)))
11461 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11462 (sit-for 3)
11463 (throw 'exit nil)))
11464 t)))
11466 (defun org-refile-cache-put (set &rest identifiers)
11467 "Push the refile targets SET into the cache, under IDENTIFIERS."
11468 (let* ((key (sha1 (prin1-to-string identifiers)))
11469 (entry (assoc key org-refile-cache)))
11470 (if entry
11471 (setcdr entry set)
11472 (push (cons key set) org-refile-cache))))
11474 (defun org-refile-cache-get (&rest identifiers)
11475 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11476 (cond
11477 ((not org-refile-cache) nil)
11478 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11480 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11481 org-refile-cache))))
11482 (and set (org-refile-cache-check-set set) set)))))
11484 (defvar org-outline-path-cache nil
11485 "Alist between buffer positions and outline paths.
11486 It value is an alist (POSITION . PATH) where POSITION is the
11487 buffer position at the beginning of an entry and PATH is a list
11488 of strings describing the outline path for that entry, in reverse
11489 order.")
11491 (defun org-refile-get-targets (&optional default-buffer)
11492 "Produce a table with refile targets."
11493 (let ((case-fold-search nil)
11494 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11495 (entries (or org-refile-targets '((nil . (:level . 1)))))
11496 targets tgs files desc descre)
11497 (message "Getting targets...")
11498 (with-current-buffer (or default-buffer (current-buffer))
11499 (dolist (entry entries)
11500 (setq files (car entry) desc (cdr entry))
11501 (cond
11502 ((null files) (setq files (list (current-buffer))))
11503 ((eq files 'org-agenda-files)
11504 (setq files (org-agenda-files 'unrestricted)))
11505 ((and (symbolp files) (fboundp files))
11506 (setq files (funcall files)))
11507 ((and (symbolp files) (boundp files))
11508 (setq files (symbol-value files))))
11509 (when (stringp files) (setq files (list files)))
11510 (cond
11511 ((eq (car desc) :tag)
11512 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11513 ((eq (car desc) :todo)
11514 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11515 ((eq (car desc) :regexp)
11516 (setq descre (cdr desc)))
11517 ((eq (car desc) :level)
11518 (setq descre (concat "^\\*\\{" (number-to-string
11519 (if org-odd-levels-only
11520 (1- (* 2 (cdr desc)))
11521 (cdr desc)))
11522 "\\}[ \t]")))
11523 ((eq (car desc) :maxlevel)
11524 (setq descre (concat "^\\*\\{1," (number-to-string
11525 (if org-odd-levels-only
11526 (1- (* 2 (cdr desc)))
11527 (cdr desc)))
11528 "\\}[ \t]")))
11529 (t (error "Bad refiling target description %s" desc)))
11530 (dolist (f files)
11531 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11533 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11534 (progn
11535 (when (bufferp f)
11536 (setq f (buffer-file-name (buffer-base-buffer f))))
11537 (setq f (and f (expand-file-name f)))
11538 (when (eq org-refile-use-outline-path 'file)
11539 (push (list (file-name-nondirectory f) f nil nil) tgs))
11540 (when (eq org-refile-use-outline-path 'buffer-name)
11541 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11542 (when (eq org-refile-use-outline-path 'full-file-path)
11543 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11544 (org-with-wide-buffer
11545 (goto-char (point-min))
11546 (setq org-outline-path-cache nil)
11547 (while (re-search-forward descre nil t)
11548 (beginning-of-line)
11549 (let ((case-fold-search nil))
11550 (looking-at org-complex-heading-regexp))
11551 (let ((begin (point))
11552 (heading (match-string-no-properties 4)))
11553 (unless (or (and
11554 org-refile-target-verify-function
11555 (not
11556 (funcall org-refile-target-verify-function)))
11557 (not heading))
11558 (let ((re (format org-complex-heading-regexp-format
11559 (regexp-quote heading)))
11560 (target
11561 (if (not org-refile-use-outline-path) heading
11562 (mapconcat
11563 #'identity
11564 (append
11565 (pcase org-refile-use-outline-path
11566 (`file (list (file-name-nondirectory
11567 (buffer-file-name
11568 (buffer-base-buffer)))))
11569 (`full-file-path
11570 (list (buffer-file-name
11571 (buffer-base-buffer))))
11572 (`buffer-name
11573 (list (buffer-name
11574 (buffer-base-buffer))))
11575 (_ nil))
11576 (mapcar (lambda (s) (replace-regexp-in-string
11577 "/" "\\/" s nil t))
11578 (org-get-outline-path t t)))
11579 "/"))))
11580 (push (list target f re (org-refile-marker (point)))
11581 tgs)))
11582 (when (= (point) begin)
11583 ;; Verification function has not moved point.
11584 (end-of-line)))))))
11585 (when org-refile-use-cache
11586 (org-refile-cache-put tgs (buffer-file-name) descre))
11587 (setq targets (append tgs targets))))))
11588 (message "Getting targets...done")
11589 (delete-dups (nreverse targets))))
11591 (defun org--get-outline-path-1 (&optional use-cache)
11592 "Return outline path to current headline.
11594 Outline path is a list of strings, in reverse order. When
11595 optional argument USE-CACHE is non-nil, make use of a cache. See
11596 `org-get-outline-path' for details.
11598 Assume buffer is widened and point is on a headline."
11599 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11600 (let ((p (point))
11601 (heading (let ((case-fold-search nil))
11602 (looking-at org-complex-heading-regexp)
11603 (if (not (match-end 4)) ""
11604 ;; Remove statistics cookies.
11605 (org-trim
11606 (org-link-display-format
11607 (replace-regexp-in-string
11608 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11609 (match-string-no-properties 4))))))))
11610 (if (org-up-heading-safe)
11611 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11612 (when use-cache
11613 (push (cons p path) org-outline-path-cache))
11614 path)
11615 ;; This is a new root node. Since we assume we are moving
11616 ;; forward, we can drop previous cache so as to limit number
11617 ;; of associations there.
11618 (let ((path (list heading)))
11619 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11620 path)))))
11622 (defun org-get-outline-path (&optional with-self use-cache)
11623 "Return the outline path to the current entry.
11625 An outline path is a list of ancestors for current headline, as
11626 a list of strings. Statistics cookies are removed and links are
11627 replaced with their description, if any, or their path otherwise.
11629 When optional argument WITH-SELF is non-nil, the path also
11630 includes the current headline.
11632 When optional argument USE-CACHE is non-nil, cache outline paths
11633 between calls to this function so as to avoid backtracking. This
11634 argument is useful when planning to find more than one outline
11635 path in the same document. In that case, there are two
11636 conditions to satisfy:
11637 - `org-outline-path-cache' is set to nil before starting the
11638 process;
11639 - outline paths are computed by increasing buffer positions."
11640 (org-with-wide-buffer
11641 (and (or (and with-self (org-back-to-heading t))
11642 (org-up-heading-safe))
11643 (reverse (org--get-outline-path-1 use-cache)))))
11645 (defun org-format-outline-path (path &optional width prefix separator)
11646 "Format the outline path PATH for display.
11647 WIDTH is the maximum number of characters that is available.
11648 PREFIX is a prefix to be included in the returned string,
11649 such as the file name.
11650 SEPARATOR is inserted between the different parts of the path,
11651 the default is \"/\"."
11652 (setq width (or width 79))
11653 (setq path (delq nil path))
11654 (unless (> width 0)
11655 (user-error "Argument `width' must be positive"))
11656 (setq separator (or separator "/"))
11657 (let* ((org-odd-levels-only nil)
11658 (fpath (concat
11659 prefix (and prefix path separator)
11660 (mapconcat
11661 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11662 (cl-loop for head in path
11663 for n from 0
11664 collect (org-add-props
11665 head nil 'face
11666 (nth (% n org-n-level-faces) org-level-faces)))
11667 separator))))
11668 (when (> (length fpath) width)
11669 (if (< width 7)
11670 ;; It's unlikely that `width' will be this small, but don't
11671 ;; waste characters by adding ".." if it is.
11672 (setq fpath (substring fpath 0 width))
11673 (setf (substring fpath (- width 2)) "..")))
11674 fpath))
11676 (defun org-display-outline-path (&optional file current separator just-return-string)
11677 "Display the current outline path in the echo area.
11679 If FILE is non-nil, prepend the output with the file name.
11680 If CURRENT is non-nil, append the current heading to the output.
11681 SEPARATOR is passed through to `org-format-outline-path'. It separates
11682 the different parts of the path and defaults to \"/\".
11683 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11684 (interactive "P")
11685 (let* (case-fold-search
11686 (bfn (buffer-file-name (buffer-base-buffer)))
11687 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11688 res)
11689 (when current (setq path (append path
11690 (save-excursion
11691 (org-back-to-heading t)
11692 (when (looking-at org-complex-heading-regexp)
11693 (list (match-string 4)))))))
11694 (setq res
11695 (org-format-outline-path
11696 path
11697 (1- (frame-width))
11698 (and file bfn (concat (file-name-nondirectory bfn) separator))
11699 separator))
11700 (if just-return-string
11701 (org-no-properties res)
11702 (org-unlogged-message "%s" res))))
11704 (defvar org-refile-history nil
11705 "History for refiling operations.")
11707 (defvar org-after-refile-insert-hook nil
11708 "Hook run after `org-refile' has inserted its stuff at the new location.
11709 Note that this is still *before* the stuff will be removed from
11710 the *old* location.")
11712 (defvar org-capture-last-stored-marker)
11713 (defvar org-refile-keep nil
11714 "Non-nil means `org-refile' will copy instead of refile.")
11716 (defun org-copy ()
11717 "Like `org-refile', but copy."
11718 (interactive)
11719 (let ((org-refile-keep t))
11720 (funcall 'org-refile nil nil nil "Copy")))
11722 (defun org-refile (&optional arg default-buffer rfloc msg)
11723 "Move the entry or entries at point to another heading.
11725 The list of target headings is compiled using the information in
11726 `org-refile-targets', which see.
11728 At the target location, the entry is filed as a subitem of the
11729 target heading. Depending on `org-reverse-note-order', the new
11730 subitem will either be the first or the last subitem.
11732 If there is an active region, all entries in that region will be
11733 refiled. However, the region must fulfill the requirement that
11734 the first heading sets the top-level of the moved text.
11736 With a `\\[universal-argument]' ARG, the command will only visit the target \
11737 location
11738 and not actually move anything.
11740 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11741 location where the last
11742 refiling operation has put the subtree.
11744 With a numeric prefix argument of `2', refile to the running clock.
11746 With a numeric prefix argument of `3', emulate `org-refile-keep'
11747 being set to t and copy to the target location, don't move it.
11748 Beware that keeping refiled entries may result in duplicated ID
11749 properties.
11751 RFLOC can be a refile location obtained in a different way.
11753 MSG is a string to replace \"Refile\" in the default prompt with
11754 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11756 See also `org-refile-use-outline-path'.
11758 If you are using target caching (see `org-refile-use-cache'), you
11759 have to clear the target cache in order to find new targets.
11760 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11761 prefix argument (`C-u C-u C-u C-c C-w')."
11762 (interactive "P")
11763 (if (member arg '(0 (64)))
11764 (org-refile-cache-clear)
11765 (let* ((actionmsg (cond (msg msg)
11766 ((equal arg 3) "Refile (and keep)")
11767 (t "Refile")))
11768 (regionp (org-region-active-p))
11769 (region-start (and regionp (region-beginning)))
11770 (region-end (and regionp (region-end)))
11771 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11772 pos it nbuf file level reversed)
11773 (setq last-command nil)
11774 (when regionp
11775 (goto-char region-start)
11776 (or (bolp) (goto-char (point-at-bol)))
11777 (setq region-start (point))
11778 (unless (or (org-kill-is-subtree-p
11779 (buffer-substring region-start region-end))
11780 (prog1 org-refile-active-region-within-subtree
11781 (let ((s (point-at-eol)))
11782 (org-toggle-heading)
11783 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11784 (user-error "The region is not a (sequence of) subtree(s)")))
11785 (if (equal arg '(16))
11786 (org-refile-goto-last-stored)
11787 (when (or
11788 (and (equal arg 2)
11789 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11790 (prog1
11791 (setq it (list (or org-clock-heading "running clock")
11792 (buffer-file-name
11793 (marker-buffer org-clock-hd-marker))
11795 (marker-position org-clock-hd-marker)))
11796 (setq arg nil)))
11797 (setq it
11798 (or rfloc
11799 (let (heading-text)
11800 (save-excursion
11801 (unless (and arg (listp arg))
11802 (org-back-to-heading t)
11803 (setq heading-text
11804 (replace-regexp-in-string
11805 org-bracket-link-regexp
11806 "\\3"
11807 (or (nth 4 (org-heading-components))
11808 ""))))
11809 (org-refile-get-location
11810 (cond ((and arg (listp arg)) "Goto")
11811 (regionp (concat actionmsg " region to"))
11812 (t (concat actionmsg " subtree \""
11813 heading-text "\" to")))
11814 default-buffer
11815 (and (not (equal '(4) arg))
11816 org-refile-allow-creating-parent-nodes)))))))
11817 (setq file (nth 1 it)
11818 pos (nth 3 it))
11819 (when (and (not arg)
11821 (equal (buffer-file-name) file)
11822 (if regionp
11823 (and (>= pos region-start)
11824 (<= pos region-end))
11825 (and (>= pos (point))
11826 (< pos (save-excursion
11827 (org-end-of-subtree t t))))))
11828 (error "Cannot refile to position inside the tree or region"))
11829 (setq nbuf (or (find-buffer-visiting file)
11830 (find-file-noselect file)))
11831 (if (and arg (not (equal arg 3)))
11832 (progn
11833 (pop-to-buffer-same-window nbuf)
11834 (goto-char pos)
11835 (org-show-context 'org-goto))
11836 (if regionp
11837 (progn
11838 (org-kill-new (buffer-substring region-start region-end))
11839 (org-save-markers-in-region region-start region-end))
11840 (org-copy-subtree 1 nil t))
11841 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11842 (find-file-noselect file)))
11843 (setq reversed (org-notes-order-reversed-p))
11844 (org-with-wide-buffer
11845 (if pos
11846 (progn
11847 (goto-char pos)
11848 (setq level (org-get-valid-level (funcall outline-level) 1))
11849 (goto-char
11850 (if reversed
11851 (or (outline-next-heading) (point-max))
11852 (or (save-excursion (org-get-next-sibling))
11853 (org-end-of-subtree t t)
11854 (point-max)))))
11855 (setq level 1)
11856 (if (not reversed)
11857 (goto-char (point-max))
11858 (goto-char (point-min))
11859 (or (outline-next-heading) (goto-char (point-max)))))
11860 (unless (bolp) (newline))
11861 (org-paste-subtree level nil nil t)
11862 (when org-log-refile
11863 (org-add-log-setup 'refile nil nil org-log-refile)
11864 (unless (eq org-log-refile 'note)
11865 (save-excursion (org-add-log-note))))
11866 (and org-auto-align-tags
11867 (let ((org-loop-over-headlines-in-active-region nil))
11868 (org-set-tags nil t)))
11869 (let ((bookmark-name (plist-get org-bookmark-names-plist
11870 :last-refile)))
11871 (when bookmark-name
11872 (with-demoted-errors
11873 (bookmark-set bookmark-name))))
11874 ;; If we are refiling for capture, make sure that the
11875 ;; last-capture pointers point here
11876 (when (bound-and-true-p org-capture-is-refiling)
11877 (let ((bookmark-name (plist-get org-bookmark-names-plist
11878 :last-capture-marker)))
11879 (when bookmark-name
11880 (with-demoted-errors
11881 (bookmark-set bookmark-name))))
11882 (move-marker org-capture-last-stored-marker (point)))
11883 (when (fboundp 'deactivate-mark) (deactivate-mark))
11884 (run-hooks 'org-after-refile-insert-hook)))
11885 (unless org-refile-keep
11886 (if regionp
11887 (delete-region (point) (+ (point) (- region-end region-start)))
11888 (delete-region
11889 (and (org-back-to-heading t) (point))
11890 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11891 (when (featurep 'org-inlinetask)
11892 (org-inlinetask-remove-END-maybe))
11893 (setq org-markers-to-move nil)
11894 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11896 (defun org-refile-goto-last-stored ()
11897 "Go to the location where the last refile was stored."
11898 (interactive)
11899 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11900 (message "This is the location of the last refile"))
11902 (defun org-refile--get-location (refloc tbl)
11903 "When user refile to REFLOC, find the associated target in TBL.
11904 Also check `org-refile-target-table'."
11905 (car (delq
11907 (mapcar
11908 (lambda (r) (or (assoc r tbl)
11909 (assoc r org-refile-target-table)))
11910 (list (replace-regexp-in-string "/$" "" refloc)
11911 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11913 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11914 "Prompt the user for a refile location, using PROMPT.
11915 PROMPT should not be suffixed with a colon and a space, because
11916 this function appends the default value from
11917 `org-refile-history' automatically, if that is not empty."
11918 (let ((org-refile-targets org-refile-targets)
11919 (org-refile-use-outline-path org-refile-use-outline-path))
11920 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11921 (unless org-refile-target-table
11922 (user-error "No refile targets"))
11923 (let* ((cbuf (current-buffer))
11924 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11925 (cfunc (if (and org-refile-use-outline-path
11926 org-outline-path-complete-in-steps)
11927 #'org-olpath-completing-read
11928 #'completing-read))
11929 (extra (if org-refile-use-outline-path "/" ""))
11930 (cbnex (concat (buffer-name) extra))
11931 (filename (and cfn (expand-file-name cfn)))
11932 (tbl (mapcar
11933 (lambda (x)
11934 (if (and (not (member org-refile-use-outline-path
11935 '(file full-file-path)))
11936 (not (equal filename (nth 1 x))))
11937 (cons (concat (car x) extra " ("
11938 (file-name-nondirectory (nth 1 x)) ")")
11939 (cdr x))
11940 (cons (concat (car x) extra) (cdr x))))
11941 org-refile-target-table))
11942 (completion-ignore-case t)
11943 cdef
11944 (prompt (concat prompt
11945 (or (and (car org-refile-history)
11946 (concat " (default " (car org-refile-history) ")"))
11947 (and (assoc cbnex tbl) (setq cdef cbnex)
11948 (concat " (default " cbnex ")"))) ": "))
11949 pa answ parent-target child parent old-hist)
11950 (setq old-hist org-refile-history)
11951 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11952 nil 'org-refile-history (or cdef (car org-refile-history))))
11953 (if (setq pa (org-refile--get-location answ tbl))
11954 (progn
11955 (org-refile-check-position pa)
11956 (when (or (not org-refile-history)
11957 (not (eq old-hist org-refile-history))
11958 (not (equal (car pa) (car org-refile-history))))
11959 (setq org-refile-history
11960 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11961 org-refile-history
11962 (cdr org-refile-history))))
11963 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11964 (pop org-refile-history)))
11966 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11967 (progn
11968 (setq parent (match-string 1 answ)
11969 child (match-string 2 answ))
11970 (setq parent-target (org-refile--get-location parent tbl))
11971 (when (and parent-target
11972 (or (eq new-nodes t)
11973 (and (eq new-nodes 'confirm)
11974 (y-or-n-p (format "Create new node \"%s\"? "
11975 child)))))
11976 (org-refile-new-child parent-target child)))
11977 (user-error "Invalid target location")))))
11979 (declare-function org-string-nw-p "org-macs" (s))
11980 (defun org-refile-check-position (refile-pointer)
11981 "Check if the refile pointer matches the headline to which it points."
11982 (let* ((file (nth 1 refile-pointer))
11983 (re (nth 2 refile-pointer))
11984 (pos (nth 3 refile-pointer))
11985 buffer)
11986 (if (and (not (markerp pos)) (not file))
11987 (user-error "Please indicate a target file in the refile path")
11988 (when (org-string-nw-p re)
11989 (setq buffer (if (markerp pos)
11990 (marker-buffer pos)
11991 (or (find-buffer-visiting file)
11992 (find-file-noselect file))))
11993 (with-current-buffer buffer
11994 (org-with-wide-buffer
11995 (goto-char pos)
11996 (beginning-of-line 1)
11997 (unless (looking-at-p re)
11998 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12000 (defun org-refile-new-child (parent-target child)
12001 "Use refile target PARENT-TARGET to add new CHILD below it."
12002 (unless parent-target
12003 (error "Cannot find parent for new node"))
12004 (let ((file (nth 1 parent-target))
12005 (pos (nth 3 parent-target))
12006 level)
12007 (with-current-buffer (or (find-buffer-visiting file)
12008 (find-file-noselect file))
12009 (org-with-wide-buffer
12010 (if pos
12011 (goto-char pos)
12012 (goto-char (point-max))
12013 (unless (bolp) (newline)))
12014 (when (looking-at org-outline-regexp)
12015 (setq level (funcall outline-level))
12016 (org-end-of-subtree t t))
12017 (org-back-over-empty-lines)
12018 (insert "\n" (make-string
12019 (if pos (org-get-valid-level level 1) 1) ?*)
12020 " " child "\n")
12021 (beginning-of-line 0)
12022 (list (concat (car parent-target) "/" child) file "" (point))))))
12024 (defun org-olpath-completing-read (prompt collection &rest args)
12025 "Read an outline path like a file name."
12026 (let ((thetable collection))
12027 (apply #'completing-read
12028 prompt
12029 (lambda (string predicate &optional flag)
12030 (cond
12031 ((eq flag nil) (try-completion string thetable))
12032 ((eq flag t)
12033 (let ((l (length string)))
12034 (mapcar (lambda (x)
12035 (let ((r (substring x l))
12036 (f (if (string-match " ([^)]*)$" x)
12037 (match-string 0 x)
12038 "")))
12039 (if (string-match "/" r)
12040 (concat string (substring r 0 (match-end 0)) f)
12041 x)))
12042 (all-completions string thetable predicate))))
12043 ;; Exact match?
12044 ((eq flag 'lambda) (assoc string thetable))))
12045 args)))
12047 ;;;; Dynamic blocks
12049 (defun org-find-dblock (name)
12050 "Find the first dynamic block with name NAME in the buffer.
12051 If not found, stay at current position and return nil."
12052 (let ((case-fold-search t) pos)
12053 (save-excursion
12054 (goto-char (point-min))
12055 (setq pos (and (re-search-forward
12056 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12057 (match-beginning 0))))
12058 (when pos (goto-char pos))
12059 pos))
12061 (defun org-create-dblock (plist)
12062 "Create a dynamic block section, with parameters taken from PLIST.
12063 PLIST must contain a :name entry which is used as the name of the block."
12064 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12065 (end-of-line 1)
12066 (newline))
12067 (let ((col (current-column))
12068 (name (plist-get plist :name)))
12069 (insert "#+BEGIN: " name)
12070 (while plist
12071 (if (eq (car plist) :name)
12072 (setq plist (cddr plist))
12073 (insert " " (prin1-to-string (pop plist)))))
12074 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12075 (beginning-of-line -2)))
12077 (defun org-prepare-dblock ()
12078 "Prepare dynamic block for refresh.
12079 This empties the block, puts the cursor at the insert position and returns
12080 the property list including an extra property :name with the block name."
12081 (unless (looking-at org-dblock-start-re)
12082 (user-error "Not at a dynamic block"))
12083 (let* ((begdel (1+ (match-end 0)))
12084 (name (org-no-properties (match-string 1)))
12085 (params (append (list :name name)
12086 (read (concat "(" (match-string 3) ")")))))
12087 (save-excursion
12088 (beginning-of-line 1)
12089 (skip-chars-forward " \t")
12090 (setq params (plist-put params :indentation-column (current-column))))
12091 (unless (re-search-forward org-dblock-end-re nil t)
12092 (error "Dynamic block not terminated"))
12093 (setq params
12094 (append params
12095 (list :content (buffer-substring
12096 begdel (match-beginning 0)))))
12097 (delete-region begdel (match-beginning 0))
12098 (goto-char begdel)
12099 (open-line 1)
12100 params))
12102 (defun org-map-dblocks (&optional command)
12103 "Apply COMMAND to all dynamic blocks in the current buffer.
12104 If COMMAND is not given, use `org-update-dblock'."
12105 (let ((cmd (or command 'org-update-dblock)))
12106 (save-excursion
12107 (goto-char (point-min))
12108 (while (re-search-forward org-dblock-start-re nil t)
12109 (goto-char (match-beginning 0))
12110 (save-excursion
12111 (condition-case nil
12112 (funcall cmd)
12113 (error (message "Error during update of dynamic block"))))
12114 (unless (re-search-forward org-dblock-end-re nil t)
12115 (error "Dynamic block not terminated"))))))
12117 (defun org-dblock-update (&optional arg)
12118 "User command for updating dynamic blocks.
12119 Update the dynamic block at point. With prefix ARG, update all dynamic
12120 blocks in the buffer."
12121 (interactive "P")
12122 (if arg
12123 (org-update-all-dblocks)
12124 (or (looking-at org-dblock-start-re)
12125 (org-beginning-of-dblock))
12126 (org-update-dblock)))
12128 (defun org-update-dblock ()
12129 "Update the dynamic block at point.
12130 This means to empty the block, parse for parameters and then call
12131 the correct writing function."
12132 (interactive)
12133 (save-excursion
12134 (let* ((win (selected-window))
12135 (pos (point))
12136 (line (org-current-line))
12137 (params (org-prepare-dblock))
12138 (name (plist-get params :name))
12139 (indent (plist-get params :indentation-column))
12140 (cmd (intern (concat "org-dblock-write:" name))))
12141 (message "Updating dynamic block `%s' at line %d..." name line)
12142 (funcall cmd params)
12143 (message "Updating dynamic block `%s' at line %d...done" name line)
12144 (goto-char pos)
12145 (when (and indent (> indent 0))
12146 (setq indent (make-string indent ?\ ))
12147 (save-excursion
12148 (select-window win)
12149 (org-beginning-of-dblock)
12150 (forward-line 1)
12151 (while (not (looking-at org-dblock-end-re))
12152 (insert indent)
12153 (beginning-of-line 2))
12154 (when (looking-at org-dblock-end-re)
12155 (and (looking-at "[ \t]+")
12156 (replace-match ""))
12157 (insert indent)))))))
12159 (defun org-beginning-of-dblock ()
12160 "Find the beginning of the dynamic block at point.
12161 Error if there is no such block at point."
12162 (let ((pos (point))
12163 beg)
12164 (end-of-line 1)
12165 (if (and (re-search-backward org-dblock-start-re nil t)
12166 (setq beg (match-beginning 0))
12167 (re-search-forward org-dblock-end-re nil t)
12168 (> (match-end 0) pos))
12169 (goto-char beg)
12170 (goto-char pos)
12171 (error "Not in a dynamic block"))))
12173 (defun org-update-all-dblocks ()
12174 "Update all dynamic blocks in the buffer.
12175 This function can be used in a hook."
12176 (interactive)
12177 (when (derived-mode-p 'org-mode)
12178 (org-map-dblocks 'org-update-dblock)))
12181 ;;;; Completion
12183 (declare-function org-export-backend-options "ox" (cl-x) t)
12184 (defun org-get-export-keywords ()
12185 "Return a list of all currently understood export keywords.
12186 Export keywords include options, block names, attributes and
12187 keywords relative to each registered export back-end."
12188 (let (keywords)
12189 (dolist (backend
12190 (bound-and-true-p org-export-registered-backends)
12191 (delq nil keywords))
12192 ;; Back-end name (for keywords, like #+LATEX:)
12193 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12194 (dolist (option-entry (org-export-backend-options backend))
12195 ;; Back-end options.
12196 (push (nth 1 option-entry) keywords)))))
12198 (defconst org-options-keywords
12199 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12200 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12201 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12202 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12203 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12205 (defcustom org-structure-template-alist
12206 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12207 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12208 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12209 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12210 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12211 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12212 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12213 ("L" "#+LaTeX: ")
12214 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12215 ("H" "#+HTML: ")
12216 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12217 ("A" "#+ASCII: ")
12218 ("i" "#+INDEX: ?")
12219 ("I" "#+INCLUDE: %file ?"))
12220 "Structure completion elements.
12221 This is a list of abbreviation keys and values. The value gets inserted
12222 if you type `<' followed by the key and then press the completion key,
12223 usually `TAB'. %file will be replaced by a file name after prompting
12224 for the file using completion. The cursor will be placed at the position
12225 of the `?' in the template.
12226 There are two templates for each key, the first uses the original Org syntax,
12227 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12228 the default when the /org-mtags.el/ module has been loaded. See also the
12229 variable `org-mtags-prefer-muse-templates'."
12230 :group 'org-completion
12231 :type '(repeat
12232 (list
12233 (string :tag "Key")
12234 (string :tag "Template")))
12235 :version "26.1"
12236 :package-version '(Org . "8.3"))
12238 (defun org-try-structure-completion ()
12239 "Try to complete a structure template before point.
12240 This looks for strings like \"<e\" on an otherwise empty line and
12241 expands them."
12242 (let ((l (buffer-substring (point-at-bol) (point)))
12244 (when (and (looking-at "[ \t]*$")
12245 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12246 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12247 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12248 (match-beginning 1)) a)
12249 t)))
12251 (defun org-complete-expand-structure-template (start cell)
12252 "Expand a structure template."
12253 (let ((rpl (nth 1 cell))
12254 (ind ""))
12255 (delete-region start (point))
12256 (when (string-match "\\`[ \t]*#\\+" rpl)
12257 (cond
12258 ((bolp))
12259 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12260 (setq ind (buffer-substring (point-at-bol) (point))))
12261 (t (newline))))
12262 (setq start (point))
12263 (when (string-match "%file" rpl)
12264 (setq rpl (replace-match
12265 (concat
12266 "\""
12267 (save-match-data
12268 (abbreviate-file-name (read-file-name "Include file: ")))
12269 "\"")
12270 t t rpl)))
12271 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12272 (concat "\n" ind)))
12273 (insert rpl)
12274 (when (re-search-backward "\\?" start t) (delete-char 1))))
12276 ;;;; TODO, DEADLINE, Comments
12278 (defun org-toggle-comment ()
12279 "Change the COMMENT state of an entry."
12280 (interactive)
12281 (save-excursion
12282 (org-back-to-heading)
12283 (let ((case-fold-search nil))
12284 (looking-at org-complex-heading-regexp))
12285 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12286 (skip-chars-forward " \t")
12287 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12288 (if (org-in-commented-heading-p t)
12289 (delete-region (point)
12290 (progn (search-forward " " (line-end-position) 'move)
12291 (skip-chars-forward " \t")
12292 (point)))
12293 (insert org-comment-string)
12294 (unless (eolp) (insert " ")))))
12296 (defvar org-last-todo-state-is-todo nil
12297 "This is non-nil when the last TODO state change led to a TODO state.
12298 If the last change removed the TODO tag or switched to DONE, then
12299 this is nil.")
12301 (defvar org-setting-tags nil) ; dynamically skipped
12303 (defvar org-todo-setup-filter-hook nil
12304 "Hook for functions that pre-filter todo specs.
12305 Each function takes a todo spec and returns either nil or the spec
12306 transformed into canonical form." )
12308 (defvar org-todo-get-default-hook nil
12309 "Hook for functions that get a default item for todo.
12310 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12311 nil or a string to be used for the todo mark." )
12313 (defvar org-agenda-headline-snapshot-before-repeat)
12315 (defun org-current-effective-time ()
12316 "Return current time adjusted for `org-extend-today-until' variable."
12317 (let* ((ct (org-current-time))
12318 (dct (decode-time ct))
12319 (ct1
12320 (cond
12321 (org-use-last-clock-out-time-as-effective-time
12322 (or (org-clock-get-last-clock-out-time) ct))
12323 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12324 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12325 (t ct))))
12326 ct1))
12328 (defun org-todo-yesterday (&optional arg)
12329 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12330 (interactive "P")
12331 (if (eq major-mode 'org-agenda-mode)
12332 (apply 'org-agenda-todo-yesterday arg)
12333 (let* ((org-use-effective-time t)
12334 (hour (nth 2 (decode-time (org-current-time))))
12335 (org-extend-today-until (1+ hour)))
12336 (org-todo arg))))
12338 (defvar org-block-entry-blocking ""
12339 "First entry preventing the TODO state change.")
12341 (defun org-cancel-repeater ()
12342 "Cancel a repeater by setting its numeric value to zero."
12343 (interactive)
12344 (save-excursion
12345 (org-back-to-heading t)
12346 (let ((bound1 (point))
12347 (bound0 (save-excursion (outline-next-heading) (point))))
12348 (when (and (re-search-forward
12349 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12350 org-deadline-time-regexp "\\)\\|\\("
12351 org-ts-regexp "\\)")
12352 bound0 t)
12353 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12354 bound1 t))
12355 (replace-match "0" t nil nil 1)))))
12357 (defvar org-state)
12358 (defvar org-blocked-by-checkboxes)
12359 (defun org-todo (&optional arg)
12360 "Change the TODO state of an item.
12362 The state of an item is given by a keyword at the start of the heading,
12363 like
12364 *** TODO Write paper
12365 *** DONE Call mom
12367 The different keywords are specified in the variable `org-todo-keywords'.
12368 By default the available states are \"TODO\" and \"DONE\". So, for this
12369 example: when the item starts with TODO, it is changed to DONE.
12370 When it starts with DONE, the DONE is removed. And when neither TODO nor
12371 DONE are present, add TODO at the beginning of the heading.
12373 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12374 state.
12375 With numeric prefix ARG, switch to that state.
12376 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12377 next set of TODO \
12378 keywords (nextset).
12379 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12380 prefix, circumvent any state blocking.
12381 With a numeric prefix arg of 0, inhibit note taking for the change.
12382 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12384 When called through ELisp, arg is also interpreted in the following way:
12385 `none' -> empty state
12386 \"\" -> switch to empty state
12387 `done' -> switch to DONE
12388 `nextset' -> switch to the next set of keywords
12389 `previousset' -> switch to the previous set of keywords
12390 \"WAITING\" -> switch to the specified keyword, but only if it
12391 really is a member of `org-todo-keywords'."
12392 (interactive "P")
12393 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12394 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12395 'region-start-level 'region))
12396 org-loop-over-headlines-in-active-region)
12397 (org-map-entries
12398 `(org-todo ,arg)
12399 org-loop-over-headlines-in-active-region
12400 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12401 (when (equal arg '(16)) (setq arg 'nextset))
12402 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12403 (let ((org-blocker-hook org-blocker-hook)
12404 commentp
12405 case-fold-search)
12406 (when (equal arg '(64))
12407 (setq arg nil org-blocker-hook nil))
12408 (when (and org-blocker-hook
12409 (or org-inhibit-blocking
12410 (org-entry-get nil "NOBLOCKING")))
12411 (setq org-blocker-hook nil))
12412 (save-excursion
12413 (catch 'exit
12414 (org-back-to-heading t)
12415 (when (org-in-commented-heading-p t)
12416 (org-toggle-comment)
12417 (setq commentp t))
12418 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12419 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12420 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12421 (let* ((match-data (match-data))
12422 (startpos (point-at-bol))
12423 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12424 (org-log-done org-log-done)
12425 (org-log-repeat org-log-repeat)
12426 (org-todo-log-states org-todo-log-states)
12427 (org-inhibit-logging
12428 (if (equal arg 0)
12429 (progn (setq arg nil) 'note) org-inhibit-logging))
12430 (this (match-string 1))
12431 (hl-pos (match-beginning 0))
12432 (head (org-get-todo-sequence-head this))
12433 (ass (assoc head org-todo-kwd-alist))
12434 (interpret (nth 1 ass))
12435 (done-word (nth 3 ass))
12436 (final-done-word (nth 4 ass))
12437 (org-last-state (or this ""))
12438 (completion-ignore-case t)
12439 (member (member this org-todo-keywords-1))
12440 (tail (cdr member))
12441 (org-state (cond
12442 ((and org-todo-key-trigger
12443 (or (and (equal arg '(4))
12444 (eq org-use-fast-todo-selection 'prefix))
12445 (and (not arg) org-use-fast-todo-selection
12446 (not (eq org-use-fast-todo-selection
12447 'prefix)))))
12448 ;; Use fast selection.
12449 (org-fast-todo-selection))
12450 ((and (equal arg '(4))
12451 (or (not org-use-fast-todo-selection)
12452 (not org-todo-key-trigger)))
12453 ;; Read a state with completion.
12454 (completing-read
12455 "State: " (mapcar #'list org-todo-keywords-1)
12456 nil t))
12457 ((eq arg 'right)
12458 (if this
12459 (if tail (car tail) nil)
12460 (car org-todo-keywords-1)))
12461 ((eq arg 'left)
12462 (unless (equal member org-todo-keywords-1)
12463 (if this
12464 (nth (- (length org-todo-keywords-1)
12465 (length tail) 2)
12466 org-todo-keywords-1)
12467 (org-last org-todo-keywords-1))))
12468 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12469 (setq arg nil))) ;hack to fall back to cycling
12470 (arg
12471 ;; User or caller requests a specific state.
12472 (cond
12473 ((equal arg "") nil)
12474 ((eq arg 'none) nil)
12475 ((eq arg 'done) (or done-word (car org-done-keywords)))
12476 ((eq arg 'nextset)
12477 (or (car (cdr (member head org-todo-heads)))
12478 (car org-todo-heads)))
12479 ((eq arg 'previousset)
12480 (let ((org-todo-heads (reverse org-todo-heads)))
12481 (or (car (cdr (member head org-todo-heads)))
12482 (car org-todo-heads))))
12483 ((car (member arg org-todo-keywords-1)))
12484 ((stringp arg)
12485 (user-error "State `%s' not valid in this file" arg))
12486 ((nth (1- (prefix-numeric-value arg))
12487 org-todo-keywords-1))))
12488 ((null member) (or head (car org-todo-keywords-1)))
12489 ((equal this final-done-word) nil) ;-> make empty
12490 ((null tail) nil) ;-> first entry
12491 ((memq interpret '(type priority))
12492 (if (eq this-command last-command)
12493 (car tail)
12494 (if (> (length tail) 0)
12495 (or done-word (car org-done-keywords))
12496 nil)))
12498 (car tail))))
12499 (org-state (or
12500 (run-hook-with-args-until-success
12501 'org-todo-get-default-hook org-state org-last-state)
12502 org-state))
12503 (next (if org-state (concat " " org-state " ") " "))
12504 (change-plist (list :type 'todo-state-change :from this :to org-state
12505 :position startpos))
12506 dolog now-done-p)
12507 (when org-blocker-hook
12508 (let (org-blocked-by-checkboxes block-reason)
12509 (setq org-last-todo-state-is-todo
12510 (not (member this org-done-keywords)))
12511 (unless (save-excursion
12512 (save-match-data
12513 (org-with-wide-buffer
12514 (run-hook-with-args-until-failure
12515 'org-blocker-hook change-plist))))
12516 (setq block-reason (if org-blocked-by-checkboxes
12517 "contained checkboxes"
12518 (format "\"%s\"" org-block-entry-blocking)))
12519 (if (called-interactively-p 'interactive)
12520 (user-error "TODO state change from %s to %s blocked (by %s)"
12521 this org-state block-reason)
12522 ;; Fail silently.
12523 (message "TODO state change from %s to %s blocked (by %s)"
12524 this org-state block-reason)
12525 (throw 'exit nil)))))
12526 (store-match-data match-data)
12527 (replace-match next t t)
12528 (cond ((equal this org-state)
12529 (message "TODO state was already %s" (org-trim next)))
12530 ((not (pos-visible-in-window-p hl-pos))
12531 (message "TODO state changed to %s" (org-trim next))))
12532 (unless head
12533 (setq head (org-get-todo-sequence-head org-state)
12534 ass (assoc head org-todo-kwd-alist)
12535 interpret (nth 1 ass)
12536 done-word (nth 3 ass)
12537 final-done-word (nth 4 ass)))
12538 (when (memq arg '(nextset previousset))
12539 (message "Keyword-Set %d/%d: %s"
12540 (- (length org-todo-sets) -1
12541 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12542 (length org-todo-sets)
12543 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12544 (setq org-last-todo-state-is-todo
12545 (not (member org-state org-done-keywords)))
12546 (setq now-done-p (and (member org-state org-done-keywords)
12547 (not (member this org-done-keywords))))
12548 (and logging (org-local-logging logging))
12549 (when (and (or org-todo-log-states org-log-done)
12550 (not (eq org-inhibit-logging t))
12551 (not (memq arg '(nextset previousset))))
12552 ;; We need to look at recording a time and note.
12553 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12554 (nth 2 (assoc this org-todo-log-states))))
12555 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12556 (setq dolog 'time))
12557 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12558 (and org-state
12559 (member org-state org-not-done-keywords)
12560 (not (member this org-not-done-keywords))))
12561 ;; This is now a todo state and was not one before
12562 ;; If there was a CLOSED time stamp, get rid of it.
12563 (org-add-planning-info nil nil 'closed))
12564 (when (and now-done-p org-log-done)
12565 ;; It is now done, and it was not done before.
12566 (org-add-planning-info 'closed (org-current-effective-time))
12567 (when (and (not dolog) (eq 'note org-log-done))
12568 (org-add-log-setup 'done org-state this 'note)))
12569 (when (and org-state dolog)
12570 ;; This is a non-nil state, and we need to log it.
12571 (org-add-log-setup 'state org-state this dolog)))
12572 ;; Fixup tag positioning.
12573 (org-todo-trigger-tag-changes org-state)
12574 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12575 (when org-provide-todo-statistics
12576 (org-update-parent-todo-statistics))
12577 (run-hooks 'org-after-todo-state-change-hook)
12578 (when (and arg (not (member org-state org-done-keywords)))
12579 (setq head (org-get-todo-sequence-head org-state)))
12580 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12581 ;; Do we need to trigger a repeat?
12582 (when now-done-p
12583 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12584 ;; This is for the agenda, take a snapshot of the headline.
12585 (save-match-data
12586 (setq org-agenda-headline-snapshot-before-repeat
12587 (org-get-heading))))
12588 (org-auto-repeat-maybe org-state))
12589 ;; Fixup cursor location if close to the keyword.
12590 (when (and (outline-on-heading-p)
12591 (not (bolp))
12592 (save-excursion (beginning-of-line 1)
12593 (looking-at org-todo-line-regexp))
12594 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12595 (goto-char (or (match-end 2) (match-end 1)))
12596 (and (looking-at " ") (just-one-space)))
12597 (when org-trigger-hook
12598 (save-excursion
12599 (run-hook-with-args 'org-trigger-hook change-plist)))
12600 (when commentp (org-toggle-comment))))))))
12602 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12603 "Block turning an entry into a TODO, using the hierarchy.
12604 This checks whether the current task should be blocked from state
12605 changes. Such blocking occurs when:
12607 1. The task has children which are not all in a completed state.
12609 2. A task has a parent with the property :ORDERED:, and there
12610 are siblings prior to the current task with incomplete
12611 status.
12613 3. The parent of the task is blocked because it has siblings that should
12614 be done first, or is child of a block grandparent TODO entry."
12616 (if (not org-enforce-todo-dependencies)
12617 t ; if locally turned off don't block
12618 (catch 'dont-block
12619 ;; If this is not a todo state change, or if this entry is already DONE,
12620 ;; do not block
12621 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12622 (member (plist-get change-plist :from)
12623 (cons 'done org-done-keywords))
12624 (member (plist-get change-plist :to)
12625 (cons 'todo org-not-done-keywords))
12626 (not (plist-get change-plist :to)))
12627 (throw 'dont-block t))
12628 ;; If this task has children, and any are undone, it's blocked
12629 (save-excursion
12630 (org-back-to-heading t)
12631 (let ((this-level (funcall outline-level)))
12632 (outline-next-heading)
12633 (let ((child-level (funcall outline-level)))
12634 (while (and (not (eobp))
12635 (> child-level this-level))
12636 ;; this todo has children, check whether they are all
12637 ;; completed
12638 (when (and (not (org-entry-is-done-p))
12639 (org-entry-is-todo-p))
12640 (setq org-block-entry-blocking (org-get-heading))
12641 (throw 'dont-block nil))
12642 (outline-next-heading)
12643 (setq child-level (funcall outline-level))))))
12644 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12645 ;; any previous siblings are undone, it's blocked
12646 (save-excursion
12647 (org-back-to-heading t)
12648 (let* ((pos (point))
12649 (parent-pos (and (org-up-heading-safe) (point)))
12650 (case-fold-search nil))
12651 (unless parent-pos (throw 'dont-block t)) ; no parent
12652 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12653 (forward-line 1)
12654 (re-search-forward org-not-done-heading-regexp pos t))
12655 (setq org-block-entry-blocking (match-string 0))
12656 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12657 ;; Search further up the hierarchy, to see if an ancestor is blocked
12658 (while t
12659 (goto-char parent-pos)
12660 (unless (looking-at org-not-done-heading-regexp)
12661 (throw 'dont-block t)) ; do not block, parent is not a TODO
12662 (setq pos (point))
12663 (setq parent-pos (and (org-up-heading-safe) (point)))
12664 (unless parent-pos (throw 'dont-block t)) ; no parent
12665 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12666 (forward-line 1)
12667 (re-search-forward org-not-done-heading-regexp pos t)
12668 (setq org-block-entry-blocking (org-get-heading)))
12669 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12671 (defcustom org-track-ordered-property-with-tag nil
12672 "Should the ORDERED property also be shown as a tag?
12673 The ORDERED property decides if an entry should require subtasks to be
12674 completed in sequence. Since a property is not very visible, setting
12675 this option means that toggling the ORDERED property with the command
12676 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12677 not relevant for the behavior, but it makes things more visible.
12679 Note that toggling the tag with tags commands will not change the property
12680 and therefore not influence behavior!
12682 This can be t, meaning the tag ORDERED should be used, It can also be a
12683 string to select a different tag for this task."
12684 :group 'org-todo
12685 :type '(choice
12686 (const :tag "No tracking" nil)
12687 (const :tag "Track with ORDERED tag" t)
12688 (string :tag "Use other tag")))
12690 (defun org-toggle-ordered-property ()
12691 "Toggle the ORDERED property of the current entry.
12692 For better visibility, you can track the value of this property with a tag.
12693 See variable `org-track-ordered-property-with-tag'."
12694 (interactive)
12695 (let* ((t1 org-track-ordered-property-with-tag)
12696 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12697 (save-excursion
12698 (org-back-to-heading)
12699 (if (org-entry-get nil "ORDERED")
12700 (progn
12701 (org-delete-property "ORDERED")
12702 (and tag (org-toggle-tag tag 'off))
12703 (message "Subtasks can be completed in arbitrary order"))
12704 (org-entry-put nil "ORDERED" "t")
12705 (and tag (org-toggle-tag tag 'on))
12706 (message "Subtasks must be completed in sequence")))))
12708 (defun org-block-todo-from-checkboxes (change-plist)
12709 "Block turning an entry into a TODO, using checkboxes.
12710 This checks whether the current task should be blocked from state
12711 changes because there are unchecked boxes in this entry."
12712 (if (not org-enforce-todo-checkbox-dependencies)
12713 t ; if locally turned off don't block
12714 (catch 'dont-block
12715 ;; If this is not a todo state change, or if this entry is already DONE,
12716 ;; do not block
12717 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12718 (member (plist-get change-plist :from)
12719 (cons 'done org-done-keywords))
12720 (member (plist-get change-plist :to)
12721 (cons 'todo org-not-done-keywords))
12722 (not (plist-get change-plist :to)))
12723 (throw 'dont-block t))
12724 ;; If this task has checkboxes that are not checked, it's blocked
12725 (save-excursion
12726 (org-back-to-heading t)
12727 (let ((beg (point)) end)
12728 (outline-next-heading)
12729 (setq end (point))
12730 (goto-char beg)
12731 (when (org-list-search-forward
12732 (concat (org-item-beginning-re)
12733 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12734 "\\[[- ]\\]")
12735 end t)
12736 (when (boundp 'org-blocked-by-checkboxes)
12737 (setq org-blocked-by-checkboxes t))
12738 (throw 'dont-block nil))))
12739 t))) ; do not block
12741 (defun org-entry-blocked-p ()
12742 "Non-nil if entry at point is blocked."
12743 (and (not (org-entry-get nil "NOBLOCKING"))
12744 (member (org-entry-get nil "TODO") org-not-done-keywords)
12745 (not (run-hook-with-args-until-failure
12746 'org-blocker-hook
12747 (list :type 'todo-state-change
12748 :position (point)
12749 :from 'todo
12750 :to 'done)))))
12752 (defun org-update-statistics-cookies (all)
12753 "Update the statistics cookie, either from TODO or from checkboxes.
12754 This should be called with the cursor in a line with a statistics
12755 cookie. When called with a \\[universal-argument] prefix, update
12756 all statistics cookies in the buffer."
12757 (interactive "P")
12758 (if all
12759 (progn
12760 (org-update-checkbox-count 'all)
12761 (org-map-entries 'org-update-parent-todo-statistics))
12762 (if (not (org-at-heading-p))
12763 (org-update-checkbox-count)
12764 (let ((pos (point-marker))
12765 end l1 l2)
12766 (ignore-errors (org-back-to-heading t))
12767 (if (not (org-at-heading-p))
12768 (org-update-checkbox-count)
12769 (setq l1 (org-outline-level))
12770 (setq end (save-excursion
12771 (outline-next-heading)
12772 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12773 (point)))
12774 (if (and (save-excursion
12775 (re-search-forward
12776 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12777 (not (save-excursion (re-search-forward
12778 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12779 (org-update-checkbox-count)
12780 (if (and l2 (> l2 l1))
12781 (progn
12782 (goto-char end)
12783 (org-update-parent-todo-statistics))
12784 (goto-char pos)
12785 (beginning-of-line 1)
12786 (while (re-search-forward
12787 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12788 (point-at-eol) t)
12789 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12790 (goto-char pos)
12791 (move-marker pos nil)))))
12793 (defvar org-entry-property-inherited-from) ;; defined below
12794 (defun org-update-parent-todo-statistics ()
12795 "Update any statistics cookie in the parent of the current headline.
12796 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12797 the entire subtree and this will travel up the hierarchy and update
12798 statistics everywhere."
12799 (let* ((prop (save-excursion (org-up-heading-safe)
12800 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12801 (recursive (or (not org-hierarchical-todo-statistics)
12802 (and prop (string-match "\\<recursive\\>" prop))))
12803 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12805 (first t)
12806 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12807 level ltoggle l1 new ndel
12808 (cnt-all 0) (cnt-done 0) is-percent kwd
12809 checkbox-beg cookie-present)
12810 (catch 'exit
12811 (save-excursion
12812 (beginning-of-line 1)
12813 (setq ltoggle (funcall outline-level))
12814 ;; Three situations are to consider:
12816 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12817 ;; to the top-level ancestor on the headline;
12819 ;; 2. If parent has "recursive" property, repeat up to the
12820 ;; headline setting that property, taking inheritance into
12821 ;; account;
12823 ;; 3. Else, move up to direct parent and proceed only once.
12824 (while (and (setq level (org-up-heading-safe))
12825 (or recursive first)
12826 (>= (point) lim))
12827 (setq first nil cookie-present nil)
12828 (unless (and level
12829 (not (string-match
12830 "\\<checkbox\\>"
12831 (downcase (or (org-entry-get nil "COOKIE_DATA")
12832 "")))))
12833 (throw 'exit nil))
12834 (while (re-search-forward box-re (point-at-eol) t)
12835 (setq cnt-all 0 cnt-done 0 cookie-present t)
12836 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12837 (save-match-data
12838 (unless (outline-next-heading) (throw 'exit nil))
12839 (while (and (looking-at org-complex-heading-regexp)
12840 (> (setq l1 (length (match-string 1))) level))
12841 (setq kwd (and (or recursive (= l1 ltoggle))
12842 (match-string 2)))
12843 (if (or (eq org-provide-todo-statistics 'all-headlines)
12844 (and (eq org-provide-todo-statistics t)
12845 (or (member kwd org-done-keywords)))
12846 (and (listp org-provide-todo-statistics)
12847 (stringp (car org-provide-todo-statistics))
12848 (or (member kwd org-provide-todo-statistics)
12849 (member kwd org-done-keywords)))
12850 (and (listp org-provide-todo-statistics)
12851 (listp (car org-provide-todo-statistics))
12852 (or (member kwd (car org-provide-todo-statistics))
12853 (and (member kwd org-done-keywords)
12854 (member kwd (cadr org-provide-todo-statistics))))))
12855 (setq cnt-all (1+ cnt-all))
12856 (and (eq org-provide-todo-statistics t)
12858 (setq cnt-all (1+ cnt-all))))
12859 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12860 (member kwd org-done-keywords))
12861 (and (listp org-provide-todo-statistics)
12862 (listp (car org-provide-todo-statistics))
12863 (member kwd org-done-keywords)
12864 (member kwd (cadr org-provide-todo-statistics)))
12865 (and (listp org-provide-todo-statistics)
12866 (stringp (car org-provide-todo-statistics))
12867 (member kwd org-done-keywords)))
12868 (setq cnt-done (1+ cnt-done)))
12869 (outline-next-heading)))
12870 (setq new
12871 (if is-percent
12872 (format "[%d%%]" (floor (* 100.0 cnt-done)
12873 (max 1 cnt-all)))
12874 (format "[%d/%d]" cnt-done cnt-all))
12875 ndel (- (match-end 0) checkbox-beg))
12876 (goto-char checkbox-beg)
12877 (insert new)
12878 (delete-region (point) (+ (point) ndel))
12879 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12880 (when cookie-present
12881 (run-hook-with-args 'org-after-todo-statistics-hook
12882 cnt-done (- cnt-all cnt-done))))))
12883 (run-hooks 'org-todo-statistics-hook)))
12885 (defvar org-after-todo-statistics-hook nil
12886 "Hook that is called after a TODO statistics cookie has been updated.
12887 Each function is called with two arguments: the number of not-done entries
12888 and the number of done entries.
12890 For example, the following function, when added to this hook, will switch
12891 an entry to DONE when all children are done, and back to TODO when new
12892 entries are set to a TODO status. Note that this hook is only called
12893 when there is a statistics cookie in the headline!
12895 (defun org-summary-todo (n-done n-not-done)
12896 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12897 (let (org-log-done org-log-states) ; turn off logging
12898 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12901 (defvar org-todo-statistics-hook nil
12902 "Hook that is run whenever Org thinks TODO statistics should be updated.
12903 This hook runs even if there is no statistics cookie present, in which case
12904 `org-after-todo-statistics-hook' would not run.")
12906 (defun org-todo-trigger-tag-changes (state)
12907 "Apply the changes defined in `org-todo-state-tags-triggers'."
12908 (let ((l org-todo-state-tags-triggers)
12909 changes)
12910 (when (or (not state) (equal state ""))
12911 (setq changes (append changes (cdr (assoc "" l)))))
12912 (when (and (stringp state) (> (length state) 0))
12913 (setq changes (append changes (cdr (assoc state l)))))
12914 (when (member state org-not-done-keywords)
12915 (setq changes (append changes (cdr (assq 'todo l)))))
12916 (when (member state org-done-keywords)
12917 (setq changes (append changes (cdr (assq 'done l)))))
12918 (dolist (c changes)
12919 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12921 (defun org-local-logging (value)
12922 "Get logging settings from a property VALUE."
12923 ;; Directly set the variables, they are already local.
12924 (setq org-log-done nil
12925 org-log-repeat nil
12926 org-todo-log-states nil)
12927 (dolist (w (org-split-string value))
12928 (let (a)
12929 (cond
12930 ((setq a (assoc w org-startup-options))
12931 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12932 (set (nth 1 a) (nth 2 a))))
12933 ((setq a (org-extract-log-state-settings w))
12934 (and (member (car a) org-todo-keywords-1)
12935 (push a org-todo-log-states)))))))
12937 (defun org-get-todo-sequence-head (kwd)
12938 "Return the head of the TODO sequence to which KWD belongs.
12939 If KWD is not set, check if there is a text property remembering the
12940 right sequence."
12941 (let (p)
12942 (cond
12943 ((not kwd)
12944 (or (get-text-property (point-at-bol) 'org-todo-head)
12945 (progn
12946 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12947 nil (point-at-eol)))
12948 (get-text-property p 'org-todo-head))))
12949 ((not (member kwd org-todo-keywords-1))
12950 (car org-todo-keywords-1))
12951 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12953 (defun org-fast-todo-selection ()
12954 "Fast TODO keyword selection with single keys.
12955 Returns the new TODO keyword, or nil if no state change should occur."
12956 (let* ((fulltable org-todo-key-alist)
12957 (done-keywords org-done-keywords) ;; needed for the faces.
12958 (maxlen (apply 'max (mapcar
12959 (lambda (x)
12960 (if (stringp (car x)) (string-width (car x)) 0))
12961 fulltable)))
12962 (expert nil)
12963 (fwidth (+ maxlen 3 1 3))
12964 (ncol (/ (- (window-width) 4) fwidth))
12965 tg cnt e c tbl
12966 groups ingroup)
12967 (save-excursion
12968 (save-window-excursion
12969 (if expert
12970 (set-buffer (get-buffer-create " *Org todo*"))
12971 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12972 (erase-buffer)
12973 (setq-local org-done-keywords done-keywords)
12974 (setq tbl fulltable cnt 0)
12975 (while (setq e (pop tbl))
12976 (cond
12977 ((equal e '(:startgroup))
12978 (push '() groups) (setq ingroup t)
12979 (unless (= cnt 0)
12980 (setq cnt 0)
12981 (insert "\n"))
12982 (insert "{ "))
12983 ((equal e '(:endgroup))
12984 (setq ingroup nil cnt 0)
12985 (insert "}\n"))
12986 ((equal e '(:newline))
12987 (unless (= cnt 0)
12988 (setq cnt 0)
12989 (insert "\n")
12990 (setq e (car tbl))
12991 (while (equal (car tbl) '(:newline))
12992 (insert "\n")
12993 (setq tbl (cdr tbl)))))
12995 (setq tg (car e) c (cdr e))
12996 (when ingroup (push tg (car groups)))
12997 (setq tg (org-add-props tg nil 'face
12998 (org-get-todo-face tg)))
12999 (when (and (= cnt 0) (not ingroup)) (insert " "))
13000 (insert "[" c "] " tg (make-string
13001 (- fwidth 4 (length tg)) ?\ ))
13002 (when (= (setq cnt (1+ cnt)) ncol)
13003 (insert "\n")
13004 (when ingroup (insert " "))
13005 (setq cnt 0)))))
13006 (insert "\n")
13007 (goto-char (point-min))
13008 (unless expert (org-fit-window-to-buffer))
13009 (message "[a-z..]:Set [SPC]:clear")
13010 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13011 (cond
13012 ((or (= c ?\C-g)
13013 (and (= c ?q) (not (rassoc c fulltable))))
13014 (setq quit-flag t))
13015 ((= c ?\ ) nil)
13016 ((setq e (rassoc c fulltable) tg (car e))
13018 (t (setq quit-flag t)))))))
13020 (defun org-entry-is-todo-p ()
13021 (member (org-get-todo-state) org-not-done-keywords))
13023 (defun org-entry-is-done-p ()
13024 (member (org-get-todo-state) org-done-keywords))
13026 (defun org-get-todo-state ()
13027 "Return the TODO keyword of the current subtree."
13028 (save-excursion
13029 (org-back-to-heading t)
13030 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13031 (match-end 2)
13032 (match-string 2))))
13034 (defun org-at-date-range-p (&optional inactive-ok)
13035 "Non-nil if point is inside a date range.
13037 When optional argument INACTIVE-OK is non-nil, also consider
13038 inactive time ranges.
13040 When this function returns a non-nil value, match data is set
13041 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13042 on INACTIVE-OK."
13043 (interactive)
13044 (save-excursion
13045 (catch 'exit
13046 (let ((pos (point)))
13047 (skip-chars-backward "^[<\r\n")
13048 (skip-chars-backward "<[")
13049 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13050 (>= (match-end 0) pos)
13051 (throw 'exit t))
13052 (skip-chars-backward "^<[\r\n")
13053 (skip-chars-backward "<[")
13054 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13055 (>= (match-end 0) pos)
13056 (throw 'exit t)))
13057 nil)))
13059 (defun org-get-repeat (&optional timestamp)
13060 "Check if there is a time-stamp with repeater in this entry.
13062 Return the repeater, as a string, or nil. Also return nil when
13063 this function is called before first heading.
13065 When optional argument TIMESTAMP is a string, extract the
13066 repeater from there instead."
13067 (save-match-data
13068 (cond (timestamp
13069 (and (string-match org-repeat-re timestamp)
13070 (match-string-no-properties 1 timestamp)))
13071 ((org-before-first-heading-p) nil)
13073 (save-excursion
13074 (org-back-to-heading t)
13075 (let ((end (org-entry-end-position)))
13076 (catch :repeat
13077 (while (re-search-forward org-repeat-re end t)
13078 (when (save-match-data (org-at-timestamp-p 'agenda))
13079 (throw :repeat (match-string-no-properties 1)))))))))))
13081 (defvar org-last-changed-timestamp)
13082 (defvar org-last-inserted-timestamp)
13083 (defvar org-log-post-message)
13084 (defvar org-log-note-purpose)
13085 (defvar org-log-note-how nil)
13086 (defvar org-log-note-extra)
13087 (defun org-auto-repeat-maybe (done-word)
13088 "Check if the current headline contains a repeated time-stamp.
13090 If yes, set TODO state back to what it was and change the base date
13091 of repeating deadline/scheduled time stamps to new date.
13093 This function is run automatically after each state change to a DONE state."
13094 (let* ((repeat (org-get-repeat))
13095 (aa (assoc org-last-state org-todo-kwd-alist))
13096 (interpret (nth 1 aa))
13097 (head (nth 2 aa))
13098 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13099 (msg "Entry repeats: ")
13100 (org-log-done nil)
13101 (org-todo-log-states nil)
13102 (end (copy-marker (org-entry-end-position))))
13103 (unwind-protect
13104 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13105 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13106 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13107 org-todo-repeat-to-state)))
13108 (org-todo (cond
13109 ((and to-state (member to-state org-todo-keywords-1))
13110 to-state)
13111 ((eq interpret 'type) org-last-state)
13112 (head)
13113 (t 'none))))
13114 (org-back-to-heading t)
13115 (org-add-planning-info nil nil 'closed)
13116 ;; When `org-log-repeat' is non-nil or entry contains
13117 ;; a clock, set LAST_REPEAT property.
13118 (when (or org-log-repeat
13119 (catch :clock
13120 (while (re-search-forward org-clock-line-re end t)
13121 (when (org-at-clock-log-p) (throw :clock t)))))
13122 (org-entry-put nil "LAST_REPEAT" (format-time-string
13123 (org-time-stamp-format t t)
13124 (current-time))))
13125 (when org-log-repeat
13126 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13127 (memq 'org-add-log-note post-command-hook))
13128 ;; We are already setup for some record.
13129 (when (eq org-log-repeat 'note)
13130 ;; Make sure we take a note, not only a time stamp.
13131 (setq org-log-note-how 'note))
13132 ;; Set up for taking a record.
13133 (org-add-log-setup 'state
13134 (or done-word (car org-done-keywords))
13135 org-last-state
13136 org-log-repeat)))
13137 (let ((planning-re (regexp-opt
13138 (list org-scheduled-string org-deadline-string))))
13139 (while (re-search-forward org-ts-regexp end t)
13140 (let* ((ts (match-string 0))
13141 (planning? (org-at-planning-p))
13142 (type (if (not planning?) "Plain:"
13143 (save-excursion
13144 (re-search-backward
13145 planning-re (line-beginning-position) t)
13146 (match-string 0)))))
13147 (cond
13148 ;; Ignore fake time-stamps (e.g., within comments).
13149 ((not (org-at-timestamp-p 'agenda)))
13150 ;; Time-stamps without a repeater are usually
13151 ;; skipped. However, a SCHEDULED time-stamp without
13152 ;; one is removed, as they are no longer relevant.
13153 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13154 ts))
13155 (when (equal type org-scheduled-string)
13156 (org-remove-timestamp-with-keyword type)))
13158 (let ((n (string-to-number (match-string 2 ts)))
13159 (what (match-string 3 ts)))
13160 (when (equal what "w") (setq n (* n 7) what "d"))
13161 (when (and (equal what "h")
13162 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13163 ts)))
13164 (user-error
13165 "Cannot repeat in Repeat in %d hour(s) because no hour \
13166 has been set"
13168 ;; Preparation, see if we need to modify the start
13169 ;; date for the change.
13170 (when (match-end 1)
13171 (let ((time (save-match-data
13172 (org-time-string-to-time ts))))
13173 (cond
13174 ((equal (match-string 1 ts) ".")
13175 ;; Shift starting date to today
13176 (org-timestamp-change
13177 (- (org-today) (time-to-days time))
13178 'day))
13179 ((equal (match-string 1 ts) "+")
13180 (let ((nshiftmax 10)
13181 (nshift 0))
13182 (while (or (= nshift 0)
13183 (not (time-less-p (current-time) time)))
13184 (when (= (cl-incf nshift) nshiftmax)
13185 (or (y-or-n-p
13186 (format "%d repeater intervals were not \
13187 enough to shift date past today. Continue? "
13188 nshift))
13189 (user-error "Abort")))
13190 (org-timestamp-change n (cdr (assoc what whata)))
13191 (org-in-regexp org-ts-regexp3)
13192 (setq ts (match-string 1))
13193 (setq time
13194 (save-match-data
13195 (org-time-string-to-time ts)))))
13196 (org-timestamp-change (- n) (cdr (assoc what whata)))
13197 ;; Rematch, so that we have everything in place
13198 ;; for the real shift.
13199 (org-in-regexp org-ts-regexp3)
13200 (setq ts (match-string 1))
13201 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13202 ts)))))
13203 (save-excursion
13204 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13205 (setq msg
13206 (concat
13207 msg type " " org-last-changed-timestamp " "))))))))
13208 (setq org-log-post-message msg)
13209 (message "%s" msg))
13210 (set-marker end nil))))
13212 (defun org-show-todo-tree (arg)
13213 "Make a compact tree which shows all headlines marked with TODO.
13214 The tree will show the lines where the regexp matches, and all higher
13215 headlines above the match.
13216 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13217 With a numeric prefix N, construct a sparse tree for the Nth element
13218 of `org-todo-keywords-1'."
13219 (interactive "P")
13220 (let ((case-fold-search nil)
13221 (kwd-re
13222 (cond ((null arg) org-not-done-regexp)
13223 ((equal arg '(4))
13224 (let ((kwd
13225 (completing-read "Keyword (or KWD1|KWD2|...): "
13226 (mapcar #'list org-todo-keywords-1))))
13227 (concat "\\("
13228 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13229 "\\)\\>")))
13230 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13231 (regexp-quote (nth (1- (prefix-numeric-value arg))
13232 org-todo-keywords-1)))
13233 (t (user-error "Invalid prefix argument: %s" arg)))))
13234 (message "%d TODO entries found"
13235 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13237 (defun org--deadline-or-schedule (arg type time)
13238 "Insert DEADLINE or SCHEDULE information in current entry.
13239 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13240 `org-schedule' for information about ARG and TIME arguments."
13241 (let* ((deadline? (eq type 'deadline))
13242 (keyword (if deadline? org-deadline-string org-scheduled-string))
13243 (log (if deadline? org-log-redeadline org-log-reschedule))
13244 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13245 (old-date-time (and old-date (org-time-string-to-time old-date)))
13246 ;; Save repeater cookie from either TIME or current scheduled
13247 ;; time stamp. We are going to insert it back at the end of
13248 ;; the process.
13249 (repeater (or (and (org-string-nw-p time)
13250 ;; We use `org-repeat-re' because we need
13251 ;; to tell the difference between a real
13252 ;; repeater and a time delta, e.g. "+2d".
13253 (string-match org-repeat-re time)
13254 (match-string 1 time))
13255 (and (org-string-nw-p old-date)
13256 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13257 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13258 old-date)
13259 (match-string 1 old-date)))))
13260 (pcase arg
13261 (`(4)
13262 (when (and old-date log)
13263 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13264 nil old-date log))
13265 (org-remove-timestamp-with-keyword keyword)
13266 (message (if deadline? "Item no longer has a deadline."
13267 "Item is no longer scheduled.")))
13268 (`(16)
13269 (save-excursion
13270 (org-back-to-heading t)
13271 (let ((regexp (if deadline? org-deadline-time-regexp
13272 org-scheduled-time-regexp)))
13273 (if (not (re-search-forward regexp (line-end-position 2) t))
13274 (user-error (if deadline? "No deadline information to update"
13275 "No scheduled information to update"))
13276 (let* ((rpl0 (match-string 1))
13277 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13278 (msg (if deadline? "Warn starting from" "Delay until")))
13279 (replace-match
13280 (concat keyword
13281 " <" rpl
13282 (format " -%dd"
13283 (abs (- (time-to-days
13284 (save-match-data
13285 (org-read-date
13286 nil t nil msg old-date-time)))
13287 (time-to-days old-date-time))))
13288 ">") t t))))))
13290 (org-add-planning-info type time 'closed)
13291 (when (and old-date
13293 (not (equal old-date org-last-inserted-timestamp)))
13294 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13295 org-last-inserted-timestamp
13296 old-date
13297 log))
13298 (when repeater
13299 (save-excursion
13300 (org-back-to-heading t)
13301 (when (re-search-forward
13302 (concat keyword " " org-last-inserted-timestamp)
13303 (line-end-position 2)
13305 (goto-char (1- (match-end 0)))
13306 (insert " " repeater)
13307 (setq org-last-inserted-timestamp
13308 (concat (substring org-last-inserted-timestamp 0 -1)
13309 " " repeater
13310 (substring org-last-inserted-timestamp -1))))))
13311 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13312 org-last-inserted-timestamp)))))
13314 (defun org-deadline (arg &optional time)
13315 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13316 With one universal prefix argument, remove any deadline from the item.
13317 With two universal prefix arguments, prompt for a warning delay.
13318 With argument TIME, set the deadline at the corresponding date. TIME
13319 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13320 (interactive "P")
13321 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13322 (org-map-entries
13323 (lambda () (org--deadline-or-schedule arg 'deadline time))
13325 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13326 'region-start-level
13327 'region)
13328 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13329 (org--deadline-or-schedule arg 'deadline time)))
13331 (defun org-schedule (arg &optional time)
13332 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13333 With one universal prefix argument, remove any scheduling date from the item.
13334 With two universal prefix arguments, prompt for a delay cookie.
13335 With argument TIME, scheduled at the corresponding date. TIME can
13336 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13337 (interactive "P")
13338 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13339 (org-map-entries
13340 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13342 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13343 'region-start-level
13344 'region)
13345 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13346 (org--deadline-or-schedule arg 'scheduled time)))
13348 (defun org-get-scheduled-time (pom &optional inherit)
13349 "Get the scheduled time as a time tuple, of a format suitable
13350 for calling org-schedule with, or if there is no scheduling,
13351 returns nil."
13352 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13353 (when time
13354 (apply 'encode-time (org-parse-time-string time)))))
13356 (defun org-get-deadline-time (pom &optional inherit)
13357 "Get the deadline as a time tuple, of a format suitable for
13358 calling org-deadline with, or if there is no scheduling, returns
13359 nil."
13360 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13361 (when time
13362 (apply 'encode-time (org-parse-time-string time)))))
13364 (defun org-remove-timestamp-with-keyword (keyword)
13365 "Remove all time stamps with KEYWORD in the current entry."
13366 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13367 beg)
13368 (save-excursion
13369 (org-back-to-heading t)
13370 (setq beg (point))
13371 (outline-next-heading)
13372 (while (re-search-backward re beg t)
13373 (replace-match "")
13374 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13375 (equal (char-before) ?\ ))
13376 (backward-delete-char 1)
13377 (when (string-match "^[ \t]*$" (buffer-substring
13378 (point-at-bol) (point-at-eol)))
13379 (delete-region (point-at-bol)
13380 (min (point-max) (1+ (point-at-eol))))))))))
13382 (defvar org-time-was-given) ; dynamically scoped parameter
13383 (defvar org-end-time-was-given) ; dynamically scoped parameter
13385 (defun org-at-planning-p ()
13386 "Non-nil when point is on a planning info line."
13387 ;; This is as accurate and faster than `org-element-at-point' since
13388 ;; planning info location is fixed in the section.
13389 (org-with-wide-buffer
13390 (beginning-of-line)
13391 (and (looking-at-p org-planning-line-re)
13392 (eq (point)
13393 (ignore-errors
13394 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13395 (org-back-to-heading t)
13396 (org-with-limited-levels (org-back-to-heading t)))
13397 (line-beginning-position 2))))))
13399 (defun org-add-planning-info (what &optional time &rest remove)
13400 "Insert new timestamp with keyword in the planning line.
13401 WHAT indicates what kind of time stamp to add. It is a symbol
13402 among `closed', `deadline', `scheduled' and nil. TIME indicates
13403 the time to use. If none is given, the user is prompted for
13404 a date. REMOVE indicates what kind of entries to remove. An old
13405 WHAT entry will also be removed."
13406 (let (org-time-was-given org-end-time-was-given default-time default-input)
13407 (catch 'exit
13408 (when (and (memq what '(scheduled deadline))
13409 (or (not time)
13410 (and (stringp time)
13411 (string-match "^[-+]+[0-9]" time))))
13412 ;; Try to get a default date/time from existing timestamp
13413 (save-excursion
13414 (org-back-to-heading t)
13415 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13416 (when (re-search-forward (if (eq what 'scheduled)
13417 org-scheduled-time-regexp
13418 org-deadline-time-regexp)
13419 end t)
13420 (setq ts (match-string 1)
13421 default-time (apply 'encode-time (org-parse-time-string ts))
13422 default-input (and ts (org-get-compact-tod ts)))))))
13423 (when what
13424 (setq time
13425 (if (stringp time)
13426 ;; This is a string (relative or absolute), set
13427 ;; proper date.
13428 (apply #'encode-time
13429 (org-read-date-analyze
13430 time default-time (decode-time default-time)))
13431 ;; If necessary, get the time from the user
13432 (or time (org-read-date nil 'to-time nil nil
13433 default-time default-input)))))
13435 (org-with-wide-buffer
13436 (org-back-to-heading t)
13437 (forward-line)
13438 (unless (bolp) (insert "\n"))
13439 (cond ((looking-at-p org-planning-line-re)
13440 ;; Move to current indentation.
13441 (skip-chars-forward " \t")
13442 ;; Check if we have to remove something.
13443 (dolist (type (if what (cons what remove) remove))
13444 (save-excursion
13445 (when (re-search-forward
13446 (cl-case type
13447 (closed org-closed-time-regexp)
13448 (deadline org-deadline-time-regexp)
13449 (scheduled org-scheduled-time-regexp)
13450 (otherwise
13451 (error "Invalid planning type: %s" type)))
13452 (line-end-position) t)
13453 ;; Delete until next keyword or end of line.
13454 (delete-region
13455 (match-beginning 0)
13456 (if (re-search-forward org-keyword-time-not-clock-regexp
13457 (line-end-position)
13459 (match-beginning 0)
13460 (line-end-position))))))
13461 ;; If there is nothing more to add and no more keyword
13462 ;; is left, remove the line completely.
13463 (if (and (looking-at-p "[ \t]*$") (not what))
13464 (delete-region (line-beginning-position)
13465 (line-beginning-position 2))
13466 ;; If we removed last keyword, do not leave trailing
13467 ;; white space at the end of line.
13468 (let ((p (point)))
13469 (save-excursion
13470 (end-of-line)
13471 (unless (= (skip-chars-backward " \t" p) 0)
13472 (delete-region (point) (line-end-position)))))))
13473 ((not what) (throw 'exit nil)) ; Nothing to do.
13474 (t (insert-before-markers "\n")
13475 (backward-char 1)
13476 (when org-adapt-indentation
13477 (indent-to-column (1+ (org-outline-level))))))
13478 (when what
13479 ;; Insert planning keyword.
13480 (insert (cl-case what
13481 (closed org-closed-string)
13482 (deadline org-deadline-string)
13483 (scheduled org-scheduled-string)
13484 (otherwise (error "Invalid planning type: %s" what)))
13485 " ")
13486 ;; Insert associated timestamp.
13487 (let ((ts (org-insert-time-stamp
13488 time
13489 (or org-time-was-given
13490 (and (eq what 'closed) org-log-done-with-time))
13491 (eq what 'closed)
13492 nil nil (list org-end-time-was-given))))
13493 (unless (eolp) (insert " "))
13494 ts))))))
13496 (defvar org-log-note-marker (make-marker)
13497 "Marker pointing at the entry where the note is to be inserted.")
13498 (defvar org-log-note-purpose nil)
13499 (defvar org-log-note-state nil)
13500 (defvar org-log-note-previous-state nil)
13501 (defvar org-log-note-extra nil)
13502 (defvar org-log-note-window-configuration nil)
13503 (defvar org-log-note-return-to (make-marker))
13504 (defvar org-log-note-effective-time nil
13505 "Remembered current time so that dynamically scoped
13506 `org-extend-today-until' affects timestamps in state change log")
13508 (defvar org-log-post-message nil
13509 "Message to be displayed after a log note has been stored.
13510 The auto-repeater uses this.")
13512 (defun org-add-note ()
13513 "Add a note to the current entry.
13514 This is done in the same way as adding a state change note."
13515 (interactive)
13516 (org-add-log-setup 'note))
13518 (defun org-log-beginning (&optional create)
13519 "Return expected start of log notes in current entry.
13520 When optional argument CREATE is non-nil, the function creates
13521 a drawer to store notes, if necessary. Returned position ignores
13522 narrowing."
13523 (org-with-wide-buffer
13524 (let ((drawer (org-log-into-drawer)))
13525 (cond
13526 (drawer
13527 (org-end-of-meta-data)
13528 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13529 (end (if (org-at-heading-p) (point)
13530 (save-excursion (outline-next-heading) (point))))
13531 (case-fold-search t))
13532 (catch 'exit
13533 ;; Try to find existing drawer.
13534 (while (re-search-forward regexp end t)
13535 (let ((element (org-element-at-point)))
13536 (when (eq (org-element-type element) 'drawer)
13537 (let ((cend (org-element-property :contents-end element)))
13538 (when (and (not org-log-states-order-reversed) cend)
13539 (goto-char cend)))
13540 (throw 'exit nil))))
13541 ;; No drawer found. Create one, if permitted.
13542 (when create
13543 (unless (bolp) (insert "\n"))
13544 (let ((beg (point)))
13545 (insert ":" drawer ":\n:END:\n")
13546 (org-indent-region beg (point)))
13547 (end-of-line -1)))))
13549 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13550 (skip-chars-forward " \t\n")
13551 (beginning-of-line)
13552 (unless org-log-states-order-reversed
13553 (org-skip-over-state-notes)
13554 (skip-chars-backward " \t\n")
13555 (forward-line)))))
13556 (if (bolp) (point) (line-beginning-position 2))))
13558 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13559 "Set up the post command hook to take a note.
13560 If this is about to TODO state change, the new state is expected in STATE.
13561 HOW is an indicator what kind of note should be created.
13562 EXTRA is additional text that will be inserted into the notes buffer."
13563 (move-marker org-log-note-marker (point))
13564 (setq org-log-note-purpose purpose
13565 org-log-note-state state
13566 org-log-note-previous-state prev-state
13567 org-log-note-how how
13568 org-log-note-extra extra
13569 org-log-note-effective-time (org-current-effective-time))
13570 (add-hook 'post-command-hook 'org-add-log-note 'append))
13572 (defun org-skip-over-state-notes ()
13573 "Skip past the list of State notes in an entry."
13574 (when (ignore-errors (goto-char (org-in-item-p)))
13575 (let* ((struct (org-list-struct))
13576 (prevs (org-list-prevs-alist struct))
13577 (regexp
13578 (concat "[ \t]*- +"
13579 (replace-regexp-in-string
13580 " +" " +"
13581 (org-replace-escapes
13582 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13583 `(("%d" . ,org-ts-regexp-inactive)
13584 ("%D" . ,org-ts-regexp)
13585 ("%s" . "\"\\S-+\"")
13586 ("%S" . "\"\\S-+\"")
13587 ("%t" . ,org-ts-regexp-inactive)
13588 ("%T" . ,org-ts-regexp)
13589 ("%u" . ".*?")
13590 ("%U" . ".*?")))))))
13591 (while (looking-at-p regexp)
13592 (goto-char (or (org-list-get-next-item (point) struct prevs)
13593 (org-list-get-item-end (point) struct)))))))
13595 (defun org-add-log-note (&optional _purpose)
13596 "Pop up a window for taking a note, and add this note later."
13597 (remove-hook 'post-command-hook 'org-add-log-note)
13598 (setq org-log-note-window-configuration (current-window-configuration))
13599 (delete-other-windows)
13600 (move-marker org-log-note-return-to (point))
13601 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13602 (goto-char org-log-note-marker)
13603 (org-switch-to-buffer-other-window "*Org Note*")
13604 (erase-buffer)
13605 (if (memq org-log-note-how '(time state))
13606 (let (current-prefix-arg) (org-store-log-note))
13607 (let ((org-inhibit-startup t)) (org-mode))
13608 (insert (format "# Insert note for %s.
13609 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13610 (cond
13611 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13612 ((eq org-log-note-purpose 'done) "closed todo item")
13613 ((eq org-log-note-purpose 'state)
13614 (format "state change from \"%s\" to \"%s\""
13615 (or org-log-note-previous-state "")
13616 (or org-log-note-state "")))
13617 ((eq org-log-note-purpose 'reschedule)
13618 "rescheduling")
13619 ((eq org-log-note-purpose 'delschedule)
13620 "no longer scheduled")
13621 ((eq org-log-note-purpose 'redeadline)
13622 "changing deadline")
13623 ((eq org-log-note-purpose 'deldeadline)
13624 "removing deadline")
13625 ((eq org-log-note-purpose 'refile)
13626 "refiling")
13627 ((eq org-log-note-purpose 'note)
13628 "this entry")
13629 (t (error "This should not happen")))))
13630 (when org-log-note-extra (insert org-log-note-extra))
13631 (setq-local org-finish-function 'org-store-log-note)
13632 (run-hooks 'org-log-buffer-setup-hook)))
13634 (defvar org-note-abort nil) ; dynamically scoped
13635 (defun org-store-log-note ()
13636 "Finish taking a log note, and insert it to where it belongs."
13637 (let ((txt (prog1 (buffer-string)
13638 (kill-buffer)))
13639 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13640 lines)
13641 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13642 (setq txt (replace-match "" t t txt)))
13643 (when (string-match "\\s-+\\'" txt)
13644 (setq txt (replace-match "" t t txt)))
13645 (setq lines (org-split-string txt "\n"))
13646 (when (org-string-nw-p note)
13647 (setq note
13648 (org-replace-escapes
13649 note
13650 (list (cons "%u" (user-login-name))
13651 (cons "%U" user-full-name)
13652 (cons "%t" (format-time-string
13653 (org-time-stamp-format 'long 'inactive)
13654 org-log-note-effective-time))
13655 (cons "%T" (format-time-string
13656 (org-time-stamp-format 'long nil)
13657 org-log-note-effective-time))
13658 (cons "%d" (format-time-string
13659 (org-time-stamp-format nil 'inactive)
13660 org-log-note-effective-time))
13661 (cons "%D" (format-time-string
13662 (org-time-stamp-format nil nil)
13663 org-log-note-effective-time))
13664 (cons "%s" (cond
13665 ((not org-log-note-state) "")
13666 ((string-match-p org-ts-regexp
13667 org-log-note-state)
13668 (format "\"[%s]\""
13669 (substring org-log-note-state 1 -1)))
13670 (t (format "\"%s\"" org-log-note-state))))
13671 (cons "%S"
13672 (cond
13673 ((not org-log-note-previous-state) "")
13674 ((string-match-p org-ts-regexp
13675 org-log-note-previous-state)
13676 (format "\"[%s]\""
13677 (substring
13678 org-log-note-previous-state 1 -1)))
13679 (t (format "\"%s\""
13680 org-log-note-previous-state)))))))
13681 (when lines (setq note (concat note " \\\\")))
13682 (push note lines))
13683 (when (and lines (not (or current-prefix-arg org-note-abort)))
13684 (with-current-buffer (marker-buffer org-log-note-marker)
13685 (org-with-wide-buffer
13686 ;; Find location for the new note.
13687 (goto-char org-log-note-marker)
13688 (set-marker org-log-note-marker nil)
13689 ;; Note associated to a clock is to be located right after
13690 ;; the clock. Do not move point.
13691 (unless (eq org-log-note-purpose 'clock-out)
13692 (goto-char (org-log-beginning t)))
13693 ;; Make sure point is at the beginning of an empty line.
13694 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13695 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13696 ;; In an existing list, add a new item at the top level.
13697 ;; Otherwise, indent line like a regular one.
13698 (let ((itemp (org-in-item-p)))
13699 (if itemp
13700 (indent-line-to
13701 (let ((struct (save-excursion
13702 (goto-char itemp) (org-list-struct))))
13703 (org-list-get-ind (org-list-get-top-point struct) struct)))
13704 (org-indent-line)))
13705 (insert (org-list-bullet-string "-") (pop lines))
13706 (let ((ind (org-list-item-body-column (line-beginning-position))))
13707 (dolist (line lines)
13708 (insert "\n")
13709 (indent-line-to ind)
13710 (insert line)))
13711 (message "Note stored")
13712 (org-back-to-heading t)
13713 (org-cycle-hide-drawers 'children))
13714 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13715 ;; from within `org-add-log-note' because `buffer-undo-list'
13716 ;; is then modified outside of `org-with-remote-undo'.
13717 (when (eq this-command 'org-agenda-todo)
13718 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13719 ;; Don't add undo information when called from `org-agenda-todo'.
13720 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13721 (set-window-configuration org-log-note-window-configuration)
13722 (with-current-buffer (marker-buffer org-log-note-return-to)
13723 (goto-char org-log-note-return-to))
13724 (move-marker org-log-note-return-to nil)
13725 (when org-log-post-message (message "%s" org-log-post-message))))
13727 (defun org-remove-empty-drawer-at (pos)
13728 "Remove an empty drawer at position POS.
13729 POS may also be a marker."
13730 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13731 (org-with-wide-buffer
13732 (goto-char pos)
13733 (let ((drawer (org-element-at-point)))
13734 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13735 (not (org-element-property :contents-begin drawer)))
13736 (delete-region (org-element-property :begin drawer)
13737 (progn (goto-char (org-element-property :end drawer))
13738 (skip-chars-backward " \r\t\n")
13739 (forward-line)
13740 (point))))))))
13742 (defvar org-ts-type nil)
13743 (defun org-sparse-tree (&optional arg type)
13744 "Create a sparse tree, prompt for the details.
13745 This command can create sparse trees. You first need to select the type
13746 of match used to create the tree:
13748 t Show all TODO entries.
13749 T Show entries with a specific TODO keyword.
13750 m Show entries selected by a tags/property match.
13751 p Enter a property name and its value (both with completion on existing
13752 names/values) and show entries with that property.
13753 r Show entries matching a regular expression (`/' can be used as well).
13754 b Show deadlines and scheduled items before a date.
13755 a Show deadlines and scheduled items after a date.
13756 d Show deadlines due within `org-deadline-warning-days'.
13757 D Show deadlines and scheduled items between a date range."
13758 (interactive "P")
13759 (setq type (or type org-sparse-tree-default-date-type))
13760 (setq org-ts-type type)
13761 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13762 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13763 \[c]ycle through date types: %s"
13764 (cl-case type
13765 (all "all timestamps")
13766 (scheduled "only scheduled")
13767 (deadline "only deadline")
13768 (active "only active timestamps")
13769 (inactive "only inactive timestamps")
13770 (closed "with a closed time-stamp")
13771 (otherwise "scheduled/deadline")))
13772 (let ((answer (read-char-exclusive)))
13773 (cl-case answer
13775 (org-sparse-tree
13777 (cadr
13778 (memq type '(nil all scheduled deadline active inactive closed)))))
13779 (?d (call-interactively 'org-check-deadlines))
13780 (?b (call-interactively 'org-check-before-date))
13781 (?a (call-interactively 'org-check-after-date))
13782 (?D (call-interactively 'org-check-dates-range))
13783 (?t (call-interactively 'org-show-todo-tree))
13784 (?T (org-show-todo-tree '(4)))
13785 (?m (call-interactively 'org-match-sparse-tree))
13786 ((?p ?P)
13787 (let* ((kwd (completing-read
13788 "Property: " (mapcar #'list (org-buffer-property-keys))))
13789 (value (completing-read
13790 "Value: " (mapcar #'list (org-property-values kwd)))))
13791 (unless (string-match "\\`{.*}\\'" value)
13792 (setq value (concat "\"" value "\"")))
13793 (org-match-sparse-tree arg (concat kwd "=" value))))
13794 ((?r ?R ?/) (call-interactively 'org-occur))
13795 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13797 (defvar-local org-occur-highlights nil
13798 "List of overlays used for occur matches.")
13799 (defvar-local org-occur-parameters nil
13800 "Parameters of the active org-occur calls.
13801 This is a list, each call to org-occur pushes as cons cell,
13802 containing the regular expression and the callback, onto the list.
13803 The list can contain several entries if `org-occur' has been called
13804 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13805 will only contain one set of parameters. When the highlights are
13806 removed (for example with `C-c C-c', or with the next edit (depending
13807 on `org-remove-highlights-with-change'), this variable is emptied
13808 as well.")
13810 (defun org-occur (regexp &optional keep-previous callback)
13811 "Make a compact tree which shows all matches of REGEXP.
13813 The tree will show the lines where the regexp matches, and any other context
13814 defined in `org-show-context-detail', which see.
13816 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13817 done by a previous call to `org-occur' will be kept, to allow stacking of
13818 calls to this command.
13820 Optional argument CALLBACK can be a function of no argument. In this case,
13821 it is called with point at the end of the match, match data being set
13822 accordingly. Current match is shown only if the return value is non-nil.
13823 The function must neither move point nor alter narrowing."
13824 (interactive "sRegexp: \nP")
13825 (when (equal regexp "")
13826 (user-error "Regexp cannot be empty"))
13827 (unless keep-previous
13828 (org-remove-occur-highlights nil nil t))
13829 (push (cons regexp callback) org-occur-parameters)
13830 (let ((cnt 0))
13831 (save-excursion
13832 (goto-char (point-min))
13833 (when (or (not keep-previous) ; do not want to keep
13834 (not org-occur-highlights)) ; no previous matches
13835 ;; hide everything
13836 (org-overview))
13837 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13838 (isearch-no-upper-case-p regexp t)
13839 org-occur-case-fold-search)))
13840 (while (re-search-forward regexp nil t)
13841 (when (or (not callback)
13842 (save-match-data (funcall callback)))
13843 (setq cnt (1+ cnt))
13844 (when org-highlight-sparse-tree-matches
13845 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13846 (org-show-context 'occur-tree)))))
13847 (when org-remove-highlights-with-change
13848 (add-hook 'before-change-functions 'org-remove-occur-highlights
13849 nil 'local))
13850 (unless org-sparse-tree-open-archived-trees
13851 (org-hide-archived-subtrees (point-min) (point-max)))
13852 (run-hooks 'org-occur-hook)
13853 (when (called-interactively-p 'interactive)
13854 (message "%d match(es) for regexp %s" cnt regexp))
13855 cnt))
13857 (defun org-occur-next-match (&optional n _reset)
13858 "Function for `next-error-function' to find sparse tree matches.
13859 N is the number of matches to move, when negative move backwards.
13860 This function always goes back to the starting point when no
13861 match is found."
13862 (let* ((limit (if (< n 0) (point-min) (point-max)))
13863 (search-func (if (< n 0)
13864 'previous-single-char-property-change
13865 'next-single-char-property-change))
13866 (n (abs n))
13867 (pos (point))
13869 (catch 'exit
13870 (while (setq p1 (funcall search-func (point) 'org-type))
13871 (when (equal p1 limit)
13872 (goto-char pos)
13873 (user-error "No more matches"))
13874 (when (equal (get-char-property p1 'org-type) 'org-occur)
13875 (setq n (1- n))
13876 (when (= n 0)
13877 (goto-char p1)
13878 (throw 'exit (point))))
13879 (goto-char p1))
13880 (goto-char p1)
13881 (user-error "No more matches"))))
13883 (defun org-show-context (&optional key)
13884 "Make sure point and context are visible.
13885 Optional argument KEY, when non-nil, is a symbol. See
13886 `org-show-context-detail' for allowed values and how much is to
13887 be shown."
13888 (org-show-set-visibility
13889 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13890 ((cdr (assq key org-show-context-detail)))
13891 (t (cdr (assq 'default org-show-context-detail))))))
13893 (defun org-show-set-visibility (detail)
13894 "Set visibility around point according to DETAIL.
13895 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13896 `tree', `canonical' or t. See `org-show-context-detail' for more
13897 information."
13898 ;; Show current heading and possibly its entry, following headline
13899 ;; or all children.
13900 (if (and (org-at-heading-p) (not (eq detail 'local)))
13901 (org-flag-heading nil)
13902 (org-show-entry)
13903 ;; If point is hidden within a drawer or a block, make sure to
13904 ;; expose it.
13905 (dolist (o (overlays-at (point)))
13906 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13907 (delete-overlay o)))
13908 (unless (org-before-first-heading-p)
13909 (org-with-limited-levels
13910 (cl-case detail
13911 ((tree canonical t) (org-show-children))
13912 ((nil minimal ancestors))
13913 (t (save-excursion
13914 (outline-next-heading)
13915 (org-flag-heading nil)))))))
13916 ;; Show all siblings.
13917 (when (eq detail 'lineage) (org-show-siblings))
13918 ;; Show ancestors, possibly with their children.
13919 (when (memq detail '(ancestors lineage tree canonical t))
13920 (save-excursion
13921 (while (org-up-heading-safe)
13922 (org-flag-heading nil)
13923 (when (memq detail '(canonical t)) (org-show-entry))
13924 (when (memq detail '(tree canonical t)) (org-show-children))))))
13926 (defvar org-reveal-start-hook nil
13927 "Hook run before revealing a location.")
13929 (defun org-reveal (&optional siblings)
13930 "Show current entry, hierarchy above it, and the following headline.
13932 This can be used to show a consistent set of context around
13933 locations exposed with `org-show-context'.
13935 With optional argument SIBLINGS, on each level of the hierarchy all
13936 siblings are shown. This repairs the tree structure to what it would
13937 look like when opened with hierarchical calls to `org-cycle'.
13939 With a \\[universal-argument] \\[universal-argument] prefix, \
13940 go to the parent and show the entire tree."
13941 (interactive "P")
13942 (run-hooks 'org-reveal-start-hook)
13943 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13944 ((equal siblings '(16))
13945 (save-excursion
13946 (when (org-up-heading-safe)
13947 (org-show-subtree)
13948 (run-hook-with-args 'org-cycle-hook 'subtree))))
13949 (t (org-show-set-visibility 'lineage))))
13951 (defun org-highlight-new-match (beg end)
13952 "Highlight from BEG to END and mark the highlight is an occur headline."
13953 (let ((ov (make-overlay beg end)))
13954 (overlay-put ov 'face 'secondary-selection)
13955 (overlay-put ov 'org-type 'org-occur)
13956 (push ov org-occur-highlights)))
13958 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13959 "Remove the occur highlights from the buffer.
13960 BEG and END are ignored. If NOREMOVE is nil, remove this function
13961 from the `before-change-functions' in the current buffer."
13962 (interactive)
13963 (unless org-inhibit-highlight-removal
13964 (mapc #'delete-overlay org-occur-highlights)
13965 (setq org-occur-highlights nil)
13966 (setq org-occur-parameters nil)
13967 (unless noremove
13968 (remove-hook 'before-change-functions
13969 'org-remove-occur-highlights 'local))))
13971 ;;;; Priorities
13973 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13974 "Regular expression matching the priority indicator.")
13976 (defvar org-remove-priority-next-time nil)
13978 (defun org-priority-up ()
13979 "Increase the priority of the current item."
13980 (interactive)
13981 (org-priority 'up))
13983 (defun org-priority-down ()
13984 "Decrease the priority of the current item."
13985 (interactive)
13986 (org-priority 'down))
13988 (defun org-priority (&optional action _show)
13989 "Change the priority of an item.
13990 ACTION can be `set', `up', `down', or a character."
13991 (interactive "P")
13992 (if (equal action '(4))
13993 (org-show-priority)
13994 (unless org-enable-priority-commands
13995 (user-error "Priority commands are disabled"))
13996 (setq action (or action 'set))
13997 (let (current new news have remove)
13998 (save-excursion
13999 (org-back-to-heading t)
14000 (when (looking-at org-priority-regexp)
14001 (setq current (string-to-char (match-string 2))
14002 have t))
14003 (cond
14004 ((eq action 'remove)
14005 (setq remove t new ?\ ))
14006 ((or (eq action 'set)
14007 (integerp action))
14008 (if (not (eq action 'set))
14009 (setq new action)
14010 (message "Priority %c-%c, SPC to remove: "
14011 org-highest-priority org-lowest-priority)
14012 (save-match-data
14013 (setq new (read-char-exclusive))))
14014 (when (and (= (upcase org-highest-priority) org-highest-priority)
14015 (= (upcase org-lowest-priority) org-lowest-priority))
14016 (setq new (upcase new)))
14017 (cond ((equal new ?\ ) (setq remove t))
14018 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14019 (user-error "Priority must be between `%c' and `%c'"
14020 org-highest-priority org-lowest-priority))))
14021 ((eq action 'up)
14022 (setq new (if have
14023 (1- current) ; normal cycling
14024 ;; last priority was empty
14025 (if (eq last-command this-command)
14026 org-lowest-priority ; wrap around empty to lowest
14027 ;; default
14028 (if org-priority-start-cycle-with-default
14029 org-default-priority
14030 (1- org-default-priority))))))
14031 ((eq action 'down)
14032 (setq new (if have
14033 (1+ current) ; normal cycling
14034 ;; last priority was empty
14035 (if (eq last-command this-command)
14036 org-highest-priority ; wrap around empty to highest
14037 ;; default
14038 (if org-priority-start-cycle-with-default
14039 org-default-priority
14040 (1+ org-default-priority))))))
14041 (t (user-error "Invalid action")))
14042 (when (or (< (upcase new) org-highest-priority)
14043 (> (upcase new) org-lowest-priority))
14044 (if (and (memq action '(up down))
14045 (not have) (not (eq last-command this-command)))
14046 ;; `new' is from default priority
14047 (error
14048 "The default can not be set, see `org-default-priority' why")
14049 ;; normal cycling: `new' is beyond highest/lowest priority
14050 ;; and is wrapped around to the empty priority
14051 (setq remove t)))
14052 (setq news (format "%c" new))
14053 (if have
14054 (if remove
14055 (replace-match "" t t nil 1)
14056 (replace-match news t t nil 2))
14057 (if remove
14058 (user-error "No priority cookie found in line")
14059 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14060 (if (match-end 2)
14061 (progn
14062 (goto-char (match-end 2))
14063 (insert " [#" news "]"))
14064 (goto-char (match-beginning 3))
14065 (insert "[#" news "] "))))
14066 (org-set-tags nil 'align))
14067 (if remove
14068 (message "Priority removed")
14069 (message "Priority of current item set to %s" news)))))
14071 (defun org-show-priority ()
14072 "Show the priority of the current item.
14073 This priority is composed of the main priority given with the [#A] cookies,
14074 and by additional input from the age of a schedules or deadline entry."
14075 (interactive)
14076 (let ((pri (if (eq major-mode 'org-agenda-mode)
14077 (org-get-at-bol 'priority)
14078 (save-excursion
14079 (save-match-data
14080 (beginning-of-line)
14081 (and (looking-at org-heading-regexp)
14082 (org-get-priority (match-string 0))))))))
14083 (message "Priority is %d" (if pri pri -1000))))
14085 (defun org-get-priority (s)
14086 "Find priority cookie and return priority."
14087 (save-match-data
14088 (if (functionp org-get-priority-function)
14089 (funcall org-get-priority-function)
14090 (if (not (string-match org-priority-regexp s))
14091 (* 1000 (- org-lowest-priority org-default-priority))
14092 (* 1000 (- org-lowest-priority
14093 (string-to-char (match-string 2 s))))))))
14095 ;;;; Tags
14097 (defvar org-agenda-archives-mode)
14098 (defvar org-map-continue-from nil
14099 "Position from where mapping should continue.
14100 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14102 (defvar org-scanner-tags nil
14103 "The current tag list while the tags scanner is running.")
14105 (defvar org-trust-scanner-tags nil
14106 "Should `org-get-tags-at' use the tags for the scanner.
14107 This is for internal dynamical scoping only.
14108 When this is non-nil, the function `org-get-tags-at' will return the value
14109 of `org-scanner-tags' instead of building the list by itself. This
14110 can lead to large speed-ups when the tags scanner is used in a file with
14111 many entries, and when the list of tags is retrieved, for example to
14112 obtain a list of properties. Building the tags list for each entry in such
14113 a file becomes an N^2 operation - but with this variable set, it scales
14114 as N.")
14116 (defvar org--matcher-tags-todo-only nil)
14118 (defun org-scan-tags (action matcher todo-only &optional start-level)
14119 "Scan headline tags with inheritance and produce output ACTION.
14121 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14122 or `agenda' to produce an entry list for an agenda view. It can also be
14123 a Lisp form or a function that should be called at each matched headline, in
14124 this case the return value is a list of all return values from these calls.
14126 MATCHER is a function accepting three arguments, returning
14127 a non-nil value whenever a given set of tags qualifies a headline
14128 for inclusion. See `org-make-tags-matcher' for more information.
14129 As a special case, it can also be set to t (respectively nil) in
14130 order to match all (respectively none) headline.
14132 When TODO-ONLY is non-nil, only lines with a not-done TODO
14133 keyword are included in the output.
14135 START-LEVEL can be a string with asterisks, reducing the scope to
14136 headlines matching this string."
14137 (require 'org-agenda)
14138 (let* ((re (concat "^"
14139 (if start-level
14140 ;; Get the correct level to match
14141 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14142 org-outline-regexp)
14143 " *\\(\\<\\("
14144 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14145 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14146 (props (list 'face 'default
14147 'done-face 'org-agenda-done
14148 'undone-face 'default
14149 'mouse-face 'highlight
14150 'org-not-done-regexp org-not-done-regexp
14151 'org-todo-regexp org-todo-regexp
14152 'org-complex-heading-regexp org-complex-heading-regexp
14153 'help-echo
14154 (format "mouse-2 or RET jump to org file %s"
14155 (abbreviate-file-name
14156 (or (buffer-file-name (buffer-base-buffer))
14157 (buffer-name (buffer-base-buffer)))))))
14158 (org-map-continue-from nil)
14159 lspos tags tags-list
14160 (tags-alist (list (cons 0 org-file-tags)))
14161 (llast 0) rtn rtn1 level category i txt
14162 todo marker entry priority
14163 ts-date ts-date-type ts-date-pair)
14164 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14165 (setq action (list 'lambda nil action)))
14166 (save-excursion
14167 (goto-char (point-min))
14168 (when (eq action 'sparse-tree)
14169 (org-overview)
14170 (org-remove-occur-highlights))
14171 (while (let (case-fold-search)
14172 (re-search-forward re nil t))
14173 (setq org-map-continue-from nil)
14174 (catch :skip
14175 (setq todo
14176 ;; TODO: is the 1-2 difference a bug?
14177 (when (match-end 1) (match-string-no-properties 2))
14178 tags (when (match-end 4) (match-string-no-properties 4)))
14179 (goto-char (setq lspos (match-beginning 0)))
14180 (setq level (org-reduced-level (org-outline-level))
14181 category (org-get-category))
14182 (when (eq action 'agenda)
14183 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14184 ts-date (car ts-date-pair)
14185 ts-date-type (cdr ts-date-pair)))
14186 (setq i llast llast level)
14187 ;; remove tag lists from same and sublevels
14188 (while (>= i level)
14189 (when (setq entry (assoc i tags-alist))
14190 (setq tags-alist (delete entry tags-alist)))
14191 (setq i (1- i)))
14192 ;; add the next tags
14193 (when tags
14194 (setq tags (org-split-string tags ":")
14195 tags-alist
14196 (cons (cons level tags) tags-alist)))
14197 ;; compile tags for current headline
14198 (setq tags-list
14199 (if org-use-tag-inheritance
14200 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14201 tags)
14202 org-scanner-tags tags-list)
14203 (when org-use-tag-inheritance
14204 (setcdr (car tags-alist)
14205 (mapcar (lambda (x)
14206 (setq x (copy-sequence x))
14207 (org-add-prop-inherited x))
14208 (cdar tags-alist))))
14209 (when (and tags org-use-tag-inheritance
14210 (or (not (eq t org-use-tag-inheritance))
14211 org-tags-exclude-from-inheritance))
14212 ;; Selective inheritance, remove uninherited ones.
14213 (setcdr (car tags-alist)
14214 (org-remove-uninherited-tags (cdar tags-alist))))
14215 (when (and
14217 ;; eval matcher only when the todo condition is OK
14218 (and (or (not todo-only) (member todo org-not-done-keywords))
14219 (if (functionp matcher)
14220 (let ((case-fold-search t) (org-trust-scanner-tags t))
14221 (funcall matcher todo tags-list level))
14222 matcher))
14224 ;; Call the skipper, but return t if it does not
14225 ;; skip, so that the `and' form continues evaluating.
14226 (progn
14227 (unless (eq action 'sparse-tree) (org-agenda-skip))
14230 ;; Check if timestamps are deselecting this entry
14231 (or (not todo-only)
14232 (and (member todo org-not-done-keywords)
14233 (or (not org-agenda-tags-todo-honor-ignore-options)
14234 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14236 ;; select this headline
14237 (cond
14238 ((eq action 'sparse-tree)
14239 (and org-highlight-sparse-tree-matches
14240 (org-get-heading) (match-end 0)
14241 (org-highlight-new-match
14242 (match-beginning 1) (match-end 1)))
14243 (org-show-context 'tags-tree))
14244 ((eq action 'agenda)
14245 (setq txt (org-agenda-format-item
14247 (concat
14248 (if (eq org-tags-match-list-sublevels 'indented)
14249 (make-string (1- level) ?.) "")
14250 (org-get-heading))
14251 (make-string level ?\s)
14252 category
14253 tags-list)
14254 priority (org-get-priority txt))
14255 (goto-char lspos)
14256 (setq marker (org-agenda-new-marker))
14257 (org-add-props txt props
14258 'org-marker marker 'org-hd-marker marker 'org-category category
14259 'todo-state todo
14260 'ts-date ts-date
14261 'priority priority
14262 'type (concat "tagsmatch" ts-date-type))
14263 (push txt rtn))
14264 ((functionp action)
14265 (setq org-map-continue-from nil)
14266 (save-excursion
14267 (setq rtn1 (funcall action))
14268 (push rtn1 rtn)))
14269 (t (user-error "Invalid action")))
14271 ;; if we are to skip sublevels, jump to end of subtree
14272 (unless org-tags-match-list-sublevels
14273 (org-end-of-subtree t)
14274 (backward-char 1))))
14275 ;; Get the correct position from where to continue
14276 (if org-map-continue-from
14277 (goto-char org-map-continue-from)
14278 (and (= (point) lspos) (end-of-line 1)))))
14279 (when (and (eq action 'sparse-tree)
14280 (not org-sparse-tree-open-archived-trees))
14281 (org-hide-archived-subtrees (point-min) (point-max)))
14282 (nreverse rtn)))
14284 (defun org-remove-uninherited-tags (tags)
14285 "Remove all tags that are not inherited from the list TAGS."
14286 (cond
14287 ((eq org-use-tag-inheritance t)
14288 (if org-tags-exclude-from-inheritance
14289 (org-delete-all org-tags-exclude-from-inheritance tags)
14290 tags))
14291 ((not org-use-tag-inheritance) nil)
14292 ((stringp org-use-tag-inheritance)
14293 (delq nil (mapcar
14294 (lambda (x)
14295 (if (and (string-match org-use-tag-inheritance x)
14296 (not (member x org-tags-exclude-from-inheritance)))
14297 x nil))
14298 tags)))
14299 ((listp org-use-tag-inheritance)
14300 (delq nil (mapcar
14301 (lambda (x)
14302 (if (member x org-use-tag-inheritance) x nil))
14303 tags)))))
14305 (defun org-match-sparse-tree (&optional todo-only match)
14306 "Create a sparse tree according to tags string MATCH.
14308 MATCH is a string with match syntax. It can contain a selection
14309 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14310 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14311 those. See the manual for details.
14313 If optional argument TODO-ONLY is non-nil, only select lines that
14314 are also TODO tasks."
14315 (interactive "P")
14316 (org-agenda-prepare-buffers (list (current-buffer)))
14317 (let ((org--matcher-tags-todo-only todo-only))
14318 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14319 org--matcher-tags-todo-only)))
14321 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14323 (defvar org-cached-props nil)
14324 (defun org-cached-entry-get (pom property)
14325 (if (or (eq t org-use-property-inheritance)
14326 (and (stringp org-use-property-inheritance)
14327 (let ((case-fold-search t))
14328 (string-match-p org-use-property-inheritance property)))
14329 (and (listp org-use-property-inheritance)
14330 (member-ignore-case property org-use-property-inheritance)))
14331 ;; Caching is not possible, check it directly.
14332 (org-entry-get pom property 'inherit)
14333 ;; Get all properties, so we can do complicated checks easily.
14334 (cdr (assoc-string property
14335 (or org-cached-props
14336 (setq org-cached-props (org-entry-properties pom)))
14337 t))))
14339 (defun org-global-tags-completion-table (&optional files)
14340 "Return the list of all tags in all agenda buffer/files.
14341 Optional FILES argument is a list of files which can be used
14342 instead of the agenda files."
14343 (save-excursion
14344 (org-uniquify
14345 (delq nil
14346 (apply #'append
14347 (mapcar
14348 (lambda (file)
14349 (set-buffer (find-file-noselect file))
14350 (mapcar (lambda (x)
14351 (and (stringp (car-safe x))
14352 (list (car-safe x))))
14353 (or org-current-tag-alist (org-get-buffer-tags))))
14354 (if (car-safe files) files
14355 (org-agenda-files))))))))
14357 (defun org-make-tags-matcher (match)
14358 "Create the TAGS/TODO matcher form for the selection string MATCH.
14360 Returns a cons of the selection string MATCH and a function
14361 implementing the matcher.
14363 The matcher is to be called at an Org entry, with point on the
14364 headline, and returns non-nil if the entry matches the selection
14365 string MATCH. It must be called with three arguments: the TODO
14366 keyword at the entry (or nil if none), the list of all tags at
14367 the entry including inherited ones and the reduced level of the
14368 headline. Additionally, the category of the entry, if any, must
14369 be specified as the text property `org-category' on the headline.
14371 This function sets the variable `org--matcher-tags-todo-only' to
14372 a non-nil value if the matcher restricts matching to TODO
14373 entries, otherwise it is not touched.
14375 See also `org-scan-tags'."
14376 (unless match
14377 ;; Get a new match request, with completion against the global
14378 ;; tags table and the local tags in current buffer.
14379 (let ((org-last-tags-completion-table
14380 (org-uniquify
14381 (delq nil (append (org-get-buffer-tags)
14382 (org-global-tags-completion-table))))))
14383 (setq match
14384 (completing-read
14385 "Match: "
14386 'org-tags-completion-function nil nil nil 'org-tags-history))))
14388 (let ((match0 match)
14389 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14390 (start 0)
14391 tagsmatch todomatch tagsmatcher todomatcher)
14393 ;; Expand group tags.
14394 (setq match (org-tags-expand match))
14396 ;; Check if there is a TODO part of this match, which would be the
14397 ;; part after a "/". To make sure that this slash is not part of
14398 ;; a property value to be matched against, we also check that
14399 ;; there is no / after that slash. First, find the last slash.
14400 (let ((s 0))
14401 (while (string-match "/+" match s)
14402 (setq start (match-beginning 0))
14403 (setq s (match-end 0))))
14404 (if (and (string-match "/+" match start)
14405 (not (string-match-p "\"" match start)))
14406 ;; Match contains also a TODO-matching request.
14407 (progn
14408 (setq tagsmatch (substring match 0 (match-beginning 0)))
14409 (setq todomatch (substring match (match-end 0)))
14410 (when (string-prefix-p "!" todomatch)
14411 (setq org--matcher-tags-todo-only t)
14412 (setq todomatch (substring todomatch 1)))
14413 (when (string-match "\\`\\s-*\\'" todomatch)
14414 (setq todomatch nil)))
14415 ;; Only matching tags.
14416 (setq tagsmatch match)
14417 (setq todomatch nil))
14419 ;; Make the tags matcher.
14420 (when (org-string-nw-p tagsmatch)
14421 (let ((orlist nil)
14422 (orterms (org-split-string tagsmatch "|"))
14423 term)
14424 (while (setq term (pop orterms))
14425 (while (and (equal (substring term -1) "\\") orterms)
14426 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14427 (while (string-match re term)
14428 (let* ((rest (substring term (match-end 0)))
14429 (minus (and (match-end 1)
14430 (equal (match-string 1 term) "-")))
14431 (tag (save-match-data
14432 (replace-regexp-in-string
14433 "\\\\-" "-" (match-string 2 term))))
14434 (regexp (eq (string-to-char tag) ?{))
14435 (levelp (match-end 4))
14436 (propp (match-end 5))
14438 (cond
14439 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14440 (levelp
14441 `(,(org-op-to-function (match-string 3 term))
14442 level
14443 ,(string-to-number (match-string 4 term))))
14444 (propp
14445 (let* ((gv (pcase (upcase (match-string 5 term))
14446 ("CATEGORY"
14447 '(get-text-property (point) 'org-category))
14448 ("TODO" 'todo)
14449 (p `(org-cached-entry-get nil ,p))))
14450 (pv (match-string 7 term))
14451 (regexp (eq (string-to-char pv) ?{))
14452 (strp (eq (string-to-char pv) ?\"))
14453 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14454 (po (org-op-to-function (match-string 6 term)
14455 (if timep 'time strp))))
14456 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14457 (when timep (setq pv (org-matcher-time pv)))
14458 (cond ((and regexp (eq po 'org<>))
14459 `(not (string-match ,pv (or ,gv ""))))
14460 (regexp `(string-match ,pv (or ,gv "")))
14461 (strp `(,po (or ,gv "") ,pv))
14463 `(,po
14464 (string-to-number (or ,gv ""))
14465 ,(string-to-number pv))))))
14466 (t `(member ,tag tags-list)))))
14467 (push (if minus `(not ,mm) mm) tagsmatcher)
14468 (setq term rest)))
14469 (push `(and ,@tagsmatcher) orlist)
14470 (setq tagsmatcher nil))
14471 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14473 ;; Make the TODO matcher.
14474 (when (org-string-nw-p todomatch)
14475 (let ((orlist nil))
14476 (dolist (term (org-split-string todomatch "|"))
14477 (while (string-match re term)
14478 (let* ((minus (and (match-end 1)
14479 (equal (match-string 1 term) "-")))
14480 (kwd (match-string 2 term))
14481 (regexp (eq (string-to-char kwd) ?{))
14482 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14483 `(equal todo ,kwd))))
14484 (push (if minus `(not ,mm) mm) todomatcher))
14485 (setq term (substring term (match-end 0))))
14486 (push (if (> (length todomatcher) 1)
14487 (cons 'and todomatcher)
14488 (car todomatcher))
14489 orlist)
14490 (setq todomatcher nil))
14491 (setq todomatcher (cons 'or orlist))))
14493 ;; Return the string and function of the matcher. If no
14494 ;; tags-specific or todo-specific matcher exists, match
14495 ;; everything.
14496 (let ((matcher (if (and tagsmatcher todomatcher)
14497 `(and ,tagsmatcher ,todomatcher)
14498 (or tagsmatcher todomatcher t))))
14499 (when org--matcher-tags-todo-only
14500 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14501 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14503 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14504 "Expand group tags in MATCH.
14506 This replaces every group tag in MATCH with a regexp tag search.
14507 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14508 will be replaced like this:
14510 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14511 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14512 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14514 Replacing by a regexp preserves the structure of the match.
14515 E.g., this expansion
14517 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14519 will match anything tagged with \"Lab\" and \"Home\", or tagged
14520 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14522 A group tag in MATCH can contain regular expressions of its own.
14523 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14524 will be replaced like this:
14526 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14528 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14529 assumed to be a single group tag, and the function will return
14530 the list of tags in this group.
14532 When DOWNCASE is non-nil, expand downcased TAGS."
14533 (if org-group-tags
14534 (let* ((case-fold-search t)
14535 (stable org-mode-syntax-table)
14536 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14537 (taggroups (if downcased
14538 (mapcar (lambda (tg) (mapcar #'downcase tg))
14539 taggroups)
14540 taggroups))
14541 (taggroups-keys (mapcar #'car taggroups))
14542 (return-match (if downcased (downcase match) match))
14543 (count 0)
14544 (work-already-expanded tags-already-expanded)
14545 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14546 ;; @ and _ are allowed as word-components in tags.
14547 (modify-syntax-entry ?@ "w" stable)
14548 (modify-syntax-entry ?_ "w" stable)
14549 ;; Temporarily replace regexp-expressions in the match-expression.
14550 (while (string-match "{.+?}" return-match)
14551 (cl-incf count)
14552 (push (match-string 0 return-match) regexps-in-match)
14553 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14554 (while (and taggroups-keys
14555 (with-syntax-table stable
14556 (string-match
14557 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14558 (regexp-opt taggroups-keys) "\\>\\)")
14559 return-match)))
14560 (let* ((dir (match-string 1 return-match))
14561 (tag (match-string 2 return-match))
14562 (tag (if downcased (downcase tag) tag)))
14563 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14564 (member tag work-already-expanded))
14565 (setq tags-in-group (assoc tag taggroups))
14566 (push tag work-already-expanded)
14567 ;; Recursively expand each tag in the group, if the tag hasn't
14568 ;; already been expanded. Restore the match-data after all recursive calls.
14569 (save-match-data
14570 (let (tags-expanded)
14571 (dolist (x (cdr tags-in-group))
14572 (if (and (member x taggroups-keys)
14573 (not (member x work-already-expanded)))
14574 (setq tags-expanded
14575 (delete-dups
14576 (append
14577 (org-tags-expand x t downcased
14578 work-already-expanded)
14579 tags-expanded)))
14580 (setq tags-expanded
14581 (append (list x) tags-expanded)))
14582 (setq work-already-expanded
14583 (delete-dups
14584 (append tags-expanded
14585 work-already-expanded))))
14586 (setq tags-in-group
14587 (delete-dups (cons (car tags-in-group)
14588 tags-expanded)))))
14589 ;; Filter tag-regexps from tags.
14590 (setq regexp-in-group-escaped
14591 (delq nil (mapcar (lambda (x)
14592 (if (stringp x)
14593 (and (equal "{" (substring x 0 1))
14594 (equal "}" (substring x -1))
14597 tags-in-group))
14598 regexp-in-group
14599 (mapcar (lambda (x)
14600 (substring x 1 -1))
14601 regexp-in-group-escaped)
14602 tags-in-group
14603 (delq nil (mapcar (lambda (x)
14604 (if (stringp x)
14605 (and (not (equal "{" (substring x 0 1)))
14606 (not (equal "}" (substring x -1)))
14609 tags-in-group)))
14610 ;; If single-as-list, do no more in the while-loop.
14611 (if (not single-as-list)
14612 (progn
14613 (when regexp-in-group
14614 (setq regexp-in-group
14615 (concat "\\|"
14616 (mapconcat 'identity regexp-in-group
14617 "\\|"))))
14618 (setq tags-in-group
14619 (concat dir
14620 "{\\<"
14621 (regexp-opt tags-in-group)
14622 "\\>"
14623 regexp-in-group
14624 "}"))
14625 (when (stringp tags-in-group)
14626 (org-add-props tags-in-group '(grouptag t)))
14627 (setq return-match
14628 (replace-match tags-in-group t t return-match)))
14629 (setq tags-in-group
14630 (append regexp-in-group-escaped tags-in-group))))
14631 (setq taggroups-keys (delete tag taggroups-keys))))
14632 ;; Add the regular expressions back into the match-expression again.
14633 (while regexps-in-match
14634 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14635 (pop regexps-in-match)
14636 return-match t t))
14637 (cl-decf count))
14638 (if single-as-list
14639 (if tags-in-group tags-in-group (list return-match))
14640 return-match))
14641 (if single-as-list
14642 (list (if downcased (downcase match) match))
14643 match)))
14645 (defun org-op-to-function (op &optional stringp)
14646 "Turn an operator into the appropriate function."
14647 (setq op
14648 (cond
14649 ((equal op "<" ) '(< string< org-time<))
14650 ((equal op ">" ) '(> org-string> org-time>))
14651 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14652 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14653 ((member op '("=" "==")) '(= string= org-time=))
14654 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14655 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14657 (defun org<> (a b) (not (= a b)))
14658 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14659 (defun org-string>= (a b) (not (string< a b)))
14660 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14661 (defun org-string<> (a b) (not (string= a b)))
14662 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14663 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14664 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14665 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14666 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14667 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14668 (defun org-2ft (s)
14669 "Convert S to a floating point time.
14670 If S is already a number, just return it. If it is a string, parse
14671 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14672 (cond
14673 ((numberp s) s)
14674 ((stringp s)
14675 (condition-case nil
14676 (float-time (apply 'encode-time (org-parse-time-string s)))
14677 (error 0.)))
14678 (t 0.)))
14680 (defun org-time-today ()
14681 "Time in seconds today at 0:00.
14682 Returns the float number of seconds since the beginning of the
14683 epoch to the beginning of today (00:00)."
14684 (float-time (apply 'encode-time
14685 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14687 (defun org-matcher-time (s)
14688 "Interpret a time comparison value."
14689 (save-match-data
14690 (cond
14691 ((string= s "<now>") (float-time))
14692 ((string= s "<today>") (org-time-today))
14693 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14694 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14695 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14696 (+ (org-time-today)
14697 (* (string-to-number (match-string 1 s))
14698 (cdr (assoc (match-string 2 s)
14699 '(("d" . 86400.0) ("w" . 604800.0)
14700 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14701 (t (org-2ft s)))))
14703 (defun org-match-any-p (re list)
14704 "Does re match any element of list?"
14705 (setq list (mapcar (lambda (x) (string-match re x)) list))
14706 (delq nil list))
14708 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14709 (defvar org-tags-overlay (make-overlay 1 1))
14710 (delete-overlay org-tags-overlay)
14712 (defun org-get-local-tags-at (&optional pos)
14713 "Get a list of tags defined in the current headline."
14714 (org-get-tags-at pos 'local))
14716 (defun org-get-local-tags ()
14717 "Get a list of tags defined in the current headline."
14718 (org-get-tags-at nil 'local))
14720 (defun org-get-tags-at (&optional pos local)
14721 "Get a list of all headline tags applicable at POS.
14722 POS defaults to point. If tags are inherited, the list contains
14723 the targets in the same sequence as the headlines appear, i.e.
14724 the tags of the current headline come last.
14725 When LOCAL is non-nil, only return tags from the current headline,
14726 ignore inherited ones."
14727 (interactive)
14728 (if (and org-trust-scanner-tags
14729 (or (not pos) (equal pos (point)))
14730 (not local))
14731 org-scanner-tags
14732 (let (tags ltags lastpos parent)
14733 (save-excursion
14734 (save-restriction
14735 (widen)
14736 (goto-char (or pos (point)))
14737 (save-match-data
14738 (catch 'done
14739 (condition-case nil
14740 (progn
14741 (org-back-to-heading t)
14742 (while (not (equal lastpos (point)))
14743 (setq lastpos (point))
14744 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14745 (setq ltags (org-split-string
14746 (match-string-no-properties 1) ":"))
14747 (when parent
14748 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14749 (setq tags (append
14750 (if parent
14751 (org-remove-uninherited-tags ltags)
14752 ltags)
14753 tags)))
14754 (or org-use-tag-inheritance (throw 'done t))
14755 (when local (throw 'done t))
14756 (or (org-up-heading-safe) (error nil))
14757 (setq parent t)))
14758 (error nil)))))
14759 (if local
14760 tags
14761 (reverse (delete-dups
14762 (reverse (append
14763 (org-remove-uninherited-tags
14764 org-file-tags)
14765 tags)))))))))
14767 (defun org-add-prop-inherited (s)
14768 (add-text-properties 0 (length s) '(inherited t) s)
14771 (defun org-toggle-tag (tag &optional onoff)
14772 "Toggle the tag TAG for the current line.
14773 If ONOFF is `on' or `off', don't toggle but set to this state."
14774 (let (res current)
14775 (save-excursion
14776 (org-back-to-heading t)
14777 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14778 (point-at-eol) t)
14779 (progn
14780 (setq current (match-string 1))
14781 (replace-match ""))
14782 (setq current ""))
14783 (setq current (nreverse (org-split-string current ":")))
14784 (cond
14785 ((eq onoff 'on)
14786 (setq res t)
14787 (or (member tag current) (push tag current)))
14788 ((eq onoff 'off)
14789 (or (not (member tag current)) (setq current (delete tag current))))
14790 (t (if (member tag current)
14791 (setq current (delete tag current))
14792 (setq res t)
14793 (push tag current))))
14794 (end-of-line 1)
14795 (if current
14796 (progn
14797 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14798 (org-set-tags nil t))
14799 (delete-horizontal-space))
14800 (run-hooks 'org-after-tags-change-hook))
14801 res))
14803 (defun org--align-tags-here (to-col)
14804 "Align tags on the current headline to TO-COL.
14805 Assume point is on a headline."
14806 (let ((pos (point)))
14807 (beginning-of-line)
14808 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14809 (>= pos (match-beginning 2)))
14810 ;; No tags or point within tags: do not align.
14811 (goto-char pos)
14812 (goto-char (match-beginning 1))
14813 (let ((shift (max (- (if (>= to-col 0) to-col
14814 (- (abs to-col) (string-width (match-string 2))))
14815 (current-column))
14816 1)))
14817 (replace-match (make-string shift ?\s) nil nil nil 1)
14818 ;; Preserve initial position, if possible. In any case, stop
14819 ;; before tags.
14820 (when (< pos (point)) (goto-char pos))))))
14822 (defun org-set-tags-command (&optional arg just-align)
14823 "Call the set-tags command for the current entry."
14824 (interactive "P")
14825 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14826 (org-set-tags arg just-align)
14827 (save-excursion
14828 (unless (and (org-region-active-p)
14829 org-loop-over-headlines-in-active-region)
14830 (org-back-to-heading t))
14831 (org-set-tags arg just-align))))
14833 (defun org-set-tags-to (data)
14834 "Set the tags of the current entry to DATA, replacing the current tags.
14835 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14836 If DATA is nil or the empty string, any tags will be removed."
14837 (interactive "sTags: ")
14838 (setq data
14839 (cond
14840 ((eq data nil) "")
14841 ((equal data "") "")
14842 ((stringp data)
14843 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14844 ":"))
14845 ((listp data)
14846 (concat ":" (mapconcat 'identity data ":") ":"))))
14847 (when data
14848 (save-excursion
14849 (org-back-to-heading t)
14850 (when (let ((case-fold-search nil))
14851 (looking-at org-complex-heading-regexp))
14852 (if (match-end 5)
14853 (progn
14854 (goto-char (match-beginning 5))
14855 (insert data)
14856 (delete-region (point) (point-at-eol))
14857 (org-set-tags nil 'align))
14858 (goto-char (point-at-eol))
14859 (insert " " data)
14860 (org-set-tags nil 'align)))
14861 (beginning-of-line 1)
14862 (when (looking-at ".*?\\([ \t]+\\)$")
14863 (delete-region (match-beginning 1) (match-end 1))))))
14865 (defun org-align-all-tags ()
14866 "Align the tags in all headings."
14867 (interactive)
14868 (save-excursion
14869 (or (ignore-errors (org-back-to-heading t))
14870 (outline-next-heading))
14871 (if (org-at-heading-p)
14872 (org-set-tags t)
14873 (message "No headings"))))
14875 (defvar org-indent-indentation-per-level)
14876 (defun org-set-tags (&optional arg just-align)
14877 "Set the tags for the current headline.
14878 With prefix ARG, realign all tags in headings in the current buffer.
14879 When JUST-ALIGN is non-nil, only align tags."
14880 (interactive "P")
14881 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14882 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14883 'region-start-level
14884 'region))
14885 org-loop-over-headlines-in-active-region)
14886 (org-map-entries
14887 ;; We don't use ARG and JUST-ALIGN here because these args
14888 ;; are not useful when looping over headlines.
14889 #'org-set-tags
14890 org-loop-over-headlines-in-active-region
14892 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14893 (let ((org-setting-tags t))
14894 (if arg
14895 (save-excursion
14896 (goto-char (point-min))
14897 (while (re-search-forward org-outline-regexp-bol nil t)
14898 (org-set-tags nil t)
14899 (end-of-line))
14900 (message "All tags realigned to column %d" org-tags-column))
14901 (let* ((current (org-get-tags-string))
14902 (tags
14903 (if just-align current
14904 ;; Get a new set of tags from the user.
14905 (save-excursion
14906 (let* ((seen)
14907 (table
14908 (setq
14909 org-last-tags-completion-table
14910 ;; Uniquify tags in alists, yet preserve
14911 ;; structure (i.e., keywords).
14912 (delq nil
14913 (mapcar
14914 (lambda (pair)
14915 (let ((head (car pair)))
14916 (cond ((symbolp head) pair)
14917 ((member head seen) nil)
14918 (t (push head seen)
14919 pair))))
14920 (append
14921 (or org-current-tag-alist
14922 (org-get-buffer-tags))
14923 (and
14924 org-complete-tags-always-offer-all-agenda-tags
14925 (org-global-tags-completion-table
14926 (org-agenda-files))))))))
14927 (current-tags (org-split-string current ":"))
14928 (inherited-tags
14929 (nreverse (nthcdr (length current-tags)
14930 (nreverse (org-get-tags-at))))))
14931 (replace-regexp-in-string
14932 "\\([-+&]+\\|,\\)"
14934 (if (or (eq t org-use-fast-tag-selection)
14935 (and org-use-fast-tag-selection
14936 (delq nil (mapcar #'cdr table))))
14937 (org-fast-tag-selection
14938 current-tags inherited-tags table
14939 (and org-fast-tag-selection-include-todo
14940 org-todo-key-alist))
14941 (let ((org-add-colon-after-tag-completion
14942 (< 1 (length table))))
14943 (org-trim
14944 (completing-read
14945 "Tags: "
14946 #'org-tags-completion-function
14947 nil nil current 'org-tags-history))))))))))
14949 (when org-tags-sort-function
14950 (setq tags
14951 (mapconcat
14952 #'identity
14953 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14954 org-tags-sort-function)
14955 ":")))
14957 (if (or (string= ":" tags)
14958 (string= "::" tags))
14959 (setq tags ""))
14960 (if (not (org-string-nw-p tags)) (setq tags "")
14961 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14962 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14964 ;; Insert new tags at the correct column.
14965 (unless (equal current tags)
14966 (save-excursion
14967 (beginning-of-line)
14968 (let ((case-fold-search nil))
14969 (looking-at org-complex-heading-regexp))
14970 ;; Remove current tags, if any.
14971 (when (match-end 5) (replace-match "" nil nil nil 5))
14972 ;; Insert new tags, if any. Otherwise, remove trailing
14973 ;; white spaces.
14974 (end-of-line)
14975 (if (not (equal tags ""))
14976 ;; When text is being inserted on an invisible
14977 ;; region boundary, it can be inadvertently sucked
14978 ;; into invisibility.
14979 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14980 (skip-chars-backward " \t")
14981 (delete-region (point) (line-end-position)))))
14982 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14983 ;; is on.
14984 (unless (equal tags "")
14985 (let* ((level (save-excursion
14986 (beginning-of-line)
14987 (skip-chars-forward "\\*")))
14988 (offset (if (bound-and-true-p org-indent-mode)
14989 (* (1- org-indent-indentation-per-level)
14990 (1- level))
14992 (tags-column
14993 (+ org-tags-column
14994 (if (> org-tags-column 0) (- offset) offset))))
14995 (org--align-tags-here tags-column))))
14996 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14998 (defun org-change-tag-in-region (beg end tag off)
14999 "Add or remove TAG for each entry in the region.
15000 This works in the agenda, and also in an Org buffer."
15001 (interactive
15002 (list (region-beginning) (region-end)
15003 (let ((org-last-tags-completion-table
15004 (if (derived-mode-p 'org-mode)
15005 (org-uniquify
15006 (delq nil (append (org-get-buffer-tags)
15007 (org-global-tags-completion-table))))
15008 (org-global-tags-completion-table))))
15009 (completing-read
15010 "Tag: " 'org-tags-completion-function nil nil nil
15011 'org-tags-history))
15012 (progn
15013 (message "[s]et or [r]emove? ")
15014 (equal (read-char-exclusive) ?r))))
15015 (when (fboundp 'deactivate-mark) (deactivate-mark))
15016 (let ((agendap (equal major-mode 'org-agenda-mode))
15017 l1 l2 m buf pos newhead (cnt 0))
15018 (goto-char end)
15019 (setq l2 (1- (org-current-line)))
15020 (goto-char beg)
15021 (setq l1 (org-current-line))
15022 (cl-loop for l from l1 to l2 do
15023 (org-goto-line l)
15024 (setq m (get-text-property (point) 'org-hd-marker))
15025 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15026 (and agendap m))
15027 (setq buf (if agendap (marker-buffer m) (current-buffer))
15028 pos (if agendap m (point)))
15029 (with-current-buffer buf
15030 (save-excursion
15031 (save-restriction
15032 (goto-char pos)
15033 (setq cnt (1+ cnt))
15034 (org-toggle-tag tag (if off 'off 'on))
15035 (setq newhead (org-get-heading)))))
15036 (and agendap (org-agenda-change-all-lines newhead m))))
15037 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15039 (defun org-tags-completion-function (string _predicate &optional flag)
15040 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15041 (confirm (lambda (x) (stringp (car x)))))
15042 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15043 (setq s1 (match-string 1 string)
15044 s2 (match-string 2 string))
15045 (setq s1 "" s2 string))
15046 (cond
15047 ((eq flag nil)
15048 ;; try completion
15049 (setq rtn (try-completion s2 ctable confirm))
15050 (when (stringp rtn)
15051 (setq rtn
15052 (concat s1 s2 (substring rtn (length s2))
15053 (if (and org-add-colon-after-tag-completion
15054 (assoc rtn ctable))
15055 ":" ""))))
15056 rtn)
15057 ((eq flag t)
15058 ;; all-completions
15059 (all-completions s2 ctable confirm))
15060 ((eq flag 'lambda)
15061 ;; exact match?
15062 (assoc s2 ctable)))))
15064 (defun org-fast-tag-insert (kwd tags face &optional end)
15065 "Insert KDW, and the TAGS, the latter with face FACE.
15066 Also insert END."
15067 (insert (format "%-12s" (concat kwd ":"))
15068 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15069 (or end "")))
15071 (defun org-fast-tag-show-exit (flag)
15072 (save-excursion
15073 (org-goto-line 3)
15074 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15075 (replace-match ""))
15076 (when flag
15077 (end-of-line 1)
15078 (org-move-to-column (- (window-width) 19) t)
15079 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15081 (defun org-set-current-tags-overlay (current prefix)
15082 "Add an overlay to CURRENT tag with PREFIX."
15083 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15084 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15085 (org-overlay-display org-tags-overlay (concat prefix s))))
15087 (defvar org-last-tag-selection-key nil)
15088 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15089 "Fast tag selection with single keys.
15090 CURRENT is the current list of tags in the headline, INHERITED is the
15091 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15092 possibly with grouping information. TODO-TABLE is a similar table with
15093 TODO keywords, should these have keys assigned to them.
15094 If the keys are nil, a-z are automatically assigned.
15095 Returns the new tags string, or nil to not change the current settings."
15096 (let* ((fulltable (append table todo-table))
15097 (maxlen (apply 'max (mapcar
15098 (lambda (x)
15099 (if (stringp (car x)) (string-width (car x)) 0))
15100 fulltable)))
15101 (buf (current-buffer))
15102 (expert (eq org-fast-tag-selection-single-key 'expert))
15103 (buffer-tags nil)
15104 (fwidth (+ maxlen 3 1 3))
15105 (ncol (/ (- (window-width) 4) fwidth))
15106 (i-face 'org-done)
15107 (c-face 'org-todo)
15108 tg cnt e c char c1 c2 ntable tbl rtn
15109 ov-start ov-end ov-prefix
15110 (exit-after-next org-fast-tag-selection-single-key)
15111 (done-keywords org-done-keywords)
15112 groups ingroup intaggroup)
15113 (save-excursion
15114 (beginning-of-line 1)
15115 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15116 (setq ov-start (match-beginning 1)
15117 ov-end (match-end 1)
15118 ov-prefix "")
15119 (setq ov-start (1- (point-at-eol))
15120 ov-end (1+ ov-start))
15121 (skip-chars-forward "^\n\r")
15122 (setq ov-prefix
15123 (concat
15124 (buffer-substring (1- (point)) (point))
15125 (if (> (current-column) org-tags-column)
15127 (make-string (- org-tags-column (current-column)) ?\ ))))))
15128 (move-overlay org-tags-overlay ov-start ov-end)
15129 (save-window-excursion
15130 (if expert
15131 (set-buffer (get-buffer-create " *Org tags*"))
15132 (delete-other-windows)
15133 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15134 (org-switch-to-buffer-other-window " *Org tags*"))
15135 (erase-buffer)
15136 (setq-local org-done-keywords done-keywords)
15137 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15138 (org-fast-tag-insert "Current" current c-face "\n\n")
15139 (org-fast-tag-show-exit exit-after-next)
15140 (org-set-current-tags-overlay current ov-prefix)
15141 (setq tbl fulltable char ?a cnt 0)
15142 (while (setq e (pop tbl))
15143 (cond
15144 ((eq (car e) :startgroup)
15145 (push '() groups) (setq ingroup t)
15146 (unless (zerop cnt)
15147 (setq cnt 0)
15148 (insert "\n"))
15149 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15150 ((eq (car e) :endgroup)
15151 (setq ingroup nil cnt 0)
15152 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15153 ((eq (car e) :startgrouptag)
15154 (setq intaggroup t)
15155 (unless (zerop cnt)
15156 (setq cnt 0)
15157 (insert "\n"))
15158 (insert "[ "))
15159 ((eq (car e) :endgrouptag)
15160 (setq intaggroup nil cnt 0)
15161 (insert "]\n"))
15162 ((equal e '(:newline))
15163 (unless (zerop cnt)
15164 (setq cnt 0)
15165 (insert "\n")
15166 (setq e (car tbl))
15167 (while (equal (car tbl) '(:newline))
15168 (insert "\n")
15169 (setq tbl (cdr tbl)))))
15170 ((equal e '(:grouptags)) (insert " : "))
15172 (setq tg (copy-sequence (car e)) c2 nil)
15173 (if (cdr e)
15174 (setq c (cdr e))
15175 ;; automatically assign a character.
15176 (setq c1 (string-to-char
15177 (downcase (substring
15178 tg (if (= (string-to-char tg) ?@) 1 0)))))
15179 (if (or (rassoc c1 ntable) (rassoc c1 table))
15180 (while (or (rassoc char ntable) (rassoc char table))
15181 (setq char (1+ char)))
15182 (setq c2 c1))
15183 (setq c (or c2 char)))
15184 (when ingroup (push tg (car groups)))
15185 (setq tg (org-add-props tg nil 'face
15186 (cond
15187 ((not (assoc tg table))
15188 (org-get-todo-face tg))
15189 ((member tg current) c-face)
15190 ((member tg inherited) i-face))))
15191 (when (equal (caar tbl) :grouptags)
15192 (org-add-props tg nil 'face 'org-tag-group))
15193 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15194 (insert "[" c "] " tg (make-string
15195 (- fwidth 4 (length tg)) ?\ ))
15196 (push (cons tg c) ntable)
15197 (when (= (cl-incf cnt) ncol)
15198 (insert "\n")
15199 (when (or ingroup intaggroup) (insert " "))
15200 (setq cnt 0)))))
15201 (setq ntable (nreverse ntable))
15202 (insert "\n")
15203 (goto-char (point-min))
15204 (unless expert (org-fit-window-to-buffer))
15205 (setq rtn
15206 (catch 'exit
15207 (while t
15208 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15209 (if (not groups) "no " "")
15210 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15211 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15212 (setq org-last-tag-selection-key c)
15213 (cond
15214 ((= c ?\r) (throw 'exit t))
15215 ((= c ?!)
15216 (setq groups (not groups))
15217 (goto-char (point-min))
15218 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15219 ((= c ?\C-c)
15220 (if (not expert)
15221 (org-fast-tag-show-exit
15222 (setq exit-after-next (not exit-after-next)))
15223 (setq expert nil)
15224 (delete-other-windows)
15225 (set-window-buffer (split-window-vertically) " *Org tags*")
15226 (org-switch-to-buffer-other-window " *Org tags*")
15227 (org-fit-window-to-buffer)))
15228 ((or (= c ?\C-g)
15229 (and (= c ?q) (not (rassoc c ntable))))
15230 (delete-overlay org-tags-overlay)
15231 (setq quit-flag t))
15232 ((= c ?\ )
15233 (setq current nil)
15234 (when exit-after-next (setq exit-after-next 'now)))
15235 ((= c ?\t)
15236 (condition-case nil
15237 (setq tg (completing-read
15238 "Tag: "
15239 (or buffer-tags
15240 (with-current-buffer buf
15241 (setq buffer-tags
15242 (org-get-buffer-tags))))))
15243 (quit (setq tg "")))
15244 (when (string-match "\\S-" tg)
15245 (cl-pushnew (list tg) buffer-tags :test #'equal)
15246 (if (member tg current)
15247 (setq current (delete tg current))
15248 (push tg current)))
15249 (when exit-after-next (setq exit-after-next 'now)))
15250 ((setq e (rassoc c todo-table) tg (car e))
15251 (with-current-buffer buf
15252 (save-excursion (org-todo tg)))
15253 (when exit-after-next (setq exit-after-next 'now)))
15254 ((setq e (rassoc c ntable) tg (car e))
15255 (if (member tg current)
15256 (setq current (delete tg current))
15257 (cl-loop for g in groups do
15258 (when (member tg g)
15259 (dolist (x g) (setq current (delete x current)))))
15260 (push tg current))
15261 (when exit-after-next (setq exit-after-next 'now))))
15263 ;; Create a sorted list
15264 (setq current
15265 (sort current
15266 (lambda (a b)
15267 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15268 (when (eq exit-after-next 'now) (throw 'exit t))
15269 (goto-char (point-min))
15270 (beginning-of-line 2)
15271 (delete-region (point) (point-at-eol))
15272 (org-fast-tag-insert "Current" current c-face)
15273 (org-set-current-tags-overlay current ov-prefix)
15274 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15275 (setq tg (match-string 1))
15276 (add-text-properties
15277 (match-beginning 1) (match-end 1)
15278 (list 'face
15279 (cond
15280 ((member tg current) c-face)
15281 ((member tg inherited) i-face)
15282 (t (get-text-property (match-beginning 1) 'face))))))
15283 (goto-char (point-min)))))
15284 (delete-overlay org-tags-overlay)
15285 (if rtn
15286 (mapconcat 'identity current ":")
15287 nil))))
15289 (defun org-get-tags-string ()
15290 "Get the TAGS string in the current headline."
15291 (unless (org-at-heading-p t)
15292 (user-error "Not on a heading"))
15293 (save-excursion
15294 (beginning-of-line 1)
15295 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15296 (match-string-no-properties 1)
15297 "")))
15299 (defun org-get-tags ()
15300 "Get the list of tags specified in the current headline."
15301 (org-split-string (org-get-tags-string) ":"))
15303 (defun org-get-buffer-tags ()
15304 "Get a table of all tags used in the buffer, for completion."
15305 (org-with-wide-buffer
15306 (goto-char (point-min))
15307 (let ((tag-re (concat org-outline-regexp-bol
15308 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15309 tags)
15310 (while (re-search-forward tag-re nil t)
15311 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15312 (push tag tags)))
15313 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15315 ;;;; The mapping API
15317 (defvar org-agenda-skip-comment-trees)
15318 (defvar org-agenda-skip-function)
15319 (defun org-map-entries (func &optional match scope &rest skip)
15320 "Call FUNC at each headline selected by MATCH in SCOPE.
15322 FUNC is a function or a lisp form. The function will be called without
15323 arguments, with the cursor positioned at the beginning of the headline.
15324 The return values of all calls to the function will be collected and
15325 returned as a list.
15327 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15328 does not need to preserve point. After evaluation, the cursor will be
15329 moved to the end of the line (presumably of the headline of the
15330 processed entry) and search continues from there. Under some
15331 circumstances, this may not produce the wanted results. For example,
15332 if you have removed (e.g. archived) the current (sub)tree it could
15333 mean that the next entry will be skipped entirely. In such cases, you
15334 can specify the position from where search should continue by making
15335 FUNC set the variable `org-map-continue-from' to the desired buffer
15336 position.
15338 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15339 Only headlines that are matched by this query will be considered during
15340 the iteration. When MATCH is nil or t, all headlines will be
15341 visited by the iteration.
15343 SCOPE determines the scope of this command. It can be any of:
15345 nil The current buffer, respecting the restriction if any
15346 tree The subtree started with the entry at point
15347 region The entries within the active region, if any
15348 region-start-level
15349 The entries within the active region, but only those at
15350 the same level than the first one.
15351 file The current buffer, without restriction
15352 file-with-archives
15353 The current buffer, and any archives associated with it
15354 agenda All agenda files
15355 agenda-with-archives
15356 All agenda files with any archive files associated with them
15357 \(file1 file2 ...)
15358 If this is a list, all files in the list will be scanned
15360 The remaining args are treated as settings for the skipping facilities of
15361 the scanner. The following items can be given here:
15363 archive skip trees with the archive tag
15364 comment skip trees with the COMMENT keyword
15365 function or Emacs Lisp form:
15366 will be used as value for `org-agenda-skip-function', so
15367 whenever the function returns a position, FUNC will not be
15368 called for that entry and search will continue from the
15369 position returned
15371 If your function needs to retrieve the tags including inherited tags
15372 at the *current* entry, you can use the value of the variable
15373 `org-scanner-tags' which will be much faster than getting the value
15374 with `org-get-tags-at'. If your function gets properties with
15375 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15376 to t around the call to `org-entry-properties' to get the same speedup.
15377 Note that if your function moves around to retrieve tags and properties at
15378 a *different* entry, you cannot use these techniques."
15379 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15380 (not (org-region-active-p)))
15381 (let* ((org-agenda-archives-mode nil) ; just to make sure
15382 (org-agenda-skip-archived-trees (memq 'archive skip))
15383 (org-agenda-skip-comment-trees (memq 'comment skip))
15384 (org-agenda-skip-function
15385 (car (org-delete-all '(comment archive) skip)))
15386 (org-tags-match-list-sublevels t)
15387 (start-level (eq scope 'region-start-level))
15388 matcher res
15389 org-todo-keywords-for-agenda
15390 org-done-keywords-for-agenda
15391 org-todo-keyword-alist-for-agenda
15392 org-tag-alist-for-agenda
15393 org--matcher-tags-todo-only)
15395 (cond
15396 ((eq match t) (setq matcher t))
15397 ((eq match nil) (setq matcher t))
15398 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15400 (save-excursion
15401 (save-restriction
15402 (cond ((eq scope 'tree)
15403 (org-back-to-heading t)
15404 (org-narrow-to-subtree)
15405 (setq scope nil))
15406 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15407 (org-region-active-p))
15408 ;; If needed, set start-level to a string like "2"
15409 (when start-level
15410 (save-excursion
15411 (goto-char (region-beginning))
15412 (unless (org-at-heading-p) (outline-next-heading))
15413 (setq start-level (org-current-level))))
15414 (narrow-to-region (region-beginning)
15415 (save-excursion
15416 (goto-char (region-end))
15417 (unless (and (bolp) (org-at-heading-p))
15418 (outline-next-heading))
15419 (point)))
15420 (setq scope nil)))
15422 (if (not scope)
15423 (progn
15424 (org-agenda-prepare-buffers
15425 (and buffer-file-name (list buffer-file-name)))
15426 (setq res
15427 (org-scan-tags
15428 func matcher org--matcher-tags-todo-only start-level)))
15429 ;; Get the right scope
15430 (cond
15431 ((and scope (listp scope) (symbolp (car scope)))
15432 (setq scope (eval scope)))
15433 ((eq scope 'agenda)
15434 (setq scope (org-agenda-files t)))
15435 ((eq scope 'agenda-with-archives)
15436 (setq scope (org-agenda-files t))
15437 (setq scope (org-add-archive-files scope)))
15438 ((eq scope 'file)
15439 (setq scope (and buffer-file-name (list buffer-file-name))))
15440 ((eq scope 'file-with-archives)
15441 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15442 (org-agenda-prepare-buffers scope)
15443 (dolist (file scope)
15444 (with-current-buffer (org-find-base-buffer-visiting file)
15445 (org-with-wide-buffer
15446 (goto-char (point-min))
15447 (setq res
15448 (append
15450 (org-scan-tags
15451 func matcher org--matcher-tags-todo-only)))))))))
15452 res)))
15454 ;;; Properties API
15456 (defconst org-special-properties
15457 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15458 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15459 "The special properties valid in Org mode.
15460 These are properties that are not defined in the property drawer,
15461 but in some other way.")
15463 (defconst org-default-properties
15464 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15465 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15466 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15467 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15468 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15469 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15470 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15471 "Some properties that are used by Org mode for various purposes.
15472 Being in this list makes sure that they are offered for completion.")
15474 (defun org--valid-property-p (property)
15475 "Non nil when string PROPERTY is a valid property name."
15476 (not
15477 (or (equal property "")
15478 (string-match-p "\\s-" property))))
15480 (defun org--update-property-plist (key val props)
15481 "Associate KEY to VAL in alist PROPS.
15482 Modifications are made by side-effect. Return new alist."
15483 (let* ((appending (string= (substring key -1) "+"))
15484 (key (if appending (substring key 0 -1) key))
15485 (old (assoc-string key props t)))
15486 (if (not old) (cons (cons key val) props)
15487 (setcdr old (if appending (concat (cdr old) " " val) val))
15488 props)))
15490 (defun org-get-property-block (&optional beg force)
15491 "Return the (beg . end) range of the body of the property drawer.
15492 BEG is the beginning of the current subtree, or of the part
15493 before the first headline. If it is not given, it will be found.
15494 If the drawer does not exist, create it if FORCE is non-nil, or
15495 return nil."
15496 (org-with-wide-buffer
15497 (when beg (goto-char beg))
15498 (unless (org-before-first-heading-p)
15499 (let ((beg (cond (beg)
15500 ((or (not (featurep 'org-inlinetask))
15501 (org-inlinetask-in-task-p))
15502 (org-back-to-heading t))
15503 (t (org-with-limited-levels (org-back-to-heading t))))))
15504 (forward-line)
15505 (when (looking-at-p org-planning-line-re) (forward-line))
15506 (cond ((looking-at org-property-drawer-re)
15507 (forward-line)
15508 (cons (point) (progn (goto-char (match-end 0))
15509 (line-beginning-position))))
15510 (force
15511 (goto-char beg)
15512 (org-insert-property-drawer)
15513 (let ((pos (save-excursion (search-forward ":END:")
15514 (line-beginning-position))))
15515 (cons pos pos))))))))
15517 (defun org-at-property-p ()
15518 "Non-nil when point is inside a property drawer.
15519 See `org-property-re' for match data, if applicable."
15520 (save-excursion
15521 (beginning-of-line)
15522 (and (looking-at org-property-re)
15523 (let ((property-drawer (save-match-data (org-get-property-block))))
15524 (and property-drawer
15525 (>= (point) (car property-drawer))
15526 (< (point) (cdr property-drawer)))))))
15528 (defun org-property-action ()
15529 "Do an action on properties."
15530 (interactive)
15531 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15532 (let ((c (read-char-exclusive)))
15533 (cl-case c
15534 (?s (call-interactively #'org-set-property))
15535 (?d (call-interactively #'org-delete-property))
15536 (?D (call-interactively #'org-delete-property-globally))
15537 (?c (call-interactively #'org-compute-property-at-point))
15538 (otherwise (user-error "No such property action %c" c)))))
15540 (defun org-inc-effort ()
15541 "Increment the value of the effort property in the current entry."
15542 (interactive)
15543 (org-set-effort nil t))
15545 (defvar org-clock-effort) ; Defined in org-clock.el.
15546 (defvar org-clock-current-task) ; Defined in org-clock.el.
15547 (defun org-set-effort (&optional value increment)
15548 "Set the effort property of the current entry.
15549 With numerical prefix arg, use the nth allowed value, 0 stands for the
15550 10th allowed value.
15552 When INCREMENT is non-nil, set the property to the next allowed value."
15553 (interactive "P")
15554 (when (equal value 0) (setq value 10))
15555 (let* ((completion-ignore-case t)
15556 (prop org-effort-property)
15557 (cur (org-entry-get nil prop))
15558 (allowed (org-property-get-allowed-values nil prop 'table))
15559 (existing (mapcar 'list (org-property-values prop)))
15560 (heading (nth 4 (org-heading-components)))
15562 (val (cond
15563 ((stringp value) value)
15564 ((and allowed (integerp value))
15565 (or (car (nth (1- value) allowed))
15566 (car (org-last allowed))))
15567 ((and allowed increment)
15568 (or (cl-caadr (member (list cur) allowed))
15569 (user-error "Allowed effort values are not set")))
15570 (allowed
15571 (message "Select 1-9,0, [RET%s]: %s"
15572 (if cur (concat "=" cur) "")
15573 (mapconcat 'car allowed " "))
15574 (setq rpl (read-char-exclusive))
15575 (if (equal rpl ?\r)
15577 (setq rpl (- rpl ?0))
15578 (when (equal rpl 0) (setq rpl 10))
15579 (if (and (> rpl 0) (<= rpl (length allowed)))
15580 (car (nth (1- rpl) allowed))
15581 (org-completing-read "Effort: " allowed nil))))
15583 (org-completing-read
15584 (concat "Effort" (and cur (string-match "\\S-" cur)
15585 (concat " [" cur "]"))
15586 ": ")
15587 existing nil nil "" nil cur)))))
15588 (unless (equal (org-entry-get nil prop) val)
15589 (org-entry-put nil prop val))
15590 (org-refresh-property
15591 '((effort . identity)
15592 (effort-minutes . org-duration-to-minutes))
15593 val)
15594 (when (equal heading (bound-and-true-p org-clock-current-task))
15595 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15596 (org-clock-update-mode-line))
15597 (message "%s is now %s" prop val)))
15599 (defun org-entry-properties (&optional pom which)
15600 "Get all properties of the current entry.
15602 When POM is a buffer position, get all properties from the entry
15603 there instead.
15605 This includes the TODO keyword, the tags, time strings for
15606 deadline, scheduled, and clocking, and any additional properties
15607 defined in the entry.
15609 If WHICH is nil or `all', get all properties. If WHICH is
15610 `special' or `standard', only get that subclass. If WHICH is
15611 a string, only get that property.
15613 Return value is an alist. Keys are properties, as upcased
15614 strings."
15615 (org-with-point-at pom
15616 (when (and (derived-mode-p 'org-mode)
15617 (ignore-errors (org-back-to-heading t)))
15618 (catch 'exit
15619 (let* ((beg (point))
15620 (specific (and (stringp which) (upcase which)))
15621 (which (cond ((not specific) which)
15622 ((member specific org-special-properties) 'special)
15623 (t 'standard)))
15624 props)
15625 ;; Get the special properties, like TODO and TAGS.
15626 (when (memq which '(nil all special))
15627 (when (or (not specific) (string= specific "CLOCKSUM"))
15628 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15629 (when clocksum
15630 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15631 props)))
15632 (when specific (throw 'exit props)))
15633 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15634 (let ((clocksumt (get-text-property (point)
15635 :org-clock-minutes-today)))
15636 (when clocksumt
15637 (push (cons "CLOCKSUM_T"
15638 (org-duration-from-minutes clocksumt))
15639 props)))
15640 (when specific (throw 'exit props)))
15641 (when (or (not specific) (string= specific "ITEM"))
15642 (let ((case-fold-search nil))
15643 (when (looking-at org-complex-heading-regexp)
15644 (push (cons "ITEM"
15645 (let ((title (match-string-no-properties 4)))
15646 (if (org-string-nw-p title)
15647 (org-remove-tabs title)
15648 "")))
15649 props)))
15650 (when specific (throw 'exit props)))
15651 (when (or (not specific) (string= specific "TODO"))
15652 (let ((case-fold-search nil))
15653 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15654 (push (cons "TODO" (match-string-no-properties 2)) props)))
15655 (when specific (throw 'exit props)))
15656 (when (or (not specific) (string= specific "PRIORITY"))
15657 (push (cons "PRIORITY"
15658 (if (looking-at org-priority-regexp)
15659 (match-string-no-properties 2)
15660 (char-to-string org-default-priority)))
15661 props)
15662 (when specific (throw 'exit props)))
15663 (when (or (not specific) (string= specific "FILE"))
15664 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15665 props)
15666 (when specific (throw 'exit props)))
15667 (when (or (not specific) (string= specific "TAGS"))
15668 (let ((value (org-string-nw-p (org-get-tags-string))))
15669 (when value (push (cons "TAGS" value) props)))
15670 (when specific (throw 'exit props)))
15671 (when (or (not specific) (string= specific "ALLTAGS"))
15672 (let ((value (org-get-tags-at)))
15673 (when value
15674 (push (cons "ALLTAGS"
15675 (format ":%s:" (mapconcat #'identity value ":")))
15676 props)))
15677 (when specific (throw 'exit props)))
15678 (when (or (not specific) (string= specific "BLOCKED"))
15679 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15680 (when specific (throw 'exit props)))
15681 (when (or (not specific)
15682 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15683 (forward-line)
15684 (when (looking-at-p org-planning-line-re)
15685 (end-of-line)
15686 (let ((bol (line-beginning-position))
15687 ;; Backward compatibility: time keywords used to
15688 ;; be configurable (before 8.3). Make sure we
15689 ;; get the correct keyword.
15690 (key-assoc `(("CLOSED" . ,org-closed-string)
15691 ("DEADLINE" . ,org-deadline-string)
15692 ("SCHEDULED" . ,org-scheduled-string))))
15693 (dolist (pair (if specific (list (assoc specific key-assoc))
15694 key-assoc))
15695 (save-excursion
15696 (when (search-backward (cdr pair) bol t)
15697 (goto-char (match-end 0))
15698 (skip-chars-forward " \t")
15699 (and (looking-at org-ts-regexp-both)
15700 (push (cons (car pair)
15701 (match-string-no-properties 0))
15702 props)))))))
15703 (when specific (throw 'exit props)))
15704 (when (or (not specific)
15705 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15706 (let ((find-ts
15707 (lambda (end ts)
15708 ;; Fix next time-stamp before END. TS is the
15709 ;; list of time-stamps found so far.
15710 (let ((ts ts)
15711 (regexp (cond
15712 ((string= specific "TIMESTAMP")
15713 org-ts-regexp)
15714 ((string= specific "TIMESTAMP_IA")
15715 org-ts-regexp-inactive)
15716 ((assoc "TIMESTAMP_IA" ts)
15717 org-ts-regexp)
15718 ((assoc "TIMESTAMP" ts)
15719 org-ts-regexp-inactive)
15720 (t org-ts-regexp-both))))
15721 (catch 'next
15722 (while (re-search-forward regexp end t)
15723 (backward-char)
15724 (let ((object (org-element-context)))
15725 ;; Accept to match timestamps in node
15726 ;; properties, too.
15727 (when (memq (org-element-type object)
15728 '(node-property timestamp))
15729 (let ((type
15730 (org-element-property :type object)))
15731 (cond
15732 ((and (memq type '(active active-range))
15733 (not (equal specific "TIMESTAMP_IA")))
15734 (unless (assoc "TIMESTAMP" ts)
15735 (push (cons "TIMESTAMP"
15736 (org-element-property
15737 :raw-value object))
15739 (when specific (throw 'exit ts))))
15740 ((and (memq type '(inactive inactive-range))
15741 (not (string= specific "TIMESTAMP")))
15742 (unless (assoc "TIMESTAMP_IA" ts)
15743 (push (cons "TIMESTAMP_IA"
15744 (org-element-property
15745 :raw-value object))
15747 (when specific (throw 'exit ts))))))
15748 ;; Both timestamp types are found,
15749 ;; move to next part.
15750 (when (= (length ts) 2) (throw 'next ts)))))
15751 ts)))))
15752 (goto-char beg)
15753 ;; First look for timestamps within headline.
15754 (let ((ts (funcall find-ts (line-end-position) nil)))
15755 (if (= (length ts) 2) (setq props (nconc ts props))
15756 ;; Then find timestamps in the section, skipping
15757 ;; planning line.
15758 (let ((end (save-excursion (outline-next-heading))))
15759 (forward-line)
15760 (when (looking-at-p org-planning-line-re) (forward-line))
15761 (setq props (nconc (funcall find-ts end ts) props))))))))
15762 ;; Get the standard properties, like :PROP:.
15763 (when (memq which '(nil all standard))
15764 ;; If we are looking after a specific property, delegate
15765 ;; to `org-entry-get', which is faster. However, make an
15766 ;; exception for "CATEGORY", since it can be also set
15767 ;; through keywords (i.e. #+CATEGORY).
15768 (if (and specific (not (equal specific "CATEGORY")))
15769 (let ((value (org-entry-get beg specific nil t)))
15770 (throw 'exit (and value (list (cons specific value)))))
15771 (let ((range (org-get-property-block beg)))
15772 (when range
15773 (let ((end (cdr range)) seen-base)
15774 (goto-char (car range))
15775 ;; Unlike to `org--update-property-plist', we
15776 ;; handle the case where base values is found
15777 ;; after its extension. We also forbid standard
15778 ;; properties to be named as special properties.
15779 (while (re-search-forward org-property-re end t)
15780 (let* ((key (upcase (match-string-no-properties 2)))
15781 (extendp (string-match-p "\\+\\'" key))
15782 (key-base (if extendp (substring key 0 -1) key))
15783 (value (match-string-no-properties 3)))
15784 (cond
15785 ((member-ignore-case key-base org-special-properties))
15786 (extendp
15787 (setq props
15788 (org--update-property-plist key value props)))
15789 ((member key seen-base))
15790 (t (push key seen-base)
15791 (let ((p (assoc-string key props t)))
15792 (if p (setcdr p (concat value " " (cdr p)))
15793 (push (cons key value) props))))))))))))
15794 (unless (assoc "CATEGORY" props)
15795 (push (cons "CATEGORY" (org-get-category beg)) props)
15796 (when (string= specific "CATEGORY") (throw 'exit props)))
15797 ;; Return value.
15798 props)))))
15800 (defun org--property-local-values (property literal-nil)
15801 "Return value for PROPERTY in current entry.
15802 Value is a list whose car is the base value for PROPERTY and cdr
15803 a list of accumulated values. Return nil if neither is found in
15804 the entry. Also return nil when PROPERTY is set to \"nil\",
15805 unless LITERAL-NIL is non-nil."
15806 (let ((range (org-get-property-block)))
15807 (when range
15808 (goto-char (car range))
15809 (let* ((case-fold-search t)
15810 (end (cdr range))
15811 (value
15812 ;; Base value.
15813 (save-excursion
15814 (let ((v (and (re-search-forward
15815 (org-re-property property nil t) end t)
15816 (match-string-no-properties 3))))
15817 (list (if literal-nil v (org-not-nil v)))))))
15818 ;; Find additional values.
15819 (let* ((property+ (org-re-property (concat property "+") nil t)))
15820 (while (re-search-forward property+ end t)
15821 (push (match-string-no-properties 3) value)))
15822 ;; Return final values.
15823 (and (not (equal value '(nil))) (nreverse value))))))
15825 (defun org--property-global-value (property literal-nil)
15826 "Return value for PROPERTY in current buffer.
15827 Return value is a string. Return nil if property is not set
15828 globally. Also return nil when PROPERTY is set to \"nil\",
15829 unless LITERAL-NIL is non-nil."
15830 (let ((global
15831 (cdr (or (assoc-string property org-file-properties t)
15832 (assoc-string property org-global-properties t)
15833 (assoc-string property org-global-properties-fixed t)))))
15834 (if literal-nil global (org-not-nil global))))
15836 (defun org-entry-get (pom property &optional inherit literal-nil)
15837 "Get value of PROPERTY for entry or content at point-or-marker POM.
15839 If INHERIT is non-nil and the entry does not have the property,
15840 then also check higher levels of the hierarchy. If INHERIT is
15841 the symbol `selective', use inheritance only if the setting in
15842 `org-use-property-inheritance' selects PROPERTY for inheritance.
15844 If the property is present but empty, the return value is the
15845 empty string. If the property is not present at all, nil is
15846 returned. In any other case, return the value as a string.
15847 Search is case-insensitive.
15849 If LITERAL-NIL is set, return the string value \"nil\" as
15850 a string, do not interpret it as the list atom nil. This is used
15851 for inheritance when a \"nil\" value can supersede a non-nil
15852 value higher up the hierarchy."
15853 (org-with-point-at pom
15854 (cond
15855 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15856 ;; We need a special property. Use `org-entry-properties' to
15857 ;; retrieve it, but specify the wanted property.
15858 (cdr (assoc-string property (org-entry-properties nil property))))
15859 ((and inherit
15860 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15861 (org-entry-get-with-inheritance property literal-nil))
15863 (let* ((local (org--property-local-values property literal-nil))
15864 (value (and local (mapconcat #'identity (delq nil local) " "))))
15865 (if literal-nil value (org-not-nil value)))))))
15867 (defun org-property-or-variable-value (var &optional inherit)
15868 "Check if there is a property fixing the value of VAR.
15869 If yes, return this value. If not, return the current value of the variable."
15870 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15871 (if (and prop (stringp prop) (string-match "\\S-" prop))
15872 (read prop)
15873 (symbol-value var))))
15875 (defun org-entry-delete (pom property)
15876 "Delete PROPERTY from entry at point-or-marker POM.
15877 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15878 non-nil when a property was removed."
15879 (org-with-point-at pom
15880 (pcase (org-get-property-block)
15881 (`(,begin . ,origin)
15882 (let* ((end (copy-marker origin))
15883 (re (org-re-property
15884 (concat (regexp-quote property) "\\+?") t t)))
15885 (goto-char begin)
15886 (while (re-search-forward re end t)
15887 (delete-region (match-beginning 0) (line-beginning-position 2)))
15888 ;; If drawer is empty, remove it altogether.
15889 (when (= begin end)
15890 (delete-region (line-beginning-position 0)
15891 (line-beginning-position 2)))
15892 ;; Return non-nil if some property was removed.
15893 (prog1 (/= end origin) (set-marker end nil))))
15894 (_ nil))))
15896 ;; Multi-values properties are properties that contain multiple values
15897 ;; These values are assumed to be single words, separated by whitespace.
15898 (defun org-entry-add-to-multivalued-property (pom property value)
15899 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15900 (let* ((old (org-entry-get pom property))
15901 (values (and old (org-split-string old "[ \t]"))))
15902 (setq value (org-entry-protect-space value))
15903 (unless (member value values)
15904 (setq values (append values (list value)))
15905 (org-entry-put pom property
15906 (mapconcat 'identity values " ")))))
15908 (defun org-entry-remove-from-multivalued-property (pom property value)
15909 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15910 (let* ((old (org-entry-get pom property))
15911 (values (and old (org-split-string old "[ \t]"))))
15912 (setq value (org-entry-protect-space value))
15913 (when (member value values)
15914 (setq values (delete value values))
15915 (org-entry-put pom property
15916 (mapconcat 'identity values " ")))))
15918 (defun org-entry-member-in-multivalued-property (pom property value)
15919 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15920 (let* ((old (org-entry-get pom property))
15921 (values (and old (org-split-string old "[ \t]"))))
15922 (setq value (org-entry-protect-space value))
15923 (member value values)))
15925 (defun org-entry-get-multivalued-property (pom property)
15926 "Return a list of values in a multivalued property."
15927 (let* ((value (org-entry-get pom property))
15928 (values (and value (org-split-string value "[ \t]"))))
15929 (mapcar 'org-entry-restore-space values)))
15931 (defun org-entry-put-multivalued-property (pom property &rest values)
15932 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15933 VALUES should be a list of strings. Spaces will be protected."
15934 (org-entry-put pom property
15935 (mapconcat 'org-entry-protect-space values " "))
15936 (let* ((value (org-entry-get pom property))
15937 (values (and value (org-split-string value "[ \t]"))))
15938 (mapcar 'org-entry-restore-space values)))
15940 (defun org-entry-protect-space (s)
15941 "Protect spaces and newline in string S."
15942 (while (string-match " " s)
15943 (setq s (replace-match "%20" t t s)))
15944 (while (string-match "\n" s)
15945 (setq s (replace-match "%0A" t t s)))
15948 (defun org-entry-restore-space (s)
15949 "Restore spaces and newline in string S."
15950 (while (string-match "%20" s)
15951 (setq s (replace-match " " t t s)))
15952 (while (string-match "%0A" s)
15953 (setq s (replace-match "\n" t t s)))
15956 (defvar org-entry-property-inherited-from (make-marker)
15957 "Marker pointing to the entry from where a property was inherited.
15958 Each call to `org-entry-get-with-inheritance' will set this marker to the
15959 location of the entry where the inheritance search matched. If there was
15960 no match, the marker will point nowhere.
15961 Note that also `org-entry-get' calls this function, if the INHERIT flag
15962 is set.")
15964 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15965 "Get PROPERTY of entry or content at point, search higher levels if needed.
15966 The search will stop at the first ancestor which has the property defined.
15967 If the value found is \"nil\", return nil to show that the property
15968 should be considered as undefined (this is the meaning of nil here).
15969 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15970 (move-marker org-entry-property-inherited-from nil)
15971 (org-with-wide-buffer
15972 (let (value)
15973 (catch 'exit
15974 (while t
15975 (let ((v (org--property-local-values property literal-nil)))
15976 (when v
15977 (setq value
15978 (concat (mapconcat #'identity (delq nil v) " ")
15979 (and value " ")
15980 value)))
15981 (cond
15982 ((car v)
15983 (org-back-to-heading t)
15984 (move-marker org-entry-property-inherited-from (point))
15985 (throw 'exit nil))
15986 ((org-up-heading-safe))
15988 (let ((global (org--property-global-value property literal-nil)))
15989 (cond ((not global))
15990 (value (setq value (concat global " " value)))
15991 (t (setq value global))))
15992 (throw 'exit nil))))))
15993 (if literal-nil value (org-not-nil value)))))
15995 (defvar org-property-changed-functions nil
15996 "Hook called when the value of a property has changed.
15997 Each hook function should accept two arguments, the name of the property
15998 and the new value.")
16000 (defun org-entry-put (pom property value)
16001 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16003 If the value is nil, it is converted to the empty string. If it
16004 is not a string, an error is raised. Also raise an error on
16005 invalid property names.
16007 PROPERTY can be any regular property (see
16008 `org-special-properties'). It can also be \"TODO\",
16009 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16011 For the last two properties, VALUE may have any of the special
16012 values \"earlier\" and \"later\". The function then increases or
16013 decreases scheduled or deadline date by one day."
16014 (cond ((null value) (setq value ""))
16015 ((not (stringp value)) (error "Properties values should be strings"))
16016 ((not (org--valid-property-p property))
16017 (user-error "Invalid property name: \"%s\"" property)))
16018 (org-with-point-at pom
16019 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16020 (org-back-to-heading t)
16021 (org-with-limited-levels (org-back-to-heading t)))
16022 (let ((beg (point)))
16023 (cond
16024 ((equal property "TODO")
16025 (cond ((not (org-string-nw-p value)) (setq value 'none))
16026 ((not (member value org-todo-keywords-1))
16027 (user-error "\"%s\" is not a valid TODO state" value)))
16028 (org-todo value)
16029 (org-set-tags nil 'align))
16030 ((equal property "PRIORITY")
16031 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16032 (org-set-tags nil 'align))
16033 ((equal property "SCHEDULED")
16034 (forward-line)
16035 (if (and (looking-at-p org-planning-line-re)
16036 (re-search-forward
16037 org-scheduled-time-regexp (line-end-position) t))
16038 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16039 ((string= value "later") (org-timestamp-change 1 'day))
16040 ((string= value "") (org-schedule '(4)))
16041 (t (org-schedule nil value)))
16042 (if (member value '("earlier" "later" ""))
16043 (call-interactively #'org-schedule)
16044 (org-schedule nil value))))
16045 ((equal property "DEADLINE")
16046 (forward-line)
16047 (if (and (looking-at-p org-planning-line-re)
16048 (re-search-forward
16049 org-deadline-time-regexp (line-end-position) t))
16050 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16051 ((string= value "later") (org-timestamp-change 1 'day))
16052 ((string= value "") (org-deadline '(4)))
16053 (t (org-deadline nil value)))
16054 (if (member value '("earlier" "later" ""))
16055 (call-interactively #'org-deadline)
16056 (org-deadline nil value))))
16057 ((member property org-special-properties)
16058 (error "The %s property cannot be set with `org-entry-put'" property))
16060 (let* ((range (org-get-property-block beg 'force))
16061 (end (cdr range))
16062 (case-fold-search t))
16063 (goto-char (car range))
16064 (if (re-search-forward (org-re-property property nil t) end t)
16065 (progn (delete-region (match-beginning 0) (match-end 0))
16066 (goto-char (match-beginning 0)))
16067 (goto-char end)
16068 (insert "\n")
16069 (backward-char))
16070 (insert ":" property ":")
16071 (when value (insert " " value))
16072 (org-indent-line)))))
16073 (run-hook-with-args 'org-property-changed-functions property value)))
16075 (defun org-buffer-property-keys
16076 (&optional specials defaults columns ignore-malformed)
16077 "Get all property keys in the current buffer.
16079 When SPECIALS is non-nil, also list the special properties that
16080 reflect things like tags and TODO state.
16082 When DEFAULTS is non-nil, also include properties that has
16083 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16084 DESCRIPTION, LOCATION, and LOGGING and others.
16086 When COLUMNS in non-nil, also include property names given in
16087 COLUMN formats in the current buffer.
16089 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16090 automatically performed, such drawers will be silently ignored."
16091 (let ((case-fold-search t)
16092 (props (append
16093 (and specials org-special-properties)
16094 (and defaults (cons org-effort-property org-default-properties))
16095 nil)))
16096 (org-with-wide-buffer
16097 (goto-char (point-min))
16098 (while (re-search-forward org-property-start-re nil t)
16099 (let ((range (org-get-property-block)))
16100 (catch 'skip
16101 (unless range
16102 (when (and (not ignore-malformed)
16103 (not (org-before-first-heading-p))
16104 (y-or-n-p (format "Malformed drawer at %d, repair?"
16105 (line-beginning-position))))
16106 (org-get-property-block nil t))
16107 (throw 'skip nil))
16108 (goto-char (car range))
16109 (let ((begin (car range))
16110 (end (cdr range)))
16111 ;; Make sure that found property block is not located
16112 ;; before current point, as it would generate an infloop.
16113 ;; It can happen, for example, in the following
16114 ;; situation:
16116 ;; * Headline
16117 ;; :PROPERTIES:
16118 ;; ...
16119 ;; :END:
16120 ;; *************** Inlinetask
16121 ;; #+BEGIN_EXAMPLE
16122 ;; :PROPERTIES:
16123 ;; #+END_EXAMPLE
16125 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16126 (while (< (point) end)
16127 (let ((p (progn (looking-at org-property-re)
16128 (match-string-no-properties 2))))
16129 ;; Only add true property name, not extension symbol.
16130 (push (if (not (string-match-p "\\+\\'" p)) p
16131 (substring p 0 -1))
16132 props))
16133 (forward-line))))
16134 (outline-next-heading)))
16135 (when columns
16136 (goto-char (point-min))
16137 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16138 (let ((element (org-element-at-point)))
16139 (when (memq (org-element-type element) '(keyword node-property))
16140 (let ((value (org-element-property :value element))
16141 (start 0))
16142 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16143 (setq start (match-end 0))
16144 (let ((p (match-string-no-properties 1 value)))
16145 (unless (member-ignore-case p org-special-properties)
16146 (push p props))))))))))
16147 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16149 (defun org-property-values (key)
16150 "List all non-nil values of property KEY in current buffer."
16151 (org-with-wide-buffer
16152 (goto-char (point-min))
16153 (let ((case-fold-search t)
16154 (re (org-re-property key))
16155 values)
16156 (while (re-search-forward re nil t)
16157 (push (org-entry-get (point) key) values))
16158 (delete-dups values))))
16160 (defun org-insert-property-drawer ()
16161 "Insert a property drawer into the current entry."
16162 (org-with-wide-buffer
16163 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16164 (org-back-to-heading t)
16165 (org-with-limited-levels (org-back-to-heading t)))
16166 (forward-line)
16167 (when (looking-at-p org-planning-line-re) (forward-line))
16168 (unless (looking-at-p org-property-drawer-re)
16169 ;; Make sure we start editing a line from current entry, not from
16170 ;; next one. It prevents extending text properties or overlays
16171 ;; belonging to the latter.
16172 (when (bolp) (backward-char))
16173 (let ((begin (1+ (point)))
16174 (inhibit-read-only t))
16175 (insert "\n:PROPERTIES:\n:END:")
16176 (when (eobp) (insert "\n"))
16177 (org-indent-region begin (point))))))
16179 (defun org-insert-drawer (&optional arg drawer)
16180 "Insert a drawer at point.
16182 When optional argument ARG is non-nil, insert a property drawer.
16184 Optional argument DRAWER, when non-nil, is a string representing
16185 drawer's name. Otherwise, the user is prompted for a name.
16187 If a region is active, insert the drawer around that region
16188 instead.
16190 Point is left between drawer's boundaries."
16191 (interactive "P")
16192 (let* ((drawer (if arg "PROPERTIES"
16193 (or drawer (read-from-minibuffer "Drawer: ")))))
16194 (cond
16195 ;; With C-u, fall back on `org-insert-property-drawer'
16196 (arg (org-insert-property-drawer))
16197 ;; Check validity of suggested drawer's name.
16198 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16199 (user-error "Invalid drawer name"))
16200 ;; With an active region, insert a drawer at point.
16201 ((not (org-region-active-p))
16202 (progn
16203 (unless (bolp) (insert "\n"))
16204 (insert (format ":%s:\n\n:END:\n" drawer))
16205 (forward-line -2)))
16206 ;; Otherwise, insert the drawer at point
16208 (let ((rbeg (region-beginning))
16209 (rend (copy-marker (region-end))))
16210 (unwind-protect
16211 (progn
16212 (goto-char rbeg)
16213 (beginning-of-line)
16214 (when (save-excursion
16215 (re-search-forward org-outline-regexp-bol rend t))
16216 (user-error "Drawers cannot contain headlines"))
16217 ;; Position point at the beginning of the first
16218 ;; non-blank line in region. Insert drawer's opening
16219 ;; there, then indent it.
16220 (org-skip-whitespace)
16221 (beginning-of-line)
16222 (insert ":" drawer ":\n")
16223 (forward-line -1)
16224 (indent-for-tab-command)
16225 ;; Move point to the beginning of the first blank line
16226 ;; after the last non-blank line in region. Insert
16227 ;; drawer's closing, then indent it.
16228 (goto-char rend)
16229 (skip-chars-backward " \r\t\n")
16230 (insert "\n:END:")
16231 (deactivate-mark t)
16232 (indent-for-tab-command)
16233 (unless (eolp) (insert "\n")))
16234 ;; Clear marker, whatever the outcome of insertion is.
16235 (set-marker rend nil)))))))
16237 (defvar org-property-set-functions-alist nil
16238 "Property set function alist.
16239 Each entry should have the following format:
16241 (PROPERTY . READ-FUNCTION)
16243 The read function will be called with the same argument as
16244 `org-completing-read'.")
16246 (defun org-set-property-function (property)
16247 "Get the function that should be used to set PROPERTY.
16248 This is computed according to `org-property-set-functions-alist'."
16249 (or (cdr (assoc property org-property-set-functions-alist))
16250 'org-completing-read))
16252 (defun org-read-property-value (property)
16253 "Read PROPERTY value from user."
16254 (let* ((completion-ignore-case t)
16255 (allowed (org-property-get-allowed-values nil property 'table))
16256 (cur (org-entry-get nil property))
16257 (prompt (concat property " value"
16258 (if (and cur (string-match "\\S-" cur))
16259 (concat " [" cur "]") "") ": "))
16260 (set-function (org-set-property-function property))
16261 (val (if allowed
16262 (funcall set-function prompt allowed nil
16263 (not (get-text-property 0 'org-unrestricted
16264 (caar allowed))))
16265 (funcall set-function prompt
16266 (mapcar 'list (org-property-values property))
16267 nil nil "" nil cur))))
16268 (org-trim val)))
16270 (defvar org-last-set-property nil)
16271 (defvar org-last-set-property-value nil)
16272 (defun org-read-property-name ()
16273 "Read a property name."
16274 (let ((completion-ignore-case t)
16275 (default-prop (or (and (org-at-property-p)
16276 (match-string-no-properties 2))
16277 org-last-set-property)))
16278 (org-completing-read
16279 (concat "Property"
16280 (if default-prop (concat " [" default-prop "]") "")
16281 ": ")
16282 (mapcar #'list (org-buffer-property-keys nil t t))
16283 nil nil nil nil default-prop)))
16285 (defun org-set-property-and-value (use-last)
16286 "Allow to set [PROPERTY]: [value] direction from prompt.
16287 When use-default, don't even ask, just use the last
16288 \"[PROPERTY]: [value]\" string from the history."
16289 (interactive "P")
16290 (let* ((completion-ignore-case t)
16291 (pv (or (and use-last org-last-set-property-value)
16292 (org-completing-read
16293 "Enter a \"[Property]: [value]\" pair: "
16294 nil nil nil nil nil
16295 org-last-set-property-value)))
16296 prop val)
16297 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16298 (setq prop (match-string 1 pv)
16299 val (match-string 2 pv))
16300 (org-set-property prop val))))
16302 (defun org-set-property (property value)
16303 "In the current entry, set PROPERTY to VALUE.
16305 When called interactively, this will prompt for a property name, offering
16306 completion on existing and default properties. And then it will prompt
16307 for a value, offering completion either on allowed values (via an inherited
16308 xxx_ALL property) or on existing values in other instances of this property
16309 in the current file.
16311 Throw an error when trying to set a property with an invalid name."
16312 (interactive (list nil nil))
16313 (let ((property (or property (org-read-property-name))))
16314 ;; `org-entry-put' also makes the following check, but this one
16315 ;; avoids polluting `org-last-set-property' and
16316 ;; `org-last-set-property-value' needlessly.
16317 (unless (org--valid-property-p property)
16318 (user-error "Invalid property name: \"%s\"" property))
16319 (let ((value (or value (org-read-property-value property)))
16320 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16321 (setq org-last-set-property property)
16322 (setq org-last-set-property-value (concat property ": " value))
16323 ;; Possibly postprocess the inserted value:
16324 (when fn (setq value (funcall fn value)))
16325 (unless (equal (org-entry-get nil property) value)
16326 (org-entry-put nil property value)))))
16328 (defun org-find-property (property &optional value)
16329 "Find first entry in buffer that sets PROPERTY.
16331 When optional argument VALUE is non-nil, only consider an entry
16332 if it contains PROPERTY set to this value. If PROPERTY should be
16333 explicitly set to nil, use string \"nil\" for VALUE.
16335 Return position where the entry begins, or nil if there is no
16336 such entry. If narrowing is in effect, only search the visible
16337 part of the buffer."
16338 (save-excursion
16339 (goto-char (point-min))
16340 (let ((case-fold-search t)
16341 (re (org-re-property property nil (not value) value)))
16342 (catch 'exit
16343 (while (re-search-forward re nil t)
16344 (when (if value (org-at-property-p)
16345 (org-entry-get (point) property nil t))
16346 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16348 (defun org-delete-property (property)
16349 "In the current entry, delete PROPERTY."
16350 (interactive
16351 (let* ((completion-ignore-case t)
16352 (cat (org-entry-get (point) "CATEGORY"))
16353 (props0 (org-entry-properties nil 'standard))
16354 (props (if cat props0
16355 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16356 (prop (if (< 1 (length props))
16357 (completing-read "Property: " props nil t)
16358 (caar props))))
16359 (list prop)))
16360 (if (not property)
16361 (message "No property to delete in this entry")
16362 (org-entry-delete nil property)
16363 (message "Property \"%s\" deleted" property)))
16365 (defun org-delete-property-globally (property)
16366 "Remove PROPERTY globally, from all entries.
16367 This function ignores narrowing, if any."
16368 (interactive
16369 (let* ((completion-ignore-case t)
16370 (prop (completing-read
16371 "Globally remove property: "
16372 (mapcar #'list (org-buffer-property-keys)))))
16373 (list prop)))
16374 (org-with-wide-buffer
16375 (goto-char (point-min))
16376 (let ((count 0)
16377 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16378 (while (re-search-forward re nil t)
16379 (when (org-entry-delete (point) property) (cl-incf count)))
16380 (message "Property \"%s\" removed from %d entries" property count))))
16382 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16384 (defun org-compute-property-at-point ()
16385 "Compute the property at point.
16386 This looks for an enclosing column format, extracts the operator and
16387 then applies it to the property in the column format's scope."
16388 (interactive)
16389 (unless (org-at-property-p)
16390 (user-error "Not at a property"))
16391 (let ((prop (match-string-no-properties 2)))
16392 (org-columns-get-format-and-top-level)
16393 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16394 (user-error "No operator defined for property %s" prop))
16395 (org-columns-compute prop)))
16397 (defvar org-property-allowed-value-functions nil
16398 "Hook for functions supplying allowed values for a specific property.
16399 The functions must take a single argument, the name of the property, and
16400 return a flat list of allowed values. If \":ETC\" is one of
16401 the values, this means that these values are intended as defaults for
16402 completion, but that other values should be allowed too.
16403 The functions must return nil if they are not responsible for this
16404 property.")
16406 (defun org-property-get-allowed-values (pom property &optional table)
16407 "Get allowed values for the property PROPERTY.
16408 When TABLE is non-nil, return an alist that can directly be used for
16409 completion."
16410 (let (vals)
16411 (cond
16412 ((equal property "TODO")
16413 (setq vals (org-with-point-at pom
16414 (append org-todo-keywords-1 '("")))))
16415 ((equal property "PRIORITY")
16416 (let ((n org-lowest-priority))
16417 (while (>= n org-highest-priority)
16418 (push (char-to-string n) vals)
16419 (setq n (1- n)))))
16420 ((equal property "CATEGORY"))
16421 ((member property org-special-properties))
16422 ((setq vals (run-hook-with-args-until-success
16423 'org-property-allowed-value-functions property)))
16425 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16426 (when (and vals (string-match "\\S-" vals))
16427 (setq vals (car (read-from-string (concat "(" vals ")"))))
16428 (setq vals (mapcar (lambda (x)
16429 (cond ((stringp x) x)
16430 ((numberp x) (number-to-string x))
16431 ((symbolp x) (symbol-name x))
16432 (t "???")))
16433 vals)))))
16434 (when (member ":ETC" vals)
16435 (setq vals (remove ":ETC" vals))
16436 (org-add-props (car vals) '(org-unrestricted t)))
16437 (if table (mapcar 'list vals) vals)))
16439 (defun org-property-previous-allowed-value (&optional _previous)
16440 "Switch to the next allowed value for this property."
16441 (interactive)
16442 (org-property-next-allowed-value t))
16444 (defun org-property-next-allowed-value (&optional previous)
16445 "Switch to the next allowed value for this property."
16446 (interactive)
16447 (unless (org-at-property-p)
16448 (user-error "Not at a property"))
16449 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16450 (key (match-string 2))
16451 (value (match-string 3))
16452 (allowed (or (org-property-get-allowed-values (point) key)
16453 (and (member value '("[ ]" "[-]" "[X]"))
16454 '("[ ]" "[X]"))))
16455 (heading (save-match-data (nth 4 (org-heading-components))))
16456 nval)
16457 (unless allowed
16458 (user-error "Allowed values for this property have not been defined"))
16459 (when previous (setq allowed (reverse allowed)))
16460 (when (member value allowed)
16461 (setq nval (car (cdr (member value allowed)))))
16462 (setq nval (or nval (car allowed)))
16463 (when (equal nval value)
16464 (user-error "Only one allowed value for this property"))
16465 (org-at-property-p)
16466 (replace-match (concat " :" key ": " nval) t t)
16467 (org-indent-line)
16468 (beginning-of-line 1)
16469 (skip-chars-forward " \t")
16470 (when (equal prop org-effort-property)
16471 (org-refresh-property
16472 '((effort . identity)
16473 (effort-minutes . org-duration-to-minutes))
16474 nval)
16475 (when (string= org-clock-current-task heading)
16476 (setq org-clock-effort nval)
16477 (org-clock-update-mode-line)))
16478 (run-hook-with-args 'org-property-changed-functions key nval)))
16480 (defun org-find-olp (path &optional this-buffer)
16481 "Return a marker pointing to the entry at outline path OLP.
16482 If anything goes wrong, throw an error.
16483 You can wrap this call to catch the error like this:
16485 (condition-case msg
16486 (org-mobile-locate-entry (match-string 4))
16487 (error (nth 1 msg)))
16489 The return value will then be either a string with the error message,
16490 or a marker if everything is OK.
16492 If THIS-BUFFER is set, the outline path does not contain a file,
16493 only headings."
16494 (let* ((file (if this-buffer buffer-file-name (pop path)))
16495 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16496 (level 1)
16497 (lmin 1)
16498 (lmax 1)
16499 end found flevel)
16500 (unless buffer (error "File not found :%s" file))
16501 (with-current-buffer buffer
16502 (unless (derived-mode-p 'org-mode)
16503 (error "Buffer %s needs to be in Org mode" buffer))
16504 (org-with-wide-buffer
16505 (goto-char (point-min))
16506 (dolist (heading path)
16507 (let ((re (format org-complex-heading-regexp-format
16508 (regexp-quote heading)))
16509 (cnt 0))
16510 (while (re-search-forward re end t)
16511 (setq level (- (match-end 1) (match-beginning 1)))
16512 (when (and (>= level lmin) (<= level lmax))
16513 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16514 (when (= cnt 0)
16515 (error "Heading not found on level %d: %s" lmax heading))
16516 (when (> cnt 1)
16517 (error "Heading not unique on level %d: %s" lmax heading))
16518 (goto-char found)
16519 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16520 (setq end (save-excursion (org-end-of-subtree t t)))))
16521 (when (org-at-heading-p)
16522 (point-marker))))))
16524 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16525 "Find node HEADING in BUFFER.
16526 Return a marker to the heading if it was found, or nil if not.
16527 If POS-ONLY is set, return just the position instead of a marker.
16529 The heading text must match exact, but it may have a TODO keyword,
16530 a priority cookie and tags in the standard locations."
16531 (with-current-buffer (or buffer (current-buffer))
16532 (org-with-wide-buffer
16533 (goto-char (point-min))
16534 (let (case-fold-search)
16535 (when (re-search-forward
16536 (format org-complex-heading-regexp-format
16537 (regexp-quote heading)) nil t)
16538 (if pos-only
16539 (match-beginning 0)
16540 (move-marker (make-marker) (match-beginning 0))))))))
16542 (defun org-find-exact-heading-in-directory (heading &optional dir)
16543 "Find Org node headline HEADING in all .org files in directory DIR.
16544 When the target headline is found, return a marker to this location."
16545 (let ((files (directory-files (or dir default-directory)
16546 t "\\`[^.#].*\\.org\\'"))
16547 visiting m buffer)
16548 (catch 'found
16549 (dolist (file files)
16550 (message "trying %s" file)
16551 (setq visiting (org-find-base-buffer-visiting file))
16552 (setq buffer (or visiting (find-file-noselect file)))
16553 (setq m (org-find-exact-headline-in-buffer
16554 heading buffer))
16555 (when (and (not m) (not visiting)) (kill-buffer buffer))
16556 (and m (throw 'found m))))))
16558 (defun org-find-entry-with-id (ident)
16559 "Locate the entry that contains the ID property with exact value IDENT.
16560 IDENT can be a string, a symbol or a number, this function will search for
16561 the string representation of it.
16562 Return the position where this entry starts, or nil if there is no such entry."
16563 (interactive "sID: ")
16564 (let ((id (cond
16565 ((stringp ident) ident)
16566 ((symbolp ident) (symbol-name ident))
16567 ((numberp ident) (number-to-string ident))
16568 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16569 (org-with-wide-buffer (org-find-property "ID" id))))
16571 ;;;; Timestamps
16573 (defvar org-last-changed-timestamp nil)
16574 (defvar org-last-inserted-timestamp nil
16575 "The last time stamp inserted with `org-insert-time-stamp'.")
16577 (defun org-time-stamp (arg &optional inactive)
16578 "Prompt for a date/time and insert a time stamp.
16580 If the user specifies a time like HH:MM or if this command is
16581 called with at least one prefix argument, the time stamp contains
16582 the date and the time. Otherwise, only the date is included.
16584 All parts of a date not specified by the user are filled in from
16585 the timestamp at point, if any, or the current date/time
16586 otherwise.
16588 If there is already a timestamp at the cursor, it is replaced.
16590 With two universal prefix arguments, insert an active timestamp
16591 with the current time without prompting the user.
16593 When called from lisp, the timestamp is inactive if INACTIVE is
16594 non-nil."
16595 (interactive "P")
16596 (let* ((ts (cond
16597 ((org-at-date-range-p t)
16598 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16599 ((org-at-timestamp-p 'lax) (match-string 0))))
16600 ;; Default time is either the timestamp at point or today.
16601 ;; When entering a range, only the range start is considered.
16602 (default-time (if (not ts) (current-time)
16603 (apply #'encode-time (org-parse-time-string ts))))
16604 (default-input (and ts (org-get-compact-tod ts)))
16605 (repeater (and ts
16606 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16607 (match-string 0 ts)))
16608 org-time-was-given
16609 org-end-time-was-given
16610 (time
16611 (and (if (equal arg '(16)) (current-time)
16612 ;; Preserve `this-command' and `last-command'.
16613 (let ((this-command this-command)
16614 (last-command last-command))
16615 (org-read-date
16616 arg 'totime nil nil default-time default-input
16617 inactive))))))
16618 (cond
16619 ((and ts
16620 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16621 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16622 (insert "--")
16623 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16625 ;; Make sure we're on a timestamp. When in the middle of a date
16626 ;; range, move arbitrarily to range end.
16627 (unless (org-at-timestamp-p 'lax)
16628 (skip-chars-forward "-")
16629 (org-at-timestamp-p 'lax))
16630 (replace-match "")
16631 (setq org-last-changed-timestamp
16632 (org-insert-time-stamp
16633 time (or org-time-was-given arg)
16634 inactive nil nil (list org-end-time-was-given)))
16635 (when repeater
16636 (backward-char)
16637 (insert " " repeater)
16638 (setq org-last-changed-timestamp
16639 (concat (substring org-last-inserted-timestamp 0 -1)
16640 " " repeater ">")))
16641 (message "Timestamp updated"))
16642 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16643 (t (org-insert-time-stamp
16644 time (or org-time-was-given arg) inactive nil nil
16645 (list org-end-time-was-given))))))
16647 ;; FIXME: can we use this for something else, like computing time differences?
16648 (defun org-get-compact-tod (s)
16649 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16650 (let* ((t1 (match-string 1 s))
16651 (h1 (string-to-number (match-string 2 s)))
16652 (m1 (string-to-number (match-string 3 s)))
16653 (t2 (and (match-end 4) (match-string 5 s)))
16654 (h2 (and t2 (string-to-number (match-string 6 s))))
16655 (m2 (and t2 (string-to-number (match-string 7 s))))
16656 dh dm)
16657 (if (not t2)
16659 (setq dh (- h2 h1) dm (- m2 m1))
16660 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16661 (concat t1 "+" (number-to-string dh)
16662 (and (/= 0 dm) (format ":%02d" dm)))))))
16664 (defun org-time-stamp-inactive (&optional arg)
16665 "Insert an inactive time stamp.
16666 An inactive time stamp is enclosed in square brackets instead of angle
16667 brackets. It is inactive in the sense that it does not trigger agenda entries,
16668 does not link to the calendar and cannot be changed with the S-cursor keys.
16669 So these are more for recording a certain time/date."
16670 (interactive "P")
16671 (org-time-stamp arg 'inactive))
16673 (defvar org-date-ovl (make-overlay 1 1))
16674 (overlay-put org-date-ovl 'face 'org-date-selected)
16675 (delete-overlay org-date-ovl)
16677 (defvar org-ans1) ; dynamically scoped parameter
16678 (defvar org-ans2) ; dynamically scoped parameter
16680 (defvar org-plain-time-of-day-regexp) ; defined below
16682 (defvar org-overriding-default-time nil) ; dynamically scoped
16683 (defvar org-read-date-overlay nil)
16684 (defvar org-dcst nil) ; dynamically scoped
16685 (defvar org-read-date-history nil)
16686 (defvar org-read-date-final-answer nil)
16687 (defvar org-read-date-analyze-futurep nil)
16688 (defvar org-read-date-analyze-forced-year nil)
16689 (defvar org-read-date-inactive)
16691 (defvar org-read-date-minibuffer-local-map
16692 (let* ((map (make-sparse-keymap)))
16693 (set-keymap-parent map minibuffer-local-map)
16694 (org-defkey map (kbd ".")
16695 (lambda () (interactive)
16696 ;; Are we at the beginning of the prompt?
16697 (if (looking-back "^[^:]+: "
16698 (let ((inhibit-field-text-motion t))
16699 (line-beginning-position)))
16700 (org-eval-in-calendar '(calendar-goto-today))
16701 (insert "."))))
16702 (org-defkey map (kbd "C-.")
16703 (lambda () (interactive)
16704 (org-eval-in-calendar '(calendar-goto-today))))
16705 (org-defkey map [(meta shift left)]
16706 (lambda () (interactive)
16707 (org-eval-in-calendar '(calendar-backward-month 1))))
16708 (org-defkey map [(meta shift right)]
16709 (lambda () (interactive)
16710 (org-eval-in-calendar '(calendar-forward-month 1))))
16711 (org-defkey map [(meta shift up)]
16712 (lambda () (interactive)
16713 (org-eval-in-calendar '(calendar-backward-year 1))))
16714 (org-defkey map [(meta shift down)]
16715 (lambda () (interactive)
16716 (org-eval-in-calendar '(calendar-forward-year 1))))
16717 (org-defkey map [?\e (shift left)]
16718 (lambda () (interactive)
16719 (org-eval-in-calendar '(calendar-backward-month 1))))
16720 (org-defkey map [?\e (shift right)]
16721 (lambda () (interactive)
16722 (org-eval-in-calendar '(calendar-forward-month 1))))
16723 (org-defkey map [?\e (shift up)]
16724 (lambda () (interactive)
16725 (org-eval-in-calendar '(calendar-backward-year 1))))
16726 (org-defkey map [?\e (shift down)]
16727 (lambda () (interactive)
16728 (org-eval-in-calendar '(calendar-forward-year 1))))
16729 (org-defkey map [(shift up)]
16730 (lambda () (interactive)
16731 (org-eval-in-calendar '(calendar-backward-week 1))))
16732 (org-defkey map [(shift down)]
16733 (lambda () (interactive)
16734 (org-eval-in-calendar '(calendar-forward-week 1))))
16735 (org-defkey map [(shift left)]
16736 (lambda () (interactive)
16737 (org-eval-in-calendar '(calendar-backward-day 1))))
16738 (org-defkey map [(shift right)]
16739 (lambda () (interactive)
16740 (org-eval-in-calendar '(calendar-forward-day 1))))
16741 (org-defkey map "!"
16742 (lambda () (interactive)
16743 (org-eval-in-calendar '(diary-view-entries))
16744 (message "")))
16745 (org-defkey map ">"
16746 (lambda () (interactive)
16747 (org-eval-in-calendar '(calendar-scroll-left 1))))
16748 (org-defkey map "<"
16749 (lambda () (interactive)
16750 (org-eval-in-calendar '(calendar-scroll-right 1))))
16751 (org-defkey map "\C-v"
16752 (lambda () (interactive)
16753 (org-eval-in-calendar
16754 '(calendar-scroll-left-three-months 1))))
16755 (org-defkey map "\M-v"
16756 (lambda () (interactive)
16757 (org-eval-in-calendar
16758 '(calendar-scroll-right-three-months 1))))
16759 map)
16760 "Keymap for minibuffer commands when using `org-read-date'.")
16762 (defvar org-def)
16763 (defvar org-defdecode)
16764 (defvar org-with-time)
16766 (defvar calendar-setup) ; Dynamically scoped.
16767 (defun org-read-date (&optional with-time to-time from-string prompt
16768 default-time default-input inactive)
16769 "Read a date, possibly a time, and make things smooth for the user.
16770 The prompt will suggest to enter an ISO date, but you can also enter anything
16771 which will at least partially be understood by `parse-time-string'.
16772 Unrecognized parts of the date will default to the current day, month, year,
16773 hour and minute. If this command is called to replace a timestamp at point,
16774 or to enter the second timestamp of a range, the default time is taken
16775 from the existing stamp. Furthermore, the command prefers the future,
16776 so if you are giving a date where the year is not given, and the day-month
16777 combination is already past in the current year, it will assume you
16778 mean next year. For details, see the manual. A few examples:
16780 3-2-5 --> 2003-02-05
16781 feb 15 --> currentyear-02-15
16782 2/15 --> currentyear-02-15
16783 sep 12 9 --> 2009-09-12
16784 12:45 --> today 12:45
16785 22 sept 0:34 --> currentyear-09-22 0:34
16786 12 --> currentyear-currentmonth-12
16787 Fri --> nearest Friday after today
16788 -Tue --> last Tuesday
16789 etc.
16791 Furthermore you can specify a relative date by giving, as the *first* thing
16792 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16793 change in days weeks, months, years.
16794 With a single plus or minus, the date is relative to today. With a double
16795 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16796 +4d --> four days from today
16797 +4 --> same as above
16798 +2w --> two weeks from today
16799 ++5 --> five days from default date
16801 The function understands only English month and weekday abbreviations.
16803 While prompting, a calendar is popped up - you can also select the
16804 date with the mouse (button 1). The calendar shows a period of three
16805 months. To scroll it to other months, use the keys `>' and `<'.
16806 If you don't like the calendar, turn it off with
16807 (setq org-read-date-popup-calendar nil)
16809 With optional argument TO-TIME, the date will immediately be converted
16810 to an internal time.
16811 With an optional argument WITH-TIME, the prompt will suggest to
16812 also insert a time. Note that when WITH-TIME is not set, you can
16813 still enter a time, and this function will inform the calling routine
16814 about this change. The calling routine may then choose to change the
16815 format used to insert the time stamp into the buffer to include the time.
16816 With optional argument FROM-STRING, read from this string instead from
16817 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16818 the time/date that is used for everything that is not specified by the
16819 user."
16820 (require 'parse-time)
16821 (let* ((org-with-time with-time)
16822 (org-time-stamp-rounding-minutes
16823 (if (equal org-with-time '(16))
16824 '(0 0)
16825 org-time-stamp-rounding-minutes))
16826 (org-dcst org-display-custom-times)
16827 (ct (org-current-time))
16828 (org-def (or org-overriding-default-time default-time ct))
16829 (org-defdecode (decode-time org-def))
16830 (cur-frame (selected-frame))
16831 (mouse-autoselect-window nil) ; Don't let the mouse jump
16832 (calendar-setup
16833 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16834 (calendar-move-hook nil)
16835 (calendar-view-diary-initially-flag nil)
16836 (calendar-view-holidays-initially-flag nil)
16837 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16838 ;; Rationalize `org-def' and `org-defdecode', if required.
16839 (when (< (nth 2 org-defdecode) org-extend-today-until)
16840 (setf (nth 2 org-defdecode) -1)
16841 (setf (nth 1 org-defdecode) 59)
16842 (setq org-def (apply #'encode-time org-defdecode))
16843 (setq org-defdecode (decode-time org-def)))
16844 (let* ((timestr (format-time-string
16845 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16846 org-def))
16847 (prompt (concat (if prompt (concat prompt " ") "")
16848 (format "Date+time [%s]: " timestr))))
16849 (cond
16850 (from-string (setq ans from-string))
16851 (org-read-date-popup-calendar
16852 (save-excursion
16853 (save-window-excursion
16854 (calendar)
16855 (when (eq calendar-setup 'calendar-only)
16856 (setq cal-frame
16857 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16858 (select-frame cal-frame))
16859 (org-eval-in-calendar '(setq cursor-type nil) t)
16860 (unwind-protect
16861 (progn
16862 (calendar-forward-day (- (time-to-days org-def)
16863 (calendar-absolute-from-gregorian
16864 (calendar-current-date))))
16865 (org-eval-in-calendar nil t)
16866 (let* ((old-map (current-local-map))
16867 (map (copy-keymap calendar-mode-map))
16868 (minibuffer-local-map
16869 (copy-keymap org-read-date-minibuffer-local-map)))
16870 (org-defkey map (kbd "RET") 'org-calendar-select)
16871 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16872 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16873 (unwind-protect
16874 (progn
16875 (use-local-map map)
16876 (setq org-read-date-inactive inactive)
16877 (add-hook 'post-command-hook 'org-read-date-display)
16878 (setq org-ans0
16879 (read-string prompt
16880 default-input
16881 'org-read-date-history
16882 nil))
16883 ;; org-ans0: from prompt
16884 ;; org-ans1: from mouse click
16885 ;; org-ans2: from calendar motion
16886 (setq ans
16887 (concat org-ans0 " " (or org-ans1 org-ans2))))
16888 (remove-hook 'post-command-hook 'org-read-date-display)
16889 (use-local-map old-map)
16890 (when org-read-date-overlay
16891 (delete-overlay org-read-date-overlay)
16892 (setq org-read-date-overlay nil)))))
16893 (bury-buffer "*Calendar*")
16894 (when cal-frame
16895 (delete-frame cal-frame)
16896 (select-frame-set-input-focus cur-frame))))))
16898 (t ; Naked prompt only
16899 (unwind-protect
16900 (setq ans (read-string prompt default-input
16901 'org-read-date-history timestr))
16902 (when org-read-date-overlay
16903 (delete-overlay org-read-date-overlay)
16904 (setq org-read-date-overlay nil))))))
16906 (setq final (org-read-date-analyze ans org-def org-defdecode))
16908 (when org-read-date-analyze-forced-year
16909 (message "Year was forced into %s"
16910 (if org-read-date-force-compatible-dates
16911 "compatible range (1970-2037)"
16912 "range representable on this machine"))
16913 (ding))
16915 ;; One round trip to get rid of 34th of August and stuff like that....
16916 (setq final (decode-time (apply 'encode-time final)))
16918 (setq org-read-date-final-answer ans)
16920 (if to-time
16921 (apply 'encode-time final)
16922 (if (and (boundp 'org-time-was-given) org-time-was-given)
16923 (format "%04d-%02d-%02d %02d:%02d"
16924 (nth 5 final) (nth 4 final) (nth 3 final)
16925 (nth 2 final) (nth 1 final))
16926 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16928 (defun org-read-date-display ()
16929 "Display the current date prompt interpretation in the minibuffer."
16930 (when org-read-date-display-live
16931 (when org-read-date-overlay
16932 (delete-overlay org-read-date-overlay))
16933 (when (minibufferp (current-buffer))
16934 (save-excursion
16935 (end-of-line 1)
16936 (while (not (equal (buffer-substring
16937 (max (point-min) (- (point) 4)) (point))
16938 " "))
16939 (insert " ")))
16940 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16941 " " (or org-ans1 org-ans2)))
16942 (org-end-time-was-given nil)
16943 (f (org-read-date-analyze ans org-def org-defdecode))
16944 (fmts (if org-dcst
16945 org-time-stamp-custom-formats
16946 org-time-stamp-formats))
16947 (fmt (if (or org-with-time
16948 (and (boundp 'org-time-was-given) org-time-was-given))
16949 (cdr fmts)
16950 (car fmts)))
16951 (txt (format-time-string fmt (apply 'encode-time f)))
16952 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16953 (txt (concat "=> " txt)))
16954 (when (and org-end-time-was-given
16955 (string-match org-plain-time-of-day-regexp txt))
16956 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16957 org-end-time-was-given
16958 (substring txt (match-end 0)))))
16959 (when org-read-date-analyze-futurep
16960 (setq txt (concat txt " (=>F)")))
16961 (setq org-read-date-overlay
16962 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16963 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16965 (defun org-read-date-analyze (ans def defdecode)
16966 "Analyze the combined answer of the date prompt."
16967 ;; FIXME: cleanup and comment
16968 ;; Pass `current-time' result to `decode-time' (instead of calling
16969 ;; without arguments) so that only `current-time' has to be
16970 ;; overriden in tests.
16971 (let ((org-def def)
16972 (org-defdecode defdecode)
16973 (nowdecode (decode-time (current-time)))
16974 delta deltan deltaw deltadef year month day
16975 hour minute second wday pm h2 m2 tl wday1
16976 iso-year iso-weekday iso-week iso-date futurep kill-year)
16977 (setq org-read-date-analyze-futurep nil
16978 org-read-date-analyze-forced-year nil)
16979 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16980 (setq ans "+0"))
16982 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16983 (setq ans (replace-match "" t t ans)
16984 deltan (car delta)
16985 deltaw (nth 1 delta)
16986 deltadef (nth 2 delta)))
16988 ;; Check if there is an iso week date in there. If yes, store the
16989 ;; info and postpone interpreting it until the rest of the parsing
16990 ;; is done.
16991 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16992 (setq iso-year (when (match-end 1)
16993 (org-small-year-to-year
16994 (string-to-number (match-string 1 ans))))
16995 iso-weekday (when (match-end 3)
16996 (string-to-number (match-string 3 ans)))
16997 iso-week (string-to-number (match-string 2 ans)))
16998 (setq ans (replace-match "" t t ans)))
17000 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17001 (when (string-match
17002 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17003 (setq year (if (match-end 2)
17004 (string-to-number (match-string 2 ans))
17005 (progn (setq kill-year t)
17006 (string-to-number (format-time-string "%Y"))))
17007 month (string-to-number (match-string 3 ans))
17008 day (string-to-number (match-string 4 ans)))
17009 (setq year (org-small-year-to-year year))
17010 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17011 t nil ans)))
17013 ;; Help matching dotted european dates
17014 (when (string-match
17015 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17016 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17017 (setq kill-year t)
17018 (string-to-number (format-time-string "%Y")))
17019 day (string-to-number (match-string 1 ans))
17020 month (string-to-number (match-string 2 ans))
17021 ans (replace-match (format "%04d-%02d-%02d" year month day)
17022 t nil ans)))
17024 ;; Help matching american dates, like 5/30 or 5/30/7
17025 (when (string-match
17026 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17027 (setq year (if (match-end 4)
17028 (string-to-number (match-string 4 ans))
17029 (progn (setq kill-year t)
17030 (string-to-number (format-time-string "%Y"))))
17031 month (string-to-number (match-string 1 ans))
17032 day (string-to-number (match-string 2 ans)))
17033 (setq year (org-small-year-to-year year))
17034 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17035 t nil ans)))
17036 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17037 ;; If there is a time with am/pm, and *no* time without it, we convert
17038 ;; so that matching will be successful.
17039 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17040 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17041 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17042 (setq hour (string-to-number (match-string 1 ans))
17043 minute (if (match-end 3)
17044 (string-to-number (match-string 3 ans))
17046 pm (equal ?p
17047 (string-to-char (downcase (match-string 4 ans)))))
17048 (if (and (= hour 12) (not pm))
17049 (setq hour 0)
17050 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17051 (setq ans (replace-match (format "%02d:%02d" hour minute)
17052 t t ans))))
17054 ;; Check if a time range is given as a duration
17055 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17056 (setq hour (string-to-number (match-string 1 ans))
17057 h2 (+ hour (string-to-number (match-string 3 ans)))
17058 minute (string-to-number (match-string 2 ans))
17059 m2 (+ minute (if (match-end 5) (string-to-number
17060 (match-string 5 ans))0)))
17061 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17062 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17063 t t ans)))
17065 ;; Check if there is a time range
17066 (when (boundp 'org-end-time-was-given)
17067 (setq org-time-was-given nil)
17068 (when (and (string-match org-plain-time-of-day-regexp ans)
17069 (match-end 8))
17070 (setq org-end-time-was-given (match-string 8 ans))
17071 (setq ans (concat (substring ans 0 (match-beginning 7))
17072 (substring ans (match-end 7))))))
17074 (setq tl (parse-time-string ans)
17075 day (or (nth 3 tl) (nth 3 org-defdecode))
17076 month
17077 (cond ((nth 4 tl))
17078 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17079 ;; Day was specified. Make sure DAY+MONTH
17080 ;; combination happens in the future.
17081 ((nth 3 tl)
17082 (setq futurep t)
17083 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17084 (nth 4 nowdecode)))
17085 (t (nth 4 org-defdecode)))
17086 year
17087 (cond ((and (not kill-year) (nth 5 tl)))
17088 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17089 ;; Month was guessed in the future and is at least
17090 ;; equal to NOWDECODE's. Fix year accordingly.
17091 (futurep
17092 (if (or (> month (nth 4 nowdecode))
17093 (>= day (nth 3 nowdecode)))
17094 (nth 5 nowdecode)
17095 (1+ (nth 5 nowdecode))))
17096 ;; Month was specified. Make sure MONTH+YEAR
17097 ;; combination happens in the future.
17098 ((nth 4 tl)
17099 (setq futurep t)
17100 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17101 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17102 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17103 (t (nth 5 nowdecode))))
17104 (t (nth 5 org-defdecode)))
17105 hour (or (nth 2 tl) (nth 2 org-defdecode))
17106 minute (or (nth 1 tl) (nth 1 org-defdecode))
17107 second (or (nth 0 tl) 0)
17108 wday (nth 6 tl))
17110 (when (and (eq org-read-date-prefer-future 'time)
17111 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17112 (equal day (nth 3 nowdecode))
17113 (equal month (nth 4 nowdecode))
17114 (equal year (nth 5 nowdecode))
17115 (nth 2 tl)
17116 (or (< (nth 2 tl) (nth 2 nowdecode))
17117 (and (= (nth 2 tl) (nth 2 nowdecode))
17118 (nth 1 tl)
17119 (< (nth 1 tl) (nth 1 nowdecode)))))
17120 (setq day (1+ day)
17121 futurep t))
17123 ;; Special date definitions below
17124 (cond
17125 (iso-week
17126 ;; There was an iso week
17127 (require 'cal-iso)
17128 (setq futurep nil)
17129 (setq year (or iso-year year)
17130 day (or iso-weekday wday 1)
17131 wday nil ; to make sure that the trigger below does not match
17132 iso-date (calendar-gregorian-from-absolute
17133 (calendar-iso-to-absolute
17134 (list iso-week day year))))
17135 ; FIXME: Should we also push ISO weeks into the future?
17136 ; (when (and org-read-date-prefer-future
17137 ; (not iso-year)
17138 ; (< (calendar-absolute-from-gregorian iso-date)
17139 ; (time-to-days (current-time))))
17140 ; (setq year (1+ year)
17141 ; iso-date (calendar-gregorian-from-absolute
17142 ; (calendar-iso-to-absolute
17143 ; (list iso-week day year)))))
17144 (setq month (car iso-date)
17145 year (nth 2 iso-date)
17146 day (nth 1 iso-date)))
17147 (deltan
17148 (setq futurep nil)
17149 (unless deltadef
17150 ;; Pass `current-time' result to `decode-time' (instead of
17151 ;; calling without arguments) so that only `current-time' has
17152 ;; to be overriden in tests.
17153 (let ((now (decode-time (current-time))))
17154 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17155 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17156 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17157 ((equal deltaw "m") (setq month (+ month deltan)))
17158 ((equal deltaw "y") (setq year (+ year deltan)))))
17159 ((and wday (not (nth 3 tl)))
17160 ;; Weekday was given, but no day, so pick that day in the week
17161 ;; on or after the derived date.
17162 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17163 (unless (equal wday wday1)
17164 (setq day (+ day (% (- wday wday1 -7) 7))))))
17165 (when (and (boundp 'org-time-was-given)
17166 (nth 2 tl))
17167 (setq org-time-was-given t))
17168 (when (< year 100) (setq year (+ 2000 year)))
17169 ;; Check of the date is representable
17170 (if org-read-date-force-compatible-dates
17171 (progn
17172 (when (< year 1970)
17173 (setq year 1970 org-read-date-analyze-forced-year t))
17174 (when (> year 2037)
17175 (setq year 2037 org-read-date-analyze-forced-year t)))
17176 (condition-case nil
17177 (ignore (encode-time second minute hour day month year))
17178 (error
17179 (setq year (nth 5 org-defdecode))
17180 (setq org-read-date-analyze-forced-year t))))
17181 (setq org-read-date-analyze-futurep futurep)
17182 (list second minute hour day month year)))
17184 (defvar parse-time-weekdays)
17185 (defun org-read-date-get-relative (s today default)
17186 "Check string S for special relative date string.
17187 TODAY and DEFAULT are internal times, for today and for a default.
17188 Return shift list (N what def-flag)
17189 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17190 N is the number of WHATs to shift.
17191 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17192 the DEFAULT date rather than TODAY."
17193 (require 'parse-time)
17194 (when (and
17195 (string-match
17196 (concat
17197 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17198 "\\([0-9]+\\)?"
17199 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17200 "\\([ \t]\\|$\\)") s)
17201 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17202 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17203 (string-to-char (substring (match-string 1 s) -1))
17204 ?+))
17205 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17206 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17207 (what (if (match-end 3) (match-string 3 s) "d"))
17208 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17209 (date (if rel default today))
17210 (wday (nth 6 (decode-time date)))
17211 delta)
17212 (if wday1
17213 (progn
17214 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17215 (when (= delta 0) (setq delta 7))
17216 (when (= dir ?-)
17217 (setq delta (- delta 7))
17218 (when (= delta 0) (setq delta -7)))
17219 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17220 (list delta "d" rel))
17221 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17223 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17224 "Turn a user-specified date into the internal representation.
17225 The internal representation needed by the calendar is (month day year).
17226 This is a wrapper to handle the brain-dead convention in calendar that
17227 user function argument order change dependent on argument order."
17228 (pcase calendar-date-style
17229 (`american (list arg1 arg2 arg3))
17230 (`european (list arg2 arg1 arg3))
17231 (`iso (list arg2 arg3 arg1))))
17233 (defun org-eval-in-calendar (form &optional keepdate)
17234 "Eval FORM in the calendar window and return to current window.
17235 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17236 (let ((sf (selected-frame))
17237 (sw (selected-window)))
17238 (select-window (get-buffer-window "*Calendar*" t))
17239 (eval form)
17240 (when (and (not keepdate) (calendar-cursor-to-date))
17241 (let* ((date (calendar-cursor-to-date))
17242 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17243 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17244 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17245 (select-window sw)
17246 (select-frame-set-input-focus sf)))
17248 (defun org-calendar-select ()
17249 "Return to `org-read-date' with the date currently selected.
17250 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17251 (interactive)
17252 (when (calendar-cursor-to-date)
17253 (let* ((date (calendar-cursor-to-date))
17254 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17255 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17256 (when (active-minibuffer-window) (exit-minibuffer))))
17258 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17259 "Insert a date stamp for the date given by the internal TIME.
17260 See `format-time-string' for the format of TIME.
17261 WITH-HM means use the stamp format that includes the time of the day.
17262 INACTIVE means use square brackets instead of angular ones, so that the
17263 stamp will not contribute to the agenda.
17264 PRE and POST are optional strings to be inserted before and after the
17265 stamp.
17266 The command returns the inserted time stamp."
17267 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17268 stamp)
17269 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17270 (insert-before-markers (or pre ""))
17271 (when (listp extra)
17272 (setq extra (car extra))
17273 (if (and (stringp extra)
17274 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17275 (setq extra (format "-%02d:%02d"
17276 (string-to-number (match-string 1 extra))
17277 (string-to-number (match-string 2 extra))))
17278 (setq extra nil)))
17279 (when extra
17280 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17281 (insert-before-markers (setq stamp (format-time-string fmt time)))
17282 (insert-before-markers (or post ""))
17283 (setq org-last-inserted-timestamp stamp)))
17285 (defun org-toggle-time-stamp-overlays ()
17286 "Toggle the use of custom time stamp formats."
17287 (interactive)
17288 (setq org-display-custom-times (not org-display-custom-times))
17289 (unless org-display-custom-times
17290 (let ((p (point-min)) (bmp (buffer-modified-p)))
17291 (while (setq p (next-single-property-change p 'display))
17292 (when (and (get-text-property p 'display)
17293 (eq (get-text-property p 'face) 'org-date))
17294 (remove-text-properties
17295 p (setq p (next-single-property-change p 'display))
17296 '(display t))))
17297 (set-buffer-modified-p bmp)))
17298 (org-restart-font-lock)
17299 (setq org-table-may-need-update t)
17300 (if org-display-custom-times
17301 (message "Time stamps are overlaid with custom format")
17302 (message "Time stamp overlays removed")))
17304 (defun org-display-custom-time (beg end)
17305 "Overlay modified time stamp format over timestamp between BEG and END."
17306 (let* ((ts (buffer-substring beg end))
17307 t1 w1 with-hm tf time str w2 (off 0))
17308 (save-match-data
17309 (setq t1 (org-parse-time-string ts t))
17310 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17311 (setq off (- (match-end 0) (match-beginning 0)))))
17312 (setq end (- end off))
17313 (setq w1 (- end beg)
17314 with-hm (and (nth 1 t1) (nth 2 t1))
17315 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17316 time (org-fix-decoded-time t1)
17317 str (org-add-props
17318 (format-time-string
17319 (substring tf 1 -1) (apply 'encode-time time))
17320 nil 'mouse-face 'highlight)
17321 w2 (length str))
17322 (unless (= w2 w1)
17323 (add-text-properties (1+ beg) (+ 2 beg)
17324 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17325 (put-text-property beg end 'display str)))
17327 (defun org-fix-decoded-time (time)
17328 "Set 0 instead of nil for the first 6 elements of time.
17329 Don't touch the rest."
17330 (let ((n 0))
17331 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17333 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17334 "Difference between TIMESTAMP-STRING and now in days.
17335 If SECONDS is non-nil, return the difference in seconds."
17336 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17337 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17338 (funcall fdiff (current-time)))))
17340 (defun org-deadline-close-p (timestamp-string &optional ndays)
17341 "Is the time in TIMESTAMP-STRING close to the current date?"
17342 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17343 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17344 (not (org-entry-is-done-p))))
17346 (defun org-get-wdays (ts &optional delay zero-delay)
17347 "Get the deadline lead time appropriate for timestring TS.
17348 When DELAY is non-nil, get the delay time for scheduled items
17349 instead of the deadline lead time. When ZERO-DELAY is non-nil
17350 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17351 don't try to find the delay cookie in the scheduled timestamp."
17352 (let ((tv (if delay org-scheduled-delay-days
17353 org-deadline-warning-days)))
17354 (cond
17355 ((or (and delay (< tv 0))
17356 (and delay zero-delay (<= tv 0))
17357 (and (not delay) (<= tv 0)))
17358 ;; Enforce this value no matter what
17359 (- tv))
17360 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17361 ;; lead time is specified.
17362 (floor (* (string-to-number (match-string 1 ts))
17363 (cdr (assoc (match-string 2 ts)
17364 '(("d" . 1) ("w" . 7)
17365 ("m" . 30.4) ("y" . 365.25)
17366 ("h" . 0.041667)))))))
17367 ;; go for the default.
17368 (t tv))))
17370 (defun org-calendar-select-mouse (ev)
17371 "Return to `org-read-date' with the date currently selected.
17372 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17373 (interactive "e")
17374 (mouse-set-point ev)
17375 (when (calendar-cursor-to-date)
17376 (let* ((date (calendar-cursor-to-date))
17377 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17378 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17379 (when (active-minibuffer-window) (exit-minibuffer))))
17381 (defun org-check-deadlines (ndays)
17382 "Check if there are any deadlines due or past due.
17383 A deadline is considered due if it happens within `org-deadline-warning-days'
17384 days from today's date. If the deadline appears in an entry marked DONE,
17385 it is not shown. A numeric prefix argument NDAYS can be used to test that
17386 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17387 are shown."
17388 (interactive "P")
17389 (let* ((org-warn-days
17390 (cond
17391 ((equal ndays '(4)) 100000)
17392 (ndays (prefix-numeric-value ndays))
17393 (t (abs org-deadline-warning-days))))
17394 (case-fold-search nil)
17395 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17396 (callback
17397 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17398 (message "%d deadlines past-due or due within %d days"
17399 (org-occur regexp nil callback)
17400 org-warn-days)))
17402 (defsubst org-re-timestamp (type)
17403 "Return a regexp for timestamp TYPE.
17404 Allowed values for TYPE are:
17406 all: all timestamps
17407 active: only active timestamps (<...>)
17408 inactive: only inactive timestamps ([...])
17409 scheduled: only scheduled timestamps
17410 deadline: only deadline timestamps
17411 closed: only closed time-stamps
17413 When TYPE is nil, fall back on returning a regexp that matches
17414 both scheduled and deadline timestamps."
17415 (cl-case type
17416 (all org-ts-regexp-both)
17417 (active org-ts-regexp)
17418 (inactive org-ts-regexp-inactive)
17419 (scheduled org-scheduled-time-regexp)
17420 (deadline org-deadline-time-regexp)
17421 (closed org-closed-time-regexp)
17422 (otherwise
17423 (concat "\\<"
17424 (regexp-opt (list org-deadline-string org-scheduled-string))
17425 " *<\\([^>]+\\)>"))))
17427 (defun org-check-before-date (d)
17428 "Check if there are deadlines or scheduled entries before date D."
17429 (interactive (list (org-read-date)))
17430 (let* ((case-fold-search nil)
17431 (regexp (org-re-timestamp org-ts-type))
17432 (ts-type org-ts-type)
17433 (callback
17434 (lambda ()
17435 (let ((match (match-string 1)))
17436 (and (if (memq ts-type '(active inactive all))
17437 (eq (org-element-type (save-excursion
17438 (backward-char)
17439 (org-element-context)))
17440 'timestamp)
17441 (org-at-planning-p))
17442 (time-less-p
17443 (org-time-string-to-time match)
17444 (org-time-string-to-time d)))))))
17445 (message "%d entries before %s"
17446 (org-occur regexp nil callback)
17447 d)))
17449 (defun org-check-after-date (d)
17450 "Check if there are deadlines or scheduled entries after date D."
17451 (interactive (list (org-read-date)))
17452 (let* ((case-fold-search nil)
17453 (regexp (org-re-timestamp org-ts-type))
17454 (ts-type org-ts-type)
17455 (callback
17456 (lambda ()
17457 (let ((match (match-string 1)))
17458 (and (if (memq ts-type '(active inactive all))
17459 (eq (org-element-type (save-excursion
17460 (backward-char)
17461 (org-element-context)))
17462 'timestamp)
17463 (org-at-planning-p))
17464 (not (time-less-p
17465 (org-time-string-to-time match)
17466 (org-time-string-to-time d))))))))
17467 (message "%d entries after %s"
17468 (org-occur regexp nil callback)
17469 d)))
17471 (defun org-check-dates-range (start-date end-date)
17472 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17473 (interactive (list (org-read-date nil nil nil "Range starts")
17474 (org-read-date nil nil nil "Range end")))
17475 (let ((case-fold-search nil)
17476 (regexp (org-re-timestamp org-ts-type))
17477 (callback
17478 (let ((type org-ts-type))
17479 (lambda ()
17480 (let ((match (match-string 1)))
17481 (and
17482 (if (memq type '(active inactive all))
17483 (eq (org-element-type (save-excursion
17484 (backward-char)
17485 (org-element-context)))
17486 'timestamp)
17487 (org-at-planning-p))
17488 (not (time-less-p
17489 (org-time-string-to-time match)
17490 (org-time-string-to-time start-date)))
17491 (time-less-p
17492 (org-time-string-to-time match)
17493 (org-time-string-to-time end-date))))))))
17494 (message "%d entries between %s and %s"
17495 (org-occur regexp nil callback) start-date end-date)))
17497 (defun org-evaluate-time-range (&optional to-buffer)
17498 "Evaluate a time range by computing the difference between start and end.
17499 Normally the result is just printed in the echo area, but with prefix arg
17500 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17501 If the time range is actually in a table, the result is inserted into the
17502 next column.
17503 For time difference computation, a year is assumed to be exactly 365
17504 days in order to avoid rounding problems."
17505 (interactive "P")
17507 (org-clock-update-time-maybe)
17508 (save-excursion
17509 (unless (org-at-date-range-p t)
17510 (goto-char (point-at-bol))
17511 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17512 (unless (org-at-date-range-p t)
17513 (user-error "Not at a time-stamp range, and none found in current line")))
17514 (let* ((ts1 (match-string 1))
17515 (ts2 (match-string 2))
17516 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17517 (match-end (match-end 0))
17518 (time1 (org-time-string-to-time ts1))
17519 (time2 (org-time-string-to-time ts2))
17520 (t1 (float-time time1))
17521 (t2 (float-time time2))
17522 (diff (abs (- t2 t1)))
17523 (negative (< (- t2 t1) 0))
17524 ;; (ys (floor (* 365 24 60 60)))
17525 (ds (* 24 60 60))
17526 (hs (* 60 60))
17527 (fy "%dy %dd %02d:%02d")
17528 (fy1 "%dy %dd")
17529 (fd "%dd %02d:%02d")
17530 (fd1 "%dd")
17531 (fh "%02d:%02d")
17532 y d h m align)
17533 (if havetime
17534 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17536 d (floor (/ diff ds)) diff (mod diff ds)
17537 h (floor (/ diff hs)) diff (mod diff hs)
17538 m (floor (/ diff 60)))
17539 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17541 d (floor (+ (/ diff ds) 0.5))
17542 h 0 m 0))
17543 (if (not to-buffer)
17544 (message "%s" (org-make-tdiff-string y d h m))
17545 (if (org-at-table-p)
17546 (progn
17547 (goto-char match-end)
17548 (setq align t)
17549 (and (looking-at " *|") (goto-char (match-end 0))))
17550 (goto-char match-end))
17551 (when (looking-at
17552 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17553 (replace-match ""))
17554 (when negative (insert " -"))
17555 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17556 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17557 (insert " " (format fh h m))))
17558 (when align (org-table-align))
17559 (message "Time difference inserted")))))
17561 (defun org-make-tdiff-string (y d h m)
17562 (let ((fmt "")
17563 (l nil))
17564 (when (> y 0)
17565 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17566 (push y l))
17567 (when (> d 0)
17568 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17569 (push d l))
17570 (when (> h 0)
17571 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17572 (push h l))
17573 (when (> m 0)
17574 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17575 (push m l))
17576 (apply 'format fmt (nreverse l))))
17578 (defun org-time-string-to-time (s &optional buffer pos)
17579 "Convert a timestamp string into internal time."
17580 (condition-case errdata
17581 (apply 'encode-time (org-parse-time-string s))
17582 (error (error "Bad timestamp `%s'%s\nError was: %s"
17583 s (if (not (and buffer pos))
17585 (format-message " at %d in buffer `%s'" pos buffer))
17586 (cdr errdata)))))
17588 (defun org-time-string-to-seconds (s)
17589 "Convert a timestamp string to a number of seconds."
17590 (float-time (org-time-string-to-time s)))
17592 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17594 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17595 "Convert time stamp S to an absolute day number.
17597 If DAYNR in non-nil, and there is a specifier for a cyclic time
17598 stamp, get the closest date to DAYNR. If PREFER is
17599 `past' (respectively `future') return a date past (respectively
17600 after) or equal to DAYNR.
17602 POS is the location of time stamp S, as a buffer position in
17603 BUFFER.
17605 Diary sexp timestamps are matched against DAYNR, when non-nil.
17606 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17607 signalled."
17608 (cond
17609 ((string-match "\\`%%\\((.*)\\)" s)
17610 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17611 ;; only able to match individual dates. If it fails, raise an
17612 ;; error.
17613 (if (and daynr
17614 (org-diary-sexp-entry
17615 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17616 daynr
17617 (signal 'org-diary-sexp-no-match (list s))))
17618 (daynr (org-closest-date s daynr prefer))
17619 (t (time-to-days
17620 (condition-case errdata
17621 (apply #'encode-time (org-parse-time-string s))
17622 (error (error "Bad timestamp `%s'%s\nError was: %s"
17624 (if (not (and buffer pos)) ""
17625 (format-message " at %d in buffer `%s'" pos buffer))
17626 (cdr errdata))))))))
17628 (defun org-days-to-iso-week (days)
17629 "Return the iso week number."
17630 (require 'cal-iso)
17631 (car (calendar-iso-from-absolute days)))
17633 (defun org-small-year-to-year (year)
17634 "Convert 2-digit years into 4-digit years.
17635 YEAR is expanded into one of the 30 next years, if possible, or
17636 into a past one. Any year larger than 99 is returned unchanged."
17637 (if (>= year 100) year
17638 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17639 (century (/ current 100))
17640 (offset (- year (% current 100))))
17641 (cond ((> offset 30) (+ (* (1- century) 100) year))
17642 ((> offset -70) (+ (* century 100) year))
17643 (t (+ (* (1+ century) 100) year))))))
17645 (defun org-time-from-absolute (d)
17646 "Return the time corresponding to date D.
17647 D may be an absolute day number, or a calendar-type list (month day year)."
17648 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17649 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17651 (defvar org-agenda-current-date)
17652 (defun org-calendar-holiday ()
17653 "List of holidays, for Diary display in Org mode."
17654 (require 'holidays)
17655 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17656 (and hl (mapconcat #'identity hl "; "))))
17658 (defun org-diary-sexp-entry (sexp entry d)
17659 "Process a SEXP diary ENTRY for date D."
17660 (require 'diary-lib)
17661 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17662 ;; dynamically.
17663 (let* ((sexp `(let ((entry ,entry)
17664 (date ',d))
17665 ,(car (read-from-string sexp))))
17666 (result (if calendar-debug-sexp (eval sexp)
17667 (condition-case nil
17668 (eval sexp)
17669 (error
17670 (beep)
17671 (message "Bad sexp at line %d in %s: %s"
17672 (org-current-line)
17673 (buffer-file-name) sexp)
17674 (sleep-for 2))))))
17675 (cond ((stringp result) (split-string result "; "))
17676 ((and (consp result)
17677 (not (consp (cdr result)))
17678 (stringp (cdr result))) (cdr result))
17679 ((and (consp result)
17680 (stringp (car result))) result)
17681 (result entry))))
17683 (defun org-diary-to-ical-string (frombuf)
17684 "Get iCalendar entries from diary entries in buffer FROMBUF.
17685 This uses the icalendar.el library."
17686 (let* ((tmpdir temporary-file-directory)
17687 (tmpfile (make-temp-name
17688 (expand-file-name "orgics" tmpdir)))
17689 buf rtn b e)
17690 (with-current-buffer frombuf
17691 (icalendar-export-region (point-min) (point-max) tmpfile)
17692 (setq buf (find-buffer-visiting tmpfile))
17693 (set-buffer buf)
17694 (goto-char (point-min))
17695 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17696 (setq b (match-beginning 0)))
17697 (goto-char (point-max))
17698 (when (re-search-backward "^END:VEVENT" nil t)
17699 (setq e (match-end 0)))
17700 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17701 (kill-buffer buf)
17702 (delete-file tmpfile)
17703 rtn))
17705 (defun org-closest-date (start current prefer)
17706 "Return closest date to CURRENT starting from START.
17708 CURRENT and START are both time stamps.
17710 When PREFER is `past', return a date that is either CURRENT or
17711 past. When PREFER is `future', return a date that is either
17712 CURRENT or future.
17714 Only time stamps with a repeater are modified. Any other time
17715 stamp stay unchanged. In any case, return value is an absolute
17716 day number."
17717 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17718 ;; No repeater. Do not shift time stamp.
17719 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17720 (let ((value (string-to-number (match-string 1 start)))
17721 (type (match-string 2 start)))
17722 (if (= 0 value)
17723 ;; Repeater with a 0-value is considered as void.
17724 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17725 (let* ((base (org-date-to-gregorian start))
17726 (target (org-date-to-gregorian current))
17727 (sday (calendar-absolute-from-gregorian base))
17728 (cday (calendar-absolute-from-gregorian target))
17729 n1 n2)
17730 ;; If START is already past CURRENT, just return START.
17731 (if (<= cday sday) sday
17732 ;; Compute closest date before (N1) and closest date past
17733 ;; (N2) CURRENT.
17734 (pcase type
17735 ("h"
17736 (let ((missing-hours
17737 (mod (+ (- (* 24 (- cday sday))
17738 (nth 2 (org-parse-time-string start)))
17739 org-extend-today-until)
17740 value)))
17741 (setf n1 (if (= missing-hours 0) cday
17742 (- cday (1+ (/ missing-hours 24)))))
17743 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17744 ((or "d" "w")
17745 (let ((value (if (equal type "w") (* 7 value) value)))
17746 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17747 (setf n2 (+ n1 value))))
17748 ("m"
17749 (let* ((add-months
17750 (lambda (d n)
17751 ;; Add N months to gregorian date D, i.e.,
17752 ;; a list (MONTH DAY YEAR). Return a valid
17753 ;; gregorian date.
17754 (let ((m (+ (nth 0 d) n)))
17755 (list (mod m 12)
17756 (nth 1 d)
17757 (+ (/ m 12) (nth 2 d))))))
17758 (months ; Complete months to TARGET.
17759 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17760 (- (nth 0 target) (nth 0 base))
17761 ;; If START's day is greater than
17762 ;; TARGET's, remove incomplete month.
17763 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17764 value)
17765 value))
17766 (before (funcall add-months base months)))
17767 (setf n1 (calendar-absolute-from-gregorian before))
17768 (setf n2
17769 (calendar-absolute-from-gregorian
17770 (funcall add-months before value)))))
17772 (let* ((d (nth 1 base))
17773 (m (nth 0 base))
17774 (y (nth 2 base))
17775 (years ; Complete years to TARGET.
17776 (* (/ (- (nth 2 target)
17778 ;; If START's month and day are
17779 ;; greater than TARGET's, remove
17780 ;; incomplete year.
17781 (if (or (> (nth 0 target) m)
17782 (and (= (nth 0 target) m)
17783 (> (nth 1 target) d)))
17786 value)
17787 value))
17788 (before (list m d (+ y years))))
17789 (setf n1 (calendar-absolute-from-gregorian before))
17790 (setf n2 (calendar-absolute-from-gregorian
17791 (list m d (+ (nth 2 before) value)))))))
17792 ;; Handle PREFER parameter, if any.
17793 (cond
17794 ((eq prefer 'past) (if (= cday n2) n2 n1))
17795 ((eq prefer 'future) (if (= cday n1) n1 n2))
17796 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17798 (defun org-date-to-gregorian (d)
17799 "Turn any specification of date D into a Gregorian date for the calendar."
17800 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17801 ((and (listp d) (= (length d) 3)) d)
17802 ((stringp d)
17803 (let ((d (org-parse-time-string d)))
17804 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17805 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17807 (defun org-parse-time-string (s &optional nodefault zone)
17808 "Parse the standard Org time string.
17810 This should be a lot faster than the normal `parse-time-string'.
17812 If time is not given, defaults to 0:00. However, with optional
17813 NODEFAULT, hour and minute fields will be nil if not given.
17815 The optional ZONE is omitted or nil for Emacs local time, t for
17816 Universal Time, ‘wall’ for system wall clock time, or a string as
17817 in the TZ environment variable."
17818 (cond ((string-match org-ts-regexp0 s)
17819 (list 0
17820 (when (or (match-beginning 8) (not nodefault))
17821 (string-to-number (or (match-string 8 s) "0")))
17822 (when (or (match-beginning 7) (not nodefault))
17823 (string-to-number (or (match-string 7 s) "0")))
17824 (string-to-number (match-string 4 s))
17825 (string-to-number (match-string 3 s))
17826 (string-to-number (match-string 2 s))
17827 nil nil zone))
17828 ((string-match "^<[^>]+>$" s)
17829 ;; FIXME: `decode-time' needs to be called with ZONE as its
17830 ;; second argument. However, this requires at least Emacs
17831 ;; 25.1. We can do it when we switch to this version as our
17832 ;; minimal requirement.
17833 (decode-time (seconds-to-time (org-matcher-time s))))
17834 (t (error "Not a standard Org time string: %s" s))))
17836 (defun org-timestamp-up (&optional arg)
17837 "Increase the date item at the cursor by one.
17838 If the cursor is on the year, change the year. If it is on the month,
17839 the day or the time, change that.
17840 With prefix ARG, change by that many units."
17841 (interactive "p")
17842 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17844 (defun org-timestamp-down (&optional arg)
17845 "Decrease the date item at the cursor by one.
17846 If the cursor is on the year, change the year. If it is on the month,
17847 the day or the time, change that.
17848 With prefix ARG, change by that many units."
17849 (interactive "p")
17850 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17852 (defun org-timestamp-up-day (&optional arg)
17853 "Increase the date in the time stamp by one day.
17854 With prefix ARG, change that many days."
17855 (interactive "p")
17856 (if (and (not (org-at-timestamp-p 'lax))
17857 (org-at-heading-p))
17858 (org-todo 'up)
17859 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17861 (defun org-timestamp-down-day (&optional arg)
17862 "Decrease the date in the time stamp by one day.
17863 With prefix ARG, change that many days."
17864 (interactive "p")
17865 (if (and (not (org-at-timestamp-p 'lax))
17866 (org-at-heading-p))
17867 (org-todo 'down)
17868 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17870 (defun org-at-timestamp-p (&optional extended)
17871 "Non-nil if point is inside a timestamp.
17873 By default, the function only consider syntactically valid active
17874 timestamps. However, the caller may have a broader definition
17875 for timestamps. As a consequence, optional argument EXTENDED can
17876 be set to the following values
17878 `inactive'
17880 Include also syntactically valid inactive timestamps.
17882 `agenda'
17884 Include timestamps allowed in Agenda, i.e., those in
17885 properties drawers, planning lines and clock lines.
17887 `lax'
17889 Ignore context. The function matches any part of the
17890 document looking like a timestamp. This includes comments,
17891 example blocks...
17893 For backward-compatibility with Org 9.0, every other non-nil
17894 value is equivalent to `inactive'.
17896 When at a timestamp, return the position of the point as a symbol
17897 among `bracket', `after', `year', `month', `hour', `minute',
17898 `day' or a number of character from the last know part of the
17899 time stamp.
17901 When matching, the match groups are the following:
17902 group 1: year
17903 group 2: month
17904 group 3: day number
17905 group 4: day name
17906 group 5: hours, if any
17907 group 6: minutes, if any"
17908 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17909 (pos (point))
17910 (match?
17911 (let ((boundaries (org-in-regexp regexp)))
17912 (save-match-data
17913 (cond ((null boundaries) nil)
17914 ((eq extended 'lax) t)
17916 (or (and (eq extended 'agenda)
17917 (or (org-at-planning-p)
17918 (org-at-property-p)
17919 (and (bound-and-true-p
17920 org-agenda-include-inactive-timestamps)
17921 (org-at-clock-log-p))))
17922 (eq 'timestamp
17923 (save-excursion
17924 (when (= pos (cdr boundaries)) (forward-char -1))
17925 (org-element-type (org-element-context)))))))))))
17926 (cond
17927 ((not match?) nil)
17928 ((= pos (match-beginning 0)) 'bracket)
17929 ;; Distinguish location right before the closing bracket from
17930 ;; right after it.
17931 ((= pos (1- (match-end 0))) 'bracket)
17932 ((= pos (match-end 0)) 'after)
17933 ((org-pos-in-match-range pos 2) 'year)
17934 ((org-pos-in-match-range pos 3) 'month)
17935 ((org-pos-in-match-range pos 7) 'hour)
17936 ((org-pos-in-match-range pos 8) 'minute)
17937 ((or (org-pos-in-match-range pos 4)
17938 (org-pos-in-match-range pos 5)) 'day)
17939 ((and (> pos (or (match-end 8) (match-end 5)))
17940 (< pos (match-end 0)))
17941 (- pos (or (match-end 8) (match-end 5))))
17942 (t 'day))))
17944 (defun org-toggle-timestamp-type ()
17945 "Toggle the type (<active> or [inactive]) of a time stamp."
17946 (interactive)
17947 (when (org-at-timestamp-p 'lax)
17948 (let ((beg (match-beginning 0)) (end (match-end 0))
17949 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17950 (save-excursion
17951 (goto-char beg)
17952 (while (re-search-forward "[][<>]" end t)
17953 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17954 t t)))
17955 (message "Timestamp is now %sactive"
17956 (if (equal (char-after beg) ?<) "" "in")))))
17958 (defun org-at-clock-log-p ()
17959 "Non-nil if point is on a clock log line."
17960 (and (org-match-line org-clock-line-re)
17961 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17963 (defvar org-clock-history) ; defined in org-clock.el
17964 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17965 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17966 "Change the date in the time stamp at point.
17967 The date will be changed by N times WHAT. WHAT can be `day', `month',
17968 `year', `minute', `second'. If WHAT is not given, the cursor position
17969 in the timestamp determines what will be changed.
17970 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17971 (let ((origin (point))
17972 (timestamp? (org-at-timestamp-p 'lax))
17973 origin-cat
17974 with-hm inactive
17975 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17976 extra rem
17977 ts time time0 fixnext clrgx)
17978 (unless timestamp? (user-error "Not at a timestamp"))
17979 (if (and (not what) (eq timestamp? 'bracket))
17980 (org-toggle-timestamp-type)
17981 ;; Point isn't on brackets. Remember the part of the time-stamp
17982 ;; the point was in. Indeed, size of time-stamps may change,
17983 ;; but point must be kept in the same category nonetheless.
17984 (setq origin-cat timestamp?)
17985 (when (and (not what) (not (eq timestamp? 'day))
17986 org-display-custom-times
17987 (get-text-property (point) 'display)
17988 (not (get-text-property (1- (point)) 'display)))
17989 (setq timestamp? 'day))
17990 (setq timestamp? (or what timestamp?)
17991 inactive (= (char-after (match-beginning 0)) ?\[)
17992 ts (match-string 0))
17993 (replace-match "")
17994 (when (string-match
17995 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17997 (setq extra (match-string 1 ts))
17998 (when suppress-tmp-delay
17999 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18000 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18001 (setq with-hm t))
18002 (setq time0 (org-parse-time-string ts))
18003 (when (and updown
18004 (eq timestamp? 'minute)
18005 (not current-prefix-arg))
18006 ;; This looks like s-up and s-down. Change by one rounding step.
18007 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18008 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18009 (setcar (cdr time0) (+ (nth 1 time0)
18010 (if (> n 0) (- rem) (- dm rem))))))
18011 (setq time
18012 (apply #'encode-time
18013 (or (car time0) 0)
18014 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
18015 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
18016 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18017 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18018 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18019 (nthcdr 6 time0)))
18020 (when (and (memq timestamp? '(hour minute))
18021 extra
18022 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18023 (setq extra (org-modify-ts-extra
18024 extra
18025 (if (eq timestamp? 'hour) 2 5)
18026 n dm)))
18027 (when (integerp timestamp?)
18028 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18029 (when (eq what 'calendar)
18030 (let ((cal-date (org-get-date-from-calendar)))
18031 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18032 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18033 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18034 (setcar time0 (or (car time0) 0))
18035 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18036 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18037 (setq time (apply 'encode-time time0))))
18038 ;; Insert the new time-stamp, and ensure point stays in the same
18039 ;; category as before (i.e. not after the last position in that
18040 ;; category).
18041 (let ((pos (point)))
18042 ;; Stay before inserted string. `save-excursion' is of no use.
18043 (setq org-last-changed-timestamp
18044 (org-insert-time-stamp time with-hm inactive nil nil extra))
18045 (goto-char pos))
18046 (save-match-data
18047 (looking-at org-ts-regexp3)
18048 (goto-char
18049 (pcase origin-cat
18050 ;; `day' category ends before `hour' if any, or at the end
18051 ;; of the day name.
18052 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18053 (`hour (min (match-end 7) origin))
18054 (`minute (min (1- (match-end 8)) origin))
18055 ((pred integerp) (min (1- (match-end 0)) origin))
18056 ;; Point was right after the time-stamp. However, the
18057 ;; time-stamp length might have changed, so refer to
18058 ;; (match-end 0) instead.
18059 (`after (match-end 0))
18060 ;; `year' and `month' have both fixed size: point couldn't
18061 ;; have moved into another part.
18062 (_ origin))))
18063 ;; Update clock if on a CLOCK line.
18064 (org-clock-update-time-maybe)
18065 ;; Maybe adjust the closest clock in `org-clock-history'
18066 (when org-clock-adjust-closest
18067 (if (not (and (org-at-clock-log-p)
18068 (< 1 (length (delq nil (mapcar 'marker-position
18069 org-clock-history))))))
18070 (message "No clock to adjust")
18071 (cond ((save-excursion ; fix previous clock?
18072 (re-search-backward org-ts-regexp0 nil t)
18073 (looking-back (concat org-clock-string " \\[")
18074 (line-beginning-position)))
18075 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18076 ((save-excursion ; fix next clock?
18077 (re-search-backward org-ts-regexp0 nil t)
18078 (looking-at (concat org-ts-regexp0 "\\] =>")))
18079 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18080 (save-window-excursion
18081 ;; Find closest clock to point, adjust the previous/next one in history
18082 (let* ((p (save-excursion (org-back-to-heading t)))
18083 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18084 (clfixnth
18085 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18086 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18087 (if (not clfixpos)
18088 (message "No clock to adjust")
18089 (save-excursion
18090 (org-goto-marker-or-bmk clfixpos)
18091 (org-show-subtree)
18092 (when (re-search-forward clrgx nil t)
18093 (goto-char (match-beginning 1))
18094 (let (org-clock-adjust-closest)
18095 (org-timestamp-change n timestamp? updown))
18096 (message "Clock adjusted in %s for heading: %s"
18097 (file-name-nondirectory (buffer-file-name))
18098 (org-get-heading t t)))))))))
18099 ;; Try to recenter the calendar window, if any.
18100 (when (and org-calendar-follow-timestamp-change
18101 (get-buffer-window "*Calendar*" t)
18102 (memq timestamp? '(day month year)))
18103 (org-recenter-calendar (time-to-days time))))))
18105 (defun org-modify-ts-extra (s pos n dm)
18106 "Change the different parts of the lead-time and repeat fields in timestamp."
18107 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18108 ng h m new rem)
18109 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18110 (cond
18111 ((or (org-pos-in-match-range pos 2)
18112 (org-pos-in-match-range pos 3))
18113 (setq m (string-to-number (match-string 3 s))
18114 h (string-to-number (match-string 2 s)))
18115 (if (org-pos-in-match-range pos 2)
18116 (setq h (+ h n))
18117 (setq n (* dm (with-no-warnings (signum n))))
18118 (unless (= 0 (setq rem (% m dm)))
18119 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18120 (setq m (+ m n)))
18121 (when (< m 0) (setq m (+ m 60) h (1- h)))
18122 (when (> m 59) (setq m (- m 60) h (1+ h)))
18123 (setq h (mod h 24))
18124 (setq ng 1 new (format "-%02d:%02d" h m)))
18125 ((org-pos-in-match-range pos 6)
18126 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18127 ((org-pos-in-match-range pos 5)
18128 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18130 ((org-pos-in-match-range pos 9)
18131 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18132 ((org-pos-in-match-range pos 8)
18133 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18135 (when ng
18136 (setq s (concat
18137 (substring s 0 (match-beginning ng))
18139 (substring s (match-end ng))))))
18142 (defun org-recenter-calendar (d)
18143 "If the calendar is visible, recenter it to date D."
18144 (let ((cwin (get-buffer-window "*Calendar*" t)))
18145 (when cwin
18146 (let ((calendar-move-hook nil))
18147 (with-selected-window cwin
18148 (calendar-goto-date
18149 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18151 (defun org-goto-calendar (&optional arg)
18152 "Go to the Emacs calendar at the current date.
18153 If there is a time stamp in the current line, go to that date.
18154 A prefix ARG can be used to force the current date."
18155 (interactive "P")
18156 (let ((calendar-move-hook nil)
18157 (calendar-view-holidays-initially-flag nil)
18158 (calendar-view-diary-initially-flag nil)
18159 diff)
18160 (when (or (org-at-timestamp-p 'lax)
18161 (org-match-line (concat ".*" org-ts-regexp)))
18162 (let ((d1 (time-to-days (current-time)))
18163 (d2 (time-to-days
18164 (org-time-string-to-time (match-string 1)))))
18165 (setq diff (- d2 d1))))
18166 (calendar)
18167 (calendar-goto-today)
18168 (when (and diff (not arg)) (calendar-forward-day diff))))
18170 (defun org-get-date-from-calendar ()
18171 "Return a list (month day year) of date at point in calendar."
18172 (with-current-buffer "*Calendar*"
18173 (save-match-data
18174 (calendar-cursor-to-date))))
18176 (defun org-date-from-calendar ()
18177 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18178 If there is already a time stamp at the cursor position, update it."
18179 (interactive)
18180 (if (org-at-timestamp-p 'lax)
18181 (org-timestamp-change 0 'calendar)
18182 (let ((cal-date (org-get-date-from-calendar)))
18183 (org-insert-time-stamp
18184 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18186 (defcustom org-effort-durations
18187 `(("min" . 1)
18188 ("h" . 60)
18189 ("d" . ,(* 60 8))
18190 ("w" . ,(* 60 8 5))
18191 ("m" . ,(* 60 8 5 4))
18192 ("y" . ,(* 60 8 5 40)))
18193 "Conversion factor to minutes for an effort modifier.
18195 Each entry has the form (MODIFIER . MINUTES).
18197 In an effort string, a number followed by MODIFIER is multiplied
18198 by the specified number of MINUTES to obtain an effort in
18199 minutes.
18201 For example, if the value of this variable is ((\"hours\" . 60)), then an
18202 effort string \"2hours\" is equivalent to 120 minutes."
18203 :group 'org-agenda
18204 :version "26.1"
18205 :package-version '(Org . "8.3")
18206 :type '(alist :key-type (string :tag "Modifier")
18207 :value-type (number :tag "Minutes")))
18209 (defcustom org-image-actual-width t
18210 "Should we use the actual width of images when inlining them?
18212 When set to t, always use the image width.
18214 When set to a number, use imagemagick (when available) to set
18215 the image's width to this value.
18217 When set to a number in a list, try to get the width from any
18218 #+ATTR.* keyword if it matches a width specification like
18220 #+ATTR_HTML: :width 300px
18222 and fall back on that number if none is found.
18224 When set to nil, try to get the width from an #+ATTR.* keyword
18225 and fall back on the original width if none is found.
18227 This requires Emacs >= 24.1, build with imagemagick support."
18228 :group 'org-appearance
18229 :version "24.4"
18230 :package-version '(Org . "8.0")
18231 :type '(choice
18232 (const :tag "Use the image width" t)
18233 (integer :tag "Use a number of pixels")
18234 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18235 (const :tag "Use #+ATTR* or don't resize" nil)))
18237 (defcustom org-agenda-inhibit-startup nil
18238 "Inhibit startup when preparing agenda buffers.
18239 When this variable is t, the initialization of the Org agenda
18240 buffers is inhibited: e.g. the visibility state is not set, the
18241 tables are not re-aligned, etc."
18242 :type 'boolean
18243 :version "24.3"
18244 :group 'org-agenda)
18246 (defcustom org-agenda-ignore-properties nil
18247 "Avoid updating text properties when building the agenda.
18248 Properties are used to prepare buffers for effort estimates,
18249 appointments, statistics and subtree-local categories.
18250 If you don't use these in the agenda, you can add them to this
18251 list and agenda building will be a bit faster.
18252 The value is a list, with zero or more of the symbols `effort', `appt',
18253 `stats' or `category'."
18254 :type '(set :greedy t
18255 (const effort)
18256 (const appt)
18257 (const stats)
18258 (const category))
18259 :version "26.1"
18260 :package-version '(Org . "8.3")
18261 :group 'org-agenda)
18263 ;;;; Files
18265 (defun org-save-all-org-buffers ()
18266 "Save all Org buffers without user confirmation."
18267 (interactive)
18268 (message "Saving all Org buffers...")
18269 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18270 (when (featurep 'org-id) (org-id-locations-save))
18271 (message "Saving all Org buffers... done"))
18273 (defun org-revert-all-org-buffers ()
18274 "Revert all Org buffers.
18275 Prompt for confirmation when there are unsaved changes.
18276 Be sure you know what you are doing before letting this function
18277 overwrite your changes.
18279 This function is useful in a setup where one tracks org files
18280 with a version control system, to revert on one machine after pulling
18281 changes from another. I believe the procedure must be like this:
18283 1. M-x org-save-all-org-buffers
18284 2. Pull changes from the other machine, resolve conflicts
18285 3. M-x org-revert-all-org-buffers"
18286 (interactive)
18287 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18288 (user-error "Abort"))
18289 (save-excursion
18290 (save-window-excursion
18291 (dolist (b (buffer-list))
18292 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18293 (with-current-buffer b buffer-file-name))
18294 (pop-to-buffer-same-window b)
18295 (revert-buffer t 'no-confirm)))
18296 (when (and (featurep 'org-id) org-id-track-globally)
18297 (org-id-locations-load)))))
18299 ;;;; Agenda files
18301 ;;;###autoload
18302 (defun org-switchb (&optional arg)
18303 "Switch between Org buffers.
18305 With `\\[universal-argument]' prefix, restrict available buffers to files.
18307 With `\\[universal-argument] \\[universal-argument]' \
18308 prefix, restrict available buffers to agenda files."
18309 (interactive "P")
18310 (let ((blist (org-buffer-list
18311 (cond ((equal arg '(4)) 'files)
18312 ((equal arg '(16)) 'agenda)))))
18313 (pop-to-buffer-same-window
18314 (completing-read "Org buffer: "
18315 (mapcar #'list (mapcar #'buffer-name blist))
18316 nil t))))
18318 (defun org-buffer-list (&optional predicate exclude-tmp)
18319 "Return a list of Org buffers.
18320 PREDICATE can be `export', `files' or `agenda'.
18322 export restrict the list to Export buffers.
18323 files restrict the list to buffers visiting Org files.
18324 agenda restrict the list to buffers visiting agenda files.
18326 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18327 (let* ((bfn nil)
18328 (agenda-files (and (eq predicate 'agenda)
18329 (mapcar 'file-truename (org-agenda-files t))))
18330 (filter
18331 (cond
18332 ((eq predicate 'files)
18333 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18334 ((eq predicate 'export)
18335 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18336 ((eq predicate 'agenda)
18337 (lambda (b)
18338 (with-current-buffer b
18339 (and (derived-mode-p 'org-mode)
18340 (setq bfn (buffer-file-name b))
18341 (member (file-truename bfn) agenda-files)))))
18342 (t (lambda (b) (with-current-buffer b
18343 (or (derived-mode-p 'org-mode)
18344 (string-match "\\*Org .*Export"
18345 (buffer-name b)))))))))
18346 (delq nil
18347 (mapcar
18348 (lambda(b)
18349 (if (and (funcall filter b)
18350 (or (not exclude-tmp)
18351 (not (string-match "tmp" (buffer-name b)))))
18353 nil))
18354 (buffer-list)))))
18356 (defun org-agenda-files (&optional unrestricted archives)
18357 "Get the list of agenda files.
18358 Optional UNRESTRICTED means return the full list even if a restriction
18359 is currently in place.
18360 When ARCHIVES is t, include all archive files that are really being
18361 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18362 `org-agenda-archives-mode' is t."
18363 (let ((files
18364 (cond
18365 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18366 ((stringp org-agenda-files) (org-read-agenda-file-list))
18367 ((listp org-agenda-files) org-agenda-files)
18368 (t (error "Invalid value of `org-agenda-files'")))))
18369 (setq files (apply 'append
18370 (mapcar (lambda (f)
18371 (if (file-directory-p f)
18372 (directory-files
18373 f t org-agenda-file-regexp)
18374 (list f)))
18375 files)))
18376 (when org-agenda-skip-unavailable-files
18377 (setq files (delq nil
18378 (mapcar (function
18379 (lambda (file)
18380 (and (file-readable-p file) file)))
18381 files))))
18382 (when (or (eq archives t)
18383 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18384 (setq files (org-add-archive-files files)))
18385 files))
18387 (defun org-agenda-file-p (&optional file)
18388 "Return non-nil, if FILE is an agenda file.
18389 If FILE is omitted, use the file associated with the current
18390 buffer."
18391 (let ((fname (or file (buffer-file-name))))
18392 (and fname
18393 (member (file-truename fname)
18394 (mapcar #'file-truename (org-agenda-files t))))))
18396 (defun org-edit-agenda-file-list ()
18397 "Edit the list of agenda files.
18398 Depending on setup, this either uses customize to edit the variable
18399 `org-agenda-files', or it visits the file that is holding the list. In the
18400 latter case, the buffer is set up in a way that saving it automatically kills
18401 the buffer and restores the previous window configuration."
18402 (interactive)
18403 (if (stringp org-agenda-files)
18404 (let ((cw (current-window-configuration)))
18405 (find-file org-agenda-files)
18406 (setq-local org-window-configuration cw)
18407 (add-hook 'after-save-hook
18408 (lambda ()
18409 (set-window-configuration
18410 (prog1 org-window-configuration
18411 (kill-buffer (current-buffer))))
18412 (org-install-agenda-files-menu)
18413 (message "New agenda file list installed"))
18414 nil 'local)
18415 (message "%s" (substitute-command-keys
18416 "Edit list and finish with \\[save-buffer]")))
18417 (customize-variable 'org-agenda-files)))
18419 (defun org-store-new-agenda-file-list (list)
18420 "Set new value for the agenda file list and save it correctly."
18421 (if (stringp org-agenda-files)
18422 (let ((fe (org-read-agenda-file-list t)) b u)
18423 (while (setq b (find-buffer-visiting org-agenda-files))
18424 (kill-buffer b))
18425 (with-temp-file org-agenda-files
18426 (insert
18427 (mapconcat
18428 (lambda (f) ;; Keep un-expanded entries.
18429 (if (setq u (assoc f fe))
18430 (cdr u)
18432 list "\n")
18433 "\n")))
18434 (let ((org-mode-hook nil) (org-inhibit-startup t)
18435 (org-insert-mode-line-in-empty-file nil))
18436 (setq org-agenda-files list)
18437 (customize-save-variable 'org-agenda-files org-agenda-files))))
18439 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18440 "Read the list of agenda files from a file.
18441 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18442 filenames, used by `org-store-new-agenda-file-list' to write back
18443 un-expanded file names."
18444 (when (file-directory-p org-agenda-files)
18445 (error "`org-agenda-files' cannot be a single directory"))
18446 (when (stringp org-agenda-files)
18447 (with-temp-buffer
18448 (insert-file-contents org-agenda-files)
18449 (mapcar
18450 (lambda (f)
18451 (let ((e (expand-file-name (substitute-in-file-name f)
18452 org-directory)))
18453 (if pair-with-expansion
18454 (cons e f)
18455 e)))
18456 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18458 ;;;###autoload
18459 (defun org-cycle-agenda-files ()
18460 "Cycle through the files in `org-agenda-files'.
18461 If the current buffer visits an agenda file, find the next one in the list.
18462 If the current buffer does not, find the first agenda file."
18463 (interactive)
18464 (let* ((fs (or (org-agenda-files t)
18465 (user-error "No agenda files")))
18466 (files (copy-sequence fs))
18467 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18468 file)
18469 (when tcf
18470 (while (and (setq file (pop files))
18471 (not (equal (file-truename file) tcf)))))
18472 (find-file (car (or files fs)))
18473 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18475 (defun org-agenda-file-to-front (&optional to-end)
18476 "Move/add the current file to the top of the agenda file list.
18477 If the file is not present in the list, it is added to the front. If it is
18478 present, it is moved there. With optional argument TO-END, add/move to the
18479 end of the list."
18480 (interactive "P")
18481 (let ((org-agenda-skip-unavailable-files nil)
18482 (file-alist (mapcar (lambda (x)
18483 (cons (file-truename x) x))
18484 (org-agenda-files t)))
18485 (ctf (file-truename
18486 (or buffer-file-name
18487 (user-error "Please save the current buffer to a file"))))
18488 x had)
18489 (setq x (assoc ctf file-alist) had x)
18491 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18492 (if to-end
18493 (setq file-alist (append (delq x file-alist) (list x)))
18494 (setq file-alist (cons x (delq x file-alist))))
18495 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18496 (org-install-agenda-files-menu)
18497 (message "File %s to %s of agenda file list"
18498 (if had "moved" "added") (if to-end "end" "front"))))
18500 (defun org-remove-file (&optional file)
18501 "Remove current file from the list of files in variable `org-agenda-files'.
18502 These are the files which are being checked for agenda entries.
18503 Optional argument FILE means use this file instead of the current."
18504 (interactive)
18505 (let* ((org-agenda-skip-unavailable-files nil)
18506 (file (or file buffer-file-name
18507 (user-error "Current buffer does not visit a file")))
18508 (true-file (file-truename file))
18509 (afile (abbreviate-file-name file))
18510 (files (delq nil (mapcar
18511 (lambda (x)
18512 (unless (equal true-file
18513 (file-truename x))
18515 (org-agenda-files t)))))
18516 (if (not (= (length files) (length (org-agenda-files t))))
18517 (progn
18518 (org-store-new-agenda-file-list files)
18519 (org-install-agenda-files-menu)
18520 (message "Removed from Org Agenda list: %s" afile))
18521 (message "File was not in list: %s (not removed)" afile))))
18523 (defun org-file-menu-entry (file)
18524 (vector file (list 'find-file file) t))
18526 (defun org-check-agenda-file (file)
18527 "Make sure FILE exists. If not, ask user what to do."
18528 (unless (file-exists-p file)
18529 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18530 (abbreviate-file-name file))
18531 (let ((r (downcase (read-char-exclusive))))
18532 (cond
18533 ((equal r ?r)
18534 (org-remove-file file)
18535 (throw 'nextfile t))
18536 (t (user-error "Abort"))))))
18538 (defun org-get-agenda-file-buffer (file)
18539 "Get an agenda buffer visiting FILE.
18540 If the buffer needs to be created, add it to the list of buffers
18541 which might be released later."
18542 (let ((buf (org-find-base-buffer-visiting file)))
18543 (if buf
18544 buf ; just return it
18545 ;; Make a new buffer and remember it
18546 (setq buf (find-file-noselect file))
18547 (when buf (push buf org-agenda-new-buffers))
18548 buf)))
18550 (defun org-release-buffers (blist)
18551 "Release all buffers in list, asking the user for confirmation when needed.
18552 When a buffer is unmodified, it is just killed. When modified, it is saved
18553 \(if the user agrees) and then killed."
18554 (let (file)
18555 (dolist (buf blist)
18556 (setq file (buffer-file-name buf))
18557 (when (and (buffer-modified-p buf)
18558 file
18559 (y-or-n-p (format "Save file %s? " file)))
18560 (with-current-buffer buf (save-buffer)))
18561 (kill-buffer buf))))
18563 (defun org-agenda-prepare-buffers (files)
18564 "Create buffers for all agenda files, protect archived trees and comments."
18565 (interactive)
18566 (let ((pa '(:org-archived t))
18567 (pc '(:org-comment t))
18568 (pall '(:org-archived t :org-comment t))
18569 (inhibit-read-only t)
18570 (org-inhibit-startup org-agenda-inhibit-startup)
18571 (rea (concat ":" org-archive-tag ":"))
18572 re pos)
18573 (setq org-tag-alist-for-agenda nil
18574 org-tag-groups-alist-for-agenda nil)
18575 (save-excursion
18576 (save-restriction
18577 (dolist (file files)
18578 (catch 'nextfile
18579 (if (bufferp file)
18580 (set-buffer file)
18581 (org-check-agenda-file file)
18582 (set-buffer (org-get-agenda-file-buffer file)))
18583 (widen)
18584 (org-set-regexps-and-options 'tags-only)
18585 (setq pos (point))
18586 (or (memq 'category org-agenda-ignore-properties)
18587 (org-refresh-category-properties))
18588 (or (memq 'stats org-agenda-ignore-properties)
18589 (org-refresh-stats-properties))
18590 (or (memq 'effort org-agenda-ignore-properties)
18591 (org-refresh-effort-properties))
18592 (or (memq 'appt org-agenda-ignore-properties)
18593 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18594 (setq org-todo-keywords-for-agenda
18595 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18596 (setq org-done-keywords-for-agenda
18597 (append org-done-keywords-for-agenda org-done-keywords))
18598 (setq org-todo-keyword-alist-for-agenda
18599 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18600 (setq org-tag-alist-for-agenda
18601 (org-uniquify
18602 (append org-tag-alist-for-agenda
18603 org-current-tag-alist)))
18604 ;; Merge current file's tag groups into global
18605 ;; `org-tag-groups-alist-for-agenda'.
18606 (when org-group-tags
18607 (dolist (alist org-tag-groups-alist)
18608 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18609 (if old
18610 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18611 (push alist org-tag-groups-alist-for-agenda)))))
18612 (org-with-silent-modifications
18613 (save-excursion
18614 (remove-text-properties (point-min) (point-max) pall)
18615 (when org-agenda-skip-archived-trees
18616 (goto-char (point-min))
18617 (while (re-search-forward rea nil t)
18618 (when (org-at-heading-p t)
18619 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18620 (goto-char (point-min))
18621 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18622 (while (re-search-forward re nil t)
18623 (when (save-match-data (org-in-commented-heading-p t))
18624 (add-text-properties
18625 (match-beginning 0) (org-end-of-subtree t) pc)))))
18626 (goto-char pos)))))
18627 (setq org-todo-keywords-for-agenda
18628 (org-uniquify org-todo-keywords-for-agenda))
18629 (setq org-todo-keyword-alist-for-agenda
18630 (org-uniquify org-todo-keyword-alist-for-agenda))))
18633 ;;;; CDLaTeX minor mode
18635 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18636 "Keymap for the minor `org-cdlatex-mode'.")
18638 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18639 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18640 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18641 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18642 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18644 (defvar org-cdlatex-texmathp-advice-is-done nil
18645 "Flag remembering if we have applied the advice to texmathp already.")
18647 (define-minor-mode org-cdlatex-mode
18648 "Toggle the minor `org-cdlatex-mode'.
18649 This mode supports entering LaTeX environment and math in LaTeX fragments
18650 in Org mode.
18651 \\{org-cdlatex-mode-map}"
18652 nil " OCDL" nil
18653 (when org-cdlatex-mode
18654 (require 'cdlatex)
18655 (run-hooks 'cdlatex-mode-hook)
18656 (cdlatex-compute-tables))
18657 (unless org-cdlatex-texmathp-advice-is-done
18658 (setq org-cdlatex-texmathp-advice-is-done t)
18659 (defadvice texmathp (around org-math-always-on activate)
18660 "Always return t in Org buffers.
18661 This is because we want to insert math symbols without dollars even outside
18662 the LaTeX math segments. If Org mode thinks that point is actually inside
18663 an embedded LaTeX fragment, let `texmathp' do its job.
18664 `\\[org-cdlatex-mode-map]'"
18665 (interactive)
18666 (let (p)
18667 (cond
18668 ((not (derived-mode-p 'org-mode)) ad-do-it)
18669 ((eq this-command 'cdlatex-math-symbol)
18670 (setq ad-return-value t
18671 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18673 (let ((p (org-inside-LaTeX-fragment-p)))
18674 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18675 (setq ad-return-value t
18676 texmathp-why '("Org mode embedded math" . 0))
18677 (when p ad-do-it)))))))))
18679 (defun turn-on-org-cdlatex ()
18680 "Unconditionally turn on `org-cdlatex-mode'."
18681 (org-cdlatex-mode 1))
18683 (defun org-try-cdlatex-tab ()
18684 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18685 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18686 - inside a LaTeX fragment, or
18687 - after the first word in a line, where an abbreviation expansion could
18688 insert a LaTeX environment."
18689 (when org-cdlatex-mode
18690 (cond
18691 ;; Before any word on the line: No expansion possible.
18692 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18693 ;; Just after first word on the line: Expand it. Make sure it
18694 ;; cannot happen on headlines, though.
18695 ((save-excursion
18696 (skip-chars-backward "a-zA-Z0-9*")
18697 (skip-chars-backward " \t")
18698 (and (bolp) (not (org-at-heading-p))))
18699 (cdlatex-tab) t)
18700 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18702 (defun org-cdlatex-underscore-caret (&optional _arg)
18703 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18704 Revert to the normal definition outside of these fragments."
18705 (interactive "P")
18706 (if (org-inside-LaTeX-fragment-p)
18707 (call-interactively 'cdlatex-sub-superscript)
18708 (let (org-cdlatex-mode)
18709 (call-interactively (key-binding (vector last-input-event))))))
18711 (defun org-cdlatex-math-modify (&optional _arg)
18712 "Execute `cdlatex-math-modify' in LaTeX fragments.
18713 Revert to the normal definition outside of these fragments."
18714 (interactive "P")
18715 (if (org-inside-LaTeX-fragment-p)
18716 (call-interactively 'cdlatex-math-modify)
18717 (let (org-cdlatex-mode)
18718 (call-interactively (key-binding (vector last-input-event))))))
18720 (defun org-cdlatex-environment-indent (&optional environment item)
18721 "Execute `cdlatex-environment' and indent the inserted environment.
18723 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18725 The inserted environment is indented to current indentation
18726 unless point is at the beginning of the line, in which the
18727 environment remains unintended."
18728 (interactive)
18729 ;; cdlatex-environment always return nil. Therefore, capture output
18730 ;; first and determine if an environment was selected.
18731 (let* ((beg (point-marker))
18732 (end (copy-marker (point) t))
18733 (inserted (progn
18734 (ignore-errors (cdlatex-environment environment item))
18735 (< beg end)))
18736 ;; Figure out how many lines to move forward after the
18737 ;; environment has been inserted.
18738 (lines (when inserted
18739 (save-excursion
18740 (- (cl-loop while (< beg (point))
18741 with x = 0
18742 do (forward-line -1)
18743 (cl-incf x)
18744 finally return x)
18745 (if (progn (goto-char beg)
18746 (and (progn (skip-chars-forward " \t") (eolp))
18747 (progn (skip-chars-backward " \t") (bolp))))
18748 1 0)))))
18749 (env (org-trim (delete-and-extract-region beg end))))
18750 (when inserted
18751 ;; Get indentation of next line unless at column 0.
18752 (let ((ind (if (bolp) 0
18753 (save-excursion
18754 (org-return-indent)
18755 (prog1 (org-get-indentation)
18756 (when (progn (skip-chars-forward " \t") (eolp))
18757 (delete-region beg (point)))))))
18758 (bol (progn (skip-chars-backward " \t") (bolp))))
18759 ;; Insert a newline before environment unless at column zero
18760 ;; to "escape" the current line. Insert a newline if
18761 ;; something is one the same line as \end{ENVIRONMENT}.
18762 (insert
18763 (concat (unless bol "\n") env
18764 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18765 (unless (zerop ind)
18766 (save-excursion
18767 (goto-char beg)
18768 (while (< (point) end)
18769 (unless (eolp) (indent-line-to ind))
18770 (forward-line))))
18771 (goto-char beg)
18772 (forward-line lines)
18773 (indent-line-to ind)))
18774 (set-marker beg nil)
18775 (set-marker end nil)))
18778 ;;;; LaTeX fragments
18780 (defun org-inside-LaTeX-fragment-p ()
18781 "Test if point is inside a LaTeX fragment.
18782 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18783 sequence appearing also before point.
18784 Even though the matchers for math are configurable, this function assumes
18785 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18786 delimiters are skipped when they have been removed by customization.
18787 The return value is nil, or a cons cell with the delimiter and the
18788 position of this delimiter.
18790 This function does a reasonably good job, but can locally be fooled by
18791 for example currency specifications. For example it will assume being in
18792 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18793 fragments that are properly closed, but during editing, we have to live
18794 with the uncertainty caused by missing closing delimiters. This function
18795 looks only before point, not after."
18796 (catch 'exit
18797 (let ((pos (point))
18798 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18799 (lim (progn
18800 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18801 (point)))
18802 dd-on str (start 0) m re)
18803 (goto-char pos)
18804 (when dodollar
18805 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18806 re (nth 1 (assoc "$" org-latex-regexps)))
18807 (while (string-match re str start)
18808 (cond
18809 ((= (match-end 0) (length str))
18810 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18811 ((= (match-end 0) (- (length str) 5))
18812 (throw 'exit nil))
18813 (t (setq start (match-end 0))))))
18814 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18815 (goto-char pos)
18816 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18817 (and (match-beginning 2) (throw 'exit nil))
18818 ;; count $$
18819 (while (re-search-backward "\\$\\$" lim t)
18820 (setq dd-on (not dd-on)))
18821 (goto-char pos)
18822 (when dd-on (cons "$$" m))))))
18824 (defun org-inside-latex-macro-p ()
18825 "Is point inside a LaTeX macro or its arguments?"
18826 (save-match-data
18827 (org-in-regexp
18828 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18830 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18831 "Build an overlay between BEG and END using IMAGE file.
18832 Argument IMAGETYPE is the extension of the displayed image,
18833 as a string. It defaults to \"png\"."
18834 (let ((ov (make-overlay beg end))
18835 (imagetype (or (intern imagetype) 'png)))
18836 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18837 (overlay-put ov 'evaporate t)
18838 (overlay-put ov
18839 'modification-hooks
18840 (list (lambda (o _flag _beg _end &optional _l)
18841 (delete-overlay o))))
18842 (overlay-put ov
18843 'display
18844 (list 'image :type imagetype :file image :ascent 'center))))
18846 (defun org--list-latex-overlays (&optional beg end)
18847 "List all Org LaTeX overlays in current buffer.
18848 Limit to overlays between BEG and END when those are provided."
18849 (cl-remove-if-not
18850 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18851 (overlays-in (or beg (point-min)) (or end (point-max)))))
18853 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18854 "Remove all overlays with LaTeX fragment images in current buffer.
18855 When optional arguments BEG and END are non-nil, remove all
18856 overlays between them instead. Return a non-nil value when some
18857 overlays were removed, nil otherwise."
18858 (let ((overlays (org--list-latex-overlays beg end)))
18859 (mapc #'delete-overlay overlays)
18860 overlays))
18862 (defun org-toggle-latex-fragment (&optional arg)
18863 "Preview the LaTeX fragment at point, or all locally or globally.
18865 If the cursor is on a LaTeX fragment, create the image and overlay
18866 it over the source code, if there is none. Remove it otherwise.
18867 If there is no fragment at point, display all fragments in the
18868 current section.
18870 With prefix ARG, preview or clear image for all fragments in the
18871 current subtree or in the whole buffer when used before the first
18872 headline. With a prefix ARG `\\[universal-argument] \
18873 \\[universal-argument]' preview or clear images
18874 for all fragments in the buffer."
18875 (interactive "P")
18876 (when (display-graphic-p)
18877 (catch 'exit
18878 (save-excursion
18879 (let (beg end msg)
18880 (cond
18881 ((or (equal arg '(16))
18882 (and (equal arg '(4))
18883 (org-with-limited-levels (org-before-first-heading-p))))
18884 (if (org-remove-latex-fragment-image-overlays)
18885 (progn (message "LaTeX fragments images removed from buffer")
18886 (throw 'exit nil))
18887 (setq msg "Creating images for buffer...")))
18888 ((equal arg '(4))
18889 (org-with-limited-levels (org-back-to-heading t))
18890 (setq beg (point))
18891 (setq end (progn (org-end-of-subtree t) (point)))
18892 (if (org-remove-latex-fragment-image-overlays beg end)
18893 (progn
18894 (message "LaTeX fragment images removed from subtree")
18895 (throw 'exit nil))
18896 (setq msg "Creating images for subtree...")))
18897 ((let ((datum (org-element-context)))
18898 (when (memq (org-element-type datum)
18899 '(latex-environment latex-fragment))
18900 (setq beg (org-element-property :begin datum))
18901 (setq end (org-element-property :end datum))
18902 (if (org-remove-latex-fragment-image-overlays beg end)
18903 (progn (message "LaTeX fragment image removed")
18904 (throw 'exit nil))
18905 (setq msg "Creating image...")))))
18907 (org-with-limited-levels
18908 (setq beg (if (org-at-heading-p) (line-beginning-position)
18909 (outline-previous-heading)
18910 (point)))
18911 (setq end (progn (outline-next-heading) (point)))
18912 (if (org-remove-latex-fragment-image-overlays beg end)
18913 (progn
18914 (message "LaTeX fragment images removed from section")
18915 (throw 'exit nil))
18916 (setq msg "Creating images for section...")))))
18917 (let ((file (buffer-file-name (buffer-base-buffer))))
18918 (org-format-latex
18919 (concat org-preview-latex-image-directory "org-ltximg")
18920 beg end
18921 ;; Emacs cannot overlay images from remote hosts. Create
18922 ;; it in `temporary-file-directory' instead.
18923 (if (or (not file) (file-remote-p file))
18924 temporary-file-directory
18925 default-directory)
18926 'overlays msg 'forbuffer org-preview-latex-default-process))
18927 (message (concat msg "done")))))))
18929 (defun org-format-latex
18930 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18931 "Replace LaTeX fragments with links to an image.
18933 The function takes care of creating the replacement image.
18935 Only consider fragments between BEG and END when those are
18936 provided.
18938 When optional argument OVERLAYS is non-nil, display the image on
18939 top of the fragment instead of replacing it.
18941 PROCESSING-TYPE is the conversion method to use, as a symbol.
18943 Some of the options can be changed using the variable
18944 `org-format-latex-options', which see."
18945 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18946 (unless (eq processing-type 'verbatim)
18947 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18948 (cnt 0)
18949 checkdir-flag)
18950 (goto-char (or beg (point-min)))
18951 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18952 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18953 (overlay-recenter (or end (point-max))))
18954 (while (re-search-forward math-regexp end t)
18955 (unless (and overlays
18956 (eq (get-char-property (point) 'org-overlay-type)
18957 'org-latex-overlay))
18958 (let* ((context (org-element-context))
18959 (type (org-element-type context)))
18960 (when (memq type '(latex-environment latex-fragment))
18961 (let ((block-type (eq type 'latex-environment))
18962 (value (org-element-property :value context))
18963 (beg (org-element-property :begin context))
18964 (end (save-excursion
18965 (goto-char (org-element-property :end context))
18966 (skip-chars-backward " \r\t\n")
18967 (point))))
18968 (cond
18969 ((eq processing-type 'mathjax)
18970 ;; Prepare for MathJax processing.
18971 (if (not (string-match "\\`\\$\\$?" value))
18972 (goto-char end)
18973 (delete-region beg end)
18974 (if (string= (match-string 0 value) "$$")
18975 (insert "\\[" (substring value 2 -2) "\\]")
18976 (insert "\\(" (substring value 1 -1) "\\)"))))
18977 ((assq processing-type org-preview-latex-process-alist)
18978 ;; Process to an image.
18979 (cl-incf cnt)
18980 (goto-char beg)
18981 (let* ((processing-info
18982 (cdr (assq processing-type org-preview-latex-process-alist)))
18983 (face (face-at-point))
18984 ;; Get the colors from the face at point.
18986 (let ((color (plist-get org-format-latex-options
18987 :foreground)))
18988 (if (and forbuffer (eq color 'auto))
18989 (face-attribute face :foreground nil 'default)
18990 color)))
18992 (let ((color (plist-get org-format-latex-options
18993 :background)))
18994 (if (and forbuffer (eq color 'auto))
18995 (face-attribute face :background nil 'default)
18996 color)))
18997 (hash (sha1 (prin1-to-string
18998 (list org-format-latex-header
18999 org-latex-default-packages-alist
19000 org-latex-packages-alist
19001 org-format-latex-options
19002 forbuffer value fg bg))))
19003 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19004 (absprefix (expand-file-name prefix dir))
19005 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19006 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19007 (sep (and block-type "\n\n"))
19008 (link (concat sep "[[file:" linkfile "]]" sep))
19009 (options
19010 (org-combine-plists
19011 org-format-latex-options
19012 `(:foreground ,fg :background ,bg))))
19013 (when msg (message msg cnt))
19014 (unless checkdir-flag ; Ensure the directory exists.
19015 (setq checkdir-flag t)
19016 (let ((todir (file-name-directory absprefix)))
19017 (unless (file-directory-p todir)
19018 (make-directory todir t))))
19019 (unless (file-exists-p movefile)
19020 (org-create-formula-image
19021 value movefile options forbuffer processing-type))
19022 (if overlays
19023 (progn
19024 (dolist (o (overlays-in beg end))
19025 (when (eq (overlay-get o 'org-overlay-type)
19026 'org-latex-overlay)
19027 (delete-overlay o)))
19028 (org--format-latex-make-overlay beg end movefile imagetype)
19029 (goto-char end))
19030 (delete-region beg end)
19031 (insert
19032 (org-add-props link
19033 (list 'org-latex-src
19034 (replace-regexp-in-string "\"" "" value)
19035 'org-latex-src-embed-type
19036 (if block-type 'paragraph 'character)))))))
19037 ((eq processing-type 'mathml)
19038 ;; Process to MathML.
19039 (unless (org-format-latex-mathml-available-p)
19040 (user-error "LaTeX to MathML converter not configured"))
19041 (cl-incf cnt)
19042 (when msg (message msg cnt))
19043 (goto-char beg)
19044 (delete-region beg end)
19045 (insert (org-format-latex-as-mathml
19046 value block-type prefix dir)))
19048 (error "Unknown conversion process %s for LaTeX fragments"
19049 processing-type)))))))))))
19051 (defun org-create-math-formula (latex-frag &optional mathml-file)
19052 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19053 Use `org-latex-to-mathml-convert-command'. If the conversion is
19054 sucessful, return the portion between \"<math...> </math>\"
19055 elements otherwise return nil. When MATHML-FILE is specified,
19056 write the results in to that file. When invoked as an
19057 interactive command, prompt for LATEX-FRAG, with initial value
19058 set to the current active region and echo the results for user
19059 inspection."
19060 (interactive (list (let ((frag (when (org-region-active-p)
19061 (buffer-substring-no-properties
19062 (region-beginning) (region-end)))))
19063 (read-string "LaTeX Fragment: " frag nil frag))))
19064 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19065 (let* ((tmp-in-file
19066 (let ((file (file-relative-name
19067 (make-temp-name (expand-file-name "ltxmathml-in")))))
19068 (write-region latex-frag nil file)
19069 file))
19070 (tmp-out-file (file-relative-name
19071 (make-temp-name (expand-file-name "ltxmathml-out"))))
19072 (cmd (format-spec
19073 org-latex-to-mathml-convert-command
19074 `((?j . ,(and org-latex-to-mathml-jar-file
19075 (shell-quote-argument
19076 (expand-file-name
19077 org-latex-to-mathml-jar-file))))
19078 (?I . ,(shell-quote-argument tmp-in-file))
19079 (?i . ,latex-frag)
19080 (?o . ,(shell-quote-argument tmp-out-file)))))
19081 mathml shell-command-output)
19082 (when (called-interactively-p 'any)
19083 (unless (org-format-latex-mathml-available-p)
19084 (user-error "LaTeX to MathML converter not configured")))
19085 (message "Running %s" cmd)
19086 (setq shell-command-output (shell-command-to-string cmd))
19087 (setq mathml
19088 (when (file-readable-p tmp-out-file)
19089 (with-current-buffer (find-file-noselect tmp-out-file t)
19090 (goto-char (point-min))
19091 (when (re-search-forward
19092 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19093 (regexp-quote
19094 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19095 nil t)
19096 (prog1 (match-string 0) (kill-buffer))))))
19097 (cond
19098 (mathml
19099 (setq mathml
19100 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19101 (when mathml-file
19102 (write-region mathml nil mathml-file))
19103 (when (called-interactively-p 'any)
19104 (message mathml)))
19105 ((message "LaTeX to MathML conversion failed")
19106 (message shell-command-output)))
19107 (delete-file tmp-in-file)
19108 (when (file-exists-p tmp-out-file)
19109 (delete-file tmp-out-file))
19110 mathml))
19112 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19113 prefix &optional dir)
19114 "Use `org-create-math-formula' but check local cache first."
19115 (let* ((absprefix (expand-file-name prefix dir))
19116 (print-length nil) (print-level nil)
19117 (formula-id (concat
19118 "formula-"
19119 (sha1
19120 (prin1-to-string
19121 (list latex-frag
19122 org-latex-to-mathml-convert-command)))))
19123 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19124 (formula-cache-dir (file-name-directory formula-cache)))
19126 (unless (file-directory-p formula-cache-dir)
19127 (make-directory formula-cache-dir t))
19129 (unless (file-exists-p formula-cache)
19130 (org-create-math-formula latex-frag formula-cache))
19132 (if (file-exists-p formula-cache)
19133 ;; Successful conversion. Return the link to MathML file.
19134 (org-add-props
19135 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19136 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19137 'org-latex-src-embed-type (if latex-frag-type
19138 'paragraph 'character)))
19139 ;; Failed conversion. Return the LaTeX fragment verbatim
19140 latex-frag)))
19142 (defun org--get-display-dpi ()
19143 "Get the DPI of the display.
19144 The function assumes that the display has the same pixel width in
19145 the horizontal and vertical directions."
19146 (if (display-graphic-p)
19147 (round (/ (display-pixel-height)
19148 (/ (display-mm-height) 25.4)))
19149 (error "Attempt to calculate the dpi of a non-graphic display")))
19151 (defun org-create-formula-image
19152 (string tofile options buffer &optional processing-type)
19153 "Create an image from LaTeX source using external processes.
19155 The LaTeX STRING is saved to a temporary LaTeX file, then
19156 converted to an image file by process PROCESSING-TYPE defined in
19157 `org-preview-latex-process-alist'. A nil value defaults to
19158 `org-preview-latex-default-process'.
19160 The generated image file is eventually moved to TOFILE.
19162 The OPTIONS argument controls the size, foreground color and
19163 background color of the generated image.
19165 When BUFFER non-nil, this function is used for LaTeX previewing.
19166 Otherwise, it is used to deal with LaTeX snippets showed in
19167 a HTML file."
19168 (let* ((processing-type (or processing-type
19169 org-preview-latex-default-process))
19170 (processing-info
19171 (cdr (assq processing-type org-preview-latex-process-alist)))
19172 (programs (plist-get processing-info :programs))
19173 (error-message (or (plist-get processing-info :message) ""))
19174 (use-xcolor (plist-get processing-info :use-xcolor))
19175 (image-input-type (plist-get processing-info :image-input-type))
19176 (image-output-type (plist-get processing-info :image-output-type))
19177 (post-clean (or (plist-get processing-info :post-clean)
19178 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19179 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19180 (latex-header
19181 (or (plist-get processing-info :latex-header)
19182 (org-latex-make-preamble
19183 (org-export-get-environment (org-export-get-backend 'latex))
19184 org-format-latex-header
19185 'snippet)))
19186 (latex-compiler (plist-get processing-info :latex-compiler))
19187 (image-converter (plist-get processing-info :image-converter))
19188 (tmpdir temporary-file-directory)
19189 (texfilebase (make-temp-name
19190 (expand-file-name "orgtex" tmpdir)))
19191 (texfile (concat texfilebase ".tex"))
19192 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19193 '(1.0 . 1.0)))
19194 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19195 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19196 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19197 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19198 "Black"))
19199 (bg (or (plist-get options (if buffer :background :html-background))
19200 "Transparent"))
19201 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19202 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19203 (dolist (program programs)
19204 (org-check-external-command program error-message))
19205 (if use-xcolor
19206 (progn (if (eq fg 'default)
19207 (setq fg (org-latex-color :foreground))
19208 (setq fg (org-latex-color-format fg)))
19209 (if (eq bg 'default)
19210 (setq bg (org-latex-color :background))
19211 (setq bg (org-latex-color-format
19212 (if (string= bg "Transparent") "white" bg))))
19213 (with-temp-file texfile
19214 (insert latex-header)
19215 (insert "\n\\begin{document}\n"
19216 "\\definecolor{fg}{rgb}{" fg "}\n"
19217 "\\definecolor{bg}{rgb}{" bg "}\n"
19218 "\n\\pagecolor{bg}\n"
19219 "\n{\\color{fg}\n"
19220 string
19221 "\n}\n"
19222 "\n\\end{document}\n")))
19223 (if (eq fg 'default)
19224 (setq fg (org-dvipng-color :foreground))
19225 (unless (string= fg "Transparent")
19226 (setq fg (org-dvipng-color-format fg))))
19227 (if (eq bg 'default)
19228 (setq bg (org-dvipng-color :background))
19229 (unless (string= bg "Transparent")
19230 (setq bg (org-dvipng-color-format bg))))
19231 (with-temp-file texfile
19232 (insert latex-header)
19233 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19235 (let* ((err-msg (format "Please adjust '%s' part of \
19236 `org-preview-latex-process-alist'."
19237 processing-type))
19238 (image-input-file
19239 (org-compile-file
19240 texfile latex-compiler image-input-type err-msg log-buf))
19241 (image-output-file
19242 (org-compile-file
19243 image-input-file image-converter image-output-type err-msg log-buf
19244 `((?F . ,(shell-quote-argument fg))
19245 (?B . ,(shell-quote-argument bg))
19246 (?D . ,(shell-quote-argument (format "%s" dpi)))
19247 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19248 (copy-file image-output-file tofile 'replace)
19249 (dolist (e post-clean)
19250 (when (file-exists-p (concat texfilebase e))
19251 (delete-file (concat texfilebase e))))
19252 image-output-file)))
19254 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19255 "Fill a LaTeX header template TPL.
19256 In the template, the following place holders will be recognized:
19258 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19259 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19260 [PACKAGES] \\usepackage statements for PKG
19261 [NO-PACKAGES] do not include PKG
19262 [EXTRA] the string EXTRA
19263 [NO-EXTRA] do not include EXTRA
19265 For backward compatibility, if both the positive and the negative place
19266 holder is missing, the positive one (without the \"NO-\") will be
19267 assumed to be present at the end of the template.
19268 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19269 EXTRA is a string.
19270 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19271 (let (rpl (end ""))
19272 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19273 (setq rpl (if (or (match-end 1) (not def-pkg))
19274 "" (org-latex-packages-to-string def-pkg snippets-p t))
19275 tpl (replace-match rpl t t tpl))
19276 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19278 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19279 (setq rpl (if (or (match-end 1) (not pkg))
19280 "" (org-latex-packages-to-string pkg snippets-p t))
19281 tpl (replace-match rpl t t tpl))
19282 (when pkg (setq end
19283 (concat end "\n"
19284 (org-latex-packages-to-string pkg snippets-p)))))
19286 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19287 (setq rpl (if (or (match-end 1) (not extra))
19288 "" (concat extra "\n"))
19289 tpl (replace-match rpl t t tpl))
19290 (when (and extra (string-match "\\S-" extra))
19291 (setq end (concat end "\n" extra))))
19293 (if (string-match "\\S-" end)
19294 (concat tpl "\n" end)
19295 tpl)))
19297 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19298 "Turn an alist of packages into a string with the \\usepackage macros."
19299 (setq pkg (mapconcat (lambda(p)
19300 (cond
19301 ((stringp p) p)
19302 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19303 (format "%% Package %s omitted" (cadr p)))
19304 ((equal "" (car p))
19305 (format "\\usepackage{%s}" (cadr p)))
19307 (format "\\usepackage[%s]{%s}"
19308 (car p) (cadr p)))))
19310 "\n"))
19311 (if newline (concat pkg "\n") pkg))
19313 (defun org-dvipng-color (attr)
19314 "Return a RGB color specification for dvipng."
19315 (org-dvipng-color-format (face-attribute 'default attr nil)))
19317 (defun org-dvipng-color-format (color-name)
19318 "Convert COLOR-NAME to a RGB color value for dvipng."
19319 (apply #'format "rgb %s %s %s"
19320 (mapcar 'org-normalize-color
19321 (color-values color-name))))
19323 (defun org-latex-color (attr)
19324 "Return a RGB color for the LaTeX color package."
19325 (org-latex-color-format (face-attribute 'default attr nil)))
19327 (defun org-latex-color-format (color-name)
19328 "Convert COLOR-NAME to a RGB color value."
19329 (apply #'format "%s,%s,%s"
19330 (mapcar 'org-normalize-color
19331 (color-values color-name))))
19333 (defun org-normalize-color (value)
19334 "Return string to be used as color value for an RGB component."
19335 (format "%g" (/ value 65535.0)))
19339 ;; Image display
19341 (defvar-local org-inline-image-overlays nil)
19343 (defun org-toggle-inline-images (&optional include-linked)
19344 "Toggle the display of inline images.
19345 INCLUDE-LINKED is passed to `org-display-inline-images'."
19346 (interactive "P")
19347 (if org-inline-image-overlays
19348 (progn
19349 (org-remove-inline-images)
19350 (when (called-interactively-p 'interactive)
19351 (message "Inline image display turned off")))
19352 (org-display-inline-images include-linked)
19353 (when (called-interactively-p 'interactive)
19354 (message (if org-inline-image-overlays
19355 (format "%d images displayed inline"
19356 (length org-inline-image-overlays))
19357 "No images to display inline")))))
19359 (defun org-redisplay-inline-images ()
19360 "Refresh the display of inline images."
19361 (interactive)
19362 (if (not org-inline-image-overlays)
19363 (org-toggle-inline-images)
19364 (org-toggle-inline-images)
19365 (org-toggle-inline-images)))
19367 (defun org-display-inline-images (&optional include-linked refresh beg end)
19368 "Display inline images.
19370 An inline image is a link which follows either of these
19371 conventions:
19373 1. Its path is a file with an extension matching return value
19374 from `image-file-name-regexp' and it has no contents.
19376 2. Its description consists in a single link of the previous
19377 type.
19379 When optional argument INCLUDE-LINKED is non-nil, also links with
19380 a text description part will be inlined. This can be nice for
19381 a quick look at those images, but it does not reflect what
19382 exported files will look like.
19384 When optional argument REFRESH is non-nil, refresh existing
19385 images between BEG and END. This will create new image displays
19386 only if necessary. BEG and END default to the buffer
19387 boundaries."
19388 (interactive "P")
19389 (when (display-graphic-p)
19390 (unless refresh
19391 (org-remove-inline-images)
19392 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19393 (org-with-wide-buffer
19394 (goto-char (or beg (point-min)))
19395 (let ((case-fold-search t)
19396 (file-extension-re (image-file-name-regexp)))
19397 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19398 (let ((link (save-match-data (org-element-context))))
19399 ;; Check if we're at an inline image.
19400 (when (and (equal (org-element-property :type link) "file")
19401 (or include-linked
19402 (not (org-element-property :contents-begin link)))
19403 (let ((parent (org-element-property :parent link)))
19404 (or (not (eq (org-element-type parent) 'link))
19405 (not (cdr (org-element-contents parent)))))
19406 (string-match-p file-extension-re
19407 (org-element-property :path link)))
19408 (let ((file (expand-file-name
19409 (org-link-unescape
19410 (org-element-property :path link)))))
19411 (when (file-exists-p file)
19412 (let ((width
19413 ;; Apply `org-image-actual-width' specifications.
19414 (cond
19415 ((not (image-type-available-p 'imagemagick)) nil)
19416 ((eq org-image-actual-width t) nil)
19417 ((listp org-image-actual-width)
19419 ;; First try to find a width among
19420 ;; attributes associated to the paragraph
19421 ;; containing link.
19422 (let ((paragraph
19423 (let ((e link))
19424 (while (and (setq e (org-element-property
19425 :parent e))
19426 (not (eq (org-element-type e)
19427 'paragraph))))
19428 e)))
19429 (when paragraph
19430 (save-excursion
19431 (goto-char (org-element-property :begin paragraph))
19432 (when
19433 (re-search-forward
19434 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19435 (org-element-property
19436 :post-affiliated paragraph)
19438 (string-to-number (match-string 1))))))
19439 ;; Otherwise, fall-back to provided number.
19440 (car org-image-actual-width)))
19441 ((numberp org-image-actual-width)
19442 org-image-actual-width)))
19443 (old (get-char-property-and-overlay
19444 (org-element-property :begin link)
19445 'org-image-overlay)))
19446 (if (and (car-safe old) refresh)
19447 (image-refresh (overlay-get (cdr old) 'display))
19448 (let ((image (create-image file
19449 (and width 'imagemagick)
19451 :width width)))
19452 (when image
19453 (let* ((link
19454 ;; If inline image is the description
19455 ;; of another link, be sure to
19456 ;; consider the latter as the one to
19457 ;; apply the overlay on.
19458 (let ((parent
19459 (org-element-property :parent link)))
19460 (if (eq (org-element-type parent) 'link)
19461 parent
19462 link)))
19463 (ov (make-overlay
19464 (org-element-property :begin link)
19465 (progn
19466 (goto-char
19467 (org-element-property :end link))
19468 (skip-chars-backward " \t")
19469 (point)))))
19470 (overlay-put ov 'display image)
19471 (overlay-put ov 'face 'default)
19472 (overlay-put ov 'org-image-overlay t)
19473 (overlay-put
19474 ov 'modification-hooks
19475 (list 'org-display-inline-remove-overlay))
19476 (push ov org-inline-image-overlays)))))))))))))))
19478 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19479 "Remove inline-display overlay if a corresponding region is modified."
19480 (let ((inhibit-modification-hooks t))
19481 (when (and ov after)
19482 (delete ov org-inline-image-overlays)
19483 (delete-overlay ov))))
19485 (defun org-remove-inline-images ()
19486 "Remove inline display of images."
19487 (interactive)
19488 (mapc #'delete-overlay org-inline-image-overlays)
19489 (setq org-inline-image-overlays nil))
19491 ;;;; Key bindings
19493 ;; Outline functions from `outline-mode-prefix-map'
19494 ;; that can be remapped in Org:
19495 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19496 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19497 (define-key org-mode-map [remap outline-forward-same-level]
19498 'org-forward-heading-same-level)
19499 (define-key org-mode-map [remap outline-backward-same-level]
19500 'org-backward-heading-same-level)
19501 (define-key org-mode-map [remap outline-show-branches]
19502 'org-kill-note-or-show-branches)
19503 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19504 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19505 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19506 (define-key org-mode-map [remap outline-next-visible-heading]
19507 'org-next-visible-heading)
19508 (define-key org-mode-map [remap outline-previous-visible-heading]
19509 'org-previous-visible-heading)
19510 (define-key org-mode-map [remap show-children] 'org-show-children)
19512 ;; Outline functions from `outline-mode-prefix-map' that can not
19513 ;; be remapped in Org:
19515 ;; - the column "key binding" shows whether the Outline function is still
19516 ;; available in Org mode on the same key that it has been bound to in
19517 ;; Outline mode:
19518 ;; - "overridden": key used for a different functionality in Org mode
19519 ;; - else: key still bound to the same Outline function in Org mode
19521 ;; | Outline function | key binding | Org replacement |
19522 ;; |------------------------------------+-------------+--------------------------|
19523 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19524 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19525 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19526 ;; | `show-entry' | overridden | no replacement |
19527 ;; | `show-branches' | `C-c C-k' | still same function |
19528 ;; | `show-subtree' | overridden | visibility cycling |
19529 ;; | `show-all' | overridden | no replacement |
19530 ;; | `hide-subtree' | overridden | visibility cycling |
19531 ;; | `hide-body' | overridden | no replacement |
19532 ;; | `hide-entry' | overridden | visibility cycling |
19533 ;; | `hide-leaves' | overridden | no replacement |
19534 ;; | `hide-sublevels' | overridden | no replacement |
19535 ;; | `hide-other' | overridden | no replacement |
19537 ;; Make `C-c C-x' a prefix key
19538 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19540 ;; TAB key with modifiers
19541 (org-defkey org-mode-map "\C-i" 'org-cycle)
19542 (org-defkey org-mode-map [(tab)] 'org-cycle)
19543 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19544 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19545 ;; The following line is necessary under Suse GNU/Linux
19546 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19547 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19548 (define-key org-mode-map [backtab] 'org-shifttab)
19550 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19551 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19552 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19554 ;; Cursor keys with modifiers
19555 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19556 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19557 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19558 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19560 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19561 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19562 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19563 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19564 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19565 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19567 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19568 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19569 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19570 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19572 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19573 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19574 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19575 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19577 ;; Babel keys
19578 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19579 (dolist (pair org-babel-key-bindings)
19580 (define-key org-babel-map (car pair) (cdr pair)))
19582 ;;; Extra keys for tty access.
19583 ;; We only set them when really needed because otherwise the
19584 ;; menus don't show the simple keys
19586 (when (or org-use-extra-keys (not window-system))
19587 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19588 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19589 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19590 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19591 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19592 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19593 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19594 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19595 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19596 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19597 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19598 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19599 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19600 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19601 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19602 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19603 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19604 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19605 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19606 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19607 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19608 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19609 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19610 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19611 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19612 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19613 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19614 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19616 ;; All the other keys
19618 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19619 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19620 (if (boundp 'narrow-map)
19621 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19622 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19623 (if (boundp 'narrow-map)
19624 (org-defkey narrow-map "b" 'org-narrow-to-block)
19625 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19626 (if (boundp 'narrow-map)
19627 (org-defkey narrow-map "e" 'org-narrow-to-element)
19628 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19629 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19630 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19631 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19632 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19633 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19634 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19635 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19636 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19637 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19638 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19639 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19640 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19641 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19642 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19643 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19644 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19645 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19646 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19647 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19648 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19649 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19650 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19651 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19652 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19653 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19654 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19655 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19656 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19657 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19658 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19659 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19660 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19661 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19662 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19663 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19664 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19665 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19666 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19667 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19668 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19669 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19670 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19671 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19672 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19673 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19674 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19675 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19676 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19677 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19678 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19679 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19680 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19681 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19682 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19683 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19684 (org-defkey org-mode-map "\C-c^" 'org-sort)
19685 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19686 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19687 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19688 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19689 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19690 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19691 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19692 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19693 (org-defkey org-mode-map "\C-m" 'org-return)
19694 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19695 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19696 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19697 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19698 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19699 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19700 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19701 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19702 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19703 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19704 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19705 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19706 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19707 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19708 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19709 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19710 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19711 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19712 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19713 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19714 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19715 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19716 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19717 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19718 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19720 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19721 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19722 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19724 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19725 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19726 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19727 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19728 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19729 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19730 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19731 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19732 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19733 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19734 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19735 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19736 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19737 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19738 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19739 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19740 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19741 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19742 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19743 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19744 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19745 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19747 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19748 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19749 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19750 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19751 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19753 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19755 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19757 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19758 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19760 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19763 (defconst org-speed-commands-default
19765 ("Outline Navigation")
19766 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19767 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19768 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19769 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19770 ("F" . org-next-block)
19771 ("B" . org-previous-block)
19772 ("u" . (org-speed-move-safe 'outline-up-heading))
19773 ("j" . org-goto)
19774 ("g" . (org-refile t))
19775 ("Outline Visibility")
19776 ("c" . org-cycle)
19777 ("C" . org-shifttab)
19778 (" " . org-display-outline-path)
19779 ("s" . org-narrow-to-subtree)
19780 ("=" . org-columns)
19781 ("Outline Structure Editing")
19782 ("U" . org-metaup)
19783 ("D" . org-metadown)
19784 ("r" . org-metaright)
19785 ("l" . org-metaleft)
19786 ("R" . org-shiftmetaright)
19787 ("L" . org-shiftmetaleft)
19788 ("i" . (progn (forward-char 1) (call-interactively
19789 'org-insert-heading-respect-content)))
19790 ("^" . org-sort)
19791 ("w" . org-refile)
19792 ("a" . org-archive-subtree-default-with-confirmation)
19793 ("@" . org-mark-subtree)
19794 ("#" . org-toggle-comment)
19795 ("Clock Commands")
19796 ("I" . org-clock-in)
19797 ("O" . org-clock-out)
19798 ("Meta Data Editing")
19799 ("t" . org-todo)
19800 ("," . (org-priority))
19801 ("0" . (org-priority ?\ ))
19802 ("1" . (org-priority ?A))
19803 ("2" . (org-priority ?B))
19804 ("3" . (org-priority ?C))
19805 (":" . org-set-tags-command)
19806 ("e" . org-set-effort)
19807 ("E" . org-inc-effort)
19808 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19809 (org-entry-put (point) "APPT_WARNTIME" m)))
19810 ("Agenda Views etc")
19811 ("v" . org-agenda)
19812 ("/" . org-sparse-tree)
19813 ("Misc")
19814 ("o" . org-open-at-point)
19815 ("?" . org-speed-command-help)
19816 ("<" . (org-agenda-set-restriction-lock 'subtree))
19817 (">" . (org-agenda-remove-restriction-lock))
19819 "The default speed commands.")
19821 (defun org-print-speed-command (e)
19822 (if (> (length (car e)) 1)
19823 (progn
19824 (princ "\n")
19825 (princ (car e))
19826 (princ "\n")
19827 (princ (make-string (length (car e)) ?-))
19828 (princ "\n"))
19829 (princ (car e))
19830 (princ " ")
19831 (if (symbolp (cdr e))
19832 (princ (symbol-name (cdr e)))
19833 (prin1 (cdr e)))
19834 (princ "\n")))
19836 (defun org-speed-command-help ()
19837 "Show the available speed commands."
19838 (interactive)
19839 (if (not org-use-speed-commands)
19840 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19841 (with-output-to-temp-buffer "*Help*"
19842 (princ "User-defined Speed commands\n===========================\n")
19843 (mapc #'org-print-speed-command org-speed-commands-user)
19844 (princ "\n")
19845 (princ "Built-in Speed commands\n=======================\n")
19846 (mapc #'org-print-speed-command org-speed-commands-default))
19847 (with-current-buffer "*Help*"
19848 (setq truncate-lines t))))
19850 (defun org-speed-move-safe (cmd)
19851 "Execute CMD, but make sure that the cursor always ends up in a headline.
19852 If not, return to the original position and throw an error."
19853 (interactive)
19854 (let ((pos (point)))
19855 (call-interactively cmd)
19856 (unless (and (bolp) (org-at-heading-p))
19857 (goto-char pos)
19858 (error "Boundary reached while executing %s" cmd))))
19860 (defvar org-self-insert-command-undo-counter 0)
19862 (defvar org-table-auto-blank-field) ; defined in org-table.el
19863 (defvar org-speed-command nil)
19865 (defun org-speed-command-activate (keys)
19866 "Hook for activating single-letter speed commands.
19867 `org-speed-commands-default' specifies a minimal command set.
19868 Use `org-speed-commands-user' for further customization."
19869 (when (or (and (bolp) (looking-at org-outline-regexp))
19870 (and (functionp org-use-speed-commands)
19871 (funcall org-use-speed-commands)))
19872 (cdr (assoc keys (append org-speed-commands-user
19873 org-speed-commands-default)))))
19875 (defun org-babel-speed-command-activate (keys)
19876 "Hook for activating single-letter code block commands."
19877 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19878 (cdr (assoc keys org-babel-key-bindings))))
19880 (defcustom org-speed-command-hook
19881 '(org-speed-command-activate org-babel-speed-command-activate)
19882 "Hook for activating speed commands at strategic locations.
19883 Hook functions are called in sequence until a valid handler is
19884 found.
19886 Each hook takes a single argument, a user-pressed command key
19887 which is also a `self-insert-command' from the global map.
19889 Within the hook, examine the cursor position and the command key
19890 and return nil or a valid handler as appropriate. Handler could
19891 be one of an interactive command, a function, or a form.
19893 Set `org-use-speed-commands' to non-nil value to enable this
19894 hook. The default setting is `org-speed-command-activate'."
19895 :group 'org-structure
19896 :version "24.1"
19897 :type 'hook)
19899 (defun org-self-insert-command (N)
19900 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19901 If the cursor is in a table looking at whitespace, the whitespace is
19902 overwritten, and the table is not marked as requiring realignment."
19903 (interactive "p")
19904 (org-check-before-invisible-edit 'insert)
19905 (cond
19906 ((and org-use-speed-commands
19907 (let ((kv (this-command-keys-vector)))
19908 (setq org-speed-command
19909 (run-hook-with-args-until-success
19910 'org-speed-command-hook
19911 (make-string 1 (aref kv (1- (length kv))))))))
19912 (cond
19913 ((commandp org-speed-command)
19914 (setq this-command org-speed-command)
19915 (call-interactively org-speed-command))
19916 ((functionp org-speed-command)
19917 (funcall org-speed-command))
19918 ((and org-speed-command (listp org-speed-command))
19919 (eval org-speed-command))
19920 (t (let (org-use-speed-commands)
19921 (call-interactively 'org-self-insert-command)))))
19922 ((and
19923 (org-at-table-p)
19924 (progn
19925 ;; Check if we blank the field, and if that triggers align.
19926 (and (featurep 'org-table) org-table-auto-blank-field
19927 (memq last-command
19928 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19929 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19930 ;; Got extra space, this field does not determine
19931 ;; column width.
19932 (let (org-table-may-need-update) (org-table-blank-field))
19933 ;; No extra space, this field may determine column
19934 ;; width.
19935 (org-table-blank-field)))
19937 (eq N 1)
19938 (looking-at "[^|\n]* \\( \\)|"))
19939 ;; There is room for insertion without re-aligning the table.
19940 (delete-region (match-beginning 1) (match-end 1))
19941 (self-insert-command N))
19943 (setq org-table-may-need-update t)
19944 (self-insert-command N)
19945 (org-fix-tags-on-the-fly)
19946 (when org-self-insert-cluster-for-undo
19947 (if (not (eq last-command 'org-self-insert-command))
19948 (setq org-self-insert-command-undo-counter 1)
19949 (if (>= org-self-insert-command-undo-counter 20)
19950 (setq org-self-insert-command-undo-counter 1)
19951 (and (> org-self-insert-command-undo-counter 0)
19952 buffer-undo-list (listp buffer-undo-list)
19953 (not (cadr buffer-undo-list)) ; remove nil entry
19954 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19955 (setq org-self-insert-command-undo-counter
19956 (1+ org-self-insert-command-undo-counter))))))))
19958 (defun org-check-before-invisible-edit (kind)
19959 "Check is editing if kind KIND would be dangerous with invisible text around.
19960 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19961 ;; First, try to get out of here as quickly as possible, to reduce overhead
19962 (when (and org-catch-invisible-edits
19963 (or (not (boundp 'visible-mode)) (not visible-mode))
19964 (or (get-char-property (point) 'invisible)
19965 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19966 ;; OK, we need to take a closer look
19967 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19968 (invisible-before-point (unless (bobp) (get-char-property
19969 (1- (point)) 'invisible)))
19970 (border-and-ok-direction
19972 ;; Check if we are acting predictably before invisible text
19973 (and invisible-at-point (not invisible-before-point)
19974 (memq kind '(insert delete-backward)))
19975 ;; Check if we are acting predictably after invisible text
19976 ;; This works not well, and I have turned it off. It seems
19977 ;; better to always show and stop after invisible text.
19978 ;; (and (not invisible-at-point) invisible-before-point
19979 ;; (memq kind '(insert delete)))
19981 (when (or (memq invisible-at-point '(outline org-hide-block t))
19982 (memq invisible-before-point '(outline org-hide-block t)))
19983 (when (eq org-catch-invisible-edits 'error)
19984 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19985 (if (and org-custom-properties-overlays
19986 (y-or-n-p "Display invisible properties in this buffer? "))
19987 (org-toggle-custom-properties-visibility)
19988 ;; Make the area visible
19989 (save-excursion
19990 (when invisible-before-point
19991 (goto-char (previous-single-char-property-change
19992 (point) 'invisible)))
19993 (outline-show-subtree))
19994 (cond
19995 ((eq org-catch-invisible-edits 'show)
19996 ;; That's it, we do the edit after showing
19997 (message
19998 "Unfolding invisible region around point before editing")
19999 (sit-for 1))
20000 ((and (eq org-catch-invisible-edits 'smart)
20001 border-and-ok-direction)
20002 (message "Unfolding invisible region around point before editing"))
20004 ;; Don't do the edit, make the user repeat it in full visibility
20005 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20007 (defun org-fix-tags-on-the-fly ()
20008 "Align tags in headline at point.
20009 Unlike to `org-set-tags', it ignores region and sorting."
20010 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20011 (org-at-heading-p))
20012 (let ((org-ignore-region t)
20013 (org-tags-sort-function nil))
20014 (org-set-tags nil t))))
20016 (defun org-delete-backward-char (N)
20017 "Like `delete-backward-char', insert whitespace at field end in tables.
20018 When deleting backwards, in tables this function will insert whitespace in
20019 front of the next \"|\" separator, to keep the table aligned. The table will
20020 still be marked for re-alignment if the field did fill the entire column,
20021 because, in this case the deletion might narrow the column."
20022 (interactive "p")
20023 (save-match-data
20024 (org-check-before-invisible-edit 'delete-backward)
20025 (if (and (org-at-table-p)
20026 (eq N 1)
20027 (string-match "|" (buffer-substring (point-at-bol) (point)))
20028 (looking-at ".*?|"))
20029 (let ((pos (point))
20030 (noalign (looking-at "[^|\n\r]* |"))
20031 (c org-table-may-need-update))
20032 (backward-delete-char N)
20033 (unless overwrite-mode
20034 (skip-chars-forward "^|")
20035 (insert " ")
20036 (goto-char (1- pos)))
20037 ;; noalign: if there were two spaces at the end, this field
20038 ;; does not determine the width of the column.
20039 (when noalign (setq org-table-may-need-update c)))
20040 (backward-delete-char N)
20041 (org-fix-tags-on-the-fly))))
20043 (defun org-delete-char (N)
20044 "Like `delete-char', but insert whitespace at field end in tables.
20045 When deleting characters, in tables this function will insert whitespace in
20046 front of the next \"|\" separator, to keep the table aligned. The table will
20047 still be marked for re-alignment if the field did fill the entire column,
20048 because, in this case the deletion might narrow the column."
20049 (interactive "p")
20050 (save-match-data
20051 (org-check-before-invisible-edit 'delete)
20052 (if (and (org-at-table-p)
20053 (not (bolp))
20054 (not (= (char-after) ?|))
20055 (eq N 1))
20056 (if (looking-at ".*?|")
20057 (let ((pos (point))
20058 (noalign (looking-at "[^|\n\r]* |"))
20059 (c org-table-may-need-update))
20060 (replace-match
20061 (concat (substring (match-string 0) 1 -1) " |") nil t)
20062 (goto-char pos)
20063 ;; noalign: if there were two spaces at the end, this field
20064 ;; does not determine the width of the column.
20065 (when noalign (setq org-table-may-need-update c)))
20066 (delete-char N))
20067 (delete-char N)
20068 (org-fix-tags-on-the-fly))))
20070 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20071 (put 'org-self-insert-command 'delete-selection
20072 (lambda ()
20073 (not (run-hook-with-args-until-success
20074 'self-insert-uses-region-functions))))
20075 (put 'orgtbl-self-insert-command 'delete-selection
20076 (lambda ()
20077 (not (run-hook-with-args-until-success
20078 'self-insert-uses-region-functions))))
20079 (put 'org-delete-char 'delete-selection 'supersede)
20080 (put 'org-delete-backward-char 'delete-selection 'supersede)
20081 (put 'org-yank 'delete-selection 'yank)
20083 ;; Make `flyspell-mode' delay after some commands
20084 (put 'org-self-insert-command 'flyspell-delayed t)
20085 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20086 (put 'org-delete-char 'flyspell-delayed t)
20087 (put 'org-delete-backward-char 'flyspell-delayed t)
20089 ;; Make pabbrev-mode expand after Org mode commands
20090 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20091 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20093 (defun org-remap (map &rest commands)
20094 "In MAP, remap the functions given in COMMANDS.
20095 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20096 (let (new old)
20097 (while commands
20098 (setq old (pop commands) new (pop commands))
20099 (org-defkey map (vector 'remap old) new))))
20101 (defun org-transpose-words ()
20102 "Transpose words for Org.
20103 This uses the `org-mode-transpose-word-syntax-table' syntax
20104 table, which interprets characters in `org-emphasis-alist' as
20105 word constituents."
20106 (interactive)
20107 (with-syntax-table org-mode-transpose-word-syntax-table
20108 (call-interactively 'transpose-words)))
20109 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20111 (when (eq org-enable-table-editor 'optimized)
20112 ;; If the user wants maximum table support, we need to hijack
20113 ;; some standard editing functions
20114 (org-remap org-mode-map
20115 'self-insert-command 'org-self-insert-command
20116 'delete-char 'org-delete-char
20117 'delete-backward-char 'org-delete-backward-char)
20118 (org-defkey org-mode-map "|" 'org-force-self-insert))
20120 (defvar org-ctrl-c-ctrl-c-hook nil
20121 "Hook for functions attaching themselves to `C-c C-c'.
20123 This can be used to add additional functionality to the C-c C-c
20124 key which executes context-dependent commands. This hook is run
20125 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20126 run after the last test.
20128 Each function will be called with no arguments. The function
20129 must check if the context is appropriate for it to act. If yes,
20130 it should do its thing and then return a non-nil value. If the
20131 context is wrong, just do nothing and return nil.")
20133 (defvar org-ctrl-c-ctrl-c-final-hook nil
20134 "Hook for functions attaching themselves to `C-c C-c'.
20136 This can be used to add additional functionality to the C-c C-c
20137 key which executes context-dependent commands. This hook is run
20138 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20139 before the first test.
20141 Each function will be called with no arguments. The function
20142 must check if the context is appropriate for it to act. If yes,
20143 it should do its thing and then return a non-nil value. If the
20144 context is wrong, just do nothing and return nil.")
20146 (defvar org-tab-first-hook nil
20147 "Hook for functions to attach themselves to TAB.
20148 See `org-ctrl-c-ctrl-c-hook' for more information.
20149 This hook runs as the first action when TAB is pressed, even before
20150 `org-cycle' messes around with the `outline-regexp' to cater for
20151 inline tasks and plain list item folding.
20152 If any function in this hook returns t, any other actions that
20153 would have been caused by TAB (such as table field motion or visibility
20154 cycling) will not occur.")
20156 (defvar org-tab-after-check-for-table-hook nil
20157 "Hook for functions to attach themselves to TAB.
20158 See `org-ctrl-c-ctrl-c-hook' for more information.
20159 This hook runs after it has been established that the cursor is not in a
20160 table, but before checking if the cursor is in a headline or if global cycling
20161 should be done.
20162 If any function in this hook returns t, not other actions like visibility
20163 cycling will be done.")
20165 (defvar org-tab-after-check-for-cycling-hook nil
20166 "Hook for functions to attach themselves to TAB.
20167 See `org-ctrl-c-ctrl-c-hook' for more information.
20168 This hook runs after it has been established that not table field motion and
20169 not visibility should be done because of current context. This is probably
20170 the place where a package like yasnippets can hook in.")
20172 (defvar org-tab-before-tab-emulation-hook nil
20173 "Hook for functions to attach themselves to TAB.
20174 See `org-ctrl-c-ctrl-c-hook' for more information.
20175 This hook runs after every other options for TAB have been exhausted, but
20176 before indentation and \t insertion takes place.")
20178 (defvar org-metaleft-hook nil
20179 "Hook for functions attaching themselves to `M-left'.
20180 See `org-ctrl-c-ctrl-c-hook' for more information.")
20181 (defvar org-metaright-hook nil
20182 "Hook for functions attaching themselves to `M-right'.
20183 See `org-ctrl-c-ctrl-c-hook' for more information.")
20184 (defvar org-metaup-hook nil
20185 "Hook for functions attaching themselves to `M-up'.
20186 See `org-ctrl-c-ctrl-c-hook' for more information.")
20187 (defvar org-metadown-hook nil
20188 "Hook for functions attaching themselves to `M-down'.
20189 See `org-ctrl-c-ctrl-c-hook' for more information.")
20190 (defvar org-shiftmetaleft-hook nil
20191 "Hook for functions attaching themselves to `M-S-left'.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftmetaright-hook nil
20194 "Hook for functions attaching themselves to `M-S-right'.
20195 See `org-ctrl-c-ctrl-c-hook' for more information.")
20196 (defvar org-shiftmetaup-hook nil
20197 "Hook for functions attaching themselves to `M-S-up'.
20198 See `org-ctrl-c-ctrl-c-hook' for more information.")
20199 (defvar org-shiftmetadown-hook nil
20200 "Hook for functions attaching themselves to `M-S-down'.
20201 See `org-ctrl-c-ctrl-c-hook' for more information.")
20202 (defvar org-metareturn-hook nil
20203 "Hook for functions attaching themselves to `M-RET'.
20204 See `org-ctrl-c-ctrl-c-hook' for more information.")
20205 (defvar org-shiftup-hook nil
20206 "Hook for functions attaching themselves to `S-up'.
20207 See `org-ctrl-c-ctrl-c-hook' for more information.")
20208 (defvar org-shiftup-final-hook nil
20209 "Hook for functions attaching themselves to `S-up'.
20210 This one runs after all other options except shift-select have been excluded.
20211 See `org-ctrl-c-ctrl-c-hook' for more information.")
20212 (defvar org-shiftdown-hook nil
20213 "Hook for functions attaching themselves to `S-down'.
20214 See `org-ctrl-c-ctrl-c-hook' for more information.")
20215 (defvar org-shiftdown-final-hook nil
20216 "Hook for functions attaching themselves to `S-down'.
20217 This one runs after all other options except shift-select have been excluded.
20218 See `org-ctrl-c-ctrl-c-hook' for more information.")
20219 (defvar org-shiftleft-hook nil
20220 "Hook for functions attaching themselves to `S-left'.
20221 See `org-ctrl-c-ctrl-c-hook' for more information.")
20222 (defvar org-shiftleft-final-hook nil
20223 "Hook for functions attaching themselves to `S-left'.
20224 This one runs after all other options except shift-select have been excluded.
20225 See `org-ctrl-c-ctrl-c-hook' for more information.")
20226 (defvar org-shiftright-hook nil
20227 "Hook for functions attaching themselves to `S-right'.
20228 See `org-ctrl-c-ctrl-c-hook' for more information.")
20229 (defvar org-shiftright-final-hook nil
20230 "Hook for functions attaching themselves to `S-right'.
20231 This one runs after all other options except shift-select have been excluded.
20232 See `org-ctrl-c-ctrl-c-hook' for more information.")
20234 (defun org-modifier-cursor-error ()
20235 "Throw an error, a modified cursor command was applied in wrong context."
20236 (user-error "This command is active in special context like tables, headlines or items"))
20238 (defun org-shiftselect-error ()
20239 "Throw an error because Shift-Cursor command was applied in wrong context."
20240 (if (and (boundp 'shift-select-mode) shift-select-mode)
20241 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20242 (user-error "This command works only in special context like headlines or timestamps")))
20244 (defun org-call-for-shift-select (cmd)
20245 (let ((this-command-keys-shift-translated t))
20246 (call-interactively cmd)))
20248 (defun org-shifttab (&optional arg)
20249 "Global visibility cycling or move to previous table field.
20250 Call `org-table-previous-field' within a table.
20251 When ARG is nil, cycle globally through visibility states.
20252 When ARG is a numeric prefix, show contents of this level."
20253 (interactive "P")
20254 (cond
20255 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20256 ((integerp arg)
20257 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20258 (message "Content view to level: %d" arg)
20259 (org-content (prefix-numeric-value arg2))
20260 (org-cycle-show-empty-lines t)
20261 (setq org-cycle-global-status 'overview)))
20262 (t (call-interactively 'org-global-cycle))))
20264 (defun org-shiftmetaleft ()
20265 "Promote subtree or delete table column.
20266 Calls `org-promote-subtree', `org-outdent-item-tree', or
20267 `org-table-delete-column', depending on context. See the
20268 individual commands for more information."
20269 (interactive)
20270 (cond
20271 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20272 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20273 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20274 ((if (not (org-region-active-p)) (org-at-item-p)
20275 (save-excursion (goto-char (region-beginning))
20276 (org-at-item-p)))
20277 (call-interactively 'org-outdent-item-tree))
20278 (t (org-modifier-cursor-error))))
20280 (defun org-shiftmetaright ()
20281 "Demote subtree or insert table column.
20282 Calls `org-demote-subtree', `org-indent-item-tree', or
20283 `org-table-insert-column', depending on context. See the
20284 individual commands for more information."
20285 (interactive)
20286 (cond
20287 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20288 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20289 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20290 ((if (not (org-region-active-p)) (org-at-item-p)
20291 (save-excursion (goto-char (region-beginning))
20292 (org-at-item-p)))
20293 (call-interactively 'org-indent-item-tree))
20294 (t (org-modifier-cursor-error))))
20296 (defun org-shiftmetaup (&optional _arg)
20297 "Drag the line at point up.
20298 In a table, kill the current row.
20299 On a clock timestamp, update the value of the timestamp like `S-<up>'
20300 but also adjust the previous clocked item in the clock history.
20301 Everywhere else, drag the line at point up."
20302 (interactive "P")
20303 (cond
20304 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20305 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20306 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20307 (call-interactively 'org-timestamp-up)))
20308 (t (call-interactively 'org-drag-line-backward))))
20310 (defun org-shiftmetadown (&optional _arg)
20311 "Drag the line at point down.
20312 In a table, insert an empty row at the current line.
20313 On a clock timestamp, update the value of the timestamp like `S-<down>'
20314 but also adjust the previous clocked item in the clock history.
20315 Everywhere else, drag the line at point down."
20316 (interactive "P")
20317 (cond
20318 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20319 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20320 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20321 (call-interactively 'org-timestamp-down)))
20322 (t (call-interactively 'org-drag-line-forward))))
20324 (defsubst org-hidden-tree-error ()
20325 (user-error
20326 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20328 (defun org-metaleft (&optional _arg)
20329 "Promote heading, list item at point or move table column left.
20331 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20332 depending on context. With no specific context, calls the Emacs
20333 default `backward-word'. See the individual commands for more
20334 information.
20336 This function runs the hook `org-metaleft-hook' as a first step,
20337 and returns at first non-nil value."
20338 (interactive "P")
20339 (cond
20340 ((run-hook-with-args-until-success 'org-metaleft-hook))
20341 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20342 ((org-with-limited-levels
20343 (or (org-at-heading-p)
20344 (and (org-region-active-p)
20345 (save-excursion
20346 (goto-char (region-beginning))
20347 (org-at-heading-p)))))
20348 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20349 (call-interactively 'org-do-promote))
20350 ;; At an inline task.
20351 ((org-at-heading-p)
20352 (call-interactively 'org-inlinetask-promote))
20353 ((or (org-at-item-p)
20354 (and (org-region-active-p)
20355 (save-excursion
20356 (goto-char (region-beginning))
20357 (org-at-item-p))))
20358 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20359 (call-interactively 'org-outdent-item))
20360 (t (call-interactively 'backward-word))))
20362 (defun org-metaright (&optional _arg)
20363 "Demote heading, list item at point or move table column right.
20365 In front of a drawer or a block keyword, indent it correctly.
20367 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20368 `org-indent-drawer' or `org-indent-block' depending on context.
20369 With no specific context, calls the Emacs default `forward-word'.
20370 See the individual commands for more information.
20372 This function runs the hook `org-metaright-hook' as a first step,
20373 and returns at first non-nil value."
20374 (interactive "P")
20375 (cond
20376 ((run-hook-with-args-until-success 'org-metaright-hook))
20377 ((org-at-table-p) (call-interactively 'org-table-move-column))
20378 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20379 ((org-at-block-p) (call-interactively 'org-indent-block))
20380 ((org-with-limited-levels
20381 (or (org-at-heading-p)
20382 (and (org-region-active-p)
20383 (save-excursion
20384 (goto-char (region-beginning))
20385 (org-at-heading-p)))))
20386 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20387 (call-interactively 'org-do-demote))
20388 ;; At an inline task.
20389 ((org-at-heading-p)
20390 (call-interactively 'org-inlinetask-demote))
20391 ((or (org-at-item-p)
20392 (and (org-region-active-p)
20393 (save-excursion
20394 (goto-char (region-beginning))
20395 (org-at-item-p))))
20396 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20397 (call-interactively 'org-indent-item))
20398 (t (call-interactively 'forward-word))))
20400 (defun org-check-for-hidden (what)
20401 "Check if there are hidden headlines/items in the current visual line.
20402 WHAT can be either `headlines' or `items'. If the current line is
20403 an outline or item heading and it has a folded subtree below it,
20404 this function returns t, nil otherwise."
20405 (let ((re (cond
20406 ((eq what 'headlines) org-outline-regexp-bol)
20407 ((eq what 'items) (org-item-beginning-re))
20408 (t (error "This should not happen"))))
20409 beg end)
20410 (save-excursion
20411 (catch 'exit
20412 (unless (org-region-active-p)
20413 (setq beg (point-at-bol))
20414 (beginning-of-line 2)
20415 (while (and (not (eobp)) ;; this is like `next-line'
20416 (get-char-property (1- (point)) 'invisible))
20417 (beginning-of-line 2))
20418 (setq end (point))
20419 (goto-char beg)
20420 (goto-char (point-at-eol))
20421 (setq end (max end (point)))
20422 (while (re-search-forward re end t)
20423 (when (get-char-property (match-beginning 0) 'invisible)
20424 (throw 'exit t))))
20425 nil))))
20427 (defun org-metaup (&optional _arg)
20428 "Move subtree up or move table row up.
20429 Calls `org-move-subtree-up' or `org-table-move-row' or
20430 `org-move-item-up', depending on context. See the individual commands
20431 for more information."
20432 (interactive "P")
20433 (cond
20434 ((run-hook-with-args-until-success 'org-metaup-hook))
20435 ((org-region-active-p)
20436 (let* ((a (min (region-beginning) (region-end)))
20437 (b (1- (max (region-beginning) (region-end))))
20438 (c (save-excursion (goto-char a)
20439 (move-beginning-of-line 0)))
20440 (d (save-excursion (goto-char a)
20441 (move-end-of-line 0) (point))))
20442 (transpose-regions a b c d)
20443 (goto-char c)))
20444 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20445 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20446 ((org-at-item-p) (call-interactively 'org-move-item-up))
20447 (t (org-drag-element-backward))))
20449 (defun org-metadown (&optional _arg)
20450 "Move subtree down or move table row down.
20451 Calls `org-move-subtree-down' or `org-table-move-row' or
20452 `org-move-item-down', depending on context. See the individual
20453 commands for more information."
20454 (interactive "P")
20455 (cond
20456 ((run-hook-with-args-until-success 'org-metadown-hook))
20457 ((org-region-active-p)
20458 (let* ((a (min (region-beginning) (region-end)))
20459 (b (max (region-beginning) (region-end)))
20460 (c (save-excursion (goto-char b)
20461 (move-beginning-of-line 1)))
20462 (d (save-excursion (goto-char b)
20463 (move-end-of-line 1) (1+ (point)))))
20464 (transpose-regions a b c d)
20465 (goto-char d)))
20466 ((org-at-table-p) (call-interactively 'org-table-move-row))
20467 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20468 ((org-at-item-p) (call-interactively 'org-move-item-down))
20469 (t (org-drag-element-forward))))
20471 (defun org-shiftup (&optional arg)
20472 "Increase item in timestamp or increase priority of current headline.
20473 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20474 depending on context. See the individual commands for more information."
20475 (interactive "P")
20476 (cond
20477 ((run-hook-with-args-until-success 'org-shiftup-hook))
20478 ((and org-support-shift-select (org-region-active-p))
20479 (org-call-for-shift-select 'previous-line))
20480 ((org-at-timestamp-p 'lax)
20481 (call-interactively (if org-edit-timestamp-down-means-later
20482 'org-timestamp-down 'org-timestamp-up)))
20483 ((and (not (eq org-support-shift-select 'always))
20484 org-enable-priority-commands
20485 (org-at-heading-p))
20486 (call-interactively 'org-priority-up))
20487 ((and (not org-support-shift-select) (org-at-item-p))
20488 (call-interactively 'org-previous-item))
20489 ((org-clocktable-try-shift 'up arg))
20490 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20491 (org-support-shift-select
20492 (org-call-for-shift-select 'previous-line))
20493 (t (org-shiftselect-error))))
20495 (defun org-shiftdown (&optional arg)
20496 "Decrease item in timestamp or decrease priority of current headline.
20497 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20498 depending on context. See the individual commands for more information."
20499 (interactive "P")
20500 (cond
20501 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20502 ((and org-support-shift-select (org-region-active-p))
20503 (org-call-for-shift-select 'next-line))
20504 ((org-at-timestamp-p 'lax)
20505 (call-interactively (if org-edit-timestamp-down-means-later
20506 'org-timestamp-up 'org-timestamp-down)))
20507 ((and (not (eq org-support-shift-select 'always))
20508 org-enable-priority-commands
20509 (org-at-heading-p))
20510 (call-interactively 'org-priority-down))
20511 ((and (not org-support-shift-select) (org-at-item-p))
20512 (call-interactively 'org-next-item))
20513 ((org-clocktable-try-shift 'down arg))
20514 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20515 (org-support-shift-select
20516 (org-call-for-shift-select 'next-line))
20517 (t (org-shiftselect-error))))
20519 (defun org-shiftright (&optional arg)
20520 "Cycle the thing at point or in the current line, depending on context.
20521 Depending on context, this does one of the following:
20523 - switch a timestamp at point one day into the future
20524 - on a headline, switch to the next TODO keyword.
20525 - on an item, switch entire list to the next bullet type
20526 - on a property line, switch to the next allowed value
20527 - on a clocktable definition line, move time block into the future"
20528 (interactive "P")
20529 (cond
20530 ((run-hook-with-args-until-success 'org-shiftright-hook))
20531 ((and org-support-shift-select (org-region-active-p))
20532 (org-call-for-shift-select 'forward-char))
20533 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20534 ((and (not (eq org-support-shift-select 'always))
20535 (org-at-heading-p))
20536 (let ((org-inhibit-logging
20537 (not org-treat-S-cursor-todo-selection-as-state-change))
20538 (org-inhibit-blocking
20539 (not org-treat-S-cursor-todo-selection-as-state-change)))
20540 (org-call-with-arg 'org-todo 'right)))
20541 ((or (and org-support-shift-select
20542 (not (eq org-support-shift-select 'always))
20543 (org-at-item-bullet-p))
20544 (and (not org-support-shift-select) (org-at-item-p)))
20545 (org-call-with-arg 'org-cycle-list-bullet nil))
20546 ((and (not (eq org-support-shift-select 'always))
20547 (org-at-property-p))
20548 (call-interactively 'org-property-next-allowed-value))
20549 ((org-clocktable-try-shift 'right arg))
20550 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20551 (org-support-shift-select
20552 (org-call-for-shift-select 'forward-char))
20553 (t (org-shiftselect-error))))
20555 (defun org-shiftleft (&optional arg)
20556 "Cycle the thing at point or in the current line, depending on context.
20557 Depending on context, this does one of the following:
20559 - switch a timestamp at point one day into the past
20560 - on a headline, switch to the previous TODO keyword.
20561 - on an item, switch entire list to the previous bullet type
20562 - on a property line, switch to the previous allowed value
20563 - on a clocktable definition line, move time block into the past"
20564 (interactive "P")
20565 (cond
20566 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20567 ((and org-support-shift-select (org-region-active-p))
20568 (org-call-for-shift-select 'backward-char))
20569 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20570 ((and (not (eq org-support-shift-select 'always))
20571 (org-at-heading-p))
20572 (let ((org-inhibit-logging
20573 (not org-treat-S-cursor-todo-selection-as-state-change))
20574 (org-inhibit-blocking
20575 (not org-treat-S-cursor-todo-selection-as-state-change)))
20576 (org-call-with-arg 'org-todo 'left)))
20577 ((or (and org-support-shift-select
20578 (not (eq org-support-shift-select 'always))
20579 (org-at-item-bullet-p))
20580 (and (not org-support-shift-select) (org-at-item-p)))
20581 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20582 ((and (not (eq org-support-shift-select 'always))
20583 (org-at-property-p))
20584 (call-interactively 'org-property-previous-allowed-value))
20585 ((org-clocktable-try-shift 'left arg))
20586 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20587 (org-support-shift-select
20588 (org-call-for-shift-select 'backward-char))
20589 (t (org-shiftselect-error))))
20591 (defun org-shiftcontrolright ()
20592 "Switch to next TODO set."
20593 (interactive)
20594 (cond
20595 ((and org-support-shift-select (org-region-active-p))
20596 (org-call-for-shift-select 'forward-word))
20597 ((and (not (eq org-support-shift-select 'always))
20598 (org-at-heading-p))
20599 (org-call-with-arg 'org-todo 'nextset))
20600 (org-support-shift-select
20601 (org-call-for-shift-select 'forward-word))
20602 (t (org-shiftselect-error))))
20604 (defun org-shiftcontrolleft ()
20605 "Switch to previous TODO set."
20606 (interactive)
20607 (cond
20608 ((and org-support-shift-select (org-region-active-p))
20609 (org-call-for-shift-select 'backward-word))
20610 ((and (not (eq org-support-shift-select 'always))
20611 (org-at-heading-p))
20612 (org-call-with-arg 'org-todo 'previousset))
20613 (org-support-shift-select
20614 (org-call-for-shift-select 'backward-word))
20615 (t (org-shiftselect-error))))
20617 (defun org-shiftcontrolup (&optional n)
20618 "Change timestamps synchronously up in CLOCK log lines.
20619 Optional argument N tells to change by that many units."
20620 (interactive "P")
20621 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20622 (let (org-support-shift-select)
20623 (org-clock-timestamps-up n))
20624 (user-error "Not at a clock log")))
20626 (defun org-shiftcontroldown (&optional n)
20627 "Change timestamps synchronously down in CLOCK log lines.
20628 Optional argument N tells to change by that many units."
20629 (interactive "P")
20630 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20631 (let (org-support-shift-select)
20632 (org-clock-timestamps-down n))
20633 (user-error "Not at a clock log")))
20635 (defun org-increase-number-at-point (&optional inc)
20636 "Increment the number at point.
20637 With an optional prefix numeric argument INC, increment using
20638 this numeric value."
20639 (interactive "p")
20640 (if (not (number-at-point))
20641 (user-error "Not on a number")
20642 (unless inc (setq inc 1))
20643 (let ((pos (point))
20644 (beg (skip-chars-backward "-+^/*0-9eE."))
20645 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20646 (setq nap (buffer-substring-no-properties
20647 (+ pos beg) (+ pos beg end)))
20648 (delete-region (+ pos beg) (+ pos beg end))
20649 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20650 (when (org-at-table-p)
20651 (org-table-align)
20652 (org-table-end-of-field 1))))
20654 (defun org-decrease-number-at-point (&optional inc)
20655 "Decrement the number at point.
20656 With an optional prefix numeric argument INC, decrement using
20657 this numeric value."
20658 (interactive "p")
20659 (org-increase-number-at-point (- (or inc 1))))
20661 (defun org-ctrl-c-ret ()
20662 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20663 (interactive)
20664 (cond
20665 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20666 (t (call-interactively 'org-insert-heading))))
20668 (defun org-find-visible ()
20669 (let ((s (point)))
20670 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20671 (get-char-property s 'invisible)))
20673 (defun org-find-invisible ()
20674 (let ((s (point)))
20675 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20676 (not (get-char-property s 'invisible))))
20679 (defun org-copy-visible (beg end)
20680 "Copy the visible parts of the region."
20681 (interactive "r")
20682 (let (snippets s)
20683 (save-excursion
20684 (save-restriction
20685 (narrow-to-region beg end)
20686 (setq s (goto-char (point-min)))
20687 (while (not (= (point) (point-max)))
20688 (goto-char (org-find-invisible))
20689 (push (buffer-substring s (point)) snippets)
20690 (setq s (goto-char (org-find-visible))))))
20691 (kill-new (apply 'concat (nreverse snippets)))))
20693 (defun org-copy-special ()
20694 "Copy region in table or copy current subtree.
20695 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20696 context. See the individual commands for more information."
20697 (interactive)
20698 (call-interactively
20699 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20701 (defun org-cut-special ()
20702 "Cut region in table or cut current subtree.
20703 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20704 context. See the individual commands for more information."
20705 (interactive)
20706 (call-interactively
20707 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20709 (defun org-paste-special (arg)
20710 "Paste rectangular region into table, or past subtree relative to level.
20711 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20712 See the individual commands for more information."
20713 (interactive "P")
20714 (if (org-at-table-p)
20715 (org-table-paste-rectangle)
20716 (org-paste-subtree arg)))
20718 (defun org-edit-special (&optional arg)
20719 "Call a special editor for the element at point.
20720 When at a table, call the formula editor with `org-table-edit-formulas'.
20721 When in a source code block, call `org-edit-src-code'.
20722 When in a fixed-width region, call `org-edit-fixed-width-region'.
20723 When in an export block, call `org-edit-export-block'.
20724 When in a LaTeX environment, call `org-edit-latex-environment'.
20725 When at an #+INCLUDE keyword, visit the included file.
20726 When at a footnote reference, call `org-edit-footnote-reference'
20727 On a link, call `ffap' to visit the link at point.
20728 Otherwise, return a user error."
20729 (interactive "P")
20730 (let ((element (org-element-at-point)))
20731 (barf-if-buffer-read-only)
20732 (pcase (org-element-type element)
20733 (`src-block
20734 (if (not arg) (org-edit-src-code)
20735 (let* ((info (org-babel-get-src-block-info))
20736 (lang (nth 0 info))
20737 (params (nth 2 info))
20738 (session (cdr (assq :session params))))
20739 (if (not session) (org-edit-src-code)
20740 ;; At a src-block with a session and function called with
20741 ;; an ARG: switch to the buffer related to the inferior
20742 ;; process.
20743 (switch-to-buffer
20744 (funcall (intern (concat "org-babel-prep-session:" lang))
20745 session params))))))
20746 (`keyword
20747 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20748 (org-open-link-from-string
20749 (format "[[%s]]"
20750 (expand-file-name
20751 (let ((value (org-element-property :value element)))
20752 (cond ((org-file-url-p value)
20753 (user-error "The file is specified as a URL, cannot be edited"))
20754 ((not (org-string-nw-p value))
20755 (user-error "No file to edit"))
20756 ((string-match "\\`\"\\(.*?\\)\"" value)
20757 (match-string 1 value))
20758 ((string-match "\\`[^ \t\"]\\S-*" value)
20759 (match-string 0 value))
20760 (t (user-error "No valid file specified")))))))
20761 (user-error "No special environment to edit here")))
20762 (`table
20763 (if (eq (org-element-property :type element) 'table.el)
20764 (org-edit-table.el)
20765 (call-interactively 'org-table-edit-formulas)))
20766 ;; Only Org tables contain `table-row' type elements.
20767 (`table-row (call-interactively 'org-table-edit-formulas))
20768 (`example-block (org-edit-src-code))
20769 (`export-block (org-edit-export-block))
20770 (`fixed-width (org-edit-fixed-width-region))
20771 (`latex-environment (org-edit-latex-environment))
20773 ;; No notable element at point. Though, we may be at a link or
20774 ;; a footnote reference, which are objects. Thus, scan deeper.
20775 (let ((context (org-element-context element)))
20776 (pcase (org-element-type context)
20777 (`footnote-reference (org-edit-footnote-reference))
20778 (`inline-src-block (org-edit-inline-src-code))
20779 (`link (call-interactively #'ffap))
20780 (_ (user-error "No special environment to edit here"))))))))
20782 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20783 (defun org-ctrl-c-ctrl-c (&optional arg)
20784 "Set tags in headline, or update according to changed information at point.
20786 This command does many different things, depending on context:
20788 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20789 this is what we do.
20791 - If the cursor is on a statistics cookie, update it.
20793 - If the cursor is in a headline, prompt for tags and insert them
20794 into the current line, aligned to `org-tags-column'. When called
20795 with prefix arg, realign all tags in the current buffer.
20797 - If the cursor is in one of the special #+KEYWORD lines, this
20798 triggers scanning the buffer for these lines and updating the
20799 information.
20801 - If the cursor is inside a table, realign the table. This command
20802 works even if the automatic table editor has been turned off.
20804 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20805 the entire table.
20807 - If the cursor is at a footnote reference or definition, jump to
20808 the corresponding definition or references, respectively.
20810 - If the cursor is a the beginning of a dynamic block, update it.
20812 - If the current buffer is a capture buffer, close note and file it.
20814 - If the cursor is on a <<<target>>>, update radio targets and
20815 corresponding links in this buffer.
20817 - If the cursor is on a numbered item in a plain list, renumber the
20818 ordered list.
20820 - If the cursor is on a checkbox, toggle it.
20822 - If the cursor is on a code block, evaluate it. The variable
20823 `org-confirm-babel-evaluate' can be used to control prompting
20824 before code block evaluation, by default every code block
20825 evaluation requires confirmation. Code block evaluation can be
20826 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20827 (interactive "P")
20828 (cond
20829 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20830 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20831 (org-remove-occur-highlights)
20832 (message "Temporary highlights/overlays removed from current buffer"))
20833 ((and (local-variable-p 'org-finish-function)
20834 (fboundp org-finish-function))
20835 (funcall org-finish-function))
20836 ((org-babel-hash-at-point))
20837 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20839 (let* ((context
20840 (org-element-lineage
20841 (org-element-context)
20842 ;; Limit to supported contexts.
20843 '(babel-call clock dynamic-block footnote-definition
20844 footnote-reference inline-babel-call inline-src-block
20845 inlinetask item keyword node-property paragraph
20846 plain-list property-drawer radio-target src-block
20847 statistics-cookie table table-cell table-row
20848 timestamp)
20850 (type (org-element-type context)))
20851 ;; For convenience: at the first line of a paragraph on the same
20852 ;; line as an item, apply function on that item instead.
20853 (when (eq type 'paragraph)
20854 (let ((parent (org-element-property :parent context)))
20855 (when (and (eq (org-element-type parent) 'item)
20856 (= (line-beginning-position)
20857 (org-element-property :begin parent)))
20858 (setq context parent)
20859 (setq type 'item))))
20860 ;; Act according to type of element or object at point.
20862 ;; Do nothing on a blank line, except if it is contained in
20863 ;; a src block. Hence, we first check if point is in such
20864 ;; a block and then if it is at a blank line.
20865 (pcase type
20866 ((or `inline-src-block `src-block)
20867 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20868 (org-babel-eval-wipe-error-buffer)
20869 (org-babel-execute-src-block
20870 current-prefix-arg (org-babel-get-src-block-info nil context))))
20871 ((guard (org-match-line "[ \t]*$"))
20872 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20873 (user-error
20874 (substitute-command-keys
20875 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20876 ((or `babel-call `inline-babel-call)
20877 (let ((info (org-babel-lob-get-info context)))
20878 (when info (org-babel-execute-src-block nil info))))
20879 (`clock (org-clock-update-time-maybe))
20880 (`dynamic-block
20881 (save-excursion
20882 (goto-char (org-element-property :post-affiliated context))
20883 (org-update-dblock)))
20884 (`footnote-definition
20885 (goto-char (org-element-property :post-affiliated context))
20886 (call-interactively 'org-footnote-action))
20887 (`footnote-reference (call-interactively #'org-footnote-action))
20888 ((or `headline `inlinetask)
20889 (save-excursion (goto-char (org-element-property :begin context))
20890 (call-interactively #'org-set-tags)))
20891 (`item
20892 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20893 ;; unconditionally, whereas `C-u' will toggle its presence.
20894 ;; Without a universal argument, if the item has a checkbox,
20895 ;; toggle it. Otherwise repair the list.
20896 (let* ((box (org-element-property :checkbox context))
20897 (struct (org-element-property :structure context))
20898 (old-struct (copy-tree struct))
20899 (parents (org-list-parents-alist struct))
20900 (prevs (org-list-prevs-alist struct))
20901 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20902 (org-list-set-checkbox
20903 (org-element-property :begin context) struct
20904 (cond ((equal arg '(16)) "[-]")
20905 ((and (not box) (equal arg '(4))) "[ ]")
20906 ((or (not box) (equal arg '(4))) nil)
20907 ((eq box 'on) "[ ]")
20908 (t "[X]")))
20909 ;; Mimic `org-list-write-struct' but with grabbing a return
20910 ;; value from `org-list-struct-fix-box'.
20911 (org-list-struct-fix-ind struct parents 2)
20912 (org-list-struct-fix-item-end struct)
20913 (org-list-struct-fix-bul struct prevs)
20914 (org-list-struct-fix-ind struct parents)
20915 (let ((block-item
20916 (org-list-struct-fix-box struct parents prevs orderedp)))
20917 (if (and box (equal struct old-struct))
20918 (if (equal arg '(16))
20919 (message "Checkboxes already reset")
20920 (user-error "Cannot toggle this checkbox: %s"
20921 (if (eq box 'on)
20922 "all subitems checked"
20923 "unchecked subitems")))
20924 (org-list-struct-apply-struct struct old-struct)
20925 (org-update-checkbox-count-maybe))
20926 (when block-item
20927 (message "Checkboxes were removed due to empty box at line %d"
20928 (org-current-line block-item))))))
20929 (`keyword
20930 (let ((org-inhibit-startup-visibility-stuff t)
20931 (org-startup-align-all-tables nil))
20932 (when (boundp 'org-table-coordinate-overlays)
20933 (mapc #'delete-overlay org-table-coordinate-overlays)
20934 (setq org-table-coordinate-overlays nil))
20935 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20936 (message "Local setup has been refreshed"))
20937 (`plain-list
20938 ;; At a plain list, with a double C-u argument, set
20939 ;; checkboxes of each item to "[-]", whereas a single one
20940 ;; will toggle their presence according to the state of the
20941 ;; first item in the list. Without an argument, repair the
20942 ;; list.
20943 (let* ((begin (org-element-property :contents-begin context))
20944 (beginm (move-marker (make-marker) begin))
20945 (struct (org-element-property :structure context))
20946 (old-struct (copy-tree struct))
20947 (first-box (save-excursion
20948 (goto-char begin)
20949 (looking-at org-list-full-item-re)
20950 (match-string-no-properties 3)))
20951 (new-box (cond ((equal arg '(16)) "[-]")
20952 ((equal arg '(4)) (unless first-box "[ ]"))
20953 ((equal first-box "[X]") "[ ]")
20954 (t "[X]"))))
20955 (cond
20956 (arg
20957 (dolist (pos
20958 (org-list-get-all-items
20959 begin struct (org-list-prevs-alist struct)))
20960 (org-list-set-checkbox pos struct new-box)))
20961 ((and first-box (eq (point) begin))
20962 ;; For convenience, when point is at bol on the first
20963 ;; item of the list and no argument is provided, simply
20964 ;; toggle checkbox of that item, if any.
20965 (org-list-set-checkbox begin struct new-box)))
20966 (org-list-write-struct
20967 struct (org-list-parents-alist struct) old-struct)
20968 (org-update-checkbox-count-maybe)
20969 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20970 ((or `property-drawer `node-property)
20971 (call-interactively #'org-property-action))
20972 (`radio-target
20973 (call-interactively #'org-update-radio-target-regexp))
20974 (`statistics-cookie
20975 (call-interactively #'org-update-statistics-cookies))
20976 ((or `table `table-cell `table-row)
20977 ;; At a table, recalculate every field and align it. Also
20978 ;; send the table if necessary. If the table has
20979 ;; a `table.el' type, just give up. At a table row or cell,
20980 ;; maybe recalculate line but always align table.
20981 (if (eq (org-element-property :type context) 'table.el)
20982 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20983 Use `\\[org-edit-special]' to edit table.el tables"))
20984 (let ((org-enable-table-editor t))
20985 (if (or (eq type 'table)
20986 ;; Check if point is at a TBLFM line.
20987 (and (eq type 'table-row)
20988 (= (point) (org-element-property :end context))))
20989 (save-excursion
20990 (if (org-at-TBLFM-p)
20991 (progn (require 'org-table)
20992 (org-table-calc-current-TBLFM))
20993 (goto-char (org-element-property :contents-begin context))
20994 (org-call-with-arg 'org-table-recalculate (or arg t))
20995 (orgtbl-send-table 'maybe)))
20996 (org-table-maybe-eval-formula)
20997 (cond (arg (call-interactively #'org-table-recalculate))
20998 ((org-table-maybe-recalculate-line))
20999 (t (org-table-align)))))))
21000 (`timestamp (org-timestamp-change 0 'day))
21001 ((and `nil (guard (org-at-heading-p)))
21002 ;; When point is on an unsupported object type, we can miss
21003 ;; the fact that it also is at a heading. Handle it here.
21004 (call-interactively #'org-set-tags))
21005 ((guard
21006 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21008 (user-error
21009 (substitute-command-keys
21010 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21012 (defun org-mode-restart ()
21013 (interactive)
21014 (let ((indent-status (bound-and-true-p org-indent-mode)))
21015 (funcall major-mode)
21016 (hack-local-variables)
21017 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21018 (org-indent-mode -1))
21019 (org-reset-file-cache))
21020 (message "%s restarted" major-mode))
21022 (defun org-kill-note-or-show-branches ()
21023 "Abort storing current note, or call `outline-show-branches'."
21024 (interactive)
21025 (if (not org-finish-function)
21026 (progn
21027 (outline-hide-subtree)
21028 (call-interactively 'outline-show-branches))
21029 (let ((org-note-abort t))
21030 (funcall org-finish-function))))
21032 (defun org-delete-indentation (&optional arg)
21033 "Join current line to previous and fix whitespace at join.
21035 If previous line is a headline add to headline title. Otherwise
21036 the function calls `delete-indentation'.
21038 With a non-nil optional argument, join it to the following one."
21039 (interactive "*P")
21040 (if (save-excursion
21041 (beginning-of-line (if arg 1 0))
21042 (let ((case-fold-search nil))
21043 (looking-at org-complex-heading-regexp)))
21044 ;; At headline.
21045 (let ((tags-column (when (match-beginning 5)
21046 (save-excursion (goto-char (match-beginning 5))
21047 (current-column))))
21048 (string (concat " " (progn (when arg (forward-line 1))
21049 (org-trim (delete-and-extract-region
21050 (line-beginning-position)
21051 (line-end-position)))))))
21052 (unless (bobp) (delete-region (point) (1- (point))))
21053 (goto-char (or (match-end 4)
21054 (match-beginning 5)
21055 (match-end 0)))
21056 (skip-chars-backward " \t")
21057 (save-excursion (insert string))
21058 ;; Adjust alignment of tags.
21059 (cond
21060 ((not tags-column)) ;no tags
21061 (org-auto-align-tags (org-set-tags nil t))
21062 (t (org--align-tags-here tags-column)))) ;preserve tags column
21063 (delete-indentation arg)))
21065 (defun org-open-line (n)
21066 "Insert a new row in tables, call `open-line' elsewhere.
21067 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21068 As a special case, when a document starts with a table, allow to
21069 call `open-line' on the very first character."
21070 (interactive "*p")
21071 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21072 (org-table-insert-row)
21073 (open-line n)))
21075 (defun org-return (&optional indent)
21076 "Goto next table row or insert a newline.
21078 Calls `org-table-next-row' or `newline', depending on context.
21080 When optional INDENT argument is non-nil, call
21081 `newline-and-indent' instead of `newline'.
21083 When `org-return-follows-link' is non-nil and point is on
21084 a timestamp or a link, call `org-open-at-point'. However, it
21085 will not happen if point is in a table or on a \"dead\"
21086 object (e.g., within a comment). In these case, you need to use
21087 `org-open-at-point' directly."
21088 (interactive)
21089 (let ((context (if org-return-follows-link (org-element-context)
21090 (org-element-at-point))))
21091 (cond
21092 ;; In a table, call `org-table-next-row'.
21093 ((or (and (eq (org-element-type context) 'table)
21094 (>= (point) (org-element-property :contents-begin context))
21095 (< (point) (org-element-property :contents-end context)))
21096 (org-element-lineage context '(table-row table-cell) t))
21097 (org-table-justify-field-maybe)
21098 (call-interactively #'org-table-next-row))
21099 ;; On a link or a timestamp, call `org-open-at-point' if
21100 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21101 ;; locations, e.g., in a comment, as `org-open-at-point'.
21102 ((and org-return-follows-link
21103 (or (org-in-regexp org-ts-regexp-both nil t)
21104 (org-in-regexp org-tsr-regexp-both nil t)
21105 (org-in-regexp org-any-link-re nil t)))
21106 (call-interactively #'org-open-at-point))
21107 ;; Insert newline in heading, but preserve tags.
21108 ((and (not (bolp))
21109 (save-excursion (beginning-of-line)
21110 (let ((case-fold-search nil))
21111 (looking-at org-complex-heading-regexp))))
21112 ;; At headline. Split line. However, if point is on keyword,
21113 ;; priority cookie or tags, do not break any of them: add
21114 ;; a newline after the headline instead.
21115 (let ((tags-column (and (match-beginning 5)
21116 (save-excursion (goto-char (match-beginning 5))
21117 (current-column))))
21118 (string
21119 (when (and (match-end 4) (org-point-in-group (point) 4))
21120 (delete-and-extract-region (point) (match-end 4)))))
21121 ;; Adjust tag alignment.
21122 (cond
21123 ((not (and tags-column string)))
21124 (org-auto-align-tags (org-set-tags nil t))
21125 (t (org--align-tags-here tags-column))) ;preserve tags column
21126 (end-of-line)
21127 (org-show-entry)
21128 (if indent (newline-and-indent) (newline))
21129 (when string (save-excursion (insert (org-trim string))))))
21130 ;; In a list, make sure indenting keeps trailing text within.
21131 ((and indent
21132 (not (eolp))
21133 (org-element-lineage context '(item)))
21134 (let ((trailing-data
21135 (delete-and-extract-region (point) (line-end-position))))
21136 (newline-and-indent)
21137 (save-excursion (insert trailing-data))))
21138 (t (if indent (newline-and-indent) (newline))))))
21140 (defun org-return-indent ()
21141 "Goto next table row or insert a newline and indent.
21142 Calls `org-table-next-row' or `newline-and-indent', depending on
21143 context. See the individual commands for more information."
21144 (interactive)
21145 (org-return t))
21147 (defun org-ctrl-c-star ()
21148 "Compute table, or change heading status of lines.
21149 Calls `org-table-recalculate' or `org-toggle-heading',
21150 depending on context."
21151 (interactive)
21152 (cond
21153 ((org-at-table-p)
21154 (call-interactively 'org-table-recalculate))
21156 ;; Convert all lines in region to list items
21157 (call-interactively 'org-toggle-heading))))
21159 (defun org-ctrl-c-minus ()
21160 "Insert separator line in table or modify bullet status of line.
21161 Also turns a plain line or a region of lines into list items.
21162 Calls `org-table-insert-hline', `org-toggle-item', or
21163 `org-cycle-list-bullet', depending on context."
21164 (interactive)
21165 (cond
21166 ((org-at-table-p)
21167 (call-interactively 'org-table-insert-hline))
21168 ((org-region-active-p)
21169 (call-interactively 'org-toggle-item))
21170 ((org-in-item-p)
21171 (call-interactively 'org-cycle-list-bullet))
21173 (call-interactively 'org-toggle-item))))
21175 (defun org-toggle-heading (&optional nstars)
21176 "Convert headings to normal text, or items or text to headings.
21177 If there is no active region, only convert the current line.
21179 With a `\\[universal-argument]' prefix, convert the whole list at
21180 point into heading.
21182 In a region:
21184 - If the first non blank line is a headline, remove the stars
21185 from all headlines in the region.
21187 - If it is a normal line, turn each and every normal line (i.e.,
21188 not an heading or an item) in the region into headings. If you
21189 want to convert only the first line of this region, use one
21190 universal prefix argument.
21192 - If it is a plain list item, turn all plain list items into headings.
21194 When converting a line into a heading, the number of stars is chosen
21195 such that the lines become children of the current entry. However,
21196 when a numeric prefix argument is given, its value determines the
21197 number of stars to add."
21198 (interactive "P")
21199 (let ((skip-blanks
21200 (function
21201 ;; Return beginning of first non-blank line, starting from
21202 ;; line at POS.
21203 (lambda (pos)
21204 (save-excursion
21205 (goto-char pos)
21206 (while (org-at-comment-p) (forward-line))
21207 (skip-chars-forward " \r\t\n")
21208 (point-at-bol)))))
21209 beg end toggled)
21210 ;; Determine boundaries of changes. If a universal prefix has
21211 ;; been given, put the list in a region. If region ends at a bol,
21212 ;; do not consider the last line to be in the region.
21214 (when (and current-prefix-arg (org-at-item-p))
21215 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21216 (org-mark-element))
21218 (if (org-region-active-p)
21219 (setq beg (funcall skip-blanks (region-beginning))
21220 end (copy-marker (save-excursion
21221 (goto-char (region-end))
21222 (if (bolp) (point) (point-at-eol)))))
21223 (setq beg (funcall skip-blanks (point-at-bol))
21224 end (copy-marker (point-at-eol))))
21225 ;; Ensure inline tasks don't count as headings.
21226 (org-with-limited-levels
21227 (save-excursion
21228 (goto-char beg)
21229 (cond
21230 ;; Case 1. Started at an heading: de-star headings.
21231 ((org-at-heading-p)
21232 (while (< (point) end)
21233 (when (org-at-heading-p t)
21234 (looking-at org-outline-regexp) (replace-match "")
21235 (setq toggled t))
21236 (forward-line)))
21237 ;; Case 2. Started at an item: change items into headlines.
21238 ;; One star will be added by `org-list-to-subtree'.
21239 ((org-at-item-p)
21240 (while (< (point) end)
21241 (when (org-at-item-p)
21242 ;; Pay attention to cases when region ends before list.
21243 (let* ((struct (org-list-struct))
21244 (list-end
21245 (min (org-list-get-bottom-point struct) (1+ end))))
21246 (save-restriction
21247 (narrow-to-region (point) list-end)
21248 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21249 (setq toggled t))
21250 (forward-line)))
21251 ;; Case 3. Started at normal text: make every line an heading,
21252 ;; skipping headlines and items.
21253 (t (let* ((stars
21254 (make-string
21255 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21256 (add-stars
21257 (cond (nstars "") ; stars from prefix only
21258 ((equal stars "") "*") ; before first heading
21259 (org-odd-levels-only "**") ; inside heading, odd
21260 (t "*"))) ; inside heading, oddeven
21261 (rpl (concat stars add-stars " "))
21262 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21263 (while (< (point) (if (equal nstars '(4)) lend end))
21264 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21265 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21266 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21267 (forward-line)))))))
21268 (unless toggled (message "Cannot toggle heading from here"))))
21270 (defun org-meta-return (&optional arg)
21271 "Insert a new heading or wrap a region in a table.
21272 Calls `org-insert-heading', `org-insert-item' or
21273 `org-table-wrap-region', depending on context. When called with
21274 an argument, unconditionally call `org-insert-heading'."
21275 (interactive "P")
21276 (org-check-before-invisible-edit 'insert)
21277 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21278 (call-interactively (cond (arg #'org-insert-heading)
21279 ((org-at-table-p) #'org-table-wrap-region)
21280 ((org-in-item-p) #'org-insert-item)
21281 (t #'org-insert-heading)))))
21283 ;;; Menu entries
21285 (defsubst org-in-subtree-not-table-p ()
21286 "Are we in a subtree and not in a table?"
21287 (and (not (org-before-first-heading-p))
21288 (not (org-at-table-p))))
21290 ;; Define the Org mode menus
21291 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21292 '("Tbl"
21293 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21294 ["Next Field" org-cycle (org-at-table-p)]
21295 ["Previous Field" org-shifttab (org-at-table-p)]
21296 ["Next Row" org-return (org-at-table-p)]
21297 "--"
21298 ["Blank Field" org-table-blank-field (org-at-table-p)]
21299 ["Edit Field" org-table-edit-field (org-at-table-p)]
21300 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21301 "--"
21302 ("Column"
21303 ["Move Column Left" org-metaleft (org-at-table-p)]
21304 ["Move Column Right" org-metaright (org-at-table-p)]
21305 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21306 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21307 ("Row"
21308 ["Move Row Up" org-metaup (org-at-table-p)]
21309 ["Move Row Down" org-metadown (org-at-table-p)]
21310 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21311 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21312 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21313 "--"
21314 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21315 ("Rectangle"
21316 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21317 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21318 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21319 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21320 "--"
21321 ("Calculate"
21322 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21323 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21324 ["Edit Formulas" org-edit-special (org-at-table-p)]
21325 "--"
21326 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21327 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21328 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21329 "--"
21330 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21331 "--"
21332 ["Sum Column/Rectangle" org-table-sum
21333 (or (org-at-table-p) (org-region-active-p))]
21334 ["Which Column?" org-table-current-column (org-at-table-p)])
21335 ["Debug Formulas"
21336 org-table-toggle-formula-debugger
21337 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21338 ["Show Col/Row Numbers"
21339 org-table-toggle-coordinate-overlays
21340 :style toggle
21341 :selected (bound-and-true-p org-table-overlay-coordinates)]
21342 "--"
21343 ["Create" org-table-create (and (not (org-at-table-p))
21344 org-enable-table-editor)]
21345 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21346 ["Import from File" org-table-import (not (org-at-table-p))]
21347 ["Export to File" org-table-export (org-at-table-p)]
21348 "--"
21349 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21350 "--"
21351 ("Plot"
21352 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21353 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21355 (easy-menu-define org-org-menu org-mode-map "Org menu"
21356 '("Org"
21357 ("Show/Hide"
21358 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21359 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21360 ["Sparse Tree..." org-sparse-tree t]
21361 ["Reveal Context" org-reveal t]
21362 ["Show All" outline-show-all t]
21363 "--"
21364 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21365 "--"
21366 ["New Heading" org-insert-heading t]
21367 ("Navigate Headings"
21368 ["Up" outline-up-heading t]
21369 ["Next" outline-next-visible-heading t]
21370 ["Previous" outline-previous-visible-heading t]
21371 ["Next Same Level" outline-forward-same-level t]
21372 ["Previous Same Level" outline-backward-same-level t]
21373 "--"
21374 ["Jump" org-goto t])
21375 ("Edit Structure"
21376 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21377 "--"
21378 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21379 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21380 "--"
21381 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21382 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21383 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21384 "--"
21385 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21386 "--"
21387 ["Copy visible text" org-copy-visible t]
21388 "--"
21389 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21390 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21391 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21392 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21393 "--"
21394 ["Sort Region/Children" org-sort t]
21395 "--"
21396 ["Convert to odd levels" org-convert-to-odd-levels t]
21397 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21398 ("Editing"
21399 ["Emphasis..." org-emphasize t]
21400 ["Edit Source Example" org-edit-special t]
21401 "--"
21402 ["Footnote new/jump" org-footnote-action t]
21403 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21404 ("Archive"
21405 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21406 "--"
21407 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21408 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21409 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21411 "--"
21412 ("Hyperlinks"
21413 ["Store Link (Global)" org-store-link t]
21414 ["Find existing link to here" org-occur-link-in-agenda-files t]
21415 ["Insert Link" org-insert-link t]
21416 ["Follow Link" org-open-at-point t]
21417 "--"
21418 ["Next link" org-next-link t]
21419 ["Previous link" org-previous-link t]
21420 "--"
21421 ["Descriptive Links"
21422 org-toggle-link-display
21423 :style radio
21424 :selected org-descriptive-links
21426 ["Literal Links"
21427 org-toggle-link-display
21428 :style radio
21429 :selected (not org-descriptive-links)])
21430 "--"
21431 ("TODO Lists"
21432 ["TODO/DONE/-" org-todo t]
21433 ("Select keyword"
21434 ["Next keyword" org-shiftright (org-at-heading-p)]
21435 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21436 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21437 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21438 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21439 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21440 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21441 "--"
21442 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21443 :selected org-enforce-todo-dependencies :style toggle :active t]
21444 "Settings for tree at point"
21445 ["Do Children sequentially" org-toggle-ordered-property :style radio
21446 :selected (org-entry-get nil "ORDERED")
21447 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21448 ["Do Children parallel" org-toggle-ordered-property :style radio
21449 :selected (not (org-entry-get nil "ORDERED"))
21450 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21451 "--"
21452 ["Set Priority" org-priority t]
21453 ["Priority Up" org-shiftup t]
21454 ["Priority Down" org-shiftdown t]
21455 "--"
21456 ["Get news from all feeds" org-feed-update-all t]
21457 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21458 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21459 ("TAGS and Properties"
21460 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21461 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21462 "--"
21463 ["Set property" org-set-property (not (org-before-first-heading-p))]
21464 ["Column view of properties" org-columns t]
21465 ["Insert Column View DBlock" org-columns-insert-dblock t])
21466 ("Dates and Scheduling"
21467 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21468 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21469 ("Change Date"
21470 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21471 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21472 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21473 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21474 ["Compute Time Range" org-evaluate-time-range t]
21475 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21476 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21477 "--"
21478 ["Custom time format" org-toggle-time-stamp-overlays
21479 :style radio :selected org-display-custom-times]
21480 "--"
21481 ["Goto Calendar" org-goto-calendar t]
21482 ["Date from Calendar" org-date-from-calendar t]
21483 "--"
21484 ["Start/Restart Timer" org-timer-start t]
21485 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21486 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21487 ["Insert Timer String" org-timer t]
21488 ["Insert Timer Item" org-timer-item t])
21489 ("Logging work"
21490 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21491 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21492 ["Clock out" org-clock-out t]
21493 ["Clock cancel" org-clock-cancel t]
21494 "--"
21495 ["Mark as default task" org-clock-mark-default-task t]
21496 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21497 ["Goto running clock" org-clock-goto t]
21498 "--"
21499 ["Display times" org-clock-display t]
21500 ["Create clock table" org-clock-report t]
21501 "--"
21502 ["Record DONE time"
21503 (progn (setq org-log-done (not org-log-done))
21504 (message "Switching to %s will %s record a timestamp"
21505 (car org-done-keywords)
21506 (if org-log-done "automatically" "not")))
21507 :style toggle :selected org-log-done])
21508 "--"
21509 ["Agenda Command..." org-agenda t]
21510 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21511 ("File List for Agenda")
21512 ("Special views current file"
21513 ["TODO Tree" org-show-todo-tree t]
21514 ["Check Deadlines" org-check-deadlines t]
21515 ["Tags/Property tree" org-match-sparse-tree t])
21516 "--"
21517 ["Export/Publish..." org-export-dispatch t]
21518 ("LaTeX"
21519 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21520 :selected org-cdlatex-mode]
21521 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21522 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21523 ["Modify math symbol" org-cdlatex-math-modify
21524 (org-inside-LaTeX-fragment-p)]
21525 ["Insert citation" org-reftex-citation t])
21526 "--"
21527 ("MobileOrg"
21528 ["Push Files and Views" org-mobile-push t]
21529 ["Get Captured and Flagged" org-mobile-pull t]
21530 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21531 "--"
21532 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21533 "--"
21534 ("Documentation"
21535 ["Show Version" org-version t]
21536 ["Info Documentation" org-info t])
21537 ("Customize"
21538 ["Browse Org Group" org-customize t]
21539 "--"
21540 ["Expand This Menu" org-create-customize-menu
21541 (fboundp 'customize-menu-create)])
21542 ["Send bug report" org-submit-bug-report t]
21543 "--"
21544 ("Refresh/Reload"
21545 ["Refresh setup current buffer" org-mode-restart t]
21546 ["Reload Org (after update)" org-reload t]
21547 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21550 (defun org-info (&optional node)
21551 "Read documentation for Org in the info system.
21552 With optional NODE, go directly to that node."
21553 (interactive)
21554 (info (format "(org)%s" (or node ""))))
21556 ;;;###autoload
21557 (defun org-submit-bug-report ()
21558 "Submit a bug report on Org via mail.
21560 Don't hesitate to report any problems or inaccurate documentation.
21562 If you don't have setup sending mail from (X)Emacs, please copy the
21563 output buffer into your mail program, as it gives us important
21564 information about your Org version and configuration."
21565 (interactive)
21566 (require 'reporter)
21567 (defvar reporter-prompt-for-summary-p)
21568 (org-load-modules-maybe)
21569 (org-require-autoloaded-modules)
21570 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21571 (reporter-submit-bug-report
21572 "emacs-orgmode@gnu.org"
21573 (org-version nil 'full)
21574 (let (list)
21575 (save-window-excursion
21576 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21577 (delete-other-windows)
21578 (erase-buffer)
21579 (insert "You are about to submit a bug report to the Org mailing list.
21581 We would like to add your full Org and Outline configuration to the
21582 bug report. This greatly simplifies the work of the maintainer and
21583 other experts on the mailing list.
21585 HOWEVER, some variables you have customized may contain private
21586 information. The names of customers, colleagues, or friends, might
21587 appear in the form of file names, tags, todo states, or search strings.
21588 If you answer yes to the prompt, you might want to check and remove
21589 such private information before sending the email.")
21590 (add-text-properties (point-min) (point-max) '(face org-warning))
21591 (when (yes-or-no-p "Include your Org configuration ")
21592 (mapatoms
21593 (lambda (v)
21594 (and (boundp v)
21595 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21596 (or (and (symbol-value v)
21597 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21598 (and
21599 (get v 'custom-type) (get v 'standard-value)
21600 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21601 (push v list)))))
21602 (kill-buffer (get-buffer "*Warn about privacy*"))
21603 list))
21604 nil nil
21605 "Remember to cover the basics, that is, what you expected to happen and
21606 what in fact did happen. You don't know how to make a good report? See
21608 http://orgmode.org/manual/Feedback.html#Feedback
21610 Your bug report will be posted to the Org mailing list.
21611 ------------------------------------------------------------------------")
21612 (save-excursion
21613 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21614 (replace-match "\\1Bug: \\3 [\\2]")))))
21617 (defun org-install-agenda-files-menu ()
21618 (let ((bl (buffer-list)))
21619 (save-excursion
21620 (while bl
21621 (set-buffer (pop bl))
21622 (when (derived-mode-p 'org-mode) (setq bl nil)))
21623 (when (derived-mode-p 'org-mode)
21624 (easy-menu-change
21625 '("Org") "File List for Agenda"
21626 (append
21627 (list
21628 ["Edit File List" (org-edit-agenda-file-list) t]
21629 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21630 ["Remove Current File from List" org-remove-file t]
21631 ["Cycle through agenda files" org-cycle-agenda-files t]
21632 ["Occur in all agenda files" org-occur-in-agenda-files t]
21633 "--")
21634 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21636 ;;;; Documentation
21638 (defun org-require-autoloaded-modules ()
21639 (interactive)
21640 (mapc #'require
21641 '(org-agenda org-archive org-attach org-clock org-colview org-id
21642 org-table org-timer)))
21644 ;;;###autoload
21645 (defun org-reload (&optional uncompiled)
21646 "Reload all org lisp files.
21647 With prefix arg UNCOMPILED, load the uncompiled versions."
21648 (interactive "P")
21649 (require 'loadhist)
21650 (let* ((org-dir (org-find-library-dir "org"))
21651 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21652 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21653 (remove-re (format "\\`%s\\'"
21654 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21655 (feats (delete-dups
21656 (mapcar 'file-name-sans-extension
21657 (mapcar 'file-name-nondirectory
21658 (delq nil
21659 (mapcar 'feature-file
21660 features))))))
21661 (lfeat (append
21662 (sort
21663 (setq feats
21664 (delq nil (mapcar
21665 (lambda (f)
21666 (if (and (string-match feature-re f)
21667 (not (string-match remove-re f)))
21668 f nil))
21669 feats)))
21670 'string-lessp)
21671 (list "org-version" "org")))
21672 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21673 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21674 load-uncore load-misses)
21675 (setq load-misses
21676 (delq 't
21677 (mapcar (lambda (f)
21678 (or (org-load-noerror-mustsuffix (concat org-dir f))
21679 (and (string= org-dir contrib-dir)
21680 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21681 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21682 (add-to-list 'load-uncore f 'append)
21685 lfeat)))
21686 (when load-uncore
21687 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21688 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21689 (if load-misses
21690 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21691 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21692 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21694 ;;;###autoload
21695 (defun org-customize ()
21696 "Call the customize function with org as argument."
21697 (interactive)
21698 (org-load-modules-maybe)
21699 (org-require-autoloaded-modules)
21700 (customize-browse 'org))
21702 (defun org-create-customize-menu ()
21703 "Create a full customization menu for Org mode, insert it into the menu."
21704 (interactive)
21705 (org-load-modules-maybe)
21706 (org-require-autoloaded-modules)
21707 (if (fboundp 'customize-menu-create)
21708 (progn
21709 (easy-menu-change
21710 '("Org") "Customize"
21711 `(["Browse Org group" org-customize t]
21712 "--"
21713 ,(customize-menu-create 'org)
21714 ["Set" Custom-set t]
21715 ["Save" Custom-save t]
21716 ["Reset to Current" Custom-reset-current t]
21717 ["Reset to Saved" Custom-reset-saved t]
21718 ["Reset to Standard Settings" Custom-reset-standard t]))
21719 (message "\"Org\"-menu now contains full customization menu"))
21720 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21722 ;;;; Miscellaneous stuff
21724 ;;; Generally useful functions
21726 (defun org-get-at-eol (property n)
21727 "Get text property PROPERTY at the end of line less N characters."
21728 (get-text-property (- (point-at-eol) n) property))
21730 (defun org-find-text-property-in-string (prop s)
21731 "Return the first non-nil value of property PROP in string S."
21732 (or (get-text-property 0 prop s)
21733 (get-text-property (or (next-single-property-change 0 prop s) 0)
21734 prop s)))
21736 (defun org-display-warning (message)
21737 "Display the given MESSAGE as a warning."
21738 (display-warning 'org message :warning))
21740 (defun org-eval (form)
21741 "Eval FORM and return result."
21742 (condition-case error
21743 (eval form)
21744 (error (format "%%![Error: %s]" error))))
21746 (defun org-in-clocktable-p ()
21747 "Check if the cursor is in a clocktable."
21748 (let ((pos (point)) start)
21749 (save-excursion
21750 (end-of-line 1)
21751 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21752 (setq start (match-beginning 0))
21753 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21754 (>= (match-end 0) pos)
21755 start))))
21757 (defun org-in-verbatim-emphasis ()
21758 (save-match-data
21759 (and (org-in-regexp org-verbatim-re 2)
21760 (>= (point) (match-beginning 3))
21761 (<= (point) (match-end 4)))))
21763 (defun org-overlay-display (ovl text &optional face evap)
21764 "Make overlay OVL display TEXT with face FACE."
21765 (overlay-put ovl 'display text)
21766 (if face (overlay-put ovl 'face face))
21767 (if evap (overlay-put ovl 'evaporate t)))
21769 (defun org-overlay-before-string (ovl text &optional face evap)
21770 "Make overlay OVL display TEXT with face FACE."
21771 (if face (org-add-props text nil 'face face))
21772 (overlay-put ovl 'before-string text)
21773 (if evap (overlay-put ovl 'evaporate t)))
21775 (defun org-find-overlays (prop &optional pos delete)
21776 "Find all overlays specifying PROP at POS or point.
21777 If DELETE is non-nil, delete all those overlays."
21778 (let (found)
21779 (dolist (ov (overlays-at (or pos (point))) found)
21780 (cond ((not (overlay-get ov prop)))
21781 (delete (delete-overlay ov))
21782 (t (push ov found))))))
21784 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21785 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21786 (if (and marker (marker-buffer marker)
21787 (buffer-live-p (marker-buffer marker)))
21788 (progn
21789 (pop-to-buffer-same-window (marker-buffer marker))
21790 (when (or (> marker (point-max)) (< marker (point-min)))
21791 (widen))
21792 (goto-char marker)
21793 (org-show-context 'org-goto))
21794 (if bookmark
21795 (bookmark-jump bookmark)
21796 (error "Cannot find location"))))
21798 (defun org-quote-csv-field (s)
21799 "Quote field for inclusion in CSV material."
21800 (if (string-match "[\",]" s)
21801 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21804 (defun org-force-self-insert (N)
21805 "Needed to enforce self-insert under remapping."
21806 (interactive "p")
21807 (self-insert-command N))
21809 (defun org-string-width (s)
21810 "Compute width of string, ignoring invisible characters.
21811 This ignores character with invisibility property `org-link', and also
21812 characters with property `org-cwidth', because these will become invisible
21813 upon the next fontification round."
21814 (let (b l)
21815 (when (or (eq t buffer-invisibility-spec)
21816 (assq 'org-link buffer-invisibility-spec))
21817 (while (setq b (text-property-any 0 (length s)
21818 'invisible 'org-link s))
21819 (setq s (concat (substring s 0 b)
21820 (substring s (or (next-single-property-change
21821 b 'invisible s)
21822 (length s)))))))
21823 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21824 (setq s (concat (substring s 0 b)
21825 (substring s (or (next-single-property-change
21826 b 'org-cwidth s)
21827 (length s))))))
21828 (setq l (string-width s) b -1)
21829 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21830 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21833 (defun org-shorten-string (s maxlength)
21834 "Shorten string S so that it is no longer than MAXLENGTH characters.
21835 If the string is shorter or has length MAXLENGTH, just return the
21836 original string. If it is longer, the functions finds a space in the
21837 string, breaks this string off at that locations and adds three dots
21838 as ellipsis. Including the ellipsis, the string will not be longer
21839 than MAXLENGTH. If finding a good breaking point in the string does
21840 not work, the string is just chopped off in the middle of a word
21841 if necessary."
21842 (if (<= (length s) maxlength)
21844 (let* ((n (max (- maxlength 4) 1))
21845 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21846 (if (string-match re s)
21847 (concat (match-string 1 s) "...")
21848 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21850 (defun org-get-indentation (&optional line)
21851 "Get the indentation of the current line, interpreting tabs.
21852 When LINE is given, assume it represents a line and compute its indentation."
21853 (if line
21854 (when (string-match "^ *" (org-remove-tabs line))
21855 (match-end 0))
21856 (save-excursion
21857 (beginning-of-line 1)
21858 (skip-chars-forward " \t")
21859 (current-column))))
21861 (defun org-get-string-indentation (s)
21862 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21863 (let ((n -1) (i 0) (w tab-width) c)
21864 (catch 'exit
21865 (while (< (setq n (1+ n)) (length s))
21866 (setq c (aref s n))
21867 (cond ((= c ?\ ) (setq i (1+ i)))
21868 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21869 (t (throw 'exit t)))))
21872 (defun org-remove-tabs (s &optional width)
21873 "Replace tabulators in S with spaces.
21874 Assumes that s is a single line, starting in column 0."
21875 (setq width (or width tab-width))
21876 (while (string-match "\t" s)
21877 (setq s (replace-match
21878 (make-string
21879 (- (* width (/ (+ (match-beginning 0) width) width))
21880 (match-beginning 0)) ?\ )
21881 t t s)))
21884 (defun org-fix-indentation (line ind)
21885 "Fix indentation in LINE.
21886 IND is a cons cell with target and minimum indentation.
21887 If the current indentation in LINE is smaller than the minimum,
21888 leave it alone. If it is larger than ind, set it to the target."
21889 (let* ((l (org-remove-tabs line))
21890 (i (org-get-indentation l))
21891 (i1 (car ind)) (i2 (cdr ind)))
21892 (when (>= i i2) (setq l (substring line i2)))
21893 (if (> i1 0)
21894 (concat (make-string i1 ?\ ) l)
21895 l)))
21897 (defun org-remove-indentation (code &optional n)
21898 "Remove maximum common indentation in string CODE and return it.
21899 N may optionally be the number of columns to remove. Return CODE
21900 as-is if removal failed."
21901 (with-temp-buffer
21902 (insert code)
21903 (if (org-do-remove-indentation n) (buffer-string) code)))
21905 (defun org-do-remove-indentation (&optional n)
21906 "Remove the maximum common indentation from the buffer.
21907 When optional argument N is a positive integer, remove exactly
21908 that much characters from indentation, if possible. Return nil
21909 if it fails."
21910 (catch :exit
21911 (goto-char (point-min))
21912 ;; Find maximum common indentation, if not specified.
21913 (let ((n (or n
21914 (let ((min-ind (point-max)))
21915 (save-excursion
21916 (while (re-search-forward "^[ \t]*\\S-" nil t)
21917 (let ((ind (1- (current-column))))
21918 (if (zerop ind) (throw :exit nil)
21919 (setq min-ind (min min-ind ind))))))
21920 min-ind))))
21921 (if (zerop n) (throw :exit nil)
21922 ;; Remove exactly N indentation, but give up if not possible.
21923 (while (not (eobp))
21924 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21925 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21926 ((< ind n) (throw :exit nil))
21927 (t (indent-line-to (- ind n))))
21928 (forward-line)))
21929 ;; Signal success.
21930 t))))
21932 (defun org-fill-template (template alist)
21933 "Find each %key of ALIST in TEMPLATE and replace it."
21934 (let ((case-fold-search nil))
21935 (dolist (entry (sort (copy-sequence alist)
21936 (lambda (a b) (< (length (car a)) (length (car b))))))
21937 (setq template
21938 (replace-regexp-in-string
21939 (concat "%" (regexp-quote (car entry)))
21940 (or (cdr entry) "") template t t)))
21941 template))
21943 (defun org-base-buffer (buffer)
21944 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21945 (if (not buffer)
21946 buffer
21947 (or (buffer-base-buffer buffer)
21948 buffer)))
21950 (defun org-wrap (string &optional width lines)
21951 "Wrap string to either a number of lines, or a width in characters.
21952 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21953 that costs. If there is a word longer than WIDTH, the text is actually
21954 wrapped to the length of that word.
21955 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21956 many lines, whatever width that takes.
21957 The return value is a list of lines, without newlines at the end."
21958 (let* ((words (org-split-string string "[ \t\n]+"))
21959 (maxword (apply 'max (mapcar 'org-string-width words)))
21960 w ll)
21961 (cond (width
21962 (org-do-wrap words (max maxword width)))
21963 (lines
21964 (setq w maxword)
21965 (setq ll (org-do-wrap words maxword))
21966 (if (<= (length ll) lines)
21968 (setq ll words)
21969 (while (> (length ll) lines)
21970 (setq w (1+ w))
21971 (setq ll (org-do-wrap words w)))
21972 ll))
21973 (t (error "Cannot wrap this")))))
21975 (defun org-do-wrap (words width)
21976 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21977 (let (lines line)
21978 (while words
21979 (setq line (pop words))
21980 (while (and words (< (+ (length line) (length (car words))) width))
21981 (setq line (concat line " " (pop words))))
21982 (setq lines (push line lines)))
21983 (nreverse lines)))
21985 (defun org-split-string (string &optional separators)
21986 "Splits STRING into substrings at SEPARATORS.
21987 SEPARATORS is a regular expression.
21988 No empty strings are returned if there are matches at the beginning
21989 and end of string."
21990 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
21991 (let ((start 0) notfirst list)
21992 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
21993 (if (and notfirst
21994 (= start (match-beginning 0))
21995 (< start (length string)))
21996 (1+ start) start))
21997 (< (match-beginning 0) (length string)))
21998 (setq notfirst t)
21999 (or (eq (match-beginning 0) 0)
22000 (and (eq (match-beginning 0) (match-end 0))
22001 (eq (match-beginning 0) start))
22002 (push (substring string start (match-beginning 0)) list))
22003 (setq start (match-end 0)))
22004 (or (eq start (length string))
22005 (push (substring string start) list))
22006 (nreverse list)))
22008 (defun org-quote-vert (s)
22009 "Replace \"|\" with \"\\vert\"."
22010 (while (string-match "|" s)
22011 (setq s (replace-match "\\vert" t t s)))
22014 (defun org-uuidgen-p (s)
22015 "Is S an ID created by UUIDGEN?"
22016 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22018 (defun org-in-src-block-p (&optional inside)
22019 "Whether point is in a code source block.
22020 When INSIDE is non-nil, don't consider we are within a src block
22021 when point is at #+BEGIN_SRC or #+END_SRC."
22022 (let ((case-fold-search t))
22023 (or (and (eq (get-char-property (point) 'src-block) t))
22024 (and (not inside)
22025 (save-match-data
22026 (save-excursion
22027 (beginning-of-line)
22028 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22030 (defun org-context ()
22031 "Return a list of contexts of the current cursor position.
22032 If several contexts apply, all are returned.
22033 Each context entry is a list with a symbol naming the context, and
22034 two positions indicating start and end of the context. Possible
22035 contexts are:
22037 :headline anywhere in a headline
22038 :headline-stars on the leading stars in a headline
22039 :todo-keyword on a TODO keyword (including DONE) in a headline
22040 :tags on the TAGS in a headline
22041 :priority on the priority cookie in a headline
22042 :item on the first line of a plain list item
22043 :item-bullet on the bullet/number of a plain list item
22044 :checkbox on the checkbox in a plain list item
22045 :table in an Org table
22046 :table-special on a special filed in a table
22047 :table-table in a table.el table
22048 :clocktable in a clocktable
22049 :src-block in a source block
22050 :link on a hyperlink
22051 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22052 :target on a <<target>>
22053 :radio-target on a <<<radio-target>>>
22054 :latex-fragment on a LaTeX fragment
22055 :latex-preview on a LaTeX fragment with overlaid preview image
22057 This function expects the position to be visible because it uses font-lock
22058 faces as a help to recognize the following contexts: :table-special, :link,
22059 and :keyword."
22060 (let* ((f (get-text-property (point) 'face))
22061 (faces (if (listp f) f (list f)))
22062 (case-fold-search t)
22063 (p (point)) clist o)
22064 ;; First the large context
22065 (cond
22066 ((org-at-heading-p t)
22067 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22068 (when (progn
22069 (beginning-of-line 1)
22070 (looking-at org-todo-line-tags-regexp))
22071 (push (org-point-in-group p 1 :headline-stars) clist)
22072 (push (org-point-in-group p 2 :todo-keyword) clist)
22073 (push (org-point-in-group p 4 :tags) clist))
22074 (goto-char p)
22075 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22076 (when (looking-at "\\[#[A-Z0-9]\\]")
22077 (push (org-point-in-group p 0 :priority) clist)))
22079 ((org-at-item-p)
22080 (push (org-point-in-group p 2 :item-bullet) clist)
22081 (push (list :item (point-at-bol)
22082 (save-excursion (org-end-of-item) (point)))
22083 clist)
22084 (and (org-at-item-checkbox-p)
22085 (push (org-point-in-group p 0 :checkbox) clist)))
22087 ((org-at-table-p)
22088 (push (list :table (org-table-begin) (org-table-end)) clist)
22089 (when (memq 'org-formula faces)
22090 (push (list :table-special
22091 (previous-single-property-change p 'face)
22092 (next-single-property-change p 'face)) clist)))
22093 ((org-at-table-p 'any)
22094 (push (list :table-table) clist)))
22095 (goto-char p)
22097 (let ((case-fold-search t))
22098 ;; New the "medium" contexts: clocktables, source blocks
22099 (cond ((org-in-clocktable-p)
22100 (push (list :clocktable
22101 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22102 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22103 (match-beginning 1))
22104 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22105 (match-end 0))) clist))
22106 ((org-in-src-block-p)
22107 (push (list :src-block
22108 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22109 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22110 (match-beginning 1))
22111 (and (search-forward "#+END_SRC" nil t)
22112 (match-beginning 0))) clist))))
22113 (goto-char p)
22115 ;; Now the small context
22116 (cond
22117 ((org-at-timestamp-p)
22118 (push (org-point-in-group p 0 :timestamp) clist))
22119 ((memq 'org-link faces)
22120 (push (list :link
22121 (previous-single-property-change p 'face)
22122 (next-single-property-change p 'face)) clist))
22123 ((memq 'org-special-keyword faces)
22124 (push (list :keyword
22125 (previous-single-property-change p 'face)
22126 (next-single-property-change p 'face)) clist))
22127 ((org-at-target-p)
22128 (push (org-point-in-group p 0 :target) clist)
22129 (goto-char (1- (match-beginning 0)))
22130 (when (looking-at org-radio-target-regexp)
22131 (push (org-point-in-group p 0 :radio-target) clist))
22132 (goto-char p))
22133 ((setq o (cl-some
22134 (lambda (o)
22135 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22137 (overlays-at (point))))
22138 (push (list :latex-fragment
22139 (overlay-start o) (overlay-end o)) clist)
22140 (push (list :latex-preview
22141 (overlay-start o) (overlay-end o)) clist))
22142 ((org-inside-LaTeX-fragment-p)
22143 ;; FIXME: positions wrong.
22144 (push (list :latex-fragment (point) (point)) clist)))
22146 (setq clist (nreverse (delq nil clist)))
22147 clist))
22149 (defun org-in-regexp (regexp &optional nlines visually)
22150 "Check if point is inside a match of REGEXP.
22152 Normally only the current line is checked, but you can include
22153 NLINES extra lines around point into the search. If VISUALLY is
22154 set, require that the cursor is not after the match but really
22155 on, so that the block visually is on the match.
22157 Return nil or a cons cell (BEG . END) where BEG and END are,
22158 respectively, the positions at the beginning and the end of the
22159 match."
22160 (catch :exit
22161 (let ((pos (point))
22162 (eol (line-end-position (if nlines (1+ nlines) 1))))
22163 (save-excursion
22164 (beginning-of-line (- 1 (or nlines 0)))
22165 (while (and (re-search-forward regexp eol t)
22166 (<= (match-beginning 0) pos))
22167 (let ((end (match-end 0)))
22168 (when (or (> end pos) (and (= end pos) (not visually)))
22169 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22171 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22172 "Non-nil when point is between matches of START-RE and END-RE.
22174 Also return a non-nil value when point is on one of the matches.
22176 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22177 buffer positions. Default values are the positions of headlines
22178 surrounding the point.
22180 The functions returns a cons cell whose car (resp. cdr) is the
22181 position before START-RE (resp. after END-RE)."
22182 (save-match-data
22183 (let ((pos (point))
22184 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22185 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22186 beg end)
22187 (save-excursion
22188 ;; Point is on a block when on START-RE or if START-RE can be
22189 ;; found before it...
22190 (and (or (org-in-regexp start-re)
22191 (re-search-backward start-re limit-up t))
22192 (setq beg (match-beginning 0))
22193 ;; ... and END-RE after it...
22194 (goto-char (match-end 0))
22195 (re-search-forward end-re limit-down t)
22196 (> (setq end (match-end 0)) pos)
22197 ;; ... without another START-RE in-between.
22198 (goto-char (match-beginning 0))
22199 (not (re-search-backward start-re (1+ beg) t))
22200 ;; Return value.
22201 (cons beg end))))))
22203 (defun org-in-block-p (names)
22204 "Non-nil when point belongs to a block whose name belongs to NAMES.
22206 NAMES is a list of strings containing names of blocks.
22208 Return first block name matched, or nil. Beware that in case of
22209 nested blocks, the returned name may not belong to the closest
22210 block from point."
22211 (save-match-data
22212 (catch 'exit
22213 (let ((case-fold-search t)
22214 (lim-up (save-excursion (outline-previous-heading)))
22215 (lim-down (save-excursion (outline-next-heading))))
22216 (dolist (name names)
22217 (let ((n (regexp-quote name)))
22218 (when (org-between-regexps-p
22219 (concat "^[ \t]*#\\+begin_" n)
22220 (concat "^[ \t]*#\\+end_" n)
22221 lim-up lim-down)
22222 (throw 'exit n)))))
22223 nil)))
22225 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22226 "Call `multi-occur' with buffers for all agenda files."
22227 (interactive "sOrg-files matching: ")
22228 (let* ((files (org-agenda-files))
22229 (tnames (mapcar #'file-truename files))
22230 (extra org-agenda-text-search-extra-files))
22231 (when (eq (car extra) 'agenda-archives)
22232 (setq extra (cdr extra))
22233 (setq files (org-add-archive-files files)))
22234 (dolist (f extra)
22235 (unless (member (file-truename f) tnames)
22236 (unless (member f files) (setq files (append files (list f))))
22237 (setq tnames (append tnames (list (file-truename f))))))
22238 (multi-occur
22239 (mapcar (lambda (x)
22240 (with-current-buffer
22241 ;; FIXME: Why not just (find-file-noselect x)?
22242 ;; Is it to avoid the "revert buffer" prompt?
22243 (or (get-file-buffer x) (find-file-noselect x))
22244 (widen)
22245 (current-buffer)))
22246 files)
22247 regexp)))
22249 (add-hook 'occur-mode-find-occurrence-hook
22250 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22252 (defun org-occur-link-in-agenda-files ()
22253 "Create a link and search for it in the agendas.
22254 The link is not stored in `org-stored-links', it is just created
22255 for the search purpose."
22256 (interactive)
22257 (let ((link (condition-case nil
22258 (org-store-link nil)
22259 (error "Unable to create a link to here"))))
22260 (org-occur-in-agenda-files (regexp-quote link))))
22262 (defun org-reverse-string (string)
22263 "Return the reverse of STRING."
22264 (apply 'string (reverse (string-to-list string))))
22266 ;; defsubst org-uniquify must be defined before first use
22268 (defun org-uniquify-alist (alist)
22269 "Merge elements of ALIST with the same key.
22271 For example, in this alist:
22273 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22274 => \\='((a 1 3) (b 2))
22276 merge (a 1) and (a 3) into (a 1 3).
22278 The function returns the new ALIST."
22279 (let (rtn)
22280 (dolist (e alist rtn)
22281 (let (n)
22282 (if (not (assoc (car e) rtn))
22283 (push e rtn)
22284 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22285 (setq rtn (assq-delete-all (car e) rtn))
22286 (push n rtn))))))
22288 (defun org-delete-all (elts list)
22289 "Remove all elements in ELTS from LIST.
22290 Comparison is done with `equal'. It is a destructive operation
22291 that may remove elements by altering the list structure."
22292 (while elts
22293 (setq list (delete (pop elts) list)))
22294 list)
22296 (defun org-back-over-empty-lines ()
22297 "Move backwards over whitespace, to the beginning of the first empty line.
22298 Returns the number of empty lines passed."
22299 (let ((pos (point)))
22300 (if (cdr (assq 'heading org-blank-before-new-entry))
22301 (skip-chars-backward " \t\n\r")
22302 (unless (eobp)
22303 (forward-line -1)))
22304 (beginning-of-line 2)
22305 (goto-char (min (point) pos))
22306 (count-lines (point) pos)))
22308 (defun org-skip-whitespace ()
22309 (skip-chars-forward " \t\n\r"))
22311 (defun org-point-in-group (point group &optional context)
22312 "Check if POINT is in match-group GROUP.
22313 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22314 match. If the match group does not exist or point is not inside it,
22315 return nil."
22316 (and (match-beginning group)
22317 (>= point (match-beginning group))
22318 (<= point (match-end group))
22319 (if context
22320 (list context (match-beginning group) (match-end group))
22321 t)))
22323 (defun org-switch-to-buffer-other-window (&rest args)
22324 "Switch to buffer in a second window on the current frame.
22325 In particular, do not allow pop-up frames.
22326 Returns the newly created buffer."
22327 (org-no-popups
22328 (apply 'switch-to-buffer-other-window args)))
22330 (defun org-combine-plists (&rest plists)
22331 "Create a single property list from all plists in PLISTS.
22332 The process starts by copying the first list, and then setting properties
22333 from the other lists. Settings in the last list are the most significant
22334 ones and overrule settings in the other lists."
22335 (let ((rtn (copy-sequence (pop plists)))
22336 p v ls)
22337 (while plists
22338 (setq ls (pop plists))
22339 (while ls
22340 (setq p (pop ls) v (pop ls))
22341 (setq rtn (plist-put rtn p v))))
22342 rtn))
22344 (defun org-replace-escapes (string table)
22345 "Replace %-escapes in STRING with values in TABLE.
22346 TABLE is an association list with keys like \"%a\" and string values.
22347 The sequences in STRING may contain normal field width and padding information,
22348 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22349 so values can contain further %-escapes if they are define later in TABLE."
22350 (let ((tbl (copy-alist table))
22351 (case-fold-search nil)
22352 (pchg 0)
22353 re rpl)
22354 (dolist (e tbl)
22355 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22356 (when (and (cdr e) (string-match re (cdr e)))
22357 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22358 (safe "SREF"))
22359 (add-text-properties 0 3 (list 'sref sref) safe)
22360 (setcdr e (replace-match safe t t (cdr e)))))
22361 (while (string-match re string)
22362 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22363 (cdr e)))
22364 (setq string (replace-match rpl t t string))))
22365 (while (setq pchg (next-property-change pchg string))
22366 (let ((sref (get-text-property pchg 'sref string)))
22367 (when (and sref (string-match "SREF" string pchg))
22368 (setq string (replace-match sref t t string)))))
22369 string))
22371 (defun org-find-base-buffer-visiting (file)
22372 "Like `find-buffer-visiting' but always return the base buffer and
22373 not an indirect buffer."
22374 (let ((buf (or (get-file-buffer file)
22375 (find-buffer-visiting file))))
22376 (if buf
22377 (or (buffer-base-buffer buf) buf)
22378 nil)))
22380 ;;; TODO: Only called once, from ox-odt which should probably use
22381 ;;; org-export-inline-image-p or something.
22382 (defun org-file-image-p (file)
22383 "Return non-nil if FILE is an image."
22384 (save-match-data
22385 (string-match (image-file-name-regexp) file)))
22387 (defun org-get-cursor-date (&optional with-time)
22388 "Return the date at cursor in as a time.
22389 This works in the calendar and in the agenda, anywhere else it just
22390 returns the current time.
22391 If WITH-TIME is non-nil, returns the time of the event at point (in
22392 the agenda) or the current time of the day."
22393 (let (date day defd tp hod mod)
22394 (when with-time
22395 (setq tp (get-text-property (point) 'time))
22396 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22397 (setq hod (string-to-number (match-string 1 tp))
22398 mod (string-to-number (match-string 2 tp))))
22399 (or tp (let ((now (decode-time)))
22400 (setq hod (nth 2 now)
22401 mod (nth 1 now)))))
22402 (cond
22403 ((eq major-mode 'calendar-mode)
22404 (setq date (calendar-cursor-to-date)
22405 defd (encode-time 0 (or mod 0) (or hod 0)
22406 (nth 1 date) (nth 0 date) (nth 2 date))))
22407 ((eq major-mode 'org-agenda-mode)
22408 (setq day (get-text-property (point) 'day))
22409 (when day
22410 (setq date (calendar-gregorian-from-absolute day)
22411 defd (encode-time 0 (or mod 0) (or hod 0)
22412 (nth 1 date) (nth 0 date) (nth 2 date))))))
22413 (or defd (current-time))))
22415 (defun org-mark-subtree (&optional up)
22416 "Mark the current subtree.
22417 This puts point at the start of the current subtree, and mark at
22418 the end. If a numeric prefix UP is given, move up into the
22419 hierarchy of headlines by UP levels before marking the subtree."
22420 (interactive "P")
22421 (org-with-limited-levels
22422 (cond ((org-at-heading-p) (beginning-of-line))
22423 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22424 (t (outline-previous-visible-heading 1))))
22425 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22426 (if (called-interactively-p 'any)
22427 (call-interactively 'org-mark-element)
22428 (org-mark-element)))
22430 (defun org-file-newer-than-p (file time)
22431 "Non-nil if FILE is newer than TIME.
22432 FILE is a filename, as a string, TIME is a list of integers, as
22433 returned by, e.g., `current-time'."
22434 (and (file-exists-p file)
22435 ;; Only compare times up to whole seconds as some file-systems
22436 ;; (e.g. HFS+) do not retain any finer granularity. As
22437 ;; a consequence, make sure we return non-nil when the two
22438 ;; times are equal.
22439 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22440 (cl-subseq time 0 2)))))
22442 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22443 "Compile a SOURCE file using PROCESS.
22445 PROCESS is either a function or a list of shell commands, as
22446 strings. EXT is a file extension, without the leading dot, as
22447 a string. It is used to check if the process actually succeeded.
22449 PROCESS must create a file with the same base name and directory
22450 as SOURCE, but ending with EXT. The function then returns its
22451 filename. Otherwise, it raises an error. The error message can
22452 then be refined by providing string ERR-MSG, which is appended to
22453 the standard message.
22455 If PROCESS is a function, it is called with a single argument:
22456 the SOURCE file.
22458 If it is a list of commands, each of them is called using
22459 `shell-command'. By default, in each command, %b, %f, %F, %o and
22460 %O are replaced with, respectively, SOURCE base name, name, full
22461 name, directory and absolute output file name. It is possible,
22462 however, to use more place-holders by specifying them in optional
22463 argument SPEC, as an alist following the pattern
22465 (CHARACTER . REPLACEMENT-STRING).
22467 When PROCESS is a list of commands, optional argument LOG-BUF can
22468 be set to a buffer or a buffer name. `shell-command' then uses
22469 it for output."
22470 (let* ((base-name (file-name-base source))
22471 (full-name (file-truename source))
22472 (out-dir (or (file-name-directory source) "./"))
22473 (output (expand-file-name (concat base-name "." ext) out-dir))
22474 (time (current-time))
22475 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22476 (save-window-excursion
22477 (pcase process
22478 ((pred functionp) (funcall process (shell-quote-argument source)))
22479 ((pred consp)
22480 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22481 (spec (append spec
22482 `((?b . ,(shell-quote-argument base-name))
22483 (?f . ,(shell-quote-argument source))
22484 (?F . ,(shell-quote-argument full-name))
22485 (?o . ,(shell-quote-argument out-dir))
22486 (?O . ,(shell-quote-argument output))))))
22487 (dolist (command process)
22488 (shell-command (format-spec command spec) log-buf))
22489 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22490 (_ (error "No valid command to process %S%s" source err-msg))))
22491 ;; Check for process failure. Output file is expected to be
22492 ;; located in the same directory as SOURCE.
22493 (unless (org-file-newer-than-p output time)
22494 (error (format "File %S wasn't produced%s" output err-msg)))
22495 output))
22497 ;;; Indentation
22499 (defvar org-element-greater-elements)
22500 (defun org--get-expected-indentation (element contentsp)
22501 "Expected indentation column for current line, according to ELEMENT.
22502 ELEMENT is an element containing point. CONTENTSP is non-nil
22503 when indentation is to be computed according to contents of
22504 ELEMENT."
22505 (let ((type (org-element-type element))
22506 (start (org-element-property :begin element))
22507 (post-affiliated (org-element-property :post-affiliated element)))
22508 (org-with-wide-buffer
22509 (cond
22510 (contentsp
22511 (cl-case type
22512 ((diary-sexp footnote-definition) 0)
22513 ((headline inlinetask nil)
22514 (if (not org-adapt-indentation) 0
22515 (let ((level (org-current-level)))
22516 (if level (1+ level) 0))))
22517 ((item plain-list) (org-list-item-body-column post-affiliated))
22519 (goto-char start)
22520 (org-get-indentation))))
22521 ((memq type '(headline inlinetask nil))
22522 (if (org-match-line "[ \t]*$")
22523 (org--get-expected-indentation element t)
22525 ((memq type '(diary-sexp footnote-definition)) 0)
22526 ;; First paragraph of a footnote definition or an item.
22527 ;; Indent like parent.
22528 ((< (line-beginning-position) start)
22529 (org--get-expected-indentation
22530 (org-element-property :parent element) t))
22531 ;; At first line: indent according to previous sibling, if any,
22532 ;; ignoring footnote definitions and inline tasks, or parent's
22533 ;; contents.
22534 ((= (line-beginning-position) start)
22535 (catch 'exit
22536 (while t
22537 (if (= (point-min) start) (throw 'exit 0)
22538 (goto-char (1- start))
22539 (let* ((previous (org-element-at-point))
22540 (parent previous))
22541 (while (and parent (<= (org-element-property :end parent) start))
22542 (setq previous parent
22543 parent (org-element-property :parent parent)))
22544 (cond
22545 ((not previous) (throw 'exit 0))
22546 ((> (org-element-property :end previous) start)
22547 (throw 'exit (org--get-expected-indentation previous t)))
22548 ((memq (org-element-type previous)
22549 '(footnote-definition inlinetask))
22550 (setq start (org-element-property :begin previous)))
22551 (t (goto-char (org-element-property :begin previous))
22552 (throw 'exit
22553 (if (bolp) (org-get-indentation)
22554 ;; At first paragraph in an item or
22555 ;; a footnote definition.
22556 (org--get-expected-indentation
22557 (org-element-property :parent previous) t))))))))))
22558 ;; Otherwise, move to the first non-blank line above.
22560 (beginning-of-line)
22561 (let ((pos (point)))
22562 (skip-chars-backward " \r\t\n")
22563 (cond
22564 ;; Two blank lines end a footnote definition or a plain
22565 ;; list. When we indent an empty line after them, the
22566 ;; containing list or footnote definition is over, so it
22567 ;; qualifies as a previous sibling. Therefore, we indent
22568 ;; like its first line.
22569 ((and (memq type '(footnote-definition plain-list))
22570 (> (count-lines (point) pos) 2))
22571 (goto-char start)
22572 (org-get-indentation))
22573 ;; Line above is the first one of a paragraph at the
22574 ;; beginning of an item or a footnote definition. Indent
22575 ;; like parent.
22576 ((< (line-beginning-position) start)
22577 (org--get-expected-indentation
22578 (org-element-property :parent element) t))
22579 ;; Line above is the beginning of an element, i.e., point
22580 ;; was originally on the blank lines between element's start
22581 ;; and contents.
22582 ((= (line-beginning-position) post-affiliated)
22583 (org--get-expected-indentation element t))
22584 ;; POS is after contents in a greater element. Indent like
22585 ;; the beginning of the element.
22586 ((and (memq type org-element-greater-elements)
22587 (let ((cend (org-element-property :contents-end element)))
22588 (and cend (<= cend pos))))
22589 ;; As a special case, if point is at the end of a footnote
22590 ;; definition or an item, indent like the very last element
22591 ;; within. If that last element is an item, indent like
22592 ;; its contents.
22593 (if (memq type '(footnote-definition item plain-list))
22594 (let ((last (org-element-at-point)))
22595 (goto-char pos)
22596 (org--get-expected-indentation
22597 last (eq (org-element-type last) 'item)))
22598 (goto-char start)
22599 (org-get-indentation)))
22600 ;; In any other case, indent like the current line.
22601 (t (org-get-indentation)))))))))
22603 (defun org--align-node-property ()
22604 "Align node property at point.
22605 Alignment is done according to `org-property-format', which see."
22606 (when (save-excursion
22607 (beginning-of-line)
22608 (looking-at org-property-re))
22609 (replace-match
22610 (concat (match-string 4)
22611 (org-trim
22612 (format org-property-format (match-string 1) (match-string 3))))
22613 t t)))
22615 (defun org-indent-line ()
22616 "Indent line depending on context.
22618 Indentation is done according to the following rules:
22620 - Footnote definitions, diary sexps, headlines and inline tasks
22621 have to start at column 0.
22623 - On the very first line of an element, consider, in order, the
22624 next rules until one matches:
22626 1. If there's a sibling element before, ignoring footnote
22627 definitions and inline tasks, indent like its first line.
22629 2. If element has a parent, indent like its contents. More
22630 precisely, if parent is an item, indent after the
22631 description part, if any, or the bullet (see
22632 `org-list-description-max-indent'). Else, indent like
22633 parent's first line.
22635 3. Otherwise, indent relatively to current level, if
22636 `org-adapt-indentation' is non-nil, or to left margin.
22638 - On a blank line at the end of an element, indent according to
22639 the type of the element. More precisely
22641 1. If element is a plain list, an item, or a footnote
22642 definition, indent like the very last element within.
22644 2. If element is a paragraph, indent like its last non blank
22645 line.
22647 3. Otherwise, indent like its very first line.
22649 - In the code part of a source block, use language major mode
22650 to indent current line if `org-src-tab-acts-natively' is
22651 non-nil. If it is nil, do nothing.
22653 - Otherwise, indent like the first non-blank line above.
22655 The function doesn't indent an item as it could break the whole
22656 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22657 `\\[org-shiftmetaright]'.
22659 Also align node properties according to `org-property-format'."
22660 (interactive)
22661 (cond
22662 (orgstruct-is-++
22663 (let ((indent-line-function
22664 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22665 (indent-according-to-mode)))
22666 ((org-at-heading-p) 'noindent)
22668 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22669 (type (org-element-type element)))
22670 (cond ((and (memq type '(plain-list item))
22671 (= (line-beginning-position)
22672 (org-element-property :post-affiliated element)))
22673 'noindent)
22674 ((and (eq type 'latex-environment)
22675 (>= (point) (org-element-property :post-affiliated element))
22676 (< (point) (org-with-wide-buffer
22677 (goto-char (org-element-property :end element))
22678 (skip-chars-backward " \r\t\n")
22679 (line-beginning-position 2))))
22680 'noindent)
22681 ((and (eq type 'src-block)
22682 org-src-tab-acts-natively
22683 (> (line-beginning-position)
22684 (org-element-property :post-affiliated element))
22685 (< (line-beginning-position)
22686 (org-with-wide-buffer
22687 (goto-char (org-element-property :end element))
22688 (skip-chars-backward " \r\t\n")
22689 (line-beginning-position))))
22690 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22692 (let ((column (org--get-expected-indentation element nil)))
22693 ;; Preserve current column.
22694 (if (<= (current-column) (current-indentation))
22695 (indent-line-to column)
22696 (save-excursion (indent-line-to column))))
22697 ;; Align node property. Also preserve current column.
22698 (when (eq type 'node-property)
22699 (let ((column (current-column)))
22700 (org--align-node-property)
22701 (org-move-to-column column)))))))))
22703 (defun org-indent-region (start end)
22704 "Indent each non-blank line in the region.
22705 Called from a program, START and END specify the region to
22706 indent. The function will not indent contents of example blocks,
22707 verse blocks and export blocks as leading white spaces are
22708 assumed to be significant there."
22709 (interactive "r")
22710 (save-excursion
22711 (goto-char start)
22712 (skip-chars-forward " \r\t\n")
22713 (unless (eobp) (beginning-of-line))
22714 (let ((indent-to
22715 (lambda (ind pos)
22716 ;; Set IND as indentation for all lines between point and
22717 ;; POS. Blank lines are ignored. Leave point after POS
22718 ;; once done.
22719 (let ((limit (copy-marker pos)))
22720 (while (< (point) limit)
22721 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22722 (forward-line))
22723 (set-marker limit nil))))
22724 (end (copy-marker end)))
22725 (while (< (point) end)
22726 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22727 (let* ((element (org-element-at-point))
22728 (type (org-element-type element))
22729 (element-end (copy-marker (org-element-property :end element)))
22730 (ind (org--get-expected-indentation element nil)))
22731 (cond
22732 ;; Element indented as a single block. Example blocks
22733 ;; preserving indentation are a special case since the
22734 ;; "contents" must not be indented whereas the block
22735 ;; boundaries can.
22736 ((or (memq type '(export-block latex-environment))
22737 (and (eq type 'example-block)
22738 (not
22739 (or org-src-preserve-indentation
22740 (org-element-property :preserve-indent element)))))
22741 (let ((offset (- ind (org-get-indentation))))
22742 (unless (zerop offset)
22743 (indent-rigidly (org-element-property :begin element)
22744 (org-element-property :end element)
22745 offset)))
22746 (goto-char element-end))
22747 ;; Elements indented line wise. Be sure to exclude
22748 ;; example blocks (preserving indentation) and source
22749 ;; blocks from this category as they are treated
22750 ;; specially later.
22751 ((or (memq type '(paragraph table table-row))
22752 (not (or (org-element-property :contents-begin element)
22753 (memq type '(example-block src-block)))))
22754 (when (eq type 'node-property)
22755 (org--align-node-property)
22756 (beginning-of-line))
22757 (funcall indent-to ind (min element-end end)))
22758 ;; Elements consisting of three parts: before the
22759 ;; contents, the contents, and after the contents. The
22760 ;; contents are treated specially, according to the
22761 ;; element type, or not indented at all. Other parts are
22762 ;; indented as a single block.
22764 (let* ((post (copy-marker
22765 (org-element-property :post-affiliated element)))
22766 (cbeg
22767 (copy-marker
22768 (cond
22769 ((not (org-element-property :contents-begin element))
22770 ;; Fake contents for source blocks.
22771 (org-with-wide-buffer
22772 (goto-char post)
22773 (line-beginning-position 2)))
22774 ((memq type '(footnote-definition item plain-list))
22775 ;; Contents in these elements could start on
22776 ;; the same line as the beginning of the
22777 ;; element. Make sure we start indenting
22778 ;; from the second line.
22779 (org-with-wide-buffer
22780 (goto-char post)
22781 (end-of-line)
22782 (skip-chars-forward " \r\t\n")
22783 (if (eobp) (point) (line-beginning-position))))
22784 (t (org-element-property :contents-begin element)))))
22785 (cend (copy-marker
22786 (or (org-element-property :contents-end element)
22787 ;; Fake contents for source blocks.
22788 (org-with-wide-buffer
22789 (goto-char element-end)
22790 (skip-chars-backward " \r\t\n")
22791 (line-beginning-position)))
22792 t)))
22793 ;; Do not change items indentation individually as it
22794 ;; might break the list as a whole. On the other
22795 ;; hand, when at a plain list, indent it as a whole.
22796 (cond ((eq type 'plain-list)
22797 (let ((offset (- ind (org-get-indentation))))
22798 (unless (zerop offset)
22799 (indent-rigidly (org-element-property :begin element)
22800 (org-element-property :end element)
22801 offset))
22802 (goto-char cbeg)))
22803 ((eq type 'item) (goto-char cbeg))
22804 (t (funcall indent-to ind (min cbeg end))))
22805 (when (< (point) end)
22806 (cl-case type
22807 ((example-block verse-block))
22808 (src-block
22809 ;; In a source block, indent source code
22810 ;; according to language major mode, but only if
22811 ;; `org-src-tab-acts-natively' is non-nil.
22812 (when (and (< (point) end) org-src-tab-acts-natively)
22813 (ignore-errors
22814 (org-babel-do-in-edit-buffer
22815 (indent-region (point-min) (point-max))))))
22816 (t (org-indent-region (point) (min cend end))))
22817 (goto-char (min cend end))
22818 (when (< (point) end)
22819 (funcall indent-to ind (min element-end end))))
22820 (set-marker post nil)
22821 (set-marker cbeg nil)
22822 (set-marker cend nil))))
22823 (set-marker element-end nil))))
22824 (set-marker end nil))))
22826 (defun org-indent-drawer ()
22827 "Indent the drawer at point."
22828 (interactive)
22829 (unless (save-excursion
22830 (beginning-of-line)
22831 (looking-at-p org-drawer-regexp))
22832 (user-error "Not at a drawer"))
22833 (let ((element (org-element-at-point)))
22834 (unless (memq (org-element-type element) '(drawer property-drawer))
22835 (user-error "Not at a drawer"))
22836 (org-with-wide-buffer
22837 (org-indent-region (org-element-property :begin element)
22838 (org-element-property :end element))))
22839 (message "Drawer at point indented"))
22841 (defun org-indent-block ()
22842 "Indent the block at point."
22843 (interactive)
22844 (unless (save-excursion
22845 (beginning-of-line)
22846 (let ((case-fold-search t))
22847 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22848 (user-error "Not at a block"))
22849 (let ((element (org-element-at-point)))
22850 (unless (memq (org-element-type element)
22851 '(comment-block center-block dynamic-block example-block
22852 export-block quote-block special-block
22853 src-block verse-block))
22854 (user-error "Not at a block"))
22855 (org-with-wide-buffer
22856 (org-indent-region (org-element-property :begin element)
22857 (org-element-property :end element))))
22858 (message "Block at point indented"))
22861 ;;; Filling
22863 ;; We use our own fill-paragraph and auto-fill functions.
22865 ;; `org-fill-paragraph' relies on adaptive filling and context
22866 ;; checking. Appropriate `fill-prefix' is computed with
22867 ;; `org-adaptive-fill-function'.
22869 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22870 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22871 ;; `org-adaptive-fill-function' value. Internally,
22872 ;; `org-comment-line-break-function' breaks the line.
22874 ;; `org-setup-filling' installs filling and auto-filling related
22875 ;; variables during `org-mode' initialization.
22877 (defvar org-element-paragraph-separate) ; org-element.el
22878 (defun org-setup-filling ()
22879 (require 'org-element)
22880 ;; Prevent auto-fill from inserting unwanted new items.
22881 (when (boundp 'fill-nobreak-predicate)
22882 (setq-local
22883 fill-nobreak-predicate
22884 (org-uniquify
22885 (append fill-nobreak-predicate
22886 '(org-fill-line-break-nobreak-p
22887 org-fill-n-macro-as-item-nobreak-p
22888 org-fill-paragraph-with-timestamp-nobreak-p)))))
22889 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22890 (setq-local paragraph-start paragraph-ending)
22891 (setq-local paragraph-separate paragraph-ending))
22892 (setq-local fill-paragraph-function 'org-fill-paragraph)
22893 (setq-local auto-fill-inhibit-regexp nil)
22894 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22895 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22896 (setq-local comment-line-break-function 'org-comment-line-break-function))
22898 (defun org-fill-line-break-nobreak-p ()
22899 "Non-nil when a new line at point would create an Org line break."
22900 (save-excursion
22901 (skip-chars-backward "[ \t]")
22902 (skip-chars-backward "\\\\")
22903 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22905 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22906 "Non-nil when a new line at point would split a timestamp."
22907 (and (org-at-timestamp-p 'lax)
22908 (not (looking-at org-ts-regexp-both))))
22910 (defun org-fill-n-macro-as-item-nobreak-p ()
22911 "Non-nil when a new line at point would create a new list."
22912 ;; During export, a "n" macro followed by a dot or a closing
22913 ;; parenthesis can end up being parsed as a new list item.
22914 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22916 (declare-function message-in-body-p "message" ())
22917 (defvar orgtbl-line-start-regexp) ; From org-table.el
22918 (defun org-adaptive-fill-function ()
22919 "Compute a fill prefix for the current line.
22920 Return fill prefix, as a string, or nil if current line isn't
22921 meant to be filled. For convenience, if `adaptive-fill-regexp'
22922 matches in paragraphs or comments, use it."
22923 (catch 'exit
22924 (when (derived-mode-p 'message-mode)
22925 (save-excursion
22926 (beginning-of-line)
22927 (cond ((not (message-in-body-p)) (throw 'exit nil))
22928 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22929 ((looking-at message-cite-prefix-regexp)
22930 (throw 'exit (match-string-no-properties 0)))
22931 ((looking-at org-outline-regexp)
22932 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22933 (org-with-wide-buffer
22934 (unless (org-at-heading-p)
22935 (let* ((p (line-beginning-position))
22936 (element (save-excursion
22937 (beginning-of-line)
22938 (org-element-at-point)))
22939 (type (org-element-type element))
22940 (post-affiliated (org-element-property :post-affiliated element)))
22941 (unless (< p post-affiliated)
22942 (cl-case type
22943 (comment
22944 (save-excursion
22945 (beginning-of-line)
22946 (looking-at "[ \t]*")
22947 (concat (match-string 0) "# ")))
22948 (footnote-definition "")
22949 ((item plain-list)
22950 (make-string (org-list-item-body-column post-affiliated) ?\s))
22951 (paragraph
22952 ;; Fill prefix is usually the same as the current line,
22953 ;; unless the paragraph is at the beginning of an item.
22954 (let ((parent (org-element-property :parent element)))
22955 (save-excursion
22956 (beginning-of-line)
22957 (cond ((eq (org-element-type parent) 'item)
22958 (make-string (org-list-item-body-column
22959 (org-element-property :begin parent))
22960 ?\s))
22961 ((and adaptive-fill-regexp
22962 ;; Locally disable
22963 ;; `adaptive-fill-function' to let
22964 ;; `fill-context-prefix' handle
22965 ;; `adaptive-fill-regexp' variable.
22966 (let (adaptive-fill-function)
22967 (fill-context-prefix
22968 post-affiliated
22969 (org-element-property :end element)))))
22970 ((looking-at "[ \t]+") (match-string 0))
22971 (t "")))))
22972 (comment-block
22973 ;; Only fill contents if P is within block boundaries.
22974 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22975 (forward-line)
22976 (point)))
22977 (cend (save-excursion
22978 (goto-char (org-element-property :end element))
22979 (skip-chars-backward " \r\t\n")
22980 (line-beginning-position))))
22981 (when (and (>= p cbeg) (< p cend))
22982 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22983 (match-string 0)
22984 "")))))))))))
22986 (declare-function message-goto-body "message" ())
22987 (defvar message-cite-prefix-regexp) ; From message.el
22989 (defun org-fill-element (&optional justify)
22990 "Fill element at point, when applicable.
22992 This function only applies to comment blocks, comments, example
22993 blocks and paragraphs. Also, as a special case, re-align table
22994 when point is at one.
22996 If JUSTIFY is non-nil (interactively, with prefix argument),
22997 justify as well. If `sentence-end-double-space' is non-nil, then
22998 period followed by one space does not end a sentence, so don't
22999 break a line there. The variable `fill-column' controls the
23000 width for filling.
23002 For convenience, when point is at a plain list, an item or
23003 a footnote definition, try to fill the first paragraph within."
23004 (with-syntax-table org-mode-transpose-word-syntax-table
23005 ;; Move to end of line in order to get the first paragraph within
23006 ;; a plain list or a footnote definition.
23007 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
23008 ;; First check if point is in a blank line at the beginning of
23009 ;; the buffer. In that case, ignore filling.
23010 (cl-case (org-element-type element)
23011 ;; Use major mode filling function is src blocks.
23012 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23013 ;; Align Org tables, leave table.el tables as-is.
23014 (table-row (org-table-align) t)
23015 (table
23016 (when (eq (org-element-property :type element) 'org)
23017 (save-excursion
23018 (goto-char (org-element-property :post-affiliated element))
23019 (org-table-align)))
23021 (paragraph
23022 ;; Paragraphs may contain `line-break' type objects.
23023 (let ((beg (max (point-min)
23024 (org-element-property :contents-begin element)))
23025 (end (min (point-max)
23026 (org-element-property :contents-end element))))
23027 ;; Do nothing if point is at an affiliated keyword.
23028 (if (< (line-end-position) beg) t
23029 (when (derived-mode-p 'message-mode)
23030 ;; In `message-mode', do not fill following citation
23031 ;; in current paragraph nor text before message body.
23032 (let ((body-start (save-excursion (message-goto-body))))
23033 (when body-start (setq beg (max body-start beg))))
23034 (when (save-excursion
23035 (re-search-forward
23036 (concat "^" message-cite-prefix-regexp) end t))
23037 (setq end (match-beginning 0))))
23038 ;; Fill paragraph, taking line breaks into account.
23039 (save-excursion
23040 (goto-char beg)
23041 (let ((cuts (list beg)))
23042 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23043 (when (eq 'line-break
23044 (org-element-type
23045 (save-excursion (backward-char)
23046 (org-element-context))))
23047 (push (point) cuts)))
23048 (dolist (c (delq end cuts))
23049 (fill-region-as-paragraph c end justify)
23050 (setq end c))))
23051 t)))
23052 ;; Contents of `comment-block' type elements should be
23053 ;; filled as plain text, but only if point is within block
23054 ;; markers.
23055 (comment-block
23056 (let* ((case-fold-search t)
23057 (beg (save-excursion
23058 (goto-char (org-element-property :begin element))
23059 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23060 (forward-line)
23061 (point)))
23062 (end (save-excursion
23063 (goto-char (org-element-property :end element))
23064 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23065 (line-beginning-position))))
23066 (if (or (< (point) beg) (> (point) end)) t
23067 (fill-region-as-paragraph
23068 (save-excursion (end-of-line)
23069 (re-search-backward "^[ \t]*$" beg 'move)
23070 (line-beginning-position))
23071 (save-excursion (beginning-of-line)
23072 (re-search-forward "^[ \t]*$" end 'move)
23073 (line-beginning-position))
23074 justify))))
23075 ;; Fill comments.
23076 (comment
23077 (let ((begin (org-element-property :post-affiliated element))
23078 (end (org-element-property :end element)))
23079 (when (and (>= (point) begin) (<= (point) end))
23080 (let ((begin (save-excursion
23081 (end-of-line)
23082 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23083 (progn (forward-line) (point))
23084 begin)))
23085 (end (save-excursion
23086 (end-of-line)
23087 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23088 (1- (line-beginning-position))
23089 (skip-chars-backward " \r\t\n")
23090 (line-end-position)))))
23091 ;; Do not fill comments when at a blank line.
23092 (when (> end begin)
23093 (let ((fill-prefix
23094 (save-excursion
23095 (beginning-of-line)
23096 (looking-at "[ \t]*#")
23097 (let ((comment-prefix (match-string 0)))
23098 (goto-char (match-end 0))
23099 (if (looking-at adaptive-fill-regexp)
23100 (concat comment-prefix (match-string 0))
23101 (concat comment-prefix " "))))))
23102 (save-excursion
23103 (fill-region-as-paragraph begin end justify))))))
23105 ;; Ignore every other element.
23106 (otherwise t)))))
23108 (defun org-fill-paragraph (&optional justify region)
23109 "Fill element at point, when applicable.
23111 This function only applies to comment blocks, comments, example
23112 blocks and paragraphs. Also, as a special case, re-align table
23113 when point is at one.
23115 For convenience, when point is at a plain list, an item or
23116 a footnote definition, try to fill the first paragraph within.
23118 If JUSTIFY is non-nil (interactively, with prefix argument),
23119 justify as well. If `sentence-end-double-space' is non-nil, then
23120 period followed by one space does not end a sentence, so don't
23121 break a line there. The variable `fill-column' controls the
23122 width for filling.
23124 The REGION argument is non-nil if called interactively; in that
23125 case, if Transient Mark mode is enabled and the mark is active,
23126 fill each of the elements in the active region, instead of just
23127 filling the current element."
23128 (interactive (progn
23129 (barf-if-buffer-read-only)
23130 (list (if current-prefix-arg 'full) t)))
23131 (cond
23132 ((and (derived-mode-p 'message-mode)
23133 (or (not (message-in-body-p))
23134 (save-excursion (move-beginning-of-line 1)
23135 (looking-at message-cite-prefix-regexp))))
23136 ;; First ensure filling is correct in message-mode.
23137 (let ((fill-paragraph-function
23138 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23139 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23140 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23141 (paragraph-separate
23142 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23143 (fill-paragraph nil)))
23144 ((and region transient-mark-mode mark-active
23145 (not (eq (region-beginning) (region-end))))
23146 (let ((origin (point-marker))
23147 (start (region-beginning)))
23148 (unwind-protect
23149 (progn
23150 (goto-char (region-end))
23151 (while (> (point) start)
23152 (org-backward-paragraph)
23153 (org-fill-element justify)))
23154 (goto-char origin)
23155 (set-marker origin nil))))
23156 (t (org-fill-element justify))))
23157 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23159 (defun org-auto-fill-function ()
23160 "Auto-fill function."
23161 ;; Check if auto-filling is meaningful.
23162 (let ((fc (current-fill-column)))
23163 (when (and fc (> (current-column) fc))
23164 (let* ((fill-prefix (org-adaptive-fill-function))
23165 ;; Enforce empty fill prefix, if required. Otherwise, it
23166 ;; will be computed again.
23167 (adaptive-fill-mode (not (equal fill-prefix ""))))
23168 (when fill-prefix (do-auto-fill))))))
23170 (defun org-comment-line-break-function (&optional soft)
23171 "Break line at point and indent, continuing comment if within one.
23172 The inserted newline is marked hard if variable
23173 `use-hard-newlines' is true, unless optional argument SOFT is
23174 non-nil."
23175 (if soft (insert-and-inherit ?\n) (newline 1))
23176 (save-excursion (forward-char -1) (delete-horizontal-space))
23177 (delete-horizontal-space)
23178 (indent-to-left-margin)
23179 (insert-before-markers-and-inherit fill-prefix))
23182 ;;; Fixed Width Areas
23184 (defun org-toggle-fixed-width ()
23185 "Toggle fixed-width markup.
23187 Add or remove fixed-width markup on current line, whenever it
23188 makes sense. Return an error otherwise.
23190 If a region is active and if it contains only fixed-width areas
23191 or blank lines, remove all fixed-width markup in it. If the
23192 region contains anything else, convert all non-fixed-width lines
23193 to fixed-width ones.
23195 Blank lines at the end of the region are ignored unless the
23196 region only contains such lines."
23197 (interactive)
23198 (if (not (org-region-active-p))
23199 ;; No region:
23201 ;; Remove fixed width marker only in a fixed-with element.
23203 ;; Add fixed width maker in paragraphs, in blank lines after
23204 ;; elements or at the beginning of a headline or an inlinetask,
23205 ;; and before any one-line elements (e.g., a clock).
23206 (progn
23207 (beginning-of-line)
23208 (let* ((element (org-element-at-point))
23209 (type (org-element-type element)))
23210 (cond
23211 ((and (eq type 'fixed-width)
23212 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23213 (replace-match
23214 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23215 ((and (memq type '(babel-call clock comment diary-sexp headline
23216 horizontal-rule keyword paragraph
23217 planning))
23218 (<= (org-element-property :post-affiliated element) (point)))
23219 (skip-chars-forward " \t")
23220 (insert ": "))
23221 ((and (looking-at-p "[ \t]*$")
23222 (or (eq type 'inlinetask)
23223 (save-excursion
23224 (skip-chars-forward " \r\t\n")
23225 (<= (org-element-property :end element) (point)))))
23226 (delete-region (point) (line-end-position))
23227 (org-indent-line)
23228 (insert ": "))
23229 (t (user-error "Cannot insert a fixed-width line here")))))
23230 ;; Region active.
23231 (let* ((begin (save-excursion
23232 (goto-char (region-beginning))
23233 (line-beginning-position)))
23234 (end (copy-marker
23235 (save-excursion
23236 (goto-char (region-end))
23237 (unless (eolp) (beginning-of-line))
23238 (if (save-excursion (re-search-backward "\\S-" begin t))
23239 (progn (skip-chars-backward " \r\t\n") (point))
23240 (point)))))
23241 (all-fixed-width-p
23242 (catch 'not-all-p
23243 (save-excursion
23244 (goto-char begin)
23245 (skip-chars-forward " \r\t\n")
23246 (when (eobp) (throw 'not-all-p nil))
23247 (while (< (point) end)
23248 (let ((element (org-element-at-point)))
23249 (if (eq (org-element-type element) 'fixed-width)
23250 (goto-char (org-element-property :end element))
23251 (throw 'not-all-p nil))))
23252 t))))
23253 (if all-fixed-width-p
23254 (save-excursion
23255 (goto-char begin)
23256 (while (< (point) end)
23257 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23258 (replace-match
23259 "" nil nil nil
23260 (if (= (line-end-position) (match-end 0)) 0 1)))
23261 (forward-line)))
23262 (let ((min-ind (point-max)))
23263 ;; Find minimum indentation across all lines.
23264 (save-excursion
23265 (goto-char begin)
23266 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23267 (setq min-ind 0)
23268 (catch 'zerop
23269 (while (< (point) end)
23270 (unless (looking-at-p "[ \t]*$")
23271 (let ((ind (org-get-indentation)))
23272 (setq min-ind (min min-ind ind))
23273 (when (zerop ind) (throw 'zerop t))))
23274 (forward-line)))))
23275 ;; Loop over all lines and add fixed-width markup everywhere
23276 ;; but in fixed-width lines.
23277 (save-excursion
23278 (goto-char begin)
23279 (while (< (point) end)
23280 (cond
23281 ((org-at-heading-p)
23282 (insert ": ")
23283 (forward-line)
23284 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23285 (insert ":")
23286 (forward-line)))
23287 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23288 (let* ((element (org-element-at-point))
23289 (element-end (org-element-property :end element)))
23290 (if (eq (org-element-type element) 'fixed-width)
23291 (progn (goto-char element-end)
23292 (skip-chars-backward " \r\t\n")
23293 (forward-line))
23294 (let ((limit (min end element-end)))
23295 (while (< (point) limit)
23296 (org-move-to-column min-ind t)
23297 (insert ": ")
23298 (forward-line))))))
23300 (org-move-to-column min-ind t)
23301 (insert ": ")
23302 (forward-line)))))))
23303 (set-marker end nil))))
23306 ;;; Comments
23308 ;; Org comments syntax is quite complex. It requires the entire line
23309 ;; to be just a comment. Also, even with the right syntax at the
23310 ;; beginning of line, some elements (e.g., verse-block or
23311 ;; example-block) don't accept comments. Usual Emacs comment commands
23312 ;; cannot cope with those requirements. Therefore, Org replaces them.
23314 ;; Org still relies on `comment-dwim', but cannot trust
23315 ;; `comment-only-p'. So, `comment-region-function' and
23316 ;; `uncomment-region-function' both point
23317 ;; to`org-comment-or-uncomment-region'. Eventually,
23318 ;; `org-insert-comment' takes care of insertion of comments at the
23319 ;; beginning of line.
23321 ;; `org-setup-comments-handling' install comments related variables
23322 ;; during `org-mode' initialization.
23324 (defun org-setup-comments-handling ()
23325 (interactive)
23326 (setq-local comment-use-syntax nil)
23327 (setq-local comment-start "# ")
23328 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23329 (setq-local comment-insert-comment-function 'org-insert-comment)
23330 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23331 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23333 (defun org-insert-comment ()
23334 "Insert an empty comment above current line.
23335 If the line is empty, insert comment at its beginning. When
23336 point is within a source block, comment according to the related
23337 major mode."
23338 (if (let ((element (org-element-at-point)))
23339 (and (eq (org-element-type element) 'src-block)
23340 (< (save-excursion
23341 (goto-char (org-element-property :post-affiliated element))
23342 (line-end-position))
23343 (point))
23344 (> (save-excursion
23345 (goto-char (org-element-property :end element))
23346 (skip-chars-backward " \r\t\n")
23347 (line-beginning-position))
23348 (point))))
23349 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23350 (beginning-of-line)
23351 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23352 (open-line 1))
23353 (org-indent-line)
23354 (insert "# ")))
23356 (defvar comment-empty-lines) ; From newcomment.el.
23357 (defun org-comment-or-uncomment-region (beg end &rest _)
23358 "Comment or uncomment each non-blank line in the region.
23359 Uncomment each non-blank line between BEG and END if it only
23360 contains commented lines. Otherwise, comment them. If region is
23361 strictly within a source block, use appropriate comment syntax."
23362 (if (let ((element (org-element-at-point)))
23363 (and (eq (org-element-type element) 'src-block)
23364 (< (save-excursion
23365 (goto-char (org-element-property :post-affiliated element))
23366 (line-end-position))
23367 beg)
23368 (>= (save-excursion
23369 (goto-char (org-element-property :end element))
23370 (skip-chars-backward " \r\t\n")
23371 (line-beginning-position))
23372 end)))
23373 ;; Translate region boundaries for the Org buffer to the source
23374 ;; buffer.
23375 (let ((offset (- end beg)))
23376 (save-excursion
23377 (goto-char beg)
23378 (org-babel-do-in-edit-buffer
23379 (comment-or-uncomment-region (point) (+ offset (point))))))
23380 (save-restriction
23381 ;; Restrict region
23382 (narrow-to-region (save-excursion (goto-char beg)
23383 (skip-chars-forward " \r\t\n" end)
23384 (line-beginning-position))
23385 (save-excursion (goto-char end)
23386 (skip-chars-backward " \r\t\n" beg)
23387 (line-end-position)))
23388 (let ((uncommentp
23389 ;; UNCOMMENTP is non-nil when every non blank line between
23390 ;; BEG and END is a comment.
23391 (save-excursion
23392 (goto-char (point-min))
23393 (while (and (not (eobp))
23394 (let ((element (org-element-at-point)))
23395 (and (eq (org-element-type element) 'comment)
23396 (goto-char (min (point-max)
23397 (org-element-property
23398 :end element)))))))
23399 (eobp))))
23400 (if uncommentp
23401 ;; Only blank lines and comments in region: uncomment it.
23402 (save-excursion
23403 (goto-char (point-min))
23404 (while (not (eobp))
23405 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23406 (replace-match "" nil nil nil 1))
23407 (forward-line)))
23408 ;; Comment each line in region.
23409 (let ((min-indent (point-max)))
23410 ;; First find the minimum indentation across all lines.
23411 (save-excursion
23412 (goto-char (point-min))
23413 (while (and (not (eobp)) (not (zerop min-indent)))
23414 (unless (looking-at "[ \t]*$")
23415 (setq min-indent (min min-indent (current-indentation))))
23416 (forward-line)))
23417 ;; Then loop over all lines.
23418 (save-excursion
23419 (goto-char (point-min))
23420 (while (not (eobp))
23421 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23422 ;; Don't get fooled by invisible text (e.g. link path)
23423 ;; when moving to column MIN-INDENT.
23424 (let ((buffer-invisibility-spec nil))
23425 (org-move-to-column min-indent t))
23426 (insert comment-start))
23427 (forward-line)))))))))
23429 (defun org-comment-dwim (_arg)
23430 "Call `comment-dwim' within a source edit buffer if needed."
23431 (interactive "*P")
23432 (if (org-in-src-block-p)
23433 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23434 (call-interactively 'comment-dwim)))
23437 ;;; Timestamps API
23439 ;; This section contains tools to operate on timestamp objects, as
23440 ;; returned by, e.g. `org-element-context'.
23442 (defun org-timestamp--to-internal-time (timestamp &optional end)
23443 "Encode TIMESTAMP object into Emacs internal time.
23444 Use end of date range or time range when END is non-nil."
23445 (apply #'encode-time
23446 (cons 0
23447 (mapcar
23448 (lambda (prop) (or (org-element-property prop timestamp) 0))
23449 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23450 '(:minute-start :hour-start :day-start :month-start
23451 :year-start))))))
23453 (defun org-timestamp-has-time-p (timestamp)
23454 "Non-nil when TIMESTAMP has a time specified."
23455 (org-element-property :hour-start timestamp))
23457 (defun org-timestamp-format (timestamp format &optional end utc)
23458 "Format a TIMESTAMP object into a string.
23460 FORMAT is a format specifier to be passed to
23461 `format-time-string'.
23463 When optional argument END is non-nil, use end of date-range or
23464 time-range, if possible.
23466 When optional argument UTC is non-nil, time will be expressed as
23467 Universal Time."
23468 (format-time-string
23469 format (org-timestamp--to-internal-time timestamp end)
23470 (and utc t)))
23472 (defun org-timestamp-split-range (timestamp &optional end)
23473 "Extract a TIMESTAMP object from a date or time range.
23475 END, when non-nil, means extract the end of the range.
23476 Otherwise, extract its start.
23478 Return a new timestamp object."
23479 (let ((type (org-element-property :type timestamp)))
23480 (if (memq type '(active inactive diary)) timestamp
23481 (let ((split-ts (org-element-copy timestamp)))
23482 ;; Set new type.
23483 (org-element-put-property
23484 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23485 ;; Copy start properties over end properties if END is
23486 ;; non-nil. Otherwise, copy end properties over `start' ones.
23487 (let ((p-alist '((:minute-start . :minute-end)
23488 (:hour-start . :hour-end)
23489 (:day-start . :day-end)
23490 (:month-start . :month-end)
23491 (:year-start . :year-end))))
23492 (dolist (p-cell p-alist)
23493 (org-element-put-property
23494 split-ts
23495 (funcall (if end #'car #'cdr) p-cell)
23496 (org-element-property
23497 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23498 ;; Eventually refresh `:raw-value'.
23499 (org-element-put-property split-ts :raw-value nil)
23500 (org-element-put-property
23501 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23503 (defun org-timestamp-translate (timestamp &optional boundary)
23504 "Translate TIMESTAMP object to custom format.
23506 Format string is defined in `org-time-stamp-custom-formats',
23507 which see.
23509 When optional argument BOUNDARY is non-nil, it is either the
23510 symbol `start' or `end'. In this case, only translate the
23511 starting or ending part of TIMESTAMP if it is a date or time
23512 range. Otherwise, translate both parts.
23514 Return timestamp as-is if `org-display-custom-times' is nil or if
23515 it has a `diary' type."
23516 (let ((type (org-element-property :type timestamp)))
23517 (if (or (not org-display-custom-times) (eq type 'diary))
23518 (org-element-interpret-data timestamp)
23519 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23520 org-time-stamp-custom-formats)))
23521 (if (and (not boundary) (memq type '(active-range inactive-range)))
23522 (concat (org-timestamp-format timestamp fmt)
23523 "--"
23524 (org-timestamp-format timestamp fmt t))
23525 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23529 ;;; Other stuff.
23531 (defvar reftex-docstruct-symbol)
23532 (defvar org--rds)
23534 (defun org-reftex-citation ()
23535 "Use reftex-citation to insert a citation into the buffer.
23536 This looks for a line like
23538 #+BIBLIOGRAPHY: foo plain option:-d
23540 and derives from it that foo.bib is the bibliography file relevant
23541 for this document. It then installs the necessary environment for RefTeX
23542 to work in this buffer and calls `reftex-citation' to insert a citation
23543 into the buffer.
23545 Export of such citations to both LaTeX and HTML is handled by the contributed
23546 package ox-bibtex by Taru Karttunen."
23547 (interactive)
23548 (let ((reftex-docstruct-symbol 'org--rds)
23549 org--rds bib)
23550 (org-with-wide-buffer
23551 (let ((case-fold-search t)
23552 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23553 (if (not (save-excursion
23554 (or (re-search-forward re nil t)
23555 (re-search-backward re nil t))))
23556 (user-error "No bibliography defined in file")
23557 (setq bib (concat (match-string 1) ".bib")
23558 org--rds (list (list 'bib bib))))))
23559 (call-interactively 'reftex-citation)))
23561 ;;;; Functions extending outline functionality
23563 (defun org-beginning-of-line (&optional n)
23564 "Go to the beginning of the current visible line.
23566 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23567 tags on the first attempt, and only move to after the tags when
23568 the cursor is already beyond the end of the headline.
23570 With argument N not nil or 1, move forward N - 1 lines first."
23571 (interactive "^p")
23572 (let ((origin (point))
23573 (special (pcase org-special-ctrl-a/e
23574 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23575 deactivate-mark)
23576 ;; First move to a visible line.
23577 (if (bound-and-true-p visual-line-mode)
23578 (beginning-of-visual-line n)
23579 (move-beginning-of-line n)
23580 ;; `move-beginning-of-line' may leave point after invisible
23581 ;; characters if line starts with such of these (e.g., with
23582 ;; a link at column 0). Really move to the beginning of the
23583 ;; current visible line.
23584 (beginning-of-line))
23585 (cond
23586 ;; No special behavior. Point is already at the beginning of
23587 ;; a line, logical or visual.
23588 ((not special))
23589 ;; `beginning-of-visual-line' left point before logical beginning
23590 ;; of line: point is at the beginning of a visual line. Bail
23591 ;; out.
23592 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23593 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23594 ;; At a headline, special position is before the title, but
23595 ;; after any TODO keyword or priority cookie.
23596 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23597 (line-end-position)))
23598 (bol (point)))
23599 (if (eq special 'reversed)
23600 (when (and (= origin bol) (eq last-command this-command))
23601 (goto-char refpos))
23602 (when (or (> origin refpos) (= origin bol))
23603 (goto-char refpos)))))
23604 ((and (looking-at org-list-full-item-re)
23605 (memq (org-element-type (save-match-data (org-element-at-point)))
23606 '(item plain-list)))
23607 ;; Set special position at first white space character after
23608 ;; bullet, and check-box, if any.
23609 (let ((after-bullet
23610 (let ((box (match-end 3)))
23611 (cond ((not box) (match-end 1))
23612 ((eq (char-after box) ?\s) (1+ box))
23613 (t box)))))
23614 (if (eq special 'reversed)
23615 (when (and (= (point) origin) (eq last-command this-command))
23616 (goto-char after-bullet))
23617 (when (or (> origin after-bullet) (= (point) origin))
23618 (goto-char after-bullet)))))
23619 ;; No special context. Point is already at beginning of line.
23620 (t nil))))
23622 (defun org-end-of-line (&optional n)
23623 "Go to the end of the line, but before ellipsis, if any.
23625 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23626 tags on the first attempt, and only move to after the tags when
23627 the cursor is already beyond the end of the headline.
23629 With argument N not nil or 1, move forward N - 1 lines first."
23630 (interactive "^p")
23631 (let ((origin (point))
23632 (special (pcase org-special-ctrl-a/e
23633 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23634 deactivate-mark)
23635 ;; First move to a visible line.
23636 (if (bound-and-true-p visual-line-mode)
23637 (beginning-of-visual-line n)
23638 (move-beginning-of-line n))
23639 (cond
23640 ;; At a headline, with tags.
23641 ((and special
23642 (save-excursion
23643 (beginning-of-line)
23644 (let ((case-fold-search nil))
23645 (looking-at org-complex-heading-regexp)))
23646 (match-end 5))
23647 (let ((tags (save-excursion
23648 (goto-char (match-beginning 5))
23649 (skip-chars-backward " \t")
23650 (point)))
23651 (visual-end (and (bound-and-true-p visual-line-mode)
23652 (save-excursion
23653 (end-of-visual-line)
23654 (point)))))
23655 ;; If `end-of-visual-line' brings us before end of line or
23656 ;; even tags, i.e., the headline spans over multiple visual
23657 ;; lines, move there.
23658 (cond ((and visual-end
23659 (< visual-end tags)
23660 (<= origin visual-end))
23661 (goto-char visual-end))
23662 ((eq special 'reversed)
23663 (if (and (= origin (line-end-position))
23664 (eq this-command last-command))
23665 (goto-char tags)
23666 (end-of-line)))
23668 (if (or (< origin tags) (= origin (line-end-position)))
23669 (goto-char tags)
23670 (end-of-line))))))
23671 ((bound-and-true-p visual-line-mode)
23672 (let ((bol (line-beginning-position)))
23673 (end-of-visual-line)
23674 ;; If `end-of-visual-line' gets us past the ellipsis at the
23675 ;; end of a line, backtrack and use `end-of-line' instead.
23676 (when (/= bol (line-beginning-position))
23677 (goto-char bol)
23678 (end-of-line))))
23679 (t (end-of-line)))))
23681 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23682 (define-key org-mode-map "\C-e" 'org-end-of-line)
23684 (defun org-backward-sentence (&optional _arg)
23685 "Go to beginning of sentence, or beginning of table field.
23686 This will call `backward-sentence' or `org-table-beginning-of-field',
23687 depending on context."
23688 (interactive)
23689 (let* ((element (org-element-at-point))
23690 (contents-begin (org-element-property :contents-begin element))
23691 (table (org-element-lineage element '(table) t)))
23692 (if (and table
23693 (> (point) contents-begin)
23694 (<= (point) (org-element-property :contents-end table)))
23695 (call-interactively #'org-table-beginning-of-field)
23696 (save-restriction
23697 (when (and contents-begin
23698 (< (point-min) contents-begin)
23699 (> (point) contents-begin))
23700 (narrow-to-region contents-begin
23701 (org-element-property :contents-end element)))
23702 (call-interactively #'backward-sentence)))))
23704 (defun org-forward-sentence (&optional _arg)
23705 "Go to end of sentence, or end of table field.
23706 This will call `forward-sentence' or `org-table-end-of-field',
23707 depending on context."
23708 (interactive)
23709 (let* ((element (org-element-at-point))
23710 (contents-end (org-element-property :contents-end element))
23711 (table (org-element-lineage element '(table) t)))
23712 (if (and table
23713 (>= (point) (org-element-property :contents-begin table))
23714 (< (point) contents-end))
23715 (call-interactively #'org-table-end-of-field)
23716 (save-restriction
23717 (when (and contents-end
23718 (> (point-max) contents-end)
23719 ;; Skip blank lines between elements.
23720 (< (org-element-property :end element)
23721 (save-excursion (goto-char contents-end)
23722 (skip-chars-forward " \r\t\n"))))
23723 (narrow-to-region (org-element-property :contents-begin element)
23724 contents-end))
23725 (call-interactively #'forward-sentence)))))
23727 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23728 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23730 (defun org-kill-line (&optional _arg)
23731 "Kill line, to tags or end of line."
23732 (interactive)
23733 (cond
23734 ((or (not org-special-ctrl-k)
23735 (bolp)
23736 (not (org-at-heading-p)))
23737 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23738 org-ctrl-k-protect-subtree
23739 (or (eq org-ctrl-k-protect-subtree 'error)
23740 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23741 (user-error "C-k aborted as it would kill a hidden subtree"))
23742 (call-interactively
23743 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23744 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23745 (kill-region (point) (match-beginning 1))
23746 (org-set-tags nil t))
23747 (t (kill-region (point) (point-at-eol)))))
23749 (define-key org-mode-map "\C-k" 'org-kill-line)
23751 (defun org-yank (&optional arg)
23752 "Yank. If the kill is a subtree, treat it specially.
23753 This command will look at the current kill and check if is a single
23754 subtree, or a series of subtrees[1]. If it passes the test, and if the
23755 cursor is at the beginning of a line or after the stars of a currently
23756 empty headline, then the yank is handled specially. How exactly depends
23757 on the value of the following variables.
23759 `org-yank-folded-subtrees'
23760 By default, this variable is non-nil, which results in
23761 subtree(s) being folded after insertion, except if doing so
23762 would swallow text after the yanked text.
23764 `org-yank-adjusted-subtrees'
23765 When non-nil (the default value is nil), the subtree will be
23766 promoted or demoted in order to fit into the local outline tree
23767 structure, which means that the level will be adjusted so that it
23768 becomes the smaller one of the two *visible* surrounding headings.
23770 Any prefix to this command will cause `yank' to be called directly with
23771 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23772 will just
23773 plainly yank the text as it is.
23775 \[1] The test checks if the first non-white line is a heading
23776 and if there are no other headings with fewer stars."
23777 (interactive "P")
23778 (org-yank-generic 'yank arg))
23780 (defun org-yank-generic (command arg)
23781 "Perform some yank-like command.
23783 This function implements the behavior described in the `org-yank'
23784 documentation. However, it has been generalized to work for any
23785 interactive command with similar behavior."
23787 ;; pretend to be command COMMAND
23788 (setq this-command command)
23790 (if arg
23791 (call-interactively command)
23793 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23794 (and (org-kill-is-subtree-p)
23795 (or (bolp)
23796 (and (looking-at "[ \t]*$")
23797 (string-match
23798 "\\`\\*+\\'"
23799 (buffer-substring (point-at-bol) (point)))))))
23800 swallowp)
23801 (cond
23802 ((and subtreep org-yank-folded-subtrees)
23803 (let ((beg (point))
23804 end)
23805 (if (and subtreep org-yank-adjusted-subtrees)
23806 (org-paste-subtree nil nil 'for-yank)
23807 (call-interactively command))
23809 (setq end (point))
23810 (goto-char beg)
23811 (when (and (bolp) subtreep
23812 (not (setq swallowp
23813 (org-yank-folding-would-swallow-text beg end))))
23814 (org-with-limited-levels
23815 (or (looking-at org-outline-regexp)
23816 (re-search-forward org-outline-regexp-bol end t))
23817 (while (and (< (point) end) (looking-at org-outline-regexp))
23818 (outline-hide-subtree)
23819 (org-cycle-show-empty-lines 'folded)
23820 (condition-case nil
23821 (outline-forward-same-level 1)
23822 (error (goto-char end))))))
23823 (when swallowp
23824 (message
23825 "Inserted text not folded because that would swallow text"))
23827 (goto-char end)
23828 (skip-chars-forward " \t\n\r")
23829 (beginning-of-line 1)
23830 (push-mark beg 'nomsg)))
23831 ((and subtreep org-yank-adjusted-subtrees)
23832 (let ((beg (point-at-bol)))
23833 (org-paste-subtree nil nil 'for-yank)
23834 (push-mark beg 'nomsg)))
23836 (call-interactively command))))))
23838 (defun org-yank-folding-would-swallow-text (beg end)
23839 "Would hide-subtree at BEG swallow any text after END?"
23840 (let (level)
23841 (org-with-limited-levels
23842 (save-excursion
23843 (goto-char beg)
23844 (when (or (looking-at org-outline-regexp)
23845 (re-search-forward org-outline-regexp-bol end t))
23846 (setq level (org-outline-level)))
23847 (goto-char end)
23848 (skip-chars-forward " \t\r\n\v\f")
23849 (not (or (eobp)
23850 (and (bolp) (looking-at-p org-outline-regexp)
23851 (<= (org-outline-level) level))))))))
23853 (define-key org-mode-map "\C-y" 'org-yank)
23855 (defun org-truely-invisible-p ()
23856 "Check if point is at a character currently not visible.
23857 This version does not only check the character property, but also
23858 `visible-mode'."
23859 (unless (bound-and-true-p visible-mode)
23860 (org-invisible-p)))
23862 (defun org-invisible-p2 ()
23863 "Check if point is at a character currently not visible.
23865 If the point is at EOL (and not at the beginning of a buffer too),
23866 move it back by one char before doing this check."
23867 (save-excursion
23868 (when (and (eolp) (not (bobp)))
23869 (backward-char 1))
23870 (org-invisible-p)))
23872 (defun org-back-to-heading (&optional invisible-ok)
23873 "Call `outline-back-to-heading', but provide a better error message."
23874 (condition-case nil
23875 (outline-back-to-heading invisible-ok)
23876 (error (error "Before first headline at position %d in buffer %s"
23877 (point) (current-buffer)))))
23879 (defun org-before-first-heading-p ()
23880 "Before first heading?"
23881 (save-excursion
23882 (end-of-line)
23883 (null (re-search-backward org-outline-regexp-bol nil t))))
23885 (defun org-at-heading-p (&optional ignored)
23886 (outline-on-heading-p t))
23888 (defun org-in-commented-heading-p (&optional no-inheritance)
23889 "Non-nil if point is under a commented heading.
23890 This function also checks ancestors of the current headline,
23891 unless optional argument NO-INHERITANCE is non-nil."
23892 (cond
23893 ((org-before-first-heading-p) nil)
23894 ((let ((headline (nth 4 (org-heading-components))))
23895 (and headline
23896 (let ((case-fold-search nil))
23897 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23898 headline)))))
23899 (no-inheritance nil)
23901 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23903 (defun org-at-comment-p nil
23904 "Is cursor in a commented line?"
23905 (save-excursion
23906 (save-match-data
23907 (beginning-of-line)
23908 (looking-at "^[ \t]*# "))))
23910 (defun org-at-drawer-p nil
23911 "Is cursor at a drawer keyword?"
23912 (save-excursion
23913 (move-beginning-of-line 1)
23914 (looking-at org-drawer-regexp)))
23916 (defun org-at-block-p nil
23917 "Is cursor at a block keyword?"
23918 (save-excursion
23919 (move-beginning-of-line 1)
23920 (looking-at org-block-regexp)))
23922 (defun org-point-at-end-of-empty-headline ()
23923 "If point is at the end of an empty headline, return t, else nil.
23924 If the heading only contains a TODO keyword, it is still still considered
23925 empty."
23926 (let ((case-fold-search nil))
23927 (and (looking-at "[ \t]*$")
23928 org-todo-line-regexp
23929 (save-excursion
23930 (beginning-of-line)
23931 (looking-at org-todo-line-regexp)
23932 (string= (match-string 3) "")))))
23934 (defun org-at-heading-or-item-p ()
23935 (or (org-at-heading-p) (org-at-item-p)))
23937 (defun org-at-target-p ()
23938 (or (org-in-regexp org-radio-target-regexp)
23939 (org-in-regexp org-target-regexp)))
23940 ;; Compatibility alias with Org versions < 7.8.03
23941 (defalias 'org-on-target-p 'org-at-target-p)
23943 (defun org-up-heading-all (arg)
23944 "Move to the heading line of which the present line is a subheading.
23945 This function considers both visible and invisible heading lines.
23946 With argument, move up ARG levels."
23947 (outline-up-heading arg t))
23949 (defun org-up-heading-safe ()
23950 "Move to the heading line of which the present line is a subheading.
23951 This version will not throw an error. It will return the level of the
23952 headline found, or nil if no higher level is found.
23954 Also, this function will be a lot faster than `outline-up-heading',
23955 because it relies on stars being the outline starters. This can really
23956 make a significant difference in outlines with very many siblings."
23957 (when (ignore-errors (org-back-to-heading t))
23958 (let ((level-up (1- (funcall outline-level))))
23959 (and (> level-up 0)
23960 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23961 (funcall outline-level)))))
23963 (defun org-first-sibling-p ()
23964 "Is this heading the first child of its parents?"
23965 (interactive)
23966 (let ((re org-outline-regexp-bol)
23967 level l)
23968 (unless (org-at-heading-p t)
23969 (user-error "Not at a heading"))
23970 (setq level (funcall outline-level))
23971 (save-excursion
23972 (if (not (re-search-backward re nil t))
23974 (setq l (funcall outline-level))
23975 (< l level)))))
23977 (defun org-goto-sibling (&optional previous)
23978 "Goto the next sibling, even if it is invisible.
23979 When PREVIOUS is set, go to the previous sibling instead. Returns t
23980 when a sibling was found. When none is found, return nil and don't
23981 move point."
23982 (let ((fun (if previous 're-search-backward 're-search-forward))
23983 (pos (point))
23984 (re org-outline-regexp-bol)
23985 level l)
23986 (when (ignore-errors (org-back-to-heading t))
23987 (setq level (funcall outline-level))
23988 (catch 'exit
23989 (or previous (forward-char 1))
23990 (while (funcall fun re nil t)
23991 (setq l (funcall outline-level))
23992 (when (< l level) (goto-char pos) (throw 'exit nil))
23993 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23994 (goto-char pos)
23995 nil))))
23997 (defun org-show-siblings ()
23998 "Show all siblings of the current headline."
23999 (save-excursion
24000 (while (org-goto-sibling) (org-flag-heading nil)))
24001 (save-excursion
24002 (while (org-goto-sibling 'previous)
24003 (org-flag-heading nil))))
24005 (defun org-goto-first-child ()
24006 "Goto the first child, even if it is invisible.
24007 Return t when a child was found. Otherwise don't move point and
24008 return nil."
24009 (let (level (pos (point)) (re org-outline-regexp-bol))
24010 (when (ignore-errors (org-back-to-heading t))
24011 (setq level (outline-level))
24012 (forward-char 1)
24013 (if (and (re-search-forward re nil t) (> (outline-level) level))
24014 (progn (goto-char (match-beginning 0)) t)
24015 (goto-char pos) nil))))
24017 (defun org-show-hidden-entry ()
24018 "Show an entry where even the heading is hidden."
24019 (save-excursion
24020 (org-show-entry)))
24022 (defun org-flag-heading (flag &optional entry)
24023 "Flag the current heading. FLAG non-nil means make invisible.
24024 When ENTRY is non-nil, show the entire entry."
24025 (save-excursion
24026 (org-back-to-heading t)
24027 ;; Check if we should show the entire entry
24028 (if entry
24029 (progn
24030 (org-show-entry)
24031 (save-excursion
24032 (and (outline-next-heading)
24033 (org-flag-heading nil))))
24034 (outline-flag-region (max (point-min) (1- (point)))
24035 (save-excursion (outline-end-of-heading) (point))
24036 flag))))
24038 (defun org-get-next-sibling ()
24039 "Move to next heading of the same level, and return point.
24040 If there is no such heading, return nil.
24041 This is like outline-next-sibling, but invisible headings are ok."
24042 (let ((level (funcall outline-level)))
24043 (outline-next-heading)
24044 (while (and (not (eobp)) (> (funcall outline-level) level))
24045 (outline-next-heading))
24046 (unless (or (eobp) (< (funcall outline-level) level))
24047 (point))))
24049 (defun org-get-last-sibling ()
24050 "Move to previous heading of the same level, and return point.
24051 If there is no such heading, return nil."
24052 (let ((opoint (point))
24053 (level (funcall outline-level)))
24054 (outline-previous-heading)
24055 (when (and (/= (point) opoint) (outline-on-heading-p t))
24056 (while (and (> (funcall outline-level) level)
24057 (not (bobp)))
24058 (outline-previous-heading))
24059 (unless (< (funcall outline-level) level)
24060 (point)))))
24062 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24063 "Goto to the end of a subtree."
24064 ;; This contains an exact copy of the original function, but it uses
24065 ;; `org-back-to-heading', to make it work also in invisible
24066 ;; trees. And is uses an invisible-ok argument.
24067 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24068 ;; Furthermore, when used inside Org, finding the end of a large subtree
24069 ;; with many children and grandchildren etc, this can be much faster
24070 ;; than the outline version.
24071 (org-back-to-heading invisible-ok)
24072 (let ((first t)
24073 (level (funcall outline-level)))
24074 (if (and (derived-mode-p 'org-mode) (< level 1000))
24075 ;; A true heading (not a plain list item), in Org
24076 ;; This means we can easily find the end by looking
24077 ;; only for the right number of stars. Using a regexp to do
24078 ;; this is so much faster than using a Lisp loop.
24079 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24080 (forward-char 1)
24081 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24082 ;; something else, do it the slow way
24083 (while (and (not (eobp))
24084 (or first (> (funcall outline-level) level)))
24085 (setq first nil)
24086 (outline-next-heading)))
24087 (unless to-heading
24088 (when (memq (preceding-char) '(?\n ?\^M))
24089 ;; Go to end of line before heading
24090 (forward-char -1)
24091 (when (memq (preceding-char) '(?\n ?\^M))
24092 ;; leave blank line before heading
24093 (forward-char -1)))))
24094 (point))
24096 (defun org-end-of-meta-data (&optional full)
24097 "Skip planning line and properties drawer in current entry.
24098 When optional argument FULL is non-nil, also skip empty lines,
24099 clocking lines and regular drawers at the beginning of the
24100 entry."
24101 (org-back-to-heading t)
24102 (forward-line)
24103 (when (looking-at-p org-planning-line-re) (forward-line))
24104 (when (looking-at org-property-drawer-re)
24105 (goto-char (match-end 0))
24106 (forward-line))
24107 (when (and full (not (org-at-heading-p)))
24108 (catch 'exit
24109 (let ((end (save-excursion (outline-next-heading) (point)))
24110 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24111 (while (not (eobp))
24112 (cond ((looking-at-p org-drawer-regexp)
24113 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24114 (forward-line)
24115 (throw 'exit t)))
24116 ((looking-at-p re) (forward-line))
24117 (t (throw 'exit t))))))))
24119 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24120 "Move forward to the ARG'th subheading at same level as this one.
24121 Stop at the first and last subheadings of a superior heading.
24122 Normally this only looks at visible headings, but when INVISIBLE-OK is
24123 non-nil it will also look at invisible ones."
24124 (interactive "p")
24125 (let ((backward? (and arg (< arg 0))))
24126 (if (org-before-first-heading-p)
24127 (if backward? (goto-char (point-min)) (outline-next-heading))
24128 (org-back-to-heading invisible-ok)
24129 (unless backward? (end-of-line)) ;do not match current headline
24130 (let ((level (- (match-end 0) (match-beginning 0) 1))
24131 (f (if backward? #'re-search-backward #'re-search-forward))
24132 (count (if arg (abs arg) 1))
24133 (result (point)))
24134 (while (and (> count 0)
24135 (funcall f org-outline-regexp-bol nil 'move))
24136 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24137 (cond ((< l level) (setq count 0))
24138 ((and (= l level)
24139 (or invisible-ok
24140 (not (org-invisible-p
24141 (line-beginning-position)))))
24142 (cl-decf count)
24143 (when (= l level) (setq result (point)))))))
24144 (goto-char result))
24145 (beginning-of-line))))
24147 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24148 "Move backward to the ARG'th subheading at same level as this one.
24149 Stop at the first and last subheadings of a superior heading."
24150 (interactive "p")
24151 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24153 (defun org-next-visible-heading (arg)
24154 "Move to the next visible heading.
24156 This function wraps `outline-next-visible-heading' with
24157 `org-with-limited-levels' in order to skip over inline tasks and
24158 respect customization of `org-odd-levels-only'."
24159 (interactive "p")
24160 (org-with-limited-levels
24161 (outline-next-visible-heading arg)))
24163 (defun org-previous-visible-heading (arg)
24164 "Move to the previous visible heading.
24166 This function wraps `outline-previous-visible-heading' with
24167 `org-with-limited-levels' in order to skip over inline tasks and
24168 respect customization of `org-odd-levels-only'."
24169 (interactive "p")
24170 (org-with-limited-levels
24171 (outline-previous-visible-heading arg)))
24173 (defun org-next-block (arg &optional backward block-regexp)
24174 "Jump to the next block.
24176 With a prefix argument ARG, jump forward ARG many blocks.
24178 When BACKWARD is non-nil, jump to the previous block.
24180 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24181 Match data is set according to this regexp when the function
24182 returns.
24184 Return point at beginning of the opening line of found block.
24185 Throw an error if no block is found."
24186 (interactive "p")
24187 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24188 (case-fold-search t)
24189 (search-fn (if backward #'re-search-backward #'re-search-forward))
24190 (count (or arg 1))
24191 (origin (point))
24192 last-element)
24193 (if backward (beginning-of-line) (end-of-line))
24194 (while (and (> count 0) (funcall search-fn re nil t))
24195 (let ((element (save-excursion
24196 (goto-char (match-beginning 0))
24197 (save-match-data (org-element-at-point)))))
24198 (when (and (memq (org-element-type element)
24199 '(center-block comment-block dynamic-block
24200 example-block export-block quote-block
24201 special-block src-block verse-block))
24202 (<= (match-beginning 0)
24203 (org-element-property :post-affiliated element)))
24204 (setq last-element element)
24205 (cl-decf count))))
24206 (if (= count 0)
24207 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24208 (save-match-data (org-show-context)))
24209 (goto-char origin)
24210 (user-error "No %s code blocks" (if backward "previous" "further")))))
24212 (defun org-previous-block (arg &optional block-regexp)
24213 "Jump to the previous block.
24214 With a prefix argument ARG, jump backward ARG many source blocks.
24215 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24216 (interactive "p")
24217 (org-next-block arg t block-regexp))
24219 (defun org-forward-paragraph ()
24220 "Move forward to beginning of next paragraph or equivalent.
24222 The function moves point to the beginning of the next visible
24223 structural element, which can be a paragraph, a table, a list
24224 item, etc. It also provides some special moves for convenience:
24226 - On an affiliated keyword, jump to the beginning of the
24227 relative element.
24228 - On an item or a footnote definition, move to the second
24229 element inside, if any.
24230 - On a table or a property drawer, jump after it.
24231 - On a verse or source block, stop after blank lines."
24232 (interactive)
24233 (when (eobp) (user-error "Cannot move further down"))
24234 (let* ((deactivate-mark nil)
24235 (element (org-element-at-point))
24236 (type (org-element-type element))
24237 (post-affiliated (org-element-property :post-affiliated element))
24238 (contents-begin (org-element-property :contents-begin element))
24239 (contents-end (org-element-property :contents-end element))
24240 (end (let ((end (org-element-property :end element)) (parent element))
24241 (while (and (setq parent (org-element-property :parent parent))
24242 (= (org-element-property :contents-end parent) end))
24243 (setq end (org-element-property :end parent)))
24244 end)))
24245 (cond ((not element)
24246 (skip-chars-forward " \r\t\n")
24247 (or (eobp) (beginning-of-line)))
24248 ;; On affiliated keywords, move to element's beginning.
24249 ((< (point) post-affiliated)
24250 (goto-char post-affiliated))
24251 ;; At a table row, move to the end of the table. Similarly,
24252 ;; at a node property, move to the end of the property
24253 ;; drawer.
24254 ((memq type '(node-property table-row))
24255 (goto-char (org-element-property
24256 :end (org-element-property :parent element))))
24257 ((memq type '(property-drawer table)) (goto-char end))
24258 ;; Consider blank lines as separators in verse and source
24259 ;; blocks to ease editing.
24260 ((memq type '(src-block verse-block))
24261 (when (eq type 'src-block)
24262 (setq contents-end
24263 (save-excursion (goto-char end)
24264 (skip-chars-backward " \r\t\n")
24265 (line-beginning-position))))
24266 (beginning-of-line)
24267 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24268 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24269 (goto-char end)
24270 (skip-chars-forward " \r\t\n")
24271 (if (= (point) contents-end) (goto-char end)
24272 (beginning-of-line))))
24273 ;; With no contents, just skip element.
24274 ((not contents-begin) (goto-char end))
24275 ;; If contents are invisible, skip the element altogether.
24276 ((org-invisible-p (line-end-position))
24277 (cl-case type
24278 (headline
24279 (org-with-limited-levels (outline-next-visible-heading 1)))
24280 ;; At a plain list, make sure we move to the next item
24281 ;; instead of skipping the whole list.
24282 (plain-list (forward-char)
24283 (org-forward-paragraph))
24284 (otherwise (goto-char end))))
24285 ((>= (point) contents-end) (goto-char end))
24286 ((>= (point) contents-begin)
24287 ;; This can only happen on paragraphs and plain lists.
24288 (cl-case type
24289 (paragraph (goto-char end))
24290 ;; At a plain list, try to move to second element in
24291 ;; first item, if possible.
24292 (plain-list (end-of-line)
24293 (org-forward-paragraph))))
24294 ;; When contents start on the middle of a line (e.g. in
24295 ;; items and footnote definitions), try to reach first
24296 ;; element starting after current line.
24297 ((> (line-end-position) contents-begin)
24298 (end-of-line)
24299 (org-forward-paragraph))
24300 (t (goto-char contents-begin)))))
24302 (defun org-backward-paragraph ()
24303 "Move backward to start of previous paragraph or equivalent.
24305 The function moves point to the beginning of the current
24306 structural element, which can be a paragraph, a table, a list
24307 item, etc., or to the beginning of the previous visible one if
24308 point is already there. It also provides some special moves for
24309 convenience:
24311 - On an affiliated keyword, jump to the first one.
24312 - On a table or a property drawer, move to its beginning.
24313 - On a verse or source block, stop before blank lines."
24314 (interactive)
24315 (when (bobp) (user-error "Cannot move further up"))
24316 (let* ((deactivate-mark nil)
24317 (element (org-element-at-point))
24318 (type (org-element-type element))
24319 (contents-begin (org-element-property :contents-begin element))
24320 (contents-end (org-element-property :contents-end element))
24321 (post-affiliated (org-element-property :post-affiliated element))
24322 (begin (org-element-property :begin element)))
24323 (cond
24324 ((not element) (goto-char (point-min)))
24325 ((= (point) begin)
24326 (backward-char)
24327 (org-backward-paragraph))
24328 ((<= (point) post-affiliated) (goto-char begin))
24329 ((memq type '(node-property table-row))
24330 (goto-char (org-element-property
24331 :post-affiliated (org-element-property :parent element))))
24332 ((memq type '(property-drawer table)) (goto-char begin))
24333 ((memq type '(src-block verse-block))
24334 (when (eq type 'src-block)
24335 (setq contents-begin
24336 (save-excursion (goto-char begin) (forward-line) (point))))
24337 (if (= (point) contents-begin) (goto-char post-affiliated)
24338 ;; Inside a verse block, see blank lines as paragraph
24339 ;; separators.
24340 (let ((origin (point)))
24341 (skip-chars-backward " \r\t\n" contents-begin)
24342 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24343 (skip-chars-forward " \r\t\n" origin)
24344 (if (= (point) origin) (goto-char contents-begin)
24345 (beginning-of-line))))))
24346 ((not contents-begin) (goto-char (or post-affiliated begin)))
24347 ((eq type 'paragraph)
24348 (goto-char contents-begin)
24349 ;; When at first paragraph in an item or a footnote definition,
24350 ;; move directly to beginning of line.
24351 (let ((parent-contents
24352 (org-element-property
24353 :contents-begin (org-element-property :parent element))))
24354 (when (and parent-contents (= parent-contents contents-begin))
24355 (beginning-of-line))))
24356 ;; At the end of a greater element, move to the beginning of the
24357 ;; last element within.
24358 ((>= (point) contents-end)
24359 (goto-char (1- contents-end))
24360 (org-backward-paragraph))
24361 (t (goto-char (or post-affiliated begin))))
24362 ;; Ensure we never leave point invisible.
24363 (when (org-invisible-p (point)) (beginning-of-visual-line))))
24365 (defun org-forward-element ()
24366 "Move forward by one element.
24367 Move to the next element at the same level, when possible."
24368 (interactive)
24369 (cond ((eobp) (user-error "Cannot move further down"))
24370 ((org-with-limited-levels (org-at-heading-p))
24371 (let ((origin (point)))
24372 (goto-char (org-end-of-subtree nil t))
24373 (unless (org-with-limited-levels (org-at-heading-p))
24374 (goto-char origin)
24375 (user-error "Cannot move further down"))))
24377 (let* ((elem (org-element-at-point))
24378 (end (org-element-property :end elem))
24379 (parent (org-element-property :parent elem)))
24380 (cond ((and parent (= (org-element-property :contents-end parent) end))
24381 (goto-char (org-element-property :end parent)))
24382 ((integer-or-marker-p end) (goto-char end))
24383 (t (message "No element at point")))))))
24385 (defun org-backward-element ()
24386 "Move backward by one element.
24387 Move to the previous element at the same level, when possible."
24388 (interactive)
24389 (cond ((bobp) (user-error "Cannot move further up"))
24390 ((org-with-limited-levels (org-at-heading-p))
24391 ;; At a headline, move to the previous one, if any, or stay
24392 ;; here.
24393 (let ((origin (point)))
24394 (org-with-limited-levels (org-backward-heading-same-level 1))
24395 ;; When current headline has no sibling above, move to its
24396 ;; parent.
24397 (when (= (point) origin)
24398 (or (org-with-limited-levels (org-up-heading-safe))
24399 (progn (goto-char origin)
24400 (user-error "Cannot move further up"))))))
24402 (let* ((elem (org-element-at-point))
24403 (beg (org-element-property :begin elem)))
24404 (cond
24405 ;; Move to beginning of current element if point isn't
24406 ;; there already.
24407 ((null beg) (message "No element at point"))
24408 ((/= (point) beg) (goto-char beg))
24409 (t (goto-char beg)
24410 (skip-chars-backward " \r\t\n")
24411 (unless (bobp)
24412 (let ((prev (org-element-at-point)))
24413 (goto-char (org-element-property :begin prev))
24414 (while (and (setq prev (org-element-property :parent prev))
24415 (<= (org-element-property :end prev) beg))
24416 (goto-char (org-element-property :begin prev)))))))))))
24418 (defun org-up-element ()
24419 "Move to upper element."
24420 (interactive)
24421 (if (org-with-limited-levels (org-at-heading-p))
24422 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24423 (let* ((elem (org-element-at-point))
24424 (parent (org-element-property :parent elem)))
24425 (if parent (goto-char (org-element-property :begin parent))
24426 (if (org-with-limited-levels (org-before-first-heading-p))
24427 (user-error "No surrounding element")
24428 (org-with-limited-levels (org-back-to-heading)))))))
24430 (defun org-down-element ()
24431 "Move to inner element."
24432 (interactive)
24433 (let ((element (org-element-at-point)))
24434 (cond
24435 ((memq (org-element-type element) '(plain-list table))
24436 (goto-char (org-element-property :contents-begin element))
24437 (forward-char))
24438 ((memq (org-element-type element) org-element-greater-elements)
24439 ;; If contents are hidden, first disclose them.
24440 (when (org-invisible-p (line-end-position)) (org-cycle))
24441 (goto-char (or (org-element-property :contents-begin element)
24442 (user-error "No content for this element"))))
24443 (t (user-error "No inner element")))))
24445 (defun org-drag-element-backward ()
24446 "Move backward element at point."
24447 (interactive)
24448 (let ((elem (or (org-element-at-point)
24449 (user-error "No element at point"))))
24450 (if (eq (org-element-type elem) 'headline)
24451 ;; Preserve point when moving a whole tree, even if point was
24452 ;; on blank lines below the headline.
24453 (let ((offset (skip-chars-backward " \t\n")))
24454 (unwind-protect (org-move-subtree-up)
24455 (forward-char (- offset))))
24456 (let ((prev-elem
24457 (save-excursion
24458 (goto-char (org-element-property :begin elem))
24459 (skip-chars-backward " \r\t\n")
24460 (unless (bobp)
24461 (let* ((beg (org-element-property :begin elem))
24462 (prev (org-element-at-point))
24463 (up prev))
24464 (while (and (setq up (org-element-property :parent up))
24465 (<= (org-element-property :end up) beg))
24466 (setq prev up))
24467 prev)))))
24468 ;; Error out if no previous element or previous element is
24469 ;; a parent of the current one.
24470 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24471 (user-error "Cannot drag element backward")
24472 (let ((pos (point)))
24473 (org-element-swap-A-B prev-elem elem)
24474 (goto-char (+ (org-element-property :begin prev-elem)
24475 (- pos (org-element-property :begin elem))))))))))
24477 (defun org-drag-element-forward ()
24478 "Move forward element at point."
24479 (interactive)
24480 (let* ((pos (point))
24481 (elem (or (org-element-at-point)
24482 (user-error "No element at point"))))
24483 (when (= (point-max) (org-element-property :end elem))
24484 (user-error "Cannot drag element forward"))
24485 (goto-char (org-element-property :end elem))
24486 (let ((next-elem (org-element-at-point)))
24487 (when (or (org-element-nested-p elem next-elem)
24488 (and (eq (org-element-type next-elem) 'headline)
24489 (not (eq (org-element-type elem) 'headline))))
24490 (goto-char pos)
24491 (user-error "Cannot drag element forward"))
24492 ;; Compute new position of point: it's shifted by NEXT-ELEM
24493 ;; body's length (without final blanks) and by the length of
24494 ;; blanks between ELEM and NEXT-ELEM.
24495 (let ((size-next (- (save-excursion
24496 (goto-char (org-element-property :end next-elem))
24497 (skip-chars-backward " \r\t\n")
24498 (forward-line)
24499 ;; Small correction if buffer doesn't end
24500 ;; with a newline character.
24501 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24502 (org-element-property :begin next-elem)))
24503 (size-blank (- (org-element-property :end elem)
24504 (save-excursion
24505 (goto-char (org-element-property :end elem))
24506 (skip-chars-backward " \r\t\n")
24507 (forward-line)
24508 (point)))))
24509 (org-element-swap-A-B elem next-elem)
24510 (goto-char (+ pos size-next size-blank))))))
24512 (defun org-drag-line-forward (arg)
24513 "Drag the line at point ARG lines forward."
24514 (interactive "p")
24515 (dotimes (_ (abs arg))
24516 (let ((c (current-column)))
24517 (if (< 0 arg)
24518 (progn
24519 (beginning-of-line 2)
24520 (transpose-lines 1)
24521 (beginning-of-line 0))
24522 (transpose-lines 1)
24523 (beginning-of-line -1))
24524 (org-move-to-column c))))
24526 (defun org-drag-line-backward (arg)
24527 "Drag the line at point ARG lines backward."
24528 (interactive "p")
24529 (org-drag-line-forward (- arg)))
24531 (defun org-mark-element ()
24532 "Put point at beginning of this element, mark at end.
24534 Interactively, if this command is repeated or (in Transient Mark
24535 mode) if the mark is active, it marks the next element after the
24536 ones already marked."
24537 (interactive)
24538 (let (deactivate-mark)
24539 (if (and (called-interactively-p 'any)
24540 (or (and (eq last-command this-command) (mark t))
24541 (and transient-mark-mode mark-active)))
24542 (set-mark
24543 (save-excursion
24544 (goto-char (mark))
24545 (goto-char (org-element-property :end (org-element-at-point)))))
24546 (let ((element (org-element-at-point)))
24547 (end-of-line)
24548 (push-mark (org-element-property :end element) t t)
24549 (goto-char (org-element-property :begin element))))))
24551 (defun org-narrow-to-element ()
24552 "Narrow buffer to current element."
24553 (interactive)
24554 (let ((elem (org-element-at-point)))
24555 (cond
24556 ((eq (car elem) 'headline)
24557 (narrow-to-region
24558 (org-element-property :begin elem)
24559 (org-element-property :end elem)))
24560 ((memq (car elem) org-element-greater-elements)
24561 (narrow-to-region
24562 (org-element-property :contents-begin elem)
24563 (org-element-property :contents-end elem)))
24565 (narrow-to-region
24566 (org-element-property :begin elem)
24567 (org-element-property :end elem))))))
24569 (defun org-transpose-element ()
24570 "Transpose current and previous elements, keeping blank lines between.
24571 Point is moved after both elements."
24572 (interactive)
24573 (org-skip-whitespace)
24574 (let ((end (org-element-property :end (org-element-at-point))))
24575 (org-drag-element-backward)
24576 (goto-char end)))
24578 (defun org-unindent-buffer ()
24579 "Un-indent the visible part of the buffer.
24580 Relative indentation (between items, inside blocks, etc.) isn't
24581 modified."
24582 (interactive)
24583 (unless (eq major-mode 'org-mode)
24584 (user-error "Cannot un-indent a buffer not in Org mode"))
24585 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24586 (unindent-tree
24587 (lambda (contents)
24588 (dolist (element (reverse contents))
24589 (if (memq (org-element-type element) '(headline section))
24590 (funcall unindent-tree (org-element-contents element))
24591 (save-excursion
24592 (save-restriction
24593 (narrow-to-region
24594 (org-element-property :begin element)
24595 (org-element-property :end element))
24596 (org-do-remove-indentation))))))))
24597 (funcall unindent-tree (org-element-contents parse-tree))))
24599 (defun org-show-children (&optional level)
24600 "Show all direct subheadings of this heading.
24601 Prefix arg LEVEL is how many levels below the current level
24602 should be shown. Default is enough to cause the following
24603 heading to appear."
24604 (interactive "p")
24605 ;; If `orgstruct-mode' is active, use the slower version.
24606 (if orgstruct-mode (call-interactively #'outline-show-children)
24607 (save-excursion
24608 (org-back-to-heading t)
24609 (let* ((current-level (funcall outline-level))
24610 (max-level (org-get-valid-level
24611 current-level
24612 (if level (prefix-numeric-value level) 1)))
24613 (end (save-excursion (org-end-of-subtree t t)))
24614 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24615 (past-first-child nil)
24616 ;; Make sure to skip inlinetasks.
24617 (re (format regexp-fmt
24618 current-level
24619 (cond
24620 ((not (featurep 'org-inlinetask)) "")
24621 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24623 (t (1- org-inlinetask-min-level))))))
24624 ;; Display parent heading.
24625 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24626 (forward-line)
24627 ;; Display children. First child may be deeper than expected
24628 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24629 ;; MAX-LEVEL accordingly.
24630 (while (re-search-forward re end t)
24631 (unless past-first-child
24632 (setq re (format regexp-fmt
24633 current-level
24634 (max (funcall outline-level) max-level)))
24635 (setq past-first-child t))
24636 (outline-flag-region
24637 (line-end-position 0) (line-end-position) nil))))))
24639 (defun org-show-subtree ()
24640 "Show everything after this heading at deeper levels."
24641 (interactive)
24642 (outline-flag-region
24643 (point)
24644 (save-excursion
24645 (org-end-of-subtree t t))
24646 nil))
24648 (defun org-show-entry ()
24649 "Show the body directly following this heading.
24650 Show the heading too, if it is currently invisible."
24651 (interactive)
24652 (save-excursion
24653 (ignore-errors
24654 (org-back-to-heading t)
24655 (outline-flag-region
24656 (max (point-min) (1- (point)))
24657 (save-excursion
24658 (if (re-search-forward
24659 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24660 (match-beginning 1)
24661 (point-max)))
24662 nil)
24663 (org-cycle-hide-drawers 'children))))
24665 (defun org-make-options-regexp (kwds &optional extra)
24666 "Make a regular expression for keyword lines.
24667 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24668 when non-nil, is a regexp matching keywords names."
24669 (concat "^[ \t]*#\\+\\("
24670 (regexp-opt kwds)
24671 (and extra (concat (and kwds "\\|") extra))
24672 "\\):[ \t]*\\(.*\\)"))
24674 ;;;; Integration with and fixes for other packages
24676 ;;; Imenu support
24678 (defvar-local org-imenu-markers nil
24679 "All markers currently used by Imenu.")
24681 (defun org-imenu-new-marker (&optional pos)
24682 "Return a new marker for use by Imenu, and remember the marker."
24683 (let ((m (make-marker)))
24684 (move-marker m (or pos (point)))
24685 (push m org-imenu-markers)
24688 (defun org-imenu-get-tree ()
24689 "Produce the index for Imenu."
24690 (dolist (x org-imenu-markers) (move-marker x nil))
24691 (setq org-imenu-markers nil)
24692 (let* ((case-fold-search nil)
24693 (n org-imenu-depth)
24694 (re (concat "^" (org-get-limited-outline-regexp)))
24695 (subs (make-vector (1+ n) nil))
24696 (last-level 0)
24697 m level head0 head)
24698 (org-with-wide-buffer
24699 (goto-char (point-max))
24700 (while (re-search-backward re nil t)
24701 (setq level (org-reduced-level (funcall outline-level)))
24702 (when (and (<= level n)
24703 (looking-at org-complex-heading-regexp)
24704 (setq head0 (match-string-no-properties 4)))
24705 (setq head (org-link-display-format head0)
24706 m (org-imenu-new-marker))
24707 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24708 (if (>= level last-level)
24709 (push (cons head m) (aref subs level))
24710 (push (cons head (aref subs (1+ level))) (aref subs level))
24711 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24712 (setq last-level level))))
24713 (aref subs 1)))
24715 (eval-after-load "imenu"
24716 '(progn
24717 (add-hook 'imenu-after-jump-hook
24718 (lambda ()
24719 (when (derived-mode-p 'org-mode)
24720 (org-show-context 'org-goto))))))
24722 (defun org-link-display-format (s)
24723 "Replace links in string S with their description.
24724 If there is no description, use the link target."
24725 (save-match-data
24726 (replace-regexp-in-string
24727 org-bracket-link-analytic-regexp
24728 (lambda (m)
24729 (if (match-end 5) (match-string 5 m)
24730 (concat (match-string 1 m) (match-string 3 m))))
24731 s nil t)))
24733 (defun org-toggle-link-display ()
24734 "Toggle the literal or descriptive display of links."
24735 (interactive)
24736 (if org-descriptive-links
24737 (progn (org-remove-from-invisibility-spec '(org-link))
24738 (org-restart-font-lock)
24739 (setq org-descriptive-links nil))
24740 (progn (add-to-invisibility-spec '(org-link))
24741 (org-restart-font-lock)
24742 (setq org-descriptive-links t))))
24744 ;; Speedbar support
24746 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24747 "Overlay marking the agenda restriction line in speedbar.")
24748 (overlay-put org-speedbar-restriction-lock-overlay
24749 'face 'org-agenda-restriction-lock)
24750 (overlay-put org-speedbar-restriction-lock-overlay
24751 'help-echo "Agendas are currently limited to this item.")
24752 (delete-overlay org-speedbar-restriction-lock-overlay)
24754 (defun org-speedbar-set-agenda-restriction ()
24755 "Restrict future agenda commands to the location at point in speedbar.
24756 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24757 (interactive)
24758 (require 'org-agenda)
24759 (let (p m tp np dir txt)
24760 (cond
24761 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24762 'org-imenu t))
24763 (setq m (get-text-property p 'org-imenu-marker))
24764 (with-current-buffer (marker-buffer m)
24765 (goto-char m)
24766 (org-agenda-set-restriction-lock 'subtree)))
24767 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24768 'speedbar-function 'speedbar-find-file))
24769 (setq tp (previous-single-property-change
24770 (1+ p) 'speedbar-function)
24771 np (next-single-property-change
24772 tp 'speedbar-function)
24773 dir (speedbar-line-directory)
24774 txt (buffer-substring-no-properties (or tp (point-min))
24775 (or np (point-max))))
24776 (with-current-buffer (find-file-noselect
24777 (let ((default-directory dir))
24778 (expand-file-name txt)))
24779 (unless (derived-mode-p 'org-mode)
24780 (user-error "Cannot restrict to non-Org mode file"))
24781 (org-agenda-set-restriction-lock 'file)))
24782 (t (user-error "Don't know how to restrict Org mode agenda")))
24783 (move-overlay org-speedbar-restriction-lock-overlay
24784 (point-at-bol) (point-at-eol))
24785 (setq current-prefix-arg nil)
24786 (org-agenda-maybe-redo)))
24788 (defvar speedbar-file-key-map)
24789 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24790 (eval-after-load "speedbar"
24791 '(progn
24792 (speedbar-add-supported-extension ".org")
24793 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24794 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24795 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24796 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24797 (add-hook 'speedbar-visiting-tag-hook
24798 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24800 ;;; Fixes and Hacks for problems with other packages
24802 (defun org--flyspell-object-check-p (element)
24803 "Non-nil when Flyspell can check object at point.
24804 ELEMENT is the element at point."
24805 (let ((object (save-excursion
24806 (when (looking-at-p "\\>") (backward-char))
24807 (org-element-context element))))
24808 (cl-case (org-element-type object)
24809 ;; Prevent checks in links due to keybinding conflict with
24810 ;; Flyspell.
24811 ((code entity export-snippet inline-babel-call
24812 inline-src-block line-break latex-fragment link macro
24813 statistics-cookie target timestamp verbatim)
24814 nil)
24815 (footnote-reference
24816 ;; Only in inline footnotes, within the definition.
24817 (and (eq (org-element-property :type object) 'inline)
24818 (< (save-excursion
24819 (goto-char (org-element-property :begin object))
24820 (search-forward ":" nil t 2))
24821 (point))))
24822 (otherwise t))))
24824 (defun org-mode-flyspell-verify ()
24825 "Function used for `flyspell-generic-check-word-predicate'."
24826 (if (org-at-heading-p)
24827 ;; At a headline or an inlinetask, check title only. This is
24828 ;; faster than relying on `org-element-at-point'.
24829 (and (save-excursion (beginning-of-line)
24830 (and (let ((case-fold-search t))
24831 (not (looking-at-p "\\*+ END[ \t]*$")))
24832 (let ((case-fold-search nil))
24833 (looking-at org-complex-heading-regexp))))
24834 (match-beginning 4)
24835 (>= (point) (match-beginning 4))
24836 (or (not (match-beginning 5))
24837 (< (point) (match-beginning 5))))
24838 (let* ((element (org-element-at-point))
24839 (post-affiliated (org-element-property :post-affiliated element)))
24840 (cond
24841 ;; Ignore checks in all affiliated keywords but captions.
24842 ((< (point) post-affiliated)
24843 (and (save-excursion
24844 (beginning-of-line)
24845 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24846 (> (point) (match-end 0))
24847 (org--flyspell-object-check-p element)))
24848 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24849 ((let ((log (org-log-into-drawer)))
24850 (and log
24851 (let ((drawer (org-element-lineage element '(drawer))))
24852 (and drawer
24853 (eq (compare-strings
24854 log nil nil
24855 (org-element-property :drawer-name drawer) nil nil t)
24856 t)))))
24857 nil)
24859 (cl-case (org-element-type element)
24860 ((comment quote-section) t)
24861 (comment-block
24862 ;; Allow checks between block markers, not on them.
24863 (and (> (line-beginning-position) post-affiliated)
24864 (save-excursion
24865 (end-of-line)
24866 (skip-chars-forward " \r\t\n")
24867 (< (point) (org-element-property :end element)))))
24868 ;; Arbitrary list of keywords where checks are meaningful.
24869 ;; Make sure point is on the value part of the element.
24870 (keyword
24871 (and (member (org-element-property :key element)
24872 '("DESCRIPTION" "TITLE"))
24873 (save-excursion
24874 (search-backward ":" (line-beginning-position) t))))
24875 ;; Check is globally allowed in paragraphs verse blocks and
24876 ;; table rows (after affiliated keywords) but some objects
24877 ;; must not be affected.
24878 ((paragraph table-row verse-block)
24879 (let ((cbeg (org-element-property :contents-begin element))
24880 (cend (org-element-property :contents-end element)))
24881 (and cbeg (>= (point) cbeg) (< (point) cend)
24882 (org--flyspell-object-check-p element))))))))))
24883 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24885 (defun org-remove-flyspell-overlays-in (beg end)
24886 "Remove flyspell overlays in region."
24887 (and (bound-and-true-p flyspell-mode)
24888 (fboundp 'flyspell-delete-region-overlays)
24889 (flyspell-delete-region-overlays beg end)))
24891 (defvar flyspell-delayed-commands)
24892 (eval-after-load "flyspell"
24893 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24895 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24896 (eval-after-load "bookmark"
24897 '(if (boundp 'bookmark-after-jump-hook)
24898 ;; We can use the hook
24899 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24900 ;; Hook not available, use advice
24901 (defadvice bookmark-jump (after org-make-visible activate)
24902 "Make the position visible."
24903 (org-bookmark-jump-unhide))))
24905 ;; Make sure saveplace shows the location if it was hidden
24906 (eval-after-load "saveplace"
24907 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24908 "Make the position visible."
24909 (org-bookmark-jump-unhide)))
24911 ;; Make sure ecb shows the location if it was hidden
24912 (eval-after-load "ecb"
24913 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24914 "Make hierarchy visible when jumping into location from ECB tree buffer."
24915 (when (derived-mode-p 'org-mode)
24916 (org-show-context))))
24918 (defun org-bookmark-jump-unhide ()
24919 "Unhide the current position, to show the bookmark location."
24920 (and (derived-mode-p 'org-mode)
24921 (or (org-invisible-p)
24922 (save-excursion (goto-char (max (point-min) (1- (point))))
24923 (org-invisible-p)))
24924 (org-show-context 'bookmark-jump)))
24926 (defun org-mark-jump-unhide ()
24927 "Make the point visible with `org-show-context' after jumping to the mark."
24928 (when (and (derived-mode-p 'org-mode)
24929 (org-invisible-p))
24930 (org-show-context 'mark-goto)))
24932 (eval-after-load "simple"
24933 '(defadvice pop-to-mark-command (after org-make-visible activate)
24934 "Make the point visible with `org-show-context'."
24935 (org-mark-jump-unhide)))
24937 (eval-after-load "simple"
24938 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24939 "Make the point visible with `org-show-context'."
24940 (org-mark-jump-unhide)))
24942 (eval-after-load "simple"
24943 '(defadvice pop-global-mark (after org-make-visible activate)
24944 "Make the point visible with `org-show-context'."
24945 (org-mark-jump-unhide)))
24947 ;; Make session.el ignore our circular variable
24948 (defvar session-globals-exclude)
24949 (eval-after-load "session"
24950 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24952 ;;;; Finish up
24954 (provide 'org)
24956 (run-hooks 'org-load-hook)
24958 ;;; org.el ends here