Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blobce2c108a42eeb90c6821a32f4c2b1dd7709092aa
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. When a non-empty string,
1131 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 (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
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 foreground 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 STATE should be one of the symbols listed in the docstring of
4705 `org-cycle-hook'."
4706 (when (and (not org-cycle-open-archived-trees)
4707 (not (memq state '(overview folded))))
4708 (save-excursion
4709 (let* ((globalp (memq state '(contents all)))
4710 (beg (if globalp (point-min) (point)))
4711 (end (if globalp (point-max) (org-end-of-subtree t))))
4712 (org-hide-archived-subtrees beg end)
4713 (goto-char beg)
4714 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4715 (message "%s" (substitute-command-keys
4716 "Subtree is archived and stays closed. Use \
4717 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4719 (defun org-force-cycle-archived ()
4720 "Cycle subtree even if it is archived."
4721 (interactive)
4722 (setq this-command 'org-cycle)
4723 (let ((org-cycle-open-archived-trees t))
4724 (call-interactively 'org-cycle)))
4726 (defun org-hide-archived-subtrees (beg end)
4727 "Re-hide all archived subtrees after a visibility state change."
4728 (org-with-wide-buffer
4729 (let ((case-fold-search nil)
4730 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4731 (goto-char beg)
4732 ;; Include headline point is currently on.
4733 (beginning-of-line)
4734 (while (and (< (point) end) (re-search-forward re end t))
4735 (when (member org-archive-tag (org-get-tags))
4736 (org-flag-subtree t)
4737 (org-end-of-subtree t))))))
4739 (declare-function outline-end-of-heading "outline" ())
4740 (declare-function outline-flag-region "outline" (from to flag))
4741 (defun org-flag-subtree (flag)
4742 (save-excursion
4743 (org-back-to-heading t)
4744 (outline-end-of-heading)
4745 (outline-flag-region (point)
4746 (progn (org-end-of-subtree t) (point))
4747 flag)))
4749 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4751 ;; Declare Column View Code
4753 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4754 (declare-function org-columns-compute "org-colview" (property))
4756 ;; Declare ID code
4758 (declare-function org-id-store-link "org-id")
4759 (declare-function org-id-locations-load "org-id")
4760 (declare-function org-id-locations-save "org-id")
4761 (defvar org-id-track-globally)
4763 ;;; Variables for pre-computed regular expressions, all buffer local
4765 (defvar-local org-todo-regexp nil
4766 "Matches any of the TODO state keywords.
4767 Since TODO keywords are case-sensitive, `case-fold-search' is
4768 expected to be bound to nil when matching against this regexp.")
4770 (defvar-local org-not-done-regexp nil
4771 "Matches any of the TODO state keywords except the last one.
4772 Since TODO keywords are case-sensitive, `case-fold-search' is
4773 expected to be bound to nil when matching against this regexp.")
4775 (defvar-local org-not-done-heading-regexp nil
4776 "Matches a TODO headline that is not done.
4777 Since TODO keywords are case-sensitive, `case-fold-search' is
4778 expected to be bound to nil when matching against this regexp.")
4780 (defvar-local org-todo-line-regexp nil
4781 "Matches a headline and puts TODO state into group 2 if present.
4782 Since TODO keywords are case-sensitive, `case-fold-search' is
4783 expected to be bound to nil when matching against this regexp.")
4785 (defvar-local org-complex-heading-regexp nil
4786 "Matches a headline and puts everything into groups:
4788 group 1: Stars
4789 group 2: The TODO keyword, maybe
4790 group 3: Priority cookie
4791 group 4: True headline
4792 group 5: Tags
4794 Since TODO keywords are case-sensitive, `case-fold-search' is
4795 expected to be bound to nil when matching against this regexp.")
4797 (defvar-local org-complex-heading-regexp-format nil
4798 "Printf format to make regexp to match an exact headline.
4799 This regexp will match the headline of any node which has the
4800 exact headline text that is put into the format, but may have any
4801 TODO state, priority and tags.")
4803 (defvar-local org-todo-line-tags-regexp nil
4804 "Matches a headline and puts TODO state into group 2 if present.
4805 Also put tags into group 4 if tags are present.")
4807 (defconst org-plain-time-of-day-regexp
4808 (concat
4809 "\\(\\<[012]?[0-9]"
4810 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4811 "\\(--?"
4812 "\\(\\<[012]?[0-9]"
4813 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4814 "\\)?")
4815 "Regular expression to match a plain time or time range.
4816 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4817 groups carry important information:
4818 0 the full match
4819 1 the first time, range or not
4820 8 the second time, if it is a range.")
4822 (defconst org-plain-time-extension-regexp
4823 (concat
4824 "\\(\\<[012]?[0-9]"
4825 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4826 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4827 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4828 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4829 groups carry important information:
4830 0 the full match
4831 7 hours of duration
4832 9 minutes of duration")
4834 (defconst org-stamp-time-of-day-regexp
4835 (concat
4836 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4837 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4838 "\\(--?"
4839 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4840 "Regular expression to match a timestamp time or time range.
4841 After a match, the following groups carry important information:
4842 0 the full match
4843 1 date plus weekday, for back referencing to make sure both times are on the same day
4844 2 the first time, range or not
4845 4 the second time, if it is a range.")
4847 (defconst org-startup-options
4848 '(("fold" org-startup-folded t)
4849 ("overview" org-startup-folded t)
4850 ("nofold" org-startup-folded nil)
4851 ("showall" org-startup-folded nil)
4852 ("showeverything" org-startup-folded showeverything)
4853 ("content" org-startup-folded content)
4854 ("indent" org-startup-indented t)
4855 ("noindent" org-startup-indented nil)
4856 ("hidestars" org-hide-leading-stars t)
4857 ("showstars" org-hide-leading-stars nil)
4858 ("odd" org-odd-levels-only t)
4859 ("oddeven" org-odd-levels-only nil)
4860 ("align" org-startup-align-all-tables t)
4861 ("noalign" org-startup-align-all-tables nil)
4862 ("inlineimages" org-startup-with-inline-images t)
4863 ("noinlineimages" org-startup-with-inline-images nil)
4864 ("latexpreview" org-startup-with-latex-preview t)
4865 ("nolatexpreview" org-startup-with-latex-preview nil)
4866 ("customtime" org-display-custom-times t)
4867 ("logdone" org-log-done time)
4868 ("lognotedone" org-log-done note)
4869 ("nologdone" org-log-done nil)
4870 ("lognoteclock-out" org-log-note-clock-out t)
4871 ("nolognoteclock-out" org-log-note-clock-out nil)
4872 ("logrepeat" org-log-repeat state)
4873 ("lognoterepeat" org-log-repeat note)
4874 ("logdrawer" org-log-into-drawer t)
4875 ("nologdrawer" org-log-into-drawer nil)
4876 ("logstatesreversed" org-log-states-order-reversed t)
4877 ("nologstatesreversed" org-log-states-order-reversed nil)
4878 ("nologrepeat" org-log-repeat nil)
4879 ("logreschedule" org-log-reschedule time)
4880 ("lognotereschedule" org-log-reschedule note)
4881 ("nologreschedule" org-log-reschedule nil)
4882 ("logredeadline" org-log-redeadline time)
4883 ("lognoteredeadline" org-log-redeadline note)
4884 ("nologredeadline" org-log-redeadline nil)
4885 ("logrefile" org-log-refile time)
4886 ("lognoterefile" org-log-refile note)
4887 ("nologrefile" org-log-refile nil)
4888 ("fninline" org-footnote-define-inline t)
4889 ("nofninline" org-footnote-define-inline nil)
4890 ("fnlocal" org-footnote-section nil)
4891 ("fnauto" org-footnote-auto-label t)
4892 ("fnprompt" org-footnote-auto-label nil)
4893 ("fnconfirm" org-footnote-auto-label confirm)
4894 ("fnplain" org-footnote-auto-label plain)
4895 ("fnadjust" org-footnote-auto-adjust t)
4896 ("nofnadjust" org-footnote-auto-adjust nil)
4897 ("constcgs" constants-unit-system cgs)
4898 ("constSI" constants-unit-system SI)
4899 ("noptag" org-tag-persistent-alist nil)
4900 ("hideblocks" org-hide-block-startup t)
4901 ("nohideblocks" org-hide-block-startup nil)
4902 ("beamer" org-startup-with-beamer-mode t)
4903 ("entitiespretty" org-pretty-entities t)
4904 ("entitiesplain" org-pretty-entities nil))
4905 "Variable associated with STARTUP options for org-mode.
4906 Each element is a list of three items: the startup options (as written
4907 in the #+STARTUP line), the corresponding variable, and the value to set
4908 this variable to if the option is found. An optional forth element PUSH
4909 means to push this value onto the list in the variable.")
4911 (defcustom org-group-tags t
4912 "When non-nil (the default), use group tags.
4913 This can be turned on/off through `org-toggle-tags-groups'."
4914 :group 'org-tags
4915 :group 'org-startup
4916 :type 'boolean)
4918 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4920 (defun org-toggle-tags-groups ()
4921 "Toggle support for group tags.
4922 Support for group tags is controlled by the option
4923 `org-group-tags', which is non-nil by default."
4924 (interactive)
4925 (setq org-group-tags (not org-group-tags))
4926 (cond ((and (derived-mode-p 'org-agenda-mode)
4927 org-group-tags)
4928 (org-agenda-redo))
4929 ((derived-mode-p 'org-mode)
4930 (let ((org-inhibit-startup t)) (org-mode))))
4931 (message "Groups tags support has been turned %s"
4932 (if org-group-tags "on" "off")))
4934 (defun org-set-regexps-and-options (&optional tags-only)
4935 "Precompute regular expressions used in the current buffer.
4936 When optional argument TAGS-ONLY is non-nil, only compute tags
4937 related expressions."
4938 (when (derived-mode-p 'org-mode)
4939 (let ((alist (org--setup-collect-keywords
4940 (org-make-options-regexp
4941 (append '("FILETAGS" "TAGS" "SETUPFILE")
4942 (and (not tags-only)
4943 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4944 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4945 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4946 ;; Startup options. Get this early since it does change
4947 ;; behavior for other options (e.g., tags).
4948 (let ((startup (cdr (assq 'startup alist))))
4949 (dolist (option startup)
4950 (let ((entry (assoc-string option org-startup-options t)))
4951 (when entry
4952 (let ((var (nth 1 entry))
4953 (val (nth 2 entry)))
4954 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4955 (unless (listp (symbol-value var))
4956 (set (make-local-variable var) nil))
4957 (add-to-list var val)))))))
4958 (setq-local org-file-tags
4959 (mapcar #'org-add-prop-inherited
4960 (cdr (assq 'filetags alist))))
4961 (setq org-current-tag-alist
4962 (append org-tag-persistent-alist
4963 (let ((tags (cdr (assq 'tags alist))))
4964 (if tags (org-tag-string-to-alist tags)
4965 org-tag-alist))))
4966 (setq org-tag-groups-alist
4967 (org-tag-alist-to-groups org-current-tag-alist))
4968 (unless tags-only
4969 ;; File properties.
4970 (setq-local org-file-properties (cdr (assq 'property alist)))
4971 ;; Archive location.
4972 (let ((archive (cdr (assq 'archive alist))))
4973 (when archive (setq-local org-archive-location archive)))
4974 ;; Category.
4975 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4976 (when cat
4977 (setq-local org-category (intern cat))
4978 (setq-local org-file-properties
4979 (org--update-property-plist
4980 "CATEGORY" cat org-file-properties))))
4981 ;; Columns.
4982 (let ((column (cdr (assq 'columns alist))))
4983 (when column (setq-local org-columns-default-format column)))
4984 ;; Constants.
4985 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4986 ;; Link abbreviations.
4987 (let ((links (cdr (assq 'link alist))))
4988 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4989 ;; Priorities.
4990 (let ((priorities (cdr (assq 'priorities alist))))
4991 (when priorities
4992 (setq-local org-highest-priority (nth 0 priorities))
4993 (setq-local org-lowest-priority (nth 1 priorities))
4994 (setq-local org-default-priority (nth 2 priorities))))
4995 ;; Scripts.
4996 (let ((scripts (assq 'scripts alist)))
4997 (when scripts
4998 (setq-local org-use-sub-superscripts (cdr scripts))))
4999 ;; TODO keywords.
5000 (setq-local org-todo-kwd-alist nil)
5001 (setq-local org-todo-key-alist nil)
5002 (setq-local org-todo-key-trigger nil)
5003 (setq-local org-todo-keywords-1 nil)
5004 (setq-local org-done-keywords nil)
5005 (setq-local org-todo-heads nil)
5006 (setq-local org-todo-sets nil)
5007 (setq-local org-todo-log-states nil)
5008 (let ((todo-sequences
5009 (or (nreverse (cdr (assq 'todo alist)))
5010 (let ((d (default-value 'org-todo-keywords)))
5011 (if (not (stringp (car d))) d
5012 ;; XXX: Backward compatibility code.
5013 (list (cons org-todo-interpretation d)))))))
5014 (dolist (sequence todo-sequences)
5015 (let* ((sequence (or (run-hook-with-args-until-success
5016 'org-todo-setup-filter-hook sequence)
5017 sequence))
5018 (sequence-type (car sequence))
5019 (keywords (cdr sequence))
5020 (sep (member "|" keywords))
5021 names alist)
5022 (dolist (k (remove "|" keywords))
5023 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5025 (error "Invalid TODO keyword %s" k))
5026 (let ((name (match-string 1 k))
5027 (key (match-string 2 k))
5028 (log (org-extract-log-state-settings k)))
5029 (push name names)
5030 (push (cons name (and key (string-to-char key))) alist)
5031 (when log (push log org-todo-log-states))))
5032 (let* ((names (nreverse names))
5033 (done (if sep (org-remove-keyword-keys (cdr sep))
5034 (last names)))
5035 (head (car names))
5036 (tail (list sequence-type head (car done) (org-last done))))
5037 (add-to-list 'org-todo-heads head 'append)
5038 (push names org-todo-sets)
5039 (setq org-done-keywords (append org-done-keywords done nil))
5040 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5041 (setq org-todo-key-alist
5042 (append org-todo-key-alist
5043 (and alist
5044 (append '((:startgroup))
5045 (nreverse alist)
5046 '((:endgroup))))))
5047 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5048 (setq org-todo-sets (nreverse org-todo-sets)
5049 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5050 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5051 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5052 ;; Compute the regular expressions and other local variables.
5053 ;; Using `org-outline-regexp-bol' would complicate them much,
5054 ;; because of the fixed white space at the end of that string.
5055 (unless org-done-keywords
5056 (setq org-done-keywords
5057 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5058 (setq org-not-done-keywords
5059 (org-delete-all org-done-keywords
5060 (copy-sequence org-todo-keywords-1))
5061 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5062 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5063 org-not-done-heading-regexp
5064 (format org-heading-keyword-regexp-format org-not-done-regexp)
5065 org-todo-line-regexp
5066 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5067 org-complex-heading-regexp
5068 (concat "^\\(\\*+\\)"
5069 "\\(?: +" org-todo-regexp "\\)?"
5070 "\\(?: +\\(\\[#.\\]\\)\\)?"
5071 "\\(?: +\\(.*?\\)\\)??"
5072 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5073 "[ \t]*$")
5074 org-complex-heading-regexp-format
5075 (concat "^\\(\\*+\\)"
5076 "\\(?: +" org-todo-regexp "\\)?"
5077 "\\(?: +\\(\\[#.\\]\\)\\)?"
5078 "\\(?: +"
5079 ;; Stats cookies can be stuck to body.
5080 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5081 "\\(%s\\)"
5082 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5083 "\\)"
5084 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5085 "[ \t]*$")
5086 org-todo-line-tags-regexp
5087 (concat "^\\(\\*+\\)"
5088 "\\(?: +" org-todo-regexp "\\)?"
5089 "\\(?: +\\(.*?\\)\\)??"
5090 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5091 "[ \t]*$"))
5092 (org-compute-latex-and-related-regexp)))))
5094 (defun org--setup-collect-keywords (regexp &optional files alist)
5095 "Return setup keywords values as an alist.
5097 REGEXP matches a subset of setup keywords. FILES is a list of
5098 file names already visited. It is used to avoid circular setup
5099 files. ALIST, when non-nil, is the alist computed so far.
5101 Return value contains the following keys: `archive', `category',
5102 `columns', `constants', `filetags', `link', `priorities',
5103 `property', `scripts', `startup', `tags' and `todo'."
5104 (org-with-wide-buffer
5105 (goto-char (point-min))
5106 (let ((case-fold-search t))
5107 (while (re-search-forward regexp nil t)
5108 (let ((element (org-element-at-point)))
5109 (when (eq (org-element-type element) 'keyword)
5110 (let ((key (org-element-property :key element))
5111 (value (org-element-property :value element)))
5112 (cond
5113 ((equal key "ARCHIVE")
5114 (when (org-string-nw-p value)
5115 (push (cons 'archive value) alist)))
5116 ((equal key "CATEGORY") (push (cons 'category value) alist))
5117 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5118 ((equal key "CONSTANTS")
5119 (let* ((constants (assq 'constants alist))
5120 (store (cdr constants)))
5121 (dolist (pair (org-split-string value))
5122 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5123 pair)
5124 (let* ((name (match-string 1 pair))
5125 (value (match-string 2 pair))
5126 (old (assoc name store)))
5127 (if old (setcdr old value)
5128 (push (cons name value) store)))))
5129 (if constants (setcdr constants store)
5130 (push (cons 'constants store) alist))))
5131 ((equal key "FILETAGS")
5132 (when (org-string-nw-p value)
5133 (let ((old (assq 'filetags alist))
5134 (new (apply #'nconc
5135 (mapcar (lambda (x) (org-split-string x ":"))
5136 (org-split-string value)))))
5137 (if old (setcdr old (append new (cdr old)))
5138 (push (cons 'filetags new) alist)))))
5139 ((equal key "LINK")
5140 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5141 (let ((links (assq 'link alist))
5142 (pair (cons (match-string-no-properties 1 value)
5143 (match-string-no-properties 2 value))))
5144 (if links (push pair (cdr links))
5145 (push (list 'link pair) alist)))))
5146 ((equal key "OPTIONS")
5147 (when (and (org-string-nw-p value)
5148 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5149 (push (cons 'scripts (read (match-string 1 value))) alist)))
5150 ((equal key "PRIORITIES")
5151 (push (cons 'priorities
5152 (let ((prio (org-split-string value)))
5153 (if (< (length prio) 3) '(?A ?C ?B)
5154 (mapcar #'string-to-char prio))))
5155 alist))
5156 ((equal key "PROPERTY")
5157 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5158 (let* ((property (assq 'property alist))
5159 (value (org--update-property-plist
5160 (match-string-no-properties 1 value)
5161 (match-string-no-properties 2 value)
5162 (cdr property))))
5163 (if property (setcdr property value)
5164 (push (cons 'property value) alist)))))
5165 ((equal key "STARTUP")
5166 (let ((startup (assq 'startup alist)))
5167 (if startup
5168 (setcdr startup
5169 (append (cdr startup) (org-split-string value)))
5170 (push (cons 'startup (org-split-string value)) alist))))
5171 ((equal key "TAGS")
5172 (let ((tag-cell (assq 'tags alist)))
5173 (if tag-cell
5174 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5175 (push (cons 'tags value) alist))))
5176 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5177 (let ((todo (assq 'todo alist))
5178 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5179 (org-split-string value))))
5180 (if todo (push value (cdr todo))
5181 (push (list 'todo value) alist))))
5182 ((equal key "SETUPFILE")
5183 (unless buffer-read-only ; Do not check in Gnus messages.
5184 (let ((f (and (org-string-nw-p value)
5185 (expand-file-name
5186 (org-unbracket-string "\"" "\"" value)))))
5187 (when (and f (file-readable-p f) (not (member f files)))
5188 (with-temp-buffer
5189 (setq default-directory (file-name-directory f))
5190 (insert-file-contents f)
5191 (setq alist
5192 ;; Fake Org mode to benefit from cache
5193 ;; without recurring needlessly.
5194 (let ((major-mode 'org-mode))
5195 (org--setup-collect-keywords
5196 regexp (cons f files) alist)))))))))))))))
5197 alist)
5199 (defun org-tag-string-to-alist (s)
5200 "Return tag alist associated to string S.
5201 S is a value for TAGS keyword or produced with
5202 `org-tag-alist-to-string'. Return value is an alist suitable for
5203 `org-tag-alist' or `org-tag-persistent-alist'."
5204 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5205 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5206 "\\|{.+?}\\)" ; regular expression
5207 "\\(?:(\\(.\\))\\)?\\'"))
5208 alist group-flag)
5209 (dolist (tokens lines (cdr (nreverse alist)))
5210 (push '(:newline) alist)
5211 (while tokens
5212 (let ((token (pop tokens)))
5213 (pcase token
5214 ("{"
5215 (push '(:startgroup) alist)
5216 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5217 ("}"
5218 (push '(:endgroup) alist)
5219 (setq group-flag nil))
5220 ("["
5221 (push '(:startgrouptag) alist)
5222 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5223 ("]"
5224 (push '(:endgrouptag) alist)
5225 (setq group-flag nil))
5226 (":"
5227 (push '(:grouptags) alist))
5228 ((guard (string-match tag-re token))
5229 (let ((tag (match-string 1 token))
5230 (key (and (match-beginning 2)
5231 (string-to-char (match-string 2 token)))))
5232 ;; Push all tags in groups, no matter if they already
5233 ;; appear somewhere else in the list.
5234 (when (or group-flag (not (assoc tag alist)))
5235 (push (cons tag key) alist))))))))))
5237 (defun org-tag-alist-to-string (alist &optional skip-key)
5238 "Return tag string associated to ALIST.
5240 ALIST is an alist, as defined in `org-tag-alist' or
5241 `org-tag-persistent-alist', or produced with
5242 `org-tag-string-to-alist'.
5244 Return value is a string suitable as a value for \"TAGS\"
5245 keyword.
5247 When optional argument SKIP-KEY is non-nil, skip selection keys
5248 next to tags."
5249 (mapconcat (lambda (token)
5250 (pcase token
5251 (`(:startgroup) "{")
5252 (`(:endgroup) "}")
5253 (`(:startgrouptag) "[")
5254 (`(:endgrouptag) "]")
5255 (`(:grouptags) ":")
5256 (`(:newline) "\\n")
5257 ((and
5258 (guard (not skip-key))
5259 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5260 (format "%s(%c)" tag key))
5261 (`(,(and tag (pred stringp)) . ,_) tag)
5262 (_ (user-error "Invalid tag token: %S" token))))
5263 alist
5264 " "))
5266 (defun org-tag-alist-to-groups (alist)
5267 "Return group alist from tag ALIST.
5268 ALIST is an alist, as defined in `org-tag-alist' or
5269 `org-tag-persistent-alist', or produced with
5270 `org-tag-string-to-alist'. Return value is an alist following
5271 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5272 a string, summarizing TAGS, as a list of strings."
5273 (let (groups group-status current-group)
5274 (dolist (token alist (nreverse groups))
5275 (pcase token
5276 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5277 (`(,(or :endgroup :endgrouptag))
5278 (when (eq group-status 'append)
5279 (push (nreverse current-group) groups))
5280 (setq group-status nil))
5281 (`(:grouptags) (setq group-status 'append))
5282 ((and `(,tag . ,_) (guard group-status))
5283 (if (eq group-status 'append) (push tag current-group)
5284 (setq current-group (list tag))))
5285 (_ nil)))))
5287 (defvar org--file-cache (make-hash-table :test #'equal)
5288 "Hash table to store contents of files referenced via a URL.
5289 This is the cache of file URLs read using `org-file-contents'.")
5291 (defun org-reset-file-cache ()
5292 "Reset the cache of files downloaded by `org-file-contents'."
5293 (clrhash org--file-cache))
5295 (defun org-file-url-p (file)
5296 "Non-nil if FILE is a URL."
5297 (require 'ffap)
5298 (string-match-p ffap-url-regexp file))
5300 (defun org-file-contents (file &optional noerror nocache)
5301 "Return the contents of FILE, as a string.
5303 FILE can be a file name or URL.
5305 If FILE is a URL, download the contents. If the URL contents are
5306 already cached in the `org--file-cache' hash table, the download step
5307 is skipped.
5309 If NOERROR is non-nil, ignore the error when unable to read the FILE
5310 from file or URL.
5312 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5313 is available. This option applies only if FILE is a URL."
5314 (let* ((is-url (org-file-url-p file))
5315 (cache (and is-url
5316 (not nocache)
5317 (gethash file org--file-cache))))
5318 (cond
5319 (cache)
5320 (is-url
5321 (with-current-buffer (url-retrieve-synchronously file)
5322 (goto-char (point-min))
5323 ;; Move point to after the url-retrieve header.
5324 (search-forward "\n\n" nil :move)
5325 ;; Search for the success code only in the url-retrieve header.
5326 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5327 ;; Update the cache `org--file-cache' and return contents.
5328 (puthash file
5329 (buffer-substring-no-properties (point) (point-max))
5330 org--file-cache)
5331 (funcall (if noerror #'message #'user-error)
5332 "Unable to fetch file from %S"
5333 file))))
5335 (with-temp-buffer
5336 (condition-case err
5337 (progn
5338 (insert-file-contents file)
5339 (buffer-string))
5340 (file-error
5341 (funcall (if noerror #'message #'user-error)
5342 (error-message-string err)))))))))
5344 (defun org-extract-log-state-settings (x)
5345 "Extract the log state setting from a TODO keyword string.
5346 This will extract info from a string like \"WAIT(w@/!)\"."
5347 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5348 (let ((kw (match-string 1 x))
5349 (log1 (and (match-end 3) (match-string 3 x)))
5350 (log2 (and (match-end 4) (match-string 4 x))))
5351 (and (or log1 log2)
5352 (list kw
5353 (and log1 (if (equal log1 "!") 'time 'note))
5354 (and log2 (if (equal log2 "!") 'time 'note)))))))
5356 (defun org-remove-keyword-keys (list)
5357 "Remove a pair of parenthesis at the end of each string in LIST."
5358 (mapcar (lambda (x)
5359 (if (string-match "(.*)$" x)
5360 (substring x 0 (match-beginning 0))
5362 list))
5364 (defun org-assign-fast-keys (alist)
5365 "Assign fast keys to a keyword-key alist.
5366 Respect keys that are already there."
5367 (let (new e (alt ?0))
5368 (while (setq e (pop alist))
5369 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5370 (cdr e)) ;; Key already assigned.
5371 (push e new)
5372 (let ((clist (string-to-list (downcase (car e))))
5373 (used (append new alist)))
5374 (when (= (car clist) ?@)
5375 (pop clist))
5376 (while (and clist (rassoc (car clist) used))
5377 (pop clist))
5378 (unless clist
5379 (while (rassoc alt used)
5380 (cl-incf alt)))
5381 (push (cons (car e) (or (car clist) alt)) new))))
5382 (nreverse new)))
5384 ;;; Some variables used in various places
5386 (defvar org-window-configuration nil
5387 "Used in various places to store a window configuration.")
5388 (defvar org-selected-window nil
5389 "Used in various places to store a window configuration.")
5390 (defvar org-finish-function nil
5391 "Function to be called when `C-c C-c' is used.
5392 This is for getting out of special buffers like capture.")
5393 (defvar org-last-state)
5395 ;; Defined somewhere in this file, but used before definition.
5396 (defvar org-entities) ;; defined in org-entities.el
5397 (defvar org-struct-menu)
5398 (defvar org-org-menu)
5399 (defvar org-tbl-menu)
5401 ;;;; Define the Org mode
5403 ;; We use a before-change function to check if a table might need
5404 ;; an update.
5405 (defvar org-table-may-need-update t
5406 "Indicates that a table might need an update.
5407 This variable is set by `org-before-change-function'.
5408 `org-table-align' sets it back to nil.")
5409 (defun org-before-change-function (_beg _end)
5410 "Every change indicates that a table might need an update."
5411 (setq org-table-may-need-update t))
5412 (defvar org-mode-map)
5413 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5414 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5415 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5416 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5417 (defvar org-table-buffer-is-an nil)
5419 (defvar bidi-paragraph-direction)
5420 (defvar buffer-face-mode-face)
5422 (require 'outline)
5424 ;; Other stuff we need.
5425 (require 'time-date)
5426 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5427 (require 'easymenu)
5428 (autoload 'easy-menu-add "easymenu")
5429 (require 'overlay)
5431 ;; (require 'org-macs) moved higher up in the file before it is first used
5432 (require 'org-entities)
5433 ;; (require 'org-compat) moved higher up in the file before it is first used
5434 (require 'org-faces)
5435 (require 'org-list)
5436 (require 'org-pcomplete)
5437 (require 'org-src)
5438 (require 'org-footnote)
5439 (require 'org-macro)
5441 ;; babel
5442 (require 'ob)
5444 ;;;###autoload
5445 (define-derived-mode org-mode outline-mode "Org"
5446 "Outline-based notes management and organizer, alias
5447 \"Carsten's outline-mode for keeping track of everything.\"
5449 Org mode develops organizational tasks around a NOTES file which
5450 contains information about projects as plain text. Org mode is
5451 implemented on top of Outline mode, which is ideal to keep the content
5452 of large files well structured. It supports ToDo items, deadlines and
5453 time stamps, which magically appear in the diary listing of the Emacs
5454 calendar. Tables are easily created with a built-in table editor.
5455 Plain text URL-like links connect to websites, emails (VM), Usenet
5456 messages (Gnus), BBDB entries, and any files related to the project.
5457 For printing and sharing of notes, an Org file (or a part of it)
5458 can be exported as a structured ASCII or HTML file.
5460 The following commands are available:
5462 \\{org-mode-map}"
5464 ;; Get rid of Outline menus, they are not needed
5465 ;; Need to do this here because define-derived-mode sets up
5466 ;; the keymap so late. Still, it is a waste to call this each time
5467 ;; we switch another buffer into Org mode.
5468 (define-key org-mode-map [menu-bar headings] 'undefined)
5469 (define-key org-mode-map [menu-bar hide] 'undefined)
5470 (define-key org-mode-map [menu-bar show] 'undefined)
5472 (org-load-modules-maybe)
5473 (org-install-agenda-files-menu)
5474 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5475 (add-to-invisibility-spec '(org-cwidth))
5476 (add-to-invisibility-spec '(org-hide-block . t))
5477 (setq-local outline-regexp org-outline-regexp)
5478 (setq-local outline-level 'org-outline-level)
5479 (setq bidi-paragraph-direction 'left-to-right)
5480 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
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 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. Do not match table hlines.
5786 (and
5787 (not (looking-at-p org-outline-regexp-bol))
5788 (not (and (equal marker "+")
5789 (org-match-line
5790 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5791 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5792 (not (string-match-p
5793 (concat org-outline-regexp-bol "\\'")
5794 (match-string 0)))))
5795 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5796 (font-lock-prepend-text-property
5797 (match-beginning 2) (match-end 2) 'face face)
5798 (when verbatim?
5799 (org-remove-flyspell-overlays-in
5800 (match-beginning 0) (match-end 0)))
5801 (add-text-properties (match-beginning 2) (match-end 2)
5802 '(font-lock-multiline t org-emphasis t))
5803 (when org-hide-emphasis-markers
5804 (add-text-properties (match-end 4) (match-beginning 5)
5805 '(invisible org-link))
5806 (add-text-properties (match-beginning 3) (match-end 3)
5807 '(invisible org-link)))
5808 (throw :exit t))))))))
5810 (defun org-emphasize (&optional char)
5811 "Insert or change an emphasis, i.e. a font like bold or italic.
5812 If there is an active region, change that region to a new emphasis.
5813 If there is no region, just insert the marker characters and position
5814 the cursor between them.
5815 CHAR should be the marker character. If it is a space, it means to
5816 remove the emphasis of the selected region.
5817 If CHAR is not given (for example in an interactive call) it will be
5818 prompted for."
5819 (interactive)
5820 (let ((erc org-emphasis-regexp-components)
5821 (string "") beg end move s)
5822 (if (org-region-active-p)
5823 (setq beg (region-beginning)
5824 end (region-end)
5825 string (buffer-substring beg end))
5826 (setq move t))
5828 (unless char
5829 (message "Emphasis marker or tag: [%s]"
5830 (mapconcat #'car org-emphasis-alist ""))
5831 (setq char (read-char-exclusive)))
5832 (if (equal char ?\s)
5833 (setq s ""
5834 move nil)
5835 (unless (assoc (char-to-string char) org-emphasis-alist)
5836 (user-error "No such emphasis marker: \"%c\"" char))
5837 (setq s (char-to-string char)))
5838 (while (and (> (length string) 1)
5839 (equal (substring string 0 1) (substring string -1))
5840 (assoc (substring string 0 1) org-emphasis-alist))
5841 (setq string (substring string 1 -1)))
5842 (setq string (concat s string s))
5843 (when beg (delete-region beg end))
5844 (unless (or (bolp)
5845 (string-match (concat "[" (nth 0 erc) "\n]")
5846 (char-to-string (char-before (point)))))
5847 (insert " "))
5848 (unless (or (eobp)
5849 (string-match (concat "[" (nth 1 erc) "\n]")
5850 (char-to-string (char-after (point)))))
5851 (insert " ") (backward-char 1))
5852 (insert string)
5853 (and move (backward-char 1))))
5855 (defconst org-nonsticky-props
5856 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5858 (defsubst org-rear-nonsticky-at (pos)
5859 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5861 (defun org-activate-links (limit)
5862 "Add link properties to links.
5863 This includes angle, plain, and bracket links."
5864 (catch :exit
5865 (while (re-search-forward org-any-link-re limit t)
5866 (let* ((start (match-beginning 0))
5867 (end (match-end 0))
5868 (style (cond ((eq ?< (char-after start)) 'angle)
5869 ((eq ?\[ (char-after (1+ start))) 'bracket)
5870 (t 'plain))))
5871 (when (and (memq style org-highlight-links)
5872 ;; Do not confuse plain links with tags.
5873 (not (and (eq style 'plain)
5874 (let ((face (get-text-property
5875 (max (1- start) (point-min)) 'face)))
5876 (if (consp face) (memq 'org-tag face)
5877 (eq 'org-tag face))))))
5878 (let* ((link-object (save-excursion
5879 (goto-char start)
5880 (save-match-data (org-element-link-parser))))
5881 (link (org-element-property :raw-link link-object))
5882 (type (org-element-property :type link-object))
5883 (path (org-element-property :path link-object))
5884 (properties ;for link's visible part
5885 (list
5886 'face (pcase (org-link-get-parameter type :face)
5887 ((and (pred functionp) face) (funcall face path))
5888 ((and (pred facep) face) face)
5889 ((and (pred consp) face) face) ;anonymous
5890 (_ 'org-link))
5891 'mouse-face (or (org-link-get-parameter type :mouse-face)
5892 'highlight)
5893 'keymap (or (org-link-get-parameter type :keymap)
5894 org-mouse-map)
5895 'help-echo (pcase (org-link-get-parameter type :help-echo)
5896 ((and (pred stringp) echo) echo)
5897 ((and (pred functionp) echo) echo)
5898 (_ (concat "LINK: " link)))
5899 'htmlize-link (pcase (org-link-get-parameter type
5900 :htmlize-link)
5901 ((and (pred functionp) f) (funcall f))
5902 (_ `(:uri ,link)))
5903 'font-lock-multiline t)))
5904 (org-remove-flyspell-overlays-in start end)
5905 (org-rear-nonsticky-at end)
5906 (if (not (eq 'bracket style))
5907 (add-text-properties start end properties)
5908 ;; Handle invisible parts in bracket links.
5909 (remove-text-properties start end '(invisible nil))
5910 (let ((hidden
5911 (append `(invisible
5912 ,(or (org-link-get-parameter type :display)
5913 'org-link))
5914 properties))
5915 (visible-start (or (match-beginning 4) (match-beginning 2)))
5916 (visible-end (or (match-end 4) (match-end 2))))
5917 (add-text-properties start visible-start hidden)
5918 (add-text-properties visible-start visible-end properties)
5919 (add-text-properties visible-end end hidden)
5920 (org-rear-nonsticky-at visible-start)
5921 (org-rear-nonsticky-at visible-end)))
5922 (let ((f (org-link-get-parameter type :activate-func)))
5923 (when (functionp f)
5924 (funcall f start end path (eq style 'bracket))))
5925 (throw :exit t))))) ;signal success
5926 nil))
5928 (defun org-activate-code (limit)
5929 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5930 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5931 (remove-text-properties (match-beginning 0) (match-end 0)
5932 '(display t invisible t intangible t))
5935 (defcustom org-src-fontify-natively t
5936 "When non-nil, fontify code in code blocks.
5937 See also the `org-block' face."
5938 :type 'boolean
5939 :version "24.4"
5940 :package-version '(Org . "8.3")
5941 :group 'org-appearance
5942 :group 'org-babel)
5944 (defcustom org-allow-promoting-top-level-subtree nil
5945 "When non-nil, allow promoting a top level subtree.
5946 The leading star of the top level headline will be replaced
5947 by a #."
5948 :type 'boolean
5949 :version "24.1"
5950 :group 'org-appearance)
5952 (defun org-fontify-meta-lines-and-blocks (limit)
5953 (condition-case nil
5954 (org-fontify-meta-lines-and-blocks-1 limit)
5955 (error (message "org-mode fontification error in %S at %d"
5956 (current-buffer)
5957 (line-number-at-pos)))))
5959 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5960 "Fontify #+ lines and blocks."
5961 (let ((case-fold-search t))
5962 (when (re-search-forward
5963 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5964 limit t)
5965 (let ((beg (match-beginning 0))
5966 (block-start (match-end 0))
5967 (block-end nil)
5968 (lang (match-string 7))
5969 (beg1 (line-beginning-position 2))
5970 (dc1 (downcase (match-string 2)))
5971 (dc3 (downcase (match-string 3)))
5972 end end1 quoting block-type)
5973 (cond
5974 ((and (match-end 4) (equal dc3 "+begin"))
5975 ;; Truly a block
5976 (setq block-type (downcase (match-string 5))
5977 quoting (member block-type org-protecting-blocks))
5978 (when (re-search-forward
5979 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5980 nil t) ;; on purpose, we look further than LIMIT
5981 (setq end (min (point-max) (match-end 0))
5982 end1 (min (point-max) (1- (match-beginning 0))))
5983 (setq block-end (match-beginning 0))
5984 (when quoting
5985 (org-remove-flyspell-overlays-in beg1 end1)
5986 (remove-text-properties beg end
5987 '(display t invisible t intangible t)))
5988 (add-text-properties
5989 beg end '(font-lock-fontified t font-lock-multiline t))
5990 (add-text-properties beg beg1 '(face org-meta-line))
5991 (org-remove-flyspell-overlays-in beg beg1)
5992 (add-text-properties ; For end_src
5993 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5994 (org-remove-flyspell-overlays-in end1 end)
5995 (cond
5996 ((and lang (not (string= lang "")) org-src-fontify-natively)
5997 (org-src-font-lock-fontify-block lang block-start block-end)
5998 (add-text-properties beg1 block-end '(src-block t)))
5999 (quoting
6000 (add-text-properties beg1 (min (point-max) (1+ end1))
6001 (list 'face
6002 (list :inherit
6003 (let ((face-name
6004 (intern (format "org-block-%s" lang))))
6005 (append (and (facep face-name) (list face-name))
6006 '(org-block))))))) ; end of source block
6007 ((not org-fontify-quote-and-verse-blocks))
6008 ((string= block-type "quote")
6009 (add-face-text-property
6010 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6011 ((string= block-type "verse")
6012 (add-face-text-property
6013 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6014 (add-text-properties beg beg1 '(face org-block-begin-line))
6015 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6016 '(face org-block-end-line))
6018 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6019 (org-remove-flyspell-overlays-in
6020 (match-beginning 0)
6021 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6022 (add-text-properties
6023 beg (match-end 3)
6024 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6025 '(font-lock-fontified t invisible t)
6026 '(font-lock-fontified t face org-document-info-keyword)))
6027 (add-text-properties
6028 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6029 (if (string-equal dc1 "+title:")
6030 '(font-lock-fontified t face org-document-title)
6031 '(font-lock-fontified t face org-document-info))))
6032 ((string-prefix-p "+caption" dc1)
6033 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6034 (remove-text-properties (match-beginning 0) (match-end 0)
6035 '(display t invisible t intangible t))
6036 ;; Handle short captions.
6037 (save-excursion
6038 (beginning-of-line)
6039 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6040 (add-text-properties (line-beginning-position) (match-end 1)
6041 '(font-lock-fontified t face org-meta-line))
6042 (add-text-properties (match-end 0) (line-end-position)
6043 '(font-lock-fontified t face org-block))
6045 ((member dc3 '(" " ""))
6046 (org-remove-flyspell-overlays-in beg (match-end 0))
6047 (add-text-properties
6048 beg (match-end 0)
6049 '(font-lock-fontified t face font-lock-comment-face)))
6050 (t ;; just any other in-buffer setting, but not indented
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6052 (remove-text-properties (match-beginning 0) (match-end 0)
6053 '(display t invisible t intangible t))
6054 (add-text-properties beg (match-end 0)
6055 '(font-lock-fontified t face org-meta-line))
6056 t))))))
6058 (defun org-fontify-drawers (limit)
6059 "Fontify drawers."
6060 (when (re-search-forward org-drawer-regexp limit t)
6061 (add-text-properties
6062 (match-beginning 0) (match-end 0)
6063 '(font-lock-fontified t face org-special-keyword))
6064 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6067 (defun org-fontify-macros (limit)
6068 "Fontify macros."
6069 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6070 (add-text-properties
6071 (match-beginning 0) (match-end 0)
6072 '(font-lock-fontified t face org-macro))
6073 (when org-hide-macro-markers
6074 (add-text-properties (match-end 2) (match-beginning 2)
6075 '(invisible t))
6076 (add-text-properties (match-beginning 1) (match-end 1)
6077 '(invisible t)))
6078 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6081 (defun org-activate-footnote-links (limit)
6082 "Add text properties for footnotes."
6083 (let ((fn (org-footnote-next-reference-or-definition limit)))
6084 (when fn
6085 (let* ((beg (nth 1 fn))
6086 (end (nth 2 fn))
6087 (label (car fn))
6088 (referencep (/= (line-beginning-position) beg)))
6089 (when (and referencep (nth 3 fn))
6090 (save-excursion
6091 (goto-char beg)
6092 (search-forward (or label "fn:"))
6093 (org-remove-flyspell-overlays-in beg (match-end 0))))
6094 (add-text-properties beg end
6095 (list 'mouse-face 'highlight
6096 'keymap org-mouse-map
6097 'help-echo
6098 (if referencep "Footnote reference"
6099 "Footnote definition")
6100 'font-lock-fontified t
6101 'font-lock-multiline t
6102 'face 'org-footnote))))))
6104 (defun org-activate-dates (limit)
6105 "Add text properties for dates."
6106 (when (and (re-search-forward org-tsr-regexp-both limit t)
6107 (not (equal (char-before (match-beginning 0)) 91)))
6108 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6109 (add-text-properties (match-beginning 0) (match-end 0)
6110 (list 'mouse-face 'highlight
6111 'keymap org-mouse-map))
6112 (org-rear-nonsticky-at (match-end 0))
6113 (when org-display-custom-times
6114 ;; If it's a date range, activate custom time for second date.
6115 (when (match-end 3)
6116 (org-display-custom-time (match-beginning 3) (match-end 3)))
6117 (org-display-custom-time (match-beginning 1) (match-end 1)))
6120 (defvar-local org-target-link-regexp nil
6121 "Regular expression matching radio targets in plain text.")
6123 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6124 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6125 border border border))
6126 "Regular expression matching a link target.")
6128 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6129 "Regular expression matching a radio target.")
6131 (defconst org-any-target-regexp
6132 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6133 "Regular expression matching any target.")
6135 (defun org-activate-target-links (limit)
6136 "Add text properties for target matches."
6137 (when org-target-link-regexp
6138 (let ((case-fold-search t))
6139 (when (re-search-forward org-target-link-regexp limit t)
6140 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6141 (add-text-properties (match-beginning 1) (match-end 1)
6142 (list 'mouse-face 'highlight
6143 'keymap org-mouse-map
6144 'help-echo "Radio target link"
6145 'org-linked-text t))
6146 (org-rear-nonsticky-at (match-end 1))
6147 t))))
6149 (defun org-update-radio-target-regexp ()
6150 "Find all radio targets in this file and update the regular expression.
6151 Also refresh fontification if needed."
6152 (interactive)
6153 (let ((old-regexp org-target-link-regexp)
6154 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6155 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6156 (targets
6157 (org-with-wide-buffer
6158 (goto-char (point-min))
6159 (let (rtn)
6160 (while (re-search-forward org-radio-target-regexp nil t)
6161 ;; Make sure point is really within the object.
6162 (backward-char)
6163 (let ((obj (org-element-context)))
6164 (when (eq (org-element-type obj) 'radio-target)
6165 (cl-pushnew (org-element-property :value obj) rtn
6166 :test #'equal))))
6167 rtn))))
6168 (setq org-target-link-regexp
6169 (and targets
6170 (concat before-re
6171 (mapconcat
6172 (lambda (x)
6173 (replace-regexp-in-string
6174 " +" "\\s-+" (regexp-quote x) t t))
6175 targets
6176 "\\|")
6177 after-re)))
6178 (unless (equal old-regexp org-target-link-regexp)
6179 ;; Clean-up cache.
6180 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6181 ((not org-target-link-regexp) old-regexp)
6183 (concat before-re
6184 (mapconcat
6185 (lambda (re)
6186 (substring re (length before-re)
6187 (- (length after-re))))
6188 (list old-regexp org-target-link-regexp)
6189 "\\|")
6190 after-re)))))
6191 (org-with-wide-buffer
6192 (goto-char (point-min))
6193 (while (re-search-forward regexp nil t)
6194 (org-element-cache-refresh (match-beginning 1)))))
6195 ;; Re fontify buffer.
6196 (when (memq 'radio org-highlight-links)
6197 (org-restart-font-lock)))))
6199 (defun org-hide-wide-columns (limit)
6200 (let (s e)
6201 (setq s (text-property-any (point) (or limit (point-max))
6202 'org-cwidth t))
6203 (when s
6204 (setq e (next-single-property-change s 'org-cwidth))
6205 (add-text-properties s e '(invisible org-cwidth))
6206 (goto-char e)
6207 t)))
6209 (defvar org-latex-and-related-regexp nil
6210 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6212 (defun org-compute-latex-and-related-regexp ()
6213 "Compute regular expression for LaTeX, entities and sub/superscript.
6214 Result depends on variable `org-highlight-latex-and-related'."
6215 (setq-local
6216 org-latex-and-related-regexp
6217 (let* ((re-sub
6218 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6219 ((eq org-use-sub-superscripts '{})
6220 (list org-match-substring-with-braces-regexp))
6221 (org-use-sub-superscripts (list org-match-substring-regexp))))
6222 (re-latex
6223 (when (memq 'latex org-highlight-latex-and-related)
6224 (let ((matchers (plist-get org-format-latex-options :matchers)))
6225 (delq nil
6226 (mapcar (lambda (x)
6227 (and (member (car x) matchers) (nth 1 x)))
6228 org-latex-regexps)))))
6229 (re-entities
6230 (when (memq 'entities org-highlight-latex-and-related)
6231 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6232 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6234 (defun org-do-latex-and-related (limit)
6235 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6236 LIMIT bounds the search for syntax to highlight. Stop at first
6237 highlighted object, if any. Return t if some highlighting was
6238 done, nil otherwise."
6239 (when (org-string-nw-p org-latex-and-related-regexp)
6240 (catch 'found
6241 (while (re-search-forward org-latex-and-related-regexp limit t)
6242 (unless
6243 (cl-some
6244 (lambda (f)
6245 (memq f '(org-code org-verbatim underline org-special-keyword)))
6246 (save-excursion
6247 (goto-char (1+ (match-beginning 0)))
6248 (face-at-point nil t)))
6249 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6250 '(?_ ?^))
6252 0)))
6253 (font-lock-prepend-text-property
6254 (+ offset (match-beginning 0)) (match-end 0)
6255 'face 'org-latex-and-related)
6256 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6257 '(font-lock-multiline t)))
6258 (throw 'found t)))
6259 nil)))
6261 (defun org-restart-font-lock ()
6262 "Restart `font-lock-mode', to force refontification."
6263 (when (and (boundp 'font-lock-mode) font-lock-mode)
6264 (font-lock-mode -1)
6265 (font-lock-mode 1)))
6267 (defun org-activate-tags (limit)
6268 (when (re-search-forward
6269 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6270 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6271 (add-text-properties (match-beginning 1) (match-end 1)
6272 (list 'mouse-face 'highlight
6273 'keymap org-mouse-map))
6274 (org-rear-nonsticky-at (match-end 1))
6277 (defun org-outline-level ()
6278 "Compute the outline level of the heading at point.
6280 If this is called at a normal headline, the level is the number
6281 of stars. Use `org-reduced-level' to remove the effect of
6282 `org-odd-levels'. Unlike to `org-current-level', this function
6283 takes into consideration inlinetasks."
6284 (org-with-wide-buffer
6285 (end-of-line)
6286 (if (re-search-backward org-outline-regexp-bol nil t)
6287 (1- (- (match-end 0) (match-beginning 0)))
6288 0)))
6290 (defvar org-font-lock-keywords nil)
6292 (defsubst org-re-property (property &optional literal allow-null value)
6293 "Return a regexp matching a PROPERTY line.
6295 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6296 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6297 non-nil, match properties even without a value.
6299 Match group 3 is set to the value when it exists. If there is no
6300 value and ALLOW-NULL is non-nil, it is set to the empty string.
6302 With optional argument VALUE, match only property lines with
6303 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6304 unless LITERAL is non-nil."
6305 (concat
6306 "^\\(?4:[ \t]*\\)"
6307 (format "\\(?1::\\(?2:%s\\):\\)"
6308 (if literal property (regexp-quote property)))
6309 (cond (value
6310 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6311 (if literal value (regexp-quote value))))
6312 (allow-null
6313 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6315 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6317 (defconst org-property-re
6318 (org-re-property "\\S-+" 'literal t)
6319 "Regular expression matching a property line.
6320 There are four matching groups:
6321 1: :PROPKEY: including the leading and trailing colon,
6322 2: PROPKEY without the leading and trailing colon,
6323 3: PROPVAL without leading or trailing spaces,
6324 4: the indentation of the current line,
6325 5: trailing whitespace.")
6327 (defvar org-font-lock-hook nil
6328 "Functions to be called for special font lock stuff.")
6330 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6332 (defvar org-font-lock-set-keywords-hook nil
6333 "Functions that can manipulate `org-font-lock-extra-keywords'.
6334 This is called after `org-font-lock-extra-keywords' is defined, but before
6335 it is installed to be used by font lock. This can be useful if something
6336 needs to be inserted at a specific position in the font-lock sequence.")
6338 (defun org-font-lock-hook (limit)
6339 "Run `org-font-lock-hook' within LIMIT."
6340 (run-hook-with-args 'org-font-lock-hook limit))
6342 (defun org-set-font-lock-defaults ()
6343 "Set font lock defaults for the current buffer."
6344 (let* ((em org-fontify-emphasized-text)
6345 (lk org-highlight-links)
6346 (org-font-lock-extra-keywords
6347 (list
6348 ;; Call the hook
6349 '(org-font-lock-hook)
6350 ;; Headlines
6351 `(,(if org-fontify-whole-heading-line
6352 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6353 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6354 (1 (org-get-level-face 1))
6355 (2 (org-get-level-face 2))
6356 (3 (org-get-level-face 3)))
6357 ;; Table lines
6358 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6359 (1 'org-table t))
6360 ;; Table internals
6361 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6362 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6363 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6364 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6365 ;; Drawers
6366 '(org-fontify-drawers)
6367 ;; Properties
6368 (list org-property-re
6369 '(1 'org-special-keyword t)
6370 '(3 'org-property-value t))
6371 ;; Link related fontification.
6372 '(org-activate-links)
6373 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6374 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6375 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6376 (when (memq 'footnote lk) '(org-activate-footnote-links))
6377 ;; Targets.
6378 (list org-any-target-regexp '(0 'org-target t))
6379 ;; Diary sexps.
6380 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6381 ;; Macro
6382 '(org-fontify-macros)
6383 '(org-hide-wide-columns (0 nil append))
6384 ;; TODO keyword
6385 (list (format org-heading-keyword-regexp-format
6386 org-todo-regexp)
6387 '(2 (org-get-todo-face 2) t))
6388 ;; DONE
6389 (if org-fontify-done-headline
6390 (list (format org-heading-keyword-regexp-format
6391 (concat
6392 "\\(?:"
6393 (mapconcat 'regexp-quote org-done-keywords "\\|")
6394 "\\)"))
6395 '(2 'org-headline-done t))
6396 nil)
6397 ;; Priorities
6398 '(org-font-lock-add-priority-faces)
6399 ;; Tags
6400 '(org-font-lock-add-tag-faces)
6401 ;; Tags groups
6402 (when (and org-group-tags org-tag-groups-alist)
6403 (list (concat org-outline-regexp-bol ".+\\(:"
6404 (regexp-opt (mapcar 'car org-tag-groups-alist))
6405 ":\\).*$")
6406 '(1 'org-tag-group prepend)))
6407 ;; Special keywords
6408 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6409 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6410 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6411 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6412 ;; Emphasis
6413 (when em '(org-do-emphasis-faces))
6414 ;; Checkboxes
6415 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6416 1 'org-checkbox prepend)
6417 (when (cdr (assq 'checkbox org-list-automatic-rules))
6418 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6419 (0 (org-get-checkbox-statistics-face) t)))
6420 ;; Description list items
6421 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6422 1 'org-list-dt prepend)
6423 ;; ARCHIVEd headings
6424 (list (concat
6425 org-outline-regexp-bol
6426 "\\(.*:" org-archive-tag ":.*\\)")
6427 '(1 'org-archived prepend))
6428 ;; Specials
6429 '(org-do-latex-and-related)
6430 '(org-fontify-entities)
6431 '(org-raise-scripts)
6432 ;; Code
6433 '(org-activate-code (1 'org-code t))
6434 ;; COMMENT
6435 (list (format
6436 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6437 org-todo-regexp
6438 org-comment-string)
6439 '(9 'org-special-keyword t))
6440 ;; Blocks and meta lines
6441 '(org-fontify-meta-lines-and-blocks))))
6442 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6443 (run-hooks 'org-font-lock-set-keywords-hook)
6444 ;; Now set the full font-lock-keywords
6445 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6446 (setq-local font-lock-defaults
6447 '(org-font-lock-keywords t nil nil backward-paragraph))
6448 (kill-local-variable 'font-lock-keywords)
6449 nil))
6451 (defun org-toggle-pretty-entities ()
6452 "Toggle the composition display of entities as UTF8 characters."
6453 (interactive)
6454 (setq-local org-pretty-entities (not org-pretty-entities))
6455 (org-restart-font-lock)
6456 (if org-pretty-entities
6457 (message "Entities are now displayed as UTF8 characters")
6458 (save-restriction
6459 (widen)
6460 (decompose-region (point-min) (point-max))
6461 (message "Entities are now displayed as plain text"))))
6463 (defvar-local org-custom-properties-overlays nil
6464 "List of overlays used for custom properties.")
6466 (defun org-toggle-custom-properties-visibility ()
6467 "Display or hide properties in `org-custom-properties'."
6468 (interactive)
6469 (if org-custom-properties-overlays
6470 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6471 (setq org-custom-properties-overlays nil))
6472 (when org-custom-properties
6473 (org-with-wide-buffer
6474 (goto-char (point-min))
6475 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6476 (while (re-search-forward regexp nil t)
6477 (let ((end (cdr (save-match-data (org-get-property-block)))))
6478 (when (and end (< (point) end))
6479 ;; Hide first custom property in current drawer.
6480 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6481 (overlay-put o 'invisible t)
6482 (overlay-put o 'org-custom-property t)
6483 (push o org-custom-properties-overlays))
6484 ;; Hide additional custom properties in the same drawer.
6485 (while (re-search-forward regexp end t)
6486 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6487 (overlay-put o 'invisible t)
6488 (overlay-put o 'org-custom-property t)
6489 (push o org-custom-properties-overlays)))))
6490 ;; Each entry is limited to a single property drawer.
6491 (outline-next-heading)))))))
6493 (defun org-fontify-entities (limit)
6494 "Find an entity to fontify."
6495 (let (ee)
6496 (when org-pretty-entities
6497 (catch 'match
6498 ;; "\_ "-family is left out on purpose. Only the first one,
6499 ;; i.e., "\_ ", could be fontified anyway, and it would be
6500 ;; confusing when adding a second white space character.
6501 (while (re-search-forward
6502 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6503 limit t)
6504 (when (and (not (org-at-comment-p))
6505 (setq ee (org-entity-get (match-string 1)))
6506 (= (length (nth 6 ee)) 1))
6507 (let* ((end (if (equal (match-string 2) "{}")
6508 (match-end 2)
6509 (match-end 1))))
6510 (add-text-properties
6511 (match-beginning 0) end
6512 (list 'font-lock-fontified t))
6513 (compose-region (match-beginning 0) end
6514 (nth 6 ee) nil)
6515 (backward-char 1)
6516 (throw 'match t))))
6517 nil))))
6519 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6520 "Fontify string S like in Org mode."
6521 (with-temp-buffer
6522 (insert s)
6523 (let ((org-odd-levels-only odd-levels))
6524 (org-mode)
6525 (org-font-lock-ensure)
6526 (buffer-string))))
6528 (defvar org-m nil)
6529 (defvar org-l nil)
6530 (defvar org-f nil)
6531 (defun org-get-level-face (n)
6532 "Get the right face for match N in font-lock matching of headlines."
6533 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6534 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6535 (if org-cycle-level-faces
6536 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6537 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6538 (cond
6539 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6540 ((eq n 2) org-f)
6541 (t (unless org-level-color-stars-only org-f))))
6543 (defun org-face-from-face-or-color (context inherit face-or-color)
6544 "Create a face list that inherits INHERIT, but sets the foreground color.
6545 When FACE-OR-COLOR is not a string, just return it."
6546 (if (stringp face-or-color)
6547 (list :inherit inherit
6548 (cdr (assoc context org-faces-easy-properties))
6549 face-or-color)
6550 face-or-color))
6552 (defun org-get-todo-face (kwd)
6553 "Get the right face for a TODO keyword KWD.
6554 If KWD is a number, get the corresponding match group."
6555 (when (numberp kwd) (setq kwd (match-string kwd)))
6556 (or (org-face-from-face-or-color
6557 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6558 (and (member kwd org-done-keywords) 'org-done)
6559 'org-todo))
6561 (defun org-get-priority-face (priority)
6562 "Get the right face for PRIORITY.
6563 PRIORITY is a character."
6564 (or (org-face-from-face-or-color
6565 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6566 'org-priority))
6568 (defun org-get-tag-face (tag)
6569 "Get the right face for TAG.
6570 If TAG is a number, get the corresponding match group."
6571 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6572 (or (org-face-from-face-or-color
6573 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6574 'org-tag)))
6576 (defun org-font-lock-add-priority-faces (limit)
6577 "Add the special priority faces."
6578 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6579 (add-text-properties
6580 (match-beginning 1) (match-end 1)
6581 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6582 'font-lock-fontified t))))
6584 (defun org-font-lock-add-tag-faces (limit)
6585 "Add the special tag faces."
6586 (when (and org-tag-faces org-tags-special-faces-re)
6587 (while (re-search-forward org-tags-special-faces-re limit t)
6588 (add-text-properties (match-beginning 1) (match-end 1)
6589 (list 'face (org-get-tag-face 1)
6590 'font-lock-fontified t))
6591 (backward-char 1))))
6593 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6594 "Remove fontification and activation overlays from links."
6595 (font-lock-default-unfontify-region beg end)
6596 (let* ((buffer-undo-list t)
6597 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6598 (inhibit-modification-hooks t)
6599 deactivate-mark buffer-file-name buffer-file-truename)
6600 (decompose-region beg end)
6601 (remove-text-properties beg end
6602 '(mouse-face t keymap t org-linked-text t
6603 invisible t intangible t
6604 org-emphasis t))
6605 (org-remove-font-lock-display-properties beg end)))
6607 (defconst org-script-display '(((raise -0.3) (height 0.7))
6608 ((raise 0.3) (height 0.7))
6609 ((raise -0.5))
6610 ((raise 0.5)))
6611 "Display properties for showing superscripts and subscripts.")
6613 (defun org-remove-font-lock-display-properties (beg end)
6614 "Remove specific display properties that have been added by font lock.
6615 The will remove the raise properties that are used to show superscripts
6616 and subscripts."
6617 (let (next prop)
6618 (while (< beg end)
6619 (setq next (next-single-property-change beg 'display nil end)
6620 prop (get-text-property beg 'display))
6621 (when (member prop org-script-display)
6622 (put-text-property beg next 'display nil))
6623 (setq beg next))))
6625 (defun org-raise-scripts (limit)
6626 "Add raise properties to sub/superscripts."
6627 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6628 (re-search-forward
6629 (if (eq org-use-sub-superscripts t)
6630 org-match-substring-regexp
6631 org-match-substring-with-braces-regexp)
6632 limit t))
6633 (let* ((pos (point)) table-p comment-p
6634 (mpos (match-beginning 3))
6635 (emph-p (get-text-property mpos 'org-emphasis))
6636 (link-p (get-text-property mpos 'mouse-face))
6637 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6638 (goto-char (point-at-bol))
6639 (setq table-p (looking-at-p org-table-dataline-regexp)
6640 comment-p (looking-at-p "^[ \t]*#[ +]"))
6641 (goto-char pos)
6642 ;; Handle a_b^c
6643 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6644 (unless (or comment-p emph-p link-p keyw-p)
6645 (put-text-property (match-beginning 3) (match-end 0)
6646 'display
6647 (if (equal (char-after (match-beginning 2)) ?^)
6648 (nth (if table-p 3 1) org-script-display)
6649 (nth (if table-p 2 0) org-script-display)))
6650 (add-text-properties (match-beginning 2) (match-end 2)
6651 (list 'invisible t))
6652 (when (and (eq (char-after (match-beginning 3)) ?{)
6653 (eq (char-before (match-end 3)) ?}))
6654 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6655 (list 'invisible t))
6656 (add-text-properties (1- (match-end 3)) (match-end 3)
6657 (list 'invisible t))))
6658 t)))
6660 ;;;; Visibility cycling, including org-goto and indirect buffer
6662 ;;; Cycling
6664 (defvar-local org-cycle-global-status nil)
6665 (put 'org-cycle-global-status 'org-state t)
6666 (defvar-local org-cycle-subtree-status nil)
6667 (put 'org-cycle-subtree-status 'org-state t)
6669 (defvar org-inlinetask-min-level)
6671 (defun org-unlogged-message (&rest args)
6672 "Display a message, but avoid logging it in the *Messages* buffer."
6673 (let ((message-log-max nil))
6674 (apply 'message args)))
6676 ;;;###autoload
6677 (defun org-cycle (&optional arg)
6678 "TAB-action and visibility cycling for Org mode.
6680 This is the command invoked in Org mode by the `TAB' key. Its main
6681 purpose is outline visibility cycling, but it also invokes other actions
6682 in special contexts.
6684 When this function is called with a `\\[universal-argument]' prefix, rotate \
6685 the entire
6686 buffer through 3 states (global cycling)
6687 1. OVERVIEW: Show only top-level headlines.
6688 2. CONTENTS: Show all headlines of all levels, but no body text.
6689 3. SHOW ALL: Show everything.
6691 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6692 switch to the startup visibility,
6693 determined by the variable `org-startup-folded', and by any VISIBILITY
6694 properties in the buffer.
6696 With a `\\[universal-argument] \\[universal-argument] \
6697 \\[universal-argument]' prefix argument, show the entire buffer, including
6698 any drawers.
6700 When inside a table, re-align the table and move to the next field.
6702 When point is at the beginning of a headline, rotate the subtree started
6703 by this line through 3 different states (local cycling)
6704 1. FOLDED: Only the main headline is shown.
6705 2. CHILDREN: The main headline and the direct children are shown.
6706 From this state, you can move to one of the children
6707 and zoom in further.
6708 3. SUBTREE: Show the entire subtree, including body text.
6709 If there is no subtree, switch directly from CHILDREN to FOLDED.
6711 When point is at the beginning of an empty headline and the variable
6712 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6713 of the headline by demoting and promoting it to likely levels. This
6714 speeds up creation document structure by pressing `TAB' once or several
6715 times right after creating a new headline.
6717 When there is a numeric prefix, go up to a heading with level ARG, do
6718 a `show-subtree' and return to the previous cursor position. If ARG
6719 is negative, go up that many levels.
6721 When point is not at the beginning of a headline, execute the global
6722 binding for `TAB', which is re-indenting the line. See the option
6723 `org-cycle-emulate-tab' for details.
6725 As a special case, if point is at the beginning of the buffer and there is
6726 no headline in line 1, this function will act as if called with prefix arg
6727 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6728 prefix arg, but only
6729 if the variable `org-cycle-global-at-bob' is t."
6730 (interactive "P")
6731 (org-load-modules-maybe)
6732 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6733 (and org-cycle-level-after-item/entry-creation
6734 (or (org-cycle-level)
6735 (org-cycle-item-indentation))))
6736 (let* ((limit-level
6737 (or org-cycle-max-level
6738 (and (boundp 'org-inlinetask-min-level)
6739 org-inlinetask-min-level
6740 (1- org-inlinetask-min-level))))
6741 (nstars (and limit-level
6742 (if org-odd-levels-only
6743 (and limit-level (1- (* limit-level 2)))
6744 limit-level)))
6745 (org-outline-regexp
6746 (if (not (derived-mode-p 'org-mode))
6747 outline-regexp
6748 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6749 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6750 (not (looking-at org-outline-regexp))))
6751 (org-cycle-hook
6752 (if bob-special
6753 (delq 'org-optimize-window-after-visibility-change
6754 (copy-sequence org-cycle-hook))
6755 org-cycle-hook))
6756 (pos (point)))
6758 (cond
6760 ((equal arg '(16))
6761 (setq last-command 'dummy)
6762 (org-set-startup-visibility)
6763 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6765 ((equal arg '(64))
6766 (outline-show-all)
6767 (org-unlogged-message "Entire buffer visible, including drawers"))
6769 ((equal arg '(4)) (org-cycle-internal-global))
6771 ;; Try hiding block at point.
6772 ((org-hide-block-toggle-maybe))
6774 ;; Try cdlatex TAB completion
6775 ((org-try-cdlatex-tab))
6777 ;; Table: enter it or move to the next field.
6778 ((org-at-table-p 'any)
6779 (if (org-at-table.el-p)
6780 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6781 Use `\\[org-edit-special]' to edit table.el tables"))
6782 (if arg (org-table-edit-field t)
6783 (org-table-justify-field-maybe)
6784 (call-interactively 'org-table-next-field))))
6786 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6788 ;; Global cycling: delegate to `org-cycle-internal-global'.
6789 (bob-special (org-cycle-internal-global))
6791 ;; Drawers: delegate to `org-flag-drawer'.
6792 ((save-excursion
6793 (beginning-of-line 1)
6794 (looking-at org-drawer-regexp))
6795 (org-flag-drawer ; toggle block visibility
6796 (not (get-char-property (match-end 0) 'invisible))))
6798 ;; Show-subtree, ARG levels up from here.
6799 ((integerp arg)
6800 (save-excursion
6801 (org-back-to-heading)
6802 (outline-up-heading (if (< arg 0) (- arg)
6803 (- (funcall outline-level) arg)))
6804 (org-show-subtree)))
6806 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6807 ((and (featurep 'org-inlinetask)
6808 (org-inlinetask-at-task-p)
6809 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6810 (org-inlinetask-toggle-visibility))
6812 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6813 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6814 (save-excursion (move-beginning-of-line 1)
6815 (looking-at org-outline-regexp)))
6816 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6817 (org-cycle-internal-local))
6819 ;; From there: TAB emulation and template completion.
6820 (buffer-read-only (org-back-to-heading))
6822 ((run-hook-with-args-until-success
6823 'org-tab-after-check-for-cycling-hook))
6825 ((org-try-structure-completion))
6827 ((run-hook-with-args-until-success
6828 'org-tab-before-tab-emulation-hook))
6830 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6831 (or (not (bolp))
6832 (not (looking-at org-outline-regexp))))
6833 (call-interactively (global-key-binding "\t")))
6835 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6836 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6837 (or (and (eq org-cycle-emulate-tab 'white)
6838 (= (match-end 0) (point-at-eol)))
6839 (and (eq org-cycle-emulate-tab 'whitestart)
6840 (>= (match-end 0) pos))))
6842 (eq org-cycle-emulate-tab t))
6843 (call-interactively (global-key-binding "\t")))
6845 (t (save-excursion
6846 (org-back-to-heading)
6847 (org-cycle)))))))
6849 (defun org-cycle-internal-global ()
6850 "Do the global cycling action."
6851 ;; Hack to avoid display of messages for .org attachments in Gnus
6852 (let ((ga (string-match "\\*fontification" (buffer-name))))
6853 (cond
6854 ((and (eq last-command this-command)
6855 (eq org-cycle-global-status 'overview))
6856 ;; We just created the overview - now do table of contents
6857 ;; This can be slow in very large buffers, so indicate action
6858 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6859 (unless ga (org-unlogged-message "CONTENTS..."))
6860 (org-content)
6861 (unless ga (org-unlogged-message "CONTENTS...done"))
6862 (setq org-cycle-global-status 'contents)
6863 (run-hook-with-args 'org-cycle-hook 'contents))
6865 ((and (eq last-command this-command)
6866 (eq org-cycle-global-status 'contents))
6867 ;; We just showed the table of contents - now show everything
6868 (run-hook-with-args 'org-pre-cycle-hook 'all)
6869 (outline-show-all)
6870 (unless ga (org-unlogged-message "SHOW ALL"))
6871 (setq org-cycle-global-status 'all)
6872 (run-hook-with-args 'org-cycle-hook 'all))
6875 ;; Default action: go to overview
6876 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6877 (org-overview)
6878 (unless ga (org-unlogged-message "OVERVIEW"))
6879 (setq org-cycle-global-status 'overview)
6880 (run-hook-with-args 'org-cycle-hook 'overview)))))
6882 (defvar org-called-with-limited-levels nil
6883 "Non-nil when `org-with-limited-levels' is currently active.")
6885 (defun org-invisible-p (&optional pos)
6886 "Non-nil if the character after POS is invisible.
6887 If POS is nil, use `point' instead."
6888 (get-char-property (or pos (point)) 'invisible))
6890 (defun org-cycle-internal-local ()
6891 "Do the local cycling action."
6892 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6893 ;; First, determine end of headline (EOH), end of subtree or item
6894 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6895 (save-excursion
6896 (if (org-at-item-p)
6897 (progn
6898 (beginning-of-line)
6899 (setq struct (org-list-struct))
6900 (setq eoh (point-at-eol))
6901 (setq eos (org-list-get-item-end-before-blank (point) struct))
6902 (setq has-children (org-list-has-child-p (point) struct)))
6903 (org-back-to-heading)
6904 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6905 (setq eos (save-excursion (org-end-of-subtree t t)
6906 (when (bolp) (backward-char)) (point)))
6907 (setq has-children
6908 (or (save-excursion
6909 (let ((level (funcall outline-level)))
6910 (outline-next-heading)
6911 (and (org-at-heading-p t)
6912 (> (funcall outline-level) level))))
6913 (save-excursion
6914 (org-list-search-forward (org-item-beginning-re) eos t)))))
6915 ;; Determine end invisible part of buffer (EOL)
6916 (beginning-of-line 2)
6917 (while (and (not (eobp)) ;This is like `next-line'.
6918 (get-char-property (1- (point)) 'invisible))
6919 (goto-char (next-single-char-property-change (point) 'invisible))
6920 (and (eolp) (beginning-of-line 2)))
6921 (setq eol (point)))
6922 ;; Find out what to do next and set `this-command'
6923 (cond
6924 ((= eos eoh)
6925 ;; Nothing is hidden behind this heading
6926 (unless (org-before-first-heading-p)
6927 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6928 (org-unlogged-message "EMPTY ENTRY")
6929 (setq org-cycle-subtree-status nil)
6930 (save-excursion
6931 (goto-char eos)
6932 (outline-next-heading)
6933 (when (org-invisible-p) (org-flag-heading nil))))
6934 ((and (or (>= eol eos)
6935 (not (string-match "\\S-" (buffer-substring eol eos))))
6936 (or has-children
6937 (not (setq children-skipped
6938 org-cycle-skip-children-state-if-no-children))))
6939 ;; Entire subtree is hidden in one line: children view
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-pre-cycle-hook 'children))
6942 (if (org-at-item-p)
6943 (org-list-set-item-visibility (point-at-bol) struct 'children)
6944 (org-show-entry)
6945 (org-with-limited-levels (org-show-children))
6946 ;; FIXME: This slows down the func way too much.
6947 ;; How keep drawers hidden in subtree anyway?
6948 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6949 ;; (org-cycle-hide-drawers 'subtree))
6951 ;; Fold every list in subtree to top-level items.
6952 (when (eq org-cycle-include-plain-lists 'integrate)
6953 (save-excursion
6954 (org-back-to-heading)
6955 (while (org-list-search-forward (org-item-beginning-re) eos t)
6956 (beginning-of-line 1)
6957 (let* ((struct (org-list-struct))
6958 (prevs (org-list-prevs-alist struct))
6959 (end (org-list-get-bottom-point struct)))
6960 (dolist (e (org-list-get-all-items (point) struct prevs))
6961 (org-list-set-item-visibility e struct 'folded))
6962 (goto-char (if (< end eos) end eos)))))))
6963 (org-unlogged-message "CHILDREN")
6964 (save-excursion
6965 (goto-char eos)
6966 (outline-next-heading)
6967 (when (org-invisible-p) (org-flag-heading nil)))
6968 (setq org-cycle-subtree-status 'children)
6969 (unless (org-before-first-heading-p)
6970 (run-hook-with-args 'org-cycle-hook 'children)))
6971 ((or children-skipped
6972 (and (eq last-command this-command)
6973 (eq org-cycle-subtree-status 'children)))
6974 ;; We just showed the children, or no children are there,
6975 ;; now show everything.
6976 (unless (org-before-first-heading-p)
6977 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6978 (outline-flag-region eoh eos nil)
6979 (org-unlogged-message
6980 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6981 (setq org-cycle-subtree-status 'subtree)
6982 (unless (org-before-first-heading-p)
6983 (run-hook-with-args 'org-cycle-hook 'subtree)))
6985 ;; Default action: hide the subtree.
6986 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6987 (outline-flag-region eoh eos t)
6988 (org-unlogged-message "FOLDED")
6989 (setq org-cycle-subtree-status 'folded)
6990 (unless (org-before-first-heading-p)
6991 (run-hook-with-args 'org-cycle-hook 'folded))))))
6993 ;;;###autoload
6994 (defun org-global-cycle (&optional arg)
6995 "Cycle the global visibility. For details see `org-cycle'.
6996 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6997 With a numeric prefix, show all headlines up to that level."
6998 (interactive "P")
6999 (let ((org-cycle-include-plain-lists
7000 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7001 (cond
7002 ((integerp arg)
7003 (outline-show-all)
7004 (outline-hide-sublevels arg)
7005 (setq org-cycle-global-status 'contents))
7006 ((equal arg '(4))
7007 (org-set-startup-visibility)
7008 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7010 (org-cycle '(4))))))
7012 (defun org-set-startup-visibility ()
7013 "Set the visibility required by startup options and properties."
7014 (cond
7015 ((eq org-startup-folded t)
7016 (org-overview))
7017 ((eq org-startup-folded 'content)
7018 (org-content))
7019 ((or (eq org-startup-folded 'showeverything)
7020 (eq org-startup-folded nil))
7021 (outline-show-all)))
7022 (unless (eq org-startup-folded 'showeverything)
7023 (when org-hide-block-startup (org-hide-block-all))
7024 (org-set-visibility-according-to-property 'no-cleanup)
7025 (org-cycle-hide-archived-subtrees 'all)
7026 (org-cycle-hide-drawers 'all)
7027 (org-cycle-show-empty-lines t)))
7029 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7030 "Switch subtree visibilities according to :VISIBILITY: property."
7031 (interactive)
7032 (org-with-wide-buffer
7033 (goto-char (point-min))
7034 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7035 (if (not (org-at-property-p)) (outline-next-heading)
7036 (let ((state (match-string 3)))
7037 (save-excursion
7038 (org-back-to-heading t)
7039 (outline-hide-subtree)
7040 (org-reveal)
7041 (cond
7042 ((equal state "folded")
7043 (outline-hide-subtree))
7044 ((equal state "children")
7045 (org-show-hidden-entry)
7046 (org-show-children))
7047 ((equal state "content")
7048 (save-excursion
7049 (save-restriction
7050 (org-narrow-to-subtree)
7051 (org-content))))
7052 ((member state '("all" "showall"))
7053 (outline-show-subtree)))))))
7054 (unless no-cleanup
7055 (org-cycle-hide-archived-subtrees 'all)
7056 (org-cycle-hide-drawers 'all)
7057 (org-cycle-show-empty-lines 'all))))
7059 ;; This function uses outline-regexp instead of the more fundamental
7060 ;; org-outline-regexp so that org-cycle-global works outside of Org
7061 ;; buffers, where outline-regexp is needed.
7062 (defun org-overview ()
7063 "Switch to overview mode, showing only top-level headlines.
7064 This shows all headlines with a level equal or greater than the level
7065 of the first headline in the buffer. This is important, because if the
7066 first headline is not level one, then (hide-sublevels 1) gives confusing
7067 results."
7068 (interactive)
7069 (save-excursion
7070 (let ((level
7071 (save-excursion
7072 (goto-char (point-min))
7073 (when (re-search-forward (concat "^" outline-regexp) nil t)
7074 (goto-char (match-beginning 0))
7075 (funcall outline-level)))))
7076 (and level (outline-hide-sublevels level)))))
7078 (defun org-content (&optional arg)
7079 "Show all headlines in the buffer, like a table of contents.
7080 With numerical argument N, show content up to level N."
7081 (interactive "P")
7082 (org-overview)
7083 (save-excursion
7084 ;; Visit all headings and show their offspring
7085 (and (integerp arg) (org-overview))
7086 (goto-char (point-max))
7087 (catch 'exit
7088 (while (and (progn (condition-case nil
7089 (outline-previous-visible-heading 1)
7090 (error (goto-char (point-min))))
7092 (looking-at org-outline-regexp))
7093 (if (integerp arg)
7094 (org-show-children (1- arg))
7095 (outline-show-branches))
7096 (when (bobp) (throw 'exit nil))))))
7098 (defun org-optimize-window-after-visibility-change (state)
7099 "Adjust the window after a change in outline visibility.
7100 This function is the default value of the hook `org-cycle-hook'."
7101 (when (get-buffer-window (current-buffer))
7102 (cond
7103 ((eq state 'content) nil)
7104 ((eq state 'all) nil)
7105 ((eq state 'folded) nil)
7106 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7107 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7109 (defun org-remove-empty-overlays-at (pos)
7110 "Remove outline overlays that do not contain non-white stuff."
7111 (dolist (o (overlays-at pos))
7112 (and (eq 'outline (overlay-get o 'invisible))
7113 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7114 (overlay-end o))))
7115 (delete-overlay o))))
7117 (defun org-clean-visibility-after-subtree-move ()
7118 "Fix visibility issues after moving a subtree."
7119 ;; First, find a reasonable region to look at:
7120 ;; Start two siblings above, end three below
7121 (let* ((beg (save-excursion
7122 (and (org-get-last-sibling)
7123 (org-get-last-sibling))
7124 (point)))
7125 (end (save-excursion
7126 (and (org-get-next-sibling)
7127 (org-get-next-sibling)
7128 (org-get-next-sibling))
7129 (if (org-at-heading-p)
7130 (point-at-eol)
7131 (point))))
7132 (level (looking-at "\\*+"))
7133 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7134 (save-excursion
7135 (save-restriction
7136 (narrow-to-region beg end)
7137 (when re
7138 ;; Properly fold already folded siblings
7139 (goto-char (point-min))
7140 (while (re-search-forward re nil t)
7141 (when (and (not (org-invisible-p))
7142 (save-excursion
7143 (goto-char (point-at-eol)) (org-invisible-p)))
7144 (outline-hide-entry))))
7145 (org-cycle-show-empty-lines 'overview)
7146 (org-cycle-hide-drawers 'overview)))))
7148 (defun org-cycle-show-empty-lines (state)
7149 "Show empty lines above all visible headlines.
7150 The region to be covered depends on STATE when called through
7151 `org-cycle-hook'. Lisp program can use t for STATE to get the
7152 entire buffer covered. Note that an empty line is only shown if there
7153 are at least `org-cycle-separator-lines' empty lines before the headline."
7154 (when (/= org-cycle-separator-lines 0)
7155 (save-excursion
7156 (let* ((n (abs org-cycle-separator-lines))
7157 (re (cond
7158 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7159 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7160 (t (let ((ns (number-to-string (- n 2))))
7161 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7162 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7163 beg end)
7164 (cond
7165 ((memq state '(overview contents t))
7166 (setq beg (point-min) end (point-max)))
7167 ((memq state '(children folded))
7168 (setq beg (point)
7169 end (progn (org-end-of-subtree t t)
7170 (line-beginning-position 2)))))
7171 (when beg
7172 (goto-char beg)
7173 (while (re-search-forward re end t)
7174 (unless (get-char-property (match-end 1) 'invisible)
7175 (let ((e (match-end 1))
7176 (b (if (>= org-cycle-separator-lines 0)
7177 (match-beginning 1)
7178 (save-excursion
7179 (goto-char (match-beginning 0))
7180 (skip-chars-backward " \t\n")
7181 (line-end-position)))))
7182 (outline-flag-region b e nil))))))))
7183 ;; Never hide empty lines at the end of the file.
7184 (save-excursion
7185 (goto-char (point-max))
7186 (outline-previous-heading)
7187 (outline-end-of-heading)
7188 (when (and (looking-at "[ \t\n]+")
7189 (= (match-end 0) (point-max)))
7190 (outline-flag-region (point) (match-end 0) nil))))
7192 (defun org-show-empty-lines-in-parent ()
7193 "Move to the parent and re-show empty lines before visible headlines."
7194 (save-excursion
7195 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7196 (org-cycle-show-empty-lines context))))
7198 (defun org-files-list ()
7199 "Return `org-agenda-files' list, plus all open Org files.
7200 This is useful for operations that need to scan all of a user's
7201 open and agenda-wise Org files."
7202 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7203 (dolist (buf (buffer-list))
7204 (with-current-buffer buf
7205 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7206 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7207 files))
7209 (defsubst org-entry-beginning-position ()
7210 "Return the beginning position of the current entry."
7211 (save-excursion (org-back-to-heading t) (point)))
7213 (defsubst org-entry-end-position ()
7214 "Return the end position of the current entry."
7215 (save-excursion (outline-next-heading) (point)))
7217 (defun org-cycle-hide-drawers (state &optional exceptions)
7218 "Re-hide all drawers after a visibility state change.
7219 STATE should be one of the symbols listed in the docstring of
7220 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7221 a list of strings specifying which drawers should not be hidden."
7222 (when (and (derived-mode-p 'org-mode)
7223 (not (memq state '(overview folded contents))))
7224 (save-excursion
7225 (let* ((globalp (eq state 'all))
7226 (beg (if globalp (point-min) (point)))
7227 (end (if globalp (point-max)
7228 (if (eq state 'children)
7229 (save-excursion (outline-next-heading) (point))
7230 (org-end-of-subtree t)))))
7231 (goto-char beg)
7232 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7233 (unless (member-ignore-case (match-string 1) exceptions)
7234 (let ((drawer (org-element-at-point)))
7235 (when (memq (org-element-type drawer) '(drawer property-drawer))
7236 (org-flag-drawer t drawer)
7237 ;; Make sure to skip drawer entirely or we might flag
7238 ;; it another time when matching its ending line with
7239 ;; `org-drawer-regexp'.
7240 (goto-char (org-element-property :end drawer))))))))))
7242 (defun org-flag-drawer (flag &optional element)
7243 "When FLAG is non-nil, hide the drawer we are at.
7244 Otherwise make it visible. When optional argument ELEMENT is
7245 a parsed drawer, as returned by `org-element-at-point', hide or
7246 show that drawer instead."
7247 (let ((drawer (or element
7248 (and (save-excursion
7249 (beginning-of-line)
7250 (looking-at-p org-drawer-regexp))
7251 (org-element-at-point)))))
7252 (when (memq (org-element-type drawer) '(drawer property-drawer))
7253 (let ((post (org-element-property :post-affiliated drawer)))
7254 (save-excursion
7255 (outline-flag-region
7256 (progn (goto-char post) (line-end-position))
7257 (progn (goto-char (org-element-property :end drawer))
7258 (skip-chars-backward " \r\t\n")
7259 (line-end-position))
7260 flag))
7261 ;; When the drawer is hidden away, make sure point lies in
7262 ;; a visible part of the buffer.
7263 (when (and flag (> (line-beginning-position) post))
7264 (goto-char post))))))
7266 (defun org-subtree-end-visible-p ()
7267 "Is the end of the current subtree visible?"
7268 (pos-visible-in-window-p
7269 (save-excursion (org-end-of-subtree t) (point))))
7271 (defun org-first-headline-recenter ()
7272 "Move cursor to the first headline and recenter the headline."
7273 (let ((window (get-buffer-window)))
7274 (when window
7275 (goto-char (point-min))
7276 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7277 (set-window-start window (line-beginning-position))))))
7279 ;;; Saving and restoring visibility
7281 (defun org-outline-overlay-data (&optional use-markers)
7282 "Return a list of the locations of all outline overlays.
7283 These are overlays with the `invisible' property value `outline'.
7284 The return value is a list of cons cells, with start and stop
7285 positions for each overlay.
7286 If USE-MARKERS is set, return the positions as markers."
7287 (let (beg end)
7288 (org-with-wide-buffer
7289 (delq nil
7290 (mapcar (lambda (o)
7291 (when (eq (overlay-get o 'invisible) 'outline)
7292 (setq beg (overlay-start o)
7293 end (overlay-end o))
7294 (and beg end (> end beg)
7295 (if use-markers
7296 (cons (copy-marker beg)
7297 (copy-marker end t))
7298 (cons beg end)))))
7299 (overlays-in (point-min) (point-max)))))))
7301 (defun org-set-outline-overlay-data (data)
7302 "Create visibility overlays for all positions in DATA.
7303 DATA should have been made by `org-outline-overlay-data'."
7304 (org-with-wide-buffer
7305 (outline-show-all)
7306 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7308 ;;; Folding of blocks
7310 (defvar-local org-hide-block-overlays nil
7311 "Overlays hiding blocks.")
7313 (defun org-block-map (function &optional start end)
7314 "Call FUNCTION at the head of all source blocks in the current buffer.
7315 Optional arguments START and END can be used to limit the range."
7316 (let ((start (or start (point-min)))
7317 (end (or end (point-max))))
7318 (save-excursion
7319 (goto-char start)
7320 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7321 (save-excursion
7322 (save-match-data
7323 (goto-char (match-beginning 0))
7324 (funcall function)))))))
7326 (defun org-hide-block-toggle-all ()
7327 "Toggle the visibility of all blocks in the current buffer."
7328 (org-block-map 'org-hide-block-toggle))
7330 (defun org-hide-block-all ()
7331 "Fold all blocks in the current buffer."
7332 (interactive)
7333 (org-show-block-all)
7334 (org-block-map 'org-hide-block-toggle-maybe))
7336 (defun org-show-block-all ()
7337 "Unfold all blocks in the current buffer."
7338 (interactive)
7339 (mapc #'delete-overlay org-hide-block-overlays)
7340 (setq org-hide-block-overlays nil))
7342 (defun org-hide-block-toggle-maybe ()
7343 "Toggle visibility of block at point.
7344 Unlike to `org-hide-block-toggle', this function does not throw
7345 an error. Return a non-nil value when toggling is successful."
7346 (interactive)
7347 (ignore-errors (org-hide-block-toggle)))
7349 (defun org-hide-block-toggle (&optional force)
7350 "Toggle the visibility of the current block.
7351 When optional argument FORCE is `off', make block visible. If it
7352 is non-nil, hide it unconditionally. Throw an error when not at
7353 a block. Return a non-nil value when toggling is successful."
7354 (interactive)
7355 (let ((element (org-element-at-point)))
7356 (unless (memq (org-element-type element)
7357 '(center-block comment-block dynamic-block example-block
7358 export-block quote-block special-block
7359 src-block verse-block))
7360 (user-error "Not at a block"))
7361 (let* ((start (save-excursion
7362 (goto-char (org-element-property :post-affiliated element))
7363 (line-end-position)))
7364 (end (save-excursion
7365 (goto-char (org-element-property :end element))
7366 (skip-chars-backward " \r\t\n")
7367 (line-end-position)))
7368 (overlays (overlays-at start)))
7369 (cond
7370 ;; Do nothing when not before or at the block opening line or
7371 ;; at the block closing line.
7372 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7373 ((and (not (eq force 'off))
7374 (not (memq t (mapcar
7375 (lambda (o)
7376 (eq (overlay-get o 'invisible) 'org-hide-block))
7377 overlays))))
7378 (let ((ov (make-overlay start end)))
7379 (overlay-put ov 'invisible 'org-hide-block)
7380 ;; Make the block accessible to `isearch'.
7381 (overlay-put
7382 ov 'isearch-open-invisible
7383 (lambda (ov)
7384 (when (memq ov org-hide-block-overlays)
7385 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7386 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7387 (delete-overlay ov))))
7388 (push ov org-hide-block-overlays)
7389 ;; When the block is hidden away, make sure point is left in
7390 ;; a visible part of the buffer.
7391 (when (> (line-beginning-position) start)
7392 (goto-char start)
7393 (beginning-of-line))
7394 ;; Signal successful toggling.
7396 ((or (not force) (eq force 'off))
7397 (dolist (ov overlays t)
7398 (when (memq ov org-hide-block-overlays)
7399 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7400 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7401 (delete-overlay ov))))))))
7403 ;; Remove overlays when changing major mode
7404 (add-hook 'org-mode-hook
7405 (lambda () (add-hook 'change-major-mode-hook
7406 'org-show-block-all 'append 'local)))
7408 ;;; Org-goto
7410 (defvar org-goto-window-configuration nil)
7411 (defvar org-goto-marker nil)
7412 (defvar org-goto-map)
7413 (defun org-goto-map ()
7414 "Set the keymap `org-goto'."
7415 (setq org-goto-map
7416 (let ((map (make-sparse-keymap)))
7417 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7418 mouse-drag-region universal-argument org-occur)))
7419 (dolist (cmd cmds)
7420 (substitute-key-definition cmd cmd map global-map)))
7421 (suppress-keymap map)
7422 (org-defkey map "\C-m" 'org-goto-ret)
7423 (org-defkey map [(return)] 'org-goto-ret)
7424 (org-defkey map [(left)] 'org-goto-left)
7425 (org-defkey map [(right)] 'org-goto-right)
7426 (org-defkey map [(control ?g)] 'org-goto-quit)
7427 (org-defkey map "\C-i" 'org-cycle)
7428 (org-defkey map [(tab)] 'org-cycle)
7429 (org-defkey map [(down)] 'outline-next-visible-heading)
7430 (org-defkey map [(up)] 'outline-previous-visible-heading)
7431 (if org-goto-auto-isearch
7432 (if (fboundp 'define-key-after)
7433 (define-key-after map [t] 'org-goto-local-auto-isearch)
7434 nil)
7435 (org-defkey map "q" 'org-goto-quit)
7436 (org-defkey map "n" 'outline-next-visible-heading)
7437 (org-defkey map "p" 'outline-previous-visible-heading)
7438 (org-defkey map "f" 'outline-forward-same-level)
7439 (org-defkey map "b" 'outline-backward-same-level)
7440 (org-defkey map "u" 'outline-up-heading))
7441 (org-defkey map "/" 'org-occur)
7442 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7443 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7444 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7445 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7446 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7447 map)))
7449 (defconst org-goto-help
7450 "Browse buffer copy, to find location or copy text.%s
7451 RET=jump to location C-g=quit and return to previous location
7452 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7454 (defvar org-goto-start-pos) ; dynamically scoped parameter
7456 (defun org-goto (&optional alternative-interface)
7457 "Look up a different location in the current file, keeping current visibility.
7459 When you want look-up or go to a different location in a
7460 document, the fastest way is often to fold the entire buffer and
7461 then dive into the tree. This method has the disadvantage, that
7462 the previous location will be folded, which may not be what you
7463 want.
7465 This command works around this by showing a copy of the current
7466 buffer in an indirect buffer, in overview mode. You can dive
7467 into the tree in that copy, use org-occur and incremental search
7468 to find a location. When pressing RET or `Q', the command
7469 returns to the original buffer in which the visibility is still
7470 unchanged. After RET it will also jump to the location selected
7471 in the indirect buffer and expose the headline hierarchy above.
7473 With a prefix argument, use the alternative interface: e.g., if
7474 `org-goto-interface' is `outline' use `outline-path-completion'."
7475 (interactive "P")
7476 (org-goto-map)
7477 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7478 (org-refile-use-outline-path t)
7479 (org-refile-target-verify-function nil)
7480 (interface
7481 (if (not alternative-interface)
7482 org-goto-interface
7483 (if (eq org-goto-interface 'outline)
7484 'outline-path-completion
7485 'outline)))
7486 (org-goto-start-pos (point))
7487 (selected-point
7488 (if (eq interface 'outline)
7489 (car (org-get-location (current-buffer) org-goto-help))
7490 (let ((pa (org-refile-get-location "Goto")))
7491 (org-refile-check-position pa)
7492 (nth 3 pa)))))
7493 (if selected-point
7494 (progn
7495 (org-mark-ring-push org-goto-start-pos)
7496 (goto-char selected-point)
7497 (when (or (org-invisible-p) (org-invisible-p2))
7498 (org-show-context 'org-goto)))
7499 (message "Quit"))))
7501 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7502 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7503 (defvar org-goto-local-auto-isearch-map) ; defined below
7505 (defun org-get-location (_buf help)
7506 "Let the user select a location in current buffer.
7507 This function uses a recursive edit. It returns the selected position
7508 or nil."
7509 (org-no-popups
7510 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7511 (isearch-hide-immediately nil)
7512 (isearch-search-fun-function
7513 (lambda () 'org-goto-local-search-headings))
7514 (org-goto-selected-point org-goto-exit-command))
7515 (save-excursion
7516 (save-window-excursion
7517 (delete-other-windows)
7518 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7519 (pop-to-buffer-same-window
7520 (condition-case nil
7521 (make-indirect-buffer (current-buffer) "*org-goto*")
7522 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7523 (with-output-to-temp-buffer "*Org Help*"
7524 (princ (format help (if org-goto-auto-isearch
7525 " Just type for auto-isearch."
7526 " n/p/f/b/u to navigate, q to quit."))))
7527 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7528 (setq buffer-read-only nil)
7529 (let ((org-startup-truncated t)
7530 (org-startup-folded nil)
7531 (org-startup-align-all-tables nil))
7532 (org-mode)
7533 (org-overview))
7534 (setq buffer-read-only t)
7535 (if (and (boundp 'org-goto-start-pos)
7536 (integer-or-marker-p org-goto-start-pos))
7537 (progn (goto-char org-goto-start-pos)
7538 (when (org-invisible-p)
7539 (org-show-set-visibility 'lineage)))
7540 (goto-char (point-min)))
7541 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7542 (message "Select location and press RET")
7543 (use-local-map org-goto-map)
7544 (recursive-edit)))
7545 (kill-buffer "*org-goto*")
7546 (cons org-goto-selected-point org-goto-exit-command))))
7548 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7549 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7550 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7551 (if (fboundp 'isearch-other-control-char)
7552 (progn
7553 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7554 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7555 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7556 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7557 (define-key org-goto-local-auto-isearch-map [return] nil))
7559 (defun org-goto-local-search-headings (string bound noerror)
7560 "Search and make sure that any matches are in headlines."
7561 (catch 'return
7562 (while (if isearch-forward
7563 (search-forward string bound noerror)
7564 (search-backward string bound noerror))
7565 (when (save-match-data
7566 (and (save-excursion
7567 (beginning-of-line)
7568 (looking-at org-complex-heading-regexp))
7569 (or (not (match-beginning 5))
7570 (< (point) (match-beginning 5)))))
7571 (throw 'return (point))))))
7573 (defun org-goto-local-auto-isearch ()
7574 "Start isearch."
7575 (interactive)
7576 (goto-char (point-min))
7577 (let ((keys (this-command-keys)))
7578 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7579 (isearch-mode t)
7580 (isearch-process-search-char (string-to-char keys)))))
7582 (defun org-goto-ret (&optional _arg)
7583 "Finish `org-goto' by going to the new location."
7584 (interactive "P")
7585 (setq org-goto-selected-point (point))
7586 (setq org-goto-exit-command 'return)
7587 (throw 'exit nil))
7589 (defun org-goto-left ()
7590 "Finish `org-goto' by going to the new location."
7591 (interactive)
7592 (if (org-at-heading-p)
7593 (progn
7594 (beginning-of-line 1)
7595 (setq org-goto-selected-point (point)
7596 org-goto-exit-command 'left)
7597 (throw 'exit nil))
7598 (user-error "Not on a heading")))
7600 (defun org-goto-right ()
7601 "Finish `org-goto' by going to the new location."
7602 (interactive)
7603 (if (org-at-heading-p)
7604 (progn
7605 (setq org-goto-selected-point (point)
7606 org-goto-exit-command 'right)
7607 (throw 'exit nil))
7608 (user-error "Not on a heading")))
7610 (defun org-goto-quit ()
7611 "Finish `org-goto' without cursor motion."
7612 (interactive)
7613 (setq org-goto-selected-point nil)
7614 (setq org-goto-exit-command 'quit)
7615 (throw 'exit nil))
7617 ;;; Indirect buffer display of subtrees
7619 (defvar org-indirect-dedicated-frame nil
7620 "This is the frame being used for indirect tree display.")
7621 (defvar org-last-indirect-buffer nil)
7623 (defun org-tree-to-indirect-buffer (&optional arg)
7624 "Create indirect buffer and narrow it to current subtree.
7626 With a numerical prefix ARG, go up to this level and then take that tree.
7627 If ARG is negative, go up that many levels.
7629 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7630 indirect buffer previously made with this command, to avoid proliferation of
7631 indirect buffers. However, when you call the command with a \
7632 `\\[universal-argument]' prefix, or
7633 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7634 so that you can work with several indirect buffers at the same time. If
7635 `org-indirect-buffer-display' is `dedicated-frame', the \
7636 `\\[universal-argument]' prefix also
7637 requests that a new frame be made for the new buffer, so that the dedicated
7638 frame is not changed."
7639 (interactive "P")
7640 (let ((cbuf (current-buffer))
7641 (cwin (selected-window))
7642 (pos (point))
7643 beg end level heading ibuf)
7644 (save-excursion
7645 (org-back-to-heading t)
7646 (when (numberp arg)
7647 (setq level (org-outline-level))
7648 (when (< arg 0) (setq arg (+ level arg)))
7649 (while (> (setq level (org-outline-level)) arg)
7650 (org-up-heading-safe)))
7651 (setq beg (point)
7652 heading (org-get-heading 'no-tags))
7653 (org-end-of-subtree t t)
7654 (when (org-at-heading-p) (backward-char 1))
7655 (setq end (point)))
7656 (when (and (buffer-live-p org-last-indirect-buffer)
7657 (not (eq org-indirect-buffer-display 'new-frame))
7658 (not arg))
7659 (kill-buffer org-last-indirect-buffer))
7660 (setq ibuf (org-get-indirect-buffer cbuf heading)
7661 org-last-indirect-buffer ibuf)
7662 (cond
7663 ((or (eq org-indirect-buffer-display 'new-frame)
7664 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7665 (select-frame (make-frame))
7666 (delete-other-windows)
7667 (pop-to-buffer-same-window ibuf)
7668 (org-set-frame-title heading))
7669 ((eq org-indirect-buffer-display 'dedicated-frame)
7670 (raise-frame
7671 (select-frame (or (and org-indirect-dedicated-frame
7672 (frame-live-p org-indirect-dedicated-frame)
7673 org-indirect-dedicated-frame)
7674 (setq org-indirect-dedicated-frame (make-frame)))))
7675 (delete-other-windows)
7676 (pop-to-buffer-same-window ibuf)
7677 (org-set-frame-title (concat "Indirect: " heading)))
7678 ((eq org-indirect-buffer-display 'current-window)
7679 (pop-to-buffer-same-window ibuf))
7680 ((eq org-indirect-buffer-display 'other-window)
7681 (pop-to-buffer ibuf))
7682 (t (error "Invalid value")))
7683 (narrow-to-region beg end)
7684 (outline-show-all)
7685 (goto-char pos)
7686 (run-hook-with-args 'org-cycle-hook 'all)
7687 (and (window-live-p cwin) (select-window cwin))))
7689 (defun org-get-indirect-buffer (&optional buffer heading)
7690 (setq buffer (or buffer (current-buffer)))
7691 (let ((n 1) (base (buffer-name buffer)) bname)
7692 (while (buffer-live-p
7693 (get-buffer
7694 (setq bname
7695 (concat base "-"
7696 (if heading (concat heading "-" (number-to-string n))
7697 (number-to-string n))))))
7698 (setq n (1+ n)))
7699 (condition-case nil
7700 (make-indirect-buffer buffer bname 'clone)
7701 (error (make-indirect-buffer buffer bname)))))
7703 (defun org-set-frame-title (title)
7704 "Set the title of the current frame to the string TITLE."
7705 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7707 ;;;; Structure editing
7709 ;;; Inserting headlines
7711 (defun org--line-empty-p (n)
7712 "Is the Nth next line empty?
7714 Counts the current line as N = 1 and the previous line as N = 0;
7715 see `beginning-of-line'."
7716 (save-excursion
7717 (and (not (bobp))
7718 (or (beginning-of-line n) t)
7719 (save-match-data
7720 (looking-at "[ \t]*$")))))
7722 (defun org-previous-line-empty-p ()
7723 "Is the previous line a blank line?
7724 When NEXT is non-nil, check the next line instead."
7725 (org--line-empty-p 0))
7727 (defun org-next-line-empty-p ()
7728 "Is the previous line a blank line?
7729 When NEXT is non-nil, check the next line instead."
7730 (org--line-empty-p 2))
7732 (defun org--blank-before-heading-p (&optional parent)
7733 "Non-nil when an empty line should precede a new heading here.
7734 When optional argument PARENT is non-nil, consider parent
7735 headline instead of current one."
7736 (pcase (assq 'heading org-blank-before-new-entry)
7737 (`(heading . auto)
7738 (save-excursion
7739 (org-with-limited-levels
7740 (unless (and (org-before-first-heading-p)
7741 (not (outline-next-heading)))
7742 (org-back-to-heading t)
7743 (when parent (org-up-heading-safe))
7744 (cond ((not (bobp))
7745 (org-previous-line-empty-p))
7746 ((outline-next-heading)
7747 (org-previous-line-empty-p))
7748 ;; Ignore trailing spaces on last buffer line.
7749 ((progn (skip-chars-backward " \t") (bolp))
7750 (org-previous-line-empty-p))
7751 (t nil))))))
7752 (`(heading . ,value) value)
7753 (_ nil)))
7755 (defun org-insert-heading (&optional arg invisible-ok top)
7756 "Insert a new heading or an item with the same depth at point.
7758 If point is at the beginning of a heading, insert a new heading
7759 or a new headline above the current one. When at the beginning
7760 of a regular line of text, turn it into a heading.
7762 If point is in the middle of a line, split it and create a new
7763 headline with the text in the current line after point (see
7764 `org-M-RET-may-split-line' on how to modify this behavior). As
7765 a special case, on a headline, splitting can only happen on the
7766 title itself. E.g., this excludes breaking stars or tags.
7768 With a `\\[universal-argument]' prefix, set \
7769 `org-insert-heading-respect-content' to
7770 a non-nil value for the duration of the command. This forces the
7771 insertion of a heading after the current subtree, independently
7772 on the location of point.
7774 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7775 insert the heading at the end of the tree
7776 above the current heading. For example, if point is within a
7777 2nd-level heading, then it will insert a 2nd-level heading at
7778 the end of the 1st-level parent subtree.
7780 When INVISIBLE-OK is set, stop at invisible headlines when going
7781 back. This is important for non-interactive uses of the
7782 command.
7784 When optional argument TOP is non-nil, insert a level 1 heading,
7785 unconditionally."
7786 (interactive "P")
7787 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7788 (level (org-current-level))
7789 (stars (make-string (if (and level (not top)) level 1) ?*)))
7790 (cond
7791 ((or org-insert-heading-respect-content
7792 (member arg '((4) (16)))
7793 (and (not invisible-ok)
7794 (invisible-p (max (1- (point)) (point-min)))))
7795 ;; Position point at the location of insertion.
7796 (if (not level) ;before first headline
7797 (org-with-limited-levels (outline-next-heading))
7798 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7799 ;; is nil.
7800 (org-with-limited-levels (org-back-to-heading invisible-ok))
7801 (cond ((equal arg '(16))
7802 (org-up-heading-safe)
7803 (org-end-of-subtree t t))
7805 (org-end-of-subtree t t))))
7806 (unless (bolp) (insert "\n")) ;ensure final newline
7807 (unless (and blank? (org-previous-line-empty-p))
7808 (org-N-empty-lines-before-current (if blank? 1 0)))
7809 (insert stars " \n")
7810 (forward-char -1))
7811 ;; At a headline...
7812 ((org-at-heading-p)
7813 (cond ((bolp)
7814 (when blank? (save-excursion (insert "\n")))
7815 (save-excursion (insert stars " \n"))
7816 (unless (and blank? (org-previous-line-empty-p))
7817 (org-N-empty-lines-before-current (if blank? 1 0)))
7818 (end-of-line))
7819 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7820 (org-match-line org-complex-heading-regexp)
7821 (org-pos-in-match-range (point) 4))
7822 ;; Grab the text that should moved to the new headline.
7823 ;; Preserve tags.
7824 (let ((split (delete-and-extract-region (point) (match-end 4))))
7825 (if (looking-at "[ \t]*$") (replace-match "")
7826 (org-set-tags nil t))
7827 (end-of-line)
7828 (when blank? (insert "\n"))
7829 (insert "\n" stars " ")
7830 (when (org-string-nw-p split) (insert split))
7831 (when (eobp) (save-excursion (insert "\n")))))
7833 (end-of-line)
7834 (when blank? (insert "\n"))
7835 (insert "\n" stars " ")
7836 (when (eobp) (save-excursion (insert "\n"))))))
7837 ;; On regular text, turn line into a headline or split, if
7838 ;; appropriate.
7839 ((bolp)
7840 (insert stars " ")
7841 (unless (and blank? (org-previous-line-empty-p))
7842 (org-N-empty-lines-before-current (if blank? 1 0))))
7844 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7845 (end-of-line))
7846 (insert "\n" stars " ")
7847 (unless (and blank? (org-previous-line-empty-p))
7848 (org-N-empty-lines-before-current (if blank? 1 0))))))
7849 (run-hooks 'org-insert-heading-hook))
7851 (defun org-N-empty-lines-before-current (n)
7852 "Make the number of empty lines before current exactly N.
7853 So this will delete or add empty lines."
7854 (let ((column (current-column)))
7855 (beginning-of-line)
7856 (unless (bobp)
7857 (let ((start (save-excursion
7858 (skip-chars-backward " \r\t\n")
7859 (line-end-position))))
7860 (delete-region start (line-end-position 0))))
7861 (insert (make-string n ?\n))
7862 (move-to-column column)))
7864 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7865 "Return the heading of the current entry, without the stars.
7866 When NO-TAGS is non-nil, don't include tags.
7867 When NO-TODO is non-nil, don't include TODO keywords.
7868 When NO-PRIORITY is non-nil, don't include priority cookie.
7869 When NO-COMMENT is non-nil, don't include COMMENT string."
7870 (save-excursion
7871 (org-back-to-heading t)
7872 (let ((case-fold-search nil))
7873 (looking-at org-complex-heading-regexp)
7874 (let ((todo (and (not no-todo) (match-string 2)))
7875 (priority (and (not no-priority) (match-string 3)))
7876 (headline (pcase (match-string 4)
7877 (`nil "")
7878 ((and (guard no-comment) h)
7879 (replace-regexp-in-string
7880 (eval-when-compile
7881 (format "\\`%s[ \t]+" org-comment-string))
7882 "" h))
7883 (h h)))
7884 (tags (and (not no-tags) (match-string 5))))
7885 (mapconcat #'identity
7886 (delq nil (list todo priority headline tags))
7887 " ")))))
7889 (defvar orgstruct-mode) ; defined below
7891 (defun org-heading-components ()
7892 "Return the components of the current heading.
7893 This is a list with the following elements:
7894 - the level as an integer
7895 - the reduced level, different if `org-odd-levels-only' is set.
7896 - the TODO keyword, or nil
7897 - the priority character, like ?A, or nil if no priority is given
7898 - the headline text itself, or the tags string if no headline text
7899 - the tags string, or nil."
7900 (save-excursion
7901 (org-back-to-heading t)
7902 (when (let (case-fold-search)
7903 (looking-at
7904 (if orgstruct-mode
7905 org-heading-regexp
7906 org-complex-heading-regexp)))
7907 (if orgstruct-mode
7908 (list (length (match-string 1))
7909 (org-reduced-level (length (match-string 1)))
7912 (match-string 2)
7913 nil)
7914 (list (length (match-string 1))
7915 (org-reduced-level (length (match-string 1)))
7916 (match-string-no-properties 2)
7917 (and (match-end 3) (aref (match-string 3) 2))
7918 (match-string-no-properties 4)
7919 (match-string-no-properties 5))))))
7921 (defun org-get-entry ()
7922 "Get the entry text, after heading, entire subtree."
7923 (save-excursion
7924 (org-back-to-heading t)
7925 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7927 (defun org-edit-headline (&optional heading)
7928 "Edit the current headline.
7929 Set it to HEADING when provided."
7930 (interactive)
7931 (org-with-wide-buffer
7932 (org-back-to-heading t)
7933 (let ((case-fold-search nil))
7934 (when (looking-at org-complex-heading-regexp)
7935 (let* ((old (match-string-no-properties 4))
7936 (new (save-match-data
7937 (org-trim (or heading (read-string "Edit: " old))))))
7938 (unless (equal old new)
7939 (if old (replace-match new t t nil 4)
7940 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7941 (insert " " new))
7942 (org-set-tags nil t)
7943 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7945 (defun org-insert-heading-after-current ()
7946 "Insert a new heading with same level as current, after current subtree."
7947 (interactive)
7948 (org-back-to-heading)
7949 (org-insert-heading)
7950 (org-move-subtree-down)
7951 (end-of-line 1))
7953 (defun org-insert-heading-respect-content (&optional invisible-ok)
7954 "Insert heading with `org-insert-heading-respect-content' set to t."
7955 (interactive)
7956 (org-insert-heading '(4) invisible-ok))
7958 (defun org-insert-todo-heading-respect-content (&optional force-state)
7959 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7960 (interactive)
7961 (org-insert-todo-heading force-state '(4)))
7963 (defun org-insert-todo-heading (arg &optional force-heading)
7964 "Insert a new heading with the same level and TODO state as current heading.
7966 If the heading has no TODO state, or if the state is DONE, use
7967 the first state (TODO by default). Also with one prefix arg,
7968 force first state. With two prefix args, force inserting at the
7969 end of the parent subtree.
7971 When called at a plain list item, insert a new item with an
7972 unchecked check box."
7973 (interactive "P")
7974 (when (or force-heading (not (org-insert-item 'checkbox)))
7975 (org-insert-heading (or (and (equal arg '(16)) '(16))
7976 force-heading))
7977 (save-excursion
7978 (org-back-to-heading)
7979 (outline-previous-heading)
7980 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7981 (let* ((new-mark-x
7982 (if (or (equal arg '(4))
7983 (not (match-beginning 2))
7984 (member (match-string 2) org-done-keywords))
7985 (car org-todo-keywords-1)
7986 (match-string 2)))
7987 (new-mark
7989 (run-hook-with-args-until-success
7990 'org-todo-get-default-hook new-mark-x nil)
7991 new-mark-x)))
7992 (beginning-of-line 1)
7993 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7994 (if org-treat-insert-todo-heading-as-state-change
7995 (org-todo new-mark)
7996 (insert new-mark " "))))
7997 (when org-provide-todo-statistics
7998 (org-update-parent-todo-statistics))))
8000 (defun org-insert-subheading (arg)
8001 "Insert a new subheading and demote it.
8002 Works for outline headings and for plain lists alike."
8003 (interactive "P")
8004 (org-insert-heading arg)
8005 (cond
8006 ((org-at-heading-p) (org-do-demote))
8007 ((org-at-item-p) (org-indent-item))))
8009 (defun org-insert-todo-subheading (arg)
8010 "Insert a new subheading with TODO keyword or checkbox and demote it.
8011 Works for outline headings and for plain lists alike."
8012 (interactive "P")
8013 (org-insert-todo-heading arg)
8014 (cond
8015 ((org-at-heading-p) (org-do-demote))
8016 ((org-at-item-p) (org-indent-item))))
8018 ;;; Promotion and Demotion
8020 (defvar org-after-demote-entry-hook nil
8021 "Hook run after an entry has been demoted.
8022 The cursor will be at the beginning of the entry.
8023 When a subtree is being demoted, the hook will be called for each node.")
8025 (defvar org-after-promote-entry-hook nil
8026 "Hook run after an entry has been promoted.
8027 The cursor will be at the beginning of the entry.
8028 When a subtree is being promoted, the hook will be called for each node.")
8030 (defun org-promote-subtree ()
8031 "Promote the entire subtree.
8032 See also `org-promote'."
8033 (interactive)
8034 (save-excursion
8035 (org-with-limited-levels (org-map-tree 'org-promote)))
8036 (org-fix-position-after-promote))
8038 (defun org-demote-subtree ()
8039 "Demote the entire subtree.
8040 See `org-demote' and `org-promote'."
8041 (interactive)
8042 (save-excursion
8043 (org-with-limited-levels (org-map-tree 'org-demote)))
8044 (org-fix-position-after-promote))
8046 (defun org-do-promote ()
8047 "Promote the current heading higher up the tree.
8048 If the region is active in `transient-mark-mode', promote all
8049 headings in the region."
8050 (interactive)
8051 (save-excursion
8052 (if (org-region-active-p)
8053 (org-map-region 'org-promote (region-beginning) (region-end))
8054 (org-promote)))
8055 (org-fix-position-after-promote))
8057 (defun org-do-demote ()
8058 "Demote the current heading lower down the tree.
8059 If the region is active in `transient-mark-mode', demote all
8060 headings in the region."
8061 (interactive)
8062 (save-excursion
8063 (if (org-region-active-p)
8064 (org-map-region 'org-demote (region-beginning) (region-end))
8065 (org-demote)))
8066 (org-fix-position-after-promote))
8068 (defun org-fix-position-after-promote ()
8069 "Fix cursor position and indentation after demoting/promoting."
8070 (let ((pos (point)))
8071 (when (save-excursion
8072 (beginning-of-line)
8073 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8074 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8075 (cond ((eobp) (insert " "))
8076 ((eolp) (insert " "))
8077 ((equal (char-after) ?\s) (forward-char 1))))))
8079 (defun org-current-level ()
8080 "Return the level of the current entry, or nil if before the first headline.
8081 The level is the number of stars at the beginning of the
8082 headline. Use `org-reduced-level' to remove the effect of
8083 `org-odd-levels'. Unlike to `org-outline-level', this function
8084 ignores inlinetasks."
8085 (let ((level (org-with-limited-levels (org-outline-level))))
8086 (and (> level 0) level)))
8088 (defun org-get-previous-line-level ()
8089 "Return the outline depth of the last headline before the current line.
8090 Returns 0 for the first headline in the buffer, and nil if before the
8091 first headline."
8092 (and (org-current-level)
8093 (or (and (/= (line-beginning-position) (point-min))
8094 (save-excursion (beginning-of-line 0) (org-current-level)))
8095 0)))
8097 (defun org-reduced-level (l)
8098 "Compute the effective level of a heading.
8099 This takes into account the setting of `org-odd-levels-only'."
8100 (cond
8101 ((zerop l) 0)
8102 (org-odd-levels-only (1+ (floor (/ l 2))))
8103 (t l)))
8105 (defun org-level-increment ()
8106 "Return the number of stars that will be added or removed at a
8107 time to headlines when structure editing, based on the value of
8108 `org-odd-levels-only'."
8109 (if org-odd-levels-only 2 1))
8111 (defun org-get-valid-level (level &optional change)
8112 "Rectify a level change under the influence of `org-odd-levels-only'.
8113 LEVEL is a current level, CHANGE is by how much the level should
8114 be modified. Even if CHANGE is nil, LEVEL may be returned
8115 modified because even level numbers will become the next higher
8116 odd number. Returns values greater than 0."
8117 (if org-odd-levels-only
8118 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8119 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8120 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8121 (max 1 (+ level (or change 0)))))
8123 (defun org-promote ()
8124 "Promote the current heading higher up the tree."
8125 (org-with-wide-buffer
8126 (org-back-to-heading t)
8127 (let* ((after-change-functions (remq 'flyspell-after-change-function
8128 after-change-functions))
8129 (level (save-match-data (funcall outline-level)))
8130 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8131 (diff (abs (- level (length up-head) -1))))
8132 (cond
8133 ((and (= level 1) org-allow-promoting-top-level-subtree)
8134 (replace-match "# " nil t))
8135 ((= level 1)
8136 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8137 (t (replace-match up-head nil t)))
8138 (unless (= level 1)
8139 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8140 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8141 (run-hooks 'org-after-promote-entry-hook))))
8143 (defun org-demote ()
8144 "Demote the current heading lower down the tree."
8145 (org-with-wide-buffer
8146 (org-back-to-heading t)
8147 (let* ((after-change-functions (remq 'flyspell-after-change-function
8148 after-change-functions))
8149 (level (save-match-data (funcall outline-level)))
8150 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8151 (diff (abs (- level (length down-head) -1))))
8152 (replace-match down-head nil t)
8153 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8154 (when org-adapt-indentation (org-fixup-indentation diff))
8155 (run-hooks 'org-after-demote-entry-hook))))
8157 (defun org-cycle-level ()
8158 "Cycle the level of an empty headline through possible states.
8159 This goes first to child, then to parent, level, then up the hierarchy.
8160 After top level, it switches back to sibling level."
8161 (interactive)
8162 (let ((org-adapt-indentation nil))
8163 (when (org-point-at-end-of-empty-headline)
8164 (setq this-command 'org-cycle-level) ; Only needed for caching
8165 (let ((cur-level (org-current-level))
8166 (prev-level (org-get-previous-line-level)))
8167 (cond
8168 ;; If first headline in file, promote to top-level.
8169 ((= prev-level 0)
8170 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8171 do (org-do-promote)))
8172 ;; If same level as prev, demote one.
8173 ((= prev-level cur-level)
8174 (org-do-demote))
8175 ;; If parent is top-level, promote to top level if not already.
8176 ((= prev-level 1)
8177 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8178 do (org-do-promote)))
8179 ;; If top-level, return to prev-level.
8180 ((= cur-level 1)
8181 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8182 do (org-do-demote)))
8183 ;; If less than prev-level, promote one.
8184 ((< cur-level prev-level)
8185 (org-do-promote))
8186 ;; If deeper than prev-level, promote until higher than
8187 ;; prev-level.
8188 ((> cur-level prev-level)
8189 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8190 do (org-do-promote))))
8191 t))))
8193 (defun org-map-tree (fun)
8194 "Call FUN for every heading underneath the current one."
8195 (org-back-to-heading t)
8196 (let ((level (funcall outline-level)))
8197 (save-excursion
8198 (funcall fun)
8199 (while (and (progn
8200 (outline-next-heading)
8201 (> (funcall outline-level) level))
8202 (not (eobp)))
8203 (funcall fun)))))
8205 (defun org-map-region (fun beg end)
8206 "Call FUN for every heading between BEG and END."
8207 (let ((org-ignore-region t))
8208 (save-excursion
8209 (setq end (copy-marker end))
8210 (goto-char beg)
8211 (when (and (re-search-forward org-outline-regexp-bol nil t)
8212 (< (point) end))
8213 (funcall fun))
8214 (while (and (progn
8215 (outline-next-heading)
8216 (< (point) end))
8217 (not (eobp)))
8218 (funcall fun)))))
8220 (defun org-fixup-indentation (diff)
8221 "Change the indentation in the current entry by DIFF.
8223 DIFF is an integer. Indentation is done according to the
8224 following rules:
8226 - Planning information and property drawers are always indented
8227 according to the new level of the headline;
8229 - Footnote definitions and their contents are ignored;
8231 - Inlinetasks' boundaries are not shifted;
8233 - Empty lines are ignored;
8235 - Other lines' indentation are shifted by DIFF columns, unless
8236 it would introduce a structural change in the document, in
8237 which case no shifting is done at all.
8239 Assume point is at a heading or an inlinetask beginning."
8240 (org-with-wide-buffer
8241 (narrow-to-region (line-beginning-position)
8242 (save-excursion
8243 (if (org-with-limited-levels (org-at-heading-p))
8244 (org-with-limited-levels (outline-next-heading))
8245 (org-inlinetask-goto-end))
8246 (point)))
8247 (forward-line)
8248 ;; Indent properly planning info and property drawer.
8249 (when (looking-at-p org-planning-line-re)
8250 (org-indent-line)
8251 (forward-line))
8252 (when (looking-at org-property-drawer-re)
8253 (goto-char (match-end 0))
8254 (forward-line)
8255 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8256 (catch 'no-shift
8257 (when (zerop diff) (throw 'no-shift nil))
8258 ;; If DIFF is negative, first check if a shift is possible at all
8259 ;; (e.g., it doesn't break structure). This can only happen if
8260 ;; some contents are not properly indented.
8261 (let ((case-fold-search t))
8262 (when (< diff 0)
8263 (let ((diff (- diff))
8264 (forbidden-re (concat org-outline-regexp
8265 "\\|"
8266 (substring org-footnote-definition-re 1))))
8267 (save-excursion
8268 (while (not (eobp))
8269 (cond
8270 ((looking-at-p "[ \t]*$") (forward-line))
8271 ((and (looking-at-p org-footnote-definition-re)
8272 (let ((e (org-element-at-point)))
8273 (and (eq (org-element-type e) 'footnote-definition)
8274 (goto-char (org-element-property :end e))))))
8275 ((looking-at-p org-outline-regexp) (forward-line))
8276 ;; Give up if shifting would move before column 0 or
8277 ;; if it would introduce a headline or a footnote
8278 ;; definition.
8280 (skip-chars-forward " \t")
8281 (let ((ind (current-column)))
8282 (when (or (< ind diff)
8283 (and (= ind diff) (looking-at-p forbidden-re)))
8284 (throw 'no-shift nil)))
8285 ;; Ignore contents of example blocks and source
8286 ;; blocks if their indentation is meant to be
8287 ;; preserved. Jump to block's closing line.
8288 (beginning-of-line)
8289 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8290 (let ((e (org-element-at-point)))
8291 (and (memq (org-element-type e)
8292 '(example-block src-block))
8293 (or org-src-preserve-indentation
8294 (org-element-property :preserve-indent e))
8295 (goto-char (org-element-property :end e))
8296 (progn (skip-chars-backward " \r\t\n")
8297 (beginning-of-line)
8298 t))))
8299 (forward-line))))))))
8300 ;; Shift lines but footnote definitions, inlinetasks boundaries
8301 ;; by DIFF. Also skip contents of source or example blocks
8302 ;; when indentation is meant to be preserved.
8303 (while (not (eobp))
8304 (cond
8305 ((and (looking-at-p org-footnote-definition-re)
8306 (let ((e (org-element-at-point)))
8307 (and (eq (org-element-type e) 'footnote-definition)
8308 (goto-char (org-element-property :end e))))))
8309 ((looking-at-p org-outline-regexp) (forward-line))
8310 ((looking-at-p "[ \t]*$") (forward-line))
8312 (indent-line-to (+ (org-get-indentation) diff))
8313 (beginning-of-line)
8314 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8315 (let ((e (org-element-at-point)))
8316 (and (memq (org-element-type e)
8317 '(example-block src-block))
8318 (or org-src-preserve-indentation
8319 (org-element-property :preserve-indent e))
8320 (goto-char (org-element-property :end e))
8321 (progn (skip-chars-backward " \r\t\n")
8322 (beginning-of-line)
8323 t))))
8324 (forward-line)))))))))
8326 (defun org-convert-to-odd-levels ()
8327 "Convert an Org file with all levels allowed to one with odd levels.
8328 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8329 level 5 etc."
8330 (interactive)
8331 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8332 (let ((outline-level 'org-outline-level)
8333 (org-odd-levels-only nil) n)
8334 (save-excursion
8335 (goto-char (point-min))
8336 (while (re-search-forward "^\\*\\*+ " nil t)
8337 (setq n (- (length (match-string 0)) 2))
8338 (while (>= (setq n (1- n)) 0)
8339 (org-demote))
8340 (end-of-line 1))))))
8342 (defun org-convert-to-oddeven-levels ()
8343 "Convert an Org file with only odd levels to one with odd/even levels.
8344 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8345 file contains a section with an even level, conversion would
8346 destroy the structure of the file. An error is signaled in this
8347 case."
8348 (interactive)
8349 (goto-char (point-min))
8350 ;; First check if there are no even levels
8351 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8352 (org-show-set-visibility 'canonical)
8353 (error "Not all levels are odd in this file. Conversion not possible"))
8354 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8355 (let ((outline-regexp org-outline-regexp)
8356 (outline-level 'org-outline-level)
8357 (org-odd-levels-only nil) n)
8358 (save-excursion
8359 (goto-char (point-min))
8360 (while (re-search-forward "^\\*\\*+ " nil t)
8361 (setq n (/ (1- (length (match-string 0))) 2))
8362 (while (>= (setq n (1- n)) 0)
8363 (org-promote))
8364 (end-of-line 1))))))
8366 (defun org-tr-level (n)
8367 "Make N odd if required."
8368 (if org-odd-levels-only (1+ (/ n 2)) n))
8370 ;;; Vertical tree motion, cutting and pasting of subtrees
8372 (defun org-move-subtree-up (&optional arg)
8373 "Move the current subtree up past ARG headlines of the same level."
8374 (interactive "p")
8375 (org-move-subtree-down (- (prefix-numeric-value arg))))
8377 (defun org-move-subtree-down (&optional arg)
8378 "Move the current subtree down past ARG headlines of the same level."
8379 (interactive "p")
8380 (setq arg (prefix-numeric-value arg))
8381 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8382 'org-get-last-sibling))
8383 (ins-point (make-marker))
8384 (cnt (abs arg))
8385 (col (current-column))
8386 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8387 ;; Select the tree
8388 (org-back-to-heading)
8389 (setq beg0 (point))
8390 (save-excursion
8391 (setq ne-beg (org-back-over-empty-lines))
8392 (setq beg (point)))
8393 (save-match-data
8394 (save-excursion (outline-end-of-heading)
8395 (setq folded (org-invisible-p)))
8396 (progn (org-end-of-subtree nil t)
8397 (unless (eobp) (backward-char))))
8398 (outline-next-heading)
8399 (setq ne-end (org-back-over-empty-lines))
8400 (setq end (point))
8401 (goto-char beg0)
8402 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8403 ;; include less whitespace
8404 (save-excursion
8405 (goto-char beg)
8406 (forward-line (- ne-beg ne-end))
8407 (setq beg (point))))
8408 ;; Find insertion point, with error handling
8409 (while (> cnt 0)
8410 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8411 (progn (goto-char beg0)
8412 (user-error "Cannot move past superior level or buffer limit")))
8413 (setq cnt (1- cnt)))
8414 (when (> arg 0)
8415 ;; Moving forward - still need to move over subtree
8416 (org-end-of-subtree t t)
8417 (save-excursion
8418 (org-back-over-empty-lines)
8419 (or (bolp) (newline))))
8420 (setq ne-ins (org-back-over-empty-lines))
8421 (move-marker ins-point (point))
8422 (setq txt (buffer-substring beg end))
8423 (org-save-markers-in-region beg end)
8424 (delete-region beg end)
8425 (org-remove-empty-overlays-at beg)
8426 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8427 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8428 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8429 (let ((bbb (point)))
8430 (insert-before-markers txt)
8431 (org-reinstall-markers-in-region bbb)
8432 (move-marker ins-point bbb))
8433 (or (bolp) (insert "\n"))
8434 (setq ins-end (point))
8435 (goto-char ins-point)
8436 (org-skip-whitespace)
8437 (when (and (< arg 0)
8438 (org-first-sibling-p)
8439 (> ne-ins ne-beg))
8440 ;; Move whitespace back to beginning
8441 (save-excursion
8442 (goto-char ins-end)
8443 (let ((kill-whole-line t))
8444 (kill-line (- ne-ins ne-beg)) (point)))
8445 (insert (make-string (- ne-ins ne-beg) ?\n)))
8446 (move-marker ins-point nil)
8447 (if folded
8448 (outline-hide-subtree)
8449 (org-show-entry)
8450 (org-show-children)
8451 (org-cycle-hide-drawers 'children))
8452 (org-clean-visibility-after-subtree-move)
8453 ;; move back to the initial column we were at
8454 (move-to-column col)))
8456 (defvar org-subtree-clip ""
8457 "Clipboard for cut and paste of subtrees.
8458 This is actually only a copy of the kill, because we use the normal kill
8459 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8461 (defvar org-subtree-clip-folded nil
8462 "Was the last copied subtree folded?
8463 This is used to fold the tree back after pasting.")
8465 (defun org-cut-subtree (&optional n)
8466 "Cut the current subtree into the clipboard.
8467 With prefix arg N, cut this many sequential subtrees.
8468 This is a short-hand for marking the subtree and then cutting it."
8469 (interactive "p")
8470 (org-copy-subtree n 'cut))
8472 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8473 "Copy the current subtree it in the clipboard.
8474 With prefix arg N, copy this many sequential subtrees.
8475 This is a short-hand for marking the subtree and then copying it.
8476 If CUT is non-nil, actually cut the subtree.
8477 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8478 of some markers in the region, even if CUT is non-nil. This is
8479 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8480 (interactive "p")
8481 (let (beg end folded (beg0 (point)))
8482 (if (called-interactively-p 'any)
8483 (org-back-to-heading nil) ; take what looks like a subtree
8484 (org-back-to-heading t)) ; take what is really there
8485 (setq beg (point))
8486 (skip-chars-forward " \t\r\n")
8487 (save-match-data
8488 (if nosubtrees
8489 (outline-next-heading)
8490 (save-excursion (outline-end-of-heading)
8491 (setq folded (org-invisible-p)))
8492 (ignore-errors (org-forward-heading-same-level (1- n) t))
8493 (org-end-of-subtree t t)))
8494 ;; Include the end of an inlinetask
8495 (when (and (featurep 'org-inlinetask)
8496 (looking-at-p (concat (org-inlinetask-outline-regexp)
8497 "END[ \t]*$")))
8498 (end-of-line))
8499 (setq end (point))
8500 (goto-char beg0)
8501 (when (> end beg)
8502 (setq org-subtree-clip-folded folded)
8503 (when (or cut force-store-markers)
8504 (org-save-markers-in-region beg end))
8505 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8506 (setq org-subtree-clip (current-kill 0))
8507 (message "%s: Subtree(s) with %d characters"
8508 (if cut "Cut" "Copied")
8509 (length org-subtree-clip)))))
8511 (defun org-paste-subtree (&optional level tree for-yank remove)
8512 "Paste the clipboard as a subtree, with modification of headline level.
8513 The entire subtree is promoted or demoted in order to match a new headline
8514 level.
8516 If the cursor is at the beginning of a headline, the same level as
8517 that headline is used to paste the tree.
8519 If not, the new level is derived from the *visible* headings
8520 before and after the insertion point, and taken to be the inferior headline
8521 level of the two. So if the previous visible heading is level 3 and the
8522 next is level 4 (or vice versa), level 4 will be used for insertion.
8523 This makes sure that the subtree remains an independent subtree and does
8524 not swallow low level entries.
8526 You can also force a different level, either by using a numeric prefix
8527 argument, or by inserting the heading marker by hand. For example, if the
8528 cursor is after \"*****\", then the tree will be shifted to level 5.
8530 If optional TREE is given, use this text instead of the kill ring.
8532 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8533 move back over whitespace before inserting, and move point to the end of
8534 the inserted text when done.
8536 When REMOVE is non-nil, remove the subtree from the clipboard."
8537 (interactive "P")
8538 (setq tree (or tree (and kill-ring (current-kill 0))))
8539 (unless (org-kill-is-subtree-p tree)
8540 (user-error "%s"
8541 (substitute-command-keys
8542 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8543 (org-with-limited-levels
8544 (let* ((visp (not (org-invisible-p)))
8545 (txt tree)
8546 (^re_ "\\(\\*+\\)[ \t]*")
8547 (old-level (if (string-match org-outline-regexp-bol txt)
8548 (- (match-end 0) (match-beginning 0) 1)
8549 -1))
8550 (force-level (cond (level (prefix-numeric-value level))
8551 ((and (looking-at "[ \t]*$")
8552 (string-match
8553 "^\\*+$" (buffer-substring
8554 (point-at-bol) (point))))
8555 (- (match-end 0) (match-beginning 0)))
8556 ((and (bolp)
8557 (looking-at org-outline-regexp))
8558 (- (match-end 0) (point) 1))))
8559 (previous-level (save-excursion
8560 (condition-case nil
8561 (progn
8562 (outline-previous-visible-heading 1)
8563 (if (looking-at ^re_)
8564 (- (match-end 0) (match-beginning 0) 1)
8566 (error 1))))
8567 (next-level (save-excursion
8568 (condition-case nil
8569 (progn
8570 (or (looking-at org-outline-regexp)
8571 (outline-next-visible-heading 1))
8572 (if (looking-at ^re_)
8573 (- (match-end 0) (match-beginning 0) 1)
8575 (error 1))))
8576 (new-level (or force-level (max previous-level next-level)))
8577 (shift (if (or (= old-level -1)
8578 (= new-level -1)
8579 (= old-level new-level))
8581 (- new-level old-level)))
8582 (delta (if (> shift 0) -1 1))
8583 (func (if (> shift 0) 'org-demote 'org-promote))
8584 (org-odd-levels-only nil)
8585 beg end newend)
8586 ;; Remove the forced level indicator
8587 (when force-level
8588 (delete-region (point-at-bol) (point)))
8589 ;; Paste
8590 (beginning-of-line (if (bolp) 1 2))
8591 (setq beg (point))
8592 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8593 (insert-before-markers txt)
8594 (unless (string-suffix-p "\n" txt) (insert "\n"))
8595 (setq newend (point))
8596 (org-reinstall-markers-in-region beg)
8597 (setq end (point))
8598 (goto-char beg)
8599 (skip-chars-forward " \t\n\r")
8600 (setq beg (point))
8601 (when (and (org-invisible-p) visp)
8602 (save-excursion (outline-show-heading)))
8603 ;; Shift if necessary
8604 (unless (= shift 0)
8605 (save-restriction
8606 (narrow-to-region beg end)
8607 (while (not (= shift 0))
8608 (org-map-region func (point-min) (point-max))
8609 (setq shift (+ delta shift)))
8610 (goto-char (point-min))
8611 (setq newend (point-max))))
8612 (when (or (called-interactively-p 'interactive) for-yank)
8613 (message "Clipboard pasted as level %d subtree" new-level))
8614 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8615 kill-ring
8616 (eq org-subtree-clip (current-kill 0))
8617 org-subtree-clip-folded)
8618 ;; The tree was folded before it was killed/copied
8619 (outline-hide-subtree))
8620 (and for-yank (goto-char newend))
8621 (and remove (setq kill-ring (cdr kill-ring))))))
8623 (defun org-kill-is-subtree-p (&optional txt)
8624 "Check if the current kill is an outline subtree, or a set of trees.
8625 Returns nil if kill does not start with a headline, or if the first
8626 headline level is not the largest headline level in the tree.
8627 So this will actually accept several entries of equal levels as well,
8628 which is OK for `org-paste-subtree'.
8629 If optional TXT is given, check this string instead of the current kill."
8630 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8631 (re (org-get-limited-outline-regexp))
8632 (^re (concat "^" re))
8633 (start-level (and kill
8634 (string-match
8635 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8636 kill)
8637 (- (match-end 2) (match-beginning 2) 1)))
8638 (start (1+ (or (match-beginning 2) -1))))
8639 (if (not start-level)
8640 (progn
8641 nil) ;; does not even start with a heading
8642 (catch 'exit
8643 (while (setq start (string-match ^re kill (1+ start)))
8644 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8645 (throw 'exit nil)))
8646 t))))
8648 (defvar org-markers-to-move nil
8649 "Markers that should be moved with a cut-and-paste operation.
8650 Those markers are stored together with their positions relative to
8651 the start of the region.")
8653 (defun org-save-markers-in-region (beg end)
8654 "Check markers in region.
8655 If these markers are between BEG and END, record their position relative
8656 to BEG, so that after moving the block of text, we can put the markers back
8657 into place.
8658 This function gets called just before an entry or tree gets cut from the
8659 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8660 called immediately, to move the markers with the entries."
8661 (setq org-markers-to-move nil)
8662 (when (featurep 'org-clock)
8663 (org-clock-save-markers-for-cut-and-paste beg end))
8664 (when (featurep 'org-agenda)
8665 (org-agenda-save-markers-for-cut-and-paste beg end)))
8667 (defun org-check-and-save-marker (marker beg end)
8668 "Check if MARKER is between BEG and END.
8669 If yes, remember the marker and the distance to BEG."
8670 (when (and (marker-buffer marker)
8671 (equal (marker-buffer marker) (current-buffer))
8672 (>= marker beg) (< marker end))
8673 (push (cons marker (- marker beg)) org-markers-to-move)))
8675 (defun org-reinstall-markers-in-region (beg)
8676 "Move all remembered markers to their position relative to BEG."
8677 (dolist (x org-markers-to-move)
8678 (move-marker (car x) (+ beg (cdr x))))
8679 (setq org-markers-to-move nil))
8681 (defun org-narrow-to-subtree ()
8682 "Narrow buffer to the current subtree."
8683 (interactive)
8684 (save-excursion
8685 (save-match-data
8686 (org-with-limited-levels
8687 (narrow-to-region
8688 (progn (org-back-to-heading t) (point))
8689 (progn (org-end-of-subtree t t)
8690 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8691 (point)))))))
8693 (defun org-narrow-to-block ()
8694 "Narrow buffer to the current block."
8695 (interactive)
8696 (let* ((case-fold-search t)
8697 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8698 "^[ \t]*#\\+end_.*")))
8699 (if blockp
8700 (narrow-to-region (car blockp) (cdr blockp))
8701 (user-error "Not in a block"))))
8703 (defun org-clone-subtree-with-time-shift (n &optional shift)
8704 "Clone the task (subtree) at point N times.
8705 The clones will be inserted as siblings.
8707 In interactive use, the user will be prompted for the number of
8708 clones to be produced. If the entry has a timestamp, the user
8709 will also be prompted for a time shift, which may be a repeater
8710 as used in time stamps, for example `+3d'. To disable this,
8711 you can call the function with a universal prefix argument.
8713 When a valid repeater is given and the entry contains any time
8714 stamps, the clones will become a sequence in time, with time
8715 stamps in the subtree shifted for each clone produced. If SHIFT
8716 is nil or the empty string, time stamps will be left alone. The
8717 ID property of the original subtree is removed.
8719 In each clone, all the CLOCK entries will be removed. This
8720 prevents Org from considering that the clocked times overlap.
8722 If the original subtree did contain time stamps with a repeater,
8723 the following will happen:
8724 - the repeater will be removed in each clone
8725 - an additional clone will be produced, with the current, unshifted
8726 date(s) in the entry.
8727 - the original entry will be placed *after* all the clones, with
8728 repeater intact.
8729 - the start days in the repeater in the original entry will be shifted
8730 to past the last clone.
8731 In this way you can spell out a number of instances of a repeating task,
8732 and still retain the repeater to cover future instances of the task.
8734 As described above, N+1 clones are produced when the original
8735 subtree has a repeater. Setting N to 0, then, can be used to
8736 remove the repeater from a subtree and create a shifted clone
8737 with the original repeater."
8738 (interactive "nNumber of clones to produce: ")
8739 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8740 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8741 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8742 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8743 (shift
8744 (or shift
8745 (if (and (not (equal current-prefix-arg '(4)))
8746 (save-excursion
8747 (goto-char beg)
8748 (re-search-forward org-ts-regexp-both end-of-tree t)))
8749 (read-from-minibuffer
8750 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8751 ""))) ;No time shift
8752 (doshift
8753 (and (org-string-nw-p shift)
8754 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8755 shift)
8756 (user-error "Invalid shift specification %s" shift)))))
8757 (goto-char end-of-tree)
8758 (unless (bolp) (insert "\n"))
8759 (let* ((end (point))
8760 (template (buffer-substring beg end))
8761 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8762 (shift-what (pcase (and doshift (match-string 2 shift))
8763 (`nil nil)
8764 ("d" 'day)
8765 ("w" (setq shift-n (* 7 shift-n)) 'day)
8766 ("m" 'month)
8767 ("y" 'year)
8768 (_ (error "Unsupported time unit"))))
8769 (nmin 1)
8770 (nmax n)
8771 (n-no-remove -1)
8772 (idprop (org-entry-get nil "ID")))
8773 (when (and doshift
8774 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8775 template))
8776 (delete-region beg end)
8777 (setq end beg)
8778 (setq nmin 0)
8779 (setq nmax (1+ nmax))
8780 (setq n-no-remove nmax))
8781 (goto-char end)
8782 (cl-loop for n from nmin to nmax do
8783 (insert
8784 ;; Prepare clone.
8785 (with-temp-buffer
8786 (insert template)
8787 (org-mode)
8788 (goto-char (point-min))
8789 (org-show-subtree)
8790 (and idprop (if org-clone-delete-id
8791 (org-entry-delete nil "ID")
8792 (org-id-get-create t)))
8793 (unless (= n 0)
8794 (while (re-search-forward org-clock-line-re nil t)
8795 (delete-region (line-beginning-position)
8796 (line-beginning-position 2)))
8797 (goto-char (point-min))
8798 (while (re-search-forward org-drawer-regexp nil t)
8799 (org-remove-empty-drawer-at (point))))
8800 (goto-char (point-min))
8801 (when doshift
8802 (while (re-search-forward org-ts-regexp-both nil t)
8803 (org-timestamp-change (* n shift-n) shift-what))
8804 (unless (= n n-no-remove)
8805 (goto-char (point-min))
8806 (while (re-search-forward org-ts-regexp nil t)
8807 (save-excursion
8808 (goto-char (match-beginning 0))
8809 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8810 (delete-region (match-beginning 1) (match-end 1)))))))
8811 (buffer-string)))))
8812 (goto-char beg)))
8814 ;;; Outline Sorting
8816 (defun org-sort (&optional with-case)
8817 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8818 Optional argument WITH-CASE means sort case-sensitively."
8819 (interactive "P")
8820 (org-call-with-arg
8821 (cond ((org-at-table-p) #'org-table-sort-lines)
8822 ((org-at-item-p) #'org-sort-list)
8823 (t #'org-sort-entries))
8824 with-case))
8826 (defun org-sort-remove-invisible (s)
8827 "Remove invisible part of links and emphasis markers from string S."
8828 (remove-text-properties 0 (length s) org-rm-props s)
8829 (replace-regexp-in-string
8830 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8831 (replace-regexp-in-string
8832 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8833 (org-link-display-format s)
8834 t t) t t))
8836 (defvar org-priority-regexp) ; defined later in the file
8838 (defvar org-after-sorting-entries-or-items-hook nil
8839 "Hook that is run after a bunch of entries or items have been sorted.
8840 When children are sorted, the cursor is in the parent line when this
8841 hook gets called. When a region or a plain list is sorted, the cursor
8842 will be in the first entry of the sorted region/list.")
8844 (defun org-sort-entries
8845 (&optional with-case sorting-type getkey-func compare-func property
8846 interactive?)
8847 "Sort entries on a certain level of an outline tree.
8848 If there is an active region, the entries in the region are sorted.
8849 Else, if the cursor is before the first entry, sort the top-level items.
8850 Else, the children of the entry at point are sorted.
8852 Sorting can be alphabetically, numerically, by date/time as given by
8853 a time stamp, by a property, by priority order, or by a custom function.
8855 The command prompts for the sorting type unless it has been given to the
8856 function through the SORTING-TYPE argument, which needs to be a character,
8857 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8858 the precise meaning of each character:
8860 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8861 c By creation time, which is assumed to be the first inactive time stamp
8862 at the beginning of a line.
8863 d By deadline date/time.
8864 k By clocking time.
8865 n Numerically, by converting the beginning of the entry/item to a number.
8866 o By order of TODO keywords.
8867 p By priority according to the cookie.
8868 r By the value of a property.
8869 s By scheduled date/time.
8870 t By date/time, either the first active time stamp in the entry, or, if
8871 none exist, by the first inactive one.
8873 Capital letters will reverse the sort order.
8875 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8876 called with point at the beginning of the record. It must return a
8877 value that is compatible with COMPARE-FUNC, the function used to
8878 compare entries.
8880 Comparing entries ignores case by default. However, with an optional argument
8881 WITH-CASE, the sorting considers case as well.
8883 Sorting is done against the visible part of the headlines, it ignores hidden
8884 links.
8886 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8888 A non-nil value for INTERACTIVE? is used to signal that this
8889 function is being called interactively."
8890 (interactive (list current-prefix-arg nil nil nil nil t))
8891 (let ((case-func (if with-case 'identity 'downcase))
8892 (cmstr
8893 ;; The clock marker is lost when using `sort-subr', let's
8894 ;; store the clocking string.
8895 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8896 (save-excursion
8897 (goto-char org-clock-marker)
8898 (buffer-substring-no-properties (line-beginning-position)
8899 (point)))))
8900 start beg end stars re re2
8901 txt what tmp)
8902 ;; Find beginning and end of region to sort
8903 (cond
8904 ((org-region-active-p)
8905 ;; we will sort the region
8906 (setq end (region-end)
8907 what "region")
8908 (goto-char (region-beginning))
8909 (unless (org-at-heading-p) (outline-next-heading))
8910 (setq start (point)))
8911 ((or (org-at-heading-p)
8912 (ignore-errors (progn (org-back-to-heading) t)))
8913 ;; we will sort the children of the current headline
8914 (org-back-to-heading)
8915 (setq start (point)
8916 end (progn (org-end-of-subtree t t)
8917 (or (bolp) (insert "\n"))
8918 (when (>= (org-back-over-empty-lines) 1)
8919 (forward-line 1))
8920 (point))
8921 what "children")
8922 (goto-char start)
8923 (outline-show-subtree)
8924 (outline-next-heading))
8926 ;; we will sort the top-level entries in this file
8927 (goto-char (point-min))
8928 (or (org-at-heading-p) (outline-next-heading))
8929 (setq start (point))
8930 (goto-char (point-max))
8931 (beginning-of-line 1)
8932 (when (looking-at ".*?\\S-")
8933 ;; File ends in a non-white line
8934 (end-of-line 1)
8935 (insert "\n"))
8936 (setq end (point-max))
8937 (setq what "top-level")
8938 (goto-char start)
8939 (outline-show-all)))
8941 (setq beg (point))
8942 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8944 (looking-at "\\(\\*+\\)")
8945 (setq stars (match-string 1)
8946 re (concat "^" (regexp-quote stars) " +")
8947 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8948 txt (buffer-substring beg end))
8949 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8950 (when (and (not (equal stars "*")) (string-match re2 txt))
8951 (user-error "Region to sort contains a level above the first entry"))
8953 (unless sorting-type
8954 (message
8955 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8956 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8957 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8958 what)
8959 (setq sorting-type (read-char-exclusive)))
8961 (unless getkey-func
8962 (and (= (downcase sorting-type) ?f)
8963 (setq getkey-func
8964 (or (and interactive?
8965 (org-read-function
8966 "Function for extracting keys: "))
8967 (error "Missing key extractor")))))
8969 (and (= (downcase sorting-type) ?r)
8970 (not property)
8971 (setq property
8972 (completing-read "Property: "
8973 (mapcar #'list (org-buffer-property-keys t))
8974 nil t)))
8976 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8977 (message "Sorting entries...")
8979 (save-restriction
8980 (narrow-to-region start end)
8981 (let ((dcst (downcase sorting-type))
8982 (case-fold-search nil)
8983 (now (current-time)))
8984 (sort-subr
8985 (/= dcst sorting-type)
8986 ;; This function moves to the beginning character of the "record" to
8987 ;; be sorted.
8988 (lambda nil
8989 (if (re-search-forward re nil t)
8990 (goto-char (match-beginning 0))
8991 (goto-char (point-max))))
8992 ;; This function moves to the last character of the "record" being
8993 ;; sorted.
8994 (lambda nil
8995 (save-match-data
8996 (condition-case nil
8997 (outline-forward-same-level 1)
8998 (error
8999 (goto-char (point-max))))))
9000 ;; This function returns the value that gets sorted against.
9001 (lambda nil
9002 (cond
9003 ((= dcst ?n)
9004 (if (looking-at org-complex-heading-regexp)
9005 (string-to-number (org-sort-remove-invisible (match-string 4)))
9006 nil))
9007 ((= dcst ?a)
9008 (if (looking-at org-complex-heading-regexp)
9009 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9010 nil))
9011 ((= dcst ?k)
9012 (or (get-text-property (point) :org-clock-minutes) 0))
9013 ((= dcst ?t)
9014 (let ((end (save-excursion (outline-next-heading) (point))))
9015 (if (or (re-search-forward org-ts-regexp end t)
9016 (re-search-forward org-ts-regexp-both end t))
9017 (org-time-string-to-seconds (match-string 0))
9018 (float-time now))))
9019 ((= dcst ?c)
9020 (let ((end (save-excursion (outline-next-heading) (point))))
9021 (if (re-search-forward
9022 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9023 end t)
9024 (org-time-string-to-seconds (match-string 0))
9025 (float-time now))))
9026 ((= dcst ?s)
9027 (let ((end (save-excursion (outline-next-heading) (point))))
9028 (if (re-search-forward org-scheduled-time-regexp end t)
9029 (org-time-string-to-seconds (match-string 1))
9030 (float-time now))))
9031 ((= dcst ?d)
9032 (let ((end (save-excursion (outline-next-heading) (point))))
9033 (if (re-search-forward org-deadline-time-regexp end t)
9034 (org-time-string-to-seconds (match-string 1))
9035 (float-time now))))
9036 ((= dcst ?p)
9037 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9038 (string-to-char (match-string 2))
9039 org-default-priority))
9040 ((= dcst ?r)
9041 (or (org-entry-get nil property) ""))
9042 ((= dcst ?o)
9043 (when (looking-at org-complex-heading-regexp)
9044 (let* ((m (match-string 2))
9045 (s (if (member m org-done-keywords) '- '+)))
9046 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9047 ((= dcst ?f)
9048 (if getkey-func
9049 (progn
9050 (setq tmp (funcall getkey-func))
9051 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9052 tmp)
9053 (error "Invalid key function `%s'" getkey-func)))
9054 (t (error "Invalid sorting type `%c'" sorting-type))))
9056 (cond
9057 ((= dcst ?a) 'string<)
9058 ((= dcst ?f)
9059 (or compare-func
9060 (and interactive?
9061 (org-read-function
9062 (concat "Function for comparing keys "
9063 "(empty for default `sort-subr' predicate): ")
9064 'allow-empty))))
9065 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9066 (run-hooks 'org-after-sorting-entries-or-items-hook)
9067 ;; Reset the clock marker if needed
9068 (when cmstr
9069 (save-excursion
9070 (goto-char start)
9071 (search-forward cmstr nil t)
9072 (move-marker org-clock-marker (point))))
9073 (message "Sorting entries...done")))
9075 ;;; The orgstruct minor mode
9077 ;; Define a minor mode which can be used in other modes in order to
9078 ;; integrate the Org mode structure editing commands.
9080 ;; This is really a hack, because the Org mode structure commands use
9081 ;; keys which normally belong to the major mode. Here is how it
9082 ;; works: The minor mode defines all the keys necessary to operate the
9083 ;; structure commands, but wraps the commands into a function which
9084 ;; tests if the cursor is currently at a headline or a plain list
9085 ;; item. If that is the case, the structure command is used,
9086 ;; temporarily setting many Org mode variables like regular
9087 ;; expressions for filling etc. However, when any of those keys is
9088 ;; used at a different location, function uses `key-binding' to look
9089 ;; up if the key has an associated command in another currently active
9090 ;; keymap (minor modes, major mode, global), and executes that
9091 ;; command. There might be problems if any of the keys is otherwise
9092 ;; used as a prefix key.
9094 (defcustom orgstruct-heading-prefix-regexp ""
9095 "Regexp that matches the custom prefix of Org headlines in
9096 orgstruct(++)-mode."
9097 :group 'org
9098 :version "24.4"
9099 :package-version '(Org . "8.3")
9100 :type 'regexp)
9101 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9103 (defcustom orgstruct-setup-hook nil
9104 "Hook run after orgstruct-mode-map is filled."
9105 :group 'org
9106 :version "24.4"
9107 :package-version '(Org . "8.0")
9108 :type 'hook)
9110 (defvar orgstruct-initialized nil)
9112 (defvar org-local-vars nil
9113 "List of local variables, for use by `orgstruct-mode'.")
9115 ;;;###autoload
9116 (define-minor-mode orgstruct-mode
9117 "Toggle the minor mode `orgstruct-mode'.
9118 This mode is for using Org mode structure commands in other
9119 modes. The following keys behave as if Org mode were active, if
9120 the cursor is on a headline, or on a plain list item (both as
9121 defined by Org mode)."
9122 nil " OrgStruct" (make-sparse-keymap)
9123 (funcall (if orgstruct-mode
9124 'add-to-invisibility-spec
9125 'remove-from-invisibility-spec)
9126 '(outline . t))
9127 (when orgstruct-mode
9128 (org-load-modules-maybe)
9129 (unless orgstruct-initialized
9130 (orgstruct-setup)
9131 (setq orgstruct-initialized t))))
9133 ;;;###autoload
9134 (defun turn-on-orgstruct ()
9135 "Unconditionally turn on `orgstruct-mode'."
9136 (orgstruct-mode 1))
9138 (defvar-local orgstruct-is-++ nil
9139 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9140 (defvar-local org-fb-vars nil)
9141 (defun orgstruct++-mode (&optional arg)
9142 "Toggle `orgstruct-mode', the enhanced version of it.
9143 In addition to setting orgstruct-mode, this also exports all
9144 indentation and autofilling variables from Org mode into the
9145 buffer. It will also recognize item context in multiline items."
9146 (interactive "P")
9147 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9148 (if (< arg 1)
9149 (progn (orgstruct-mode -1)
9150 (dolist (v org-fb-vars)
9151 (set (make-local-variable (car v))
9152 (if (eq (car-safe (cadr v)) 'quote)
9153 (cl-cadadr v)
9154 (nth 1 v)))))
9155 (orgstruct-mode 1)
9156 (setq org-fb-vars nil)
9157 (unless org-local-vars
9158 (setq org-local-vars (org-get-local-variables)))
9159 (let (var val)
9160 (dolist (x org-local-vars)
9161 (when (string-match
9162 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9163 \\|fill-prefix\\|indent-\\)"
9164 (symbol-name (car x)))
9165 (setq var (car x) val (nth 1 x))
9166 (push (list var `(quote ,(eval var))) org-fb-vars)
9167 (set (make-local-variable var)
9168 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9169 (setq-local orgstruct-is-++ t))))
9171 ;;;###autoload
9172 (defun turn-on-orgstruct++ ()
9173 "Unconditionally turn on `orgstruct++-mode'."
9174 (orgstruct++-mode 1))
9176 (defun orgstruct-error ()
9177 "Error when there is no default binding for a structure key."
9178 (interactive)
9179 (funcall (if (fboundp 'user-error)
9180 'user-error
9181 'error)
9182 "This key has no function outside structure elements"))
9184 (defun orgstruct-setup ()
9185 "Setup orgstruct keymap."
9186 (dolist (cell '((org-demote . t)
9187 (org-metaleft . t)
9188 (org-metaright . t)
9189 (org-promote . t)
9190 (org-shiftmetaleft . t)
9191 (org-shiftmetaright . t)
9192 org-backward-element
9193 org-backward-heading-same-level
9194 org-ctrl-c-ret
9195 org-ctrl-c-minus
9196 org-ctrl-c-star
9197 org-cycle
9198 org-force-cycle-archived
9199 org-forward-heading-same-level
9200 org-insert-heading
9201 org-insert-heading-respect-content
9202 org-kill-note-or-show-branches
9203 org-mark-subtree
9204 org-meta-return
9205 org-metadown
9206 org-metaup
9207 org-narrow-to-subtree
9208 org-promote-subtree
9209 org-reveal
9210 org-shiftdown
9211 org-shiftleft
9212 org-shiftmetadown
9213 org-shiftmetaup
9214 org-shiftright
9215 org-shifttab
9216 org-shifttab
9217 org-shiftup
9218 org-show-children
9219 org-show-subtree
9220 org-sort
9221 org-up-element
9222 outline-demote
9223 outline-next-visible-heading
9224 outline-previous-visible-heading
9225 outline-promote
9226 outline-up-heading))
9227 (let ((f (or (car-safe cell) cell))
9228 (disable-when-heading-prefix (cdr-safe cell)))
9229 (when (fboundp f)
9230 (let ((new-bindings))
9231 (dolist (binding (nconc (where-is-internal f org-mode-map)
9232 (where-is-internal f outline-mode-map)))
9233 (push binding new-bindings)
9234 ;; TODO use local-function-key-map
9235 (dolist (rep '(("<tab>" . "TAB")
9236 ("<return>" . "RET")
9237 ("<escape>" . "ESC")
9238 ("<delete>" . "DEL")))
9239 (setq binding (read-kbd-macro
9240 (let ((case-fold-search))
9241 (replace-regexp-in-string
9242 (regexp-quote (cdr rep))
9243 (car rep)
9244 (key-description binding)))))
9245 (cl-pushnew binding new-bindings :test 'equal)))
9246 (dolist (binding new-bindings)
9247 (let ((key (lookup-key orgstruct-mode-map binding)))
9248 (when (or (not key) (numberp key))
9249 (ignore-errors
9250 (org-defkey orgstruct-mode-map
9251 binding
9252 (orgstruct-make-binding
9253 f binding disable-when-heading-prefix))))))))))
9254 (run-hooks 'orgstruct-setup-hook))
9256 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9257 "Create a function for binding in the structure minor mode.
9258 FUN is the command to call inside a table. KEY is the key that
9259 should be checked in for a command to execute outside of tables.
9260 Non-nil `disable-when-heading-prefix' means to disable the command
9261 if `orgstruct-heading-prefix-regexp' is not empty."
9262 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9263 (let ((nname name)
9264 (i 0))
9265 (while (fboundp (intern nname))
9266 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9267 (setq name (intern nname)))
9268 (eval
9269 (let ((bindings '((org-heading-regexp
9270 (concat "^"
9271 orgstruct-heading-prefix-regexp
9272 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9273 (org-outline-regexp
9274 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9275 (org-outline-regexp-bol
9276 (concat "^" org-outline-regexp))
9277 (outline-regexp org-outline-regexp)
9278 (outline-heading-end-regexp "\n")
9279 (outline-level 'org-outline-level)
9280 (outline-heading-alist))))
9281 `(defun ,name (arg)
9282 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9283 "Outside of structure, run the binding of `"
9284 (key-description key) "'."
9285 (when disable-when-heading-prefix
9286 (concat
9287 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9288 "back to the default binding due to limitations of Org's implementation of\n"
9289 "`" (symbol-name fun) "'.")))
9290 (interactive "p")
9291 (let* ((disable
9292 ,(and disable-when-heading-prefix
9293 '(not (string= orgstruct-heading-prefix-regexp ""))))
9294 (fallback
9295 (or disable
9296 (not
9297 (let* ,bindings
9298 (org-context-p 'headline 'item
9299 ,(when (memq fun
9300 '(org-insert-heading
9301 org-insert-heading-respect-content
9302 org-meta-return))
9303 '(when orgstruct-is-++
9304 'item-body))))))))
9305 (if fallback
9306 (let* ((orgstruct-mode)
9307 (binding
9308 (let ((key ,key))
9309 (catch 'exit
9310 (dolist
9311 (rep
9312 '(nil
9313 ("<\\([^>]*\\)tab>" . "\\1TAB")
9314 ("<\\([^>]*\\)return>" . "\\1RET")
9315 ("<\\([^>]*\\)escape>" . "\\1ESC")
9316 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9317 nil)
9318 (when rep
9319 (setq key (read-kbd-macro
9320 (let ((case-fold-search))
9321 (replace-regexp-in-string
9322 (car rep)
9323 (cdr rep)
9324 (key-description key))))))
9325 (when (key-binding key)
9326 (throw 'exit (key-binding key))))))))
9327 (if (keymapp binding)
9328 (org-set-transient-map binding)
9329 (let ((func (or binding
9330 (unless disable
9331 'orgstruct-error))))
9332 (when func
9333 (call-interactively func)))))
9334 (org-run-like-in-org-mode
9335 (lambda ()
9336 (interactive)
9337 (let* ,bindings
9338 (call-interactively ',fun)))))))))
9339 name))
9341 (defun org-contextualize-keys (alist contexts)
9342 "Return valid elements in ALIST depending on CONTEXTS.
9344 `org-agenda-custom-commands' or `org-capture-templates' are the
9345 values used for ALIST, and `org-agenda-custom-commands-contexts'
9346 or `org-capture-templates-contexts' are the associated contexts
9347 definitions."
9348 (let ((contexts
9349 ;; normalize contexts
9350 (mapcar
9351 (lambda(c) (cond ((listp (cadr c))
9352 (list (car c) (car c) (nth 1 c)))
9353 ((string= "" (cadr c))
9354 (list (car c) (car c) (nth 2 c)))
9355 (t c)))
9356 contexts))
9357 (a alist) r s)
9358 ;; loop over all commands or templates
9359 (dolist (c a)
9360 (let (vrules repl)
9361 (cond
9362 ((not (assoc (car c) contexts))
9363 (push c r))
9364 ((and (assoc (car c) contexts)
9365 (setq vrules (org-contextualize-validate-key
9366 (car c) contexts)))
9367 (mapc (lambda (vr)
9368 (unless (equal (car vr) (cadr vr))
9369 (setq repl vr)))
9370 vrules)
9371 (if (not repl) (push c r)
9372 (push (cadr repl) s)
9373 (push
9374 (cons (car c)
9375 (cdr (or (assoc (cadr repl) alist)
9376 (error "Undefined key `%s' as contextual replacement for `%s'"
9377 (cadr repl) (car c)))))
9378 r))))))
9379 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9380 (delq
9382 (delete-dups
9383 (mapcar (lambda (x)
9384 (let ((tpl (car x)))
9385 (unless (delq
9387 (mapcar (lambda (y)
9388 (equal y tpl))
9390 x)))
9391 (reverse r))))))
9393 (defun org-contextualize-validate-key (key contexts)
9394 "Check CONTEXTS for agenda or capture KEY."
9395 (let (res)
9396 (dolist (r contexts)
9397 (dolist (rr (car (last r)))
9398 (when
9399 (and (equal key (car r))
9400 (if (functionp rr) (funcall rr)
9401 (or (and (eq (car rr) 'in-file)
9402 (buffer-file-name)
9403 (string-match (cdr rr) (buffer-file-name)))
9404 (and (eq (car rr) 'in-mode)
9405 (string-match (cdr rr) (symbol-name major-mode)))
9406 (and (eq (car rr) 'in-buffer)
9407 (string-match (cdr rr) (buffer-name)))
9408 (when (and (eq (car rr) 'not-in-file)
9409 (buffer-file-name))
9410 (not (string-match (cdr rr) (buffer-file-name))))
9411 (when (eq (car rr) 'not-in-mode)
9412 (not (string-match (cdr rr) (symbol-name major-mode))))
9413 (when (eq (car rr) 'not-in-buffer)
9414 (not (string-match (cdr rr) (buffer-name)))))))
9415 (push r res))))
9416 (delete-dups (delq nil res))))
9418 (defun org-context-p (&rest contexts)
9419 "Check if local context is any of CONTEXTS.
9420 Possible values in the list of contexts are `table', `headline', and `item'."
9421 (let ((pos (point)))
9422 (goto-char (point-at-bol))
9423 (prog1 (or (and (memq 'table contexts)
9424 (looking-at "[ \t]*|"))
9425 (and (memq 'headline contexts)
9426 (looking-at org-outline-regexp))
9427 (and (memq 'item contexts)
9428 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9429 (and (memq 'item-body contexts)
9430 (org-in-item-p)))
9431 (goto-char pos))))
9433 (defconst org-unique-local-variables
9434 '(org-element--cache
9435 org-element--cache-objects
9436 org-element--cache-sync-keys
9437 org-element--cache-sync-requests
9438 org-element--cache-sync-timer)
9439 "List of local variables that cannot be transferred to another buffer.")
9441 (defun org-get-local-variables ()
9442 "Return a list of all local variables in an Org mode buffer."
9443 (delq nil
9444 (mapcar
9445 (lambda (x)
9446 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9447 (name (car binding)))
9448 (and (not (get name 'org-state))
9449 (not (memq name org-unique-local-variables))
9450 (string-match-p
9451 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9452 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9453 (symbol-name name))
9454 binding)))
9455 (with-temp-buffer
9456 (org-mode)
9457 (buffer-local-variables)))))
9459 (defun org-clone-local-variables (from-buffer &optional regexp)
9460 "Clone local variables from FROM-BUFFER.
9461 Optional argument REGEXP selects variables to clone."
9462 (dolist (pair (buffer-local-variables from-buffer))
9463 (pcase pair
9464 (`(,name . ,value) ;ignore unbound variables
9465 (when (and (not (memq name org-unique-local-variables))
9466 (or (null regexp) (string-match-p regexp (symbol-name name))))
9467 (set (make-local-variable name) value))))))
9469 ;;;###autoload
9470 (defun org-run-like-in-org-mode (cmd)
9471 "Run a command, pretending that the current buffer is in Org mode.
9472 This will temporarily bind local variables that are typically bound in
9473 Org mode to the values they have in Org mode, and then interactively
9474 call CMD."
9475 (org-load-modules-maybe)
9476 (unless org-local-vars
9477 (setq org-local-vars (org-get-local-variables)))
9478 (let (binds)
9479 (dolist (var org-local-vars)
9480 (when (or (not (boundp (car var)))
9481 (eq (symbol-value (car var))
9482 (default-value (car var))))
9483 (push (list (car var) `(quote ,(cadr var))) binds)))
9484 (eval `(let ,binds
9485 (call-interactively (quote ,cmd))))))
9487 (defun org-get-category (&optional pos force-refresh)
9488 "Get the category applying to position POS."
9489 (save-match-data
9490 (when force-refresh (org-refresh-category-properties))
9491 (let ((pos (or pos (point))))
9492 (or (get-text-property pos 'org-category)
9493 (progn (org-refresh-category-properties)
9494 (get-text-property pos 'org-category))))))
9496 ;;; Refresh properties
9498 (defun org-refresh-properties (dprop tprop)
9499 "Refresh buffer text properties.
9500 DPROP is the drawer property and TPROP is either the
9501 corresponding text property to set, or an alist with each element
9502 being a text property (as a symbol) and a function to apply to
9503 the value of the drawer property."
9504 (let* ((case-fold-search t)
9505 (inhibit-read-only t)
9506 (inherit? (org-property-inherit-p dprop))
9507 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9508 (global (and inherit? (org--property-global-value dprop nil))))
9509 (org-with-silent-modifications
9510 (org-with-point-at 1
9511 ;; Set global values (e.g., values defined through
9512 ;; "#+PROPERTY:" keywords) to the whole buffer.
9513 (when global (put-text-property (point-min) (point-max) tprop global))
9514 ;; Set local values.
9515 (while (re-search-forward property-re nil t)
9516 (when (org-at-property-p)
9517 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9518 (outline-next-heading))))))
9520 (defun org-refresh-property (tprop p &optional inherit)
9521 "Refresh the buffer text property TPROP from the drawer property P.
9522 The refresh happens only for the current headline, or the whole
9523 sub-tree if optional argument INHERIT is non-nil."
9524 (unless (org-before-first-heading-p)
9525 (save-excursion
9526 (org-back-to-heading t)
9527 (let ((start (point))
9528 (end (save-excursion
9529 (if inherit (org-end-of-subtree t t)
9530 (or (outline-next-heading) (point-max))))))
9531 (if (symbolp tprop)
9532 ;; TPROP is a text property symbol.
9533 (put-text-property start end tprop p)
9534 ;; TPROP is an alist with (property . function) elements.
9535 (pcase-dolist (`(,prop . ,f) tprop)
9536 (put-text-property start end prop (funcall f p))))))))
9538 (defun org-refresh-category-properties ()
9539 "Refresh category text properties in the buffer."
9540 (let ((case-fold-search t)
9541 (inhibit-read-only t)
9542 (default-category
9543 (cond ((null org-category)
9544 (if buffer-file-name
9545 (file-name-sans-extension
9546 (file-name-nondirectory buffer-file-name))
9547 "???"))
9548 ((symbolp org-category) (symbol-name org-category))
9549 (t org-category))))
9550 (org-with-silent-modifications
9551 (org-with-wide-buffer
9552 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9553 ;; This is the default category for the buffer. If none is
9554 ;; found, fall-back to `org-category' or buffer file name.
9555 (put-text-property
9556 (point-min) (point-max)
9557 'org-category
9558 (catch 'buffer-category
9559 (goto-char (point-max))
9560 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9561 (let ((element (org-element-at-point)))
9562 (when (eq (org-element-type element) 'keyword)
9563 (throw 'buffer-category
9564 (org-element-property :value element)))))
9565 default-category))
9566 ;; Set sub-tree specific categories.
9567 (goto-char (point-min))
9568 (let ((regexp (org-re-property "CATEGORY")))
9569 (while (re-search-forward regexp nil t)
9570 (let ((value (match-string-no-properties 3)))
9571 (when (org-at-property-p)
9572 (put-text-property
9573 (save-excursion (org-back-to-heading t) (point))
9574 (save-excursion (org-end-of-subtree t t) (point))
9575 'org-category
9576 value)))))))))
9578 (defun org-refresh-stats-properties ()
9579 "Refresh stats text properties in the buffer."
9580 (org-with-silent-modifications
9581 (org-with-point-at 1
9582 (let ((regexp (concat org-outline-regexp-bol
9583 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9584 (while (re-search-forward regexp nil t)
9585 (let* ((numerator (string-to-number (match-string 1)))
9586 (denominator (and (match-end 2)
9587 (string-to-number (match-string 2))))
9588 (stats (cond ((not denominator) numerator) ;percent
9589 ((= denominator 0) 0)
9590 (t (/ (* numerator 100) denominator)))))
9591 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9592 'org-stats stats)))))))
9594 (defun org-refresh-effort-properties ()
9595 "Refresh effort properties"
9596 (org-refresh-properties
9597 org-effort-property
9598 '((effort . identity)
9599 (effort-minutes . org-duration-to-minutes))))
9601 ;;;; Link Stuff
9603 ;;; Link abbreviations
9605 (defun org-link-expand-abbrev (link)
9606 "Apply replacements as defined in `org-link-abbrev-alist'."
9607 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9608 (let* ((key (match-string 1 link))
9609 (as (or (assoc key org-link-abbrev-alist-local)
9610 (assoc key org-link-abbrev-alist)))
9611 (tag (and (match-end 2) (match-string 3 link)))
9612 rpl)
9613 (if (not as)
9614 link
9615 (setq rpl (cdr as))
9616 (cond
9617 ((symbolp rpl) (funcall rpl tag))
9618 ((string-match "%(\\([^)]+\\))" rpl)
9619 (replace-match
9620 (save-match-data
9621 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9622 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9623 ((string-match "%h" rpl)
9624 (replace-match (url-hexify-string (or tag "")) t t rpl))
9625 (t (concat rpl tag)))))
9626 link))
9628 ;;; Storing and inserting links
9630 (defvar org-insert-link-history nil
9631 "Minibuffer history for links inserted with `org-insert-link'.")
9633 (defvar org-stored-links nil
9634 "Contains the links stored with `org-store-link'.")
9636 (defvar org-store-link-plist nil
9637 "Plist with info about the most recently link created with `org-store-link'.")
9639 (defun org-store-link-functions ()
9640 "Return a list of functions that are called to create and store a link.
9641 The functions defined in the :store property of
9642 `org-link-parameters'.
9644 Each function will be called in turn until one returns a non-nil
9645 value. Each function should check if it is responsible for
9646 creating this link (for example by looking at the major mode).
9647 If not, it must exit and return nil. If yes, it should return
9648 a non-nil value after calling `org-store-link-props' with a list
9649 of properties and values. Special properties are:
9651 :type The link prefix, like \"http\". This must be given.
9652 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9653 This is obligatory as well.
9654 :description Optional default description for the second pair
9655 of brackets in an Org mode link. The user can still change
9656 this when inserting this link into an Org mode buffer.
9658 In addition to these, any additional properties can be specified
9659 and then used in capture templates."
9660 (cl-loop for link in org-link-parameters
9661 with store-func
9662 do (setq store-func (org-link-get-parameter (car link) :store))
9663 if store-func
9664 collect store-func))
9666 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9667 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9669 ;;;###autoload
9670 (defun org-store-link (arg)
9671 "Store an org-link to the current location.
9672 \\<org-mode-map>
9673 This link is added to `org-stored-links' and can later be inserted
9674 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9676 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9677 A single
9678 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9679 `org-gnus-prefer-web-links' for links to Usenet articles.
9681 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9682 skipping storing functions that are not
9683 part of Org core.
9685 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9686 prefix ARG forces storing a link for each line in the
9687 active region."
9688 (interactive "P")
9689 (org-load-modules-maybe)
9690 (if (and (equal arg '(64)) (org-region-active-p))
9691 (save-excursion
9692 (let ((end (region-end)))
9693 (goto-char (region-beginning))
9694 (set-mark (point))
9695 (while (< (point-at-eol) end)
9696 (move-end-of-line 1) (activate-mark)
9697 (let (current-prefix-arg)
9698 (call-interactively 'org-store-link))
9699 (move-beginning-of-line 2)
9700 (set-mark (point)))))
9701 (setq org-store-link-plist nil)
9702 (let (link cpltxt desc description search
9703 txt custom-id agenda-link sfuns sfunsn)
9704 (cond
9706 ;; Store a link using an external link type
9707 ((and (not (equal arg '(16)))
9708 (setq sfuns
9709 (delq
9710 nil (mapcar (lambda (f)
9711 (let (fs) (if (funcall f) (push f fs))))
9712 (org-store-link-functions)))
9713 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9714 (or (and (cdr sfuns)
9715 (funcall (intern
9716 (completing-read
9717 "Which function for creating the link? "
9718 sfunsn nil t (car sfunsn)))))
9719 (funcall (caar sfuns)))
9720 (setq link (plist-get org-store-link-plist :link)
9721 desc (or (plist-get org-store-link-plist
9722 :description)
9723 link))))
9725 ;; Store a link from a source code buffer.
9726 ((org-src-edit-buffer-p)
9727 (let ((coderef-format (org-src-coderef-format)))
9728 (cond ((save-excursion
9729 (beginning-of-line)
9730 (looking-at (org-src-coderef-regexp coderef-format)))
9731 (setq link (format "(%s)" (match-string-no-properties 3))))
9732 ((called-interactively-p 'any)
9733 (let ((label (read-string "Code line label: ")))
9734 (end-of-line)
9735 (setq link (format coderef-format label))
9736 (let ((gc (- 79 (length link))))
9737 (if (< (current-column) gc)
9738 (org-move-to-column gc t)
9739 (insert " ")))
9740 (insert link)
9741 (setq link (concat "(" label ")"))
9742 (setq desc nil)))
9743 (t (setq link nil)))))
9745 ;; We are in the agenda, link to referenced location
9746 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9747 (let ((m (or (get-text-property (point) 'org-hd-marker)
9748 (get-text-property (point) 'org-marker))))
9749 (when m
9750 (org-with-point-at m
9751 (setq agenda-link
9752 (if (called-interactively-p 'any)
9753 (call-interactively 'org-store-link)
9754 (org-store-link nil)))))))
9756 ((eq major-mode 'calendar-mode)
9757 (let ((cd (calendar-cursor-to-date)))
9758 (setq link
9759 (format-time-string
9760 (car org-time-stamp-formats)
9761 (apply 'encode-time
9762 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9763 nil nil nil))))
9764 (org-store-link-props :type "calendar" :date cd)))
9766 ((eq major-mode 'help-mode)
9767 (setq link (concat "help:" (save-excursion
9768 (goto-char (point-min))
9769 (looking-at "^[^ ]+")
9770 (match-string 0))))
9771 (org-store-link-props :type "help"))
9773 ((eq major-mode 'w3-mode)
9774 (setq cpltxt (if (and (buffer-name)
9775 (not (string-match "Untitled" (buffer-name))))
9776 (buffer-name)
9777 (url-view-url t))
9778 link (url-view-url t))
9779 (org-store-link-props :type "w3" :url (url-view-url t)))
9781 ((eq major-mode 'image-mode)
9782 (setq cpltxt (concat "file:"
9783 (abbreviate-file-name buffer-file-name))
9784 link cpltxt)
9785 (org-store-link-props :type "image" :file buffer-file-name))
9787 ;; In dired, store a link to the file of the current line
9788 ((derived-mode-p 'dired-mode)
9789 (let ((file (dired-get-filename nil t)))
9790 (setq file (if file
9791 (abbreviate-file-name
9792 (expand-file-name (dired-get-filename nil t)))
9793 ;; otherwise, no file so use current directory.
9794 default-directory))
9795 (setq cpltxt (concat "file:" file)
9796 link cpltxt)))
9798 ((setq search (run-hook-with-args-until-success
9799 'org-create-file-search-functions))
9800 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9801 "::" search))
9802 (setq cpltxt (or description link)))
9804 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9805 (org-with-limited-levels
9806 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9807 (cond
9808 ;; Store a link using the target at point
9809 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9810 (setq cpltxt
9811 (concat "file:"
9812 (abbreviate-file-name
9813 (buffer-file-name (buffer-base-buffer)))
9814 "::" (match-string 1))
9815 link cpltxt))
9816 ((and (featurep 'org-id)
9817 (or (eq org-id-link-to-org-use-id t)
9818 (and (called-interactively-p 'any)
9819 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9820 (and (eq org-id-link-to-org-use-id
9821 'create-if-interactive-and-no-custom-id)
9822 (not custom-id))))
9823 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9824 ;; Store a link using the ID at point
9825 (setq link (condition-case nil
9826 (prog1 (org-id-store-link)
9827 (setq desc (or (plist-get org-store-link-plist
9828 :description)
9829 "")))
9830 (error
9831 ;; Probably before first headline, link only to file
9832 (concat "file:"
9833 (abbreviate-file-name
9834 (buffer-file-name (buffer-base-buffer))))))))
9836 ;; Just link to current headline
9837 (setq cpltxt (concat "file:"
9838 (abbreviate-file-name
9839 (buffer-file-name (buffer-base-buffer)))))
9840 ;; Add a context search string
9841 (when (org-xor org-context-in-file-links
9842 (equal arg '(4)))
9843 (let* ((element (org-element-at-point))
9844 (name (org-element-property :name element)))
9845 (setq txt (cond
9846 ((org-at-heading-p) nil)
9847 (name)
9848 ((org-region-active-p)
9849 (buffer-substring (region-beginning) (region-end)))))
9850 (when (or (null txt) (string-match "\\S-" txt))
9851 (setq cpltxt
9852 (concat cpltxt "::"
9853 (condition-case nil
9854 (org-make-org-heading-search-string txt)
9855 (error "")))
9856 desc (or name
9857 (nth 4 (ignore-errors (org-heading-components)))
9858 "NONE")))))
9859 (when (string-match "::\\'" cpltxt)
9860 (setq cpltxt (substring cpltxt 0 -2)))
9861 (setq link cpltxt)))))
9863 ((buffer-file-name (buffer-base-buffer))
9864 ;; Just link to this file here.
9865 (setq cpltxt (concat "file:"
9866 (abbreviate-file-name
9867 (buffer-file-name (buffer-base-buffer)))))
9868 ;; Add a context string.
9869 (when (org-xor org-context-in-file-links
9870 (equal arg '(4)))
9871 (setq txt (if (org-region-active-p)
9872 (buffer-substring (region-beginning) (region-end))
9873 (buffer-substring (point-at-bol) (point-at-eol))))
9874 ;; Only use search option if there is some text.
9875 (when (string-match "\\S-" txt)
9876 (setq cpltxt
9877 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9878 desc "NONE")))
9879 (setq link cpltxt))
9881 ((called-interactively-p 'interactive)
9882 (user-error "No method for storing a link from this buffer"))
9884 (t (setq link nil)))
9886 ;; We're done setting link and desc, clean up
9887 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9888 (setq link (or link cpltxt)
9889 desc (or desc cpltxt))
9890 (cond ((not desc))
9891 ((equal desc "NONE") (setq desc nil))
9892 (t (setq desc
9893 (replace-regexp-in-string
9894 org-bracket-link-analytic-regexp
9895 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9896 desc))))
9897 ;; Return the link
9898 (if (not (and (or (called-interactively-p 'any)
9899 executing-kbd-macro)
9900 link))
9901 (or agenda-link (and link (org-make-link-string link desc)))
9902 (push (list link desc) org-stored-links)
9903 (message "Stored: %s" (or desc link))
9904 (when custom-id
9905 (setq link (concat "file:" (abbreviate-file-name
9906 (buffer-file-name)) "::#" custom-id))
9907 (push (list link desc) org-stored-links))
9908 (car org-stored-links)))))
9910 (defun org-store-link-props (&rest plist)
9911 "Store link properties, extract names, addresses and dates."
9912 (let ((x (plist-get plist :from)))
9913 (when x
9914 (let ((adr (mail-extract-address-components x)))
9915 (setq plist (plist-put plist :fromname (car adr)))
9916 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9917 (let ((x (plist-get plist :to)))
9918 (when x
9919 (let ((adr (mail-extract-address-components x)))
9920 (setq plist (plist-put plist :toname (car adr)))
9921 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9922 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9923 (when x
9924 (setq plist (plist-put plist :date-timestamp
9925 (format-time-string
9926 (org-time-stamp-format t) x)))
9927 (setq plist (plist-put plist :date-timestamp-inactive
9928 (format-time-string
9929 (org-time-stamp-format t t) x)))))
9930 (let ((from (plist-get plist :from))
9931 (to (plist-get plist :to)))
9932 (when (and from to org-from-is-user-regexp)
9933 (setq plist
9934 (plist-put plist :fromto
9935 (if (string-match org-from-is-user-regexp from)
9936 (concat "to %t")
9937 (concat "from %f"))))))
9938 (setq org-store-link-plist plist))
9940 (defun org-add-link-props (&rest plist)
9941 "Add these properties to the link property list."
9942 (let (key value)
9943 (while plist
9944 (setq key (pop plist) value (pop plist))
9945 (setq org-store-link-plist
9946 (plist-put org-store-link-plist key value)))))
9948 (defun org-email-link-description (&optional fmt)
9949 "Return the description part of an email link.
9950 This takes information from `org-store-link-plist' and formats it
9951 according to FMT (default from `org-email-link-description-format')."
9952 (setq fmt (or fmt org-email-link-description-format))
9953 (let* ((p org-store-link-plist)
9954 (to (plist-get p :toaddress))
9955 (from (plist-get p :fromaddress))
9956 (table
9957 (list
9958 (cons "%c" (plist-get p :fromto))
9959 (cons "%F" (plist-get p :from))
9960 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9961 (cons "%T" (plist-get p :to))
9962 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9963 (cons "%s" (plist-get p :subject))
9964 (cons "%d" (plist-get p :date))
9965 (cons "%m" (plist-get p :message-id)))))
9966 (when (string-match "%c" fmt)
9967 ;; Check if the user wrote this message
9968 (if (and org-from-is-user-regexp from to
9969 (save-match-data (string-match org-from-is-user-regexp from)))
9970 (setq fmt (replace-match "to %t" t t fmt))
9971 (setq fmt (replace-match "from %f" t t fmt))))
9972 (org-replace-escapes fmt table)))
9974 (defun org-make-org-heading-search-string (&optional string)
9975 "Make search string for the current headline or STRING."
9976 (let ((s (or string
9977 (and (derived-mode-p 'org-mode)
9978 (save-excursion
9979 (org-back-to-heading t)
9980 (org-element-property :raw-value (org-element-at-point))))))
9981 (lines org-context-in-file-links))
9982 (or string (setq s (concat "*" s))) ; Add * for headlines
9983 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9984 (when (and string (integerp lines) (> lines 0))
9985 (let ((slines (org-split-string s "\n")))
9986 (when (< lines (length slines))
9987 (setq s (mapconcat
9988 'identity
9989 (reverse (nthcdr (- (length slines) lines)
9990 (reverse slines))) "\n")))))
9991 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9993 (defun org-make-link-string (link &optional description)
9994 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9995 (unless (org-string-nw-p link) (error "Empty link"))
9996 (let ((uri (cond ((string-match org-link-types-re link)
9997 (concat (match-string 1 link)
9998 (org-link-escape (substring link (match-end 1)))))
9999 ;; For readability, url-encode internal links only
10000 ;; when absolutely needed (i.e, when they contain
10001 ;; square brackets). File links however, are
10002 ;; encoded since, e.g., spaces are significant.
10003 ((or (file-name-absolute-p link)
10004 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10005 (org-link-escape link))
10006 (t link)))
10007 (description
10008 (and (org-string-nw-p description)
10009 ;; Remove brackets from description, as they are fatal.
10010 (replace-regexp-in-string
10011 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10012 (org-trim description)))))
10013 (format "[[%s]%s]"
10015 (if description (format "[%s]" description) ""))))
10017 (defconst org-link-escape-chars
10018 ;;%20 %5B %5D %25
10019 '(?\s ?\[ ?\] ?%)
10020 "List of characters that should be escaped in a link when stored to Org.
10021 This is the list that is used for internal purposes.")
10023 (defun org-link-escape (text &optional table merge)
10024 "Return percent escaped representation of TEXT.
10025 TEXT is a string with the text to escape.
10026 Optional argument TABLE is a list with characters that should be
10027 escaped. When nil, `org-link-escape-chars' is used.
10028 If optional argument MERGE is set, merge TABLE into
10029 `org-link-escape-chars'."
10030 (let ((characters-to-encode
10031 (cond ((null table) org-link-escape-chars)
10032 (merge (append org-link-escape-chars table))
10033 (t table))))
10034 (mapconcat
10035 (lambda (c)
10036 (if (or (memq c characters-to-encode)
10037 (and org-url-hexify-p (or (< c 32) (> c 126))))
10038 (mapconcat (lambda (e) (format "%%%.2X" e))
10039 (or (encode-coding-char c 'utf-8)
10040 (error "Unable to percent escape character: %c" c))
10042 (char-to-string c)))
10043 text "")))
10045 (defun org-link-unescape (str)
10046 "Unhex hexified Unicode parts in string STR.
10047 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10048 reciprocal of `org-link-escape', which see."
10049 (if (org-string-nw-p str)
10050 (replace-regexp-in-string
10051 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10052 str))
10054 (defun org-link-unescape-compound (hex)
10055 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10056 Note: this function also decodes single byte encodings like
10057 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10058 (save-match-data
10059 (let* ((bytes (cdr (split-string hex "%")))
10060 (ret "")
10061 (eat 0)
10062 (sum 0))
10063 (while bytes
10064 (let* ((val (string-to-number (pop bytes) 16))
10065 (shift-xor
10066 (if (= 0 eat)
10067 (cond
10068 ((>= val 252) (cons 6 252))
10069 ((>= val 248) (cons 5 248))
10070 ((>= val 240) (cons 4 240))
10071 ((>= val 224) (cons 3 224))
10072 ((>= val 192) (cons 2 192))
10073 (t (cons 0 0)))
10074 (cons 6 128))))
10075 (when (>= val 192) (setq eat (car shift-xor)))
10076 (setq val (logxor val (cdr shift-xor)))
10077 (setq sum (+ (lsh sum (car shift-xor)) val))
10078 (when (> eat 0) (setq eat (- eat 1)))
10079 (cond
10080 ((= 0 eat) ;multi byte
10081 (setq ret (concat ret (char-to-string sum)))
10082 (setq sum 0))
10083 ((not bytes) ; single byte(s)
10084 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10085 ret)))
10087 (defun org-link-unescape-single-byte-sequence (hex)
10088 "Unhexify hex-encoded single byte character sequences."
10089 (mapconcat (lambda (byte)
10090 (char-to-string (string-to-number byte 16)))
10091 (cdr (split-string hex "%")) ""))
10093 (defun org-xor (a b)
10094 "Exclusive or."
10095 (if a (not b) b))
10097 (defun org-fixup-message-id-for-http (s)
10098 "Replace special characters in a message id, so it can be used in an http query."
10099 (when (string-match "%" s)
10100 (setq s (mapconcat (lambda (c)
10101 (if (eq c ?%)
10102 "%25"
10103 (char-to-string c)))
10104 s "")))
10105 (while (string-match "<" s)
10106 (setq s (replace-match "%3C" t t s)))
10107 (while (string-match ">" s)
10108 (setq s (replace-match "%3E" t t s)))
10109 (while (string-match "@" s)
10110 (setq s (replace-match "%40" t t s)))
10113 (defun org-link-prettify (link)
10114 "Return a human-readable representation of LINK.
10115 The car of LINK must be a raw link.
10116 The cdr of LINK must be either a link description or nil."
10117 (let ((desc (or (cadr link) "<no description>")))
10118 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10119 "<" (car link) ">")))
10121 ;;;###autoload
10122 (defun org-insert-link-global ()
10123 "Insert a link like Org mode does.
10124 This command can be called in any mode to insert a link in Org syntax."
10125 (interactive)
10126 (org-load-modules-maybe)
10127 (org-run-like-in-org-mode 'org-insert-link))
10129 (defun org-insert-all-links (arg &optional pre post)
10130 "Insert all links in `org-stored-links'.
10131 When a universal prefix, do not delete the links from `org-stored-links'.
10132 When `ARG' is a number, insert the last N link(s).
10133 `PRE' and `POST' are optional arguments to define a string to
10134 prepend or to append."
10135 (interactive "P")
10136 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10137 (links (copy-sequence org-stored-links))
10138 (pr (or pre "- "))
10139 (po (or post "\n"))
10140 (cnt 1) l)
10141 (if (null org-stored-links)
10142 (message "No link to insert")
10143 (while (and (or (listp arg) (>= arg cnt))
10144 (setq l (if (listp arg)
10145 (pop links)
10146 (pop org-stored-links))))
10147 (setq cnt (1+ cnt))
10148 (insert pr)
10149 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10150 (insert po)))))
10152 (defun org-insert-last-stored-link (arg)
10153 "Insert the last link stored in `org-stored-links'."
10154 (interactive "p")
10155 (org-insert-all-links arg "" "\n"))
10157 (defun org-link-fontify-links-to-this-file ()
10158 "Fontify links to the current file in `org-stored-links'."
10159 (let ((f (buffer-file-name)) a b)
10160 (setq a (mapcar (lambda(l)
10161 (let ((ll (car l)))
10162 (when (and (string-match "^file:\\(.+\\)::" ll)
10163 (equal f (expand-file-name (match-string 1 ll))))
10164 ll)))
10165 org-stored-links))
10166 (when (featurep 'org-id)
10167 (setq b (mapcar (lambda(l)
10168 (let ((ll (car l)))
10169 (when (and (string-match "^id:\\(.+\\)$" ll)
10170 (equal f (expand-file-name
10171 (or (org-id-find-id-file
10172 (match-string 1 ll)) ""))))
10173 ll)))
10174 org-stored-links)))
10175 (mapcar (lambda(l)
10176 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10177 (delq nil (append a b)))))
10179 (defvar org--links-history nil)
10180 (defun org-insert-link (&optional complete-file link-location default-description)
10181 "Insert a link. At the prompt, enter the link.
10183 Completion can be used to insert any of the link protocol prefixes in use.
10185 The history can be used to select a link previously stored with
10186 `org-store-link'. When the empty string is entered (i.e. if you just
10187 press `RET' at the prompt), the link defaults to the most recently
10188 stored link. As `SPC' triggers completion in the minibuffer, you need to
10189 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10191 You will also be prompted for a description, and if one is given, it will
10192 be displayed in the buffer instead of the link.
10194 If there is already a link at point, this command will allow you to edit
10195 link and description parts.
10197 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10198 file name can be
10199 selected using completion. The path to the file will be relative to the
10200 current directory if the file is in the current directory or a subdirectory.
10201 Otherwise, the link will be the absolute path as completed in the minibuffer
10202 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10203 option `org-link-file-path-type'.
10205 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10206 absolute path even if the file is in
10207 the current directory or below.
10209 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10210 prefix negates `org-keep-stored-link-after-insertion'.
10212 If `org-make-link-description-function' is non-nil, this function will be
10213 called with the link target, and the result will be the default
10214 link description.
10216 If the LINK-LOCATION parameter is non-nil, this value will be used as
10217 the link location instead of reading one interactively.
10219 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10220 as the default description."
10221 (interactive "P")
10222 (let* ((wcf (current-window-configuration))
10223 (origbuf (current-buffer))
10224 (region (when (org-region-active-p)
10225 (buffer-substring (region-beginning) (region-end))))
10226 (remove (and region (list (region-beginning) (region-end))))
10227 (desc region)
10228 (link link-location)
10229 (abbrevs org-link-abbrev-alist-local)
10230 entry all-prefixes auto-desc)
10231 (cond
10232 (link-location) ; specified by arg, just use it.
10233 ((org-in-regexp org-bracket-link-regexp 1)
10234 ;; We do have a link at point, and we are going to edit it.
10235 (setq remove (list (match-beginning 0) (match-end 0)))
10236 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10237 (setq link (read-string "Link: "
10238 (org-link-unescape
10239 (match-string-no-properties 1)))))
10240 ((or (org-in-regexp org-angle-link-re)
10241 (org-in-regexp org-plain-link-re))
10242 ;; Convert to bracket link
10243 (setq remove (list (match-beginning 0) (match-end 0))
10244 link (read-string "Link: "
10245 (org-unbracket-string "<" ">" (match-string 0)))))
10246 ((member complete-file '((4) (16)))
10247 ;; Completing read for file names.
10248 (setq link (org-file-complete-link complete-file)))
10250 ;; Read link, with completion for stored links.
10251 (org-link-fontify-links-to-this-file)
10252 (org-switch-to-buffer-other-window "*Org Links*")
10253 (with-current-buffer "*Org Links*"
10254 (erase-buffer)
10255 (insert "Insert a link.
10256 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10257 (when org-stored-links
10258 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10259 (insert (mapconcat 'org-link-prettify
10260 (reverse org-stored-links) "\n")))
10261 (goto-char (point-min)))
10262 (let ((cw (selected-window)))
10263 (select-window (get-buffer-window "*Org Links*" 'visible))
10264 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10265 (unless (pos-visible-in-window-p (point-max))
10266 (org-fit-window-to-buffer))
10267 (and (window-live-p cw) (select-window cw)))
10268 (setq all-prefixes (append (mapcar 'car abbrevs)
10269 (mapcar 'car org-link-abbrev-alist)
10270 (org-link-types)))
10271 (unwind-protect
10272 ;; Fake a link history, containing the stored links.
10273 (let ((org--links-history
10274 (append (mapcar #'car org-stored-links)
10275 org-insert-link-history)))
10276 (setq link
10277 (org-completing-read
10278 "Link: "
10279 (append
10280 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10281 (mapcar #'car org-stored-links))
10282 nil nil nil
10283 'org--links-history
10284 (caar org-stored-links)))
10285 (unless (org-string-nw-p link) (user-error "No link selected"))
10286 (dolist (l org-stored-links)
10287 (when (equal link (cadr l))
10288 (setq link (car l))
10289 (setq auto-desc t)))
10290 (when (or (member link all-prefixes)
10291 (and (equal ":" (substring link -1))
10292 (member (substring link 0 -1) all-prefixes)
10293 (setq link (substring link 0 -1))))
10294 (setq link (with-current-buffer origbuf
10295 (org-link-try-special-completion link)))))
10296 (set-window-configuration wcf)
10297 (kill-buffer "*Org Links*"))
10298 (setq entry (assoc link org-stored-links))
10299 (or entry (push link org-insert-link-history))
10300 (setq desc (or desc (nth 1 entry)))))
10302 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10303 (not org-keep-stored-link-after-insertion))
10304 (setq org-stored-links (delq (assoc link org-stored-links)
10305 org-stored-links)))
10307 (when (and (string-match org-plain-link-re link)
10308 (not (string-match org-ts-regexp link)))
10309 ;; URL-like link, normalize the use of angular brackets.
10310 (setq link (org-unbracket-string "<" ">" link)))
10312 ;; Check if we are linking to the current file with a search
10313 ;; option If yes, simplify the link by using only the search
10314 ;; option.
10315 (when (and buffer-file-name
10316 (let ((case-fold-search nil))
10317 (string-match "\\`file:\\(.+?\\)::" link)))
10318 (let ((path (match-string-no-properties 1 link))
10319 (search (substring-no-properties link (match-end 0))))
10320 (save-match-data
10321 (when (equal (file-truename buffer-file-name) (file-truename path))
10322 ;; We are linking to this same file, with a search option
10323 (setq link search)))))
10325 ;; Check if we can/should use a relative path. If yes, simplify the link
10326 (let ((case-fold-search nil))
10327 (when (string-match "\\`\\(file\\|docview\\):" link)
10328 (let* ((type (match-string-no-properties 0 link))
10329 (path (substring-no-properties link (match-end 0)))
10330 (origpath path))
10331 (cond
10332 ((or (eq org-link-file-path-type 'absolute)
10333 (equal complete-file '(16)))
10334 (setq path (abbreviate-file-name (expand-file-name path))))
10335 ((eq org-link-file-path-type 'noabbrev)
10336 (setq path (expand-file-name path)))
10337 ((eq org-link-file-path-type 'relative)
10338 (setq path (file-relative-name path)))
10340 (save-match-data
10341 (if (string-match (concat "^" (regexp-quote
10342 (expand-file-name
10343 (file-name-as-directory
10344 default-directory))))
10345 (expand-file-name path))
10346 ;; We are linking a file with relative path name.
10347 (setq path (substring (expand-file-name path)
10348 (match-end 0)))
10349 (setq path (abbreviate-file-name (expand-file-name path)))))))
10350 (setq link (concat type path))
10351 (when (equal desc origpath)
10352 (setq desc path)))))
10354 (if org-make-link-description-function
10355 (setq desc
10356 (or (condition-case nil
10357 (funcall org-make-link-description-function link desc)
10358 (error (progn (message "Can't get link description from `%s'"
10359 (symbol-name org-make-link-description-function))
10360 (sit-for 2) nil)))
10361 (read-string "Description: " default-description)))
10362 (if default-description (setq desc default-description)
10363 (setq desc (or (and auto-desc desc)
10364 (read-string "Description: " desc)))))
10366 (unless (string-match "\\S-" desc) (setq desc nil))
10367 (when remove (apply 'delete-region remove))
10368 (insert (org-make-link-string link desc))
10369 ;; Redisplay so as the new link has proper invisible characters.
10370 (sit-for 0)))
10372 (defun org-link-try-special-completion (type)
10373 "If there is completion support for link type TYPE, offer it."
10374 (let ((fun (org-link-get-parameter type :complete)))
10375 (if (functionp fun)
10376 (funcall fun)
10377 (read-string "Link (no completion support): " (concat type ":")))))
10379 (defun org-file-complete-link (&optional arg)
10380 "Create a file link using completion."
10381 (let ((file (read-file-name "File: "))
10382 (pwd (file-name-as-directory (expand-file-name ".")))
10383 (pwd1 (file-name-as-directory (abbreviate-file-name
10384 (expand-file-name ".")))))
10385 (cond ((equal arg '(16))
10386 (concat "file:"
10387 (abbreviate-file-name (expand-file-name file))))
10388 ((string-match
10389 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10390 (concat "file:" (match-string 1 file)))
10391 ((string-match
10392 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10393 (expand-file-name file))
10394 (concat "file:"
10395 (match-string 1 (expand-file-name file))))
10396 (t (concat "file:" file)))))
10398 (defun org-completing-read (&rest args)
10399 "Completing-read with SPACE being a normal character."
10400 (let ((enable-recursive-minibuffers t)
10401 (minibuffer-local-completion-map
10402 (copy-keymap minibuffer-local-completion-map)))
10403 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10404 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10405 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10406 'org-time-stamp-inactive)
10407 (apply #'completing-read args)))
10409 ;;; Opening/following a link
10411 (defvar org-link-search-failed nil)
10413 (defvar org-open-link-functions nil
10414 "Hook for functions finding a plain text link.
10415 These functions must take a single argument, the link content.
10416 They will be called for links that look like [[link text][description]]
10417 when LINK TEXT does not have a protocol like \"http:\" and does not look
10418 like a filename (e.g. \"./blue.png\").
10420 These functions will be called *before* Org attempts to resolve the
10421 link by doing text searches in the current buffer - so if you want a
10422 link \"[[target]]\" to still find \"<<target>>\", your function should
10423 handle this as a special case.
10425 When the function does handle the link, it must return a non-nil value.
10426 If it decides that it is not responsible for this link, it must return
10427 nil to indicate that that Org can continue with other options like
10428 exact and fuzzy text search.")
10430 (defun org-next-link (&optional search-backward)
10431 "Move forward to the next link.
10432 If the link is in hidden text, expose it."
10433 (interactive "P")
10434 (when (and org-link-search-failed (eq this-command last-command))
10435 (goto-char (point-min))
10436 (message "Link search wrapped back to beginning of buffer"))
10437 (setq org-link-search-failed nil)
10438 (let* ((pos (point))
10439 (ct (org-context))
10440 (a (assq :link ct))
10441 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10442 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10443 ((looking-at org-any-link-re)
10444 ;; Don't stay stuck at link without an org-link face
10445 (forward-char (if search-backward -1 1))))
10446 (if (funcall srch-fun org-any-link-re nil t)
10447 (progn
10448 (goto-char (match-beginning 0))
10449 (when (org-invisible-p) (org-show-context)))
10450 (goto-char pos)
10451 (setq org-link-search-failed t)
10452 (message "No further link found"))))
10454 (defun org-previous-link ()
10455 "Move backward to the previous link.
10456 If the link is in hidden text, expose it."
10457 (interactive)
10458 (funcall 'org-next-link t))
10460 (defun org-translate-link (s)
10461 "Translate a link string if a translation function has been defined."
10462 (with-temp-buffer
10463 (insert (org-trim s))
10464 (org-trim (org-element-interpret-data (org-element-context)))))
10466 (defun org-translate-link-from-planner (type path)
10467 "Translate a link from Emacs Planner syntax so that Org can follow it.
10468 This is still an experimental function, your mileage may vary."
10469 (cond
10470 ((member type '("http" "https" "news" "ftp"))
10471 ;; standard Internet links are the same.
10472 nil)
10473 ((and (equal type "irc") (string-match "^//" path))
10474 ;; Planner has two / at the beginning of an irc link, we have 1.
10475 ;; We should have zero, actually....
10476 (setq path (substring path 1)))
10477 ((and (equal type "lisp") (string-match "^/" path))
10478 ;; Planner has a slash, we do not.
10479 (setq type "elisp" path (substring path 1)))
10480 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10481 ;; A typical message link. Planner has the id after the final slash,
10482 ;; we separate it with a hash mark
10483 (setq path (concat (match-string 1 path) "#"
10484 (org-unbracket-string "<" ">" (match-string 2 path))))))
10485 (cons type path))
10487 (defun org-find-file-at-mouse (ev)
10488 "Open file link or URL at mouse."
10489 (interactive "e")
10490 (mouse-set-point ev)
10491 (org-open-at-point 'in-emacs))
10493 (defun org-open-at-mouse (ev)
10494 "Open file link or URL at mouse.
10495 See the docstring of `org-open-file' for details."
10496 (interactive "e")
10497 (mouse-set-point ev)
10498 (when (eq major-mode 'org-agenda-mode)
10499 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10500 (org-open-at-point))
10502 (defvar org-window-config-before-follow-link nil
10503 "The window configuration before following a link.
10504 This is saved in case the need arises to restore it.")
10506 ;;;###autoload
10507 (defun org-open-at-point-global ()
10508 "Follow a link or time-stamp like Org mode does.
10509 This command can be called in any mode to follow an external link
10510 or a time-stamp that has Org mode syntax. Its behavior is
10511 undefined when called on internal links (e.g., fuzzy links).
10512 Raise an error when there is nothing to follow. "
10513 (interactive)
10514 (cond ((org-in-regexp org-any-link-re)
10515 (org-open-link-from-string (match-string-no-properties 0)))
10516 ((or (org-in-regexp org-ts-regexp-both nil t)
10517 (org-in-regexp org-tsr-regexp-both nil t))
10518 (org-follow-timestamp-link))
10519 (t (user-error "No link found"))))
10521 ;;;###autoload
10522 (defun org-open-link-from-string (s &optional arg reference-buffer)
10523 "Open a link in the string S, as if it was in Org mode."
10524 (interactive "sLink: \nP")
10525 (let ((reference-buffer (or reference-buffer (current-buffer))))
10526 (with-temp-buffer
10527 (let ((org-inhibit-startup (not reference-buffer)))
10528 (org-mode)
10529 (insert s)
10530 (goto-char (point-min))
10531 (when reference-buffer
10532 (setq org-link-abbrev-alist-local
10533 (with-current-buffer reference-buffer
10534 org-link-abbrev-alist-local)))
10535 (org-open-at-point arg reference-buffer)))))
10537 (defvar org-open-at-point-functions nil
10538 "Hook that is run when following a link at point.
10540 Functions in this hook must return t if they identify and follow
10541 a link at point. If they don't find anything interesting at point,
10542 they must return nil.")
10544 (defvar org-link-search-inhibit-query nil)
10545 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10546 (defun org--open-doi-link (path)
10547 "Open a \"doi\" type link.
10548 PATH is a the path to search for, as a string."
10549 (browse-url (url-encode-url (concat org-doi-server-url path))))
10551 (defun org--open-elisp-link (path)
10552 "Open a \"elisp\" type link.
10553 PATH is the sexp to evaluate, as a string."
10554 (let ((cmd path))
10555 (if (or (and (org-string-nw-p
10556 org-confirm-elisp-link-not-regexp)
10557 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10558 (not org-confirm-elisp-link-function)
10559 (funcall org-confirm-elisp-link-function
10560 (format "Execute \"%s\" as elisp? "
10561 (org-add-props cmd nil 'face 'org-warning))))
10562 (message "%s => %s" cmd
10563 (if (eq (string-to-char cmd) ?\()
10564 (eval (read cmd))
10565 (call-interactively (read cmd))))
10566 (user-error "Abort"))))
10568 (defun org--open-help-link (path)
10569 "Open a \"help\" type link.
10570 PATH is a symbol name, as a string."
10571 (pcase (intern path)
10572 ((and (pred fboundp) variable) (describe-function variable))
10573 ((and (pred boundp) function) (describe-variable function))
10574 (name (user-error "Unknown function or variable: %s" name))))
10576 (defun org--open-shell-link (path)
10577 "Open a \"shell\" type link.
10578 PATH is the command to execute, as a string."
10579 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10580 (cmd path))
10581 (if (or (and (org-string-nw-p
10582 org-confirm-shell-link-not-regexp)
10583 (string-match
10584 org-confirm-shell-link-not-regexp cmd))
10585 (not org-confirm-shell-link-function)
10586 (funcall org-confirm-shell-link-function
10587 (format "Execute \"%s\" in shell? "
10588 (org-add-props cmd nil
10589 'face 'org-warning))))
10590 (progn
10591 (message "Executing %s" cmd)
10592 (shell-command cmd buf)
10593 (when (featurep 'midnight)
10594 (setq clean-buffer-list-kill-buffer-names
10595 (cons (buffer-name buf)
10596 clean-buffer-list-kill-buffer-names))))
10597 (user-error "Abort"))))
10599 (defun org-open-at-point (&optional arg reference-buffer)
10600 "Open link, timestamp, footnote or tags at point.
10602 When point is on a link, follow it. Normally, files will be
10603 opened by an appropriate application. If the optional prefix
10604 argument ARG is non-nil, Emacs will visit the file. With
10605 a double prefix argument, try to open outside of Emacs, in the
10606 application the system uses for this file type.
10608 When point is on a timestamp, open the agenda at the day
10609 specified.
10611 When point is a footnote definition, move to the first reference
10612 found. If it is on a reference, move to the associated
10613 definition.
10615 When point is on a headline, display a list of every link in the
10616 entry, so it is possible to pick one, or all, of them. If point
10617 is on a tag, call `org-tags-view' instead.
10619 When optional argument REFERENCE-BUFFER is non-nil, it should
10620 specify a buffer from where the link search should happen. This
10621 is used internally by `org-open-link-from-string'.
10623 On top of syntactically correct links, this function will also
10624 try to open links and time-stamps in comments, example
10625 blocks... i.e., whenever point is on something looking like
10626 a timestamp or a link."
10627 (interactive "P")
10628 ;; On a code block, open block's results.
10629 (unless (call-interactively 'org-babel-open-src-block-result)
10630 (org-load-modules-maybe)
10631 (setq org-window-config-before-follow-link (current-window-configuration))
10632 (org-remove-occur-highlights nil nil t)
10633 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10634 (let* ((context
10635 ;; Only consider supported types, even if they are not
10636 ;; the closest one.
10637 (org-element-lineage
10638 (org-element-context)
10639 '(clock footnote-definition footnote-reference headline
10640 inlinetask link timestamp)
10642 (type (org-element-type context))
10643 (value (org-element-property :value context)))
10644 (cond
10645 ;; On a headline or an inlinetask, but not on a timestamp,
10646 ;; a link, a footnote reference or on tags.
10647 ((and (memq type '(headline inlinetask))
10648 ;; Not on tags.
10649 (let ((case-fold-search nil))
10650 (and (org-match-line org-complex-heading-regexp)
10651 (or (not (match-beginning 5))
10652 (< (point) (match-beginning 5))))))
10653 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10654 (links (car data))
10655 (links-end (cdr data)))
10656 (if links
10657 (dolist (link (if (stringp links) (list links) links))
10658 (search-forward link nil links-end)
10659 (goto-char (match-beginning 0))
10660 (org-open-at-point))
10661 (require 'org-attach)
10662 (org-attach-reveal 'if-exists))))
10663 ;; On a footnote reference or at definition's label.
10664 ((or (eq type 'footnote-reference)
10665 (and (eq type 'footnote-definition)
10666 (save-excursion
10667 ;; Do not validate action when point is on the
10668 ;; spaces right after the footnote label, in
10669 ;; order to be on par with behaviour on links.
10670 (skip-chars-forward " \t")
10671 (let ((begin
10672 (org-element-property :contents-begin context)))
10673 (if begin (< (point) begin)
10674 (= (org-element-property :post-affiliated context)
10675 (line-beginning-position)))))))
10676 (org-footnote-action))
10677 ;; No valid context. Ignore catch-all types like `headline'.
10678 ;; If point is on something looking like a link or
10679 ;; a time-stamp, try opening it. It may be useful in
10680 ;; comments, example blocks...
10681 ((memq type '(footnote-definition headline inlinetask nil))
10682 (call-interactively #'org-open-at-point-global))
10683 ;; On a clock line, make sure point is on the timestamp
10684 ;; before opening it.
10685 ((and (eq type 'clock)
10686 value
10687 (>= (point) (org-element-property :begin value))
10688 (<= (point) (org-element-property :end value)))
10689 (org-follow-timestamp-link))
10690 ;; Do nothing on white spaces after an object.
10691 ((>= (point)
10692 (save-excursion
10693 (goto-char (org-element-property :end context))
10694 (skip-chars-backward " \t")
10695 (point)))
10696 (user-error "No link found"))
10697 ((eq type 'timestamp) (org-follow-timestamp-link))
10698 ;; On tags within a headline or an inlinetask.
10699 ((and (memq type '(headline inlinetask))
10700 (let ((case-fold-search nil))
10701 (save-excursion (beginning-of-line)
10702 (looking-at org-complex-heading-regexp))
10703 (and (match-beginning 5)
10704 (>= (point) (match-beginning 5)))))
10705 (org-tags-view arg (substring (match-string 5) 0 -1)))
10706 ((eq type 'link)
10707 (let ((type (org-element-property :type context))
10708 (path (org-link-unescape (org-element-property :path context))))
10709 ;; Switch back to REFERENCE-BUFFER needed when called in
10710 ;; a temporary buffer through `org-open-link-from-string'.
10711 (with-current-buffer (or reference-buffer (current-buffer))
10712 (cond
10713 ((equal type "file")
10714 (if (string-match "[*?{]" (file-name-nondirectory path))
10715 (dired path)
10716 ;; Look into `org-link-parameters' in order to find
10717 ;; a DEDICATED-FUNCTION to open file. The function
10718 ;; will be applied on raw link instead of parsed
10719 ;; link due to the limitation in `org-add-link-type'
10720 ;; ("open" function called with a single argument).
10721 ;; If no such function is found, fallback to
10722 ;; `org-open-file'.
10723 (let* ((option (org-element-property :search-option context))
10724 (app (org-element-property :application context))
10725 (dedicated-function
10726 (org-link-get-parameter
10727 (if app (concat type "+" app) type)
10728 :follow)))
10729 (if dedicated-function
10730 (funcall dedicated-function
10731 (concat path
10732 (and option (concat "::" option))))
10733 (apply #'org-open-file
10734 path
10735 (cond (arg)
10736 ((equal app "emacs") 'emacs)
10737 ((equal app "sys") 'system))
10738 (cond ((not option) nil)
10739 ((string-match-p "\\`[0-9]+\\'" option)
10740 (list (string-to-number option)))
10741 (t (list nil
10742 (org-link-unescape option)))))))))
10743 ((functionp (org-link-get-parameter type :follow))
10744 (funcall (org-link-get-parameter type :follow) path))
10745 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10746 (unless (run-hook-with-args-until-success
10747 'org-open-link-functions path)
10748 (if (not arg) (org-mark-ring-push)
10749 (switch-to-buffer-other-window
10750 (org-get-buffer-for-internal-link (current-buffer))))
10751 (let ((destination
10752 (org-with-wide-buffer
10753 (if (equal type "radio")
10754 (org-search-radio-target
10755 (org-element-property :path context))
10756 (org-link-search
10757 (if (member type '("custom-id" "coderef"))
10758 (org-element-property :raw-link context)
10759 path)
10760 ;; Prevent fuzzy links from matching
10761 ;; themselves.
10762 (and (equal type "fuzzy")
10763 (+ 2 (org-element-property :begin context)))))
10764 (point))))
10765 (unless (and (<= (point-min) destination)
10766 (>= (point-max) destination))
10767 (widen))
10768 (goto-char destination))))
10769 (t (browse-url-at-point))))))
10770 (t (user-error "No link found")))))
10771 (run-hook-with-args 'org-follow-link-hook)))
10773 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10774 "Offer links in the current entry and return the selected link.
10775 If there is only one link, return it.
10776 If NTH is an integer, return the NTH link found.
10777 If ZERO is a string, check also this string for a link, and if
10778 there is one, return it."
10779 (with-current-buffer buffer
10780 (org-with-wide-buffer
10781 (goto-char marker)
10782 (let ((cnt ?0)
10783 have-zero end links link c)
10784 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10785 (push (match-string 0 zero) links)
10786 (setq cnt (1- cnt) have-zero t))
10787 (save-excursion
10788 (org-back-to-heading t)
10789 (setq end (save-excursion (outline-next-heading) (point)))
10790 (while (re-search-forward org-any-link-re end t)
10791 (push (match-string 0) links))
10792 (setq links (org-uniquify (reverse links))))
10793 (cond
10794 ((null links)
10795 (message "No links"))
10796 ((equal (length links) 1)
10797 (setq link (car links)))
10798 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10799 (setq link (nth (if have-zero nth (1- nth)) links)))
10800 (t ; we have to select a link
10801 (save-excursion
10802 (save-window-excursion
10803 (delete-other-windows)
10804 (with-output-to-temp-buffer "*Select Link*"
10805 (dolist (l links)
10806 (cond
10807 ((not (string-match org-bracket-link-regexp l))
10808 (princ (format "[%c] %s\n" (cl-incf cnt)
10809 (org-unbracket-string "<" ">" l))))
10810 ((match-end 3)
10811 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10812 (match-string 3 l) (match-string 1 l))))
10813 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10814 (match-string 1 l)))))))
10815 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10816 (message "Select link to open, RET to open all:")
10817 (setq c (read-char-exclusive))
10818 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10819 (when (equal c ?q) (user-error "Abort"))
10820 (if (equal c ?\C-m)
10821 (setq link links)
10822 (setq nth (- c ?0))
10823 (when have-zero (setq nth (1+ nth)))
10824 (unless (and (integerp nth) (>= (length links) nth))
10825 (user-error "Invalid link selection"))
10826 (setq link (nth (1- nth) links)))))
10827 (cons link end)))))
10829 ;; TODO: These functions are deprecated since `org-open-at-point'
10830 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10831 (defun org-open-file-with-system (path)
10832 "Open file at PATH using the system way of opening it."
10833 (org-open-file path 'system))
10834 (defun org-open-file-with-emacs (path)
10835 "Open file at PATH in Emacs."
10836 (org-open-file path 'emacs))
10839 ;;; File search
10841 (defvar org-create-file-search-functions nil
10842 "List of functions to construct the right search string for a file link.
10843 These functions are called in turn with point at the location to
10844 which the link should point.
10846 A function in the hook should first test if it would like to
10847 handle this file type, for example by checking the `major-mode'
10848 or the file extension. If it decides not to handle this file, it
10849 should just return nil to give other functions a chance. If it
10850 does handle the file, it must return the search string to be used
10851 when following the link. The search string will be part of the
10852 file link, given after a double colon, and `org-open-at-point'
10853 will automatically search for it. If special measures must be
10854 taken to make the search successful, another function should be
10855 added to the companion hook `org-execute-file-search-functions',
10856 which see.
10858 A function in this hook may also use `setq' to set the variable
10859 `description' to provide a suggestion for the descriptive text to
10860 be used for this link when it gets inserted into an Org buffer
10861 with \\[org-insert-link].")
10863 (defvar org-execute-file-search-functions nil
10864 "List of functions to execute a file search triggered by a link.
10866 Functions added to this hook must accept a single argument, the
10867 search string that was part of the file link, the part after the
10868 double colon. The function must first check if it would like to
10869 handle this search, for example by checking the `major-mode' or
10870 the file extension. If it decides not to handle this search, it
10871 should just return nil to give other functions a chance. If it
10872 does handle the search, it must return a non-nil value to keep
10873 other functions from trying.
10875 Each function can access the current prefix argument through the
10876 variable `current-prefix-arg'. Note that a single prefix is used
10877 to force opening a link in Emacs, so it may be good to only use a
10878 numeric or double prefix to guide the search function.
10880 In case this is needed, a function in this hook can also restore
10881 the window configuration before `org-open-at-point' was called using:
10883 (set-window-configuration org-window-config-before-follow-link)")
10885 (defun org-search-radio-target (target)
10886 "Search a radio target matching TARGET in current buffer.
10887 White spaces are not significant."
10888 (let ((re (format "<<<%s>>>"
10889 (mapconcat #'regexp-quote
10890 (org-split-string target "[ \t\n]+")
10891 "[ \t]+\\(?:\n[ \t]*\\)?")))
10892 (origin (point)))
10893 (goto-char (point-min))
10894 (catch :radio-match
10895 (while (re-search-forward re nil t)
10896 (backward-char)
10897 (let ((object (org-element-context)))
10898 (when (eq (org-element-type object) 'radio-target)
10899 (goto-char (org-element-property :begin object))
10900 (org-show-context 'link-search)
10901 (throw :radio-match nil))))
10902 (goto-char origin)
10903 (user-error "No match for radio target: %s" target))))
10905 (defun org-link-search (s &optional avoid-pos stealth)
10906 "Search for a search string S.
10908 If S starts with \"#\", it triggers a custom ID search.
10910 If S is enclosed within parenthesis, it initiates a coderef
10911 search.
10913 If S is surrounded by forward slashes, it is interpreted as
10914 a regular expression. In Org mode files, this will create an
10915 `org-occur' sparse tree. In ordinary files, `occur' will be used
10916 to list matches. If the current buffer is in `dired-mode', grep
10917 will be used to search in all files.
10919 When AVOID-POS is given, ignore matches near that position.
10921 When optional argument STEALTH is non-nil, do not modify
10922 visibility around point, thus ignoring `org-show-context-detail'
10923 variable.
10925 Search is case-insensitive and ignores white spaces. Return type
10926 of matched result, which is either `dedicated' or `fuzzy'."
10927 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10928 (let* ((case-fold-search t)
10929 (origin (point))
10930 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10931 (starred (eq (string-to-char normalized) ?*))
10932 (words (split-string (if starred (substring s 1) s)))
10933 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10934 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10935 type)
10936 (cond
10937 ;; Check if there are any special search functions.
10938 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10939 ((eq (string-to-char s) ?#)
10940 ;; Look for a custom ID S if S starts with "#".
10941 (let* ((id (substring normalized 1))
10942 (match (org-find-property "CUSTOM_ID" id)))
10943 (if match (progn (goto-char match) (setf type 'dedicated))
10944 (error "No match for custom ID: %s" id))))
10945 ((string-match "\\`(\\(.*\\))\\'" normalized)
10946 ;; Look for coderef targets if S is enclosed within parenthesis.
10947 (let ((coderef (match-string-no-properties 1 normalized))
10948 (re (substring s-single-re 1 -1)))
10949 (goto-char (point-min))
10950 (catch :coderef-match
10951 (while (re-search-forward re nil t)
10952 (let ((element (org-element-at-point)))
10953 (when (and (memq (org-element-type element)
10954 '(example-block src-block))
10955 ;; Build proper regexp according to current
10956 ;; block's label format.
10957 (let ((label-fmt
10958 (regexp-quote
10959 (or (org-element-property :label-fmt element)
10960 org-coderef-label-format))))
10961 (save-excursion
10962 (beginning-of-line)
10963 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10964 (format label-fmt coderef))))))
10965 (setq type 'dedicated)
10966 (goto-char (match-beginning 1))
10967 (throw :coderef-match nil))))
10968 (goto-char origin)
10969 (error "No match for coderef: %s" coderef))))
10970 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10971 ;; Look for a regular expression.
10972 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10973 (match-string 1 s)))
10974 ;; From here, we handle fuzzy links.
10976 ;; Look for targets, only if not in a headline search.
10977 ((and (not starred)
10978 (let ((target (format "<<%s>>" s-multi-re)))
10979 (catch :target-match
10980 (goto-char (point-min))
10981 (while (re-search-forward target nil t)
10982 (backward-char)
10983 (let ((context (org-element-context)))
10984 (when (eq (org-element-type context) 'target)
10985 (setq type 'dedicated)
10986 (goto-char (org-element-property :begin context))
10987 (throw :target-match t))))
10988 nil))))
10989 ;; Look for elements named after S, only if not in a headline
10990 ;; search.
10991 ((and (not starred)
10992 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10993 (catch :name-match
10994 (goto-char (point-min))
10995 (while (re-search-forward name nil t)
10996 (let ((element (org-element-at-point)))
10997 (when (equal words
10998 (split-string
10999 (org-element-property :name element)))
11000 (setq type 'dedicated)
11001 (beginning-of-line)
11002 (throw :name-match t))))
11003 nil))))
11004 ;; Regular text search. Prefer headlines in Org mode buffers.
11005 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11006 ;; statistics cookies and tags.
11007 ((and (derived-mode-p 'org-mode)
11008 (let ((title-re
11009 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11010 org-outline-regexp-bol
11011 org-comment-string
11012 (mapconcat #'regexp-quote words ".+")))
11013 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11014 (comment-re (eval-when-compile
11015 (format "\\`%s[ \t]+" org-comment-string))))
11016 (goto-char (point-min))
11017 (catch :found
11018 (while (re-search-forward title-re nil t)
11019 (when (equal words
11020 (split-string
11021 (replace-regexp-in-string
11022 cookie-re ""
11023 (replace-regexp-in-string
11024 comment-re "" (org-get-heading t t t)))))
11025 (throw :found t)))
11026 nil)))
11027 (beginning-of-line)
11028 (setq type 'dedicated))
11029 ;; Offer to create non-existent headline depending on
11030 ;; `org-link-search-must-match-exact-headline'.
11031 ((and (derived-mode-p 'org-mode)
11032 (not org-link-search-inhibit-query)
11033 (eq org-link-search-must-match-exact-headline 'query-to-create)
11034 (yes-or-no-p "No match - create this as a new heading? "))
11035 (goto-char (point-max))
11036 (unless (bolp) (newline))
11037 (org-insert-heading nil t t)
11038 (insert s "\n")
11039 (beginning-of-line 0))
11040 ;; Only headlines are looked after. No need to process
11041 ;; further: throw an error.
11042 ((and (derived-mode-p 'org-mode)
11043 (or starred org-link-search-must-match-exact-headline))
11044 (goto-char origin)
11045 (error "No match for fuzzy expression: %s" normalized))
11046 ;; Regular text search.
11047 ((catch :fuzzy-match
11048 (goto-char (point-min))
11049 (while (re-search-forward s-multi-re nil t)
11050 ;; Skip match if it contains AVOID-POS or it is included in
11051 ;; a link with a description but outside the description.
11052 (unless (or (and avoid-pos
11053 (<= (match-beginning 0) avoid-pos)
11054 (> (match-end 0) avoid-pos))
11055 (and (save-match-data
11056 (org-in-regexp org-bracket-link-regexp))
11057 (match-beginning 3)
11058 (or (> (match-beginning 3) (point))
11059 (<= (match-end 3) (point)))
11060 (org-element-lineage
11061 (save-match-data (org-element-context))
11062 '(link) t)))
11063 (goto-char (match-beginning 0))
11064 (setq type 'fuzzy)
11065 (throw :fuzzy-match t)))
11066 nil))
11067 ;; All failed. Throw an error.
11068 (t (goto-char origin)
11069 (error "No match for fuzzy expression: %s" normalized)))
11070 ;; Disclose surroundings of match, if appropriate.
11071 (when (and (derived-mode-p 'org-mode) (not stealth))
11072 (org-show-context 'link-search))
11073 type))
11075 (defun org-get-buffer-for-internal-link (buffer)
11076 "Return a buffer to be used for displaying the link target of internal links."
11077 (cond
11078 ((not org-display-internal-link-with-indirect-buffer)
11079 buffer)
11080 ((string-suffix-p "(Clone)" (buffer-name buffer))
11081 (message "Buffer is already a clone, not making another one")
11082 ;; we also do not modify visibility in this case
11083 buffer)
11084 (t ; make a new indirect buffer for displaying the link
11085 (let* ((bn (buffer-name buffer))
11086 (ibn (concat bn "(Clone)"))
11087 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11088 (with-current-buffer ib (org-overview))
11089 ib))))
11091 (defun org-do-occur (regexp &optional cleanup)
11092 "Call the Emacs command `occur'.
11093 If CLEANUP is non-nil, remove the printout of the regular expression
11094 in the *Occur* buffer. This is useful if the regex is long and not useful
11095 to read."
11096 (occur regexp)
11097 (when cleanup
11098 (let ((cwin (selected-window)) win beg end)
11099 (when (setq win (get-buffer-window "*Occur*"))
11100 (select-window win))
11101 (goto-char (point-min))
11102 (when (re-search-forward "match[a-z]+" nil t)
11103 (setq beg (match-end 0))
11104 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11105 (setq end (1- (match-beginning 0)))))
11106 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11107 (goto-char (point-min))
11108 (select-window cwin))))
11110 ;;; The mark ring for links jumps
11112 (defvar org-mark-ring nil
11113 "Mark ring for positions before jumps in Org mode.")
11114 (defvar org-mark-ring-last-goto nil
11115 "Last position in the mark ring used to go back.")
11116 ;; Fill and close the ring
11117 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11118 (dotimes (_ org-mark-ring-length)
11119 (push (make-marker) org-mark-ring))
11120 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11121 org-mark-ring)
11123 (defun org-mark-ring-push (&optional pos buffer)
11124 "Put the current position or POS into the mark ring and rotate it."
11125 (interactive)
11126 (setq pos (or pos (point)))
11127 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11128 (move-marker (car org-mark-ring)
11129 (or pos (point))
11130 (or buffer (current-buffer)))
11131 (message "%s"
11132 (substitute-command-keys
11133 "Position saved to mark ring, go back with \
11134 `\\[org-mark-ring-goto]'.")))
11136 (defun org-mark-ring-goto (&optional n)
11137 "Jump to the previous position in the mark ring.
11138 With prefix arg N, jump back that many stored positions. When
11139 called several times in succession, walk through the entire ring.
11140 Org mode commands jumping to a different position in the current file,
11141 or to another Org file, automatically push the old position onto the ring."
11142 (interactive "p")
11143 (let (p m)
11144 (if (eq last-command this-command)
11145 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11146 (setq p org-mark-ring))
11147 (setq org-mark-ring-last-goto p)
11148 (setq m (car p))
11149 (pop-to-buffer-same-window (marker-buffer m))
11150 (goto-char m)
11151 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11153 (defun org-add-angle-brackets (s)
11154 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11155 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11158 ;;; Following specific links
11160 (defvar org-agenda-buffer-tmp-name)
11161 (defvar org-agenda-start-on-weekday)
11162 (defun org-follow-timestamp-link ()
11163 "Open an agenda view for the time-stamp date/range at point."
11164 (cond
11165 ((org-at-date-range-p t)
11166 (let ((org-agenda-start-on-weekday)
11167 (t1 (match-string 1))
11168 (t2 (match-string 2)) tt1 tt2)
11169 (setq tt1 (time-to-days (org-time-string-to-time t1))
11170 tt2 (time-to-days (org-time-string-to-time t2)))
11171 (let ((org-agenda-buffer-tmp-name
11172 (format "*Org Agenda(a:%s)"
11173 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11174 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11175 ((org-at-timestamp-p 'lax)
11176 (let ((org-agenda-buffer-tmp-name
11177 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11178 (org-agenda-list nil (time-to-days (org-time-string-to-time
11179 (substring (match-string 1) 0 10)))
11180 1)))
11181 (t (error "This should not happen"))))
11184 ;;; Following file links
11185 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11186 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11187 (declare-function mailcap-mime-info
11188 "mailcap" (string &optional request no-decode))
11189 (defvar org-wait nil)
11190 (defun org-open-file (path &optional in-emacs line search)
11191 "Open the file at PATH.
11192 First, this expands any special file name abbreviations. Then the
11193 configuration variable `org-file-apps' is checked if it contains an
11194 entry for this file type, and if yes, the corresponding command is launched.
11196 If no application is found, Emacs simply visits the file.
11198 With optional prefix argument IN-EMACS, Emacs will visit the file.
11199 With a double \\[universal-argument] \\[universal-argument] \
11200 prefix arg, Org tries to avoid opening in Emacs
11201 and to use an external application to visit the file.
11203 Optional LINE specifies a line to go to, optional SEARCH a string
11204 to search for. If LINE or SEARCH is given, the file will be
11205 opened in Emacs, unless an entry from org-file-apps that makes
11206 use of groups in a regexp matches.
11208 If you want to change the way frames are used when following a
11209 link, please customize `org-link-frame-setup'.
11211 If the file does not exist, an error is thrown."
11212 (let* ((file (if (equal path "")
11213 buffer-file-name
11214 (substitute-in-file-name (expand-file-name path))))
11215 (file-apps (append org-file-apps (org-default-apps)))
11216 (apps (cl-remove-if
11217 'org-file-apps-entry-match-against-dlink-p file-apps))
11218 (apps-dlink (cl-remove-if-not
11219 'org-file-apps-entry-match-against-dlink-p file-apps))
11220 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11221 (dirp (unless remp (file-directory-p file)))
11222 (file (if (and dirp org-open-directory-means-index-dot-org)
11223 (concat (file-name-as-directory file) "index.org")
11224 file))
11225 (a-m-a-p (assq 'auto-mode apps))
11226 (dfile (downcase file))
11227 ;; Reconstruct the original link from the PATH, LINE and
11228 ;; SEARCH args.
11229 (link (cond (line (concat file "::" (number-to-string line)))
11230 (search (concat file "::" search))
11231 (t file)))
11232 (dlink (downcase link))
11233 (ext
11234 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11235 (match-string 1 dfile)))
11236 (save-position-maybe
11237 (let ((old-buffer (current-buffer))
11238 (old-pos (point))
11239 (old-mode major-mode))
11240 (lambda ()
11241 (and (derived-mode-p 'org-mode)
11242 (eq old-mode 'org-mode)
11243 (or (not (eq old-buffer (current-buffer)))
11244 (not (eq old-pos (point))))
11245 (org-mark-ring-push old-pos old-buffer)))))
11246 cmd link-match-data)
11247 (cond
11248 ((member in-emacs '((16) system))
11249 (setq cmd (cdr (assq 'system apps))))
11250 (in-emacs (setq cmd 'emacs))
11252 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11253 (and dirp (cdr (assq 'directory apps)))
11254 ;; First, try matching against apps-dlink if we
11255 ;; get a match here, store the match data for
11256 ;; later.
11257 (let ((match (assoc-default dlink apps-dlink
11258 'string-match)))
11259 (if match
11260 (progn (setq link-match-data (match-data))
11261 match)
11262 (progn (setq in-emacs (or in-emacs line search))
11263 nil))) ; if we have no match in apps-dlink,
11264 ; always open the file in emacs if line or search
11265 ; is given (for backwards compatibility)
11266 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11267 'string-match)
11268 (cdr (assoc ext apps))
11269 (cdr (assq t apps))))))
11270 (when (eq cmd 'system)
11271 (setq cmd (cdr (assq 'system apps))))
11272 (when (eq cmd 'default)
11273 (setq cmd (cdr (assoc t apps))))
11274 (when (eq cmd 'mailcap)
11275 (require 'mailcap)
11276 (mailcap-parse-mailcaps)
11277 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11278 (command (mailcap-mime-info mime-type)))
11279 (if (stringp command)
11280 (setq cmd command)
11281 (setq cmd 'emacs))))
11282 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11283 (not (file-exists-p file))
11284 (not org-open-non-existing-files))
11285 (user-error "No such file: %s" file))
11286 (cond
11287 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11288 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11289 (while (string-match "['\"]%s['\"]" cmd)
11290 (setq cmd (replace-match "%s" t t cmd)))
11291 (setq cmd (replace-regexp-in-string
11292 "%s"
11293 (shell-quote-argument (convert-standard-filename file))
11295 nil t))
11297 ;; Replace "%1", "%2" etc. in command with group matches from regex
11298 (save-match-data
11299 (let ((match-index 1)
11300 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11301 (set-match-data link-match-data)
11302 (while (<= match-index number-of-groups)
11303 (let ((regex (concat "%" (number-to-string match-index)))
11304 (replace-with (match-string match-index dlink)))
11305 (while (string-match regex cmd)
11306 (setq cmd (replace-match replace-with t t cmd))))
11307 (setq match-index (+ match-index 1)))))
11309 (save-window-excursion
11310 (message "Running %s...done" cmd)
11311 (start-process-shell-command cmd nil cmd)
11312 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11313 ((or (stringp cmd)
11314 (eq cmd 'emacs))
11315 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11316 (widen)
11317 (cond (line (org-goto-line line)
11318 (when (derived-mode-p 'org-mode) (org-reveal)))
11319 (search (condition-case err
11320 (org-link-search search)
11321 ;; Save position before error-ing out so user
11322 ;; can easily move back to the original buffer.
11323 (error (funcall save-position-maybe)
11324 (error (nth 1 err)))))))
11325 ((functionp cmd)
11326 (save-match-data
11327 (set-match-data link-match-data)
11328 (condition-case nil
11329 (funcall cmd file link)
11330 ;; FIXME: Remove this check when most default installations
11331 ;; of Emacs have at least Org 9.0.
11332 ((debug wrong-number-of-arguments wrong-type-argument
11333 invalid-function)
11334 (user-error "Please see Org News for version 9.0 about \
11335 `org-file-apps'--Lisp error: %S" cmd)))))
11336 ((consp cmd)
11337 ;; FIXME: Remove this check when most default installations of
11338 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11339 ;; fall back to `org-link-frame-setup' for an old usage of
11340 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11341 (user-error "Please see Org News for version 9.0 about \
11342 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11343 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11344 (funcall save-position-maybe)))
11346 (defun org-file-apps-entry-match-against-dlink-p (entry)
11347 "This function returns non-nil if `entry' uses a regular
11348 expression which should be matched against the whole link by
11349 org-open-file.
11351 It assumes that is the case when the entry uses a regular
11352 expression which has at least one grouping construct and the
11353 action is either a lisp form or a command string containing
11354 `%1', i.e. using at least one subexpression match as a
11355 parameter."
11356 (let ((selector (car entry))
11357 (action (cdr entry)))
11358 (if (stringp selector)
11359 (and (> (regexp-opt-depth selector) 0)
11360 (or (and (stringp action)
11361 (string-match "%[0-9]" action))
11362 (consp action)))
11363 nil)))
11365 (defun org-default-apps ()
11366 "Return the default applications for this operating system."
11367 (cond
11368 ((eq system-type 'darwin)
11369 org-file-apps-defaults-macosx)
11370 ((eq system-type 'windows-nt)
11371 org-file-apps-defaults-windowsnt)
11372 (t org-file-apps-defaults-gnu)))
11374 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11375 "Convert extensions to regular expressions in the cars of LIST.
11376 Also, weed out any non-string entries, because the return value is used
11377 only for regexp matching.
11378 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11379 point to the symbol `emacs', indicating that the file should
11380 be opened in Emacs."
11381 (append
11382 (delq nil
11383 (mapcar (lambda (x)
11384 (unless (not (stringp (car x)))
11385 (if (string-match "\\W" (car x))
11387 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11388 list))
11389 (when add-auto-mode
11390 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11392 (defvar ange-ftp-name-format)
11393 (defun org-file-remote-p (file)
11394 "Test whether FILE specifies a location on a remote system.
11395 Return non-nil if the location is indeed remote.
11397 For example, the filename \"/user@host:/foo\" specifies a location
11398 on the system \"/user@host:\"."
11399 (cond ((fboundp 'file-remote-p)
11400 (file-remote-p file))
11401 ((fboundp 'tramp-handle-file-remote-p)
11402 (tramp-handle-file-remote-p file))
11403 ((and (boundp 'ange-ftp-name-format)
11404 (string-match (car ange-ftp-name-format) file))
11405 t)))
11408 ;;;; Refiling
11410 (defun org-get-org-file ()
11411 "Read a filename, with default directory `org-directory'."
11412 (let ((default (or org-default-notes-file remember-data-file)))
11413 (read-file-name (format "File name [%s]: " default)
11414 (file-name-as-directory org-directory)
11415 default)))
11417 (defun org-notes-order-reversed-p ()
11418 "Check if the current file should receive notes in reversed order."
11419 (cond
11420 ((not org-reverse-note-order) nil)
11421 ((eq t org-reverse-note-order) t)
11422 ((not (listp org-reverse-note-order)) nil)
11423 (t (catch 'exit
11424 (dolist (entry org-reverse-note-order)
11425 (when (string-match (car entry) buffer-file-name)
11426 (throw 'exit (cdr entry))))))))
11428 (defvar org-refile-target-table nil
11429 "The list of refile targets, created by `org-refile'.")
11431 (defvar org-agenda-new-buffers nil
11432 "Buffers created to visit agenda files.")
11434 (defvar org-refile-cache nil
11435 "Cache for refile targets.")
11437 (defvar org-refile-markers nil
11438 "All the markers used for caching refile locations.")
11440 (defun org-refile-marker (pos)
11441 "Get a new refile marker, but only if caching is in use."
11442 (if (not org-refile-use-cache)
11444 (let ((m (make-marker)))
11445 (move-marker m pos)
11446 (push m org-refile-markers)
11447 m)))
11449 (defun org-refile-cache-clear ()
11450 "Clear the refile cache and disable all the markers."
11451 (dolist (m org-refile-markers) (move-marker m nil))
11452 (setq org-refile-markers nil)
11453 (setq org-refile-cache nil)
11454 (message "Refile cache has been cleared"))
11456 (defun org-refile-cache-check-set (set)
11457 "Check if all the markers in the cache still have live buffers."
11458 (let (marker)
11459 (catch 'exit
11460 (while (and set (setq marker (nth 3 (pop set))))
11461 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11462 (when (and marker (null (marker-buffer marker)))
11463 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11464 (sit-for 3)
11465 (throw 'exit nil)))
11466 t)))
11468 (defun org-refile-cache-put (set &rest identifiers)
11469 "Push the refile targets SET into the cache, under IDENTIFIERS."
11470 (let* ((key (sha1 (prin1-to-string identifiers)))
11471 (entry (assoc key org-refile-cache)))
11472 (if entry
11473 (setcdr entry set)
11474 (push (cons key set) org-refile-cache))))
11476 (defun org-refile-cache-get (&rest identifiers)
11477 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11478 (cond
11479 ((not org-refile-cache) nil)
11480 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11482 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11483 org-refile-cache))))
11484 (and set (org-refile-cache-check-set set) set)))))
11486 (defvar org-outline-path-cache nil
11487 "Alist between buffer positions and outline paths.
11488 It value is an alist (POSITION . PATH) where POSITION is the
11489 buffer position at the beginning of an entry and PATH is a list
11490 of strings describing the outline path for that entry, in reverse
11491 order.")
11493 (defun org-refile-get-targets (&optional default-buffer)
11494 "Produce a table with refile targets."
11495 (let ((case-fold-search nil)
11496 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11497 (entries (or org-refile-targets '((nil . (:level . 1)))))
11498 targets tgs files desc descre)
11499 (message "Getting targets...")
11500 (with-current-buffer (or default-buffer (current-buffer))
11501 (dolist (entry entries)
11502 (setq files (car entry) desc (cdr entry))
11503 (cond
11504 ((null files) (setq files (list (current-buffer))))
11505 ((eq files 'org-agenda-files)
11506 (setq files (org-agenda-files 'unrestricted)))
11507 ((and (symbolp files) (fboundp files))
11508 (setq files (funcall files)))
11509 ((and (symbolp files) (boundp files))
11510 (setq files (symbol-value files))))
11511 (when (stringp files) (setq files (list files)))
11512 (cond
11513 ((eq (car desc) :tag)
11514 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11515 ((eq (car desc) :todo)
11516 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11517 ((eq (car desc) :regexp)
11518 (setq descre (cdr desc)))
11519 ((eq (car desc) :level)
11520 (setq descre (concat "^\\*\\{" (number-to-string
11521 (if org-odd-levels-only
11522 (1- (* 2 (cdr desc)))
11523 (cdr desc)))
11524 "\\}[ \t]")))
11525 ((eq (car desc) :maxlevel)
11526 (setq descre (concat "^\\*\\{1," (number-to-string
11527 (if org-odd-levels-only
11528 (1- (* 2 (cdr desc)))
11529 (cdr desc)))
11530 "\\}[ \t]")))
11531 (t (error "Bad refiling target description %s" desc)))
11532 (dolist (f files)
11533 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11535 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11536 (progn
11537 (when (bufferp f)
11538 (setq f (buffer-file-name (buffer-base-buffer f))))
11539 (setq f (and f (expand-file-name f)))
11540 (when (eq org-refile-use-outline-path 'file)
11541 (push (list (file-name-nondirectory f) f nil nil) tgs))
11542 (when (eq org-refile-use-outline-path 'buffer-name)
11543 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11544 (when (eq org-refile-use-outline-path 'full-file-path)
11545 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11546 (org-with-wide-buffer
11547 (goto-char (point-min))
11548 (setq org-outline-path-cache nil)
11549 (while (re-search-forward descre nil t)
11550 (beginning-of-line)
11551 (let ((case-fold-search nil))
11552 (looking-at org-complex-heading-regexp))
11553 (let ((begin (point))
11554 (heading (match-string-no-properties 4)))
11555 (unless (or (and
11556 org-refile-target-verify-function
11557 (not
11558 (funcall org-refile-target-verify-function)))
11559 (not heading))
11560 (let ((re (format org-complex-heading-regexp-format
11561 (regexp-quote heading)))
11562 (target
11563 (if (not org-refile-use-outline-path) heading
11564 (mapconcat
11565 #'identity
11566 (append
11567 (pcase org-refile-use-outline-path
11568 (`file (list (file-name-nondirectory
11569 (buffer-file-name
11570 (buffer-base-buffer)))))
11571 (`full-file-path
11572 (list (buffer-file-name
11573 (buffer-base-buffer))))
11574 (`buffer-name
11575 (list (buffer-name
11576 (buffer-base-buffer))))
11577 (_ nil))
11578 (mapcar (lambda (s) (replace-regexp-in-string
11579 "/" "\\/" s nil t))
11580 (org-get-outline-path t t)))
11581 "/"))))
11582 (push (list target f re (org-refile-marker (point)))
11583 tgs)))
11584 (when (= (point) begin)
11585 ;; Verification function has not moved point.
11586 (end-of-line)))))))
11587 (when org-refile-use-cache
11588 (org-refile-cache-put tgs (buffer-file-name) descre))
11589 (setq targets (append tgs targets))))))
11590 (message "Getting targets...done")
11591 (delete-dups (nreverse targets))))
11593 (defun org--get-outline-path-1 (&optional use-cache)
11594 "Return outline path to current headline.
11596 Outline path is a list of strings, in reverse order. When
11597 optional argument USE-CACHE is non-nil, make use of a cache. See
11598 `org-get-outline-path' for details.
11600 Assume buffer is widened and point is on a headline."
11601 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11602 (let ((p (point))
11603 (heading (let ((case-fold-search nil))
11604 (looking-at org-complex-heading-regexp)
11605 (if (not (match-end 4)) ""
11606 ;; Remove statistics cookies.
11607 (org-trim
11608 (org-link-display-format
11609 (replace-regexp-in-string
11610 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11611 (match-string-no-properties 4))))))))
11612 (if (org-up-heading-safe)
11613 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11614 (when use-cache
11615 (push (cons p path) org-outline-path-cache))
11616 path)
11617 ;; This is a new root node. Since we assume we are moving
11618 ;; forward, we can drop previous cache so as to limit number
11619 ;; of associations there.
11620 (let ((path (list heading)))
11621 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11622 path)))))
11624 (defun org-get-outline-path (&optional with-self use-cache)
11625 "Return the outline path to the current entry.
11627 An outline path is a list of ancestors for current headline, as
11628 a list of strings. Statistics cookies are removed and links are
11629 replaced with their description, if any, or their path otherwise.
11631 When optional argument WITH-SELF is non-nil, the path also
11632 includes the current headline.
11634 When optional argument USE-CACHE is non-nil, cache outline paths
11635 between calls to this function so as to avoid backtracking. This
11636 argument is useful when planning to find more than one outline
11637 path in the same document. In that case, there are two
11638 conditions to satisfy:
11639 - `org-outline-path-cache' is set to nil before starting the
11640 process;
11641 - outline paths are computed by increasing buffer positions."
11642 (org-with-wide-buffer
11643 (and (or (and with-self (org-back-to-heading t))
11644 (org-up-heading-safe))
11645 (reverse (org--get-outline-path-1 use-cache)))))
11647 (defun org-format-outline-path (path &optional width prefix separator)
11648 "Format the outline path PATH for display.
11649 WIDTH is the maximum number of characters that is available.
11650 PREFIX is a prefix to be included in the returned string,
11651 such as the file name.
11652 SEPARATOR is inserted between the different parts of the path,
11653 the default is \"/\"."
11654 (setq width (or width 79))
11655 (setq path (delq nil path))
11656 (unless (> width 0)
11657 (user-error "Argument `width' must be positive"))
11658 (setq separator (or separator "/"))
11659 (let* ((org-odd-levels-only nil)
11660 (fpath (concat
11661 prefix (and prefix path separator)
11662 (mapconcat
11663 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11664 (cl-loop for head in path
11665 for n from 0
11666 collect (org-add-props
11667 head nil 'face
11668 (nth (% n org-n-level-faces) org-level-faces)))
11669 separator))))
11670 (when (> (length fpath) width)
11671 (if (< width 7)
11672 ;; It's unlikely that `width' will be this small, but don't
11673 ;; waste characters by adding ".." if it is.
11674 (setq fpath (substring fpath 0 width))
11675 (setf (substring fpath (- width 2)) "..")))
11676 fpath))
11678 (defun org-display-outline-path (&optional file current separator just-return-string)
11679 "Display the current outline path in the echo area.
11681 If FILE is non-nil, prepend the output with the file name.
11682 If CURRENT is non-nil, append the current heading to the output.
11683 SEPARATOR is passed through to `org-format-outline-path'. It separates
11684 the different parts of the path and defaults to \"/\".
11685 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11686 (interactive "P")
11687 (let* (case-fold-search
11688 (bfn (buffer-file-name (buffer-base-buffer)))
11689 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11690 res)
11691 (when current (setq path (append path
11692 (save-excursion
11693 (org-back-to-heading t)
11694 (when (looking-at org-complex-heading-regexp)
11695 (list (match-string 4)))))))
11696 (setq res
11697 (org-format-outline-path
11698 path
11699 (1- (frame-width))
11700 (and file bfn (concat (file-name-nondirectory bfn) separator))
11701 separator))
11702 (if just-return-string
11703 (org-no-properties res)
11704 (org-unlogged-message "%s" res))))
11706 (defvar org-refile-history nil
11707 "History for refiling operations.")
11709 (defvar org-after-refile-insert-hook nil
11710 "Hook run after `org-refile' has inserted its stuff at the new location.
11711 Note that this is still *before* the stuff will be removed from
11712 the *old* location.")
11714 (defvar org-capture-last-stored-marker)
11715 (defvar org-refile-keep nil
11716 "Non-nil means `org-refile' will copy instead of refile.")
11718 (defun org-copy ()
11719 "Like `org-refile', but copy."
11720 (interactive)
11721 (let ((org-refile-keep t))
11722 (funcall 'org-refile nil nil nil "Copy")))
11724 (defun org-refile (&optional arg default-buffer rfloc msg)
11725 "Move the entry or entries at point to another heading.
11727 The list of target headings is compiled using the information in
11728 `org-refile-targets', which see.
11730 At the target location, the entry is filed as a subitem of the
11731 target heading. Depending on `org-reverse-note-order', the new
11732 subitem will either be the first or the last subitem.
11734 If there is an active region, all entries in that region will be
11735 refiled. However, the region must fulfill the requirement that
11736 the first heading sets the top-level of the moved text.
11738 With a `\\[universal-argument]' ARG, the command will only visit the target \
11739 location
11740 and not actually move anything.
11742 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11743 location where the last
11744 refiling operation has put the subtree.
11746 With a numeric prefix argument of `2', refile to the running clock.
11748 With a numeric prefix argument of `3', emulate `org-refile-keep'
11749 being set to t and copy to the target location, don't move it.
11750 Beware that keeping refiled entries may result in duplicated ID
11751 properties.
11753 RFLOC can be a refile location obtained in a different way.
11755 MSG is a string to replace \"Refile\" in the default prompt with
11756 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11758 See also `org-refile-use-outline-path'.
11760 If you are using target caching (see `org-refile-use-cache'), you
11761 have to clear the target cache in order to find new targets.
11762 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11763 prefix argument (`C-u C-u C-u C-c C-w')."
11764 (interactive "P")
11765 (if (member arg '(0 (64)))
11766 (org-refile-cache-clear)
11767 (let* ((actionmsg (cond (msg msg)
11768 ((equal arg 3) "Refile (and keep)")
11769 (t "Refile")))
11770 (regionp (org-region-active-p))
11771 (region-start (and regionp (region-beginning)))
11772 (region-end (and regionp (region-end)))
11773 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11774 pos it nbuf file level reversed)
11775 (setq last-command nil)
11776 (when regionp
11777 (goto-char region-start)
11778 (or (bolp) (goto-char (point-at-bol)))
11779 (setq region-start (point))
11780 (unless (or (org-kill-is-subtree-p
11781 (buffer-substring region-start region-end))
11782 (prog1 org-refile-active-region-within-subtree
11783 (let ((s (point-at-eol)))
11784 (org-toggle-heading)
11785 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11786 (user-error "The region is not a (sequence of) subtree(s)")))
11787 (if (equal arg '(16))
11788 (org-refile-goto-last-stored)
11789 (when (or
11790 (and (equal arg 2)
11791 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11792 (prog1
11793 (setq it (list (or org-clock-heading "running clock")
11794 (buffer-file-name
11795 (marker-buffer org-clock-hd-marker))
11797 (marker-position org-clock-hd-marker)))
11798 (setq arg nil)))
11799 (setq it
11800 (or rfloc
11801 (let (heading-text)
11802 (save-excursion
11803 (unless (and arg (listp arg))
11804 (org-back-to-heading t)
11805 (setq heading-text
11806 (replace-regexp-in-string
11807 org-bracket-link-regexp
11808 "\\3"
11809 (or (nth 4 (org-heading-components))
11810 ""))))
11811 (org-refile-get-location
11812 (cond ((and arg (listp arg)) "Goto")
11813 (regionp (concat actionmsg " region to"))
11814 (t (concat actionmsg " subtree \""
11815 heading-text "\" to")))
11816 default-buffer
11817 (and (not (equal '(4) arg))
11818 org-refile-allow-creating-parent-nodes)))))))
11819 (setq file (nth 1 it)
11820 pos (nth 3 it))
11821 (when (and (not arg)
11823 (equal (buffer-file-name) file)
11824 (if regionp
11825 (and (>= pos region-start)
11826 (<= pos region-end))
11827 (and (>= pos (point))
11828 (< pos (save-excursion
11829 (org-end-of-subtree t t))))))
11830 (error "Cannot refile to position inside the tree or region"))
11831 (setq nbuf (or (find-buffer-visiting file)
11832 (find-file-noselect file)))
11833 (if (and arg (not (equal arg 3)))
11834 (progn
11835 (pop-to-buffer-same-window nbuf)
11836 (goto-char (cond (pos)
11837 ((org-notes-order-reversed-p) (point-min))
11838 (t (point-max))))
11839 (org-show-context 'org-goto))
11840 (if regionp
11841 (progn
11842 (org-kill-new (buffer-substring region-start region-end))
11843 (org-save-markers-in-region region-start region-end))
11844 (org-copy-subtree 1 nil t))
11845 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11846 (find-file-noselect file)))
11847 (setq reversed (org-notes-order-reversed-p))
11848 (org-with-wide-buffer
11849 (if pos
11850 (progn
11851 (goto-char pos)
11852 (setq level (org-get-valid-level (funcall outline-level) 1))
11853 (goto-char
11854 (if reversed
11855 (or (outline-next-heading) (point-max))
11856 (or (save-excursion (org-get-next-sibling))
11857 (org-end-of-subtree t t)
11858 (point-max)))))
11859 (setq level 1)
11860 (if (not reversed)
11861 (goto-char (point-max))
11862 (goto-char (point-min))
11863 (or (outline-next-heading) (goto-char (point-max)))))
11864 (unless (bolp) (newline))
11865 (org-paste-subtree level nil nil t)
11866 (when org-log-refile
11867 (org-add-log-setup 'refile nil nil org-log-refile)
11868 (unless (eq org-log-refile 'note)
11869 (save-excursion (org-add-log-note))))
11870 (and org-auto-align-tags
11871 (let ((org-loop-over-headlines-in-active-region nil))
11872 (org-set-tags nil t)))
11873 (let ((bookmark-name (plist-get org-bookmark-names-plist
11874 :last-refile)))
11875 (when bookmark-name
11876 (with-demoted-errors
11877 (bookmark-set bookmark-name))))
11878 ;; If we are refiling for capture, make sure that the
11879 ;; last-capture pointers point here
11880 (when (bound-and-true-p org-capture-is-refiling)
11881 (let ((bookmark-name (plist-get org-bookmark-names-plist
11882 :last-capture-marker)))
11883 (when bookmark-name
11884 (with-demoted-errors
11885 (bookmark-set bookmark-name))))
11886 (move-marker org-capture-last-stored-marker (point)))
11887 (when (fboundp 'deactivate-mark) (deactivate-mark))
11888 (run-hooks 'org-after-refile-insert-hook)))
11889 (unless org-refile-keep
11890 (if regionp
11891 (delete-region (point) (+ (point) (- region-end region-start)))
11892 (delete-region
11893 (and (org-back-to-heading t) (point))
11894 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11895 (when (featurep 'org-inlinetask)
11896 (org-inlinetask-remove-END-maybe))
11897 (setq org-markers-to-move nil)
11898 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11900 (defun org-refile-goto-last-stored ()
11901 "Go to the location where the last refile was stored."
11902 (interactive)
11903 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11904 (message "This is the location of the last refile"))
11906 (defun org-refile--get-location (refloc tbl)
11907 "When user refile to REFLOC, find the associated target in TBL.
11908 Also check `org-refile-target-table'."
11909 (car (delq
11911 (mapcar
11912 (lambda (r) (or (assoc r tbl)
11913 (assoc r org-refile-target-table)))
11914 (list (replace-regexp-in-string "/$" "" refloc)
11915 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11917 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11918 "Prompt the user for a refile location, using PROMPT.
11919 PROMPT should not be suffixed with a colon and a space, because
11920 this function appends the default value from
11921 `org-refile-history' automatically, if that is not empty."
11922 (let ((org-refile-targets org-refile-targets)
11923 (org-refile-use-outline-path org-refile-use-outline-path))
11924 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11925 (unless org-refile-target-table
11926 (user-error "No refile targets"))
11927 (let* ((cbuf (current-buffer))
11928 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11929 (cfunc (if (and org-refile-use-outline-path
11930 org-outline-path-complete-in-steps)
11931 #'org-olpath-completing-read
11932 #'completing-read))
11933 (extra (if org-refile-use-outline-path "/" ""))
11934 (cbnex (concat (buffer-name) extra))
11935 (filename (and cfn (expand-file-name cfn)))
11936 (tbl (mapcar
11937 (lambda (x)
11938 (if (and (not (member org-refile-use-outline-path
11939 '(file full-file-path)))
11940 (not (equal filename (nth 1 x))))
11941 (cons (concat (car x) extra " ("
11942 (file-name-nondirectory (nth 1 x)) ")")
11943 (cdr x))
11944 (cons (concat (car x) extra) (cdr x))))
11945 org-refile-target-table))
11946 (completion-ignore-case t)
11947 cdef
11948 (prompt (concat prompt
11949 (or (and (car org-refile-history)
11950 (concat " (default " (car org-refile-history) ")"))
11951 (and (assoc cbnex tbl) (setq cdef cbnex)
11952 (concat " (default " cbnex ")"))) ": "))
11953 pa answ parent-target child parent old-hist)
11954 (setq old-hist org-refile-history)
11955 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11956 nil 'org-refile-history (or cdef (car org-refile-history))))
11957 (if (setq pa (org-refile--get-location answ tbl))
11958 (progn
11959 (org-refile-check-position pa)
11960 (when (or (not org-refile-history)
11961 (not (eq old-hist org-refile-history))
11962 (not (equal (car pa) (car org-refile-history))))
11963 (setq org-refile-history
11964 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11965 org-refile-history
11966 (cdr org-refile-history))))
11967 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11968 (pop org-refile-history)))
11970 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11971 (progn
11972 (setq parent (match-string 1 answ)
11973 child (match-string 2 answ))
11974 (setq parent-target (org-refile--get-location parent tbl))
11975 (when (and parent-target
11976 (or (eq new-nodes t)
11977 (and (eq new-nodes 'confirm)
11978 (y-or-n-p (format "Create new node \"%s\"? "
11979 child)))))
11980 (org-refile-new-child parent-target child)))
11981 (user-error "Invalid target location")))))
11983 (declare-function org-string-nw-p "org-macs" (s))
11984 (defun org-refile-check-position (refile-pointer)
11985 "Check if the refile pointer matches the headline to which it points."
11986 (let* ((file (nth 1 refile-pointer))
11987 (re (nth 2 refile-pointer))
11988 (pos (nth 3 refile-pointer))
11989 buffer)
11990 (if (and (not (markerp pos)) (not file))
11991 (user-error "Please indicate a target file in the refile path")
11992 (when (org-string-nw-p re)
11993 (setq buffer (if (markerp pos)
11994 (marker-buffer pos)
11995 (or (find-buffer-visiting file)
11996 (find-file-noselect file))))
11997 (with-current-buffer buffer
11998 (org-with-wide-buffer
11999 (goto-char pos)
12000 (beginning-of-line 1)
12001 (unless (looking-at-p re)
12002 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12004 (defun org-refile-new-child (parent-target child)
12005 "Use refile target PARENT-TARGET to add new CHILD below it."
12006 (unless parent-target
12007 (error "Cannot find parent for new node"))
12008 (let ((file (nth 1 parent-target))
12009 (pos (nth 3 parent-target))
12010 level)
12011 (with-current-buffer (or (find-buffer-visiting file)
12012 (find-file-noselect file))
12013 (org-with-wide-buffer
12014 (if pos
12015 (goto-char pos)
12016 (goto-char (point-max))
12017 (unless (bolp) (newline)))
12018 (when (looking-at org-outline-regexp)
12019 (setq level (funcall outline-level))
12020 (org-end-of-subtree t t))
12021 (org-back-over-empty-lines)
12022 (insert "\n" (make-string
12023 (if pos (org-get-valid-level level 1) 1) ?*)
12024 " " child "\n")
12025 (beginning-of-line 0)
12026 (list (concat (car parent-target) "/" child) file "" (point))))))
12028 (defun org-olpath-completing-read (prompt collection &rest args)
12029 "Read an outline path like a file name."
12030 (let ((thetable collection))
12031 (apply #'completing-read
12032 prompt
12033 (lambda (string predicate &optional flag)
12034 (cond
12035 ((eq flag nil) (try-completion string thetable))
12036 ((eq flag t)
12037 (let ((l (length string)))
12038 (mapcar (lambda (x)
12039 (let ((r (substring x l))
12040 (f (if (string-match " ([^)]*)$" x)
12041 (match-string 0 x)
12042 "")))
12043 (if (string-match "/" r)
12044 (concat string (substring r 0 (match-end 0)) f)
12045 x)))
12046 (all-completions string thetable predicate))))
12047 ;; Exact match?
12048 ((eq flag 'lambda) (assoc string thetable))))
12049 args)))
12051 ;;;; Dynamic blocks
12053 (defun org-find-dblock (name)
12054 "Find the first dynamic block with name NAME in the buffer.
12055 If not found, stay at current position and return nil."
12056 (let ((case-fold-search t) pos)
12057 (save-excursion
12058 (goto-char (point-min))
12059 (setq pos (and (re-search-forward
12060 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12061 (match-beginning 0))))
12062 (when pos (goto-char pos))
12063 pos))
12065 (defun org-create-dblock (plist)
12066 "Create a dynamic block section, with parameters taken from PLIST.
12067 PLIST must contain a :name entry which is used as the name of the block."
12068 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12069 (end-of-line 1)
12070 (newline))
12071 (let ((col (current-column))
12072 (name (plist-get plist :name)))
12073 (insert "#+BEGIN: " name)
12074 (while plist
12075 (if (eq (car plist) :name)
12076 (setq plist (cddr plist))
12077 (insert " " (prin1-to-string (pop plist)))))
12078 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12079 (beginning-of-line -2)))
12081 (defun org-prepare-dblock ()
12082 "Prepare dynamic block for refresh.
12083 This empties the block, puts the cursor at the insert position and returns
12084 the property list including an extra property :name with the block name."
12085 (unless (looking-at org-dblock-start-re)
12086 (user-error "Not at a dynamic block"))
12087 (let* ((begdel (1+ (match-end 0)))
12088 (name (org-no-properties (match-string 1)))
12089 (params (append (list :name name)
12090 (read (concat "(" (match-string 3) ")")))))
12091 (save-excursion
12092 (beginning-of-line 1)
12093 (skip-chars-forward " \t")
12094 (setq params (plist-put params :indentation-column (current-column))))
12095 (unless (re-search-forward org-dblock-end-re nil t)
12096 (error "Dynamic block not terminated"))
12097 (setq params
12098 (append params
12099 (list :content (buffer-substring
12100 begdel (match-beginning 0)))))
12101 (delete-region begdel (match-beginning 0))
12102 (goto-char begdel)
12103 (open-line 1)
12104 params))
12106 (defun org-map-dblocks (&optional command)
12107 "Apply COMMAND to all dynamic blocks in the current buffer.
12108 If COMMAND is not given, use `org-update-dblock'."
12109 (let ((cmd (or command 'org-update-dblock)))
12110 (save-excursion
12111 (goto-char (point-min))
12112 (while (re-search-forward org-dblock-start-re nil t)
12113 (goto-char (match-beginning 0))
12114 (save-excursion
12115 (condition-case nil
12116 (funcall cmd)
12117 (error (message "Error during update of dynamic block"))))
12118 (unless (re-search-forward org-dblock-end-re nil t)
12119 (error "Dynamic block not terminated"))))))
12121 (defun org-dblock-update (&optional arg)
12122 "User command for updating dynamic blocks.
12123 Update the dynamic block at point. With prefix ARG, update all dynamic
12124 blocks in the buffer."
12125 (interactive "P")
12126 (if arg
12127 (org-update-all-dblocks)
12128 (or (looking-at org-dblock-start-re)
12129 (org-beginning-of-dblock))
12130 (org-update-dblock)))
12132 (defun org-update-dblock ()
12133 "Update the dynamic block at point.
12134 This means to empty the block, parse for parameters and then call
12135 the correct writing function."
12136 (interactive)
12137 (save-excursion
12138 (let* ((win (selected-window))
12139 (pos (point))
12140 (line (org-current-line))
12141 (params (org-prepare-dblock))
12142 (name (plist-get params :name))
12143 (indent (plist-get params :indentation-column))
12144 (cmd (intern (concat "org-dblock-write:" name))))
12145 (message "Updating dynamic block `%s' at line %d..." name line)
12146 (funcall cmd params)
12147 (message "Updating dynamic block `%s' at line %d...done" name line)
12148 (goto-char pos)
12149 (when (and indent (> indent 0))
12150 (setq indent (make-string indent ?\ ))
12151 (save-excursion
12152 (select-window win)
12153 (org-beginning-of-dblock)
12154 (forward-line 1)
12155 (while (not (looking-at org-dblock-end-re))
12156 (insert indent)
12157 (beginning-of-line 2))
12158 (when (looking-at org-dblock-end-re)
12159 (and (looking-at "[ \t]+")
12160 (replace-match ""))
12161 (insert indent)))))))
12163 (defun org-beginning-of-dblock ()
12164 "Find the beginning of the dynamic block at point.
12165 Error if there is no such block at point."
12166 (let ((pos (point))
12167 beg)
12168 (end-of-line 1)
12169 (if (and (re-search-backward org-dblock-start-re nil t)
12170 (setq beg (match-beginning 0))
12171 (re-search-forward org-dblock-end-re nil t)
12172 (> (match-end 0) pos))
12173 (goto-char beg)
12174 (goto-char pos)
12175 (error "Not in a dynamic block"))))
12177 (defun org-update-all-dblocks ()
12178 "Update all dynamic blocks in the buffer.
12179 This function can be used in a hook."
12180 (interactive)
12181 (when (derived-mode-p 'org-mode)
12182 (org-map-dblocks 'org-update-dblock)))
12185 ;;;; Completion
12187 (declare-function org-export-backend-options "ox" (cl-x) t)
12188 (defun org-get-export-keywords ()
12189 "Return a list of all currently understood export keywords.
12190 Export keywords include options, block names, attributes and
12191 keywords relative to each registered export back-end."
12192 (let (keywords)
12193 (dolist (backend
12194 (bound-and-true-p org-export-registered-backends)
12195 (delq nil keywords))
12196 ;; Back-end name (for keywords, like #+LATEX:)
12197 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12198 (dolist (option-entry (org-export-backend-options backend))
12199 ;; Back-end options.
12200 (push (nth 1 option-entry) keywords)))))
12202 (defconst org-options-keywords
12203 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12204 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12205 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12206 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12207 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12209 (defcustom org-structure-template-alist
12210 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12211 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12212 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12213 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12214 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12215 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12216 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12217 ("L" "#+LaTeX: ")
12218 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12219 ("H" "#+HTML: ")
12220 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12221 ("A" "#+ASCII: ")
12222 ("i" "#+INDEX: ?")
12223 ("I" "#+INCLUDE: %file ?"))
12224 "Structure completion elements.
12225 This is a list of abbreviation keys and values. The value gets inserted
12226 if you type `<' followed by the key and then press the completion key,
12227 usually `TAB'. %file will be replaced by a file name after prompting
12228 for the file using completion. The cursor will be placed at the position
12229 of the `?' in the template.
12230 There are two templates for each key, the first uses the original Org syntax,
12231 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12232 the default when the /org-mtags.el/ module has been loaded. See also the
12233 variable `org-mtags-prefer-muse-templates'."
12234 :group 'org-completion
12235 :type '(repeat
12236 (list
12237 (string :tag "Key")
12238 (string :tag "Template")))
12239 :version "26.1"
12240 :package-version '(Org . "8.3"))
12242 (defun org-try-structure-completion ()
12243 "Try to complete a structure template before point.
12244 This looks for strings like \"<e\" on an otherwise empty line and
12245 expands them."
12246 (let ((l (buffer-substring (point-at-bol) (point)))
12248 (when (and (looking-at "[ \t]*$")
12249 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12250 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12251 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12252 (match-beginning 1)) a)
12253 t)))
12255 (defun org-complete-expand-structure-template (start cell)
12256 "Expand a structure template."
12257 (let ((rpl (nth 1 cell))
12258 (ind ""))
12259 (delete-region start (point))
12260 (when (string-match "\\`[ \t]*#\\+" rpl)
12261 (cond
12262 ((bolp))
12263 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12264 (setq ind (buffer-substring (point-at-bol) (point))))
12265 (t (newline))))
12266 (setq start (point))
12267 (when (string-match "%file" rpl)
12268 (setq rpl (replace-match
12269 (concat
12270 "\""
12271 (save-match-data
12272 (abbreviate-file-name (read-file-name "Include file: ")))
12273 "\"")
12274 t t rpl)))
12275 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12276 (concat "\n" ind)))
12277 (insert rpl)
12278 (when (re-search-backward "\\?" start t) (delete-char 1))))
12280 ;;;; TODO, DEADLINE, Comments
12282 (defun org-toggle-comment ()
12283 "Change the COMMENT state of an entry."
12284 (interactive)
12285 (save-excursion
12286 (org-back-to-heading)
12287 (let ((case-fold-search nil))
12288 (looking-at org-complex-heading-regexp))
12289 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12290 (skip-chars-forward " \t")
12291 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12292 (if (org-in-commented-heading-p t)
12293 (delete-region (point)
12294 (progn (search-forward " " (line-end-position) 'move)
12295 (skip-chars-forward " \t")
12296 (point)))
12297 (insert org-comment-string)
12298 (unless (eolp) (insert " ")))))
12300 (defvar org-last-todo-state-is-todo nil
12301 "This is non-nil when the last TODO state change led to a TODO state.
12302 If the last change removed the TODO tag or switched to DONE, then
12303 this is nil.")
12305 (defvar org-setting-tags nil) ; dynamically skipped
12307 (defvar org-todo-setup-filter-hook nil
12308 "Hook for functions that pre-filter todo specs.
12309 Each function takes a todo spec and returns either nil or the spec
12310 transformed into canonical form." )
12312 (defvar org-todo-get-default-hook nil
12313 "Hook for functions that get a default item for todo.
12314 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12315 nil or a string to be used for the todo mark." )
12317 (defvar org-agenda-headline-snapshot-before-repeat)
12319 (defun org-current-effective-time ()
12320 "Return current time adjusted for `org-extend-today-until' variable."
12321 (let* ((ct (org-current-time))
12322 (dct (decode-time ct))
12323 (ct1
12324 (cond
12325 (org-use-last-clock-out-time-as-effective-time
12326 (or (org-clock-get-last-clock-out-time) ct))
12327 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12328 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12329 (t ct))))
12330 ct1))
12332 (defun org-todo-yesterday (&optional arg)
12333 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12334 (interactive "P")
12335 (if (eq major-mode 'org-agenda-mode)
12336 (apply 'org-agenda-todo-yesterday arg)
12337 (let* ((org-use-effective-time t)
12338 (hour (nth 2 (decode-time (org-current-time))))
12339 (org-extend-today-until (1+ hour)))
12340 (org-todo arg))))
12342 (defvar org-block-entry-blocking ""
12343 "First entry preventing the TODO state change.")
12345 (defun org-cancel-repeater ()
12346 "Cancel a repeater by setting its numeric value to zero."
12347 (interactive)
12348 (save-excursion
12349 (org-back-to-heading t)
12350 (let ((bound1 (point))
12351 (bound0 (save-excursion (outline-next-heading) (point))))
12352 (when (and (re-search-forward
12353 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12354 org-deadline-time-regexp "\\)\\|\\("
12355 org-ts-regexp "\\)")
12356 bound0 t)
12357 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12358 bound1 t))
12359 (replace-match "0" t nil nil 1)))))
12361 (defvar org-state)
12362 (defvar org-blocked-by-checkboxes)
12363 (defun org-todo (&optional arg)
12364 "Change the TODO state of an item.
12366 The state of an item is given by a keyword at the start of the heading,
12367 like
12368 *** TODO Write paper
12369 *** DONE Call mom
12371 The different keywords are specified in the variable `org-todo-keywords'.
12372 By default the available states are \"TODO\" and \"DONE\". So, for this
12373 example: when the item starts with TODO, it is changed to DONE.
12374 When it starts with DONE, the DONE is removed. And when neither TODO nor
12375 DONE are present, add TODO at the beginning of the heading.
12377 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12378 state.
12379 With numeric prefix ARG, switch to that state.
12380 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12381 next set of TODO \
12382 keywords (nextset).
12383 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12384 prefix, circumvent any state blocking.
12385 With a numeric prefix arg of 0, inhibit note taking for the change.
12386 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12388 When called through ELisp, arg is also interpreted in the following way:
12389 `none' -> empty state
12390 \"\" -> switch to empty state
12391 `done' -> switch to DONE
12392 `nextset' -> switch to the next set of keywords
12393 `previousset' -> switch to the previous set of keywords
12394 \"WAITING\" -> switch to the specified keyword, but only if it
12395 really is a member of `org-todo-keywords'."
12396 (interactive "P")
12397 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12398 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12399 'region-start-level 'region))
12400 org-loop-over-headlines-in-active-region)
12401 (org-map-entries
12402 `(org-todo ,arg)
12403 org-loop-over-headlines-in-active-region
12404 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12405 (when (equal arg '(16)) (setq arg 'nextset))
12406 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12407 (let ((org-blocker-hook org-blocker-hook)
12408 commentp
12409 case-fold-search)
12410 (when (equal arg '(64))
12411 (setq arg nil org-blocker-hook nil))
12412 (when (and org-blocker-hook
12413 (or org-inhibit-blocking
12414 (org-entry-get nil "NOBLOCKING")))
12415 (setq org-blocker-hook nil))
12416 (save-excursion
12417 (catch 'exit
12418 (org-back-to-heading t)
12419 (when (org-in-commented-heading-p t)
12420 (org-toggle-comment)
12421 (setq commentp t))
12422 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12423 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12424 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12425 (let* ((match-data (match-data))
12426 (startpos (point-at-bol))
12427 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12428 (org-log-done org-log-done)
12429 (org-log-repeat org-log-repeat)
12430 (org-todo-log-states org-todo-log-states)
12431 (org-inhibit-logging
12432 (if (equal arg 0)
12433 (progn (setq arg nil) 'note) org-inhibit-logging))
12434 (this (match-string 1))
12435 (hl-pos (match-beginning 0))
12436 (head (org-get-todo-sequence-head this))
12437 (ass (assoc head org-todo-kwd-alist))
12438 (interpret (nth 1 ass))
12439 (done-word (nth 3 ass))
12440 (final-done-word (nth 4 ass))
12441 (org-last-state (or this ""))
12442 (completion-ignore-case t)
12443 (member (member this org-todo-keywords-1))
12444 (tail (cdr member))
12445 (org-state (cond
12446 ((and org-todo-key-trigger
12447 (or (and (equal arg '(4))
12448 (eq org-use-fast-todo-selection 'prefix))
12449 (and (not arg) org-use-fast-todo-selection
12450 (not (eq org-use-fast-todo-selection
12451 'prefix)))))
12452 ;; Use fast selection.
12453 (org-fast-todo-selection))
12454 ((and (equal arg '(4))
12455 (or (not org-use-fast-todo-selection)
12456 (not org-todo-key-trigger)))
12457 ;; Read a state with completion.
12458 (completing-read
12459 "State: " (mapcar #'list org-todo-keywords-1)
12460 nil t))
12461 ((eq arg 'right)
12462 (if this
12463 (if tail (car tail) nil)
12464 (car org-todo-keywords-1)))
12465 ((eq arg 'left)
12466 (unless (equal member org-todo-keywords-1)
12467 (if this
12468 (nth (- (length org-todo-keywords-1)
12469 (length tail) 2)
12470 org-todo-keywords-1)
12471 (org-last org-todo-keywords-1))))
12472 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12473 (setq arg nil))) ;hack to fall back to cycling
12474 (arg
12475 ;; User or caller requests a specific state.
12476 (cond
12477 ((equal arg "") nil)
12478 ((eq arg 'none) nil)
12479 ((eq arg 'done) (or done-word (car org-done-keywords)))
12480 ((eq arg 'nextset)
12481 (or (car (cdr (member head org-todo-heads)))
12482 (car org-todo-heads)))
12483 ((eq arg 'previousset)
12484 (let ((org-todo-heads (reverse org-todo-heads)))
12485 (or (car (cdr (member head org-todo-heads)))
12486 (car org-todo-heads))))
12487 ((car (member arg org-todo-keywords-1)))
12488 ((stringp arg)
12489 (user-error "State `%s' not valid in this file" arg))
12490 ((nth (1- (prefix-numeric-value arg))
12491 org-todo-keywords-1))))
12492 ((null member) (or head (car org-todo-keywords-1)))
12493 ((equal this final-done-word) nil) ;-> make empty
12494 ((null tail) nil) ;-> first entry
12495 ((memq interpret '(type priority))
12496 (if (eq this-command last-command)
12497 (car tail)
12498 (if (> (length tail) 0)
12499 (or done-word (car org-done-keywords))
12500 nil)))
12502 (car tail))))
12503 (org-state (or
12504 (run-hook-with-args-until-success
12505 'org-todo-get-default-hook org-state org-last-state)
12506 org-state))
12507 (next (if org-state (concat " " org-state " ") " "))
12508 (change-plist (list :type 'todo-state-change :from this :to org-state
12509 :position startpos))
12510 dolog now-done-p)
12511 (when org-blocker-hook
12512 (let (org-blocked-by-checkboxes block-reason)
12513 (setq org-last-todo-state-is-todo
12514 (not (member this org-done-keywords)))
12515 (unless (save-excursion
12516 (save-match-data
12517 (org-with-wide-buffer
12518 (run-hook-with-args-until-failure
12519 'org-blocker-hook change-plist))))
12520 (setq block-reason (if org-blocked-by-checkboxes
12521 "contained checkboxes"
12522 (format "\"%s\"" org-block-entry-blocking)))
12523 (if (called-interactively-p 'interactive)
12524 (user-error "TODO state change from %s to %s blocked (by %s)"
12525 this org-state block-reason)
12526 ;; Fail silently.
12527 (message "TODO state change from %s to %s blocked (by %s)"
12528 this org-state block-reason)
12529 (throw 'exit nil)))))
12530 (store-match-data match-data)
12531 (replace-match next t t)
12532 (cond ((equal this org-state)
12533 (message "TODO state was already %s" (org-trim next)))
12534 ((not (pos-visible-in-window-p hl-pos))
12535 (message "TODO state changed to %s" (org-trim next))))
12536 (unless head
12537 (setq head (org-get-todo-sequence-head org-state)
12538 ass (assoc head org-todo-kwd-alist)
12539 interpret (nth 1 ass)
12540 done-word (nth 3 ass)
12541 final-done-word (nth 4 ass)))
12542 (when (memq arg '(nextset previousset))
12543 (message "Keyword-Set %d/%d: %s"
12544 (- (length org-todo-sets) -1
12545 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12546 (length org-todo-sets)
12547 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12548 (setq org-last-todo-state-is-todo
12549 (not (member org-state org-done-keywords)))
12550 (setq now-done-p (and (member org-state org-done-keywords)
12551 (not (member this org-done-keywords))))
12552 (and logging (org-local-logging logging))
12553 (when (and (or org-todo-log-states org-log-done)
12554 (not (eq org-inhibit-logging t))
12555 (not (memq arg '(nextset previousset))))
12556 ;; We need to look at recording a time and note.
12557 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12558 (nth 2 (assoc this org-todo-log-states))))
12559 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12560 (setq dolog 'time))
12561 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12562 (and org-state
12563 (member org-state org-not-done-keywords)
12564 (not (member this org-not-done-keywords))))
12565 ;; This is now a todo state and was not one before
12566 ;; If there was a CLOSED time stamp, get rid of it.
12567 (org-add-planning-info nil nil 'closed))
12568 (when (and now-done-p org-log-done)
12569 ;; It is now done, and it was not done before.
12570 (org-add-planning-info 'closed (org-current-effective-time))
12571 (when (and (not dolog) (eq 'note org-log-done))
12572 (org-add-log-setup 'done org-state this 'note)))
12573 (when (and org-state dolog)
12574 ;; This is a non-nil state, and we need to log it.
12575 (org-add-log-setup 'state org-state this dolog)))
12576 ;; Fixup tag positioning.
12577 (org-todo-trigger-tag-changes org-state)
12578 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12579 (when org-provide-todo-statistics
12580 (org-update-parent-todo-statistics))
12581 (run-hooks 'org-after-todo-state-change-hook)
12582 (when (and arg (not (member org-state org-done-keywords)))
12583 (setq head (org-get-todo-sequence-head org-state)))
12584 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12585 ;; Do we need to trigger a repeat?
12586 (when now-done-p
12587 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12588 ;; This is for the agenda, take a snapshot of the headline.
12589 (save-match-data
12590 (setq org-agenda-headline-snapshot-before-repeat
12591 (org-get-heading))))
12592 (org-auto-repeat-maybe org-state))
12593 ;; Fixup cursor location if close to the keyword.
12594 (when (and (outline-on-heading-p)
12595 (not (bolp))
12596 (save-excursion (beginning-of-line 1)
12597 (looking-at org-todo-line-regexp))
12598 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12599 (goto-char (or (match-end 2) (match-end 1)))
12600 (and (looking-at " ") (just-one-space)))
12601 (when org-trigger-hook
12602 (save-excursion
12603 (run-hook-with-args 'org-trigger-hook change-plist)))
12604 (when commentp (org-toggle-comment))))))))
12606 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12607 "Block turning an entry into a TODO, using the hierarchy.
12608 This checks whether the current task should be blocked from state
12609 changes. Such blocking occurs when:
12611 1. The task has children which are not all in a completed state.
12613 2. A task has a parent with the property :ORDERED:, and there
12614 are siblings prior to the current task with incomplete
12615 status.
12617 3. The parent of the task is blocked because it has siblings that should
12618 be done first, or is child of a block grandparent TODO entry."
12620 (if (not org-enforce-todo-dependencies)
12621 t ; if locally turned off don't block
12622 (catch 'dont-block
12623 ;; If this is not a todo state change, or if this entry is already DONE,
12624 ;; do not block
12625 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12626 (member (plist-get change-plist :from)
12627 (cons 'done org-done-keywords))
12628 (member (plist-get change-plist :to)
12629 (cons 'todo org-not-done-keywords))
12630 (not (plist-get change-plist :to)))
12631 (throw 'dont-block t))
12632 ;; If this task has children, and any are undone, it's blocked
12633 (save-excursion
12634 (org-back-to-heading t)
12635 (let ((this-level (funcall outline-level)))
12636 (outline-next-heading)
12637 (let ((child-level (funcall outline-level)))
12638 (while (and (not (eobp))
12639 (> child-level this-level))
12640 ;; this todo has children, check whether they are all
12641 ;; completed
12642 (when (and (not (org-entry-is-done-p))
12643 (org-entry-is-todo-p))
12644 (setq org-block-entry-blocking (org-get-heading))
12645 (throw 'dont-block nil))
12646 (outline-next-heading)
12647 (setq child-level (funcall outline-level))))))
12648 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12649 ;; any previous siblings are undone, it's blocked
12650 (save-excursion
12651 (org-back-to-heading t)
12652 (let* ((pos (point))
12653 (parent-pos (and (org-up-heading-safe) (point)))
12654 (case-fold-search nil))
12655 (unless parent-pos (throw 'dont-block t)) ; no parent
12656 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12657 (forward-line 1)
12658 (re-search-forward org-not-done-heading-regexp pos t))
12659 (setq org-block-entry-blocking (match-string 0))
12660 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12661 ;; Search further up the hierarchy, to see if an ancestor is blocked
12662 (while t
12663 (goto-char parent-pos)
12664 (unless (looking-at org-not-done-heading-regexp)
12665 (throw 'dont-block t)) ; do not block, parent is not a TODO
12666 (setq pos (point))
12667 (setq parent-pos (and (org-up-heading-safe) (point)))
12668 (unless parent-pos (throw 'dont-block t)) ; no parent
12669 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12670 (forward-line 1)
12671 (re-search-forward org-not-done-heading-regexp pos t)
12672 (setq org-block-entry-blocking (org-get-heading)))
12673 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12675 (defcustom org-track-ordered-property-with-tag nil
12676 "Should the ORDERED property also be shown as a tag?
12677 The ORDERED property decides if an entry should require subtasks to be
12678 completed in sequence. Since a property is not very visible, setting
12679 this option means that toggling the ORDERED property with the command
12680 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12681 not relevant for the behavior, but it makes things more visible.
12683 Note that toggling the tag with tags commands will not change the property
12684 and therefore not influence behavior!
12686 This can be t, meaning the tag ORDERED should be used, It can also be a
12687 string to select a different tag for this task."
12688 :group 'org-todo
12689 :type '(choice
12690 (const :tag "No tracking" nil)
12691 (const :tag "Track with ORDERED tag" t)
12692 (string :tag "Use other tag")))
12694 (defun org-toggle-ordered-property ()
12695 "Toggle the ORDERED property of the current entry.
12696 For better visibility, you can track the value of this property with a tag.
12697 See variable `org-track-ordered-property-with-tag'."
12698 (interactive)
12699 (let* ((t1 org-track-ordered-property-with-tag)
12700 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12701 (save-excursion
12702 (org-back-to-heading)
12703 (if (org-entry-get nil "ORDERED")
12704 (progn
12705 (org-delete-property "ORDERED")
12706 (and tag (org-toggle-tag tag 'off))
12707 (message "Subtasks can be completed in arbitrary order"))
12708 (org-entry-put nil "ORDERED" "t")
12709 (and tag (org-toggle-tag tag 'on))
12710 (message "Subtasks must be completed in sequence")))))
12712 (defun org-block-todo-from-checkboxes (change-plist)
12713 "Block turning an entry into a TODO, using checkboxes.
12714 This checks whether the current task should be blocked from state
12715 changes because there are unchecked boxes in this entry."
12716 (if (not org-enforce-todo-checkbox-dependencies)
12717 t ; if locally turned off don't block
12718 (catch 'dont-block
12719 ;; If this is not a todo state change, or if this entry is already DONE,
12720 ;; do not block
12721 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12722 (member (plist-get change-plist :from)
12723 (cons 'done org-done-keywords))
12724 (member (plist-get change-plist :to)
12725 (cons 'todo org-not-done-keywords))
12726 (not (plist-get change-plist :to)))
12727 (throw 'dont-block t))
12728 ;; If this task has checkboxes that are not checked, it's blocked
12729 (save-excursion
12730 (org-back-to-heading t)
12731 (let ((beg (point)) end)
12732 (outline-next-heading)
12733 (setq end (point))
12734 (goto-char beg)
12735 (when (org-list-search-forward
12736 (concat (org-item-beginning-re)
12737 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12738 "\\[[- ]\\]")
12739 end t)
12740 (when (boundp 'org-blocked-by-checkboxes)
12741 (setq org-blocked-by-checkboxes t))
12742 (throw 'dont-block nil))))
12743 t))) ; do not block
12745 (defun org-entry-blocked-p ()
12746 "Non-nil if entry at point is blocked."
12747 (and (not (org-entry-get nil "NOBLOCKING"))
12748 (member (org-entry-get nil "TODO") org-not-done-keywords)
12749 (not (run-hook-with-args-until-failure
12750 'org-blocker-hook
12751 (list :type 'todo-state-change
12752 :position (point)
12753 :from 'todo
12754 :to 'done)))))
12756 (defun org-update-statistics-cookies (all)
12757 "Update the statistics cookie, either from TODO or from checkboxes.
12758 This should be called with the cursor in a line with a statistics
12759 cookie. When called with a \\[universal-argument] prefix, update
12760 all statistics cookies in the buffer."
12761 (interactive "P")
12762 (if all
12763 (progn
12764 (org-update-checkbox-count 'all)
12765 (org-map-entries 'org-update-parent-todo-statistics))
12766 (if (not (org-at-heading-p))
12767 (org-update-checkbox-count)
12768 (let ((pos (point-marker))
12769 end l1 l2)
12770 (ignore-errors (org-back-to-heading t))
12771 (if (not (org-at-heading-p))
12772 (org-update-checkbox-count)
12773 (setq l1 (org-outline-level))
12774 (setq end (save-excursion
12775 (outline-next-heading)
12776 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12777 (point)))
12778 (if (and (save-excursion
12779 (re-search-forward
12780 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12781 (not (save-excursion (re-search-forward
12782 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12783 (org-update-checkbox-count)
12784 (if (and l2 (> l2 l1))
12785 (progn
12786 (goto-char end)
12787 (org-update-parent-todo-statistics))
12788 (goto-char pos)
12789 (beginning-of-line 1)
12790 (while (re-search-forward
12791 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12792 (point-at-eol) t)
12793 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12794 (goto-char pos)
12795 (move-marker pos nil)))))
12797 (defvar org-entry-property-inherited-from) ;; defined below
12798 (defun org-update-parent-todo-statistics ()
12799 "Update any statistics cookie in the parent of the current headline.
12800 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12801 the entire subtree and this will travel up the hierarchy and update
12802 statistics everywhere."
12803 (let* ((prop (save-excursion (org-up-heading-safe)
12804 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12805 (recursive (or (not org-hierarchical-todo-statistics)
12806 (and prop (string-match "\\<recursive\\>" prop))))
12807 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12809 (first t)
12810 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12811 level ltoggle l1 new ndel
12812 (cnt-all 0) (cnt-done 0) is-percent kwd
12813 checkbox-beg cookie-present)
12814 (catch 'exit
12815 (save-excursion
12816 (beginning-of-line 1)
12817 (setq ltoggle (funcall outline-level))
12818 ;; Three situations are to consider:
12820 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12821 ;; to the top-level ancestor on the headline;
12823 ;; 2. If parent has "recursive" property, repeat up to the
12824 ;; headline setting that property, taking inheritance into
12825 ;; account;
12827 ;; 3. Else, move up to direct parent and proceed only once.
12828 (while (and (setq level (org-up-heading-safe))
12829 (or recursive first)
12830 (>= (point) lim))
12831 (setq first nil cookie-present nil)
12832 (unless (and level
12833 (not (string-match
12834 "\\<checkbox\\>"
12835 (downcase (or (org-entry-get nil "COOKIE_DATA")
12836 "")))))
12837 (throw 'exit nil))
12838 (while (re-search-forward box-re (point-at-eol) t)
12839 (setq cnt-all 0 cnt-done 0 cookie-present t)
12840 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12841 (save-match-data
12842 (unless (outline-next-heading) (throw 'exit nil))
12843 (while (and (looking-at org-complex-heading-regexp)
12844 (> (setq l1 (length (match-string 1))) level))
12845 (setq kwd (and (or recursive (= l1 ltoggle))
12846 (match-string 2)))
12847 (if (or (eq org-provide-todo-statistics 'all-headlines)
12848 (and (eq org-provide-todo-statistics t)
12849 (or (member kwd org-done-keywords)))
12850 (and (listp org-provide-todo-statistics)
12851 (stringp (car org-provide-todo-statistics))
12852 (or (member kwd org-provide-todo-statistics)
12853 (member kwd org-done-keywords)))
12854 (and (listp org-provide-todo-statistics)
12855 (listp (car org-provide-todo-statistics))
12856 (or (member kwd (car org-provide-todo-statistics))
12857 (and (member kwd org-done-keywords)
12858 (member kwd (cadr org-provide-todo-statistics))))))
12859 (setq cnt-all (1+ cnt-all))
12860 (and (eq org-provide-todo-statistics t)
12862 (setq cnt-all (1+ cnt-all))))
12863 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12864 (member kwd org-done-keywords))
12865 (and (listp org-provide-todo-statistics)
12866 (listp (car org-provide-todo-statistics))
12867 (member kwd org-done-keywords)
12868 (member kwd (cadr org-provide-todo-statistics)))
12869 (and (listp org-provide-todo-statistics)
12870 (stringp (car org-provide-todo-statistics))
12871 (member kwd org-done-keywords)))
12872 (setq cnt-done (1+ cnt-done)))
12873 (outline-next-heading)))
12874 (setq new
12875 (if is-percent
12876 (format "[%d%%]" (floor (* 100.0 cnt-done)
12877 (max 1 cnt-all)))
12878 (format "[%d/%d]" cnt-done cnt-all))
12879 ndel (- (match-end 0) checkbox-beg))
12880 (goto-char checkbox-beg)
12881 (insert new)
12882 (delete-region (point) (+ (point) ndel))
12883 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12884 (when cookie-present
12885 (run-hook-with-args 'org-after-todo-statistics-hook
12886 cnt-done (- cnt-all cnt-done))))))
12887 (run-hooks 'org-todo-statistics-hook)))
12889 (defvar org-after-todo-statistics-hook nil
12890 "Hook that is called after a TODO statistics cookie has been updated.
12891 Each function is called with two arguments: the number of not-done entries
12892 and the number of done entries.
12894 For example, the following function, when added to this hook, will switch
12895 an entry to DONE when all children are done, and back to TODO when new
12896 entries are set to a TODO status. Note that this hook is only called
12897 when there is a statistics cookie in the headline!
12899 (defun org-summary-todo (n-done n-not-done)
12900 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12901 (let (org-log-done org-log-states) ; turn off logging
12902 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12905 (defvar org-todo-statistics-hook nil
12906 "Hook that is run whenever Org thinks TODO statistics should be updated.
12907 This hook runs even if there is no statistics cookie present, in which case
12908 `org-after-todo-statistics-hook' would not run.")
12910 (defun org-todo-trigger-tag-changes (state)
12911 "Apply the changes defined in `org-todo-state-tags-triggers'."
12912 (let ((l org-todo-state-tags-triggers)
12913 changes)
12914 (when (or (not state) (equal state ""))
12915 (setq changes (append changes (cdr (assoc "" l)))))
12916 (when (and (stringp state) (> (length state) 0))
12917 (setq changes (append changes (cdr (assoc state l)))))
12918 (when (member state org-not-done-keywords)
12919 (setq changes (append changes (cdr (assq 'todo l)))))
12920 (when (member state org-done-keywords)
12921 (setq changes (append changes (cdr (assq 'done l)))))
12922 (dolist (c changes)
12923 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12925 (defun org-local-logging (value)
12926 "Get logging settings from a property VALUE."
12927 ;; Directly set the variables, they are already local.
12928 (setq org-log-done nil
12929 org-log-repeat nil
12930 org-todo-log-states nil)
12931 (dolist (w (org-split-string value))
12932 (let (a)
12933 (cond
12934 ((setq a (assoc w org-startup-options))
12935 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12936 (set (nth 1 a) (nth 2 a))))
12937 ((setq a (org-extract-log-state-settings w))
12938 (and (member (car a) org-todo-keywords-1)
12939 (push a org-todo-log-states)))))))
12941 (defun org-get-todo-sequence-head (kwd)
12942 "Return the head of the TODO sequence to which KWD belongs.
12943 If KWD is not set, check if there is a text property remembering the
12944 right sequence."
12945 (let (p)
12946 (cond
12947 ((not kwd)
12948 (or (get-text-property (point-at-bol) 'org-todo-head)
12949 (progn
12950 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12951 nil (point-at-eol)))
12952 (get-text-property p 'org-todo-head))))
12953 ((not (member kwd org-todo-keywords-1))
12954 (car org-todo-keywords-1))
12955 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12957 (defun org-fast-todo-selection ()
12958 "Fast TODO keyword selection with single keys.
12959 Returns the new TODO keyword, or nil if no state change should occur."
12960 (let* ((fulltable org-todo-key-alist)
12961 (done-keywords org-done-keywords) ;; needed for the faces.
12962 (maxlen (apply 'max (mapcar
12963 (lambda (x)
12964 (if (stringp (car x)) (string-width (car x)) 0))
12965 fulltable)))
12966 (expert nil)
12967 (fwidth (+ maxlen 3 1 3))
12968 (ncol (/ (- (window-width) 4) fwidth))
12969 tg cnt e c tbl
12970 groups ingroup)
12971 (save-excursion
12972 (save-window-excursion
12973 (if expert
12974 (set-buffer (get-buffer-create " *Org todo*"))
12975 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12976 (erase-buffer)
12977 (setq-local org-done-keywords done-keywords)
12978 (setq tbl fulltable cnt 0)
12979 (while (setq e (pop tbl))
12980 (cond
12981 ((equal e '(:startgroup))
12982 (push '() groups) (setq ingroup t)
12983 (unless (= cnt 0)
12984 (setq cnt 0)
12985 (insert "\n"))
12986 (insert "{ "))
12987 ((equal e '(:endgroup))
12988 (setq ingroup nil cnt 0)
12989 (insert "}\n"))
12990 ((equal e '(:newline))
12991 (unless (= cnt 0)
12992 (setq cnt 0)
12993 (insert "\n")
12994 (setq e (car tbl))
12995 (while (equal (car tbl) '(:newline))
12996 (insert "\n")
12997 (setq tbl (cdr tbl)))))
12999 (setq tg (car e) c (cdr e))
13000 (when ingroup (push tg (car groups)))
13001 (setq tg (org-add-props tg nil 'face
13002 (org-get-todo-face tg)))
13003 (when (and (= cnt 0) (not ingroup)) (insert " "))
13004 (insert "[" c "] " tg (make-string
13005 (- fwidth 4 (length tg)) ?\ ))
13006 (when (= (setq cnt (1+ cnt)) ncol)
13007 (insert "\n")
13008 (when ingroup (insert " "))
13009 (setq cnt 0)))))
13010 (insert "\n")
13011 (goto-char (point-min))
13012 (unless expert (org-fit-window-to-buffer))
13013 (message "[a-z..]:Set [SPC]:clear")
13014 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13015 (cond
13016 ((or (= c ?\C-g)
13017 (and (= c ?q) (not (rassoc c fulltable))))
13018 (setq quit-flag t))
13019 ((= c ?\ ) nil)
13020 ((setq e (rassoc c fulltable) tg (car e))
13022 (t (setq quit-flag t)))))))
13024 (defun org-entry-is-todo-p ()
13025 (member (org-get-todo-state) org-not-done-keywords))
13027 (defun org-entry-is-done-p ()
13028 (member (org-get-todo-state) org-done-keywords))
13030 (defun org-get-todo-state ()
13031 "Return the TODO keyword of the current subtree."
13032 (save-excursion
13033 (org-back-to-heading t)
13034 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13035 (match-end 2)
13036 (match-string 2))))
13038 (defun org-at-date-range-p (&optional inactive-ok)
13039 "Non-nil if point is inside a date range.
13041 When optional argument INACTIVE-OK is non-nil, also consider
13042 inactive time ranges.
13044 When this function returns a non-nil value, match data is set
13045 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13046 on INACTIVE-OK."
13047 (interactive)
13048 (save-excursion
13049 (catch 'exit
13050 (let ((pos (point)))
13051 (skip-chars-backward "^[<\r\n")
13052 (skip-chars-backward "<[")
13053 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13054 (>= (match-end 0) pos)
13055 (throw 'exit t))
13056 (skip-chars-backward "^<[\r\n")
13057 (skip-chars-backward "<[")
13058 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13059 (>= (match-end 0) pos)
13060 (throw 'exit t)))
13061 nil)))
13063 (defun org-get-repeat (&optional timestamp)
13064 "Check if there is a time-stamp with repeater in this entry.
13066 Return the repeater, as a string, or nil. Also return nil when
13067 this function is called before first heading.
13069 When optional argument TIMESTAMP is a string, extract the
13070 repeater from there instead."
13071 (save-match-data
13072 (cond (timestamp
13073 (and (string-match org-repeat-re timestamp)
13074 (match-string-no-properties 1 timestamp)))
13075 ((org-before-first-heading-p) nil)
13077 (save-excursion
13078 (org-back-to-heading t)
13079 (let ((end (org-entry-end-position)))
13080 (catch :repeat
13081 (while (re-search-forward org-repeat-re end t)
13082 (when (save-match-data (org-at-timestamp-p 'agenda))
13083 (throw :repeat (match-string-no-properties 1)))))))))))
13085 (defvar org-last-changed-timestamp)
13086 (defvar org-last-inserted-timestamp)
13087 (defvar org-log-post-message)
13088 (defvar org-log-note-purpose)
13089 (defvar org-log-note-how nil)
13090 (defvar org-log-note-extra)
13091 (defun org-auto-repeat-maybe (done-word)
13092 "Check if the current headline contains a repeated time-stamp.
13094 If yes, set TODO state back to what it was and change the base date
13095 of repeating deadline/scheduled time stamps to new date.
13097 This function is run automatically after each state change to a DONE state."
13098 (let* ((repeat (org-get-repeat))
13099 (aa (assoc org-last-state org-todo-kwd-alist))
13100 (interpret (nth 1 aa))
13101 (head (nth 2 aa))
13102 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13103 (msg "Entry repeats: ")
13104 (org-log-done nil)
13105 (org-todo-log-states nil)
13106 (end (copy-marker (org-entry-end-position))))
13107 (unwind-protect
13108 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13109 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13110 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13111 org-todo-repeat-to-state)))
13112 (org-todo (cond
13113 ((and to-state (member to-state org-todo-keywords-1))
13114 to-state)
13115 ((eq interpret 'type) org-last-state)
13116 (head)
13117 (t 'none))))
13118 (org-back-to-heading t)
13119 (org-add-planning-info nil nil 'closed)
13120 ;; When `org-log-repeat' is non-nil or entry contains
13121 ;; a clock, set LAST_REPEAT property.
13122 (when (or org-log-repeat
13123 (catch :clock
13124 (while (re-search-forward org-clock-line-re end t)
13125 (when (org-at-clock-log-p) (throw :clock t)))))
13126 (org-entry-put nil "LAST_REPEAT" (format-time-string
13127 (org-time-stamp-format t t)
13128 (current-time))))
13129 (when org-log-repeat
13130 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13131 (memq 'org-add-log-note post-command-hook))
13132 ;; We are already setup for some record.
13133 (when (eq org-log-repeat 'note)
13134 ;; Make sure we take a note, not only a time stamp.
13135 (setq org-log-note-how 'note))
13136 ;; Set up for taking a record.
13137 (org-add-log-setup 'state
13138 (or done-word (car org-done-keywords))
13139 org-last-state
13140 org-log-repeat)))
13141 (let ((planning-re (regexp-opt
13142 (list org-scheduled-string org-deadline-string))))
13143 (while (re-search-forward org-ts-regexp end t)
13144 (let* ((ts (match-string 0))
13145 (planning? (org-at-planning-p))
13146 (type (if (not planning?) "Plain:"
13147 (save-excursion
13148 (re-search-backward
13149 planning-re (line-beginning-position) t)
13150 (match-string 0)))))
13151 (cond
13152 ;; Ignore fake time-stamps (e.g., within comments).
13153 ((not (org-at-timestamp-p 'agenda)))
13154 ;; Time-stamps without a repeater are usually
13155 ;; skipped. However, a SCHEDULED time-stamp without
13156 ;; one is removed, as they are no longer relevant.
13157 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13158 ts))
13159 (when (equal type org-scheduled-string)
13160 (org-remove-timestamp-with-keyword type)))
13162 (let ((n (string-to-number (match-string 2 ts)))
13163 (what (match-string 3 ts)))
13164 (when (equal what "w") (setq n (* n 7) what "d"))
13165 (when (and (equal what "h")
13166 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13167 ts)))
13168 (user-error
13169 "Cannot repeat in Repeat in %d hour(s) because no hour \
13170 has been set"
13172 ;; Preparation, see if we need to modify the start
13173 ;; date for the change.
13174 (when (match-end 1)
13175 (let ((time (save-match-data
13176 (org-time-string-to-time ts))))
13177 (cond
13178 ((equal (match-string 1 ts) ".")
13179 ;; Shift starting date to today
13180 (org-timestamp-change
13181 (- (org-today) (time-to-days time))
13182 'day))
13183 ((equal (match-string 1 ts) "+")
13184 (let ((nshiftmax 10)
13185 (nshift 0))
13186 (while (or (= nshift 0)
13187 (not (time-less-p (current-time) time)))
13188 (when (= (cl-incf nshift) nshiftmax)
13189 (or (y-or-n-p
13190 (format "%d repeater intervals were not \
13191 enough to shift date past today. Continue? "
13192 nshift))
13193 (user-error "Abort")))
13194 (org-timestamp-change n (cdr (assoc what whata)))
13195 (org-in-regexp org-ts-regexp3)
13196 (setq ts (match-string 1))
13197 (setq time
13198 (save-match-data
13199 (org-time-string-to-time ts)))))
13200 (org-timestamp-change (- n) (cdr (assoc what whata)))
13201 ;; Rematch, so that we have everything in place
13202 ;; for the real shift.
13203 (org-in-regexp org-ts-regexp3)
13204 (setq ts (match-string 1))
13205 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13206 ts)))))
13207 (save-excursion
13208 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13209 (setq msg
13210 (concat
13211 msg type " " org-last-changed-timestamp " "))))))))
13212 (setq org-log-post-message msg)
13213 (message "%s" msg))
13214 (set-marker end nil))))
13216 (defun org-show-todo-tree (arg)
13217 "Make a compact tree which shows all headlines marked with TODO.
13218 The tree will show the lines where the regexp matches, and all higher
13219 headlines above the match.
13220 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13221 With a numeric prefix N, construct a sparse tree for the Nth element
13222 of `org-todo-keywords-1'."
13223 (interactive "P")
13224 (let ((case-fold-search nil)
13225 (kwd-re
13226 (cond ((null arg) org-not-done-regexp)
13227 ((equal arg '(4))
13228 (let ((kwd
13229 (completing-read "Keyword (or KWD1|KWD2|...): "
13230 (mapcar #'list org-todo-keywords-1))))
13231 (concat "\\("
13232 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13233 "\\)\\>")))
13234 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13235 (regexp-quote (nth (1- (prefix-numeric-value arg))
13236 org-todo-keywords-1)))
13237 (t (user-error "Invalid prefix argument: %s" arg)))))
13238 (message "%d TODO entries found"
13239 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13241 (defun org--deadline-or-schedule (arg type time)
13242 "Insert DEADLINE or SCHEDULE information in current entry.
13243 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13244 `org-schedule' for information about ARG and TIME arguments."
13245 (let* ((deadline? (eq type 'deadline))
13246 (keyword (if deadline? org-deadline-string org-scheduled-string))
13247 (log (if deadline? org-log-redeadline org-log-reschedule))
13248 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13249 (old-date-time (and old-date (org-time-string-to-time old-date)))
13250 ;; Save repeater cookie from either TIME or current scheduled
13251 ;; time stamp. We are going to insert it back at the end of
13252 ;; the process.
13253 (repeater (or (and (org-string-nw-p time)
13254 ;; We use `org-repeat-re' because we need
13255 ;; to tell the difference between a real
13256 ;; repeater and a time delta, e.g. "+2d".
13257 (string-match org-repeat-re time)
13258 (match-string 1 time))
13259 (and (org-string-nw-p old-date)
13260 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13261 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13262 old-date)
13263 (match-string 1 old-date)))))
13264 (pcase arg
13265 (`(4)
13266 (when (and old-date log)
13267 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13268 nil old-date log))
13269 (org-remove-timestamp-with-keyword keyword)
13270 (message (if deadline? "Item no longer has a deadline."
13271 "Item is no longer scheduled.")))
13272 (`(16)
13273 (save-excursion
13274 (org-back-to-heading t)
13275 (let ((regexp (if deadline? org-deadline-time-regexp
13276 org-scheduled-time-regexp)))
13277 (if (not (re-search-forward regexp (line-end-position 2) t))
13278 (user-error (if deadline? "No deadline information to update"
13279 "No scheduled information to update"))
13280 (let* ((rpl0 (match-string 1))
13281 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13282 (msg (if deadline? "Warn starting from" "Delay until")))
13283 (replace-match
13284 (concat keyword
13285 " <" rpl
13286 (format " -%dd"
13287 (abs (- (time-to-days
13288 (save-match-data
13289 (org-read-date
13290 nil t nil msg old-date-time)))
13291 (time-to-days old-date-time))))
13292 ">") t t))))))
13294 (org-add-planning-info type time 'closed)
13295 (when (and old-date
13297 (not (equal old-date org-last-inserted-timestamp)))
13298 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13299 org-last-inserted-timestamp
13300 old-date
13301 log))
13302 (when repeater
13303 (save-excursion
13304 (org-back-to-heading t)
13305 (when (re-search-forward
13306 (concat keyword " " org-last-inserted-timestamp)
13307 (line-end-position 2)
13309 (goto-char (1- (match-end 0)))
13310 (insert " " repeater)
13311 (setq org-last-inserted-timestamp
13312 (concat (substring org-last-inserted-timestamp 0 -1)
13313 " " repeater
13314 (substring org-last-inserted-timestamp -1))))))
13315 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13316 org-last-inserted-timestamp)))))
13318 (defun org-deadline (arg &optional time)
13319 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13320 With one universal prefix argument, remove any deadline from the item.
13321 With two universal prefix arguments, prompt for a warning delay.
13322 With argument TIME, set the deadline at the corresponding date. TIME
13323 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13324 (interactive "P")
13325 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13326 (org-map-entries
13327 (lambda () (org--deadline-or-schedule arg 'deadline time))
13329 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13330 'region-start-level
13331 'region)
13332 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13333 (org--deadline-or-schedule arg 'deadline time)))
13335 (defun org-schedule (arg &optional time)
13336 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13337 With one universal prefix argument, remove any scheduling date from the item.
13338 With two universal prefix arguments, prompt for a delay cookie.
13339 With argument TIME, scheduled at the corresponding date. TIME can
13340 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13341 (interactive "P")
13342 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13343 (org-map-entries
13344 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13346 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13347 'region-start-level
13348 'region)
13349 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13350 (org--deadline-or-schedule arg 'scheduled time)))
13352 (defun org-get-scheduled-time (pom &optional inherit)
13353 "Get the scheduled time as a time tuple, of a format suitable
13354 for calling org-schedule with, or if there is no scheduling,
13355 returns nil."
13356 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13357 (when time
13358 (apply 'encode-time (org-parse-time-string time)))))
13360 (defun org-get-deadline-time (pom &optional inherit)
13361 "Get the deadline as a time tuple, of a format suitable for
13362 calling org-deadline with, or if there is no scheduling, returns
13363 nil."
13364 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13365 (when time
13366 (apply 'encode-time (org-parse-time-string time)))))
13368 (defun org-remove-timestamp-with-keyword (keyword)
13369 "Remove all time stamps with KEYWORD in the current entry."
13370 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13371 beg)
13372 (save-excursion
13373 (org-back-to-heading t)
13374 (setq beg (point))
13375 (outline-next-heading)
13376 (while (re-search-backward re beg t)
13377 (replace-match "")
13378 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13379 (equal (char-before) ?\ ))
13380 (backward-delete-char 1)
13381 (when (string-match "^[ \t]*$" (buffer-substring
13382 (point-at-bol) (point-at-eol)))
13383 (delete-region (point-at-bol)
13384 (min (point-max) (1+ (point-at-eol))))))))))
13386 (defvar org-time-was-given) ; dynamically scoped parameter
13387 (defvar org-end-time-was-given) ; dynamically scoped parameter
13389 (defun org-at-planning-p ()
13390 "Non-nil when point is on a planning info line."
13391 ;; This is as accurate and faster than `org-element-at-point' since
13392 ;; planning info location is fixed in the section.
13393 (org-with-wide-buffer
13394 (beginning-of-line)
13395 (and (looking-at-p org-planning-line-re)
13396 (eq (point)
13397 (ignore-errors
13398 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13399 (org-back-to-heading t)
13400 (org-with-limited-levels (org-back-to-heading t)))
13401 (line-beginning-position 2))))))
13403 (defun org-add-planning-info (what &optional time &rest remove)
13404 "Insert new timestamp with keyword in the planning line.
13405 WHAT indicates what kind of time stamp to add. It is a symbol
13406 among `closed', `deadline', `scheduled' and nil. TIME indicates
13407 the time to use. If none is given, the user is prompted for
13408 a date. REMOVE indicates what kind of entries to remove. An old
13409 WHAT entry will also be removed."
13410 (let (org-time-was-given org-end-time-was-given default-time default-input)
13411 (catch 'exit
13412 (when (and (memq what '(scheduled deadline))
13413 (or (not time)
13414 (and (stringp time)
13415 (string-match "^[-+]+[0-9]" time))))
13416 ;; Try to get a default date/time from existing timestamp
13417 (save-excursion
13418 (org-back-to-heading t)
13419 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13420 (when (re-search-forward (if (eq what 'scheduled)
13421 org-scheduled-time-regexp
13422 org-deadline-time-regexp)
13423 end t)
13424 (setq ts (match-string 1)
13425 default-time (apply 'encode-time (org-parse-time-string ts))
13426 default-input (and ts (org-get-compact-tod ts)))))))
13427 (when what
13428 (setq time
13429 (if (stringp time)
13430 ;; This is a string (relative or absolute), set
13431 ;; proper date.
13432 (apply #'encode-time
13433 (org-read-date-analyze
13434 time default-time (decode-time default-time)))
13435 ;; If necessary, get the time from the user
13436 (or time (org-read-date nil 'to-time nil nil
13437 default-time default-input)))))
13439 (org-with-wide-buffer
13440 (org-back-to-heading t)
13441 (forward-line)
13442 (unless (bolp) (insert "\n"))
13443 (cond ((looking-at-p org-planning-line-re)
13444 ;; Move to current indentation.
13445 (skip-chars-forward " \t")
13446 ;; Check if we have to remove something.
13447 (dolist (type (if what (cons what remove) remove))
13448 (save-excursion
13449 (when (re-search-forward
13450 (cl-case type
13451 (closed org-closed-time-regexp)
13452 (deadline org-deadline-time-regexp)
13453 (scheduled org-scheduled-time-regexp)
13454 (otherwise
13455 (error "Invalid planning type: %s" type)))
13456 (line-end-position) t)
13457 ;; Delete until next keyword or end of line.
13458 (delete-region
13459 (match-beginning 0)
13460 (if (re-search-forward org-keyword-time-not-clock-regexp
13461 (line-end-position)
13463 (match-beginning 0)
13464 (line-end-position))))))
13465 ;; If there is nothing more to add and no more keyword
13466 ;; is left, remove the line completely.
13467 (if (and (looking-at-p "[ \t]*$") (not what))
13468 (delete-region (line-beginning-position)
13469 (line-beginning-position 2))
13470 ;; If we removed last keyword, do not leave trailing
13471 ;; white space at the end of line.
13472 (let ((p (point)))
13473 (save-excursion
13474 (end-of-line)
13475 (unless (= (skip-chars-backward " \t" p) 0)
13476 (delete-region (point) (line-end-position)))))))
13477 ((not what) (throw 'exit nil)) ; Nothing to do.
13478 (t (insert-before-markers "\n")
13479 (backward-char 1)
13480 (when org-adapt-indentation
13481 (indent-to-column (1+ (org-outline-level))))))
13482 (when what
13483 ;; Insert planning keyword.
13484 (insert (cl-case what
13485 (closed org-closed-string)
13486 (deadline org-deadline-string)
13487 (scheduled org-scheduled-string)
13488 (otherwise (error "Invalid planning type: %s" what)))
13489 " ")
13490 ;; Insert associated timestamp.
13491 (let ((ts (org-insert-time-stamp
13492 time
13493 (or org-time-was-given
13494 (and (eq what 'closed) org-log-done-with-time))
13495 (eq what 'closed)
13496 nil nil (list org-end-time-was-given))))
13497 (unless (eolp) (insert " "))
13498 ts))))))
13500 (defvar org-log-note-marker (make-marker)
13501 "Marker pointing at the entry where the note is to be inserted.")
13502 (defvar org-log-note-purpose nil)
13503 (defvar org-log-note-state nil)
13504 (defvar org-log-note-previous-state nil)
13505 (defvar org-log-note-extra nil)
13506 (defvar org-log-note-window-configuration nil)
13507 (defvar org-log-note-return-to (make-marker))
13508 (defvar org-log-note-effective-time nil
13509 "Remembered current time so that dynamically scoped
13510 `org-extend-today-until' affects timestamps in state change log")
13512 (defvar org-log-post-message nil
13513 "Message to be displayed after a log note has been stored.
13514 The auto-repeater uses this.")
13516 (defun org-add-note ()
13517 "Add a note to the current entry.
13518 This is done in the same way as adding a state change note."
13519 (interactive)
13520 (org-add-log-setup 'note))
13522 (defun org-log-beginning (&optional create)
13523 "Return expected start of log notes in current entry.
13524 When optional argument CREATE is non-nil, the function creates
13525 a drawer to store notes, if necessary. Returned position ignores
13526 narrowing."
13527 (org-with-wide-buffer
13528 (let ((drawer (org-log-into-drawer)))
13529 (cond
13530 (drawer
13531 (org-end-of-meta-data)
13532 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13533 (end (if (org-at-heading-p) (point)
13534 (save-excursion (outline-next-heading) (point))))
13535 (case-fold-search t))
13536 (catch 'exit
13537 ;; Try to find existing drawer.
13538 (while (re-search-forward regexp end t)
13539 (let ((element (org-element-at-point)))
13540 (when (eq (org-element-type element) 'drawer)
13541 (let ((cend (org-element-property :contents-end element)))
13542 (when (and (not org-log-states-order-reversed) cend)
13543 (goto-char cend)))
13544 (throw 'exit nil))))
13545 ;; No drawer found. Create one, if permitted.
13546 (when create
13547 (unless (bolp) (insert "\n"))
13548 (let ((beg (point)))
13549 (insert ":" drawer ":\n:END:\n")
13550 (org-indent-region beg (point)))
13551 (end-of-line -1)))))
13553 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13554 (skip-chars-forward " \t\n")
13555 (beginning-of-line)
13556 (unless org-log-states-order-reversed
13557 (org-skip-over-state-notes)
13558 (skip-chars-backward " \t\n")
13559 (forward-line)))))
13560 (if (bolp) (point) (line-beginning-position 2))))
13562 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13563 "Set up the post command hook to take a note.
13564 If this is about to TODO state change, the new state is expected in STATE.
13565 HOW is an indicator what kind of note should be created.
13566 EXTRA is additional text that will be inserted into the notes buffer."
13567 (move-marker org-log-note-marker (point))
13568 (setq org-log-note-purpose purpose
13569 org-log-note-state state
13570 org-log-note-previous-state prev-state
13571 org-log-note-how how
13572 org-log-note-extra extra
13573 org-log-note-effective-time (org-current-effective-time))
13574 (add-hook 'post-command-hook 'org-add-log-note 'append))
13576 (defun org-skip-over-state-notes ()
13577 "Skip past the list of State notes in an entry."
13578 (when (ignore-errors (goto-char (org-in-item-p)))
13579 (let* ((struct (org-list-struct))
13580 (prevs (org-list-prevs-alist struct))
13581 (regexp
13582 (concat "[ \t]*- +"
13583 (replace-regexp-in-string
13584 " +" " +"
13585 (org-replace-escapes
13586 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13587 `(("%d" . ,org-ts-regexp-inactive)
13588 ("%D" . ,org-ts-regexp)
13589 ("%s" . "\"\\S-+\"")
13590 ("%S" . "\"\\S-+\"")
13591 ("%t" . ,org-ts-regexp-inactive)
13592 ("%T" . ,org-ts-regexp)
13593 ("%u" . ".*?")
13594 ("%U" . ".*?")))))))
13595 (while (looking-at-p regexp)
13596 (goto-char (or (org-list-get-next-item (point) struct prevs)
13597 (org-list-get-item-end (point) struct)))))))
13599 (defun org-add-log-note (&optional _purpose)
13600 "Pop up a window for taking a note, and add this note later."
13601 (remove-hook 'post-command-hook 'org-add-log-note)
13602 (setq org-log-note-window-configuration (current-window-configuration))
13603 (delete-other-windows)
13604 (move-marker org-log-note-return-to (point))
13605 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13606 (goto-char org-log-note-marker)
13607 (org-switch-to-buffer-other-window "*Org Note*")
13608 (erase-buffer)
13609 (if (memq org-log-note-how '(time state))
13610 (org-store-log-note)
13611 (let ((org-inhibit-startup t)) (org-mode))
13612 (insert (format "# Insert note for %s.
13613 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13614 (cond
13615 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13616 ((eq org-log-note-purpose 'done) "closed todo item")
13617 ((eq org-log-note-purpose 'state)
13618 (format "state change from \"%s\" to \"%s\""
13619 (or org-log-note-previous-state "")
13620 (or org-log-note-state "")))
13621 ((eq org-log-note-purpose 'reschedule)
13622 "rescheduling")
13623 ((eq org-log-note-purpose 'delschedule)
13624 "no longer scheduled")
13625 ((eq org-log-note-purpose 'redeadline)
13626 "changing deadline")
13627 ((eq org-log-note-purpose 'deldeadline)
13628 "removing deadline")
13629 ((eq org-log-note-purpose 'refile)
13630 "refiling")
13631 ((eq org-log-note-purpose 'note)
13632 "this entry")
13633 (t (error "This should not happen")))))
13634 (when org-log-note-extra (insert org-log-note-extra))
13635 (setq-local org-finish-function 'org-store-log-note)
13636 (run-hooks 'org-log-buffer-setup-hook)))
13638 (defvar org-note-abort nil) ; dynamically scoped
13639 (defun org-store-log-note ()
13640 "Finish taking a log note, and insert it to where it belongs."
13641 (let ((txt (prog1 (buffer-string)
13642 (kill-buffer)))
13643 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13644 lines)
13645 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13646 (setq txt (replace-match "" t t txt)))
13647 (when (string-match "\\s-+\\'" txt)
13648 (setq txt (replace-match "" t t txt)))
13649 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13650 (when (org-string-nw-p note)
13651 (setq note
13652 (org-replace-escapes
13653 note
13654 (list (cons "%u" (user-login-name))
13655 (cons "%U" user-full-name)
13656 (cons "%t" (format-time-string
13657 (org-time-stamp-format 'long 'inactive)
13658 org-log-note-effective-time))
13659 (cons "%T" (format-time-string
13660 (org-time-stamp-format 'long nil)
13661 org-log-note-effective-time))
13662 (cons "%d" (format-time-string
13663 (org-time-stamp-format nil 'inactive)
13664 org-log-note-effective-time))
13665 (cons "%D" (format-time-string
13666 (org-time-stamp-format nil nil)
13667 org-log-note-effective-time))
13668 (cons "%s" (cond
13669 ((not org-log-note-state) "")
13670 ((string-match-p org-ts-regexp
13671 org-log-note-state)
13672 (format "\"[%s]\""
13673 (substring org-log-note-state 1 -1)))
13674 (t (format "\"%s\"" org-log-note-state))))
13675 (cons "%S"
13676 (cond
13677 ((not org-log-note-previous-state) "")
13678 ((string-match-p org-ts-regexp
13679 org-log-note-previous-state)
13680 (format "\"[%s]\""
13681 (substring
13682 org-log-note-previous-state 1 -1)))
13683 (t (format "\"%s\""
13684 org-log-note-previous-state)))))))
13685 (when lines (setq note (concat note " \\\\")))
13686 (push note lines))
13687 (when (and lines (not org-note-abort))
13688 (with-current-buffer (marker-buffer org-log-note-marker)
13689 (org-with-wide-buffer
13690 ;; Find location for the new note.
13691 (goto-char org-log-note-marker)
13692 (set-marker org-log-note-marker nil)
13693 ;; Note associated to a clock is to be located right after
13694 ;; the clock. Do not move point.
13695 (unless (eq org-log-note-purpose 'clock-out)
13696 (goto-char (org-log-beginning t)))
13697 ;; Make sure point is at the beginning of an empty line.
13698 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13699 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13700 ;; In an existing list, add a new item at the top level.
13701 ;; Otherwise, indent line like a regular one.
13702 (let ((itemp (org-in-item-p)))
13703 (if itemp
13704 (indent-line-to
13705 (let ((struct (save-excursion
13706 (goto-char itemp) (org-list-struct))))
13707 (org-list-get-ind (org-list-get-top-point struct) struct)))
13708 (org-indent-line)))
13709 (insert (org-list-bullet-string "-") (pop lines))
13710 (let ((ind (org-list-item-body-column (line-beginning-position))))
13711 (dolist (line lines)
13712 (insert "\n")
13713 (indent-line-to ind)
13714 (insert line)))
13715 (message "Note stored")
13716 (org-back-to-heading t)
13717 (org-cycle-hide-drawers 'children))
13718 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13719 ;; from within `org-add-log-note' because `buffer-undo-list'
13720 ;; is then modified outside of `org-with-remote-undo'.
13721 (when (eq this-command 'org-agenda-todo)
13722 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13723 ;; Don't add undo information when called from `org-agenda-todo'.
13724 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13725 (set-window-configuration org-log-note-window-configuration)
13726 (with-current-buffer (marker-buffer org-log-note-return-to)
13727 (goto-char org-log-note-return-to))
13728 (move-marker org-log-note-return-to nil)
13729 (when org-log-post-message (message "%s" org-log-post-message))))
13731 (defun org-remove-empty-drawer-at (pos)
13732 "Remove an empty drawer at position POS.
13733 POS may also be a marker."
13734 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13735 (org-with-wide-buffer
13736 (goto-char pos)
13737 (let ((drawer (org-element-at-point)))
13738 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13739 (not (org-element-property :contents-begin drawer)))
13740 (delete-region (org-element-property :begin drawer)
13741 (progn (goto-char (org-element-property :end drawer))
13742 (skip-chars-backward " \r\t\n")
13743 (forward-line)
13744 (point))))))))
13746 (defvar org-ts-type nil)
13747 (defun org-sparse-tree (&optional arg type)
13748 "Create a sparse tree, prompt for the details.
13749 This command can create sparse trees. You first need to select the type
13750 of match used to create the tree:
13752 t Show all TODO entries.
13753 T Show entries with a specific TODO keyword.
13754 m Show entries selected by a tags/property match.
13755 p Enter a property name and its value (both with completion on existing
13756 names/values) and show entries with that property.
13757 r Show entries matching a regular expression (`/' can be used as well).
13758 b Show deadlines and scheduled items before a date.
13759 a Show deadlines and scheduled items after a date.
13760 d Show deadlines due within `org-deadline-warning-days'.
13761 D Show deadlines and scheduled items between a date range."
13762 (interactive "P")
13763 (setq type (or type org-sparse-tree-default-date-type))
13764 (setq org-ts-type type)
13765 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13766 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13767 \[c]ycle through date types: %s"
13768 (cl-case type
13769 (all "all timestamps")
13770 (scheduled "only scheduled")
13771 (deadline "only deadline")
13772 (active "only active timestamps")
13773 (inactive "only inactive timestamps")
13774 (closed "with a closed time-stamp")
13775 (otherwise "scheduled/deadline")))
13776 (let ((answer (read-char-exclusive)))
13777 (cl-case answer
13779 (org-sparse-tree
13781 (cadr
13782 (memq type '(nil all scheduled deadline active inactive closed)))))
13783 (?d (call-interactively 'org-check-deadlines))
13784 (?b (call-interactively 'org-check-before-date))
13785 (?a (call-interactively 'org-check-after-date))
13786 (?D (call-interactively 'org-check-dates-range))
13787 (?t (call-interactively 'org-show-todo-tree))
13788 (?T (org-show-todo-tree '(4)))
13789 (?m (call-interactively 'org-match-sparse-tree))
13790 ((?p ?P)
13791 (let* ((kwd (completing-read
13792 "Property: " (mapcar #'list (org-buffer-property-keys))))
13793 (value (completing-read
13794 "Value: " (mapcar #'list (org-property-values kwd)))))
13795 (unless (string-match "\\`{.*}\\'" value)
13796 (setq value (concat "\"" value "\"")))
13797 (org-match-sparse-tree arg (concat kwd "=" value))))
13798 ((?r ?R ?/) (call-interactively 'org-occur))
13799 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13801 (defvar-local org-occur-highlights nil
13802 "List of overlays used for occur matches.")
13803 (defvar-local org-occur-parameters nil
13804 "Parameters of the active org-occur calls.
13805 This is a list, each call to org-occur pushes as cons cell,
13806 containing the regular expression and the callback, onto the list.
13807 The list can contain several entries if `org-occur' has been called
13808 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13809 will only contain one set of parameters. When the highlights are
13810 removed (for example with `C-c C-c', or with the next edit (depending
13811 on `org-remove-highlights-with-change'), this variable is emptied
13812 as well.")
13814 (defun org-occur (regexp &optional keep-previous callback)
13815 "Make a compact tree which shows all matches of REGEXP.
13817 The tree will show the lines where the regexp matches, and any other context
13818 defined in `org-show-context-detail', which see.
13820 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13821 done by a previous call to `org-occur' will be kept, to allow stacking of
13822 calls to this command.
13824 Optional argument CALLBACK can be a function of no argument. In this case,
13825 it is called with point at the end of the match, match data being set
13826 accordingly. Current match is shown only if the return value is non-nil.
13827 The function must neither move point nor alter narrowing."
13828 (interactive "sRegexp: \nP")
13829 (when (equal regexp "")
13830 (user-error "Regexp cannot be empty"))
13831 (unless keep-previous
13832 (org-remove-occur-highlights nil nil t))
13833 (push (cons regexp callback) org-occur-parameters)
13834 (let ((cnt 0))
13835 (save-excursion
13836 (goto-char (point-min))
13837 (when (or (not keep-previous) ; do not want to keep
13838 (not org-occur-highlights)) ; no previous matches
13839 ;; hide everything
13840 (org-overview))
13841 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13842 (isearch-no-upper-case-p regexp t)
13843 org-occur-case-fold-search)))
13844 (while (re-search-forward regexp nil t)
13845 (when (or (not callback)
13846 (save-match-data (funcall callback)))
13847 (setq cnt (1+ cnt))
13848 (when org-highlight-sparse-tree-matches
13849 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13850 (org-show-context 'occur-tree)))))
13851 (when org-remove-highlights-with-change
13852 (add-hook 'before-change-functions 'org-remove-occur-highlights
13853 nil 'local))
13854 (unless org-sparse-tree-open-archived-trees
13855 (org-hide-archived-subtrees (point-min) (point-max)))
13856 (run-hooks 'org-occur-hook)
13857 (when (called-interactively-p 'interactive)
13858 (message "%d match(es) for regexp %s" cnt regexp))
13859 cnt))
13861 (defun org-occur-next-match (&optional n _reset)
13862 "Function for `next-error-function' to find sparse tree matches.
13863 N is the number of matches to move, when negative move backwards.
13864 This function always goes back to the starting point when no
13865 match is found."
13866 (let* ((limit (if (< n 0) (point-min) (point-max)))
13867 (search-func (if (< n 0)
13868 'previous-single-char-property-change
13869 'next-single-char-property-change))
13870 (n (abs n))
13871 (pos (point))
13873 (catch 'exit
13874 (while (setq p1 (funcall search-func (point) 'org-type))
13875 (when (equal p1 limit)
13876 (goto-char pos)
13877 (user-error "No more matches"))
13878 (when (equal (get-char-property p1 'org-type) 'org-occur)
13879 (setq n (1- n))
13880 (when (= n 0)
13881 (goto-char p1)
13882 (throw 'exit (point))))
13883 (goto-char p1))
13884 (goto-char p1)
13885 (user-error "No more matches"))))
13887 (defun org-show-context (&optional key)
13888 "Make sure point and context are visible.
13889 Optional argument KEY, when non-nil, is a symbol. See
13890 `org-show-context-detail' for allowed values and how much is to
13891 be shown."
13892 (org-show-set-visibility
13893 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13894 ((cdr (assq key org-show-context-detail)))
13895 (t (cdr (assq 'default org-show-context-detail))))))
13897 (defun org-show-set-visibility (detail)
13898 "Set visibility around point according to DETAIL.
13899 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13900 `tree', `canonical' or t. See `org-show-context-detail' for more
13901 information."
13902 ;; Show current heading and possibly its entry, following headline
13903 ;; or all children.
13904 (if (and (org-at-heading-p) (not (eq detail 'local)))
13905 (org-flag-heading nil)
13906 (org-show-entry)
13907 ;; If point is hidden within a drawer or a block, make sure to
13908 ;; expose it.
13909 (dolist (o (overlays-at (point)))
13910 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13911 (delete-overlay o)))
13912 (unless (org-before-first-heading-p)
13913 (org-with-limited-levels
13914 (cl-case detail
13915 ((tree canonical t) (org-show-children))
13916 ((nil minimal ancestors))
13917 (t (save-excursion
13918 (outline-next-heading)
13919 (org-flag-heading nil)))))))
13920 ;; Show all siblings.
13921 (when (eq detail 'lineage) (org-show-siblings))
13922 ;; Show ancestors, possibly with their children.
13923 (when (memq detail '(ancestors lineage tree canonical t))
13924 (save-excursion
13925 (while (org-up-heading-safe)
13926 (org-flag-heading nil)
13927 (when (memq detail '(canonical t)) (org-show-entry))
13928 (when (memq detail '(tree canonical t)) (org-show-children))))))
13930 (defvar org-reveal-start-hook nil
13931 "Hook run before revealing a location.")
13933 (defun org-reveal (&optional siblings)
13934 "Show current entry, hierarchy above it, and the following headline.
13936 This can be used to show a consistent set of context around
13937 locations exposed with `org-show-context'.
13939 With optional argument SIBLINGS, on each level of the hierarchy all
13940 siblings are shown. This repairs the tree structure to what it would
13941 look like when opened with hierarchical calls to `org-cycle'.
13943 With a \\[universal-argument] \\[universal-argument] prefix, \
13944 go to the parent and show the entire tree."
13945 (interactive "P")
13946 (run-hooks 'org-reveal-start-hook)
13947 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13948 ((equal siblings '(16))
13949 (save-excursion
13950 (when (org-up-heading-safe)
13951 (org-show-subtree)
13952 (run-hook-with-args 'org-cycle-hook 'subtree))))
13953 (t (org-show-set-visibility 'lineage))))
13955 (defun org-highlight-new-match (beg end)
13956 "Highlight from BEG to END and mark the highlight is an occur headline."
13957 (let ((ov (make-overlay beg end)))
13958 (overlay-put ov 'face 'secondary-selection)
13959 (overlay-put ov 'org-type 'org-occur)
13960 (push ov org-occur-highlights)))
13962 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13963 "Remove the occur highlights from the buffer.
13964 BEG and END are ignored. If NOREMOVE is nil, remove this function
13965 from the `before-change-functions' in the current buffer."
13966 (interactive)
13967 (unless org-inhibit-highlight-removal
13968 (mapc #'delete-overlay org-occur-highlights)
13969 (setq org-occur-highlights nil)
13970 (setq org-occur-parameters nil)
13971 (unless noremove
13972 (remove-hook 'before-change-functions
13973 'org-remove-occur-highlights 'local))))
13975 ;;;; Priorities
13977 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13978 "Regular expression matching the priority indicator.")
13980 (defvar org-remove-priority-next-time nil)
13982 (defun org-priority-up ()
13983 "Increase the priority of the current item."
13984 (interactive)
13985 (org-priority 'up))
13987 (defun org-priority-down ()
13988 "Decrease the priority of the current item."
13989 (interactive)
13990 (org-priority 'down))
13992 (defun org-priority (&optional action _show)
13993 "Change the priority of an item.
13994 ACTION can be `set', `up', `down', or a character."
13995 (interactive "P")
13996 (if (equal action '(4))
13997 (org-show-priority)
13998 (unless org-enable-priority-commands
13999 (user-error "Priority commands are disabled"))
14000 (setq action (or action 'set))
14001 (let (current new news have remove)
14002 (save-excursion
14003 (org-back-to-heading t)
14004 (when (looking-at org-priority-regexp)
14005 (setq current (string-to-char (match-string 2))
14006 have t))
14007 (cond
14008 ((eq action 'remove)
14009 (setq remove t new ?\ ))
14010 ((or (eq action 'set)
14011 (integerp action))
14012 (if (not (eq action 'set))
14013 (setq new action)
14014 (message "Priority %c-%c, SPC to remove: "
14015 org-highest-priority org-lowest-priority)
14016 (save-match-data
14017 (setq new (read-char-exclusive))))
14018 (when (and (= (upcase org-highest-priority) org-highest-priority)
14019 (= (upcase org-lowest-priority) org-lowest-priority))
14020 (setq new (upcase new)))
14021 (cond ((equal new ?\ ) (setq remove t))
14022 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14023 (user-error "Priority must be between `%c' and `%c'"
14024 org-highest-priority org-lowest-priority))))
14025 ((eq action 'up)
14026 (setq new (if have
14027 (1- current) ; normal cycling
14028 ;; last priority was empty
14029 (if (eq last-command this-command)
14030 org-lowest-priority ; wrap around empty to lowest
14031 ;; default
14032 (if org-priority-start-cycle-with-default
14033 org-default-priority
14034 (1- org-default-priority))))))
14035 ((eq action 'down)
14036 (setq new (if have
14037 (1+ current) ; normal cycling
14038 ;; last priority was empty
14039 (if (eq last-command this-command)
14040 org-highest-priority ; wrap around empty to highest
14041 ;; default
14042 (if org-priority-start-cycle-with-default
14043 org-default-priority
14044 (1+ org-default-priority))))))
14045 (t (user-error "Invalid action")))
14046 (when (or (< (upcase new) org-highest-priority)
14047 (> (upcase new) org-lowest-priority))
14048 (if (and (memq action '(up down))
14049 (not have) (not (eq last-command this-command)))
14050 ;; `new' is from default priority
14051 (error
14052 "The default can not be set, see `org-default-priority' why")
14053 ;; normal cycling: `new' is beyond highest/lowest priority
14054 ;; and is wrapped around to the empty priority
14055 (setq remove t)))
14056 (setq news (format "%c" new))
14057 (if have
14058 (if remove
14059 (replace-match "" t t nil 1)
14060 (replace-match news t t nil 2))
14061 (if remove
14062 (user-error "No priority cookie found in line")
14063 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14064 (if (match-end 2)
14065 (progn
14066 (goto-char (match-end 2))
14067 (insert " [#" news "]"))
14068 (goto-char (match-beginning 3))
14069 (insert "[#" news "] "))))
14070 (org-set-tags nil 'align))
14071 (if remove
14072 (message "Priority removed")
14073 (message "Priority of current item set to %s" news)))))
14075 (defun org-show-priority ()
14076 "Show the priority of the current item.
14077 This priority is composed of the main priority given with the [#A] cookies,
14078 and by additional input from the age of a schedules or deadline entry."
14079 (interactive)
14080 (let ((pri (if (eq major-mode 'org-agenda-mode)
14081 (org-get-at-bol 'priority)
14082 (save-excursion
14083 (save-match-data
14084 (beginning-of-line)
14085 (and (looking-at org-heading-regexp)
14086 (org-get-priority (match-string 0))))))))
14087 (message "Priority is %d" (if pri pri -1000))))
14089 (defun org-get-priority (s)
14090 "Find priority cookie and return priority."
14091 (save-match-data
14092 (if (functionp org-get-priority-function)
14093 (funcall org-get-priority-function)
14094 (if (not (string-match org-priority-regexp s))
14095 (* 1000 (- org-lowest-priority org-default-priority))
14096 (* 1000 (- org-lowest-priority
14097 (string-to-char (match-string 2 s))))))))
14099 ;;;; Tags
14101 (defvar org-agenda-archives-mode)
14102 (defvar org-map-continue-from nil
14103 "Position from where mapping should continue.
14104 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14106 (defvar org-scanner-tags nil
14107 "The current tag list while the tags scanner is running.")
14109 (defvar org-trust-scanner-tags nil
14110 "Should `org-get-tags-at' use the tags for the scanner.
14111 This is for internal dynamical scoping only.
14112 When this is non-nil, the function `org-get-tags-at' will return the value
14113 of `org-scanner-tags' instead of building the list by itself. This
14114 can lead to large speed-ups when the tags scanner is used in a file with
14115 many entries, and when the list of tags is retrieved, for example to
14116 obtain a list of properties. Building the tags list for each entry in such
14117 a file becomes an N^2 operation - but with this variable set, it scales
14118 as N.")
14120 (defvar org--matcher-tags-todo-only nil)
14122 (defun org-scan-tags (action matcher todo-only &optional start-level)
14123 "Scan headline tags with inheritance and produce output ACTION.
14125 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14126 or `agenda' to produce an entry list for an agenda view. It can also be
14127 a Lisp form or a function that should be called at each matched headline, in
14128 this case the return value is a list of all return values from these calls.
14130 MATCHER is a function accepting three arguments, returning
14131 a non-nil value whenever a given set of tags qualifies a headline
14132 for inclusion. See `org-make-tags-matcher' for more information.
14133 As a special case, it can also be set to t (respectively nil) in
14134 order to match all (respectively none) headline.
14136 When TODO-ONLY is non-nil, only lines with a not-done TODO
14137 keyword are included in the output.
14139 START-LEVEL can be a string with asterisks, reducing the scope to
14140 headlines matching this string."
14141 (require 'org-agenda)
14142 (let* ((re (concat "^"
14143 (if start-level
14144 ;; Get the correct level to match
14145 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14146 org-outline-regexp)
14147 " *\\(\\<\\("
14148 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14149 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14150 (props (list 'face 'default
14151 'done-face 'org-agenda-done
14152 'undone-face 'default
14153 'mouse-face 'highlight
14154 'org-not-done-regexp org-not-done-regexp
14155 'org-todo-regexp org-todo-regexp
14156 'org-complex-heading-regexp org-complex-heading-regexp
14157 'help-echo
14158 (format "mouse-2 or RET jump to org file %s"
14159 (abbreviate-file-name
14160 (or (buffer-file-name (buffer-base-buffer))
14161 (buffer-name (buffer-base-buffer)))))))
14162 (org-map-continue-from nil)
14163 lspos tags tags-list
14164 (tags-alist (list (cons 0 org-file-tags)))
14165 (llast 0) rtn rtn1 level category i txt
14166 todo marker entry priority
14167 ts-date ts-date-type ts-date-pair)
14168 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14169 (setq action (list 'lambda nil action)))
14170 (save-excursion
14171 (goto-char (point-min))
14172 (when (eq action 'sparse-tree)
14173 (org-overview)
14174 (org-remove-occur-highlights))
14175 (while (let (case-fold-search)
14176 (re-search-forward re nil t))
14177 (setq org-map-continue-from nil)
14178 (catch :skip
14179 (setq todo
14180 ;; TODO: is the 1-2 difference a bug?
14181 (when (match-end 1) (match-string-no-properties 2))
14182 tags (when (match-end 4) (match-string-no-properties 4)))
14183 (goto-char (setq lspos (match-beginning 0)))
14184 (setq level (org-reduced-level (org-outline-level))
14185 category (org-get-category))
14186 (when (eq action 'agenda)
14187 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14188 ts-date (car ts-date-pair)
14189 ts-date-type (cdr ts-date-pair)))
14190 (setq i llast llast level)
14191 ;; remove tag lists from same and sublevels
14192 (while (>= i level)
14193 (when (setq entry (assoc i tags-alist))
14194 (setq tags-alist (delete entry tags-alist)))
14195 (setq i (1- i)))
14196 ;; add the next tags
14197 (when tags
14198 (setq tags (org-split-string tags ":")
14199 tags-alist
14200 (cons (cons level tags) tags-alist)))
14201 ;; compile tags for current headline
14202 (setq tags-list
14203 (if org-use-tag-inheritance
14204 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14205 tags)
14206 org-scanner-tags tags-list)
14207 (when org-use-tag-inheritance
14208 (setcdr (car tags-alist)
14209 (mapcar (lambda (x)
14210 (setq x (copy-sequence x))
14211 (org-add-prop-inherited x))
14212 (cdar tags-alist))))
14213 (when (and tags org-use-tag-inheritance
14214 (or (not (eq t org-use-tag-inheritance))
14215 org-tags-exclude-from-inheritance))
14216 ;; Selective inheritance, remove uninherited ones.
14217 (setcdr (car tags-alist)
14218 (org-remove-uninherited-tags (cdar tags-alist))))
14219 (when (and
14221 ;; eval matcher only when the todo condition is OK
14222 (and (or (not todo-only) (member todo org-not-done-keywords))
14223 (if (functionp matcher)
14224 (let ((case-fold-search t) (org-trust-scanner-tags t))
14225 (funcall matcher todo tags-list level))
14226 matcher))
14228 ;; Call the skipper, but return t if it does not
14229 ;; skip, so that the `and' form continues evaluating.
14230 (progn
14231 (unless (eq action 'sparse-tree) (org-agenda-skip))
14234 ;; Check if timestamps are deselecting this entry
14235 (or (not todo-only)
14236 (and (member todo org-not-done-keywords)
14237 (or (not org-agenda-tags-todo-honor-ignore-options)
14238 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14240 ;; select this headline
14241 (cond
14242 ((eq action 'sparse-tree)
14243 (and org-highlight-sparse-tree-matches
14244 (org-get-heading) (match-end 0)
14245 (org-highlight-new-match
14246 (match-beginning 1) (match-end 1)))
14247 (org-show-context 'tags-tree))
14248 ((eq action 'agenda)
14249 (setq txt (org-agenda-format-item
14251 (concat
14252 (if (eq org-tags-match-list-sublevels 'indented)
14253 (make-string (1- level) ?.) "")
14254 (org-get-heading))
14255 (make-string level ?\s)
14256 category
14257 tags-list)
14258 priority (org-get-priority txt))
14259 (goto-char lspos)
14260 (setq marker (org-agenda-new-marker))
14261 (org-add-props txt props
14262 'org-marker marker 'org-hd-marker marker 'org-category category
14263 'todo-state todo
14264 'ts-date ts-date
14265 'priority priority
14266 'type (concat "tagsmatch" ts-date-type))
14267 (push txt rtn))
14268 ((functionp action)
14269 (setq org-map-continue-from nil)
14270 (save-excursion
14271 (setq rtn1 (funcall action))
14272 (push rtn1 rtn)))
14273 (t (user-error "Invalid action")))
14275 ;; if we are to skip sublevels, jump to end of subtree
14276 (unless org-tags-match-list-sublevels
14277 (org-end-of-subtree t)
14278 (backward-char 1))))
14279 ;; Get the correct position from where to continue
14280 (if org-map-continue-from
14281 (goto-char org-map-continue-from)
14282 (and (= (point) lspos) (end-of-line 1)))))
14283 (when (and (eq action 'sparse-tree)
14284 (not org-sparse-tree-open-archived-trees))
14285 (org-hide-archived-subtrees (point-min) (point-max)))
14286 (nreverse rtn)))
14288 (defun org-remove-uninherited-tags (tags)
14289 "Remove all tags that are not inherited from the list TAGS."
14290 (cond
14291 ((eq org-use-tag-inheritance t)
14292 (if org-tags-exclude-from-inheritance
14293 (org-delete-all org-tags-exclude-from-inheritance tags)
14294 tags))
14295 ((not org-use-tag-inheritance) nil)
14296 ((stringp org-use-tag-inheritance)
14297 (delq nil (mapcar
14298 (lambda (x)
14299 (if (and (string-match org-use-tag-inheritance x)
14300 (not (member x org-tags-exclude-from-inheritance)))
14301 x nil))
14302 tags)))
14303 ((listp org-use-tag-inheritance)
14304 (delq nil (mapcar
14305 (lambda (x)
14306 (if (member x org-use-tag-inheritance) x nil))
14307 tags)))))
14309 (defun org-match-sparse-tree (&optional todo-only match)
14310 "Create a sparse tree according to tags string MATCH.
14312 MATCH is a string with match syntax. It can contain a selection
14313 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14314 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14315 those. See the manual for details.
14317 If optional argument TODO-ONLY is non-nil, only select lines that
14318 are also TODO tasks."
14319 (interactive "P")
14320 (org-agenda-prepare-buffers (list (current-buffer)))
14321 (let ((org--matcher-tags-todo-only todo-only))
14322 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14323 org--matcher-tags-todo-only)))
14325 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14327 (defvar org-cached-props nil)
14328 (defun org-cached-entry-get (pom property)
14329 (if (or (eq t org-use-property-inheritance)
14330 (and (stringp org-use-property-inheritance)
14331 (let ((case-fold-search t))
14332 (string-match-p org-use-property-inheritance property)))
14333 (and (listp org-use-property-inheritance)
14334 (member-ignore-case property org-use-property-inheritance)))
14335 ;; Caching is not possible, check it directly.
14336 (org-entry-get pom property 'inherit)
14337 ;; Get all properties, so we can do complicated checks easily.
14338 (cdr (assoc-string property
14339 (or org-cached-props
14340 (setq org-cached-props (org-entry-properties pom)))
14341 t))))
14343 (defun org-global-tags-completion-table (&optional files)
14344 "Return the list of all tags in all agenda buffer/files.
14345 Optional FILES argument is a list of files which can be used
14346 instead of the agenda files."
14347 (save-excursion
14348 (org-uniquify
14349 (delq nil
14350 (apply #'append
14351 (mapcar
14352 (lambda (file)
14353 (set-buffer (find-file-noselect file))
14354 (mapcar (lambda (x)
14355 (and (stringp (car-safe x))
14356 (list (car-safe x))))
14357 (or org-current-tag-alist (org-get-buffer-tags))))
14358 (if (car-safe files) files
14359 (org-agenda-files))))))))
14361 (defun org-make-tags-matcher (match)
14362 "Create the TAGS/TODO matcher form for the selection string MATCH.
14364 Returns a cons of the selection string MATCH and a function
14365 implementing the matcher.
14367 The matcher is to be called at an Org entry, with point on the
14368 headline, and returns non-nil if the entry matches the selection
14369 string MATCH. It must be called with three arguments: the TODO
14370 keyword at the entry (or nil if none), the list of all tags at
14371 the entry including inherited ones and the reduced level of the
14372 headline. Additionally, the category of the entry, if any, must
14373 be specified as the text property `org-category' on the headline.
14375 This function sets the variable `org--matcher-tags-todo-only' to
14376 a non-nil value if the matcher restricts matching to TODO
14377 entries, otherwise it is not touched.
14379 See also `org-scan-tags'."
14380 (unless match
14381 ;; Get a new match request, with completion against the global
14382 ;; tags table and the local tags in current buffer.
14383 (let ((org-last-tags-completion-table
14384 (org-uniquify
14385 (delq nil (append (org-get-buffer-tags)
14386 (org-global-tags-completion-table))))))
14387 (setq match
14388 (completing-read
14389 "Match: "
14390 'org-tags-completion-function nil nil nil 'org-tags-history))))
14392 (let ((match0 match)
14393 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14394 (start 0)
14395 tagsmatch todomatch tagsmatcher todomatcher)
14397 ;; Expand group tags.
14398 (setq match (org-tags-expand match))
14400 ;; Check if there is a TODO part of this match, which would be the
14401 ;; part after a "/". To make sure that this slash is not part of
14402 ;; a property value to be matched against, we also check that
14403 ;; there is no / after that slash. First, find the last slash.
14404 (let ((s 0))
14405 (while (string-match "/+" match s)
14406 (setq start (match-beginning 0))
14407 (setq s (match-end 0))))
14408 (if (and (string-match "/+" match start)
14409 (not (string-match-p "\"" match start)))
14410 ;; Match contains also a TODO-matching request.
14411 (progn
14412 (setq tagsmatch (substring match 0 (match-beginning 0)))
14413 (setq todomatch (substring match (match-end 0)))
14414 (when (string-prefix-p "!" todomatch)
14415 (setq org--matcher-tags-todo-only t)
14416 (setq todomatch (substring todomatch 1)))
14417 (when (string-match "\\`\\s-*\\'" todomatch)
14418 (setq todomatch nil)))
14419 ;; Only matching tags.
14420 (setq tagsmatch match)
14421 (setq todomatch nil))
14423 ;; Make the tags matcher.
14424 (when (org-string-nw-p tagsmatch)
14425 (let ((orlist nil)
14426 (orterms (org-split-string tagsmatch "|"))
14427 term)
14428 (while (setq term (pop orterms))
14429 (while (and (equal (substring term -1) "\\") orterms)
14430 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14431 (while (string-match re term)
14432 (let* ((rest (substring term (match-end 0)))
14433 (minus (and (match-end 1)
14434 (equal (match-string 1 term) "-")))
14435 (tag (save-match-data
14436 (replace-regexp-in-string
14437 "\\\\-" "-" (match-string 2 term))))
14438 (regexp (eq (string-to-char tag) ?{))
14439 (levelp (match-end 4))
14440 (propp (match-end 5))
14442 (cond
14443 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14444 (levelp
14445 `(,(org-op-to-function (match-string 3 term))
14446 level
14447 ,(string-to-number (match-string 4 term))))
14448 (propp
14449 (let* ((gv (pcase (upcase (match-string 5 term))
14450 ("CATEGORY"
14451 '(get-text-property (point) 'org-category))
14452 ("TODO" 'todo)
14453 (p `(org-cached-entry-get nil ,p))))
14454 (pv (match-string 7 term))
14455 (regexp (eq (string-to-char pv) ?{))
14456 (strp (eq (string-to-char pv) ?\"))
14457 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14458 (po (org-op-to-function (match-string 6 term)
14459 (if timep 'time strp))))
14460 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14461 (when timep (setq pv (org-matcher-time pv)))
14462 (cond ((and regexp (eq po 'org<>))
14463 `(not (string-match ,pv (or ,gv ""))))
14464 (regexp `(string-match ,pv (or ,gv "")))
14465 (strp `(,po (or ,gv "") ,pv))
14467 `(,po
14468 (string-to-number (or ,gv ""))
14469 ,(string-to-number pv))))))
14470 (t `(member ,tag tags-list)))))
14471 (push (if minus `(not ,mm) mm) tagsmatcher)
14472 (setq term rest)))
14473 (push `(and ,@tagsmatcher) orlist)
14474 (setq tagsmatcher nil))
14475 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14477 ;; Make the TODO matcher.
14478 (when (org-string-nw-p todomatch)
14479 (let ((orlist nil))
14480 (dolist (term (org-split-string todomatch "|"))
14481 (while (string-match re term)
14482 (let* ((minus (and (match-end 1)
14483 (equal (match-string 1 term) "-")))
14484 (kwd (match-string 2 term))
14485 (regexp (eq (string-to-char kwd) ?{))
14486 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14487 `(equal todo ,kwd))))
14488 (push (if minus `(not ,mm) mm) todomatcher))
14489 (setq term (substring term (match-end 0))))
14490 (push (if (> (length todomatcher) 1)
14491 (cons 'and todomatcher)
14492 (car todomatcher))
14493 orlist)
14494 (setq todomatcher nil))
14495 (setq todomatcher (cons 'or orlist))))
14497 ;; Return the string and function of the matcher. If no
14498 ;; tags-specific or todo-specific matcher exists, match
14499 ;; everything.
14500 (let ((matcher (if (and tagsmatcher todomatcher)
14501 `(and ,tagsmatcher ,todomatcher)
14502 (or tagsmatcher todomatcher t))))
14503 (when org--matcher-tags-todo-only
14504 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14505 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14507 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14508 "Expand group tags in MATCH.
14510 This replaces every group tag in MATCH with a regexp tag search.
14511 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14512 will be replaced like this:
14514 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14515 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14516 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14518 Replacing by a regexp preserves the structure of the match.
14519 E.g., this expansion
14521 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14523 will match anything tagged with \"Lab\" and \"Home\", or tagged
14524 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14526 A group tag in MATCH can contain regular expressions of its own.
14527 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14528 will be replaced like this:
14530 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14532 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14533 assumed to be a single group tag, and the function will return
14534 the list of tags in this group.
14536 When DOWNCASE is non-nil, expand downcased TAGS."
14537 (if org-group-tags
14538 (let* ((case-fold-search t)
14539 (stable org-mode-syntax-table)
14540 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14541 (taggroups (if downcased
14542 (mapcar (lambda (tg) (mapcar #'downcase tg))
14543 taggroups)
14544 taggroups))
14545 (taggroups-keys (mapcar #'car taggroups))
14546 (return-match (if downcased (downcase match) match))
14547 (count 0)
14548 (work-already-expanded tags-already-expanded)
14549 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14550 ;; @ and _ are allowed as word-components in tags.
14551 (modify-syntax-entry ?@ "w" stable)
14552 (modify-syntax-entry ?_ "w" stable)
14553 ;; Temporarily replace regexp-expressions in the match-expression.
14554 (while (string-match "{.+?}" return-match)
14555 (cl-incf count)
14556 (push (match-string 0 return-match) regexps-in-match)
14557 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14558 (while (and taggroups-keys
14559 (with-syntax-table stable
14560 (string-match
14561 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14562 (regexp-opt taggroups-keys) "\\>\\)")
14563 return-match)))
14564 (let* ((dir (match-string 1 return-match))
14565 (tag (match-string 2 return-match))
14566 (tag (if downcased (downcase tag) tag)))
14567 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14568 (member tag work-already-expanded))
14569 (setq tags-in-group (assoc tag taggroups))
14570 (push tag work-already-expanded)
14571 ;; Recursively expand each tag in the group, if the tag hasn't
14572 ;; already been expanded. Restore the match-data after all recursive calls.
14573 (save-match-data
14574 (let (tags-expanded)
14575 (dolist (x (cdr tags-in-group))
14576 (if (and (member x taggroups-keys)
14577 (not (member x work-already-expanded)))
14578 (setq tags-expanded
14579 (delete-dups
14580 (append
14581 (org-tags-expand x t downcased
14582 work-already-expanded)
14583 tags-expanded)))
14584 (setq tags-expanded
14585 (append (list x) tags-expanded)))
14586 (setq work-already-expanded
14587 (delete-dups
14588 (append tags-expanded
14589 work-already-expanded))))
14590 (setq tags-in-group
14591 (delete-dups (cons (car tags-in-group)
14592 tags-expanded)))))
14593 ;; Filter tag-regexps from tags.
14594 (setq regexp-in-group-escaped
14595 (delq nil (mapcar (lambda (x)
14596 (if (stringp x)
14597 (and (equal "{" (substring x 0 1))
14598 (equal "}" (substring x -1))
14601 tags-in-group))
14602 regexp-in-group
14603 (mapcar (lambda (x)
14604 (substring x 1 -1))
14605 regexp-in-group-escaped)
14606 tags-in-group
14607 (delq nil (mapcar (lambda (x)
14608 (if (stringp x)
14609 (and (not (equal "{" (substring x 0 1)))
14610 (not (equal "}" (substring x -1)))
14613 tags-in-group)))
14614 ;; If single-as-list, do no more in the while-loop.
14615 (if (not single-as-list)
14616 (progn
14617 (when regexp-in-group
14618 (setq regexp-in-group
14619 (concat "\\|"
14620 (mapconcat 'identity regexp-in-group
14621 "\\|"))))
14622 (setq tags-in-group
14623 (concat dir
14624 "{\\<"
14625 (regexp-opt tags-in-group)
14626 "\\>"
14627 regexp-in-group
14628 "}"))
14629 (when (stringp tags-in-group)
14630 (org-add-props tags-in-group '(grouptag t)))
14631 (setq return-match
14632 (replace-match tags-in-group t t return-match)))
14633 (setq tags-in-group
14634 (append regexp-in-group-escaped tags-in-group))))
14635 (setq taggroups-keys (delete tag taggroups-keys))))
14636 ;; Add the regular expressions back into the match-expression again.
14637 (while regexps-in-match
14638 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14639 (pop regexps-in-match)
14640 return-match t t))
14641 (cl-decf count))
14642 (if single-as-list
14643 (if tags-in-group tags-in-group (list return-match))
14644 return-match))
14645 (if single-as-list
14646 (list (if downcased (downcase match) match))
14647 match)))
14649 (defun org-op-to-function (op &optional stringp)
14650 "Turn an operator into the appropriate function."
14651 (setq op
14652 (cond
14653 ((equal op "<" ) '(< string< org-time<))
14654 ((equal op ">" ) '(> org-string> org-time>))
14655 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14656 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14657 ((member op '("=" "==")) '(= string= org-time=))
14658 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14659 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14661 (defun org<> (a b) (not (= a b)))
14662 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14663 (defun org-string>= (a b) (not (string< a b)))
14664 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14665 (defun org-string<> (a b) (not (string= 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) (< a b)))
14668 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14669 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14670 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14671 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14672 (defun org-2ft (s)
14673 "Convert S to a floating point time.
14674 If S is already a number, just return it. If it is a string, parse
14675 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14676 (cond
14677 ((numberp s) s)
14678 ((stringp s)
14679 (condition-case nil
14680 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14681 (error 0.)))
14682 (t 0.)))
14684 (defun org-time-today ()
14685 "Time in seconds today at 0:00.
14686 Returns the float number of seconds since the beginning of the
14687 epoch to the beginning of today (00:00)."
14688 (float-time (apply 'encode-time
14689 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14691 (defun org-matcher-time (s)
14692 "Interpret a time comparison value."
14693 (save-match-data
14694 (cond
14695 ((string= s "<now>") (float-time))
14696 ((string= s "<today>") (org-time-today))
14697 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14698 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14699 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14700 (+ (org-time-today)
14701 (* (string-to-number (match-string 1 s))
14702 (cdr (assoc (match-string 2 s)
14703 '(("d" . 86400.0) ("w" . 604800.0)
14704 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14705 (t (org-2ft s)))))
14707 (defun org-match-any-p (re list)
14708 "Does re match any element of list?"
14709 (setq list (mapcar (lambda (x) (string-match re x)) list))
14710 (delq nil list))
14712 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14713 (defvar org-tags-overlay (make-overlay 1 1))
14714 (delete-overlay org-tags-overlay)
14716 (defun org-get-local-tags-at (&optional pos)
14717 "Get a list of tags defined in the current headline."
14718 (org-get-tags-at pos 'local))
14720 (defun org-get-local-tags ()
14721 "Get a list of tags defined in the current headline."
14722 (org-get-tags-at nil 'local))
14724 (defun org-get-tags-at (&optional pos local)
14725 "Get a list of all headline tags applicable at POS.
14726 POS defaults to point. If tags are inherited, the list contains
14727 the targets in the same sequence as the headlines appear, i.e.
14728 the tags of the current headline come last.
14729 When LOCAL is non-nil, only return tags from the current headline,
14730 ignore inherited ones."
14731 (interactive)
14732 (if (and org-trust-scanner-tags
14733 (or (not pos) (equal pos (point)))
14734 (not local))
14735 org-scanner-tags
14736 (let (tags ltags lastpos parent)
14737 (save-excursion
14738 (save-restriction
14739 (widen)
14740 (goto-char (or pos (point)))
14741 (save-match-data
14742 (catch 'done
14743 (condition-case nil
14744 (progn
14745 (org-back-to-heading t)
14746 (while (not (equal lastpos (point)))
14747 (setq lastpos (point))
14748 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14749 (setq ltags (org-split-string
14750 (match-string-no-properties 1) ":"))
14751 (when parent
14752 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14753 (setq tags (append
14754 (if parent
14755 (org-remove-uninherited-tags ltags)
14756 ltags)
14757 tags)))
14758 (or org-use-tag-inheritance (throw 'done t))
14759 (when local (throw 'done t))
14760 (or (org-up-heading-safe) (error nil))
14761 (setq parent t)))
14762 (error nil)))))
14763 (if local
14764 tags
14765 (reverse (delete-dups
14766 (reverse (append
14767 (org-remove-uninherited-tags
14768 org-file-tags)
14769 tags)))))))))
14771 (defun org-add-prop-inherited (s)
14772 (add-text-properties 0 (length s) '(inherited t) s)
14775 (defun org-toggle-tag (tag &optional onoff)
14776 "Toggle the tag TAG for the current line.
14777 If ONOFF is `on' or `off', don't toggle but set to this state."
14778 (let (res current)
14779 (save-excursion
14780 (org-back-to-heading t)
14781 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14782 (point-at-eol) t)
14783 (progn
14784 (setq current (match-string 1))
14785 (replace-match ""))
14786 (setq current ""))
14787 (setq current (nreverse (org-split-string current ":")))
14788 (cond
14789 ((eq onoff 'on)
14790 (setq res t)
14791 (or (member tag current) (push tag current)))
14792 ((eq onoff 'off)
14793 (or (not (member tag current)) (setq current (delete tag current))))
14794 (t (if (member tag current)
14795 (setq current (delete tag current))
14796 (setq res t)
14797 (push tag current))))
14798 (end-of-line 1)
14799 (if current
14800 (progn
14801 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14802 (org-set-tags nil t))
14803 (delete-horizontal-space))
14804 (run-hooks 'org-after-tags-change-hook))
14805 res))
14807 (defun org--align-tags-here (to-col)
14808 "Align tags on the current headline to TO-COL.
14809 Assume point is on a headline."
14810 (let ((pos (point)))
14811 (beginning-of-line)
14812 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14813 (>= pos (match-beginning 2)))
14814 ;; No tags or point within tags: do not align.
14815 (goto-char pos)
14816 (goto-char (match-beginning 1))
14817 (let ((shift (max (- (if (>= to-col 0) to-col
14818 (- (abs to-col) (string-width (match-string 2))))
14819 (current-column))
14820 1)))
14821 (replace-match (make-string shift ?\s) nil nil nil 1)
14822 ;; Preserve initial position, if possible. In any case, stop
14823 ;; before tags.
14824 (when (< pos (point)) (goto-char pos))))))
14826 (defun org-set-tags-command (&optional arg just-align)
14827 "Call the set-tags command for the current entry."
14828 (interactive "P")
14829 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14830 (org-set-tags arg just-align)
14831 (save-excursion
14832 (unless (and (org-region-active-p)
14833 org-loop-over-headlines-in-active-region)
14834 (org-back-to-heading t))
14835 (org-set-tags arg just-align))))
14837 (defun org-set-tags-to (data)
14838 "Set the tags of the current entry to DATA, replacing the current tags.
14839 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14840 If DATA is nil or the empty string, any tags will be removed."
14841 (interactive "sTags: ")
14842 (setq data
14843 (cond
14844 ((eq data nil) "")
14845 ((equal data "") "")
14846 ((stringp data)
14847 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14848 ":"))
14849 ((listp data)
14850 (concat ":" (mapconcat 'identity data ":") ":"))))
14851 (when data
14852 (save-excursion
14853 (org-back-to-heading t)
14854 (when (let ((case-fold-search nil))
14855 (looking-at org-complex-heading-regexp))
14856 (if (match-end 5)
14857 (progn
14858 (goto-char (match-beginning 5))
14859 (insert data)
14860 (delete-region (point) (point-at-eol))
14861 (org-set-tags nil 'align))
14862 (goto-char (point-at-eol))
14863 (insert " " data)
14864 (org-set-tags nil 'align)))
14865 (beginning-of-line 1)
14866 (when (looking-at ".*?\\([ \t]+\\)$")
14867 (delete-region (match-beginning 1) (match-end 1))))))
14869 (defun org-align-all-tags ()
14870 "Align the tags in all headings."
14871 (interactive)
14872 (save-excursion
14873 (or (ignore-errors (org-back-to-heading t))
14874 (outline-next-heading))
14875 (if (org-at-heading-p)
14876 (org-set-tags t)
14877 (message "No headings"))))
14879 (defvar org-indent-indentation-per-level)
14880 (defun org-set-tags (&optional arg just-align)
14881 "Set the tags for the current headline.
14882 With prefix ARG, realign all tags in headings in the current buffer.
14883 When JUST-ALIGN is non-nil, only align tags."
14884 (interactive "P")
14885 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14886 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14887 'region-start-level
14888 'region))
14889 org-loop-over-headlines-in-active-region)
14890 (org-map-entries
14891 ;; We don't use ARG and JUST-ALIGN here because these args
14892 ;; are not useful when looping over headlines.
14893 #'org-set-tags
14894 org-loop-over-headlines-in-active-region
14896 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14897 (let ((org-setting-tags t))
14898 (if arg
14899 (save-excursion
14900 (goto-char (point-min))
14901 (while (re-search-forward org-outline-regexp-bol nil t)
14902 (org-set-tags nil t)
14903 (end-of-line))
14904 (message "All tags realigned to column %d" org-tags-column))
14905 (let* ((current (org-get-tags-string))
14906 (tags
14907 (if just-align current
14908 ;; Get a new set of tags from the user.
14909 (save-excursion
14910 (let* ((seen)
14911 (table
14912 (setq
14913 org-last-tags-completion-table
14914 ;; Uniquify tags in alists, yet preserve
14915 ;; structure (i.e., keywords).
14916 (delq nil
14917 (mapcar
14918 (lambda (pair)
14919 (let ((head (car pair)))
14920 (cond ((symbolp head) pair)
14921 ((member head seen) nil)
14922 (t (push head seen)
14923 pair))))
14924 (append
14925 (or org-current-tag-alist
14926 (org-get-buffer-tags))
14927 (and
14928 org-complete-tags-always-offer-all-agenda-tags
14929 (org-global-tags-completion-table
14930 (org-agenda-files))))))))
14931 (current-tags (org-split-string current ":"))
14932 (inherited-tags
14933 (nreverse (nthcdr (length current-tags)
14934 (nreverse (org-get-tags-at))))))
14935 (replace-regexp-in-string
14936 "\\([-+&]+\\|,\\)"
14938 (if (or (eq t org-use-fast-tag-selection)
14939 (and org-use-fast-tag-selection
14940 (delq nil (mapcar #'cdr table))))
14941 (org-fast-tag-selection
14942 current-tags inherited-tags table
14943 (and org-fast-tag-selection-include-todo
14944 org-todo-key-alist))
14945 (let ((org-add-colon-after-tag-completion
14946 (< 1 (length table))))
14947 (org-trim
14948 (completing-read
14949 "Tags: "
14950 #'org-tags-completion-function
14951 nil nil current 'org-tags-history))))))))))
14953 (when org-tags-sort-function
14954 (setq tags
14955 (mapconcat
14956 #'identity
14957 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14958 org-tags-sort-function)
14959 ":")))
14961 (if (or (string= ":" tags)
14962 (string= "::" tags))
14963 (setq tags ""))
14964 (if (not (org-string-nw-p tags)) (setq tags "")
14965 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14966 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14968 ;; Insert new tags at the correct column.
14969 (unless (equal current tags)
14970 (save-excursion
14971 (beginning-of-line)
14972 (let ((case-fold-search nil))
14973 (looking-at org-complex-heading-regexp))
14974 ;; Remove current tags, if any.
14975 (when (match-end 5) (replace-match "" nil nil nil 5))
14976 ;; Insert new tags, if any. Otherwise, remove trailing
14977 ;; white spaces.
14978 (end-of-line)
14979 (if (not (equal tags ""))
14980 ;; When text is being inserted on an invisible
14981 ;; region boundary, it can be inadvertently sucked
14982 ;; into invisibility.
14983 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14984 (skip-chars-backward " \t")
14985 (delete-region (point) (line-end-position)))))
14986 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14987 ;; is on.
14988 (unless (equal tags "")
14989 (let* ((level (save-excursion
14990 (beginning-of-line)
14991 (skip-chars-forward "\\*")))
14992 (offset (if (bound-and-true-p org-indent-mode)
14993 (* (1- org-indent-indentation-per-level)
14994 (1- level))
14996 (tags-column
14997 (+ org-tags-column
14998 (if (> org-tags-column 0) (- offset) offset))))
14999 (org--align-tags-here tags-column))))
15000 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15002 (defun org-change-tag-in-region (beg end tag off)
15003 "Add or remove TAG for each entry in the region.
15004 This works in the agenda, and also in an Org buffer."
15005 (interactive
15006 (list (region-beginning) (region-end)
15007 (let ((org-last-tags-completion-table
15008 (if (derived-mode-p 'org-mode)
15009 (org-uniquify
15010 (delq nil (append (org-get-buffer-tags)
15011 (org-global-tags-completion-table))))
15012 (org-global-tags-completion-table))))
15013 (completing-read
15014 "Tag: " 'org-tags-completion-function nil nil nil
15015 'org-tags-history))
15016 (progn
15017 (message "[s]et or [r]emove? ")
15018 (equal (read-char-exclusive) ?r))))
15019 (when (fboundp 'deactivate-mark) (deactivate-mark))
15020 (let ((agendap (equal major-mode 'org-agenda-mode))
15021 l1 l2 m buf pos newhead (cnt 0))
15022 (goto-char end)
15023 (setq l2 (1- (org-current-line)))
15024 (goto-char beg)
15025 (setq l1 (org-current-line))
15026 (cl-loop for l from l1 to l2 do
15027 (org-goto-line l)
15028 (setq m (get-text-property (point) 'org-hd-marker))
15029 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15030 (and agendap m))
15031 (setq buf (if agendap (marker-buffer m) (current-buffer))
15032 pos (if agendap m (point)))
15033 (with-current-buffer buf
15034 (save-excursion
15035 (save-restriction
15036 (goto-char pos)
15037 (setq cnt (1+ cnt))
15038 (org-toggle-tag tag (if off 'off 'on))
15039 (setq newhead (org-get-heading)))))
15040 (and agendap (org-agenda-change-all-lines newhead m))))
15041 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15043 (defun org-tags-completion-function (string _predicate &optional flag)
15044 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15045 (confirm (lambda (x) (stringp (car x)))))
15046 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15047 (setq s1 (match-string 1 string)
15048 s2 (match-string 2 string))
15049 (setq s1 "" s2 string))
15050 (cond
15051 ((eq flag nil)
15052 ;; try completion
15053 (setq rtn (try-completion s2 ctable confirm))
15054 (when (stringp rtn)
15055 (setq rtn
15056 (concat s1 s2 (substring rtn (length s2))
15057 (if (and org-add-colon-after-tag-completion
15058 (assoc rtn ctable))
15059 ":" ""))))
15060 rtn)
15061 ((eq flag t)
15062 ;; all-completions
15063 (all-completions s2 ctable confirm))
15064 ((eq flag 'lambda)
15065 ;; exact match?
15066 (assoc s2 ctable)))))
15068 (defun org-fast-tag-insert (kwd tags face &optional end)
15069 "Insert KDW, and the TAGS, the latter with face FACE.
15070 Also insert END."
15071 (insert (format "%-12s" (concat kwd ":"))
15072 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15073 (or end "")))
15075 (defun org-fast-tag-show-exit (flag)
15076 (save-excursion
15077 (org-goto-line 3)
15078 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15079 (replace-match ""))
15080 (when flag
15081 (end-of-line 1)
15082 (org-move-to-column (- (window-width) 19) t)
15083 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15085 (defun org-set-current-tags-overlay (current prefix)
15086 "Add an overlay to CURRENT tag with PREFIX."
15087 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15088 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15089 (org-overlay-display org-tags-overlay (concat prefix s))))
15091 (defvar org-last-tag-selection-key nil)
15092 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15093 "Fast tag selection with single keys.
15094 CURRENT is the current list of tags in the headline, INHERITED is the
15095 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15096 possibly with grouping information. TODO-TABLE is a similar table with
15097 TODO keywords, should these have keys assigned to them.
15098 If the keys are nil, a-z are automatically assigned.
15099 Returns the new tags string, or nil to not change the current settings."
15100 (let* ((fulltable (append table todo-table))
15101 (maxlen (apply 'max (mapcar
15102 (lambda (x)
15103 (if (stringp (car x)) (string-width (car x)) 0))
15104 fulltable)))
15105 (buf (current-buffer))
15106 (expert (eq org-fast-tag-selection-single-key 'expert))
15107 (buffer-tags nil)
15108 (fwidth (+ maxlen 3 1 3))
15109 (ncol (/ (- (window-width) 4) fwidth))
15110 (i-face 'org-done)
15111 (c-face 'org-todo)
15112 tg cnt e c char c1 c2 ntable tbl rtn
15113 ov-start ov-end ov-prefix
15114 (exit-after-next org-fast-tag-selection-single-key)
15115 (done-keywords org-done-keywords)
15116 groups ingroup intaggroup)
15117 (save-excursion
15118 (beginning-of-line 1)
15119 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15120 (setq ov-start (match-beginning 1)
15121 ov-end (match-end 1)
15122 ov-prefix "")
15123 (setq ov-start (1- (point-at-eol))
15124 ov-end (1+ ov-start))
15125 (skip-chars-forward "^\n\r")
15126 (setq ov-prefix
15127 (concat
15128 (buffer-substring (1- (point)) (point))
15129 (if (> (current-column) org-tags-column)
15131 (make-string (- org-tags-column (current-column)) ?\ ))))))
15132 (move-overlay org-tags-overlay ov-start ov-end)
15133 (save-window-excursion
15134 (if expert
15135 (set-buffer (get-buffer-create " *Org tags*"))
15136 (delete-other-windows)
15137 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15138 (org-switch-to-buffer-other-window " *Org tags*"))
15139 (erase-buffer)
15140 (setq-local org-done-keywords done-keywords)
15141 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15142 (org-fast-tag-insert "Current" current c-face "\n\n")
15143 (org-fast-tag-show-exit exit-after-next)
15144 (org-set-current-tags-overlay current ov-prefix)
15145 (setq tbl fulltable char ?a cnt 0)
15146 (while (setq e (pop tbl))
15147 (cond
15148 ((eq (car e) :startgroup)
15149 (push '() groups) (setq ingroup t)
15150 (unless (zerop cnt)
15151 (setq cnt 0)
15152 (insert "\n"))
15153 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15154 ((eq (car e) :endgroup)
15155 (setq ingroup nil cnt 0)
15156 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15157 ((eq (car e) :startgrouptag)
15158 (setq intaggroup t)
15159 (unless (zerop cnt)
15160 (setq cnt 0)
15161 (insert "\n"))
15162 (insert "[ "))
15163 ((eq (car e) :endgrouptag)
15164 (setq intaggroup nil cnt 0)
15165 (insert "]\n"))
15166 ((equal e '(:newline))
15167 (unless (zerop cnt)
15168 (setq cnt 0)
15169 (insert "\n")
15170 (setq e (car tbl))
15171 (while (equal (car tbl) '(:newline))
15172 (insert "\n")
15173 (setq tbl (cdr tbl)))))
15174 ((equal e '(:grouptags)) (insert " : "))
15176 (setq tg (copy-sequence (car e)) c2 nil)
15177 (if (cdr e)
15178 (setq c (cdr e))
15179 ;; automatically assign a character.
15180 (setq c1 (string-to-char
15181 (downcase (substring
15182 tg (if (= (string-to-char tg) ?@) 1 0)))))
15183 (if (or (rassoc c1 ntable) (rassoc c1 table))
15184 (while (or (rassoc char ntable) (rassoc char table))
15185 (setq char (1+ char)))
15186 (setq c2 c1))
15187 (setq c (or c2 char)))
15188 (when ingroup (push tg (car groups)))
15189 (setq tg (org-add-props tg nil 'face
15190 (cond
15191 ((not (assoc tg table))
15192 (org-get-todo-face tg))
15193 ((member tg current) c-face)
15194 ((member tg inherited) i-face))))
15195 (when (equal (caar tbl) :grouptags)
15196 (org-add-props tg nil 'face 'org-tag-group))
15197 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15198 (insert "[" c "] " tg (make-string
15199 (- fwidth 4 (length tg)) ?\ ))
15200 (push (cons tg c) ntable)
15201 (when (= (cl-incf cnt) ncol)
15202 (insert "\n")
15203 (when (or ingroup intaggroup) (insert " "))
15204 (setq cnt 0)))))
15205 (setq ntable (nreverse ntable))
15206 (insert "\n")
15207 (goto-char (point-min))
15208 (unless expert (org-fit-window-to-buffer))
15209 (setq rtn
15210 (catch 'exit
15211 (while t
15212 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15213 (if (not groups) "no " "")
15214 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15215 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15216 (setq org-last-tag-selection-key c)
15217 (cond
15218 ((= c ?\r) (throw 'exit t))
15219 ((= c ?!)
15220 (setq groups (not groups))
15221 (goto-char (point-min))
15222 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15223 ((= c ?\C-c)
15224 (if (not expert)
15225 (org-fast-tag-show-exit
15226 (setq exit-after-next (not exit-after-next)))
15227 (setq expert nil)
15228 (delete-other-windows)
15229 (set-window-buffer (split-window-vertically) " *Org tags*")
15230 (org-switch-to-buffer-other-window " *Org tags*")
15231 (org-fit-window-to-buffer)))
15232 ((or (= c ?\C-g)
15233 (and (= c ?q) (not (rassoc c ntable))))
15234 (delete-overlay org-tags-overlay)
15235 (setq quit-flag t))
15236 ((= c ?\ )
15237 (setq current nil)
15238 (when exit-after-next (setq exit-after-next 'now)))
15239 ((= c ?\t)
15240 (condition-case nil
15241 (setq tg (completing-read
15242 "Tag: "
15243 (or buffer-tags
15244 (with-current-buffer buf
15245 (setq buffer-tags
15246 (org-get-buffer-tags))))))
15247 (quit (setq tg "")))
15248 (when (string-match "\\S-" tg)
15249 (cl-pushnew (list tg) buffer-tags :test #'equal)
15250 (if (member tg current)
15251 (setq current (delete tg current))
15252 (push tg current)))
15253 (when exit-after-next (setq exit-after-next 'now)))
15254 ((setq e (rassoc c todo-table) tg (car e))
15255 (with-current-buffer buf
15256 (save-excursion (org-todo tg)))
15257 (when exit-after-next (setq exit-after-next 'now)))
15258 ((setq e (rassoc c ntable) tg (car e))
15259 (if (member tg current)
15260 (setq current (delete tg current))
15261 (cl-loop for g in groups do
15262 (when (member tg g)
15263 (dolist (x g) (setq current (delete x current)))))
15264 (push tg current))
15265 (when exit-after-next (setq exit-after-next 'now))))
15267 ;; Create a sorted list
15268 (setq current
15269 (sort current
15270 (lambda (a b)
15271 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15272 (when (eq exit-after-next 'now) (throw 'exit t))
15273 (goto-char (point-min))
15274 (beginning-of-line 2)
15275 (delete-region (point) (point-at-eol))
15276 (org-fast-tag-insert "Current" current c-face)
15277 (org-set-current-tags-overlay current ov-prefix)
15278 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15279 (setq tg (match-string 1))
15280 (add-text-properties
15281 (match-beginning 1) (match-end 1)
15282 (list 'face
15283 (cond
15284 ((member tg current) c-face)
15285 ((member tg inherited) i-face)
15286 (t (get-text-property (match-beginning 1) 'face))))))
15287 (goto-char (point-min)))))
15288 (delete-overlay org-tags-overlay)
15289 (if rtn
15290 (mapconcat 'identity current ":")
15291 nil))))
15293 (defun org-get-tags-string ()
15294 "Get the TAGS string in the current headline."
15295 (unless (org-at-heading-p t)
15296 (user-error "Not on a heading"))
15297 (save-excursion
15298 (beginning-of-line 1)
15299 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15300 (match-string-no-properties 1)
15301 "")))
15303 (defun org-get-tags ()
15304 "Get the list of tags specified in the current headline."
15305 (org-split-string (org-get-tags-string) ":"))
15307 (defun org-get-buffer-tags ()
15308 "Get a table of all tags used in the buffer, for completion."
15309 (org-with-wide-buffer
15310 (goto-char (point-min))
15311 (let ((tag-re (concat org-outline-regexp-bol
15312 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15313 tags)
15314 (while (re-search-forward tag-re nil t)
15315 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15316 (push tag tags)))
15317 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15319 ;;;; The mapping API
15321 (defvar org-agenda-skip-comment-trees)
15322 (defvar org-agenda-skip-function)
15323 (defun org-map-entries (func &optional match scope &rest skip)
15324 "Call FUNC at each headline selected by MATCH in SCOPE.
15326 FUNC is a function or a lisp form. The function will be called without
15327 arguments, with the cursor positioned at the beginning of the headline.
15328 The return values of all calls to the function will be collected and
15329 returned as a list.
15331 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15332 does not need to preserve point. After evaluation, the cursor will be
15333 moved to the end of the line (presumably of the headline of the
15334 processed entry) and search continues from there. Under some
15335 circumstances, this may not produce the wanted results. For example,
15336 if you have removed (e.g. archived) the current (sub)tree it could
15337 mean that the next entry will be skipped entirely. In such cases, you
15338 can specify the position from where search should continue by making
15339 FUNC set the variable `org-map-continue-from' to the desired buffer
15340 position.
15342 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15343 Only headlines that are matched by this query will be considered during
15344 the iteration. When MATCH is nil or t, all headlines will be
15345 visited by the iteration.
15347 SCOPE determines the scope of this command. It can be any of:
15349 nil The current buffer, respecting the restriction if any
15350 tree The subtree started with the entry at point
15351 region The entries within the active region, if any
15352 region-start-level
15353 The entries within the active region, but only those at
15354 the same level than the first one.
15355 file The current buffer, without restriction
15356 file-with-archives
15357 The current buffer, and any archives associated with it
15358 agenda All agenda files
15359 agenda-with-archives
15360 All agenda files with any archive files associated with them
15361 \(file1 file2 ...)
15362 If this is a list, all files in the list will be scanned
15364 The remaining args are treated as settings for the skipping facilities of
15365 the scanner. The following items can be given here:
15367 archive skip trees with the archive tag
15368 comment skip trees with the COMMENT keyword
15369 function or Emacs Lisp form:
15370 will be used as value for `org-agenda-skip-function', so
15371 whenever the function returns a position, FUNC will not be
15372 called for that entry and search will continue from the
15373 position returned
15375 If your function needs to retrieve the tags including inherited tags
15376 at the *current* entry, you can use the value of the variable
15377 `org-scanner-tags' which will be much faster than getting the value
15378 with `org-get-tags-at'. If your function gets properties with
15379 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15380 to t around the call to `org-entry-properties' to get the same speedup.
15381 Note that if your function moves around to retrieve tags and properties at
15382 a *different* entry, you cannot use these techniques."
15383 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15384 (not (org-region-active-p)))
15385 (let* ((org-agenda-archives-mode nil) ; just to make sure
15386 (org-agenda-skip-archived-trees (memq 'archive skip))
15387 (org-agenda-skip-comment-trees (memq 'comment skip))
15388 (org-agenda-skip-function
15389 (car (org-delete-all '(comment archive) skip)))
15390 (org-tags-match-list-sublevels t)
15391 (start-level (eq scope 'region-start-level))
15392 matcher res
15393 org-todo-keywords-for-agenda
15394 org-done-keywords-for-agenda
15395 org-todo-keyword-alist-for-agenda
15396 org-tag-alist-for-agenda
15397 org--matcher-tags-todo-only)
15399 (cond
15400 ((eq match t) (setq matcher t))
15401 ((eq match nil) (setq matcher t))
15402 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15404 (save-excursion
15405 (save-restriction
15406 (cond ((eq scope 'tree)
15407 (org-back-to-heading t)
15408 (org-narrow-to-subtree)
15409 (setq scope nil))
15410 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15411 (org-region-active-p))
15412 ;; If needed, set start-level to a string like "2"
15413 (when start-level
15414 (save-excursion
15415 (goto-char (region-beginning))
15416 (unless (org-at-heading-p) (outline-next-heading))
15417 (setq start-level (org-current-level))))
15418 (narrow-to-region (region-beginning)
15419 (save-excursion
15420 (goto-char (region-end))
15421 (unless (and (bolp) (org-at-heading-p))
15422 (outline-next-heading))
15423 (point)))
15424 (setq scope nil)))
15426 (if (not scope)
15427 (progn
15428 (org-agenda-prepare-buffers
15429 (and buffer-file-name (list buffer-file-name)))
15430 (setq res
15431 (org-scan-tags
15432 func matcher org--matcher-tags-todo-only start-level)))
15433 ;; Get the right scope
15434 (cond
15435 ((and scope (listp scope) (symbolp (car scope)))
15436 (setq scope (eval scope)))
15437 ((eq scope 'agenda)
15438 (setq scope (org-agenda-files t)))
15439 ((eq scope 'agenda-with-archives)
15440 (setq scope (org-agenda-files t))
15441 (setq scope (org-add-archive-files scope)))
15442 ((eq scope 'file)
15443 (setq scope (and buffer-file-name (list buffer-file-name))))
15444 ((eq scope 'file-with-archives)
15445 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15446 (org-agenda-prepare-buffers scope)
15447 (dolist (file scope)
15448 (with-current-buffer (org-find-base-buffer-visiting file)
15449 (org-with-wide-buffer
15450 (goto-char (point-min))
15451 (setq res
15452 (append
15454 (org-scan-tags
15455 func matcher org--matcher-tags-todo-only)))))))))
15456 res)))
15458 ;;; Properties API
15460 (defconst org-special-properties
15461 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15462 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15463 "The special properties valid in Org mode.
15464 These are properties that are not defined in the property drawer,
15465 but in some other way.")
15467 (defconst org-default-properties
15468 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15469 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15470 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15471 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15472 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15473 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15474 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15475 "Some properties that are used by Org mode for various purposes.
15476 Being in this list makes sure that they are offered for completion.")
15478 (defun org--valid-property-p (property)
15479 "Non nil when string PROPERTY is a valid property name."
15480 (not
15481 (or (equal property "")
15482 (string-match-p "\\s-" property))))
15484 (defun org--update-property-plist (key val props)
15485 "Associate KEY to VAL in alist PROPS.
15486 Modifications are made by side-effect. Return new alist."
15487 (let* ((appending (string= (substring key -1) "+"))
15488 (key (if appending (substring key 0 -1) key))
15489 (old (assoc-string key props t)))
15490 (if (not old) (cons (cons key val) props)
15491 (setcdr old (if appending (concat (cdr old) " " val) val))
15492 props)))
15494 (defun org-get-property-block (&optional beg force)
15495 "Return the (beg . end) range of the body of the property drawer.
15496 BEG is the beginning of the current subtree, or of the part
15497 before the first headline. If it is not given, it will be found.
15498 If the drawer does not exist, create it if FORCE is non-nil, or
15499 return nil."
15500 (org-with-wide-buffer
15501 (when beg (goto-char beg))
15502 (unless (org-before-first-heading-p)
15503 (let ((beg (cond (beg)
15504 ((or (not (featurep 'org-inlinetask))
15505 (org-inlinetask-in-task-p))
15506 (org-back-to-heading t))
15507 (t (org-with-limited-levels (org-back-to-heading t))))))
15508 (forward-line)
15509 (when (looking-at-p org-planning-line-re) (forward-line))
15510 (cond ((looking-at org-property-drawer-re)
15511 (forward-line)
15512 (cons (point) (progn (goto-char (match-end 0))
15513 (line-beginning-position))))
15514 (force
15515 (goto-char beg)
15516 (org-insert-property-drawer)
15517 (let ((pos (save-excursion (search-forward ":END:")
15518 (line-beginning-position))))
15519 (cons pos pos))))))))
15521 (defun org-at-property-p ()
15522 "Non-nil when point is inside a property drawer.
15523 See `org-property-re' for match data, if applicable."
15524 (save-excursion
15525 (beginning-of-line)
15526 (and (looking-at org-property-re)
15527 (let ((property-drawer (save-match-data (org-get-property-block))))
15528 (and property-drawer
15529 (>= (point) (car property-drawer))
15530 (< (point) (cdr property-drawer)))))))
15532 (defun org-property-action ()
15533 "Do an action on properties."
15534 (interactive)
15535 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15536 (let ((c (read-char-exclusive)))
15537 (cl-case c
15538 (?s (call-interactively #'org-set-property))
15539 (?d (call-interactively #'org-delete-property))
15540 (?D (call-interactively #'org-delete-property-globally))
15541 (?c (call-interactively #'org-compute-property-at-point))
15542 (otherwise (user-error "No such property action %c" c)))))
15544 (defun org-inc-effort ()
15545 "Increment the value of the effort property in the current entry."
15546 (interactive)
15547 (org-set-effort nil t))
15549 (defvar org-clock-effort) ; Defined in org-clock.el.
15550 (defvar org-clock-current-task) ; Defined in org-clock.el.
15551 (defun org-set-effort (&optional value increment)
15552 "Set the effort property of the current entry.
15553 With numerical prefix arg, use the nth allowed value, 0 stands for the
15554 10th allowed value.
15556 When INCREMENT is non-nil, set the property to the next allowed value."
15557 (interactive "P")
15558 (when (equal value 0) (setq value 10))
15559 (let* ((completion-ignore-case t)
15560 (prop org-effort-property)
15561 (cur (org-entry-get nil prop))
15562 (allowed (org-property-get-allowed-values nil prop 'table))
15563 (existing (mapcar 'list (org-property-values prop)))
15564 (heading (nth 4 (org-heading-components)))
15566 (val (cond
15567 ((stringp value) value)
15568 ((and allowed (integerp value))
15569 (or (car (nth (1- value) allowed))
15570 (car (org-last allowed))))
15571 ((and allowed increment)
15572 (or (cl-caadr (member (list cur) allowed))
15573 (user-error "Allowed effort values are not set")))
15574 (allowed
15575 (message "Select 1-9,0, [RET%s]: %s"
15576 (if cur (concat "=" cur) "")
15577 (mapconcat 'car allowed " "))
15578 (setq rpl (read-char-exclusive))
15579 (if (equal rpl ?\r)
15581 (setq rpl (- rpl ?0))
15582 (when (equal rpl 0) (setq rpl 10))
15583 (if (and (> rpl 0) (<= rpl (length allowed)))
15584 (car (nth (1- rpl) allowed))
15585 (org-completing-read "Effort: " allowed nil))))
15587 (org-completing-read
15588 (concat "Effort" (and cur (string-match "\\S-" cur)
15589 (concat " [" cur "]"))
15590 ": ")
15591 existing nil nil "" nil cur)))))
15592 (unless (equal (org-entry-get nil prop) val)
15593 (org-entry-put nil prop val))
15594 (org-refresh-property
15595 '((effort . identity)
15596 (effort-minutes . org-duration-to-minutes))
15597 val)
15598 (when (equal heading (bound-and-true-p org-clock-current-task))
15599 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15600 (org-clock-update-mode-line))
15601 (message "%s is now %s" prop val)))
15603 (defun org-entry-properties (&optional pom which)
15604 "Get all properties of the current entry.
15606 When POM is a buffer position, get all properties from the entry
15607 there instead.
15609 This includes the TODO keyword, the tags, time strings for
15610 deadline, scheduled, and clocking, and any additional properties
15611 defined in the entry.
15613 If WHICH is nil or `all', get all properties. If WHICH is
15614 `special' or `standard', only get that subclass. If WHICH is
15615 a string, only get that property.
15617 Return value is an alist. Keys are properties, as upcased
15618 strings."
15619 (org-with-point-at pom
15620 (when (and (derived-mode-p 'org-mode)
15621 (ignore-errors (org-back-to-heading t)))
15622 (catch 'exit
15623 (let* ((beg (point))
15624 (specific (and (stringp which) (upcase which)))
15625 (which (cond ((not specific) which)
15626 ((member specific org-special-properties) 'special)
15627 (t 'standard)))
15628 props)
15629 ;; Get the special properties, like TODO and TAGS.
15630 (when (memq which '(nil all special))
15631 (when (or (not specific) (string= specific "CLOCKSUM"))
15632 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15633 (when clocksum
15634 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15635 props)))
15636 (when specific (throw 'exit props)))
15637 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15638 (let ((clocksumt (get-text-property (point)
15639 :org-clock-minutes-today)))
15640 (when clocksumt
15641 (push (cons "CLOCKSUM_T"
15642 (org-duration-from-minutes clocksumt))
15643 props)))
15644 (when specific (throw 'exit props)))
15645 (when (or (not specific) (string= specific "ITEM"))
15646 (let ((case-fold-search nil))
15647 (when (looking-at org-complex-heading-regexp)
15648 (push (cons "ITEM"
15649 (let ((title (match-string-no-properties 4)))
15650 (if (org-string-nw-p title)
15651 (org-remove-tabs title)
15652 "")))
15653 props)))
15654 (when specific (throw 'exit props)))
15655 (when (or (not specific) (string= specific "TODO"))
15656 (let ((case-fold-search nil))
15657 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15658 (push (cons "TODO" (match-string-no-properties 2)) props)))
15659 (when specific (throw 'exit props)))
15660 (when (or (not specific) (string= specific "PRIORITY"))
15661 (push (cons "PRIORITY"
15662 (if (looking-at org-priority-regexp)
15663 (match-string-no-properties 2)
15664 (char-to-string org-default-priority)))
15665 props)
15666 (when specific (throw 'exit props)))
15667 (when (or (not specific) (string= specific "FILE"))
15668 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15669 props)
15670 (when specific (throw 'exit props)))
15671 (when (or (not specific) (string= specific "TAGS"))
15672 (let ((value (org-string-nw-p (org-get-tags-string))))
15673 (when value (push (cons "TAGS" value) props)))
15674 (when specific (throw 'exit props)))
15675 (when (or (not specific) (string= specific "ALLTAGS"))
15676 (let ((value (org-get-tags-at)))
15677 (when value
15678 (push (cons "ALLTAGS"
15679 (format ":%s:" (mapconcat #'identity value ":")))
15680 props)))
15681 (when specific (throw 'exit props)))
15682 (when (or (not specific) (string= specific "BLOCKED"))
15683 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15684 (when specific (throw 'exit props)))
15685 (when (or (not specific)
15686 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15687 (forward-line)
15688 (when (looking-at-p org-planning-line-re)
15689 (end-of-line)
15690 (let ((bol (line-beginning-position))
15691 ;; Backward compatibility: time keywords used to
15692 ;; be configurable (before 8.3). Make sure we
15693 ;; get the correct keyword.
15694 (key-assoc `(("CLOSED" . ,org-closed-string)
15695 ("DEADLINE" . ,org-deadline-string)
15696 ("SCHEDULED" . ,org-scheduled-string))))
15697 (dolist (pair (if specific (list (assoc specific key-assoc))
15698 key-assoc))
15699 (save-excursion
15700 (when (search-backward (cdr pair) bol t)
15701 (goto-char (match-end 0))
15702 (skip-chars-forward " \t")
15703 (and (looking-at org-ts-regexp-both)
15704 (push (cons (car pair)
15705 (match-string-no-properties 0))
15706 props)))))))
15707 (when specific (throw 'exit props)))
15708 (when (or (not specific)
15709 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15710 (let ((find-ts
15711 (lambda (end ts)
15712 ;; Fix next time-stamp before END. TS is the
15713 ;; list of time-stamps found so far.
15714 (let ((ts ts)
15715 (regexp (cond
15716 ((string= specific "TIMESTAMP")
15717 org-ts-regexp)
15718 ((string= specific "TIMESTAMP_IA")
15719 org-ts-regexp-inactive)
15720 ((assoc "TIMESTAMP_IA" ts)
15721 org-ts-regexp)
15722 ((assoc "TIMESTAMP" ts)
15723 org-ts-regexp-inactive)
15724 (t org-ts-regexp-both))))
15725 (catch 'next
15726 (while (re-search-forward regexp end t)
15727 (backward-char)
15728 (let ((object (org-element-context)))
15729 ;; Accept to match timestamps in node
15730 ;; properties, too.
15731 (when (memq (org-element-type object)
15732 '(node-property timestamp))
15733 (let ((type
15734 (org-element-property :type object)))
15735 (cond
15736 ((and (memq type '(active active-range))
15737 (not (equal specific "TIMESTAMP_IA")))
15738 (unless (assoc "TIMESTAMP" ts)
15739 (push (cons "TIMESTAMP"
15740 (org-element-property
15741 :raw-value object))
15743 (when specific (throw 'exit ts))))
15744 ((and (memq type '(inactive inactive-range))
15745 (not (string= specific "TIMESTAMP")))
15746 (unless (assoc "TIMESTAMP_IA" ts)
15747 (push (cons "TIMESTAMP_IA"
15748 (org-element-property
15749 :raw-value object))
15751 (when specific (throw 'exit ts))))))
15752 ;; Both timestamp types are found,
15753 ;; move to next part.
15754 (when (= (length ts) 2) (throw 'next ts)))))
15755 ts)))))
15756 (goto-char beg)
15757 ;; First look for timestamps within headline.
15758 (let ((ts (funcall find-ts (line-end-position) nil)))
15759 (if (= (length ts) 2) (setq props (nconc ts props))
15760 ;; Then find timestamps in the section, skipping
15761 ;; planning line.
15762 (let ((end (save-excursion (outline-next-heading))))
15763 (forward-line)
15764 (when (looking-at-p org-planning-line-re) (forward-line))
15765 (setq props (nconc (funcall find-ts end ts) props))))))))
15766 ;; Get the standard properties, like :PROP:.
15767 (when (memq which '(nil all standard))
15768 ;; If we are looking after a specific property, delegate
15769 ;; to `org-entry-get', which is faster. However, make an
15770 ;; exception for "CATEGORY", since it can be also set
15771 ;; through keywords (i.e. #+CATEGORY).
15772 (if (and specific (not (equal specific "CATEGORY")))
15773 (let ((value (org-entry-get beg specific nil t)))
15774 (throw 'exit (and value (list (cons specific value)))))
15775 (let ((range (org-get-property-block beg)))
15776 (when range
15777 (let ((end (cdr range)) seen-base)
15778 (goto-char (car range))
15779 ;; Unlike to `org--update-property-plist', we
15780 ;; handle the case where base values is found
15781 ;; after its extension. We also forbid standard
15782 ;; properties to be named as special properties.
15783 (while (re-search-forward org-property-re end t)
15784 (let* ((key (upcase (match-string-no-properties 2)))
15785 (extendp (string-match-p "\\+\\'" key))
15786 (key-base (if extendp (substring key 0 -1) key))
15787 (value (match-string-no-properties 3)))
15788 (cond
15789 ((member-ignore-case key-base org-special-properties))
15790 (extendp
15791 (setq props
15792 (org--update-property-plist key value props)))
15793 ((member key seen-base))
15794 (t (push key seen-base)
15795 (let ((p (assoc-string key props t)))
15796 (if p (setcdr p (concat value " " (cdr p)))
15797 (push (cons key value) props))))))))))))
15798 (unless (assoc "CATEGORY" props)
15799 (push (cons "CATEGORY" (org-get-category beg)) props)
15800 (when (string= specific "CATEGORY") (throw 'exit props)))
15801 ;; Return value.
15802 props)))))
15804 (defun org--property-local-values (property literal-nil)
15805 "Return value for PROPERTY in current entry.
15806 Value is a list whose car is the base value for PROPERTY and cdr
15807 a list of accumulated values. Return nil if neither is found in
15808 the entry. Also return nil when PROPERTY is set to \"nil\",
15809 unless LITERAL-NIL is non-nil."
15810 (let ((range (org-get-property-block)))
15811 (when range
15812 (goto-char (car range))
15813 (let* ((case-fold-search t)
15814 (end (cdr range))
15815 (value
15816 ;; Base value.
15817 (save-excursion
15818 (let ((v (and (re-search-forward
15819 (org-re-property property nil t) end t)
15820 (match-string-no-properties 3))))
15821 (list (if literal-nil v (org-not-nil v)))))))
15822 ;; Find additional values.
15823 (let* ((property+ (org-re-property (concat property "+") nil t)))
15824 (while (re-search-forward property+ end t)
15825 (push (match-string-no-properties 3) value)))
15826 ;; Return final values.
15827 (and (not (equal value '(nil))) (nreverse value))))))
15829 (defun org--property-global-value (property literal-nil)
15830 "Return value for PROPERTY in current buffer.
15831 Return value is a string. Return nil if property is not set
15832 globally. Also return nil when PROPERTY is set to \"nil\",
15833 unless LITERAL-NIL is non-nil."
15834 (let ((global
15835 (cdr (or (assoc-string property org-file-properties t)
15836 (assoc-string property org-global-properties t)
15837 (assoc-string property org-global-properties-fixed t)))))
15838 (if literal-nil global (org-not-nil global))))
15840 (defun org-entry-get (pom property &optional inherit literal-nil)
15841 "Get value of PROPERTY for entry or content at point-or-marker POM.
15843 If INHERIT is non-nil and the entry does not have the property,
15844 then also check higher levels of the hierarchy. If INHERIT is
15845 the symbol `selective', use inheritance only if the setting in
15846 `org-use-property-inheritance' selects PROPERTY for inheritance.
15848 If the property is present but empty, the return value is the
15849 empty string. If the property is not present at all, nil is
15850 returned. In any other case, return the value as a string.
15851 Search is case-insensitive.
15853 If LITERAL-NIL is set, return the string value \"nil\" as
15854 a string, do not interpret it as the list atom nil. This is used
15855 for inheritance when a \"nil\" value can supersede a non-nil
15856 value higher up the hierarchy."
15857 (org-with-point-at pom
15858 (cond
15859 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15860 ;; We need a special property. Use `org-entry-properties' to
15861 ;; retrieve it, but specify the wanted property.
15862 (cdr (assoc-string property (org-entry-properties nil property))))
15863 ((and inherit
15864 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15865 (org-entry-get-with-inheritance property literal-nil))
15867 (let* ((local (org--property-local-values property literal-nil))
15868 (value (and local (mapconcat #'identity (delq nil local) " "))))
15869 (if literal-nil value (org-not-nil value)))))))
15871 (defun org-property-or-variable-value (var &optional inherit)
15872 "Check if there is a property fixing the value of VAR.
15873 If yes, return this value. If not, return the current value of the variable."
15874 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15875 (if (and prop (stringp prop) (string-match "\\S-" prop))
15876 (read prop)
15877 (symbol-value var))))
15879 (defun org-entry-delete (pom property)
15880 "Delete PROPERTY from entry at point-or-marker POM.
15881 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15882 non-nil when a property was removed."
15883 (org-with-point-at pom
15884 (pcase (org-get-property-block)
15885 (`(,begin . ,origin)
15886 (let* ((end (copy-marker origin))
15887 (re (org-re-property
15888 (concat (regexp-quote property) "\\+?") t t)))
15889 (goto-char begin)
15890 (while (re-search-forward re end t)
15891 (delete-region (match-beginning 0) (line-beginning-position 2)))
15892 ;; If drawer is empty, remove it altogether.
15893 (when (= begin end)
15894 (delete-region (line-beginning-position 0)
15895 (line-beginning-position 2)))
15896 ;; Return non-nil if some property was removed.
15897 (prog1 (/= end origin) (set-marker end nil))))
15898 (_ nil))))
15900 ;; Multi-values properties are properties that contain multiple values
15901 ;; These values are assumed to be single words, separated by whitespace.
15902 (defun org-entry-add-to-multivalued-property (pom property value)
15903 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15904 (let* ((old (org-entry-get pom property))
15905 (values (and old (org-split-string old "[ \t]"))))
15906 (setq value (org-entry-protect-space value))
15907 (unless (member value values)
15908 (setq values (append values (list value)))
15909 (org-entry-put pom property
15910 (mapconcat 'identity values " ")))))
15912 (defun org-entry-remove-from-multivalued-property (pom property value)
15913 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15914 (let* ((old (org-entry-get pom property))
15915 (values (and old (org-split-string old "[ \t]"))))
15916 (setq value (org-entry-protect-space value))
15917 (when (member value values)
15918 (setq values (delete value values))
15919 (org-entry-put pom property
15920 (mapconcat 'identity values " ")))))
15922 (defun org-entry-member-in-multivalued-property (pom property value)
15923 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15924 (let* ((old (org-entry-get pom property))
15925 (values (and old (org-split-string old "[ \t]"))))
15926 (setq value (org-entry-protect-space value))
15927 (member value values)))
15929 (defun org-entry-get-multivalued-property (pom property)
15930 "Return a list of values in a multivalued property."
15931 (let* ((value (org-entry-get pom property))
15932 (values (and value (org-split-string value "[ \t]"))))
15933 (mapcar 'org-entry-restore-space values)))
15935 (defun org-entry-put-multivalued-property (pom property &rest values)
15936 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15937 VALUES should be a list of strings. Spaces will be protected."
15938 (org-entry-put pom property
15939 (mapconcat 'org-entry-protect-space values " "))
15940 (let* ((value (org-entry-get pom property))
15941 (values (and value (org-split-string value "[ \t]"))))
15942 (mapcar 'org-entry-restore-space values)))
15944 (defun org-entry-protect-space (s)
15945 "Protect spaces and newline in string S."
15946 (while (string-match " " s)
15947 (setq s (replace-match "%20" t t s)))
15948 (while (string-match "\n" s)
15949 (setq s (replace-match "%0A" t t s)))
15952 (defun org-entry-restore-space (s)
15953 "Restore spaces and newline in string S."
15954 (while (string-match "%20" s)
15955 (setq s (replace-match " " t t s)))
15956 (while (string-match "%0A" s)
15957 (setq s (replace-match "\n" t t s)))
15960 (defvar org-entry-property-inherited-from (make-marker)
15961 "Marker pointing to the entry from where a property was inherited.
15962 Each call to `org-entry-get-with-inheritance' will set this marker to the
15963 location of the entry where the inheritance search matched. If there was
15964 no match, the marker will point nowhere.
15965 Note that also `org-entry-get' calls this function, if the INHERIT flag
15966 is set.")
15968 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15969 "Get PROPERTY of entry or content at point, search higher levels if needed.
15970 The search will stop at the first ancestor which has the property defined.
15971 If the value found is \"nil\", return nil to show that the property
15972 should be considered as undefined (this is the meaning of nil here).
15973 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15974 (move-marker org-entry-property-inherited-from nil)
15975 (org-with-wide-buffer
15976 (let (value)
15977 (catch 'exit
15978 (while t
15979 (let ((v (org--property-local-values property literal-nil)))
15980 (when v
15981 (setq value
15982 (concat (mapconcat #'identity (delq nil v) " ")
15983 (and value " ")
15984 value)))
15985 (cond
15986 ((car v)
15987 (org-back-to-heading t)
15988 (move-marker org-entry-property-inherited-from (point))
15989 (throw 'exit nil))
15990 ((org-up-heading-safe))
15992 (let ((global (org--property-global-value property literal-nil)))
15993 (cond ((not global))
15994 (value (setq value (concat global " " value)))
15995 (t (setq value global))))
15996 (throw 'exit nil))))))
15997 (if literal-nil value (org-not-nil value)))))
15999 (defvar org-property-changed-functions nil
16000 "Hook called when the value of a property has changed.
16001 Each hook function should accept two arguments, the name of the property
16002 and the new value.")
16004 (defun org-entry-put (pom property value)
16005 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16007 If the value is nil, it is converted to the empty string. If it
16008 is not a string, an error is raised. Also raise an error on
16009 invalid property names.
16011 PROPERTY can be any regular property (see
16012 `org-special-properties'). It can also be \"TODO\",
16013 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16015 For the last two properties, VALUE may have any of the special
16016 values \"earlier\" and \"later\". The function then increases or
16017 decreases scheduled or deadline date by one day."
16018 (cond ((null value) (setq value ""))
16019 ((not (stringp value)) (error "Properties values should be strings"))
16020 ((not (org--valid-property-p property))
16021 (user-error "Invalid property name: \"%s\"" property)))
16022 (org-with-point-at pom
16023 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16024 (org-back-to-heading t)
16025 (org-with-limited-levels (org-back-to-heading t)))
16026 (let ((beg (point)))
16027 (cond
16028 ((equal property "TODO")
16029 (cond ((not (org-string-nw-p value)) (setq value 'none))
16030 ((not (member value org-todo-keywords-1))
16031 (user-error "\"%s\" is not a valid TODO state" value)))
16032 (org-todo value)
16033 (org-set-tags nil 'align))
16034 ((equal property "PRIORITY")
16035 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16036 (org-set-tags nil 'align))
16037 ((equal property "SCHEDULED")
16038 (forward-line)
16039 (if (and (looking-at-p org-planning-line-re)
16040 (re-search-forward
16041 org-scheduled-time-regexp (line-end-position) t))
16042 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16043 ((string= value "later") (org-timestamp-change 1 'day))
16044 ((string= value "") (org-schedule '(4)))
16045 (t (org-schedule nil value)))
16046 (if (member value '("earlier" "later" ""))
16047 (call-interactively #'org-schedule)
16048 (org-schedule nil value))))
16049 ((equal property "DEADLINE")
16050 (forward-line)
16051 (if (and (looking-at-p org-planning-line-re)
16052 (re-search-forward
16053 org-deadline-time-regexp (line-end-position) t))
16054 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16055 ((string= value "later") (org-timestamp-change 1 'day))
16056 ((string= value "") (org-deadline '(4)))
16057 (t (org-deadline nil value)))
16058 (if (member value '("earlier" "later" ""))
16059 (call-interactively #'org-deadline)
16060 (org-deadline nil value))))
16061 ((member property org-special-properties)
16062 (error "The %s property cannot be set with `org-entry-put'" property))
16064 (let* ((range (org-get-property-block beg 'force))
16065 (end (cdr range))
16066 (case-fold-search t))
16067 (goto-char (car range))
16068 (if (re-search-forward (org-re-property property nil t) end t)
16069 (progn (delete-region (match-beginning 0) (match-end 0))
16070 (goto-char (match-beginning 0)))
16071 (goto-char end)
16072 (insert "\n")
16073 (backward-char))
16074 (insert ":" property ":")
16075 (when value (insert " " value))
16076 (org-indent-line)))))
16077 (run-hook-with-args 'org-property-changed-functions property value)))
16079 (defun org-buffer-property-keys
16080 (&optional specials defaults columns ignore-malformed)
16081 "Get all property keys in the current buffer.
16083 When SPECIALS is non-nil, also list the special properties that
16084 reflect things like tags and TODO state.
16086 When DEFAULTS is non-nil, also include properties that has
16087 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16088 DESCRIPTION, LOCATION, and LOGGING and others.
16090 When COLUMNS in non-nil, also include property names given in
16091 COLUMN formats in the current buffer.
16093 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16094 automatically performed, such drawers will be silently ignored."
16095 (let ((case-fold-search t)
16096 (props (append
16097 (and specials org-special-properties)
16098 (and defaults (cons org-effort-property org-default-properties))
16099 nil)))
16100 (org-with-wide-buffer
16101 (goto-char (point-min))
16102 (while (re-search-forward org-property-start-re nil t)
16103 (let ((range (org-get-property-block)))
16104 (catch 'skip
16105 (unless range
16106 (when (and (not ignore-malformed)
16107 (not (org-before-first-heading-p))
16108 (y-or-n-p (format "Malformed drawer at %d, repair?"
16109 (line-beginning-position))))
16110 (org-get-property-block nil t))
16111 (throw 'skip nil))
16112 (goto-char (car range))
16113 (let ((begin (car range))
16114 (end (cdr range)))
16115 ;; Make sure that found property block is not located
16116 ;; before current point, as it would generate an infloop.
16117 ;; It can happen, for example, in the following
16118 ;; situation:
16120 ;; * Headline
16121 ;; :PROPERTIES:
16122 ;; ...
16123 ;; :END:
16124 ;; *************** Inlinetask
16125 ;; #+BEGIN_EXAMPLE
16126 ;; :PROPERTIES:
16127 ;; #+END_EXAMPLE
16129 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16130 (while (< (point) end)
16131 (let ((p (progn (looking-at org-property-re)
16132 (match-string-no-properties 2))))
16133 ;; Only add true property name, not extension symbol.
16134 (push (if (not (string-match-p "\\+\\'" p)) p
16135 (substring p 0 -1))
16136 props))
16137 (forward-line))))
16138 (outline-next-heading)))
16139 (when columns
16140 (goto-char (point-min))
16141 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16142 (let ((element (org-element-at-point)))
16143 (when (memq (org-element-type element) '(keyword node-property))
16144 (let ((value (org-element-property :value element))
16145 (start 0))
16146 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16147 (setq start (match-end 0))
16148 (let ((p (match-string-no-properties 1 value)))
16149 (unless (member-ignore-case p org-special-properties)
16150 (push p props))))))))))
16151 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16153 (defun org-property-values (key)
16154 "List all non-nil values of property KEY in current buffer."
16155 (org-with-wide-buffer
16156 (goto-char (point-min))
16157 (let ((case-fold-search t)
16158 (re (org-re-property key))
16159 values)
16160 (while (re-search-forward re nil t)
16161 (push (org-entry-get (point) key) values))
16162 (delete-dups values))))
16164 (defun org-insert-property-drawer ()
16165 "Insert a property drawer into the current entry."
16166 (org-with-wide-buffer
16167 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16168 (org-back-to-heading t)
16169 (org-with-limited-levels (org-back-to-heading t)))
16170 (forward-line)
16171 (when (looking-at-p org-planning-line-re) (forward-line))
16172 (unless (looking-at-p org-property-drawer-re)
16173 ;; Make sure we start editing a line from current entry, not from
16174 ;; next one. It prevents extending text properties or overlays
16175 ;; belonging to the latter.
16176 (when (bolp) (backward-char))
16177 (let ((begin (1+ (point)))
16178 (inhibit-read-only t))
16179 (insert "\n:PROPERTIES:\n:END:")
16180 (when (eobp) (insert "\n"))
16181 (org-indent-region begin (point))))))
16183 (defun org-insert-drawer (&optional arg drawer)
16184 "Insert a drawer at point.
16186 When optional argument ARG is non-nil, insert a property drawer.
16188 Optional argument DRAWER, when non-nil, is a string representing
16189 drawer's name. Otherwise, the user is prompted for a name.
16191 If a region is active, insert the drawer around that region
16192 instead.
16194 Point is left between drawer's boundaries."
16195 (interactive "P")
16196 (let* ((drawer (if arg "PROPERTIES"
16197 (or drawer (read-from-minibuffer "Drawer: ")))))
16198 (cond
16199 ;; With C-u, fall back on `org-insert-property-drawer'
16200 (arg (org-insert-property-drawer))
16201 ;; Check validity of suggested drawer's name.
16202 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16203 (user-error "Invalid drawer name"))
16204 ;; With an active region, insert a drawer at point.
16205 ((not (org-region-active-p))
16206 (progn
16207 (unless (bolp) (insert "\n"))
16208 (insert (format ":%s:\n\n:END:\n" drawer))
16209 (forward-line -2)))
16210 ;; Otherwise, insert the drawer at point
16212 (let ((rbeg (region-beginning))
16213 (rend (copy-marker (region-end))))
16214 (unwind-protect
16215 (progn
16216 (goto-char rbeg)
16217 (beginning-of-line)
16218 (when (save-excursion
16219 (re-search-forward org-outline-regexp-bol rend t))
16220 (user-error "Drawers cannot contain headlines"))
16221 ;; Position point at the beginning of the first
16222 ;; non-blank line in region. Insert drawer's opening
16223 ;; there, then indent it.
16224 (org-skip-whitespace)
16225 (beginning-of-line)
16226 (insert ":" drawer ":\n")
16227 (forward-line -1)
16228 (indent-for-tab-command)
16229 ;; Move point to the beginning of the first blank line
16230 ;; after the last non-blank line in region. Insert
16231 ;; drawer's closing, then indent it.
16232 (goto-char rend)
16233 (skip-chars-backward " \r\t\n")
16234 (insert "\n:END:")
16235 (deactivate-mark t)
16236 (indent-for-tab-command)
16237 (unless (eolp) (insert "\n")))
16238 ;; Clear marker, whatever the outcome of insertion is.
16239 (set-marker rend nil)))))))
16241 (defvar org-property-set-functions-alist nil
16242 "Property set function alist.
16243 Each entry should have the following format:
16245 (PROPERTY . READ-FUNCTION)
16247 The read function will be called with the same argument as
16248 `org-completing-read'.")
16250 (defun org-set-property-function (property)
16251 "Get the function that should be used to set PROPERTY.
16252 This is computed according to `org-property-set-functions-alist'."
16253 (or (cdr (assoc property org-property-set-functions-alist))
16254 'org-completing-read))
16256 (defun org-read-property-value (property)
16257 "Read PROPERTY value from user."
16258 (let* ((completion-ignore-case t)
16259 (allowed (org-property-get-allowed-values nil property 'table))
16260 (cur (org-entry-get nil property))
16261 (prompt (concat property " value"
16262 (if (and cur (string-match "\\S-" cur))
16263 (concat " [" cur "]") "") ": "))
16264 (set-function (org-set-property-function property))
16265 (val (if allowed
16266 (funcall set-function prompt allowed nil
16267 (not (get-text-property 0 'org-unrestricted
16268 (caar allowed))))
16269 (funcall set-function prompt
16270 (mapcar 'list (org-property-values property))
16271 nil nil "" nil cur))))
16272 (org-trim val)))
16274 (defvar org-last-set-property nil)
16275 (defvar org-last-set-property-value nil)
16276 (defun org-read-property-name ()
16277 "Read a property name."
16278 (let ((completion-ignore-case t)
16279 (default-prop (or (and (org-at-property-p)
16280 (match-string-no-properties 2))
16281 org-last-set-property)))
16282 (org-completing-read
16283 (concat "Property"
16284 (if default-prop (concat " [" default-prop "]") "")
16285 ": ")
16286 (mapcar #'list (org-buffer-property-keys nil t t))
16287 nil nil nil nil default-prop)))
16289 (defun org-set-property-and-value (use-last)
16290 "Allow to set [PROPERTY]: [value] direction from prompt.
16291 When use-default, don't even ask, just use the last
16292 \"[PROPERTY]: [value]\" string from the history."
16293 (interactive "P")
16294 (let* ((completion-ignore-case t)
16295 (pv (or (and use-last org-last-set-property-value)
16296 (org-completing-read
16297 "Enter a \"[Property]: [value]\" pair: "
16298 nil nil nil nil nil
16299 org-last-set-property-value)))
16300 prop val)
16301 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16302 (setq prop (match-string 1 pv)
16303 val (match-string 2 pv))
16304 (org-set-property prop val))))
16306 (defun org-set-property (property value)
16307 "In the current entry, set PROPERTY to VALUE.
16309 When called interactively, this will prompt for a property name, offering
16310 completion on existing and default properties. And then it will prompt
16311 for a value, offering completion either on allowed values (via an inherited
16312 xxx_ALL property) or on existing values in other instances of this property
16313 in the current file.
16315 Throw an error when trying to set a property with an invalid name."
16316 (interactive (list nil nil))
16317 (let ((property (or property (org-read-property-name))))
16318 ;; `org-entry-put' also makes the following check, but this one
16319 ;; avoids polluting `org-last-set-property' and
16320 ;; `org-last-set-property-value' needlessly.
16321 (unless (org--valid-property-p property)
16322 (user-error "Invalid property name: \"%s\"" property))
16323 (let ((value (or value (org-read-property-value property)))
16324 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16325 (setq org-last-set-property property)
16326 (setq org-last-set-property-value (concat property ": " value))
16327 ;; Possibly postprocess the inserted value:
16328 (when fn (setq value (funcall fn value)))
16329 (unless (equal (org-entry-get nil property) value)
16330 (org-entry-put nil property value)))))
16332 (defun org-find-property (property &optional value)
16333 "Find first entry in buffer that sets PROPERTY.
16335 When optional argument VALUE is non-nil, only consider an entry
16336 if it contains PROPERTY set to this value. If PROPERTY should be
16337 explicitly set to nil, use string \"nil\" for VALUE.
16339 Return position where the entry begins, or nil if there is no
16340 such entry. If narrowing is in effect, only search the visible
16341 part of the buffer."
16342 (save-excursion
16343 (goto-char (point-min))
16344 (let ((case-fold-search t)
16345 (re (org-re-property property nil (not value) value)))
16346 (catch 'exit
16347 (while (re-search-forward re nil t)
16348 (when (if value (org-at-property-p)
16349 (org-entry-get (point) property nil t))
16350 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16352 (defun org-delete-property (property)
16353 "In the current entry, delete PROPERTY."
16354 (interactive
16355 (let* ((completion-ignore-case t)
16356 (cat (org-entry-get (point) "CATEGORY"))
16357 (props0 (org-entry-properties nil 'standard))
16358 (props (if cat props0
16359 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16360 (prop (if (< 1 (length props))
16361 (completing-read "Property: " props nil t)
16362 (caar props))))
16363 (list prop)))
16364 (if (not property)
16365 (message "No property to delete in this entry")
16366 (org-entry-delete nil property)
16367 (message "Property \"%s\" deleted" property)))
16369 (defun org-delete-property-globally (property)
16370 "Remove PROPERTY globally, from all entries.
16371 This function ignores narrowing, if any."
16372 (interactive
16373 (let* ((completion-ignore-case t)
16374 (prop (completing-read
16375 "Globally remove property: "
16376 (mapcar #'list (org-buffer-property-keys)))))
16377 (list prop)))
16378 (org-with-wide-buffer
16379 (goto-char (point-min))
16380 (let ((count 0)
16381 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16382 (while (re-search-forward re nil t)
16383 (when (org-entry-delete (point) property) (cl-incf count)))
16384 (message "Property \"%s\" removed from %d entries" property count))))
16386 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16388 (defun org-compute-property-at-point ()
16389 "Compute the property at point.
16390 This looks for an enclosing column format, extracts the operator and
16391 then applies it to the property in the column format's scope."
16392 (interactive)
16393 (unless (org-at-property-p)
16394 (user-error "Not at a property"))
16395 (let ((prop (match-string-no-properties 2)))
16396 (org-columns-get-format-and-top-level)
16397 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16398 (user-error "No operator defined for property %s" prop))
16399 (org-columns-compute prop)))
16401 (defvar org-property-allowed-value-functions nil
16402 "Hook for functions supplying allowed values for a specific property.
16403 The functions must take a single argument, the name of the property, and
16404 return a flat list of allowed values. If \":ETC\" is one of
16405 the values, this means that these values are intended as defaults for
16406 completion, but that other values should be allowed too.
16407 The functions must return nil if they are not responsible for this
16408 property.")
16410 (defun org-property-get-allowed-values (pom property &optional table)
16411 "Get allowed values for the property PROPERTY.
16412 When TABLE is non-nil, return an alist that can directly be used for
16413 completion."
16414 (let (vals)
16415 (cond
16416 ((equal property "TODO")
16417 (setq vals (org-with-point-at pom
16418 (append org-todo-keywords-1 '("")))))
16419 ((equal property "PRIORITY")
16420 (let ((n org-lowest-priority))
16421 (while (>= n org-highest-priority)
16422 (push (char-to-string n) vals)
16423 (setq n (1- n)))))
16424 ((equal property "CATEGORY"))
16425 ((member property org-special-properties))
16426 ((setq vals (run-hook-with-args-until-success
16427 'org-property-allowed-value-functions property)))
16429 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16430 (when (and vals (string-match "\\S-" vals))
16431 (setq vals (car (read-from-string (concat "(" vals ")"))))
16432 (setq vals (mapcar (lambda (x)
16433 (cond ((stringp x) x)
16434 ((numberp x) (number-to-string x))
16435 ((symbolp x) (symbol-name x))
16436 (t "???")))
16437 vals)))))
16438 (when (member ":ETC" vals)
16439 (setq vals (remove ":ETC" vals))
16440 (org-add-props (car vals) '(org-unrestricted t)))
16441 (if table (mapcar 'list vals) vals)))
16443 (defun org-property-previous-allowed-value (&optional _previous)
16444 "Switch to the next allowed value for this property."
16445 (interactive)
16446 (org-property-next-allowed-value t))
16448 (defun org-property-next-allowed-value (&optional previous)
16449 "Switch to the next allowed value for this property."
16450 (interactive)
16451 (unless (org-at-property-p)
16452 (user-error "Not at a property"))
16453 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16454 (key (match-string 2))
16455 (value (match-string 3))
16456 (allowed (or (org-property-get-allowed-values (point) key)
16457 (and (member value '("[ ]" "[-]" "[X]"))
16458 '("[ ]" "[X]"))))
16459 (heading (save-match-data (nth 4 (org-heading-components))))
16460 nval)
16461 (unless allowed
16462 (user-error "Allowed values for this property have not been defined"))
16463 (when previous (setq allowed (reverse allowed)))
16464 (when (member value allowed)
16465 (setq nval (car (cdr (member value allowed)))))
16466 (setq nval (or nval (car allowed)))
16467 (when (equal nval value)
16468 (user-error "Only one allowed value for this property"))
16469 (org-at-property-p)
16470 (replace-match (concat " :" key ": " nval) t t)
16471 (org-indent-line)
16472 (beginning-of-line 1)
16473 (skip-chars-forward " \t")
16474 (when (equal prop org-effort-property)
16475 (org-refresh-property
16476 '((effort . identity)
16477 (effort-minutes . org-duration-to-minutes))
16478 nval)
16479 (when (string= org-clock-current-task heading)
16480 (setq org-clock-effort nval)
16481 (org-clock-update-mode-line)))
16482 (run-hook-with-args 'org-property-changed-functions key nval)))
16484 (defun org-find-olp (path &optional this-buffer)
16485 "Return a marker pointing to the entry at outline path OLP.
16486 If anything goes wrong, throw an error.
16487 You can wrap this call to catch the error like this:
16489 (condition-case msg
16490 (org-mobile-locate-entry (match-string 4))
16491 (error (nth 1 msg)))
16493 The return value will then be either a string with the error message,
16494 or a marker if everything is OK.
16496 If THIS-BUFFER is set, the outline path does not contain a file,
16497 only headings."
16498 (let* ((file (if this-buffer buffer-file-name (pop path)))
16499 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16500 (level 1)
16501 (lmin 1)
16502 (lmax 1)
16503 end found flevel)
16504 (unless buffer (error "File not found :%s" file))
16505 (with-current-buffer buffer
16506 (unless (derived-mode-p 'org-mode)
16507 (error "Buffer %s needs to be in Org mode" buffer))
16508 (org-with-wide-buffer
16509 (goto-char (point-min))
16510 (dolist (heading path)
16511 (let ((re (format org-complex-heading-regexp-format
16512 (regexp-quote heading)))
16513 (cnt 0))
16514 (while (re-search-forward re end t)
16515 (setq level (- (match-end 1) (match-beginning 1)))
16516 (when (and (>= level lmin) (<= level lmax))
16517 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16518 (when (= cnt 0)
16519 (error "Heading not found on level %d: %s" lmax heading))
16520 (when (> cnt 1)
16521 (error "Heading not unique on level %d: %s" lmax heading))
16522 (goto-char found)
16523 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16524 (setq end (save-excursion (org-end-of-subtree t t)))))
16525 (when (org-at-heading-p)
16526 (point-marker))))))
16528 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16529 "Find node HEADING in BUFFER.
16530 Return a marker to the heading if it was found, or nil if not.
16531 If POS-ONLY is set, return just the position instead of a marker.
16533 The heading text must match exact, but it may have a TODO keyword,
16534 a priority cookie and tags in the standard locations."
16535 (with-current-buffer (or buffer (current-buffer))
16536 (org-with-wide-buffer
16537 (goto-char (point-min))
16538 (let (case-fold-search)
16539 (when (re-search-forward
16540 (format org-complex-heading-regexp-format
16541 (regexp-quote heading)) nil t)
16542 (if pos-only
16543 (match-beginning 0)
16544 (move-marker (make-marker) (match-beginning 0))))))))
16546 (defun org-find-exact-heading-in-directory (heading &optional dir)
16547 "Find Org node headline HEADING in all .org files in directory DIR.
16548 When the target headline is found, return a marker to this location."
16549 (let ((files (directory-files (or dir default-directory)
16550 t "\\`[^.#].*\\.org\\'"))
16551 visiting m buffer)
16552 (catch 'found
16553 (dolist (file files)
16554 (message "trying %s" file)
16555 (setq visiting (org-find-base-buffer-visiting file))
16556 (setq buffer (or visiting (find-file-noselect file)))
16557 (setq m (org-find-exact-headline-in-buffer
16558 heading buffer))
16559 (when (and (not m) (not visiting)) (kill-buffer buffer))
16560 (and m (throw 'found m))))))
16562 (defun org-find-entry-with-id (ident)
16563 "Locate the entry that contains the ID property with exact value IDENT.
16564 IDENT can be a string, a symbol or a number, this function will search for
16565 the string representation of it.
16566 Return the position where this entry starts, or nil if there is no such entry."
16567 (interactive "sID: ")
16568 (let ((id (cond
16569 ((stringp ident) ident)
16570 ((symbolp ident) (symbol-name ident))
16571 ((numberp ident) (number-to-string ident))
16572 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16573 (org-with-wide-buffer (org-find-property "ID" id))))
16575 ;;;; Timestamps
16577 (defvar org-last-changed-timestamp nil)
16578 (defvar org-last-inserted-timestamp nil
16579 "The last time stamp inserted with `org-insert-time-stamp'.")
16581 (defun org-time-stamp (arg &optional inactive)
16582 "Prompt for a date/time and insert a time stamp.
16584 If the user specifies a time like HH:MM or if this command is
16585 called with at least one prefix argument, the time stamp contains
16586 the date and the time. Otherwise, only the date is included.
16588 All parts of a date not specified by the user are filled in from
16589 the timestamp at point, if any, or the current date/time
16590 otherwise.
16592 If there is already a timestamp at the cursor, it is replaced.
16594 With two universal prefix arguments, insert an active timestamp
16595 with the current time without prompting the user.
16597 When called from lisp, the timestamp is inactive if INACTIVE is
16598 non-nil."
16599 (interactive "P")
16600 (let* ((ts (cond
16601 ((org-at-date-range-p t)
16602 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16603 ((org-at-timestamp-p 'lax) (match-string 0))))
16604 ;; Default time is either the timestamp at point or today.
16605 ;; When entering a range, only the range start is considered.
16606 (default-time (if (not ts) (current-time)
16607 (apply #'encode-time (org-parse-time-string ts))))
16608 (default-input (and ts (org-get-compact-tod ts)))
16609 (repeater (and ts
16610 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16611 (match-string 0 ts)))
16612 org-time-was-given
16613 org-end-time-was-given
16614 (time
16615 (and (if (equal arg '(16)) (current-time)
16616 ;; Preserve `this-command' and `last-command'.
16617 (let ((this-command this-command)
16618 (last-command last-command))
16619 (org-read-date
16620 arg 'totime nil nil default-time default-input
16621 inactive))))))
16622 (cond
16623 ((and ts
16624 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16625 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16626 (insert "--")
16627 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16629 ;; Make sure we're on a timestamp. When in the middle of a date
16630 ;; range, move arbitrarily to range end.
16631 (unless (org-at-timestamp-p 'lax)
16632 (skip-chars-forward "-")
16633 (org-at-timestamp-p 'lax))
16634 (replace-match "")
16635 (setq org-last-changed-timestamp
16636 (org-insert-time-stamp
16637 time (or org-time-was-given arg)
16638 inactive nil nil (list org-end-time-was-given)))
16639 (when repeater
16640 (backward-char)
16641 (insert " " repeater)
16642 (setq org-last-changed-timestamp
16643 (concat (substring org-last-inserted-timestamp 0 -1)
16644 " " repeater ">")))
16645 (message "Timestamp updated"))
16646 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16647 (t (org-insert-time-stamp
16648 time (or org-time-was-given arg) inactive nil nil
16649 (list org-end-time-was-given))))))
16651 ;; FIXME: can we use this for something else, like computing time differences?
16652 (defun org-get-compact-tod (s)
16653 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16654 (let* ((t1 (match-string 1 s))
16655 (h1 (string-to-number (match-string 2 s)))
16656 (m1 (string-to-number (match-string 3 s)))
16657 (t2 (and (match-end 4) (match-string 5 s)))
16658 (h2 (and t2 (string-to-number (match-string 6 s))))
16659 (m2 (and t2 (string-to-number (match-string 7 s))))
16660 dh dm)
16661 (if (not t2)
16663 (setq dh (- h2 h1) dm (- m2 m1))
16664 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16665 (concat t1 "+" (number-to-string dh)
16666 (and (/= 0 dm) (format ":%02d" dm)))))))
16668 (defun org-time-stamp-inactive (&optional arg)
16669 "Insert an inactive time stamp.
16670 An inactive time stamp is enclosed in square brackets instead of angle
16671 brackets. It is inactive in the sense that it does not trigger agenda entries,
16672 does not link to the calendar and cannot be changed with the S-cursor keys.
16673 So these are more for recording a certain time/date."
16674 (interactive "P")
16675 (org-time-stamp arg 'inactive))
16677 (defvar org-date-ovl (make-overlay 1 1))
16678 (overlay-put org-date-ovl 'face 'org-date-selected)
16679 (delete-overlay org-date-ovl)
16681 (defvar org-ans1) ; dynamically scoped parameter
16682 (defvar org-ans2) ; dynamically scoped parameter
16684 (defvar org-plain-time-of-day-regexp) ; defined below
16686 (defvar org-overriding-default-time nil) ; dynamically scoped
16687 (defvar org-read-date-overlay nil)
16688 (defvar org-dcst nil) ; dynamically scoped
16689 (defvar org-read-date-history nil)
16690 (defvar org-read-date-final-answer nil)
16691 (defvar org-read-date-analyze-futurep nil)
16692 (defvar org-read-date-analyze-forced-year nil)
16693 (defvar org-read-date-inactive)
16695 (defvar org-read-date-minibuffer-local-map
16696 (let* ((map (make-sparse-keymap)))
16697 (set-keymap-parent map minibuffer-local-map)
16698 (org-defkey map (kbd ".")
16699 (lambda () (interactive)
16700 ;; Are we at the beginning of the prompt?
16701 (if (looking-back "^[^:]+: "
16702 (let ((inhibit-field-text-motion t))
16703 (line-beginning-position)))
16704 (org-eval-in-calendar '(calendar-goto-today))
16705 (insert "."))))
16706 (org-defkey map (kbd "C-.")
16707 (lambda () (interactive)
16708 (org-eval-in-calendar '(calendar-goto-today))))
16709 (org-defkey map [(meta shift left)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-backward-month 1))))
16712 (org-defkey map [(meta shift right)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-forward-month 1))))
16715 (org-defkey map [(meta shift up)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-backward-year 1))))
16718 (org-defkey map [(meta shift down)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-forward-year 1))))
16721 (org-defkey map [?\e (shift left)]
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(calendar-backward-month 1))))
16724 (org-defkey map [?\e (shift right)]
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(calendar-forward-month 1))))
16727 (org-defkey map [?\e (shift up)]
16728 (lambda () (interactive)
16729 (org-eval-in-calendar '(calendar-backward-year 1))))
16730 (org-defkey map [?\e (shift down)]
16731 (lambda () (interactive)
16732 (org-eval-in-calendar '(calendar-forward-year 1))))
16733 (org-defkey map [(shift up)]
16734 (lambda () (interactive)
16735 (org-eval-in-calendar '(calendar-backward-week 1))))
16736 (org-defkey map [(shift down)]
16737 (lambda () (interactive)
16738 (org-eval-in-calendar '(calendar-forward-week 1))))
16739 (org-defkey map [(shift left)]
16740 (lambda () (interactive)
16741 (org-eval-in-calendar '(calendar-backward-day 1))))
16742 (org-defkey map [(shift right)]
16743 (lambda () (interactive)
16744 (org-eval-in-calendar '(calendar-forward-day 1))))
16745 (org-defkey map "!"
16746 (lambda () (interactive)
16747 (org-eval-in-calendar '(diary-view-entries))
16748 (message "")))
16749 (org-defkey map ">"
16750 (lambda () (interactive)
16751 (org-eval-in-calendar '(calendar-scroll-left 1))))
16752 (org-defkey map "<"
16753 (lambda () (interactive)
16754 (org-eval-in-calendar '(calendar-scroll-right 1))))
16755 (org-defkey map "\C-v"
16756 (lambda () (interactive)
16757 (org-eval-in-calendar
16758 '(calendar-scroll-left-three-months 1))))
16759 (org-defkey map "\M-v"
16760 (lambda () (interactive)
16761 (org-eval-in-calendar
16762 '(calendar-scroll-right-three-months 1))))
16763 map)
16764 "Keymap for minibuffer commands when using `org-read-date'.")
16766 (defvar org-def)
16767 (defvar org-defdecode)
16768 (defvar org-with-time)
16770 (defvar calendar-setup) ; Dynamically scoped.
16771 (defun org-read-date (&optional with-time to-time from-string prompt
16772 default-time default-input inactive)
16773 "Read a date, possibly a time, and make things smooth for the user.
16774 The prompt will suggest to enter an ISO date, but you can also enter anything
16775 which will at least partially be understood by `parse-time-string'.
16776 Unrecognized parts of the date will default to the current day, month, year,
16777 hour and minute. If this command is called to replace a timestamp at point,
16778 or to enter the second timestamp of a range, the default time is taken
16779 from the existing stamp. Furthermore, the command prefers the future,
16780 so if you are giving a date where the year is not given, and the day-month
16781 combination is already past in the current year, it will assume you
16782 mean next year. For details, see the manual. A few examples:
16784 3-2-5 --> 2003-02-05
16785 feb 15 --> currentyear-02-15
16786 2/15 --> currentyear-02-15
16787 sep 12 9 --> 2009-09-12
16788 12:45 --> today 12:45
16789 22 sept 0:34 --> currentyear-09-22 0:34
16790 12 --> currentyear-currentmonth-12
16791 Fri --> nearest Friday after today
16792 -Tue --> last Tuesday
16793 etc.
16795 Furthermore you can specify a relative date by giving, as the *first* thing
16796 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16797 change in days weeks, months, years.
16798 With a single plus or minus, the date is relative to today. With a double
16799 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16800 +4d --> four days from today
16801 +4 --> same as above
16802 +2w --> two weeks from today
16803 ++5 --> five days from default date
16805 The function understands only English month and weekday abbreviations.
16807 While prompting, a calendar is popped up - you can also select the
16808 date with the mouse (button 1). The calendar shows a period of three
16809 months. To scroll it to other months, use the keys `>' and `<'.
16810 If you don't like the calendar, turn it off with
16811 (setq org-read-date-popup-calendar nil)
16813 With optional argument TO-TIME, the date will immediately be converted
16814 to an internal time.
16815 With an optional argument WITH-TIME, the prompt will suggest to
16816 also insert a time. Note that when WITH-TIME is not set, you can
16817 still enter a time, and this function will inform the calling routine
16818 about this change. The calling routine may then choose to change the
16819 format used to insert the time stamp into the buffer to include the time.
16820 With optional argument FROM-STRING, read from this string instead from
16821 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16822 the time/date that is used for everything that is not specified by the
16823 user."
16824 (require 'parse-time)
16825 (let* ((org-with-time with-time)
16826 (org-time-stamp-rounding-minutes
16827 (if (equal org-with-time '(16))
16828 '(0 0)
16829 org-time-stamp-rounding-minutes))
16830 (org-dcst org-display-custom-times)
16831 (ct (org-current-time))
16832 (org-def (or org-overriding-default-time default-time ct))
16833 (org-defdecode (decode-time org-def))
16834 (cur-frame (selected-frame))
16835 (mouse-autoselect-window nil) ; Don't let the mouse jump
16836 (calendar-setup
16837 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16838 (calendar-move-hook nil)
16839 (calendar-view-diary-initially-flag nil)
16840 (calendar-view-holidays-initially-flag nil)
16841 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16842 ;; Rationalize `org-def' and `org-defdecode', if required.
16843 (when (< (nth 2 org-defdecode) org-extend-today-until)
16844 (setf (nth 2 org-defdecode) -1)
16845 (setf (nth 1 org-defdecode) 59)
16846 (setq org-def (apply #'encode-time org-defdecode))
16847 (setq org-defdecode (decode-time org-def)))
16848 (let* ((timestr (format-time-string
16849 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16850 org-def))
16851 (prompt (concat (if prompt (concat prompt " ") "")
16852 (format "Date+time [%s]: " timestr))))
16853 (cond
16854 (from-string (setq ans from-string))
16855 (org-read-date-popup-calendar
16856 (save-excursion
16857 (save-window-excursion
16858 (calendar)
16859 (when (eq calendar-setup 'calendar-only)
16860 (setq cal-frame
16861 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16862 (select-frame cal-frame))
16863 (org-eval-in-calendar '(setq cursor-type nil) t)
16864 (unwind-protect
16865 (progn
16866 (calendar-forward-day (- (time-to-days org-def)
16867 (calendar-absolute-from-gregorian
16868 (calendar-current-date))))
16869 (org-eval-in-calendar nil t)
16870 (let* ((old-map (current-local-map))
16871 (map (copy-keymap calendar-mode-map))
16872 (minibuffer-local-map
16873 (copy-keymap org-read-date-minibuffer-local-map)))
16874 (org-defkey map (kbd "RET") 'org-calendar-select)
16875 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16876 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16877 (unwind-protect
16878 (progn
16879 (use-local-map map)
16880 (setq org-read-date-inactive inactive)
16881 (add-hook 'post-command-hook 'org-read-date-display)
16882 (setq org-ans0
16883 (read-string prompt
16884 default-input
16885 'org-read-date-history
16886 nil))
16887 ;; org-ans0: from prompt
16888 ;; org-ans1: from mouse click
16889 ;; org-ans2: from calendar motion
16890 (setq ans
16891 (concat org-ans0 " " (or org-ans1 org-ans2))))
16892 (remove-hook 'post-command-hook 'org-read-date-display)
16893 (use-local-map old-map)
16894 (when org-read-date-overlay
16895 (delete-overlay org-read-date-overlay)
16896 (setq org-read-date-overlay nil)))))
16897 (bury-buffer "*Calendar*")
16898 (when cal-frame
16899 (delete-frame cal-frame)
16900 (select-frame-set-input-focus cur-frame))))))
16902 (t ; Naked prompt only
16903 (unwind-protect
16904 (setq ans (read-string prompt default-input
16905 'org-read-date-history timestr))
16906 (when org-read-date-overlay
16907 (delete-overlay org-read-date-overlay)
16908 (setq org-read-date-overlay nil))))))
16910 (setq final (org-read-date-analyze ans org-def org-defdecode))
16912 (when org-read-date-analyze-forced-year
16913 (message "Year was forced into %s"
16914 (if org-read-date-force-compatible-dates
16915 "compatible range (1970-2037)"
16916 "range representable on this machine"))
16917 (ding))
16919 ;; One round trip to get rid of 34th of August and stuff like that....
16920 (setq final (decode-time (apply 'encode-time final)))
16922 (setq org-read-date-final-answer ans)
16924 (if to-time
16925 (apply 'encode-time final)
16926 (if (and (boundp 'org-time-was-given) org-time-was-given)
16927 (format "%04d-%02d-%02d %02d:%02d"
16928 (nth 5 final) (nth 4 final) (nth 3 final)
16929 (nth 2 final) (nth 1 final))
16930 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16932 (defun org-read-date-display ()
16933 "Display the current date prompt interpretation in the minibuffer."
16934 (when org-read-date-display-live
16935 (when org-read-date-overlay
16936 (delete-overlay org-read-date-overlay))
16937 (when (minibufferp (current-buffer))
16938 (save-excursion
16939 (end-of-line 1)
16940 (while (not (equal (buffer-substring
16941 (max (point-min) (- (point) 4)) (point))
16942 " "))
16943 (insert " ")))
16944 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16945 " " (or org-ans1 org-ans2)))
16946 (org-end-time-was-given nil)
16947 (f (org-read-date-analyze ans org-def org-defdecode))
16948 (fmts (if org-dcst
16949 org-time-stamp-custom-formats
16950 org-time-stamp-formats))
16951 (fmt (if (or org-with-time
16952 (and (boundp 'org-time-was-given) org-time-was-given))
16953 (cdr fmts)
16954 (car fmts)))
16955 (txt (format-time-string fmt (apply 'encode-time f)))
16956 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16957 (txt (concat "=> " txt)))
16958 (when (and org-end-time-was-given
16959 (string-match org-plain-time-of-day-regexp txt))
16960 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16961 org-end-time-was-given
16962 (substring txt (match-end 0)))))
16963 (when org-read-date-analyze-futurep
16964 (setq txt (concat txt " (=>F)")))
16965 (setq org-read-date-overlay
16966 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16967 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16969 (defun org-read-date-analyze (ans def defdecode)
16970 "Analyze the combined answer of the date prompt."
16971 ;; FIXME: cleanup and comment
16972 ;; Pass `current-time' result to `decode-time' (instead of calling
16973 ;; without arguments) so that only `current-time' has to be
16974 ;; overridden in tests.
16975 (let ((org-def def)
16976 (org-defdecode defdecode)
16977 (nowdecode (decode-time (current-time)))
16978 delta deltan deltaw deltadef year month day
16979 hour minute second wday pm h2 m2 tl wday1
16980 iso-year iso-weekday iso-week iso-date futurep kill-year)
16981 (setq org-read-date-analyze-futurep nil
16982 org-read-date-analyze-forced-year nil)
16983 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16984 (setq ans "+0"))
16986 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16987 (setq ans (replace-match "" t t ans)
16988 deltan (car delta)
16989 deltaw (nth 1 delta)
16990 deltadef (nth 2 delta)))
16992 ;; Check if there is an iso week date in there. If yes, store the
16993 ;; info and postpone interpreting it until the rest of the parsing
16994 ;; is done.
16995 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16996 (setq iso-year (when (match-end 1)
16997 (org-small-year-to-year
16998 (string-to-number (match-string 1 ans))))
16999 iso-weekday (when (match-end 3)
17000 (string-to-number (match-string 3 ans)))
17001 iso-week (string-to-number (match-string 2 ans)))
17002 (setq ans (replace-match "" t t ans)))
17004 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17005 (when (string-match
17006 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17007 (setq year (if (match-end 2)
17008 (string-to-number (match-string 2 ans))
17009 (progn (setq kill-year t)
17010 (string-to-number (format-time-string "%Y"))))
17011 month (string-to-number (match-string 3 ans))
17012 day (string-to-number (match-string 4 ans)))
17013 (setq year (org-small-year-to-year year))
17014 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17015 t nil ans)))
17017 ;; Help matching dotted european dates
17018 (when (string-match
17019 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17020 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17021 (setq kill-year t)
17022 (string-to-number (format-time-string "%Y")))
17023 day (string-to-number (match-string 1 ans))
17024 month (string-to-number (match-string 2 ans))
17025 ans (replace-match (format "%04d-%02d-%02d" year month day)
17026 t nil ans)))
17028 ;; Help matching american dates, like 5/30 or 5/30/7
17029 (when (string-match
17030 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17031 (setq year (if (match-end 4)
17032 (string-to-number (match-string 4 ans))
17033 (progn (setq kill-year t)
17034 (string-to-number (format-time-string "%Y"))))
17035 month (string-to-number (match-string 1 ans))
17036 day (string-to-number (match-string 2 ans)))
17037 (setq year (org-small-year-to-year year))
17038 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17039 t nil ans)))
17040 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17041 ;; If there is a time with am/pm, and *no* time without it, we convert
17042 ;; so that matching will be successful.
17043 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17044 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17045 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17046 (setq hour (string-to-number (match-string 1 ans))
17047 minute (if (match-end 3)
17048 (string-to-number (match-string 3 ans))
17050 pm (equal ?p
17051 (string-to-char (downcase (match-string 4 ans)))))
17052 (if (and (= hour 12) (not pm))
17053 (setq hour 0)
17054 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17055 (setq ans (replace-match (format "%02d:%02d" hour minute)
17056 t t ans))))
17058 ;; Check if a time range is given as a duration
17059 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17060 (setq hour (string-to-number (match-string 1 ans))
17061 h2 (+ hour (string-to-number (match-string 3 ans)))
17062 minute (string-to-number (match-string 2 ans))
17063 m2 (+ minute (if (match-end 5) (string-to-number
17064 (match-string 5 ans))0)))
17065 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17066 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17067 t t ans)))
17069 ;; Check if there is a time range
17070 (when (boundp 'org-end-time-was-given)
17071 (setq org-time-was-given nil)
17072 (when (and (string-match org-plain-time-of-day-regexp ans)
17073 (match-end 8))
17074 (setq org-end-time-was-given (match-string 8 ans))
17075 (setq ans (concat (substring ans 0 (match-beginning 7))
17076 (substring ans (match-end 7))))))
17078 (setq tl (parse-time-string ans)
17079 day (or (nth 3 tl) (nth 3 org-defdecode))
17080 month
17081 (cond ((nth 4 tl))
17082 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17083 ;; Day was specified. Make sure DAY+MONTH
17084 ;; combination happens in the future.
17085 ((nth 3 tl)
17086 (setq futurep t)
17087 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17088 (nth 4 nowdecode)))
17089 (t (nth 4 org-defdecode)))
17090 year
17091 (cond ((and (not kill-year) (nth 5 tl)))
17092 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17093 ;; Month was guessed in the future and is at least
17094 ;; equal to NOWDECODE's. Fix year accordingly.
17095 (futurep
17096 (if (or (> month (nth 4 nowdecode))
17097 (>= day (nth 3 nowdecode)))
17098 (nth 5 nowdecode)
17099 (1+ (nth 5 nowdecode))))
17100 ;; Month was specified. Make sure MONTH+YEAR
17101 ;; combination happens in the future.
17102 ((nth 4 tl)
17103 (setq futurep t)
17104 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17105 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17106 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17107 (t (nth 5 nowdecode))))
17108 (t (nth 5 org-defdecode)))
17109 hour (or (nth 2 tl) (nth 2 org-defdecode))
17110 minute (or (nth 1 tl) (nth 1 org-defdecode))
17111 second (or (nth 0 tl) 0)
17112 wday (nth 6 tl))
17114 (when (and (eq org-read-date-prefer-future 'time)
17115 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17116 (equal day (nth 3 nowdecode))
17117 (equal month (nth 4 nowdecode))
17118 (equal year (nth 5 nowdecode))
17119 (nth 2 tl)
17120 (or (< (nth 2 tl) (nth 2 nowdecode))
17121 (and (= (nth 2 tl) (nth 2 nowdecode))
17122 (nth 1 tl)
17123 (< (nth 1 tl) (nth 1 nowdecode)))))
17124 (setq day (1+ day)
17125 futurep t))
17127 ;; Special date definitions below
17128 (cond
17129 (iso-week
17130 ;; There was an iso week
17131 (require 'cal-iso)
17132 (setq futurep nil)
17133 (setq year (or iso-year year)
17134 day (or iso-weekday wday 1)
17135 wday nil ; to make sure that the trigger below does not match
17136 iso-date (calendar-gregorian-from-absolute
17137 (calendar-iso-to-absolute
17138 (list iso-week day year))))
17139 ; FIXME: Should we also push ISO weeks into the future?
17140 ; (when (and org-read-date-prefer-future
17141 ; (not iso-year)
17142 ; (< (calendar-absolute-from-gregorian iso-date)
17143 ; (time-to-days (current-time))))
17144 ; (setq year (1+ year)
17145 ; iso-date (calendar-gregorian-from-absolute
17146 ; (calendar-iso-to-absolute
17147 ; (list iso-week day year)))))
17148 (setq month (car iso-date)
17149 year (nth 2 iso-date)
17150 day (nth 1 iso-date)))
17151 (deltan
17152 (setq futurep nil)
17153 (unless deltadef
17154 ;; Pass `current-time' result to `decode-time' (instead of
17155 ;; calling without arguments) so that only `current-time' has
17156 ;; to be overridden in tests.
17157 (let ((now (decode-time (current-time))))
17158 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17159 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17160 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17161 ((equal deltaw "m") (setq month (+ month deltan)))
17162 ((equal deltaw "y") (setq year (+ year deltan)))))
17163 ((and wday (not (nth 3 tl)))
17164 ;; Weekday was given, but no day, so pick that day in the week
17165 ;; on or after the derived date.
17166 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17167 (unless (equal wday wday1)
17168 (setq day (+ day (% (- wday wday1 -7) 7))))))
17169 (when (and (boundp 'org-time-was-given)
17170 (nth 2 tl))
17171 (setq org-time-was-given t))
17172 (when (< year 100) (setq year (+ 2000 year)))
17173 ;; Check of the date is representable
17174 (if org-read-date-force-compatible-dates
17175 (progn
17176 (when (< year 1970)
17177 (setq year 1970 org-read-date-analyze-forced-year t))
17178 (when (> year 2037)
17179 (setq year 2037 org-read-date-analyze-forced-year t)))
17180 (condition-case nil
17181 (ignore (encode-time second minute hour day month year))
17182 (error
17183 (setq year (nth 5 org-defdecode))
17184 (setq org-read-date-analyze-forced-year t))))
17185 (setq org-read-date-analyze-futurep futurep)
17186 (list second minute hour day month year)))
17188 (defvar parse-time-weekdays)
17189 (defun org-read-date-get-relative (s today default)
17190 "Check string S for special relative date string.
17191 TODAY and DEFAULT are internal times, for today and for a default.
17192 Return shift list (N what def-flag)
17193 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17194 N is the number of WHATs to shift.
17195 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17196 the DEFAULT date rather than TODAY."
17197 (require 'parse-time)
17198 (when (and
17199 (string-match
17200 (concat
17201 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17202 "\\([0-9]+\\)?"
17203 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17204 "\\([ \t]\\|$\\)") s)
17205 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17206 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17207 (string-to-char (substring (match-string 1 s) -1))
17208 ?+))
17209 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17210 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17211 (what (if (match-end 3) (match-string 3 s) "d"))
17212 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17213 (date (if rel default today))
17214 (wday (nth 6 (decode-time date)))
17215 delta)
17216 (if wday1
17217 (progn
17218 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17219 (when (= delta 0) (setq delta 7))
17220 (when (= dir ?-)
17221 (setq delta (- delta 7))
17222 (when (= delta 0) (setq delta -7)))
17223 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17224 (list delta "d" rel))
17225 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17227 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17228 "Turn a user-specified date into the internal representation.
17229 The internal representation needed by the calendar is (month day year).
17230 This is a wrapper to handle the brain-dead convention in calendar that
17231 user function argument order change dependent on argument order."
17232 (pcase calendar-date-style
17233 (`american (list arg1 arg2 arg3))
17234 (`european (list arg2 arg1 arg3))
17235 (`iso (list arg2 arg3 arg1))))
17237 (defun org-eval-in-calendar (form &optional keepdate)
17238 "Eval FORM in the calendar window and return to current window.
17239 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17240 (let ((sf (selected-frame))
17241 (sw (selected-window)))
17242 (select-window (get-buffer-window "*Calendar*" t))
17243 (eval form)
17244 (when (and (not keepdate) (calendar-cursor-to-date))
17245 (let* ((date (calendar-cursor-to-date))
17246 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17247 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17248 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17249 (select-window sw)
17250 (select-frame-set-input-focus sf)))
17252 (defun org-calendar-select ()
17253 "Return to `org-read-date' with the date currently selected.
17254 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17255 (interactive)
17256 (when (calendar-cursor-to-date)
17257 (let* ((date (calendar-cursor-to-date))
17258 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17259 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17260 (when (active-minibuffer-window) (exit-minibuffer))))
17262 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17263 "Insert a date stamp for the date given by the internal TIME.
17264 See `format-time-string' for the format of TIME.
17265 WITH-HM means use the stamp format that includes the time of the day.
17266 INACTIVE means use square brackets instead of angular ones, so that the
17267 stamp will not contribute to the agenda.
17268 PRE and POST are optional strings to be inserted before and after the
17269 stamp.
17270 The command returns the inserted time stamp."
17271 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17272 stamp)
17273 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17274 (insert-before-markers (or pre ""))
17275 (when (listp extra)
17276 (setq extra (car extra))
17277 (if (and (stringp extra)
17278 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17279 (setq extra (format "-%02d:%02d"
17280 (string-to-number (match-string 1 extra))
17281 (string-to-number (match-string 2 extra))))
17282 (setq extra nil)))
17283 (when extra
17284 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17285 (insert-before-markers (setq stamp (format-time-string fmt time)))
17286 (insert-before-markers (or post ""))
17287 (setq org-last-inserted-timestamp stamp)))
17289 (defun org-toggle-time-stamp-overlays ()
17290 "Toggle the use of custom time stamp formats."
17291 (interactive)
17292 (setq org-display-custom-times (not org-display-custom-times))
17293 (unless org-display-custom-times
17294 (let ((p (point-min)) (bmp (buffer-modified-p)))
17295 (while (setq p (next-single-property-change p 'display))
17296 (when (and (get-text-property p 'display)
17297 (eq (get-text-property p 'face) 'org-date))
17298 (remove-text-properties
17299 p (setq p (next-single-property-change p 'display))
17300 '(display t))))
17301 (set-buffer-modified-p bmp)))
17302 (org-restart-font-lock)
17303 (setq org-table-may-need-update t)
17304 (if org-display-custom-times
17305 (message "Time stamps are overlaid with custom format")
17306 (message "Time stamp overlays removed")))
17308 (defun org-display-custom-time (beg end)
17309 "Overlay modified time stamp format over timestamp between BEG and END."
17310 (let* ((ts (buffer-substring beg end))
17311 t1 with-hm tf time str (off 0))
17312 (save-match-data
17313 (setq t1 (org-parse-time-string ts t))
17314 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17315 (setq off (- (match-end 0) (match-beginning 0)))))
17316 (setq end (- end off))
17317 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17318 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17319 time (org-fix-decoded-time t1)
17320 str (org-add-props
17321 (format-time-string
17322 (substring tf 1 -1) (apply 'encode-time time))
17323 nil 'mouse-face 'highlight))
17324 (put-text-property beg end 'display str)))
17326 (defun org-fix-decoded-time (time)
17327 "Set 0 instead of nil for the first 6 elements of time.
17328 Don't touch the rest."
17329 (let ((n 0))
17330 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17332 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17333 "Difference between TIMESTAMP-STRING and now in days.
17334 If SECONDS is non-nil, return the difference in seconds."
17335 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17336 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17337 (funcall fdiff (current-time)))))
17339 (defun org-deadline-close-p (timestamp-string &optional ndays)
17340 "Is the time in TIMESTAMP-STRING close to the current date?"
17341 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17342 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17343 (not (org-entry-is-done-p))))
17345 (defun org-get-wdays (ts &optional delay zero-delay)
17346 "Get the deadline lead time appropriate for timestring TS.
17347 When DELAY is non-nil, get the delay time for scheduled items
17348 instead of the deadline lead time. When ZERO-DELAY is non-nil
17349 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17350 don't try to find the delay cookie in the scheduled timestamp."
17351 (let ((tv (if delay org-scheduled-delay-days
17352 org-deadline-warning-days)))
17353 (cond
17354 ((or (and delay (< tv 0))
17355 (and delay zero-delay (<= tv 0))
17356 (and (not delay) (<= tv 0)))
17357 ;; Enforce this value no matter what
17358 (- tv))
17359 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17360 ;; lead time is specified.
17361 (floor (* (string-to-number (match-string 1 ts))
17362 (cdr (assoc (match-string 2 ts)
17363 '(("d" . 1) ("w" . 7)
17364 ("m" . 30.4) ("y" . 365.25)
17365 ("h" . 0.041667)))))))
17366 ;; go for the default.
17367 (t tv))))
17369 (defun org-calendar-select-mouse (ev)
17370 "Return to `org-read-date' with the date currently selected.
17371 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17372 (interactive "e")
17373 (mouse-set-point ev)
17374 (when (calendar-cursor-to-date)
17375 (let* ((date (calendar-cursor-to-date))
17376 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17377 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17378 (when (active-minibuffer-window) (exit-minibuffer))))
17380 (defun org-check-deadlines (ndays)
17381 "Check if there are any deadlines due or past due.
17382 A deadline is considered due if it happens within `org-deadline-warning-days'
17383 days from today's date. If the deadline appears in an entry marked DONE,
17384 it is not shown. A numeric prefix argument NDAYS can be used to test that
17385 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17386 are shown."
17387 (interactive "P")
17388 (let* ((org-warn-days
17389 (cond
17390 ((equal ndays '(4)) 100000)
17391 (ndays (prefix-numeric-value ndays))
17392 (t (abs org-deadline-warning-days))))
17393 (case-fold-search nil)
17394 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17395 (callback
17396 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17397 (message "%d deadlines past-due or due within %d days"
17398 (org-occur regexp nil callback)
17399 org-warn-days)))
17401 (defsubst org-re-timestamp (type)
17402 "Return a regexp for timestamp TYPE.
17403 Allowed values for TYPE are:
17405 all: all timestamps
17406 active: only active timestamps (<...>)
17407 inactive: only inactive timestamps ([...])
17408 scheduled: only scheduled timestamps
17409 deadline: only deadline timestamps
17410 closed: only closed time-stamps
17412 When TYPE is nil, fall back on returning a regexp that matches
17413 both scheduled and deadline timestamps."
17414 (cl-case type
17415 (all org-ts-regexp-both)
17416 (active org-ts-regexp)
17417 (inactive org-ts-regexp-inactive)
17418 (scheduled org-scheduled-time-regexp)
17419 (deadline org-deadline-time-regexp)
17420 (closed org-closed-time-regexp)
17421 (otherwise
17422 (concat "\\<"
17423 (regexp-opt (list org-deadline-string org-scheduled-string))
17424 " *<\\([^>]+\\)>"))))
17426 (defun org-check-before-date (d)
17427 "Check if there are deadlines or scheduled entries before date D."
17428 (interactive (list (org-read-date)))
17429 (let* ((case-fold-search nil)
17430 (regexp (org-re-timestamp org-ts-type))
17431 (ts-type org-ts-type)
17432 (callback
17433 (lambda ()
17434 (let ((match (match-string 1)))
17435 (and (if (memq ts-type '(active inactive all))
17436 (eq (org-element-type (save-excursion
17437 (backward-char)
17438 (org-element-context)))
17439 'timestamp)
17440 (org-at-planning-p))
17441 (time-less-p
17442 (org-time-string-to-time match t)
17443 (org-time-string-to-time d t)))))))
17444 (message "%d entries before %s"
17445 (org-occur regexp nil callback)
17446 d)))
17448 (defun org-check-after-date (d)
17449 "Check if there are deadlines or scheduled entries after date D."
17450 (interactive (list (org-read-date)))
17451 (let* ((case-fold-search nil)
17452 (regexp (org-re-timestamp org-ts-type))
17453 (ts-type org-ts-type)
17454 (callback
17455 (lambda ()
17456 (let ((match (match-string 1)))
17457 (and (if (memq ts-type '(active inactive all))
17458 (eq (org-element-type (save-excursion
17459 (backward-char)
17460 (org-element-context)))
17461 'timestamp)
17462 (org-at-planning-p))
17463 (not (time-less-p
17464 (org-time-string-to-time match t)
17465 (org-time-string-to-time d t))))))))
17466 (message "%d entries after %s"
17467 (org-occur regexp nil callback)
17468 d)))
17470 (defun org-check-dates-range (start-date end-date)
17471 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17472 (interactive (list (org-read-date nil nil nil "Range starts")
17473 (org-read-date nil nil nil "Range end")))
17474 (let ((case-fold-search nil)
17475 (regexp (org-re-timestamp org-ts-type))
17476 (callback
17477 (let ((type org-ts-type))
17478 (lambda ()
17479 (let ((match (match-string 1)))
17480 (and
17481 (if (memq type '(active inactive all))
17482 (eq (org-element-type (save-excursion
17483 (backward-char)
17484 (org-element-context)))
17485 'timestamp)
17486 (org-at-planning-p))
17487 (not (time-less-p
17488 (org-time-string-to-time match t)
17489 (org-time-string-to-time start-date t)))
17490 (time-less-p
17491 (org-time-string-to-time match t)
17492 (org-time-string-to-time end-date t))))))))
17493 (message "%d entries between %s and %s"
17494 (org-occur regexp nil callback) start-date end-date)))
17496 (defun org-evaluate-time-range (&optional to-buffer)
17497 "Evaluate a time range by computing the difference between start and end.
17498 Normally the result is just printed in the echo area, but with prefix arg
17499 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17500 If the time range is actually in a table, the result is inserted into the
17501 next column.
17502 For time difference computation, a year is assumed to be exactly 365
17503 days in order to avoid rounding problems."
17504 (interactive "P")
17506 (org-clock-update-time-maybe)
17507 (save-excursion
17508 (unless (org-at-date-range-p t)
17509 (goto-char (point-at-bol))
17510 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17511 (unless (org-at-date-range-p t)
17512 (user-error "Not at a time-stamp range, and none found in current line")))
17513 (let* ((ts1 (match-string 1))
17514 (ts2 (match-string 2))
17515 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17516 (match-end (match-end 0))
17517 (time1 (org-time-string-to-time ts1))
17518 (time2 (org-time-string-to-time ts2))
17519 (t1 (float-time time1))
17520 (t2 (float-time time2))
17521 (diff (abs (- t2 t1)))
17522 (negative (< (- t2 t1) 0))
17523 ;; (ys (floor (* 365 24 60 60)))
17524 (ds (* 24 60 60))
17525 (hs (* 60 60))
17526 (fy "%dy %dd %02d:%02d")
17527 (fy1 "%dy %dd")
17528 (fd "%dd %02d:%02d")
17529 (fd1 "%dd")
17530 (fh "%02d:%02d")
17531 y d h m align)
17532 (if havetime
17533 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17535 d (floor (/ diff ds)) diff (mod diff ds)
17536 h (floor (/ diff hs)) diff (mod diff hs)
17537 m (floor (/ diff 60)))
17538 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17540 d (floor (+ (/ diff ds) 0.5))
17541 h 0 m 0))
17542 (if (not to-buffer)
17543 (message "%s" (org-make-tdiff-string y d h m))
17544 (if (org-at-table-p)
17545 (progn
17546 (goto-char match-end)
17547 (setq align t)
17548 (and (looking-at " *|") (goto-char (match-end 0))))
17549 (goto-char match-end))
17550 (when (looking-at
17551 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17552 (replace-match ""))
17553 (when negative (insert " -"))
17554 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17555 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17556 (insert " " (format fh h m))))
17557 (when align (org-table-align))
17558 (message "Time difference inserted")))))
17560 (defun org-make-tdiff-string (y d h m)
17561 (let ((fmt "")
17562 (l nil))
17563 (when (> y 0)
17564 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17565 (push y l))
17566 (when (> d 0)
17567 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17568 (push d l))
17569 (when (> h 0)
17570 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17571 (push h l))
17572 (when (> m 0)
17573 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17574 (push m l))
17575 (apply 'format fmt (nreverse l))))
17577 (defun org-time-string-to-time (s &optional zone)
17578 "Convert timestamp string S into internal time.
17579 The optional ZONE is omitted or nil for Emacs local time, t for
17580 Universal Time, ‘wall’ for system wall clock time, or a string as
17581 in the TZ environment variable."
17582 (apply #'encode-time (org-parse-time-string s nil zone)))
17584 (defun org-time-string-to-seconds (s &optional zone)
17585 "Convert a timestamp string S into a number of seconds.
17586 The optional ZONE is omitted or nil for Emacs local time, t for
17587 Universal Time, ‘wall’ for system wall clock time, or a string as
17588 in the TZ environment variable."
17589 (float-time (org-time-string-to-time s zone)))
17591 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17593 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17594 "Convert time stamp S to an absolute day number.
17596 If DAYNR in non-nil, and there is a specifier for a cyclic time
17597 stamp, get the closest date to DAYNR. If PREFER is
17598 `past' (respectively `future') return a date past (respectively
17599 after) or equal to DAYNR.
17601 POS is the location of time stamp S, as a buffer position in
17602 BUFFER.
17604 Diary sexp timestamps are matched against DAYNR, when non-nil.
17605 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17606 signaled."
17607 (cond
17608 ((string-match "\\`%%\\((.*)\\)" s)
17609 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17610 ;; only able to match individual dates. If it fails, raise an
17611 ;; error.
17612 (if (and daynr
17613 (org-diary-sexp-entry
17614 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17615 daynr
17616 (signal 'org-diary-sexp-no-match (list s))))
17617 (daynr (org-closest-date s daynr prefer))
17618 (t (time-to-days
17619 (condition-case errdata
17620 (apply #'encode-time (org-parse-time-string s))
17621 (error (error "Bad timestamp `%s'%s\nError was: %s"
17623 (if (not (and buffer pos)) ""
17624 (format-message " at %d in buffer `%s'" pos buffer))
17625 (cdr errdata))))))))
17627 (defun org-days-to-iso-week (days)
17628 "Return the iso week number."
17629 (require 'cal-iso)
17630 (car (calendar-iso-from-absolute days)))
17632 (defun org-small-year-to-year (year)
17633 "Convert 2-digit years into 4-digit years.
17634 YEAR is expanded into one of the 30 next years, if possible, or
17635 into a past one. Any year larger than 99 is returned unchanged."
17636 (if (>= year 100) year
17637 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17638 (century (/ current 100))
17639 (offset (- year (% current 100))))
17640 (cond ((> offset 30) (+ (* (1- century) 100) year))
17641 ((> offset -70) (+ (* century 100) year))
17642 (t (+ (* (1+ century) 100) year))))))
17644 (defun org-time-from-absolute (d)
17645 "Return the time corresponding to date D.
17646 D may be an absolute day number, or a calendar-type list (month day year)."
17647 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17648 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17650 (defvar org-agenda-current-date)
17651 (defun org-calendar-holiday ()
17652 "List of holidays, for Diary display in Org mode."
17653 (require 'holidays)
17654 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17655 (and hl (mapconcat #'identity hl "; "))))
17657 (defun org-diary-sexp-entry (sexp entry d)
17658 "Process a SEXP diary ENTRY for date D."
17659 (require 'diary-lib)
17660 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17661 ;; dynamically.
17662 (let* ((sexp `(let ((entry ,entry)
17663 (date ',d))
17664 ,(car (read-from-string sexp))))
17665 (result (if calendar-debug-sexp (eval sexp)
17666 (condition-case nil
17667 (eval sexp)
17668 (error
17669 (beep)
17670 (message "Bad sexp at line %d in %s: %s"
17671 (org-current-line)
17672 (buffer-file-name) sexp)
17673 (sleep-for 2))))))
17674 (cond ((stringp result) (split-string result "; "))
17675 ((and (consp result)
17676 (not (consp (cdr result)))
17677 (stringp (cdr result))) (cdr result))
17678 ((and (consp result)
17679 (stringp (car result))) result)
17680 (result entry))))
17682 (defun org-diary-to-ical-string (frombuf)
17683 "Get iCalendar entries from diary entries in buffer FROMBUF.
17684 This uses the icalendar.el library."
17685 (let* ((tmpdir temporary-file-directory)
17686 (tmpfile (make-temp-name
17687 (expand-file-name "orgics" tmpdir)))
17688 buf rtn b e)
17689 (with-current-buffer frombuf
17690 (icalendar-export-region (point-min) (point-max) tmpfile)
17691 (setq buf (find-buffer-visiting tmpfile))
17692 (set-buffer buf)
17693 (goto-char (point-min))
17694 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17695 (setq b (match-beginning 0)))
17696 (goto-char (point-max))
17697 (when (re-search-backward "^END:VEVENT" nil t)
17698 (setq e (match-end 0)))
17699 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17700 (kill-buffer buf)
17701 (delete-file tmpfile)
17702 rtn))
17704 (defun org-closest-date (start current prefer)
17705 "Return closest date to CURRENT starting from START.
17707 CURRENT and START are both time stamps.
17709 When PREFER is `past', return a date that is either CURRENT or
17710 past. When PREFER is `future', return a date that is either
17711 CURRENT or future.
17713 Only time stamps with a repeater are modified. Any other time
17714 stamp stay unchanged. In any case, return value is an absolute
17715 day number."
17716 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17717 ;; No repeater. Do not shift time stamp.
17718 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17719 (let ((value (string-to-number (match-string 1 start)))
17720 (type (match-string 2 start)))
17721 (if (= 0 value)
17722 ;; Repeater with a 0-value is considered as void.
17723 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17724 (let* ((base (org-date-to-gregorian start))
17725 (target (org-date-to-gregorian current))
17726 (sday (calendar-absolute-from-gregorian base))
17727 (cday (calendar-absolute-from-gregorian target))
17728 n1 n2)
17729 ;; If START is already past CURRENT, just return START.
17730 (if (<= cday sday) sday
17731 ;; Compute closest date before (N1) and closest date past
17732 ;; (N2) CURRENT.
17733 (pcase type
17734 ("h"
17735 (let ((missing-hours
17736 (mod (+ (- (* 24 (- cday sday))
17737 (nth 2 (org-parse-time-string start)))
17738 org-extend-today-until)
17739 value)))
17740 (setf n1 (if (= missing-hours 0) cday
17741 (- cday (1+ (/ missing-hours 24)))))
17742 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17743 ((or "d" "w")
17744 (let ((value (if (equal type "w") (* 7 value) value)))
17745 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17746 (setf n2 (+ n1 value))))
17747 ("m"
17748 (let* ((add-months
17749 (lambda (d n)
17750 ;; Add N months to gregorian date D, i.e.,
17751 ;; a list (MONTH DAY YEAR). Return a valid
17752 ;; gregorian date.
17753 (let ((m (+ (nth 0 d) n)))
17754 (list (mod m 12)
17755 (nth 1 d)
17756 (+ (/ m 12) (nth 2 d))))))
17757 (months ; Complete months to TARGET.
17758 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17759 (- (nth 0 target) (nth 0 base))
17760 ;; If START's day is greater than
17761 ;; TARGET's, remove incomplete month.
17762 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17763 value)
17764 value))
17765 (before (funcall add-months base months)))
17766 (setf n1 (calendar-absolute-from-gregorian before))
17767 (setf n2
17768 (calendar-absolute-from-gregorian
17769 (funcall add-months before value)))))
17771 (let* ((d (nth 1 base))
17772 (m (nth 0 base))
17773 (y (nth 2 base))
17774 (years ; Complete years to TARGET.
17775 (* (/ (- (nth 2 target)
17777 ;; If START's month and day are
17778 ;; greater than TARGET's, remove
17779 ;; incomplete year.
17780 (if (or (> (nth 0 target) m)
17781 (and (= (nth 0 target) m)
17782 (> (nth 1 target) d)))
17785 value)
17786 value))
17787 (before (list m d (+ y years))))
17788 (setf n1 (calendar-absolute-from-gregorian before))
17789 (setf n2 (calendar-absolute-from-gregorian
17790 (list m d (+ (nth 2 before) value)))))))
17791 ;; Handle PREFER parameter, if any.
17792 (cond
17793 ((eq prefer 'past) (if (= cday n2) n2 n1))
17794 ((eq prefer 'future) (if (= cday n1) n1 n2))
17795 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17797 (defun org-date-to-gregorian (d)
17798 "Turn any specification of date D into a Gregorian date for the calendar."
17799 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17800 ((and (listp d) (= (length d) 3)) d)
17801 ((stringp d)
17802 (let ((d (org-parse-time-string d)))
17803 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17804 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17806 (defun org-parse-time-string (s &optional nodefault zone)
17807 "Parse the standard Org time string.
17809 This should be a lot faster than the normal `parse-time-string'.
17811 If time is not given, defaults to 0:00. However, with optional
17812 NODEFAULT, hour and minute fields will be nil if not given.
17814 The optional ZONE is omitted or nil for Emacs local time, t for
17815 Universal Time, ‘wall’ for system wall clock time, or a string as
17816 in the TZ environment variable."
17817 (cond ((string-match org-ts-regexp0 s)
17818 (list 0
17819 (when (or (match-beginning 8) (not nodefault))
17820 (string-to-number (or (match-string 8 s) "0")))
17821 (when (or (match-beginning 7) (not nodefault))
17822 (string-to-number (or (match-string 7 s) "0")))
17823 (string-to-number (match-string 4 s))
17824 (string-to-number (match-string 3 s))
17825 (string-to-number (match-string 2 s))
17826 nil nil zone))
17827 ((string-match "^<[^>]+>$" s)
17828 ;; FIXME: `decode-time' needs to be called with ZONE as its
17829 ;; second argument. However, this requires at least Emacs
17830 ;; 25.1. We can do it when we switch to this version as our
17831 ;; minimal requirement.
17832 (decode-time (seconds-to-time (org-matcher-time s))))
17833 (t (error "Not a standard Org time string: %s" s))))
17835 (defun org-timestamp-up (&optional arg)
17836 "Increase the date item at the cursor by one.
17837 If the cursor is on the year, change the year. If it is on the month,
17838 the day or the time, change that.
17839 With prefix ARG, change by that many units."
17840 (interactive "p")
17841 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17843 (defun org-timestamp-down (&optional arg)
17844 "Decrease the date item at the cursor by one.
17845 If the cursor is on the year, change the year. If it is on the month,
17846 the day or the time, change that.
17847 With prefix ARG, change by that many units."
17848 (interactive "p")
17849 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17851 (defun org-timestamp-up-day (&optional arg)
17852 "Increase the date in the time stamp by one day.
17853 With prefix ARG, change that many days."
17854 (interactive "p")
17855 (if (and (not (org-at-timestamp-p 'lax))
17856 (org-at-heading-p))
17857 (org-todo 'up)
17858 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17860 (defun org-timestamp-down-day (&optional arg)
17861 "Decrease the date in the time stamp by one day.
17862 With prefix ARG, change that many days."
17863 (interactive "p")
17864 (if (and (not (org-at-timestamp-p 'lax))
17865 (org-at-heading-p))
17866 (org-todo 'down)
17867 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17869 (defun org-at-timestamp-p (&optional extended)
17870 "Non-nil if point is inside a timestamp.
17872 By default, the function only consider syntactically valid active
17873 timestamps. However, the caller may have a broader definition
17874 for timestamps. As a consequence, optional argument EXTENDED can
17875 be set to the following values
17877 `inactive'
17879 Include also syntactically valid inactive timestamps.
17881 `agenda'
17883 Include timestamps allowed in Agenda, i.e., those in
17884 properties drawers, planning lines and clock lines.
17886 `lax'
17888 Ignore context. The function matches any part of the
17889 document looking like a timestamp. This includes comments,
17890 example blocks...
17892 For backward-compatibility with Org 9.0, every other non-nil
17893 value is equivalent to `inactive'.
17895 When at a timestamp, return the position of the point as a symbol
17896 among `bracket', `after', `year', `month', `hour', `minute',
17897 `day' or a number of character from the last know part of the
17898 time stamp.
17900 When matching, the match groups are the following:
17901 group 1: year
17902 group 2: month
17903 group 3: day number
17904 group 4: day name
17905 group 5: hours, if any
17906 group 6: minutes, if any"
17907 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17908 (pos (point))
17909 (match?
17910 (let ((boundaries (org-in-regexp regexp)))
17911 (save-match-data
17912 (cond ((null boundaries) nil)
17913 ((eq extended 'lax) t)
17915 (or (and (eq extended 'agenda)
17916 (or (org-at-planning-p)
17917 (org-at-property-p)
17918 (and (bound-and-true-p
17919 org-agenda-include-inactive-timestamps)
17920 (org-at-clock-log-p))))
17921 (eq 'timestamp
17922 (save-excursion
17923 (when (= pos (cdr boundaries)) (forward-char -1))
17924 (org-element-type (org-element-context)))))))))))
17925 (cond
17926 ((not match?) nil)
17927 ((= pos (match-beginning 0)) 'bracket)
17928 ;; Distinguish location right before the closing bracket from
17929 ;; right after it.
17930 ((= pos (1- (match-end 0))) 'bracket)
17931 ((= pos (match-end 0)) 'after)
17932 ((org-pos-in-match-range pos 2) 'year)
17933 ((org-pos-in-match-range pos 3) 'month)
17934 ((org-pos-in-match-range pos 7) 'hour)
17935 ((org-pos-in-match-range pos 8) 'minute)
17936 ((or (org-pos-in-match-range pos 4)
17937 (org-pos-in-match-range pos 5)) 'day)
17938 ((and (> pos (or (match-end 8) (match-end 5)))
17939 (< pos (match-end 0)))
17940 (- pos (or (match-end 8) (match-end 5))))
17941 (t 'day))))
17943 (defun org-toggle-timestamp-type ()
17944 "Toggle the type (<active> or [inactive]) of a time stamp."
17945 (interactive)
17946 (when (org-at-timestamp-p 'lax)
17947 (let ((beg (match-beginning 0)) (end (match-end 0))
17948 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17949 (save-excursion
17950 (goto-char beg)
17951 (while (re-search-forward "[][<>]" end t)
17952 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17953 t t)))
17954 (message "Timestamp is now %sactive"
17955 (if (equal (char-after beg) ?<) "" "in")))))
17957 (defun org-at-clock-log-p ()
17958 "Non-nil if point is on a clock log line."
17959 (and (org-match-line org-clock-line-re)
17960 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17962 (defvar org-clock-history) ; defined in org-clock.el
17963 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17964 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17965 "Change the date in the time stamp at point.
17966 The date will be changed by N times WHAT. WHAT can be `day', `month',
17967 `year', `minute', `second'. If WHAT is not given, the cursor position
17968 in the timestamp determines what will be changed.
17969 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17970 (let ((origin (point))
17971 (timestamp? (org-at-timestamp-p 'lax))
17972 origin-cat
17973 with-hm inactive
17974 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17975 extra rem
17976 ts time time0 fixnext clrgx)
17977 (unless timestamp? (user-error "Not at a timestamp"))
17978 (if (and (not what) (eq timestamp? 'bracket))
17979 (org-toggle-timestamp-type)
17980 ;; Point isn't on brackets. Remember the part of the time-stamp
17981 ;; the point was in. Indeed, size of time-stamps may change,
17982 ;; but point must be kept in the same category nonetheless.
17983 (setq origin-cat timestamp?)
17984 (when (and (not what) (not (eq timestamp? 'day))
17985 org-display-custom-times
17986 (get-text-property (point) 'display)
17987 (not (get-text-property (1- (point)) 'display)))
17988 (setq timestamp? 'day))
17989 (setq timestamp? (or what timestamp?)
17990 inactive (= (char-after (match-beginning 0)) ?\[)
17991 ts (match-string 0))
17992 (replace-match "")
17993 (when (string-match
17994 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17996 (setq extra (match-string 1 ts))
17997 (when suppress-tmp-delay
17998 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17999 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18000 (setq with-hm t))
18001 (setq time0 (org-parse-time-string ts))
18002 (when (and updown
18003 (eq timestamp? 'minute)
18004 (not current-prefix-arg))
18005 ;; This looks like s-up and s-down. Change by one rounding step.
18006 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18007 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18008 (setcar (cdr time0) (+ (nth 1 time0)
18009 (if (> n 0) (- rem) (- dm rem))))))
18010 (setq time
18011 (apply #'encode-time
18012 (or (car time0) 0)
18013 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
18014 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
18015 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
18016 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
18017 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
18018 (nthcdr 6 time0)))
18019 (when (and (memq timestamp? '(hour minute))
18020 extra
18021 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18022 (setq extra (org-modify-ts-extra
18023 extra
18024 (if (eq timestamp? 'hour) 2 5)
18025 n dm)))
18026 (when (integerp timestamp?)
18027 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
18028 (when (eq what 'calendar)
18029 (let ((cal-date (org-get-date-from-calendar)))
18030 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18031 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18032 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18033 (setcar time0 (or (car time0) 0))
18034 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18035 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18036 (setq time (apply 'encode-time time0))))
18037 ;; Insert the new time-stamp, and ensure point stays in the same
18038 ;; category as before (i.e. not after the last position in that
18039 ;; category).
18040 (let ((pos (point)))
18041 ;; Stay before inserted string. `save-excursion' is of no use.
18042 (setq org-last-changed-timestamp
18043 (org-insert-time-stamp time with-hm inactive nil nil extra))
18044 (goto-char pos))
18045 (save-match-data
18046 (looking-at org-ts-regexp3)
18047 (goto-char
18048 (pcase origin-cat
18049 ;; `day' category ends before `hour' if any, or at the end
18050 ;; of the day name.
18051 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18052 (`hour (min (match-end 7) origin))
18053 (`minute (min (1- (match-end 8)) origin))
18054 ((pred integerp) (min (1- (match-end 0)) origin))
18055 ;; Point was right after the time-stamp. However, the
18056 ;; time-stamp length might have changed, so refer to
18057 ;; (match-end 0) instead.
18058 (`after (match-end 0))
18059 ;; `year' and `month' have both fixed size: point couldn't
18060 ;; have moved into another part.
18061 (_ origin))))
18062 ;; Update clock if on a CLOCK line.
18063 (org-clock-update-time-maybe)
18064 ;; Maybe adjust the closest clock in `org-clock-history'
18065 (when org-clock-adjust-closest
18066 (if (not (and (org-at-clock-log-p)
18067 (< 1 (length (delq nil (mapcar 'marker-position
18068 org-clock-history))))))
18069 (message "No clock to adjust")
18070 (cond ((save-excursion ; fix previous clock?
18071 (re-search-backward org-ts-regexp0 nil t)
18072 (looking-back (concat org-clock-string " \\[")
18073 (line-beginning-position)))
18074 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18075 ((save-excursion ; fix next clock?
18076 (re-search-backward org-ts-regexp0 nil t)
18077 (looking-at (concat org-ts-regexp0 "\\] =>")))
18078 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18079 (save-window-excursion
18080 ;; Find closest clock to point, adjust the previous/next one in history
18081 (let* ((p (save-excursion (org-back-to-heading t)))
18082 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18083 (clfixnth
18084 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18085 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18086 (if (not clfixpos)
18087 (message "No clock to adjust")
18088 (save-excursion
18089 (org-goto-marker-or-bmk clfixpos)
18090 (org-show-subtree)
18091 (when (re-search-forward clrgx nil t)
18092 (goto-char (match-beginning 1))
18093 (let (org-clock-adjust-closest)
18094 (org-timestamp-change n timestamp? updown))
18095 (message "Clock adjusted in %s for heading: %s"
18096 (file-name-nondirectory (buffer-file-name))
18097 (org-get-heading t t)))))))))
18098 ;; Try to recenter the calendar window, if any.
18099 (when (and org-calendar-follow-timestamp-change
18100 (get-buffer-window "*Calendar*" t)
18101 (memq timestamp? '(day month year)))
18102 (org-recenter-calendar (time-to-days time))))))
18104 (defun org-modify-ts-extra (s pos n dm)
18105 "Change the different parts of the lead-time and repeat fields in timestamp."
18106 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18107 ng h m new rem)
18108 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18109 (cond
18110 ((or (org-pos-in-match-range pos 2)
18111 (org-pos-in-match-range pos 3))
18112 (setq m (string-to-number (match-string 3 s))
18113 h (string-to-number (match-string 2 s)))
18114 (if (org-pos-in-match-range pos 2)
18115 (setq h (+ h n))
18116 (setq n (* dm (with-no-warnings (signum n))))
18117 (unless (= 0 (setq rem (% m dm)))
18118 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18119 (setq m (+ m n)))
18120 (when (< m 0) (setq m (+ m 60) h (1- h)))
18121 (when (> m 59) (setq m (- m 60) h (1+ h)))
18122 (setq h (mod h 24))
18123 (setq ng 1 new (format "-%02d:%02d" h m)))
18124 ((org-pos-in-match-range pos 6)
18125 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18126 ((org-pos-in-match-range pos 5)
18127 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18129 ((org-pos-in-match-range pos 9)
18130 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18131 ((org-pos-in-match-range pos 8)
18132 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18134 (when ng
18135 (setq s (concat
18136 (substring s 0 (match-beginning ng))
18138 (substring s (match-end ng))))))
18141 (defun org-recenter-calendar (d)
18142 "If the calendar is visible, recenter it to date D."
18143 (let ((cwin (get-buffer-window "*Calendar*" t)))
18144 (when cwin
18145 (let ((calendar-move-hook nil))
18146 (with-selected-window cwin
18147 (calendar-goto-date
18148 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18150 (defun org-goto-calendar (&optional arg)
18151 "Go to the Emacs calendar at the current date.
18152 If there is a time stamp in the current line, go to that date.
18153 A prefix ARG can be used to force the current date."
18154 (interactive "P")
18155 (let ((calendar-move-hook nil)
18156 (calendar-view-holidays-initially-flag nil)
18157 (calendar-view-diary-initially-flag nil)
18158 diff)
18159 (when (or (org-at-timestamp-p 'lax)
18160 (org-match-line (concat ".*" org-ts-regexp)))
18161 (let ((d1 (time-to-days (current-time)))
18162 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18163 (setq diff (- d2 d1))))
18164 (calendar)
18165 (calendar-goto-today)
18166 (when (and diff (not arg)) (calendar-forward-day diff))))
18168 (defun org-get-date-from-calendar ()
18169 "Return a list (month day year) of date at point in calendar."
18170 (with-current-buffer "*Calendar*"
18171 (save-match-data
18172 (calendar-cursor-to-date))))
18174 (defun org-date-from-calendar ()
18175 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18176 If there is already a time stamp at the cursor position, update it."
18177 (interactive)
18178 (if (org-at-timestamp-p 'lax)
18179 (org-timestamp-change 0 'calendar)
18180 (let ((cal-date (org-get-date-from-calendar)))
18181 (org-insert-time-stamp
18182 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18184 (defcustom org-effort-durations
18185 `(("min" . 1)
18186 ("h" . 60)
18187 ("d" . ,(* 60 8))
18188 ("w" . ,(* 60 8 5))
18189 ("m" . ,(* 60 8 5 4))
18190 ("y" . ,(* 60 8 5 40)))
18191 "Conversion factor to minutes for an effort modifier.
18193 Each entry has the form (MODIFIER . MINUTES).
18195 In an effort string, a number followed by MODIFIER is multiplied
18196 by the specified number of MINUTES to obtain an effort in
18197 minutes.
18199 For example, if the value of this variable is ((\"hours\" . 60)), then an
18200 effort string \"2hours\" is equivalent to 120 minutes."
18201 :group 'org-agenda
18202 :version "26.1"
18203 :package-version '(Org . "8.3")
18204 :type '(alist :key-type (string :tag "Modifier")
18205 :value-type (number :tag "Minutes")))
18207 (defcustom org-image-actual-width t
18208 "Should we use the actual width of images when inlining them?
18210 When set to t, always use the image width.
18212 When set to a number, use imagemagick (when available) to set
18213 the image's width to this value.
18215 When set to a number in a list, try to get the width from any
18216 #+ATTR.* keyword if it matches a width specification like
18218 #+ATTR_HTML: :width 300px
18220 and fall back on that number if none is found.
18222 When set to nil, try to get the width from an #+ATTR.* keyword
18223 and fall back on the original width if none is found.
18225 This requires Emacs >= 24.1, build with imagemagick support."
18226 :group 'org-appearance
18227 :version "24.4"
18228 :package-version '(Org . "8.0")
18229 :type '(choice
18230 (const :tag "Use the image width" t)
18231 (integer :tag "Use a number of pixels")
18232 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18233 (const :tag "Use #+ATTR* or don't resize" nil)))
18235 (defcustom org-agenda-inhibit-startup nil
18236 "Inhibit startup when preparing agenda buffers.
18237 When this variable is t, the initialization of the Org agenda
18238 buffers is inhibited: e.g. the visibility state is not set, the
18239 tables are not re-aligned, etc."
18240 :type 'boolean
18241 :version "24.3"
18242 :group 'org-agenda)
18244 (defcustom org-agenda-ignore-properties nil
18245 "Avoid updating text properties when building the agenda.
18246 Properties are used to prepare buffers for effort estimates,
18247 appointments, statistics and subtree-local categories.
18248 If you don't use these in the agenda, you can add them to this
18249 list and agenda building will be a bit faster.
18250 The value is a list, with zero or more of the symbols `effort', `appt',
18251 `stats' or `category'."
18252 :type '(set :greedy t
18253 (const effort)
18254 (const appt)
18255 (const stats)
18256 (const category))
18257 :version "26.1"
18258 :package-version '(Org . "8.3")
18259 :group 'org-agenda)
18261 ;;;; Files
18263 (defun org-save-all-org-buffers ()
18264 "Save all Org buffers without user confirmation."
18265 (interactive)
18266 (message "Saving all Org buffers...")
18267 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18268 (when (featurep 'org-id) (org-id-locations-save))
18269 (message "Saving all Org buffers... done"))
18271 (defun org-revert-all-org-buffers ()
18272 "Revert all Org buffers.
18273 Prompt for confirmation when there are unsaved changes.
18274 Be sure you know what you are doing before letting this function
18275 overwrite your changes.
18277 This function is useful in a setup where one tracks org files
18278 with a version control system, to revert on one machine after pulling
18279 changes from another. I believe the procedure must be like this:
18281 1. M-x org-save-all-org-buffers
18282 2. Pull changes from the other machine, resolve conflicts
18283 3. M-x org-revert-all-org-buffers"
18284 (interactive)
18285 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18286 (user-error "Abort"))
18287 (save-excursion
18288 (save-window-excursion
18289 (dolist (b (buffer-list))
18290 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18291 (with-current-buffer b buffer-file-name))
18292 (pop-to-buffer-same-window b)
18293 (revert-buffer t 'no-confirm)))
18294 (when (and (featurep 'org-id) org-id-track-globally)
18295 (org-id-locations-load)))))
18297 ;;;; Agenda files
18299 ;;;###autoload
18300 (defun org-switchb (&optional arg)
18301 "Switch between Org buffers.
18303 With `\\[universal-argument]' prefix, restrict available buffers to files.
18305 With `\\[universal-argument] \\[universal-argument]' \
18306 prefix, restrict available buffers to agenda files."
18307 (interactive "P")
18308 (let ((blist (org-buffer-list
18309 (cond ((equal arg '(4)) 'files)
18310 ((equal arg '(16)) 'agenda)))))
18311 (pop-to-buffer-same-window
18312 (completing-read "Org buffer: "
18313 (mapcar #'list (mapcar #'buffer-name blist))
18314 nil t))))
18316 (defun org-buffer-list (&optional predicate exclude-tmp)
18317 "Return a list of Org buffers.
18318 PREDICATE can be `export', `files' or `agenda'.
18320 export restrict the list to Export buffers.
18321 files restrict the list to buffers visiting Org files.
18322 agenda restrict the list to buffers visiting agenda files.
18324 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18325 (let* ((bfn nil)
18326 (agenda-files (and (eq predicate 'agenda)
18327 (mapcar 'file-truename (org-agenda-files t))))
18328 (filter
18329 (cond
18330 ((eq predicate 'files)
18331 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18332 ((eq predicate 'export)
18333 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18334 ((eq predicate 'agenda)
18335 (lambda (b)
18336 (with-current-buffer b
18337 (and (derived-mode-p 'org-mode)
18338 (setq bfn (buffer-file-name b))
18339 (member (file-truename bfn) agenda-files)))))
18340 (t (lambda (b) (with-current-buffer b
18341 (or (derived-mode-p 'org-mode)
18342 (string-match "\\*Org .*Export"
18343 (buffer-name b)))))))))
18344 (delq nil
18345 (mapcar
18346 (lambda(b)
18347 (if (and (funcall filter b)
18348 (or (not exclude-tmp)
18349 (not (string-match "tmp" (buffer-name b)))))
18351 nil))
18352 (buffer-list)))))
18354 (defun org-agenda-files (&optional unrestricted archives)
18355 "Get the list of agenda files.
18356 Optional UNRESTRICTED means return the full list even if a restriction
18357 is currently in place.
18358 When ARCHIVES is t, include all archive files that are really being
18359 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18360 `org-agenda-archives-mode' is t."
18361 (let ((files
18362 (cond
18363 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18364 ((stringp org-agenda-files) (org-read-agenda-file-list))
18365 ((listp org-agenda-files) org-agenda-files)
18366 (t (error "Invalid value of `org-agenda-files'")))))
18367 (setq files (apply 'append
18368 (mapcar (lambda (f)
18369 (if (file-directory-p f)
18370 (directory-files
18371 f t org-agenda-file-regexp)
18372 (list f)))
18373 files)))
18374 (when org-agenda-skip-unavailable-files
18375 (setq files (delq nil
18376 (mapcar (function
18377 (lambda (file)
18378 (and (file-readable-p file) file)))
18379 files))))
18380 (when (or (eq archives t)
18381 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18382 (setq files (org-add-archive-files files)))
18383 files))
18385 (defun org-agenda-file-p (&optional file)
18386 "Return non-nil, if FILE is an agenda file.
18387 If FILE is omitted, use the file associated with the current
18388 buffer."
18389 (let ((fname (or file (buffer-file-name))))
18390 (and fname
18391 (member (file-truename fname)
18392 (mapcar #'file-truename (org-agenda-files t))))))
18394 (defun org-edit-agenda-file-list ()
18395 "Edit the list of agenda files.
18396 Depending on setup, this either uses customize to edit the variable
18397 `org-agenda-files', or it visits the file that is holding the list. In the
18398 latter case, the buffer is set up in a way that saving it automatically kills
18399 the buffer and restores the previous window configuration."
18400 (interactive)
18401 (if (stringp org-agenda-files)
18402 (let ((cw (current-window-configuration)))
18403 (find-file org-agenda-files)
18404 (setq-local org-window-configuration cw)
18405 (add-hook 'after-save-hook
18406 (lambda ()
18407 (set-window-configuration
18408 (prog1 org-window-configuration
18409 (kill-buffer (current-buffer))))
18410 (org-install-agenda-files-menu)
18411 (message "New agenda file list installed"))
18412 nil 'local)
18413 (message "%s" (substitute-command-keys
18414 "Edit list and finish with \\[save-buffer]")))
18415 (customize-variable 'org-agenda-files)))
18417 (defun org-store-new-agenda-file-list (list)
18418 "Set new value for the agenda file list and save it correctly."
18419 (if (stringp org-agenda-files)
18420 (let ((fe (org-read-agenda-file-list t)) b u)
18421 (while (setq b (find-buffer-visiting org-agenda-files))
18422 (kill-buffer b))
18423 (with-temp-file org-agenda-files
18424 (insert
18425 (mapconcat
18426 (lambda (f) ;; Keep un-expanded entries.
18427 (if (setq u (assoc f fe))
18428 (cdr u)
18430 list "\n")
18431 "\n")))
18432 (let ((org-mode-hook nil) (org-inhibit-startup t)
18433 (org-insert-mode-line-in-empty-file nil))
18434 (setq org-agenda-files list)
18435 (customize-save-variable 'org-agenda-files org-agenda-files))))
18437 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18438 "Read the list of agenda files from a file.
18439 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18440 filenames, used by `org-store-new-agenda-file-list' to write back
18441 un-expanded file names."
18442 (when (file-directory-p org-agenda-files)
18443 (error "`org-agenda-files' cannot be a single directory"))
18444 (when (stringp org-agenda-files)
18445 (with-temp-buffer
18446 (insert-file-contents org-agenda-files)
18447 (mapcar
18448 (lambda (f)
18449 (let ((e (expand-file-name (substitute-in-file-name f)
18450 org-directory)))
18451 (if pair-with-expansion
18452 (cons e f)
18453 e)))
18454 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18456 ;;;###autoload
18457 (defun org-cycle-agenda-files ()
18458 "Cycle through the files in `org-agenda-files'.
18459 If the current buffer visits an agenda file, find the next one in the list.
18460 If the current buffer does not, find the first agenda file."
18461 (interactive)
18462 (let* ((fs (or (org-agenda-files t)
18463 (user-error "No agenda files")))
18464 (files (copy-sequence fs))
18465 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18466 file)
18467 (when tcf
18468 (while (and (setq file (pop files))
18469 (not (equal (file-truename file) tcf)))))
18470 (find-file (car (or files fs)))
18471 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18473 (defun org-agenda-file-to-front (&optional to-end)
18474 "Move/add the current file to the top of the agenda file list.
18475 If the file is not present in the list, it is added to the front. If it is
18476 present, it is moved there. With optional argument TO-END, add/move to the
18477 end of the list."
18478 (interactive "P")
18479 (let ((org-agenda-skip-unavailable-files nil)
18480 (file-alist (mapcar (lambda (x)
18481 (cons (file-truename x) x))
18482 (org-agenda-files t)))
18483 (ctf (file-truename
18484 (or buffer-file-name
18485 (user-error "Please save the current buffer to a file"))))
18486 x had)
18487 (setq x (assoc ctf file-alist) had x)
18489 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18490 (if to-end
18491 (setq file-alist (append (delq x file-alist) (list x)))
18492 (setq file-alist (cons x (delq x file-alist))))
18493 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18494 (org-install-agenda-files-menu)
18495 (message "File %s to %s of agenda file list"
18496 (if had "moved" "added") (if to-end "end" "front"))))
18498 (defun org-remove-file (&optional file)
18499 "Remove current file from the list of files in variable `org-agenda-files'.
18500 These are the files which are being checked for agenda entries.
18501 Optional argument FILE means use this file instead of the current."
18502 (interactive)
18503 (let* ((org-agenda-skip-unavailable-files nil)
18504 (file (or file buffer-file-name
18505 (user-error "Current buffer does not visit a file")))
18506 (true-file (file-truename file))
18507 (afile (abbreviate-file-name file))
18508 (files (delq nil (mapcar
18509 (lambda (x)
18510 (unless (equal true-file
18511 (file-truename x))
18513 (org-agenda-files t)))))
18514 (if (not (= (length files) (length (org-agenda-files t))))
18515 (progn
18516 (org-store-new-agenda-file-list files)
18517 (org-install-agenda-files-menu)
18518 (message "Removed from Org Agenda list: %s" afile))
18519 (message "File was not in list: %s (not removed)" afile))))
18521 (defun org-file-menu-entry (file)
18522 (vector file (list 'find-file file) t))
18524 (defun org-check-agenda-file (file)
18525 "Make sure FILE exists. If not, ask user what to do."
18526 (unless (file-exists-p file)
18527 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18528 (abbreviate-file-name file))
18529 (let ((r (downcase (read-char-exclusive))))
18530 (cond
18531 ((equal r ?r)
18532 (org-remove-file file)
18533 (throw 'nextfile t))
18534 (t (user-error "Abort"))))))
18536 (defun org-get-agenda-file-buffer (file)
18537 "Get an agenda buffer visiting FILE.
18538 If the buffer needs to be created, add it to the list of buffers
18539 which might be released later."
18540 (let ((buf (org-find-base-buffer-visiting file)))
18541 (if buf
18542 buf ; just return it
18543 ;; Make a new buffer and remember it
18544 (setq buf (find-file-noselect file))
18545 (when buf (push buf org-agenda-new-buffers))
18546 buf)))
18548 (defun org-release-buffers (blist)
18549 "Release all buffers in list, asking the user for confirmation when needed.
18550 When a buffer is unmodified, it is just killed. When modified, it is saved
18551 \(if the user agrees) and then killed."
18552 (let (file)
18553 (dolist (buf blist)
18554 (setq file (buffer-file-name buf))
18555 (when (and (buffer-modified-p buf)
18556 file
18557 (y-or-n-p (format "Save file %s? " file)))
18558 (with-current-buffer buf (save-buffer)))
18559 (kill-buffer buf))))
18561 (defun org-agenda-prepare-buffers (files)
18562 "Create buffers for all agenda files, protect archived trees and comments."
18563 (interactive)
18564 (let ((pa '(:org-archived t))
18565 (pc '(:org-comment t))
18566 (pall '(:org-archived t :org-comment t))
18567 (inhibit-read-only t)
18568 (org-inhibit-startup org-agenda-inhibit-startup)
18569 (rea (concat ":" org-archive-tag ":"))
18570 re pos)
18571 (setq org-tag-alist-for-agenda nil
18572 org-tag-groups-alist-for-agenda nil)
18573 (save-excursion
18574 (save-restriction
18575 (dolist (file files)
18576 (catch 'nextfile
18577 (if (bufferp file)
18578 (set-buffer file)
18579 (org-check-agenda-file file)
18580 (set-buffer (org-get-agenda-file-buffer file)))
18581 (widen)
18582 (org-set-regexps-and-options 'tags-only)
18583 (setq pos (point))
18584 (or (memq 'category org-agenda-ignore-properties)
18585 (org-refresh-category-properties))
18586 (or (memq 'stats org-agenda-ignore-properties)
18587 (org-refresh-stats-properties))
18588 (or (memq 'effort org-agenda-ignore-properties)
18589 (org-refresh-effort-properties))
18590 (or (memq 'appt org-agenda-ignore-properties)
18591 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18592 (setq org-todo-keywords-for-agenda
18593 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18594 (setq org-done-keywords-for-agenda
18595 (append org-done-keywords-for-agenda org-done-keywords))
18596 (setq org-todo-keyword-alist-for-agenda
18597 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18598 (setq org-tag-alist-for-agenda
18599 (org-uniquify
18600 (append org-tag-alist-for-agenda
18601 org-current-tag-alist)))
18602 ;; Merge current file's tag groups into global
18603 ;; `org-tag-groups-alist-for-agenda'.
18604 (when org-group-tags
18605 (dolist (alist org-tag-groups-alist)
18606 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18607 (if old
18608 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18609 (push alist org-tag-groups-alist-for-agenda)))))
18610 (org-with-silent-modifications
18611 (save-excursion
18612 (remove-text-properties (point-min) (point-max) pall)
18613 (when org-agenda-skip-archived-trees
18614 (goto-char (point-min))
18615 (while (re-search-forward rea nil t)
18616 (when (org-at-heading-p t)
18617 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18618 (goto-char (point-min))
18619 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18620 (while (re-search-forward re nil t)
18621 (when (save-match-data (org-in-commented-heading-p t))
18622 (add-text-properties
18623 (match-beginning 0) (org-end-of-subtree t) pc)))))
18624 (goto-char pos)))))
18625 (setq org-todo-keywords-for-agenda
18626 (org-uniquify org-todo-keywords-for-agenda))
18627 (setq org-todo-keyword-alist-for-agenda
18628 (org-uniquify org-todo-keyword-alist-for-agenda))))
18631 ;;;; CDLaTeX minor mode
18633 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18634 "Keymap for the minor `org-cdlatex-mode'.")
18636 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18637 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18638 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18639 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18640 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18642 (defvar org-cdlatex-texmathp-advice-is-done nil
18643 "Flag remembering if we have applied the advice to texmathp already.")
18645 (define-minor-mode org-cdlatex-mode
18646 "Toggle the minor `org-cdlatex-mode'.
18647 This mode supports entering LaTeX environment and math in LaTeX fragments
18648 in Org mode.
18649 \\{org-cdlatex-mode-map}"
18650 nil " OCDL" nil
18651 (when org-cdlatex-mode
18652 (require 'cdlatex)
18653 (run-hooks 'cdlatex-mode-hook)
18654 (cdlatex-compute-tables))
18655 (unless org-cdlatex-texmathp-advice-is-done
18656 (setq org-cdlatex-texmathp-advice-is-done t)
18657 (defadvice texmathp (around org-math-always-on activate)
18658 "Always return t in Org buffers.
18659 This is because we want to insert math symbols without dollars even outside
18660 the LaTeX math segments. If Org mode thinks that point is actually inside
18661 an embedded LaTeX fragment, let `texmathp' do its job.
18662 `\\[org-cdlatex-mode-map]'"
18663 (interactive)
18664 (let (p)
18665 (cond
18666 ((not (derived-mode-p 'org-mode)) ad-do-it)
18667 ((eq this-command 'cdlatex-math-symbol)
18668 (setq ad-return-value t
18669 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18671 (let ((p (org-inside-LaTeX-fragment-p)))
18672 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18673 (setq ad-return-value t
18674 texmathp-why '("Org mode embedded math" . 0))
18675 (when p ad-do-it)))))))))
18677 (defun turn-on-org-cdlatex ()
18678 "Unconditionally turn on `org-cdlatex-mode'."
18679 (org-cdlatex-mode 1))
18681 (defun org-try-cdlatex-tab ()
18682 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18683 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18684 - inside a LaTeX fragment, or
18685 - after the first word in a line, where an abbreviation expansion could
18686 insert a LaTeX environment."
18687 (when org-cdlatex-mode
18688 (cond
18689 ;; Before any word on the line: No expansion possible.
18690 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18691 ;; Just after first word on the line: Expand it. Make sure it
18692 ;; cannot happen on headlines, though.
18693 ((save-excursion
18694 (skip-chars-backward "a-zA-Z0-9*")
18695 (skip-chars-backward " \t")
18696 (and (bolp) (not (org-at-heading-p))))
18697 (cdlatex-tab) t)
18698 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18700 (defun org-cdlatex-underscore-caret (&optional _arg)
18701 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18702 Revert to the normal definition outside of these fragments."
18703 (interactive "P")
18704 (if (org-inside-LaTeX-fragment-p)
18705 (call-interactively 'cdlatex-sub-superscript)
18706 (let (org-cdlatex-mode)
18707 (call-interactively (key-binding (vector last-input-event))))))
18709 (defun org-cdlatex-math-modify (&optional _arg)
18710 "Execute `cdlatex-math-modify' in LaTeX fragments.
18711 Revert to the normal definition outside of these fragments."
18712 (interactive "P")
18713 (if (org-inside-LaTeX-fragment-p)
18714 (call-interactively 'cdlatex-math-modify)
18715 (let (org-cdlatex-mode)
18716 (call-interactively (key-binding (vector last-input-event))))))
18718 (defun org-cdlatex-environment-indent (&optional environment item)
18719 "Execute `cdlatex-environment' and indent the inserted environment.
18721 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18723 The inserted environment is indented to current indentation
18724 unless point is at the beginning of the line, in which the
18725 environment remains unintended."
18726 (interactive)
18727 ;; cdlatex-environment always return nil. Therefore, capture output
18728 ;; first and determine if an environment was selected.
18729 (let* ((beg (point-marker))
18730 (end (copy-marker (point) t))
18731 (inserted (progn
18732 (ignore-errors (cdlatex-environment environment item))
18733 (< beg end)))
18734 ;; Figure out how many lines to move forward after the
18735 ;; environment has been inserted.
18736 (lines (when inserted
18737 (save-excursion
18738 (- (cl-loop while (< beg (point))
18739 with x = 0
18740 do (forward-line -1)
18741 (cl-incf x)
18742 finally return x)
18743 (if (progn (goto-char beg)
18744 (and (progn (skip-chars-forward " \t") (eolp))
18745 (progn (skip-chars-backward " \t") (bolp))))
18746 1 0)))))
18747 (env (org-trim (delete-and-extract-region beg end))))
18748 (when inserted
18749 ;; Get indentation of next line unless at column 0.
18750 (let ((ind (if (bolp) 0
18751 (save-excursion
18752 (org-return-indent)
18753 (prog1 (org-get-indentation)
18754 (when (progn (skip-chars-forward " \t") (eolp))
18755 (delete-region beg (point)))))))
18756 (bol (progn (skip-chars-backward " \t") (bolp))))
18757 ;; Insert a newline before environment unless at column zero
18758 ;; to "escape" the current line. Insert a newline if
18759 ;; something is one the same line as \end{ENVIRONMENT}.
18760 (insert
18761 (concat (unless bol "\n") env
18762 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18763 (unless (zerop ind)
18764 (save-excursion
18765 (goto-char beg)
18766 (while (< (point) end)
18767 (unless (eolp) (indent-line-to ind))
18768 (forward-line))))
18769 (goto-char beg)
18770 (forward-line lines)
18771 (indent-line-to ind)))
18772 (set-marker beg nil)
18773 (set-marker end nil)))
18776 ;;;; LaTeX fragments
18778 (defun org-inside-LaTeX-fragment-p ()
18779 "Test if point is inside a LaTeX fragment.
18780 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18781 sequence appearing also before point.
18782 Even though the matchers for math are configurable, this function assumes
18783 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18784 delimiters are skipped when they have been removed by customization.
18785 The return value is nil, or a cons cell with the delimiter and the
18786 position of this delimiter.
18788 This function does a reasonably good job, but can locally be fooled by
18789 for example currency specifications. For example it will assume being in
18790 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18791 fragments that are properly closed, but during editing, we have to live
18792 with the uncertainty caused by missing closing delimiters. This function
18793 looks only before point, not after."
18794 (catch 'exit
18795 (let ((pos (point))
18796 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18797 (lim (save-excursion (org-backward-paragraph) (point)))
18798 dd-on str (start 0) m re)
18799 (goto-char pos)
18800 (when dodollar
18801 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18802 re (nth 1 (assoc "$" org-latex-regexps)))
18803 (while (string-match re str start)
18804 (cond
18805 ((= (match-end 0) (length str))
18806 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18807 ((= (match-end 0) (- (length str) 5))
18808 (throw 'exit nil))
18809 (t (setq start (match-end 0))))))
18810 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18811 (goto-char pos)
18812 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18813 (and (match-beginning 2) (throw 'exit nil))
18814 ;; count $$
18815 (while (re-search-backward "\\$\\$" lim t)
18816 (setq dd-on (not dd-on)))
18817 (goto-char pos)
18818 (when dd-on (cons "$$" m))))))
18820 (defun org-inside-latex-macro-p ()
18821 "Is point inside a LaTeX macro or its arguments?"
18822 (save-match-data
18823 (org-in-regexp
18824 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18826 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18827 "Build an overlay between BEG and END using IMAGE file.
18828 Argument IMAGETYPE is the extension of the displayed image,
18829 as a string. It defaults to \"png\"."
18830 (let ((ov (make-overlay beg end))
18831 (imagetype (or (intern imagetype) 'png)))
18832 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18833 (overlay-put ov 'evaporate t)
18834 (overlay-put ov
18835 'modification-hooks
18836 (list (lambda (o _flag _beg _end &optional _l)
18837 (delete-overlay o))))
18838 (overlay-put ov
18839 'display
18840 (list 'image :type imagetype :file image :ascent 'center))))
18842 (defun org--list-latex-overlays (&optional beg end)
18843 "List all Org LaTeX overlays in current buffer.
18844 Limit to overlays between BEG and END when those are provided."
18845 (cl-remove-if-not
18846 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18847 (overlays-in (or beg (point-min)) (or end (point-max)))))
18849 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18850 "Remove all overlays with LaTeX fragment images in current buffer.
18851 When optional arguments BEG and END are non-nil, remove all
18852 overlays between them instead. Return a non-nil value when some
18853 overlays were removed, nil otherwise."
18854 (let ((overlays (org--list-latex-overlays beg end)))
18855 (mapc #'delete-overlay overlays)
18856 overlays))
18858 (defun org-toggle-latex-fragment (&optional arg)
18859 "Preview the LaTeX fragment at point, or all locally or globally.
18861 If the cursor is on a LaTeX fragment, create the image and overlay
18862 it over the source code, if there is none. Remove it otherwise.
18863 If there is no fragment at point, display all fragments in the
18864 current section.
18866 With prefix ARG, preview or clear image for all fragments in the
18867 current subtree or in the whole buffer when used before the first
18868 headline. With a prefix ARG `\\[universal-argument] \
18869 \\[universal-argument]' preview or clear images
18870 for all fragments in the buffer."
18871 (interactive "P")
18872 (when (display-graphic-p)
18873 (catch 'exit
18874 (save-excursion
18875 (let (beg end msg)
18876 (cond
18877 ((or (equal arg '(16))
18878 (and (equal arg '(4))
18879 (org-with-limited-levels (org-before-first-heading-p))))
18880 (if (org-remove-latex-fragment-image-overlays)
18881 (progn (message "LaTeX fragments images removed from buffer")
18882 (throw 'exit nil))
18883 (setq msg "Creating images for buffer...")))
18884 ((equal arg '(4))
18885 (org-with-limited-levels (org-back-to-heading t))
18886 (setq beg (point))
18887 (setq end (progn (org-end-of-subtree t) (point)))
18888 (if (org-remove-latex-fragment-image-overlays beg end)
18889 (progn
18890 (message "LaTeX fragment images removed from subtree")
18891 (throw 'exit nil))
18892 (setq msg "Creating images for subtree...")))
18893 ((let ((datum (org-element-context)))
18894 (when (memq (org-element-type datum)
18895 '(latex-environment latex-fragment))
18896 (setq beg (org-element-property :begin datum))
18897 (setq end (org-element-property :end datum))
18898 (if (org-remove-latex-fragment-image-overlays beg end)
18899 (progn (message "LaTeX fragment image removed")
18900 (throw 'exit nil))
18901 (setq msg "Creating image...")))))
18903 (org-with-limited-levels
18904 (setq beg (if (org-at-heading-p) (line-beginning-position)
18905 (outline-previous-heading)
18906 (point)))
18907 (setq end (progn (outline-next-heading) (point)))
18908 (if (org-remove-latex-fragment-image-overlays beg end)
18909 (progn
18910 (message "LaTeX fragment images removed from section")
18911 (throw 'exit nil))
18912 (setq msg "Creating images for section...")))))
18913 (let ((file (buffer-file-name (buffer-base-buffer))))
18914 (org-format-latex
18915 (concat org-preview-latex-image-directory "org-ltximg")
18916 beg end
18917 ;; Emacs cannot overlay images from remote hosts. Create
18918 ;; it in `temporary-file-directory' instead.
18919 (if (or (not file) (file-remote-p file))
18920 temporary-file-directory
18921 default-directory)
18922 'overlays msg 'forbuffer org-preview-latex-default-process))
18923 (message (concat msg "done")))))))
18925 (defun org-format-latex
18926 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18927 "Replace LaTeX fragments with links to an image.
18929 The function takes care of creating the replacement image.
18931 Only consider fragments between BEG and END when those are
18932 provided.
18934 When optional argument OVERLAYS is non-nil, display the image on
18935 top of the fragment instead of replacing it.
18937 PROCESSING-TYPE is the conversion method to use, as a symbol.
18939 Some of the options can be changed using the variable
18940 `org-format-latex-options', which see."
18941 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18942 (unless (eq processing-type 'verbatim)
18943 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18944 (cnt 0)
18945 checkdir-flag)
18946 (goto-char (or beg (point-min)))
18947 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18948 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18949 (overlay-recenter (or end (point-max))))
18950 (while (re-search-forward math-regexp end t)
18951 (unless (and overlays
18952 (eq (get-char-property (point) 'org-overlay-type)
18953 'org-latex-overlay))
18954 (let* ((context (org-element-context))
18955 (type (org-element-type context)))
18956 (when (memq type '(latex-environment latex-fragment))
18957 (let ((block-type (eq type 'latex-environment))
18958 (value (org-element-property :value context))
18959 (beg (org-element-property :begin context))
18960 (end (save-excursion
18961 (goto-char (org-element-property :end context))
18962 (skip-chars-backward " \r\t\n")
18963 (point))))
18964 (cond
18965 ((eq processing-type 'mathjax)
18966 ;; Prepare for MathJax processing.
18967 (if (not (string-match "\\`\\$\\$?" value))
18968 (goto-char end)
18969 (delete-region beg end)
18970 (if (string= (match-string 0 value) "$$")
18971 (insert "\\[" (substring value 2 -2) "\\]")
18972 (insert "\\(" (substring value 1 -1) "\\)"))))
18973 ((assq processing-type org-preview-latex-process-alist)
18974 ;; Process to an image.
18975 (cl-incf cnt)
18976 (goto-char beg)
18977 (let* ((processing-info
18978 (cdr (assq processing-type org-preview-latex-process-alist)))
18979 (face (face-at-point))
18980 ;; Get the colors from the face at point.
18982 (let ((color (plist-get org-format-latex-options
18983 :foreground)))
18984 (if (and forbuffer (eq color 'auto))
18985 (face-attribute face :foreground nil 'default)
18986 color)))
18988 (let ((color (plist-get org-format-latex-options
18989 :background)))
18990 (if (and forbuffer (eq color 'auto))
18991 (face-attribute face :background nil 'default)
18992 color)))
18993 (hash (sha1 (prin1-to-string
18994 (list org-format-latex-header
18995 org-latex-default-packages-alist
18996 org-latex-packages-alist
18997 org-format-latex-options
18998 forbuffer value fg bg))))
18999 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19000 (absprefix (expand-file-name prefix dir))
19001 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19002 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19003 (sep (and block-type "\n\n"))
19004 (link (concat sep "[[file:" linkfile "]]" sep))
19005 (options
19006 (org-combine-plists
19007 org-format-latex-options
19008 `(:foreground ,fg :background ,bg))))
19009 (when msg (message msg cnt))
19010 (unless checkdir-flag ; Ensure the directory exists.
19011 (setq checkdir-flag t)
19012 (let ((todir (file-name-directory absprefix)))
19013 (unless (file-directory-p todir)
19014 (make-directory todir t))))
19015 (unless (file-exists-p movefile)
19016 (org-create-formula-image
19017 value movefile options forbuffer processing-type))
19018 (if overlays
19019 (progn
19020 (dolist (o (overlays-in beg end))
19021 (when (eq (overlay-get o 'org-overlay-type)
19022 'org-latex-overlay)
19023 (delete-overlay o)))
19024 (org--format-latex-make-overlay beg end movefile imagetype)
19025 (goto-char end))
19026 (delete-region beg end)
19027 (insert
19028 (org-add-props link
19029 (list 'org-latex-src
19030 (replace-regexp-in-string "\"" "" value)
19031 'org-latex-src-embed-type
19032 (if block-type 'paragraph 'character)))))))
19033 ((eq processing-type 'mathml)
19034 ;; Process to MathML.
19035 (unless (org-format-latex-mathml-available-p)
19036 (user-error "LaTeX to MathML converter not configured"))
19037 (cl-incf cnt)
19038 (when msg (message msg cnt))
19039 (goto-char beg)
19040 (delete-region beg end)
19041 (insert (org-format-latex-as-mathml
19042 value block-type prefix dir)))
19044 (error "Unknown conversion process %s for LaTeX fragments"
19045 processing-type)))))))))))
19047 (defun org-create-math-formula (latex-frag &optional mathml-file)
19048 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19049 Use `org-latex-to-mathml-convert-command'. If the conversion is
19050 sucessful, return the portion between \"<math...> </math>\"
19051 elements otherwise return nil. When MATHML-FILE is specified,
19052 write the results in to that file. When invoked as an
19053 interactive command, prompt for LATEX-FRAG, with initial value
19054 set to the current active region and echo the results for user
19055 inspection."
19056 (interactive (list (let ((frag (when (org-region-active-p)
19057 (buffer-substring-no-properties
19058 (region-beginning) (region-end)))))
19059 (read-string "LaTeX Fragment: " frag nil frag))))
19060 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19061 (let* ((tmp-in-file
19062 (let ((file (file-relative-name
19063 (make-temp-name (expand-file-name "ltxmathml-in")))))
19064 (write-region latex-frag nil file)
19065 file))
19066 (tmp-out-file (file-relative-name
19067 (make-temp-name (expand-file-name "ltxmathml-out"))))
19068 (cmd (format-spec
19069 org-latex-to-mathml-convert-command
19070 `((?j . ,(and org-latex-to-mathml-jar-file
19071 (shell-quote-argument
19072 (expand-file-name
19073 org-latex-to-mathml-jar-file))))
19074 (?I . ,(shell-quote-argument tmp-in-file))
19075 (?i . ,latex-frag)
19076 (?o . ,(shell-quote-argument tmp-out-file)))))
19077 mathml shell-command-output)
19078 (when (called-interactively-p 'any)
19079 (unless (org-format-latex-mathml-available-p)
19080 (user-error "LaTeX to MathML converter not configured")))
19081 (message "Running %s" cmd)
19082 (setq shell-command-output (shell-command-to-string cmd))
19083 (setq mathml
19084 (when (file-readable-p tmp-out-file)
19085 (with-current-buffer (find-file-noselect tmp-out-file t)
19086 (goto-char (point-min))
19087 (when (re-search-forward
19088 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19089 (regexp-quote
19090 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19091 nil t)
19092 (prog1 (match-string 0) (kill-buffer))))))
19093 (cond
19094 (mathml
19095 (setq mathml
19096 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19097 (when mathml-file
19098 (write-region mathml nil mathml-file))
19099 (when (called-interactively-p 'any)
19100 (message mathml)))
19101 ((message "LaTeX to MathML conversion failed")
19102 (message shell-command-output)))
19103 (delete-file tmp-in-file)
19104 (when (file-exists-p tmp-out-file)
19105 (delete-file tmp-out-file))
19106 mathml))
19108 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19109 prefix &optional dir)
19110 "Use `org-create-math-formula' but check local cache first."
19111 (let* ((absprefix (expand-file-name prefix dir))
19112 (print-length nil) (print-level nil)
19113 (formula-id (concat
19114 "formula-"
19115 (sha1
19116 (prin1-to-string
19117 (list latex-frag
19118 org-latex-to-mathml-convert-command)))))
19119 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19120 (formula-cache-dir (file-name-directory formula-cache)))
19122 (unless (file-directory-p formula-cache-dir)
19123 (make-directory formula-cache-dir t))
19125 (unless (file-exists-p formula-cache)
19126 (org-create-math-formula latex-frag formula-cache))
19128 (if (file-exists-p formula-cache)
19129 ;; Successful conversion. Return the link to MathML file.
19130 (org-add-props
19131 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19132 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19133 'org-latex-src-embed-type (if latex-frag-type
19134 'paragraph 'character)))
19135 ;; Failed conversion. Return the LaTeX fragment verbatim
19136 latex-frag)))
19138 (defun org--get-display-dpi ()
19139 "Get the DPI of the display.
19140 The function assumes that the display has the same pixel width in
19141 the horizontal and vertical directions."
19142 (if (display-graphic-p)
19143 (round (/ (display-pixel-height)
19144 (/ (display-mm-height) 25.4)))
19145 (error "Attempt to calculate the dpi of a non-graphic display")))
19147 (defun org-create-formula-image
19148 (string tofile options buffer &optional processing-type)
19149 "Create an image from LaTeX source using external processes.
19151 The LaTeX STRING is saved to a temporary LaTeX file, then
19152 converted to an image file by process PROCESSING-TYPE defined in
19153 `org-preview-latex-process-alist'. A nil value defaults to
19154 `org-preview-latex-default-process'.
19156 The generated image file is eventually moved to TOFILE.
19158 The OPTIONS argument controls the size, foreground color and
19159 background color of the generated image.
19161 When BUFFER non-nil, this function is used for LaTeX previewing.
19162 Otherwise, it is used to deal with LaTeX snippets showed in
19163 a HTML file."
19164 (let* ((processing-type (or processing-type
19165 org-preview-latex-default-process))
19166 (processing-info
19167 (cdr (assq processing-type org-preview-latex-process-alist)))
19168 (programs (plist-get processing-info :programs))
19169 (error-message (or (plist-get processing-info :message) ""))
19170 (use-xcolor (plist-get processing-info :use-xcolor))
19171 (image-input-type (plist-get processing-info :image-input-type))
19172 (image-output-type (plist-get processing-info :image-output-type))
19173 (post-clean (or (plist-get processing-info :post-clean)
19174 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19175 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19176 (latex-header
19177 (or (plist-get processing-info :latex-header)
19178 (org-latex-make-preamble
19179 (org-export-get-environment (org-export-get-backend 'latex))
19180 org-format-latex-header
19181 'snippet)))
19182 (latex-compiler (plist-get processing-info :latex-compiler))
19183 (image-converter (plist-get processing-info :image-converter))
19184 (tmpdir temporary-file-directory)
19185 (texfilebase (make-temp-name
19186 (expand-file-name "orgtex" tmpdir)))
19187 (texfile (concat texfilebase ".tex"))
19188 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19189 '(1.0 . 1.0)))
19190 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19191 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19192 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19193 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19194 "Black"))
19195 (bg (or (plist-get options (if buffer :background :html-background))
19196 "Transparent"))
19197 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19198 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19199 (dolist (program programs)
19200 (org-check-external-command program error-message))
19201 (if use-xcolor
19202 (progn (if (eq fg 'default)
19203 (setq fg (org-latex-color :foreground))
19204 (setq fg (org-latex-color-format fg)))
19205 (if (eq bg 'default)
19206 (setq bg (org-latex-color :background))
19207 (setq bg (org-latex-color-format
19208 (if (string= bg "Transparent") "white" bg))))
19209 (with-temp-file texfile
19210 (insert latex-header)
19211 (insert "\n\\begin{document}\n"
19212 "\\definecolor{fg}{rgb}{" fg "}\n"
19213 "\\definecolor{bg}{rgb}{" bg "}\n"
19214 "\n\\pagecolor{bg}\n"
19215 "\n{\\color{fg}\n"
19216 string
19217 "\n}\n"
19218 "\n\\end{document}\n")))
19219 (if (eq fg 'default)
19220 (setq fg (org-dvipng-color :foreground))
19221 (unless (string= fg "Transparent")
19222 (setq fg (org-dvipng-color-format fg))))
19223 (if (eq bg 'default)
19224 (setq bg (org-dvipng-color :background))
19225 (unless (string= bg "Transparent")
19226 (setq bg (org-dvipng-color-format bg))))
19227 (with-temp-file texfile
19228 (insert latex-header)
19229 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19231 (let* ((err-msg (format "Please adjust `%s' part of \
19232 `org-preview-latex-process-alist'."
19233 processing-type))
19234 (image-input-file
19235 (org-compile-file
19236 texfile latex-compiler image-input-type err-msg log-buf))
19237 (image-output-file
19238 (org-compile-file
19239 image-input-file image-converter image-output-type err-msg log-buf
19240 `((?F . ,(shell-quote-argument fg))
19241 (?B . ,(shell-quote-argument bg))
19242 (?D . ,(shell-quote-argument (format "%s" dpi)))
19243 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19244 (copy-file image-output-file tofile 'replace)
19245 (dolist (e post-clean)
19246 (when (file-exists-p (concat texfilebase e))
19247 (delete-file (concat texfilebase e))))
19248 image-output-file)))
19250 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19251 "Fill a LaTeX header template TPL.
19252 In the template, the following place holders will be recognized:
19254 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19255 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19256 [PACKAGES] \\usepackage statements for PKG
19257 [NO-PACKAGES] do not include PKG
19258 [EXTRA] the string EXTRA
19259 [NO-EXTRA] do not include EXTRA
19261 For backward compatibility, if both the positive and the negative place
19262 holder is missing, the positive one (without the \"NO-\") will be
19263 assumed to be present at the end of the template.
19264 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19265 EXTRA is a string.
19266 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19267 (let (rpl (end ""))
19268 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19269 (setq rpl (if (or (match-end 1) (not def-pkg))
19270 "" (org-latex-packages-to-string def-pkg snippets-p t))
19271 tpl (replace-match rpl t t tpl))
19272 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19274 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19275 (setq rpl (if (or (match-end 1) (not pkg))
19276 "" (org-latex-packages-to-string pkg snippets-p t))
19277 tpl (replace-match rpl t t tpl))
19278 (when pkg (setq end
19279 (concat end "\n"
19280 (org-latex-packages-to-string pkg snippets-p)))))
19282 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19283 (setq rpl (if (or (match-end 1) (not extra))
19284 "" (concat extra "\n"))
19285 tpl (replace-match rpl t t tpl))
19286 (when (and extra (string-match "\\S-" extra))
19287 (setq end (concat end "\n" extra))))
19289 (if (string-match "\\S-" end)
19290 (concat tpl "\n" end)
19291 tpl)))
19293 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19294 "Turn an alist of packages into a string with the \\usepackage macros."
19295 (setq pkg (mapconcat (lambda(p)
19296 (cond
19297 ((stringp p) p)
19298 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19299 (format "%% Package %s omitted" (cadr p)))
19300 ((equal "" (car p))
19301 (format "\\usepackage{%s}" (cadr p)))
19303 (format "\\usepackage[%s]{%s}"
19304 (car p) (cadr p)))))
19306 "\n"))
19307 (if newline (concat pkg "\n") pkg))
19309 (defun org-dvipng-color (attr)
19310 "Return a RGB color specification for dvipng."
19311 (org-dvipng-color-format (face-attribute 'default attr nil)))
19313 (defun org-dvipng-color-format (color-name)
19314 "Convert COLOR-NAME to a RGB color value for dvipng."
19315 (apply #'format "rgb %s %s %s"
19316 (mapcar 'org-normalize-color
19317 (color-values color-name))))
19319 (defun org-latex-color (attr)
19320 "Return a RGB color for the LaTeX color package."
19321 (org-latex-color-format (face-attribute 'default attr nil)))
19323 (defun org-latex-color-format (color-name)
19324 "Convert COLOR-NAME to a RGB color value."
19325 (apply #'format "%s,%s,%s"
19326 (mapcar 'org-normalize-color
19327 (color-values color-name))))
19329 (defun org-normalize-color (value)
19330 "Return string to be used as color value for an RGB component."
19331 (format "%g" (/ value 65535.0)))
19335 ;; Image display
19337 (defvar-local org-inline-image-overlays nil)
19339 (defun org-toggle-inline-images (&optional include-linked)
19340 "Toggle the display of inline images.
19341 INCLUDE-LINKED is passed to `org-display-inline-images'."
19342 (interactive "P")
19343 (if org-inline-image-overlays
19344 (progn
19345 (org-remove-inline-images)
19346 (when (called-interactively-p 'interactive)
19347 (message "Inline image display turned off")))
19348 (org-display-inline-images include-linked)
19349 (when (called-interactively-p 'interactive)
19350 (message (if org-inline-image-overlays
19351 (format "%d images displayed inline"
19352 (length org-inline-image-overlays))
19353 "No images to display inline")))))
19355 (defun org-redisplay-inline-images ()
19356 "Refresh the display of inline images."
19357 (interactive)
19358 (if (not org-inline-image-overlays)
19359 (org-toggle-inline-images)
19360 (org-toggle-inline-images)
19361 (org-toggle-inline-images)))
19363 (defun org-display-inline-images (&optional include-linked refresh beg end)
19364 "Display inline images.
19366 An inline image is a link which follows either of these
19367 conventions:
19369 1. Its path is a file with an extension matching return value
19370 from `image-file-name-regexp' and it has no contents.
19372 2. Its description consists in a single link of the previous
19373 type.
19375 When optional argument INCLUDE-LINKED is non-nil, also links with
19376 a text description part will be inlined. This can be nice for
19377 a quick look at those images, but it does not reflect what
19378 exported files will look like.
19380 When optional argument REFRESH is non-nil, refresh existing
19381 images between BEG and END. This will create new image displays
19382 only if necessary. BEG and END default to the buffer
19383 boundaries."
19384 (interactive "P")
19385 (when (display-graphic-p)
19386 (unless refresh
19387 (org-remove-inline-images)
19388 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19389 (org-with-wide-buffer
19390 (goto-char (or beg (point-min)))
19391 (let ((case-fold-search t)
19392 (file-extension-re (image-file-name-regexp)))
19393 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19394 (let ((link (save-match-data (org-element-context))))
19395 ;; Check if we're at an inline image.
19396 (when (and (equal (org-element-property :type link) "file")
19397 (or include-linked
19398 (not (org-element-property :contents-begin link)))
19399 (let ((parent (org-element-property :parent link)))
19400 (or (not (eq (org-element-type parent) 'link))
19401 (not (cdr (org-element-contents parent)))))
19402 (string-match-p file-extension-re
19403 (org-element-property :path link)))
19404 (let ((file (expand-file-name
19405 (org-link-unescape
19406 (org-element-property :path link)))))
19407 (when (file-exists-p file)
19408 (let ((width
19409 ;; Apply `org-image-actual-width' specifications.
19410 (cond
19411 ((not (image-type-available-p 'imagemagick)) nil)
19412 ((eq org-image-actual-width t) nil)
19413 ((listp org-image-actual-width)
19415 ;; First try to find a width among
19416 ;; attributes associated to the paragraph
19417 ;; containing link.
19418 (let ((paragraph
19419 (let ((e link))
19420 (while (and (setq e (org-element-property
19421 :parent e))
19422 (not (eq (org-element-type e)
19423 'paragraph))))
19424 e)))
19425 (when paragraph
19426 (save-excursion
19427 (goto-char (org-element-property :begin paragraph))
19428 (when
19429 (re-search-forward
19430 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19431 (org-element-property
19432 :post-affiliated paragraph)
19434 (string-to-number (match-string 1))))))
19435 ;; Otherwise, fall-back to provided number.
19436 (car org-image-actual-width)))
19437 ((numberp org-image-actual-width)
19438 org-image-actual-width)))
19439 (old (get-char-property-and-overlay
19440 (org-element-property :begin link)
19441 'org-image-overlay)))
19442 (if (and (car-safe old) refresh)
19443 (image-refresh (overlay-get (cdr old) 'display))
19444 (let ((image (create-image file
19445 (and width 'imagemagick)
19447 :width width)))
19448 (when image
19449 (let* ((link
19450 ;; If inline image is the description
19451 ;; of another link, be sure to
19452 ;; consider the latter as the one to
19453 ;; apply the overlay on.
19454 (let ((parent
19455 (org-element-property :parent link)))
19456 (if (eq (org-element-type parent) 'link)
19457 parent
19458 link)))
19459 (ov (make-overlay
19460 (org-element-property :begin link)
19461 (progn
19462 (goto-char
19463 (org-element-property :end link))
19464 (skip-chars-backward " \t")
19465 (point)))))
19466 (overlay-put ov 'display image)
19467 (overlay-put ov 'face 'default)
19468 (overlay-put ov 'org-image-overlay t)
19469 (overlay-put
19470 ov 'modification-hooks
19471 (list 'org-display-inline-remove-overlay))
19472 (push ov org-inline-image-overlays)))))))))))))))
19474 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19475 "Remove inline-display overlay if a corresponding region is modified."
19476 (let ((inhibit-modification-hooks t))
19477 (when (and ov after)
19478 (delete ov org-inline-image-overlays)
19479 (delete-overlay ov))))
19481 (defun org-remove-inline-images ()
19482 "Remove inline display of images."
19483 (interactive)
19484 (mapc #'delete-overlay org-inline-image-overlays)
19485 (setq org-inline-image-overlays nil))
19487 ;;;; Key bindings
19489 ;; Outline functions from `outline-mode-prefix-map'
19490 ;; that can be remapped in Org:
19491 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19492 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19493 (define-key org-mode-map [remap outline-forward-same-level]
19494 'org-forward-heading-same-level)
19495 (define-key org-mode-map [remap outline-backward-same-level]
19496 'org-backward-heading-same-level)
19497 (define-key org-mode-map [remap outline-show-branches]
19498 'org-kill-note-or-show-branches)
19499 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19500 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19501 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19502 (define-key org-mode-map [remap outline-next-visible-heading]
19503 'org-next-visible-heading)
19504 (define-key org-mode-map [remap outline-previous-visible-heading]
19505 'org-previous-visible-heading)
19506 (define-key org-mode-map [remap show-children] 'org-show-children)
19508 ;; Outline functions from `outline-mode-prefix-map' that can not
19509 ;; be remapped in Org:
19511 ;; - the column "key binding" shows whether the Outline function is still
19512 ;; available in Org mode on the same key that it has been bound to in
19513 ;; Outline mode:
19514 ;; - "overridden": key used for a different functionality in Org mode
19515 ;; - else: key still bound to the same Outline function in Org mode
19517 ;; | Outline function | key binding | Org replacement |
19518 ;; |------------------------------------+-------------+--------------------------|
19519 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19520 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19521 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19522 ;; | `show-entry' | overridden | no replacement |
19523 ;; | `show-branches' | `C-c C-k' | still same function |
19524 ;; | `show-subtree' | overridden | visibility cycling |
19525 ;; | `show-all' | overridden | no replacement |
19526 ;; | `hide-subtree' | overridden | visibility cycling |
19527 ;; | `hide-body' | overridden | no replacement |
19528 ;; | `hide-entry' | overridden | visibility cycling |
19529 ;; | `hide-leaves' | overridden | no replacement |
19530 ;; | `hide-sublevels' | overridden | no replacement |
19531 ;; | `hide-other' | overridden | no replacement |
19533 ;; Make `C-c C-x' a prefix key
19534 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19536 ;; TAB key with modifiers
19537 (org-defkey org-mode-map "\C-i" 'org-cycle)
19538 (org-defkey org-mode-map [(tab)] 'org-cycle)
19539 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19540 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19541 ;; The following line is necessary under Suse GNU/Linux
19542 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19543 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19544 (define-key org-mode-map [backtab] 'org-shifttab)
19546 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19547 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19548 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19550 ;; Cursor keys with modifiers
19551 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19552 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19553 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19554 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19556 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19557 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19558 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19559 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19560 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19561 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19563 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19564 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19565 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19566 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19568 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19569 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19570 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19571 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19573 ;; Babel keys
19574 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19575 (dolist (pair org-babel-key-bindings)
19576 (define-key org-babel-map (car pair) (cdr pair)))
19578 ;;; Extra keys for tty access.
19579 ;; We only set them when really needed because otherwise the
19580 ;; menus don't show the simple keys
19582 (when (or org-use-extra-keys (not window-system))
19583 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19584 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19585 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19586 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19587 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19588 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19589 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19590 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19591 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19592 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19593 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19594 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19595 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19596 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19597 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19598 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19599 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19600 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19601 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19602 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19603 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19604 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19605 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19606 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19607 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19608 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19609 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19610 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19612 ;; All the other keys
19614 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19615 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19616 (if (boundp 'narrow-map)
19617 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19618 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19619 (if (boundp 'narrow-map)
19620 (org-defkey narrow-map "b" 'org-narrow-to-block)
19621 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19622 (if (boundp 'narrow-map)
19623 (org-defkey narrow-map "e" 'org-narrow-to-element)
19624 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19625 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19626 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19627 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19628 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19629 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19630 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19631 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19632 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19633 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19634 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19635 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19636 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19637 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19638 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19639 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19640 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19641 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19642 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19643 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19644 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19645 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19646 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19647 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19648 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19649 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19650 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19651 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19652 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19653 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19654 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19655 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19656 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19657 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19658 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19659 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19660 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19661 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19662 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19663 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19664 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19665 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19666 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19667 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19668 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19669 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19670 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19671 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19672 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19673 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19674 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19675 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19676 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19677 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19678 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19679 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19680 (org-defkey org-mode-map "\C-c^" 'org-sort)
19681 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19682 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19683 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19684 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19685 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19686 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19687 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19688 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19689 (org-defkey org-mode-map "\C-m" 'org-return)
19690 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19691 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19692 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19693 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19694 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19695 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19696 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19697 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19698 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19699 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19700 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19701 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19702 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19703 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19704 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19705 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19706 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19707 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19708 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19709 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19710 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19711 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19712 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19713 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19714 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19716 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19717 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19718 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19720 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19721 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19722 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19723 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19724 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19725 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19726 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19727 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19728 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19729 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19730 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19731 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19732 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19733 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19734 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19735 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19736 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19737 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19738 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19739 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19740 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19741 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19743 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19744 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19745 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19746 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19747 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19749 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19751 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19753 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19754 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19756 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19759 (defconst org-speed-commands-default
19761 ("Outline Navigation")
19762 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19763 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19764 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19765 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19766 ("F" . org-next-block)
19767 ("B" . org-previous-block)
19768 ("u" . (org-speed-move-safe 'outline-up-heading))
19769 ("j" . org-goto)
19770 ("g" . (org-refile t))
19771 ("Outline Visibility")
19772 ("c" . org-cycle)
19773 ("C" . org-shifttab)
19774 (" " . org-display-outline-path)
19775 ("s" . org-narrow-to-subtree)
19776 ("=" . org-columns)
19777 ("Outline Structure Editing")
19778 ("U" . org-metaup)
19779 ("D" . org-metadown)
19780 ("r" . org-metaright)
19781 ("l" . org-metaleft)
19782 ("R" . org-shiftmetaright)
19783 ("L" . org-shiftmetaleft)
19784 ("i" . (progn (forward-char 1) (call-interactively
19785 'org-insert-heading-respect-content)))
19786 ("^" . org-sort)
19787 ("w" . org-refile)
19788 ("a" . org-archive-subtree-default-with-confirmation)
19789 ("@" . org-mark-subtree)
19790 ("#" . org-toggle-comment)
19791 ("Clock Commands")
19792 ("I" . org-clock-in)
19793 ("O" . org-clock-out)
19794 ("Meta Data Editing")
19795 ("t" . org-todo)
19796 ("," . (org-priority))
19797 ("0" . (org-priority ?\ ))
19798 ("1" . (org-priority ?A))
19799 ("2" . (org-priority ?B))
19800 ("3" . (org-priority ?C))
19801 (":" . org-set-tags-command)
19802 ("e" . org-set-effort)
19803 ("E" . org-inc-effort)
19804 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19805 (org-entry-put (point) "APPT_WARNTIME" m)))
19806 ("Agenda Views etc")
19807 ("v" . org-agenda)
19808 ("/" . org-sparse-tree)
19809 ("Misc")
19810 ("o" . org-open-at-point)
19811 ("?" . org-speed-command-help)
19812 ("<" . (org-agenda-set-restriction-lock 'subtree))
19813 (">" . (org-agenda-remove-restriction-lock))
19815 "The default speed commands.")
19817 (defun org-print-speed-command (e)
19818 (if (> (length (car e)) 1)
19819 (progn
19820 (princ "\n")
19821 (princ (car e))
19822 (princ "\n")
19823 (princ (make-string (length (car e)) ?-))
19824 (princ "\n"))
19825 (princ (car e))
19826 (princ " ")
19827 (if (symbolp (cdr e))
19828 (princ (symbol-name (cdr e)))
19829 (prin1 (cdr e)))
19830 (princ "\n")))
19832 (defun org-speed-command-help ()
19833 "Show the available speed commands."
19834 (interactive)
19835 (if (not org-use-speed-commands)
19836 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19837 (with-output-to-temp-buffer "*Help*"
19838 (princ "User-defined Speed commands\n===========================\n")
19839 (mapc #'org-print-speed-command org-speed-commands-user)
19840 (princ "\n")
19841 (princ "Built-in Speed commands\n=======================\n")
19842 (mapc #'org-print-speed-command org-speed-commands-default))
19843 (with-current-buffer "*Help*"
19844 (setq truncate-lines t))))
19846 (defun org-speed-move-safe (cmd)
19847 "Execute CMD, but make sure that the cursor always ends up in a headline.
19848 If not, return to the original position and throw an error."
19849 (interactive)
19850 (let ((pos (point)))
19851 (call-interactively cmd)
19852 (unless (and (bolp) (org-at-heading-p))
19853 (goto-char pos)
19854 (error "Boundary reached while executing %s" cmd))))
19856 (defvar org-self-insert-command-undo-counter 0)
19858 (defvar org-table-auto-blank-field) ; defined in org-table.el
19859 (defvar org-speed-command nil)
19861 (defun org-speed-command-activate (keys)
19862 "Hook for activating single-letter speed commands.
19863 `org-speed-commands-default' specifies a minimal command set.
19864 Use `org-speed-commands-user' for further customization."
19865 (when (or (and (bolp) (looking-at org-outline-regexp))
19866 (and (functionp org-use-speed-commands)
19867 (funcall org-use-speed-commands)))
19868 (cdr (assoc keys (append org-speed-commands-user
19869 org-speed-commands-default)))))
19871 (defun org-babel-speed-command-activate (keys)
19872 "Hook for activating single-letter code block commands."
19873 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19874 (cdr (assoc keys org-babel-key-bindings))))
19876 (defcustom org-speed-command-hook
19877 '(org-speed-command-activate org-babel-speed-command-activate)
19878 "Hook for activating speed commands at strategic locations.
19879 Hook functions are called in sequence until a valid handler is
19880 found.
19882 Each hook takes a single argument, a user-pressed command key
19883 which is also a `self-insert-command' from the global map.
19885 Within the hook, examine the cursor position and the command key
19886 and return nil or a valid handler as appropriate. Handler could
19887 be one of an interactive command, a function, or a form.
19889 Set `org-use-speed-commands' to non-nil value to enable this
19890 hook. The default setting is `org-speed-command-activate'."
19891 :group 'org-structure
19892 :version "24.1"
19893 :type 'hook)
19895 (defun org-self-insert-command (N)
19896 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19897 If the cursor is in a table looking at whitespace, the whitespace is
19898 overwritten, and the table is not marked as requiring realignment."
19899 (interactive "p")
19900 (org-check-before-invisible-edit 'insert)
19901 (cond
19902 ((and org-use-speed-commands
19903 (let ((kv (this-command-keys-vector)))
19904 (setq org-speed-command
19905 (run-hook-with-args-until-success
19906 'org-speed-command-hook
19907 (make-string 1 (aref kv (1- (length kv))))))))
19908 (cond
19909 ((commandp org-speed-command)
19910 (setq this-command org-speed-command)
19911 (call-interactively org-speed-command))
19912 ((functionp org-speed-command)
19913 (funcall org-speed-command))
19914 ((and org-speed-command (listp org-speed-command))
19915 (eval org-speed-command))
19916 (t (let (org-use-speed-commands)
19917 (call-interactively 'org-self-insert-command)))))
19918 ((and
19919 (org-at-table-p)
19920 (progn
19921 ;; Check if we blank the field, and if that triggers align.
19922 (and (featurep 'org-table) org-table-auto-blank-field
19923 (memq last-command
19924 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19925 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19926 ;; Got extra space, this field does not determine
19927 ;; column width.
19928 (let (org-table-may-need-update) (org-table-blank-field))
19929 ;; No extra space, this field may determine column
19930 ;; width.
19931 (org-table-blank-field)))
19933 (eq N 1)
19934 (looking-at "[^|\n]* \\( \\)|"))
19935 ;; There is room for insertion without re-aligning the table.
19936 (delete-region (match-beginning 1) (match-end 1))
19937 (self-insert-command N))
19939 (setq org-table-may-need-update t)
19940 (self-insert-command N)
19941 (org-fix-tags-on-the-fly)
19942 (when org-self-insert-cluster-for-undo
19943 (if (not (eq last-command 'org-self-insert-command))
19944 (setq org-self-insert-command-undo-counter 1)
19945 (if (>= org-self-insert-command-undo-counter 20)
19946 (setq org-self-insert-command-undo-counter 1)
19947 (and (> org-self-insert-command-undo-counter 0)
19948 buffer-undo-list (listp buffer-undo-list)
19949 (not (cadr buffer-undo-list)) ; remove nil entry
19950 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19951 (setq org-self-insert-command-undo-counter
19952 (1+ org-self-insert-command-undo-counter))))))))
19954 (defun org-check-before-invisible-edit (kind)
19955 "Check is editing if kind KIND would be dangerous with invisible text around.
19956 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19957 ;; First, try to get out of here as quickly as possible, to reduce overhead
19958 (when (and org-catch-invisible-edits
19959 (or (not (boundp 'visible-mode)) (not visible-mode))
19960 (or (get-char-property (point) 'invisible)
19961 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19962 ;; OK, we need to take a closer look. Do not consider
19963 ;; invisibility obtained through text properties (e.g., link
19964 ;; fontification), as it cannot be toggled.
19965 (let* ((invisible-at-point
19966 (pcase (get-char-property-and-overlay (point) 'invisible)
19967 (`(,_ . ,(and (pred overlayp) o)) o)))
19968 ;; Assume that point cannot land in the middle of an
19969 ;; overlay, or between two overlays.
19970 (invisible-before-point
19971 (and (not invisible-at-point)
19972 (not (bobp))
19973 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19974 (`(,_ . ,(and (pred overlayp) o)) o))))
19975 (border-and-ok-direction
19977 ;; Check if we are acting predictably before invisible
19978 ;; text.
19979 (and invisible-at-point
19980 (memq kind '(insert delete-backward)))
19981 ;; Check if we are acting predictably after invisible text
19982 ;; This works not well, and I have turned it off. It seems
19983 ;; better to always show and stop after invisible text.
19984 ;; (and (not invisible-at-point) invisible-before-point
19985 ;; (memq kind '(insert delete)))
19987 (when (or invisible-at-point invisible-before-point)
19988 (when (eq org-catch-invisible-edits 'error)
19989 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19990 (if (and org-custom-properties-overlays
19991 (y-or-n-p "Display invisible properties in this buffer? "))
19992 (org-toggle-custom-properties-visibility)
19993 ;; Make the area visible
19994 (save-excursion
19995 (when invisible-before-point
19996 (goto-char
19997 (previous-single-char-property-change (point) 'invisible)))
19998 ;; Remove whatever overlay is currently making yet-to-be
19999 ;; edited text invisible. Also remove nested invisibility
20000 ;; related overlays.
20001 (delete-overlay (or invisible-at-point invisible-before-point))
20002 (let ((origin (if invisible-at-point (point) (1- (point)))))
20003 (while (pcase (get-char-property-and-overlay origin 'invisible)
20004 (`(,_ . ,(and (pred overlayp) o))
20005 (delete-overlay o)
20006 t)))))
20007 (cond
20008 ((eq org-catch-invisible-edits 'show)
20009 ;; That's it, we do the edit after showing
20010 (message
20011 "Unfolding invisible region around point before editing")
20012 (sit-for 1))
20013 ((and (eq org-catch-invisible-edits 'smart)
20014 border-and-ok-direction)
20015 (message "Unfolding invisible region around point before editing"))
20017 ;; Don't do the edit, make the user repeat it in full visibility
20018 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20020 (defun org-fix-tags-on-the-fly ()
20021 "Align tags in headline at point.
20022 Unlike to `org-set-tags', it ignores region and sorting."
20023 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20024 (org-at-heading-p))
20025 (let ((org-ignore-region t)
20026 (org-tags-sort-function nil))
20027 (org-set-tags nil t))))
20029 (defun org-delete-backward-char (N)
20030 "Like `delete-backward-char', insert whitespace at field end in tables.
20031 When deleting backwards, in tables this function will insert whitespace in
20032 front of the next \"|\" separator, to keep the table aligned. The table will
20033 still be marked for re-alignment if the field did fill the entire column,
20034 because, in this case the deletion might narrow the column."
20035 (interactive "p")
20036 (save-match-data
20037 (org-check-before-invisible-edit 'delete-backward)
20038 (if (and (org-at-table-p)
20039 (eq N 1)
20040 (string-match "|" (buffer-substring (point-at-bol) (point)))
20041 (looking-at ".*?|"))
20042 (let ((pos (point))
20043 (noalign (looking-at "[^|\n\r]* |"))
20044 (c org-table-may-need-update))
20045 (backward-delete-char N)
20046 (unless overwrite-mode
20047 (skip-chars-forward "^|")
20048 (insert " ")
20049 (goto-char (1- pos)))
20050 ;; noalign: if there were two spaces at the end, this field
20051 ;; does not determine the width of the column.
20052 (when noalign (setq org-table-may-need-update c)))
20053 (backward-delete-char N)
20054 (org-fix-tags-on-the-fly))))
20056 (defun org-delete-char (N)
20057 "Like `delete-char', but insert whitespace at field end in tables.
20058 When deleting characters, in tables this function will insert whitespace in
20059 front of the next \"|\" separator, to keep the table aligned. The table will
20060 still be marked for re-alignment if the field did fill the entire column,
20061 because, in this case the deletion might narrow the column."
20062 (interactive "p")
20063 (save-match-data
20064 (org-check-before-invisible-edit 'delete)
20065 (if (and (org-at-table-p)
20066 (not (bolp))
20067 (not (= (char-after) ?|))
20068 (eq N 1))
20069 (if (looking-at ".*?|")
20070 (let ((pos (point))
20071 (noalign (looking-at "[^|\n\r]* |"))
20072 (c org-table-may-need-update))
20073 (replace-match
20074 (concat (substring (match-string 0) 1 -1) " |") nil t)
20075 (goto-char pos)
20076 ;; noalign: if there were two spaces at the end, this field
20077 ;; does not determine the width of the column.
20078 (when noalign (setq org-table-may-need-update c)))
20079 (delete-char N))
20080 (delete-char N)
20081 (org-fix-tags-on-the-fly))))
20083 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20084 (put 'org-self-insert-command 'delete-selection
20085 (lambda ()
20086 (not (run-hook-with-args-until-success
20087 'self-insert-uses-region-functions))))
20088 (put 'orgtbl-self-insert-command 'delete-selection
20089 (lambda ()
20090 (not (run-hook-with-args-until-success
20091 'self-insert-uses-region-functions))))
20092 (put 'org-delete-char 'delete-selection 'supersede)
20093 (put 'org-delete-backward-char 'delete-selection 'supersede)
20094 (put 'org-yank 'delete-selection 'yank)
20096 ;; Make `flyspell-mode' delay after some commands
20097 (put 'org-self-insert-command 'flyspell-delayed t)
20098 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20099 (put 'org-delete-char 'flyspell-delayed t)
20100 (put 'org-delete-backward-char 'flyspell-delayed t)
20102 ;; Make pabbrev-mode expand after Org mode commands
20103 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20104 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20106 (defun org-remap (map &rest commands)
20107 "In MAP, remap the functions given in COMMANDS.
20108 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20109 (let (new old)
20110 (while commands
20111 (setq old (pop commands) new (pop commands))
20112 (org-defkey map (vector 'remap old) new))))
20114 (defun org-transpose-words ()
20115 "Transpose words for Org.
20116 This uses the `org-mode-transpose-word-syntax-table' syntax
20117 table, which interprets characters in `org-emphasis-alist' as
20118 word constituents."
20119 (interactive)
20120 (with-syntax-table org-mode-transpose-word-syntax-table
20121 (call-interactively 'transpose-words)))
20122 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20124 (when (eq org-enable-table-editor 'optimized)
20125 ;; If the user wants maximum table support, we need to hijack
20126 ;; some standard editing functions
20127 (org-remap org-mode-map
20128 'self-insert-command 'org-self-insert-command
20129 'delete-char 'org-delete-char
20130 'delete-backward-char 'org-delete-backward-char)
20131 (org-defkey org-mode-map "|" 'org-force-self-insert))
20133 (defvar org-ctrl-c-ctrl-c-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 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20139 run after the last 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-ctrl-c-ctrl-c-final-hook nil
20147 "Hook for functions attaching themselves to `C-c C-c'.
20149 This can be used to add additional functionality to the C-c C-c
20150 key which executes context-dependent commands. This hook is run
20151 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20152 before the first test.
20154 Each function will be called with no arguments. The function
20155 must check if the context is appropriate for it to act. If yes,
20156 it should do its thing and then return a non-nil value. If the
20157 context is wrong, just do nothing and return nil.")
20159 (defvar org-tab-first-hook nil
20160 "Hook for functions to attach themselves to TAB.
20161 See `org-ctrl-c-ctrl-c-hook' for more information.
20162 This hook runs as the first action when TAB is pressed, even before
20163 `org-cycle' messes around with the `outline-regexp' to cater for
20164 inline tasks and plain list item folding.
20165 If any function in this hook returns t, any other actions that
20166 would have been caused by TAB (such as table field motion or visibility
20167 cycling) will not occur.")
20169 (defvar org-tab-after-check-for-table-hook nil
20170 "Hook for functions to attach themselves to TAB.
20171 See `org-ctrl-c-ctrl-c-hook' for more information.
20172 This hook runs after it has been established that the cursor is not in a
20173 table, but before checking if the cursor is in a headline or if global cycling
20174 should be done.
20175 If any function in this hook returns t, not other actions like visibility
20176 cycling will be done.")
20178 (defvar org-tab-after-check-for-cycling-hook nil
20179 "Hook for functions to attach themselves to TAB.
20180 See `org-ctrl-c-ctrl-c-hook' for more information.
20181 This hook runs after it has been established that not table field motion and
20182 not visibility should be done because of current context. This is probably
20183 the place where a package like yasnippets can hook in.")
20185 (defvar org-tab-before-tab-emulation-hook nil
20186 "Hook for functions to attach themselves to TAB.
20187 See `org-ctrl-c-ctrl-c-hook' for more information.
20188 This hook runs after every other options for TAB have been exhausted, but
20189 before indentation and \t insertion takes place.")
20191 (defvar org-metaleft-hook nil
20192 "Hook for functions attaching themselves to `M-left'.
20193 See `org-ctrl-c-ctrl-c-hook' for more information.")
20194 (defvar org-metaright-hook nil
20195 "Hook for functions attaching themselves to `M-right'.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20197 (defvar org-metaup-hook nil
20198 "Hook for functions attaching themselves to `M-up'.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-metadown-hook nil
20201 "Hook for functions attaching themselves to `M-down'.
20202 See `org-ctrl-c-ctrl-c-hook' for more information.")
20203 (defvar org-shiftmetaleft-hook nil
20204 "Hook for functions attaching themselves to `M-S-left'.
20205 See `org-ctrl-c-ctrl-c-hook' for more information.")
20206 (defvar org-shiftmetaright-hook nil
20207 "Hook for functions attaching themselves to `M-S-right'.
20208 See `org-ctrl-c-ctrl-c-hook' for more information.")
20209 (defvar org-shiftmetaup-hook nil
20210 "Hook for functions attaching themselves to `M-S-up'.
20211 See `org-ctrl-c-ctrl-c-hook' for more information.")
20212 (defvar org-shiftmetadown-hook nil
20213 "Hook for functions attaching themselves to `M-S-down'.
20214 See `org-ctrl-c-ctrl-c-hook' for more information.")
20215 (defvar org-metareturn-hook nil
20216 "Hook for functions attaching themselves to `M-RET'.
20217 See `org-ctrl-c-ctrl-c-hook' for more information.")
20218 (defvar org-shiftup-hook nil
20219 "Hook for functions attaching themselves to `S-up'.
20220 See `org-ctrl-c-ctrl-c-hook' for more information.")
20221 (defvar org-shiftup-final-hook nil
20222 "Hook for functions attaching themselves to `S-up'.
20223 This one runs after all other options except shift-select have been excluded.
20224 See `org-ctrl-c-ctrl-c-hook' for more information.")
20225 (defvar org-shiftdown-hook nil
20226 "Hook for functions attaching themselves to `S-down'.
20227 See `org-ctrl-c-ctrl-c-hook' for more information.")
20228 (defvar org-shiftdown-final-hook nil
20229 "Hook for functions attaching themselves to `S-down'.
20230 This one runs after all other options except shift-select have been excluded.
20231 See `org-ctrl-c-ctrl-c-hook' for more information.")
20232 (defvar org-shiftleft-hook nil
20233 "Hook for functions attaching themselves to `S-left'.
20234 See `org-ctrl-c-ctrl-c-hook' for more information.")
20235 (defvar org-shiftleft-final-hook nil
20236 "Hook for functions attaching themselves to `S-left'.
20237 This one runs after all other options except shift-select have been excluded.
20238 See `org-ctrl-c-ctrl-c-hook' for more information.")
20239 (defvar org-shiftright-hook nil
20240 "Hook for functions attaching themselves to `S-right'.
20241 See `org-ctrl-c-ctrl-c-hook' for more information.")
20242 (defvar org-shiftright-final-hook nil
20243 "Hook for functions attaching themselves to `S-right'.
20244 This one runs after all other options except shift-select have been excluded.
20245 See `org-ctrl-c-ctrl-c-hook' for more information.")
20247 (defun org-modifier-cursor-error ()
20248 "Throw an error, a modified cursor command was applied in wrong context."
20249 (user-error "This command is active in special context like tables, headlines or items"))
20251 (defun org-shiftselect-error ()
20252 "Throw an error because Shift-Cursor command was applied in wrong context."
20253 (if (and (boundp 'shift-select-mode) shift-select-mode)
20254 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20255 (user-error "This command works only in special context like headlines or timestamps")))
20257 (defun org-call-for-shift-select (cmd)
20258 (let ((this-command-keys-shift-translated t))
20259 (call-interactively cmd)))
20261 (defun org-shifttab (&optional arg)
20262 "Global visibility cycling or move to previous table field.
20263 Call `org-table-previous-field' within a table.
20264 When ARG is nil, cycle globally through visibility states.
20265 When ARG is a numeric prefix, show contents of this level."
20266 (interactive "P")
20267 (cond
20268 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20269 ((integerp arg)
20270 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20271 (message "Content view to level: %d" arg)
20272 (org-content (prefix-numeric-value arg2))
20273 (org-cycle-show-empty-lines t)
20274 (setq org-cycle-global-status 'overview)))
20275 (t (call-interactively 'org-global-cycle))))
20277 (defun org-shiftmetaleft ()
20278 "Promote subtree or delete table column.
20279 Calls `org-promote-subtree', `org-outdent-item-tree', or
20280 `org-table-delete-column', depending on context. See the
20281 individual commands for more information."
20282 (interactive)
20283 (cond
20284 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20285 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20286 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20287 ((if (not (org-region-active-p)) (org-at-item-p)
20288 (save-excursion (goto-char (region-beginning))
20289 (org-at-item-p)))
20290 (call-interactively 'org-outdent-item-tree))
20291 (t (org-modifier-cursor-error))))
20293 (defun org-shiftmetaright ()
20294 "Demote subtree or insert table column.
20295 Calls `org-demote-subtree', `org-indent-item-tree', or
20296 `org-table-insert-column', depending on context. See the
20297 individual commands for more information."
20298 (interactive)
20299 (cond
20300 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20301 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20302 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20303 ((if (not (org-region-active-p)) (org-at-item-p)
20304 (save-excursion (goto-char (region-beginning))
20305 (org-at-item-p)))
20306 (call-interactively 'org-indent-item-tree))
20307 (t (org-modifier-cursor-error))))
20309 (defun org-shiftmetaup (&optional _arg)
20310 "Drag the line at point up.
20311 In a table, kill the current row.
20312 On a clock timestamp, update the value of the timestamp like `S-<up>'
20313 but also adjust the previous clocked item in the clock history.
20314 Everywhere else, drag the line at point up."
20315 (interactive "P")
20316 (cond
20317 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20318 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20319 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20320 (call-interactively 'org-timestamp-up)))
20321 (t (call-interactively 'org-drag-line-backward))))
20323 (defun org-shiftmetadown (&optional _arg)
20324 "Drag the line at point down.
20325 In a table, insert an empty row at the current line.
20326 On a clock timestamp, update the value of the timestamp like `S-<down>'
20327 but also adjust the previous clocked item in the clock history.
20328 Everywhere else, drag the line at point down."
20329 (interactive "P")
20330 (cond
20331 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20332 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20333 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20334 (call-interactively 'org-timestamp-down)))
20335 (t (call-interactively 'org-drag-line-forward))))
20337 (defsubst org-hidden-tree-error ()
20338 (user-error
20339 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20341 (defun org-metaleft (&optional _arg)
20342 "Promote heading, list item at point or move table column left.
20344 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20345 depending on context. With no specific context, calls the Emacs
20346 default `backward-word'. See the individual commands for more
20347 information.
20349 This function runs the hook `org-metaleft-hook' as a first step,
20350 and returns at first non-nil value."
20351 (interactive "P")
20352 (cond
20353 ((run-hook-with-args-until-success 'org-metaleft-hook))
20354 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20355 ((org-with-limited-levels
20356 (or (org-at-heading-p)
20357 (and (org-region-active-p)
20358 (save-excursion
20359 (goto-char (region-beginning))
20360 (org-at-heading-p)))))
20361 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20362 (call-interactively 'org-do-promote))
20363 ;; At an inline task.
20364 ((org-at-heading-p)
20365 (call-interactively 'org-inlinetask-promote))
20366 ((or (org-at-item-p)
20367 (and (org-region-active-p)
20368 (save-excursion
20369 (goto-char (region-beginning))
20370 (org-at-item-p))))
20371 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20372 (call-interactively 'org-outdent-item))
20373 (t (call-interactively 'backward-word))))
20375 (defun org-metaright (&optional _arg)
20376 "Demote heading, list item at point or move table column right.
20378 In front of a drawer or a block keyword, indent it correctly.
20380 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20381 `org-indent-drawer' or `org-indent-block' depending on context.
20382 With no specific context, calls the Emacs default `forward-word'.
20383 See the individual commands for more information.
20385 This function runs the hook `org-metaright-hook' as a first step,
20386 and returns at first non-nil value."
20387 (interactive "P")
20388 (cond
20389 ((run-hook-with-args-until-success 'org-metaright-hook))
20390 ((org-at-table-p) (call-interactively 'org-table-move-column))
20391 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20392 ((org-at-block-p) (call-interactively 'org-indent-block))
20393 ((org-with-limited-levels
20394 (or (org-at-heading-p)
20395 (and (org-region-active-p)
20396 (save-excursion
20397 (goto-char (region-beginning))
20398 (org-at-heading-p)))))
20399 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20400 (call-interactively 'org-do-demote))
20401 ;; At an inline task.
20402 ((org-at-heading-p)
20403 (call-interactively 'org-inlinetask-demote))
20404 ((or (org-at-item-p)
20405 (and (org-region-active-p)
20406 (save-excursion
20407 (goto-char (region-beginning))
20408 (org-at-item-p))))
20409 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20410 (call-interactively 'org-indent-item))
20411 (t (call-interactively 'forward-word))))
20413 (defun org-check-for-hidden (what)
20414 "Check if there are hidden headlines/items in the current visual line.
20415 WHAT can be either `headlines' or `items'. If the current line is
20416 an outline or item heading and it has a folded subtree below it,
20417 this function returns t, nil otherwise."
20418 (let ((re (cond
20419 ((eq what 'headlines) org-outline-regexp-bol)
20420 ((eq what 'items) (org-item-beginning-re))
20421 (t (error "This should not happen"))))
20422 beg end)
20423 (save-excursion
20424 (catch 'exit
20425 (unless (org-region-active-p)
20426 (setq beg (point-at-bol))
20427 (beginning-of-line 2)
20428 (while (and (not (eobp)) ;; this is like `next-line'
20429 (get-char-property (1- (point)) 'invisible))
20430 (beginning-of-line 2))
20431 (setq end (point))
20432 (goto-char beg)
20433 (goto-char (point-at-eol))
20434 (setq end (max end (point)))
20435 (while (re-search-forward re end t)
20436 (when (get-char-property (match-beginning 0) 'invisible)
20437 (throw 'exit t))))
20438 nil))))
20440 (defun org-metaup (&optional _arg)
20441 "Move subtree up or move table row up.
20442 Calls `org-move-subtree-up' or `org-table-move-row' or
20443 `org-move-item-up', depending on context. See the individual commands
20444 for more information."
20445 (interactive "P")
20446 (cond
20447 ((run-hook-with-args-until-success 'org-metaup-hook))
20448 ((org-region-active-p)
20449 (let* ((a (min (region-beginning) (region-end)))
20450 (b (1- (max (region-beginning) (region-end))))
20451 (c (save-excursion (goto-char a)
20452 (move-beginning-of-line 0)))
20453 (d (save-excursion (goto-char a)
20454 (move-end-of-line 0) (point))))
20455 (transpose-regions a b c d)
20456 (goto-char c)))
20457 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20458 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20459 ((org-at-item-p) (call-interactively 'org-move-item-up))
20460 (t (org-drag-element-backward))))
20462 (defun org-metadown (&optional _arg)
20463 "Move subtree down or move table row down.
20464 Calls `org-move-subtree-down' or `org-table-move-row' or
20465 `org-move-item-down', depending on context. See the individual
20466 commands for more information."
20467 (interactive "P")
20468 (cond
20469 ((run-hook-with-args-until-success 'org-metadown-hook))
20470 ((org-region-active-p)
20471 (let* ((a (min (region-beginning) (region-end)))
20472 (b (max (region-beginning) (region-end)))
20473 (c (save-excursion (goto-char b)
20474 (move-beginning-of-line 1)))
20475 (d (save-excursion (goto-char b)
20476 (move-end-of-line 1) (1+ (point)))))
20477 (transpose-regions a b c d)
20478 (goto-char d)))
20479 ((org-at-table-p) (call-interactively 'org-table-move-row))
20480 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20481 ((org-at-item-p) (call-interactively 'org-move-item-down))
20482 (t (org-drag-element-forward))))
20484 (defun org-shiftup (&optional arg)
20485 "Increase item in timestamp or increase priority of current headline.
20486 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20487 depending on context. See the individual commands for more information."
20488 (interactive "P")
20489 (cond
20490 ((run-hook-with-args-until-success 'org-shiftup-hook))
20491 ((and org-support-shift-select (org-region-active-p))
20492 (org-call-for-shift-select 'previous-line))
20493 ((org-at-timestamp-p 'lax)
20494 (call-interactively (if org-edit-timestamp-down-means-later
20495 'org-timestamp-down 'org-timestamp-up)))
20496 ((and (not (eq org-support-shift-select 'always))
20497 org-enable-priority-commands
20498 (org-at-heading-p))
20499 (call-interactively 'org-priority-up))
20500 ((and (not org-support-shift-select) (org-at-item-p))
20501 (call-interactively 'org-previous-item))
20502 ((org-clocktable-try-shift 'up arg))
20503 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20504 (org-support-shift-select
20505 (org-call-for-shift-select 'previous-line))
20506 (t (org-shiftselect-error))))
20508 (defun org-shiftdown (&optional arg)
20509 "Decrease item in timestamp or decrease priority of current headline.
20510 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20511 depending on context. See the individual commands for more information."
20512 (interactive "P")
20513 (cond
20514 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20515 ((and org-support-shift-select (org-region-active-p))
20516 (org-call-for-shift-select 'next-line))
20517 ((org-at-timestamp-p 'lax)
20518 (call-interactively (if org-edit-timestamp-down-means-later
20519 'org-timestamp-up 'org-timestamp-down)))
20520 ((and (not (eq org-support-shift-select 'always))
20521 org-enable-priority-commands
20522 (org-at-heading-p))
20523 (call-interactively 'org-priority-down))
20524 ((and (not org-support-shift-select) (org-at-item-p))
20525 (call-interactively 'org-next-item))
20526 ((org-clocktable-try-shift 'down arg))
20527 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20528 (org-support-shift-select
20529 (org-call-for-shift-select 'next-line))
20530 (t (org-shiftselect-error))))
20532 (defun org-shiftright (&optional arg)
20533 "Cycle the thing at point or in the current line, depending on context.
20534 Depending on context, this does one of the following:
20536 - switch a timestamp at point one day into the future
20537 - on a headline, switch to the next TODO keyword.
20538 - on an item, switch entire list to the next bullet type
20539 - on a property line, switch to the next allowed value
20540 - on a clocktable definition line, move time block into the future"
20541 (interactive "P")
20542 (cond
20543 ((run-hook-with-args-until-success 'org-shiftright-hook))
20544 ((and org-support-shift-select (org-region-active-p))
20545 (org-call-for-shift-select 'forward-char))
20546 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20547 ((and (not (eq org-support-shift-select 'always))
20548 (org-at-heading-p))
20549 (let ((org-inhibit-logging
20550 (not org-treat-S-cursor-todo-selection-as-state-change))
20551 (org-inhibit-blocking
20552 (not org-treat-S-cursor-todo-selection-as-state-change)))
20553 (org-call-with-arg 'org-todo 'right)))
20554 ((or (and org-support-shift-select
20555 (not (eq org-support-shift-select 'always))
20556 (org-at-item-bullet-p))
20557 (and (not org-support-shift-select) (org-at-item-p)))
20558 (org-call-with-arg 'org-cycle-list-bullet nil))
20559 ((and (not (eq org-support-shift-select 'always))
20560 (org-at-property-p))
20561 (call-interactively 'org-property-next-allowed-value))
20562 ((org-clocktable-try-shift 'right arg))
20563 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20564 (org-support-shift-select
20565 (org-call-for-shift-select 'forward-char))
20566 (t (org-shiftselect-error))))
20568 (defun org-shiftleft (&optional arg)
20569 "Cycle the thing at point or in the current line, depending on context.
20570 Depending on context, this does one of the following:
20572 - switch a timestamp at point one day into the past
20573 - on a headline, switch to the previous TODO keyword.
20574 - on an item, switch entire list to the previous bullet type
20575 - on a property line, switch to the previous allowed value
20576 - on a clocktable definition line, move time block into the past"
20577 (interactive "P")
20578 (cond
20579 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20580 ((and org-support-shift-select (org-region-active-p))
20581 (org-call-for-shift-select 'backward-char))
20582 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20583 ((and (not (eq org-support-shift-select 'always))
20584 (org-at-heading-p))
20585 (let ((org-inhibit-logging
20586 (not org-treat-S-cursor-todo-selection-as-state-change))
20587 (org-inhibit-blocking
20588 (not org-treat-S-cursor-todo-selection-as-state-change)))
20589 (org-call-with-arg 'org-todo 'left)))
20590 ((or (and org-support-shift-select
20591 (not (eq org-support-shift-select 'always))
20592 (org-at-item-bullet-p))
20593 (and (not org-support-shift-select) (org-at-item-p)))
20594 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20595 ((and (not (eq org-support-shift-select 'always))
20596 (org-at-property-p))
20597 (call-interactively 'org-property-previous-allowed-value))
20598 ((org-clocktable-try-shift 'left arg))
20599 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20600 (org-support-shift-select
20601 (org-call-for-shift-select 'backward-char))
20602 (t (org-shiftselect-error))))
20604 (defun org-shiftcontrolright ()
20605 "Switch to next TODO set."
20606 (interactive)
20607 (cond
20608 ((and org-support-shift-select (org-region-active-p))
20609 (org-call-for-shift-select 'forward-word))
20610 ((and (not (eq org-support-shift-select 'always))
20611 (org-at-heading-p))
20612 (org-call-with-arg 'org-todo 'nextset))
20613 (org-support-shift-select
20614 (org-call-for-shift-select 'forward-word))
20615 (t (org-shiftselect-error))))
20617 (defun org-shiftcontrolleft ()
20618 "Switch to previous TODO set."
20619 (interactive)
20620 (cond
20621 ((and org-support-shift-select (org-region-active-p))
20622 (org-call-for-shift-select 'backward-word))
20623 ((and (not (eq org-support-shift-select 'always))
20624 (org-at-heading-p))
20625 (org-call-with-arg 'org-todo 'previousset))
20626 (org-support-shift-select
20627 (org-call-for-shift-select 'backward-word))
20628 (t (org-shiftselect-error))))
20630 (defun org-shiftcontrolup (&optional n)
20631 "Change timestamps synchronously up in CLOCK log lines.
20632 Optional argument N tells to change by that many units."
20633 (interactive "P")
20634 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20635 (let (org-support-shift-select)
20636 (org-clock-timestamps-up n))
20637 (user-error "Not at a clock log")))
20639 (defun org-shiftcontroldown (&optional n)
20640 "Change timestamps synchronously down in CLOCK log lines.
20641 Optional argument N tells to change by that many units."
20642 (interactive "P")
20643 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20644 (let (org-support-shift-select)
20645 (org-clock-timestamps-down n))
20646 (user-error "Not at a clock log")))
20648 (defun org-increase-number-at-point (&optional inc)
20649 "Increment the number at point.
20650 With an optional prefix numeric argument INC, increment using
20651 this numeric value."
20652 (interactive "p")
20653 (if (not (number-at-point))
20654 (user-error "Not on a number")
20655 (unless inc (setq inc 1))
20656 (let ((pos (point))
20657 (beg (skip-chars-backward "-+^/*0-9eE."))
20658 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20659 (setq nap (buffer-substring-no-properties
20660 (+ pos beg) (+ pos beg end)))
20661 (delete-region (+ pos beg) (+ pos beg end))
20662 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20663 (when (org-at-table-p)
20664 (org-table-align)
20665 (org-table-end-of-field 1))))
20667 (defun org-decrease-number-at-point (&optional inc)
20668 "Decrement the number at point.
20669 With an optional prefix numeric argument INC, decrement using
20670 this numeric value."
20671 (interactive "p")
20672 (org-increase-number-at-point (- (or inc 1))))
20674 (defun org-ctrl-c-ret ()
20675 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20676 (interactive)
20677 (cond
20678 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20679 (t (call-interactively 'org-insert-heading))))
20681 (defun org-find-visible ()
20682 (let ((s (point)))
20683 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20684 (get-char-property s 'invisible)))
20686 (defun org-find-invisible ()
20687 (let ((s (point)))
20688 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20689 (not (get-char-property s 'invisible))))
20692 (defun org-copy-visible (beg end)
20693 "Copy the visible parts of the region."
20694 (interactive "r")
20695 (let (snippets s)
20696 (save-excursion
20697 (save-restriction
20698 (narrow-to-region beg end)
20699 (setq s (goto-char (point-min)))
20700 (while (not (= (point) (point-max)))
20701 (goto-char (org-find-invisible))
20702 (push (buffer-substring s (point)) snippets)
20703 (setq s (goto-char (org-find-visible))))))
20704 (kill-new (apply 'concat (nreverse snippets)))))
20706 (defun org-copy-special ()
20707 "Copy region in table or copy current subtree.
20708 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20709 context. See the individual commands for more information."
20710 (interactive)
20711 (call-interactively
20712 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20714 (defun org-cut-special ()
20715 "Cut region in table or cut current subtree.
20716 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20717 context. See the individual commands for more information."
20718 (interactive)
20719 (call-interactively
20720 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20722 (defun org-paste-special (arg)
20723 "Paste rectangular region into table, or past subtree relative to level.
20724 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20725 See the individual commands for more information."
20726 (interactive "P")
20727 (if (org-at-table-p)
20728 (org-table-paste-rectangle)
20729 (org-paste-subtree arg)))
20731 (defun org-edit-special (&optional arg)
20732 "Call a special editor for the element at point.
20733 When at a table, call the formula editor with `org-table-edit-formulas'.
20734 When in a source code block, call `org-edit-src-code'.
20735 When in a fixed-width region, call `org-edit-fixed-width-region'.
20736 When in an export block, call `org-edit-export-block'.
20737 When in a LaTeX environment, call `org-edit-latex-environment'.
20738 When at an #+INCLUDE keyword, visit the included file.
20739 When at a footnote reference, call `org-edit-footnote-reference'
20740 On a link, call `ffap' to visit the link at point.
20741 Otherwise, return a user error."
20742 (interactive "P")
20743 (let ((element (org-element-at-point)))
20744 (barf-if-buffer-read-only)
20745 (pcase (org-element-type element)
20746 (`src-block
20747 (if (not arg) (org-edit-src-code)
20748 (let* ((info (org-babel-get-src-block-info))
20749 (lang (nth 0 info))
20750 (params (nth 2 info))
20751 (session (cdr (assq :session params))))
20752 (if (not session) (org-edit-src-code)
20753 ;; At a src-block with a session and function called with
20754 ;; an ARG: switch to the buffer related to the inferior
20755 ;; process.
20756 (switch-to-buffer
20757 (funcall (intern (concat "org-babel-prep-session:" lang))
20758 session params))))))
20759 (`keyword
20760 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20761 (org-open-link-from-string
20762 (format "[[%s]]"
20763 (expand-file-name
20764 (let ((value (org-element-property :value element)))
20765 (cond ((org-file-url-p value)
20766 (user-error "The file is specified as a URL, cannot be edited"))
20767 ((not (org-string-nw-p value))
20768 (user-error "No file to edit"))
20769 ((string-match "\\`\"\\(.*?\\)\"" value)
20770 (match-string 1 value))
20771 ((string-match "\\`[^ \t\"]\\S-*" value)
20772 (match-string 0 value))
20773 (t (user-error "No valid file specified")))))))
20774 (user-error "No special environment to edit here")))
20775 (`table
20776 (if (eq (org-element-property :type element) 'table.el)
20777 (org-edit-table.el)
20778 (call-interactively 'org-table-edit-formulas)))
20779 ;; Only Org tables contain `table-row' type elements.
20780 (`table-row (call-interactively 'org-table-edit-formulas))
20781 (`example-block (org-edit-src-code))
20782 (`export-block (org-edit-export-block))
20783 (`fixed-width (org-edit-fixed-width-region))
20784 (`latex-environment (org-edit-latex-environment))
20786 ;; No notable element at point. Though, we may be at a link or
20787 ;; a footnote reference, which are objects. Thus, scan deeper.
20788 (let ((context (org-element-context element)))
20789 (pcase (org-element-type context)
20790 (`footnote-reference (org-edit-footnote-reference))
20791 (`inline-src-block (org-edit-inline-src-code))
20792 (`link (call-interactively #'ffap))
20793 (_ (user-error "No special environment to edit here"))))))))
20795 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20796 (defun org-ctrl-c-ctrl-c (&optional arg)
20797 "Set tags in headline, or update according to changed information at point.
20799 This command does many different things, depending on context:
20801 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20802 this is what we do.
20804 - If the cursor is on a statistics cookie, update it.
20806 - If the cursor is in a headline, prompt for tags and insert them
20807 into the current line, aligned to `org-tags-column'. When called
20808 with prefix arg, realign all tags in the current buffer.
20810 - If the cursor is in one of the special #+KEYWORD lines, this
20811 triggers scanning the buffer for these lines and updating the
20812 information.
20814 - If the cursor is inside a table, realign the table. This command
20815 works even if the automatic table editor has been turned off.
20817 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20818 the entire table.
20820 - If the cursor is at a footnote reference or definition, jump to
20821 the corresponding definition or references, respectively.
20823 - If the cursor is a the beginning of a dynamic block, update it.
20825 - If the current buffer is a capture buffer, close note and file it.
20827 - If the cursor is on a <<<target>>>, update radio targets and
20828 corresponding links in this buffer.
20830 - If the cursor is on a numbered item in a plain list, renumber the
20831 ordered list.
20833 - If the cursor is on a checkbox, toggle it.
20835 - If the cursor is on a code block, evaluate it. The variable
20836 `org-confirm-babel-evaluate' can be used to control prompting
20837 before code block evaluation, by default every code block
20838 evaluation requires confirmation. Code block evaluation can be
20839 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20840 (interactive "P")
20841 (cond
20842 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20843 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20844 (org-remove-occur-highlights)
20845 (message "Temporary highlights/overlays removed from current buffer"))
20846 ((and (local-variable-p 'org-finish-function)
20847 (fboundp org-finish-function))
20848 (funcall org-finish-function))
20849 ((org-babel-hash-at-point))
20850 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20852 (let* ((context
20853 (org-element-lineage
20854 (org-element-context)
20855 ;; Limit to supported contexts.
20856 '(babel-call clock dynamic-block footnote-definition
20857 footnote-reference inline-babel-call inline-src-block
20858 inlinetask item keyword node-property paragraph
20859 plain-list property-drawer radio-target src-block
20860 statistics-cookie table table-cell table-row
20861 timestamp)
20863 (type (org-element-type context)))
20864 ;; For convenience: at the first line of a paragraph on the same
20865 ;; line as an item, apply function on that item instead.
20866 (when (eq type 'paragraph)
20867 (let ((parent (org-element-property :parent context)))
20868 (when (and (eq (org-element-type parent) 'item)
20869 (= (line-beginning-position)
20870 (org-element-property :begin parent)))
20871 (setq context parent)
20872 (setq type 'item))))
20873 ;; Act according to type of element or object at point.
20875 ;; Do nothing on a blank line, except if it is contained in
20876 ;; a src block. Hence, we first check if point is in such
20877 ;; a block and then if it is at a blank line.
20878 (pcase type
20879 ((or `inline-src-block `src-block)
20880 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20881 (org-babel-eval-wipe-error-buffer)
20882 (org-babel-execute-src-block
20883 current-prefix-arg (org-babel-get-src-block-info nil context))))
20884 ((guard (org-match-line "[ \t]*$"))
20885 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20886 (user-error
20887 (substitute-command-keys
20888 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20889 ((or `babel-call `inline-babel-call)
20890 (let ((info (org-babel-lob-get-info context)))
20891 (when info (org-babel-execute-src-block nil info))))
20892 (`clock (org-clock-update-time-maybe))
20893 (`dynamic-block
20894 (save-excursion
20895 (goto-char (org-element-property :post-affiliated context))
20896 (org-update-dblock)))
20897 (`footnote-definition
20898 (goto-char (org-element-property :post-affiliated context))
20899 (call-interactively 'org-footnote-action))
20900 (`footnote-reference (call-interactively #'org-footnote-action))
20901 ((or `headline `inlinetask)
20902 (save-excursion (goto-char (org-element-property :begin context))
20903 (call-interactively #'org-set-tags)))
20904 (`item
20905 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20906 ;; unconditionally, whereas `C-u' will toggle its presence.
20907 ;; Without a universal argument, if the item has a checkbox,
20908 ;; toggle it. Otherwise repair the list.
20909 (let* ((box (org-element-property :checkbox context))
20910 (struct (org-element-property :structure context))
20911 (old-struct (copy-tree struct))
20912 (parents (org-list-parents-alist struct))
20913 (prevs (org-list-prevs-alist struct))
20914 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20915 (org-list-set-checkbox
20916 (org-element-property :begin context) struct
20917 (cond ((equal arg '(16)) "[-]")
20918 ((and (not box) (equal arg '(4))) "[ ]")
20919 ((or (not box) (equal arg '(4))) nil)
20920 ((eq box 'on) "[ ]")
20921 (t "[X]")))
20922 ;; Mimic `org-list-write-struct' but with grabbing a return
20923 ;; value from `org-list-struct-fix-box'.
20924 (org-list-struct-fix-ind struct parents 2)
20925 (org-list-struct-fix-item-end struct)
20926 (org-list-struct-fix-bul struct prevs)
20927 (org-list-struct-fix-ind struct parents)
20928 (let ((block-item
20929 (org-list-struct-fix-box struct parents prevs orderedp)))
20930 (if (and box (equal struct old-struct))
20931 (if (equal arg '(16))
20932 (message "Checkboxes already reset")
20933 (user-error "Cannot toggle this checkbox: %s"
20934 (if (eq box 'on)
20935 "all subitems checked"
20936 "unchecked subitems")))
20937 (org-list-struct-apply-struct struct old-struct)
20938 (org-update-checkbox-count-maybe))
20939 (when block-item
20940 (message "Checkboxes were removed due to empty box at line %d"
20941 (org-current-line block-item))))))
20942 (`keyword
20943 (let ((org-inhibit-startup-visibility-stuff t)
20944 (org-startup-align-all-tables nil))
20945 (when (boundp 'org-table-coordinate-overlays)
20946 (mapc #'delete-overlay org-table-coordinate-overlays)
20947 (setq org-table-coordinate-overlays nil))
20948 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20949 (message "Local setup has been refreshed"))
20950 (`plain-list
20951 ;; At a plain list, with a double C-u argument, set
20952 ;; checkboxes of each item to "[-]", whereas a single one
20953 ;; will toggle their presence according to the state of the
20954 ;; first item in the list. Without an argument, repair the
20955 ;; list.
20956 (let* ((begin (org-element-property :contents-begin context))
20957 (beginm (move-marker (make-marker) begin))
20958 (struct (org-element-property :structure context))
20959 (old-struct (copy-tree struct))
20960 (first-box (save-excursion
20961 (goto-char begin)
20962 (looking-at org-list-full-item-re)
20963 (match-string-no-properties 3)))
20964 (new-box (cond ((equal arg '(16)) "[-]")
20965 ((equal arg '(4)) (unless first-box "[ ]"))
20966 ((equal first-box "[X]") "[ ]")
20967 (t "[X]"))))
20968 (cond
20969 (arg
20970 (dolist (pos
20971 (org-list-get-all-items
20972 begin struct (org-list-prevs-alist struct)))
20973 (org-list-set-checkbox pos struct new-box)))
20974 ((and first-box (eq (point) begin))
20975 ;; For convenience, when point is at bol on the first
20976 ;; item of the list and no argument is provided, simply
20977 ;; toggle checkbox of that item, if any.
20978 (org-list-set-checkbox begin struct new-box)))
20979 (org-list-write-struct
20980 struct (org-list-parents-alist struct) old-struct)
20981 (org-update-checkbox-count-maybe)
20982 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20983 ((or `property-drawer `node-property)
20984 (call-interactively #'org-property-action))
20985 (`radio-target
20986 (call-interactively #'org-update-radio-target-regexp))
20987 (`statistics-cookie
20988 (call-interactively #'org-update-statistics-cookies))
20989 ((or `table `table-cell `table-row)
20990 ;; At a table, recalculate every field and align it. Also
20991 ;; send the table if necessary. If the table has
20992 ;; a `table.el' type, just give up. At a table row or cell,
20993 ;; maybe recalculate line but always align table.
20994 (if (eq (org-element-property :type context) 'table.el)
20995 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20996 Use `\\[org-edit-special]' to edit table.el tables"))
20997 (let ((org-enable-table-editor t))
20998 (if (or (eq type 'table)
20999 ;; Check if point is at a TBLFM line.
21000 (and (eq type 'table-row)
21001 (= (point) (org-element-property :end context))))
21002 (save-excursion
21003 (if (org-at-TBLFM-p)
21004 (progn (require 'org-table)
21005 (org-table-calc-current-TBLFM))
21006 (goto-char (org-element-property :contents-begin context))
21007 (org-call-with-arg 'org-table-recalculate (or arg t))
21008 (orgtbl-send-table 'maybe)))
21009 (org-table-maybe-eval-formula)
21010 (cond (arg (call-interactively #'org-table-recalculate))
21011 ((org-table-maybe-recalculate-line))
21012 (t (org-table-align)))))))
21013 (`timestamp (org-timestamp-change 0 'day))
21014 ((and `nil (guard (org-at-heading-p)))
21015 ;; When point is on an unsupported object type, we can miss
21016 ;; the fact that it also is at a heading. Handle it here.
21017 (call-interactively #'org-set-tags))
21018 ((guard
21019 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21021 (user-error
21022 (substitute-command-keys
21023 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21025 (defun org-mode-restart ()
21026 (interactive)
21027 (let ((indent-status (bound-and-true-p org-indent-mode)))
21028 (funcall major-mode)
21029 (hack-local-variables)
21030 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21031 (org-indent-mode -1))
21032 (org-reset-file-cache))
21033 (message "%s restarted" major-mode))
21035 (defun org-kill-note-or-show-branches ()
21036 "Abort storing current note, or call `outline-show-branches'."
21037 (interactive)
21038 (if (not org-finish-function)
21039 (progn
21040 (outline-hide-subtree)
21041 (call-interactively 'outline-show-branches))
21042 (let ((org-note-abort t))
21043 (funcall org-finish-function))))
21045 (defun org-delete-indentation (&optional arg)
21046 "Join current line to previous and fix whitespace at join.
21048 If previous line is a headline add to headline title. Otherwise
21049 the function calls `delete-indentation'.
21051 With a non-nil optional argument, join it to the following one."
21052 (interactive "*P")
21053 (if (save-excursion
21054 (beginning-of-line (if arg 1 0))
21055 (let ((case-fold-search nil))
21056 (looking-at org-complex-heading-regexp)))
21057 ;; At headline.
21058 (let ((tags-column (when (match-beginning 5)
21059 (save-excursion (goto-char (match-beginning 5))
21060 (current-column))))
21061 (string (concat " " (progn (when arg (forward-line 1))
21062 (org-trim (delete-and-extract-region
21063 (line-beginning-position)
21064 (line-end-position)))))))
21065 (unless (bobp) (delete-region (point) (1- (point))))
21066 (goto-char (or (match-end 4)
21067 (match-beginning 5)
21068 (match-end 0)))
21069 (skip-chars-backward " \t")
21070 (save-excursion (insert string))
21071 ;; Adjust alignment of tags.
21072 (cond
21073 ((not tags-column)) ;no tags
21074 (org-auto-align-tags (org-set-tags nil t))
21075 (t (org--align-tags-here tags-column)))) ;preserve tags column
21076 (delete-indentation arg)))
21078 (defun org-open-line (n)
21079 "Insert a new row in tables, call `open-line' elsewhere.
21080 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21081 As a special case, when a document starts with a table, allow to
21082 call `open-line' on the very first character."
21083 (interactive "*p")
21084 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21085 (org-table-insert-row)
21086 (open-line n)))
21088 (defun org-return (&optional indent)
21089 "Goto next table row or insert a newline.
21091 Calls `org-table-next-row' or `newline', depending on context.
21093 When optional INDENT argument is non-nil, call
21094 `newline-and-indent' instead of `newline'.
21096 When `org-return-follows-link' is non-nil and point is on
21097 a timestamp or a link, call `org-open-at-point'. However, it
21098 will not happen if point is in a table or on a \"dead\"
21099 object (e.g., within a comment). In these case, you need to use
21100 `org-open-at-point' directly."
21101 (interactive)
21102 (let ((context (if org-return-follows-link (org-element-context)
21103 (org-element-at-point))))
21104 (cond
21105 ;; In a table, call `org-table-next-row'.
21106 ((or (and (eq (org-element-type context) 'table)
21107 (>= (point) (org-element-property :contents-begin context))
21108 (< (point) (org-element-property :contents-end context)))
21109 (org-element-lineage context '(table-row table-cell) t))
21110 (org-table-justify-field-maybe)
21111 (call-interactively #'org-table-next-row))
21112 ;; On a link or a timestamp, call `org-open-at-point' if
21113 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21114 ;; locations, e.g., in a comment, as `org-open-at-point'.
21115 ((and org-return-follows-link
21116 (or (org-in-regexp org-ts-regexp-both nil t)
21117 (org-in-regexp org-tsr-regexp-both nil t)
21118 (org-in-regexp org-any-link-re nil t)))
21119 (call-interactively #'org-open-at-point))
21120 ;; Insert newline in heading, but preserve tags.
21121 ((and (not (bolp))
21122 (save-excursion (beginning-of-line)
21123 (let ((case-fold-search nil))
21124 (looking-at org-complex-heading-regexp))))
21125 ;; At headline. Split line. However, if point is on keyword,
21126 ;; priority cookie or tags, do not break any of them: add
21127 ;; a newline after the headline instead.
21128 (let ((tags-column (and (match-beginning 5)
21129 (save-excursion (goto-char (match-beginning 5))
21130 (current-column))))
21131 (string
21132 (when (and (match-end 4) (org-point-in-group (point) 4))
21133 (delete-and-extract-region (point) (match-end 4)))))
21134 ;; Adjust tag alignment.
21135 (cond
21136 ((not (and tags-column string)))
21137 (org-auto-align-tags (org-set-tags nil t))
21138 (t (org--align-tags-here tags-column))) ;preserve tags column
21139 (end-of-line)
21140 (org-show-entry)
21141 (if indent (newline-and-indent) (newline))
21142 (when string (save-excursion (insert (org-trim string))))))
21143 ;; In a list, make sure indenting keeps trailing text within.
21144 ((and indent
21145 (not (eolp))
21146 (org-element-lineage context '(item)))
21147 (let ((trailing-data
21148 (delete-and-extract-region (point) (line-end-position))))
21149 (newline-and-indent)
21150 (save-excursion (insert trailing-data))))
21151 (t (if indent (newline-and-indent) (newline))))))
21153 (defun org-return-indent ()
21154 "Goto next table row or insert a newline and indent.
21155 Calls `org-table-next-row' or `newline-and-indent', depending on
21156 context. See the individual commands for more information."
21157 (interactive)
21158 (org-return t))
21160 (defun org-ctrl-c-star ()
21161 "Compute table, or change heading status of lines.
21162 Calls `org-table-recalculate' or `org-toggle-heading',
21163 depending on context."
21164 (interactive)
21165 (cond
21166 ((org-at-table-p)
21167 (call-interactively 'org-table-recalculate))
21169 ;; Convert all lines in region to list items
21170 (call-interactively 'org-toggle-heading))))
21172 (defun org-ctrl-c-minus ()
21173 "Insert separator line in table or modify bullet status of line.
21174 Also turns a plain line or a region of lines into list items.
21175 Calls `org-table-insert-hline', `org-toggle-item', or
21176 `org-cycle-list-bullet', depending on context."
21177 (interactive)
21178 (cond
21179 ((org-at-table-p)
21180 (call-interactively 'org-table-insert-hline))
21181 ((org-region-active-p)
21182 (call-interactively 'org-toggle-item))
21183 ((org-in-item-p)
21184 (call-interactively 'org-cycle-list-bullet))
21186 (call-interactively 'org-toggle-item))))
21188 (defun org-toggle-heading (&optional nstars)
21189 "Convert headings to normal text, or items or text to headings.
21190 If there is no active region, only convert the current line.
21192 With a `\\[universal-argument]' prefix, convert the whole list at
21193 point into heading.
21195 In a region:
21197 - If the first non blank line is a headline, remove the stars
21198 from all headlines in the region.
21200 - If it is a normal line, turn each and every normal line (i.e.,
21201 not an heading or an item) in the region into headings. If you
21202 want to convert only the first line of this region, use one
21203 universal prefix argument.
21205 - If it is a plain list item, turn all plain list items into headings.
21207 When converting a line into a heading, the number of stars is chosen
21208 such that the lines become children of the current entry. However,
21209 when a numeric prefix argument is given, its value determines the
21210 number of stars to add."
21211 (interactive "P")
21212 (let ((skip-blanks
21213 (function
21214 ;; Return beginning of first non-blank line, starting from
21215 ;; line at POS.
21216 (lambda (pos)
21217 (save-excursion
21218 (goto-char pos)
21219 (while (org-at-comment-p) (forward-line))
21220 (skip-chars-forward " \r\t\n")
21221 (point-at-bol)))))
21222 beg end toggled)
21223 ;; Determine boundaries of changes. If a universal prefix has
21224 ;; been given, put the list in a region. If region ends at a bol,
21225 ;; do not consider the last line to be in the region.
21227 (when (and current-prefix-arg (org-at-item-p))
21228 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21229 (org-mark-element))
21231 (if (org-region-active-p)
21232 (setq beg (funcall skip-blanks (region-beginning))
21233 end (copy-marker (save-excursion
21234 (goto-char (region-end))
21235 (if (bolp) (point) (point-at-eol)))))
21236 (setq beg (funcall skip-blanks (point-at-bol))
21237 end (copy-marker (point-at-eol))))
21238 ;; Ensure inline tasks don't count as headings.
21239 (org-with-limited-levels
21240 (save-excursion
21241 (goto-char beg)
21242 (cond
21243 ;; Case 1. Started at an heading: de-star headings.
21244 ((org-at-heading-p)
21245 (while (< (point) end)
21246 (when (org-at-heading-p t)
21247 (looking-at org-outline-regexp) (replace-match "")
21248 (setq toggled t))
21249 (forward-line)))
21250 ;; Case 2. Started at an item: change items into headlines.
21251 ;; One star will be added by `org-list-to-subtree'.
21252 ((org-at-item-p)
21253 (while (< (point) end)
21254 (when (org-at-item-p)
21255 ;; Pay attention to cases when region ends before list.
21256 (let* ((struct (org-list-struct))
21257 (list-end
21258 (min (org-list-get-bottom-point struct) (1+ end))))
21259 (save-restriction
21260 (narrow-to-region (point) list-end)
21261 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21262 (setq toggled t))
21263 (forward-line)))
21264 ;; Case 3. Started at normal text: make every line an heading,
21265 ;; skipping headlines and items.
21266 (t (let* ((stars
21267 (make-string
21268 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21269 (add-stars
21270 (cond (nstars "") ; stars from prefix only
21271 ((equal stars "") "*") ; before first heading
21272 (org-odd-levels-only "**") ; inside heading, odd
21273 (t "*"))) ; inside heading, oddeven
21274 (rpl (concat stars add-stars " "))
21275 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21276 (while (< (point) (if (equal nstars '(4)) lend end))
21277 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21278 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21279 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21280 (forward-line)))))))
21281 (unless toggled (message "Cannot toggle heading from here"))))
21283 (defun org-meta-return (&optional arg)
21284 "Insert a new heading or wrap a region in a table.
21285 Calls `org-insert-heading', `org-insert-item' or
21286 `org-table-wrap-region', depending on context. When called with
21287 an argument, unconditionally call `org-insert-heading'."
21288 (interactive "P")
21289 (org-check-before-invisible-edit 'insert)
21290 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21291 (call-interactively (cond (arg #'org-insert-heading)
21292 ((org-at-table-p) #'org-table-wrap-region)
21293 ((org-in-item-p) #'org-insert-item)
21294 (t #'org-insert-heading)))))
21296 ;;; Menu entries
21298 (defsubst org-in-subtree-not-table-p ()
21299 "Are we in a subtree and not in a table?"
21300 (and (not (org-before-first-heading-p))
21301 (not (org-at-table-p))))
21303 ;; Define the Org mode menus
21304 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21305 '("Tbl"
21306 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21307 ["Next Field" org-cycle (org-at-table-p)]
21308 ["Previous Field" org-shifttab (org-at-table-p)]
21309 ["Next Row" org-return (org-at-table-p)]
21310 "--"
21311 ["Blank Field" org-table-blank-field (org-at-table-p)]
21312 ["Edit Field" org-table-edit-field (org-at-table-p)]
21313 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21314 "--"
21315 ("Column"
21316 ["Move Column Left" org-metaleft (org-at-table-p)]
21317 ["Move Column Right" org-metaright (org-at-table-p)]
21318 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21319 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21320 ("Row"
21321 ["Move Row Up" org-metaup (org-at-table-p)]
21322 ["Move Row Down" org-metadown (org-at-table-p)]
21323 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21324 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21325 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21326 "--"
21327 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21328 ("Rectangle"
21329 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21330 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21331 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21332 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21333 "--"
21334 ("Calculate"
21335 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21336 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21337 ["Edit Formulas" org-edit-special (org-at-table-p)]
21338 "--"
21339 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21340 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21341 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21342 "--"
21343 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21344 "--"
21345 ["Sum Column/Rectangle" org-table-sum
21346 (or (org-at-table-p) (org-region-active-p))]
21347 ["Which Column?" org-table-current-column (org-at-table-p)])
21348 ["Debug Formulas"
21349 org-table-toggle-formula-debugger
21350 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21351 ["Show Col/Row Numbers"
21352 org-table-toggle-coordinate-overlays
21353 :style toggle
21354 :selected (bound-and-true-p org-table-overlay-coordinates)]
21355 "--"
21356 ["Create" org-table-create (and (not (org-at-table-p))
21357 org-enable-table-editor)]
21358 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21359 ["Import from File" org-table-import (not (org-at-table-p))]
21360 ["Export to File" org-table-export (org-at-table-p)]
21361 "--"
21362 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21363 "--"
21364 ("Plot"
21365 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21366 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21368 (easy-menu-define org-org-menu org-mode-map "Org menu"
21369 '("Org"
21370 ("Show/Hide"
21371 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21372 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21373 ["Sparse Tree..." org-sparse-tree t]
21374 ["Reveal Context" org-reveal t]
21375 ["Show All" outline-show-all t]
21376 "--"
21377 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21378 "--"
21379 ["New Heading" org-insert-heading t]
21380 ("Navigate Headings"
21381 ["Up" outline-up-heading t]
21382 ["Next" outline-next-visible-heading t]
21383 ["Previous" outline-previous-visible-heading t]
21384 ["Next Same Level" outline-forward-same-level t]
21385 ["Previous Same Level" outline-backward-same-level t]
21386 "--"
21387 ["Jump" org-goto t])
21388 ("Edit Structure"
21389 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21390 "--"
21391 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21392 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21393 "--"
21394 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21395 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21396 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21397 "--"
21398 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21399 "--"
21400 ["Copy visible text" org-copy-visible t]
21401 "--"
21402 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21403 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21404 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21405 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21406 "--"
21407 ["Sort Region/Children" org-sort t]
21408 "--"
21409 ["Convert to odd levels" org-convert-to-odd-levels t]
21410 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21411 ("Editing"
21412 ["Emphasis..." org-emphasize t]
21413 ["Edit Source Example" org-edit-special t]
21414 "--"
21415 ["Footnote new/jump" org-footnote-action t]
21416 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21417 ("Archive"
21418 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21419 "--"
21420 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21421 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21422 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21424 "--"
21425 ("Hyperlinks"
21426 ["Store Link (Global)" org-store-link t]
21427 ["Find existing link to here" org-occur-link-in-agenda-files t]
21428 ["Insert Link" org-insert-link t]
21429 ["Follow Link" org-open-at-point t]
21430 "--"
21431 ["Next link" org-next-link t]
21432 ["Previous link" org-previous-link t]
21433 "--"
21434 ["Descriptive Links"
21435 org-toggle-link-display
21436 :style radio
21437 :selected org-descriptive-links
21439 ["Literal Links"
21440 org-toggle-link-display
21441 :style radio
21442 :selected (not org-descriptive-links)])
21443 "--"
21444 ("TODO Lists"
21445 ["TODO/DONE/-" org-todo t]
21446 ("Select keyword"
21447 ["Next keyword" org-shiftright (org-at-heading-p)]
21448 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21449 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21450 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21451 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21452 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21453 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21454 "--"
21455 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21456 :selected org-enforce-todo-dependencies :style toggle :active t]
21457 "Settings for tree at point"
21458 ["Do Children sequentially" org-toggle-ordered-property :style radio
21459 :selected (org-entry-get nil "ORDERED")
21460 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21461 ["Do Children parallel" org-toggle-ordered-property :style radio
21462 :selected (not (org-entry-get nil "ORDERED"))
21463 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21464 "--"
21465 ["Set Priority" org-priority t]
21466 ["Priority Up" org-shiftup t]
21467 ["Priority Down" org-shiftdown t]
21468 "--"
21469 ["Get news from all feeds" org-feed-update-all t]
21470 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21471 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21472 ("TAGS and Properties"
21473 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21474 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21475 "--"
21476 ["Set property" org-set-property (not (org-before-first-heading-p))]
21477 ["Column view of properties" org-columns t]
21478 ["Insert Column View DBlock" org-columns-insert-dblock t])
21479 ("Dates and Scheduling"
21480 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21481 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21482 ("Change Date"
21483 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21484 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21485 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21486 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21487 ["Compute Time Range" org-evaluate-time-range t]
21488 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21489 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21490 "--"
21491 ["Custom time format" org-toggle-time-stamp-overlays
21492 :style radio :selected org-display-custom-times]
21493 "--"
21494 ["Goto Calendar" org-goto-calendar t]
21495 ["Date from Calendar" org-date-from-calendar t]
21496 "--"
21497 ["Start/Restart Timer" org-timer-start t]
21498 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21499 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21500 ["Insert Timer String" org-timer t]
21501 ["Insert Timer Item" org-timer-item t])
21502 ("Logging work"
21503 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21504 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21505 ["Clock out" org-clock-out t]
21506 ["Clock cancel" org-clock-cancel t]
21507 "--"
21508 ["Mark as default task" org-clock-mark-default-task t]
21509 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21510 ["Goto running clock" org-clock-goto t]
21511 "--"
21512 ["Display times" org-clock-display t]
21513 ["Create clock table" org-clock-report t]
21514 "--"
21515 ["Record DONE time"
21516 (progn (setq org-log-done (not org-log-done))
21517 (message "Switching to %s will %s record a timestamp"
21518 (car org-done-keywords)
21519 (if org-log-done "automatically" "not")))
21520 :style toggle :selected org-log-done])
21521 "--"
21522 ["Agenda Command..." org-agenda t]
21523 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21524 ("File List for Agenda")
21525 ("Special views current file"
21526 ["TODO Tree" org-show-todo-tree t]
21527 ["Check Deadlines" org-check-deadlines t]
21528 ["Tags/Property tree" org-match-sparse-tree t])
21529 "--"
21530 ["Export/Publish..." org-export-dispatch t]
21531 ("LaTeX"
21532 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21533 :selected org-cdlatex-mode]
21534 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21535 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21536 ["Modify math symbol" org-cdlatex-math-modify
21537 (org-inside-LaTeX-fragment-p)]
21538 ["Insert citation" org-reftex-citation t])
21539 "--"
21540 ("MobileOrg"
21541 ["Push Files and Views" org-mobile-push t]
21542 ["Get Captured and Flagged" org-mobile-pull t]
21543 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21544 "--"
21545 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21546 "--"
21547 ("Documentation"
21548 ["Show Version" org-version t]
21549 ["Info Documentation" org-info t])
21550 ("Customize"
21551 ["Browse Org Group" org-customize t]
21552 "--"
21553 ["Expand This Menu" org-create-customize-menu
21554 (fboundp 'customize-menu-create)])
21555 ["Send bug report" org-submit-bug-report t]
21556 "--"
21557 ("Refresh/Reload"
21558 ["Refresh setup current buffer" org-mode-restart t]
21559 ["Reload Org (after update)" org-reload t]
21560 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21563 (defun org-info (&optional node)
21564 "Read documentation for Org in the info system.
21565 With optional NODE, go directly to that node."
21566 (interactive)
21567 (info (format "(org)%s" (or node ""))))
21569 ;;;###autoload
21570 (defun org-submit-bug-report ()
21571 "Submit a bug report on Org via mail.
21573 Don't hesitate to report any problems or inaccurate documentation.
21575 If you don't have setup sending mail from (X)Emacs, please copy the
21576 output buffer into your mail program, as it gives us important
21577 information about your Org version and configuration."
21578 (interactive)
21579 (require 'reporter)
21580 (defvar reporter-prompt-for-summary-p)
21581 (org-load-modules-maybe)
21582 (org-require-autoloaded-modules)
21583 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21584 (reporter-submit-bug-report
21585 "emacs-orgmode@gnu.org"
21586 (org-version nil 'full)
21587 (let (list)
21588 (save-window-excursion
21589 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21590 (delete-other-windows)
21591 (erase-buffer)
21592 (insert "You are about to submit a bug report to the Org mailing list.
21594 We would like to add your full Org and Outline configuration to the
21595 bug report. This greatly simplifies the work of the maintainer and
21596 other experts on the mailing list.
21598 HOWEVER, some variables you have customized may contain private
21599 information. The names of customers, colleagues, or friends, might
21600 appear in the form of file names, tags, todo states, or search strings.
21601 If you answer yes to the prompt, you might want to check and remove
21602 such private information before sending the email.")
21603 (add-text-properties (point-min) (point-max) '(face org-warning))
21604 (when (yes-or-no-p "Include your Org configuration ")
21605 (mapatoms
21606 (lambda (v)
21607 (and (boundp v)
21608 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21609 (or (and (symbol-value v)
21610 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21611 (and
21612 (get v 'custom-type) (get v 'standard-value)
21613 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21614 (push v list)))))
21615 (kill-buffer (get-buffer "*Warn about privacy*"))
21616 list))
21617 nil nil
21618 "Remember to cover the basics, that is, what you expected to happen and
21619 what in fact did happen. You don't know how to make a good report? See
21621 http://orgmode.org/manual/Feedback.html#Feedback
21623 Your bug report will be posted to the Org mailing list.
21624 ------------------------------------------------------------------------")
21625 (save-excursion
21626 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21627 (replace-match "\\1Bug: \\3 [\\2]")))))
21630 (defun org-install-agenda-files-menu ()
21631 (let ((bl (buffer-list)))
21632 (save-excursion
21633 (while bl
21634 (set-buffer (pop bl))
21635 (when (derived-mode-p 'org-mode) (setq bl nil)))
21636 (when (derived-mode-p 'org-mode)
21637 (easy-menu-change
21638 '("Org") "File List for Agenda"
21639 (append
21640 (list
21641 ["Edit File List" (org-edit-agenda-file-list) t]
21642 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21643 ["Remove Current File from List" org-remove-file t]
21644 ["Cycle through agenda files" org-cycle-agenda-files t]
21645 ["Occur in all agenda files" org-occur-in-agenda-files t]
21646 "--")
21647 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21649 ;;;; Documentation
21651 (defun org-require-autoloaded-modules ()
21652 (interactive)
21653 (mapc #'require
21654 '(org-agenda org-archive org-attach org-clock org-colview org-id
21655 org-table org-timer)))
21657 ;;;###autoload
21658 (defun org-reload (&optional uncompiled)
21659 "Reload all org lisp files.
21660 With prefix arg UNCOMPILED, load the uncompiled versions."
21661 (interactive "P")
21662 (require 'loadhist)
21663 (let* ((org-dir (org-find-library-dir "org"))
21664 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21665 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21666 (remove-re (format "\\`%s\\'"
21667 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21668 (feats (delete-dups
21669 (mapcar 'file-name-sans-extension
21670 (mapcar 'file-name-nondirectory
21671 (delq nil
21672 (mapcar 'feature-file
21673 features))))))
21674 (lfeat (append
21675 (sort
21676 (setq feats
21677 (delq nil (mapcar
21678 (lambda (f)
21679 (if (and (string-match feature-re f)
21680 (not (string-match remove-re f)))
21681 f nil))
21682 feats)))
21683 'string-lessp)
21684 (list "org-version" "org")))
21685 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21686 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21687 load-uncore load-misses)
21688 (setq load-misses
21689 (delq 't
21690 (mapcar (lambda (f)
21691 (or (org-load-noerror-mustsuffix (concat org-dir f))
21692 (and (string= org-dir contrib-dir)
21693 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21694 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21695 (add-to-list 'load-uncore f 'append)
21698 lfeat)))
21699 (when load-uncore
21700 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21701 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21702 (if load-misses
21703 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21704 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21705 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21707 ;;;###autoload
21708 (defun org-customize ()
21709 "Call the customize function with org as argument."
21710 (interactive)
21711 (org-load-modules-maybe)
21712 (org-require-autoloaded-modules)
21713 (customize-browse 'org))
21715 (defun org-create-customize-menu ()
21716 "Create a full customization menu for Org mode, insert it into the menu."
21717 (interactive)
21718 (org-load-modules-maybe)
21719 (org-require-autoloaded-modules)
21720 (if (fboundp 'customize-menu-create)
21721 (progn
21722 (easy-menu-change
21723 '("Org") "Customize"
21724 `(["Browse Org group" org-customize t]
21725 "--"
21726 ,(customize-menu-create 'org)
21727 ["Set" Custom-set t]
21728 ["Save" Custom-save t]
21729 ["Reset to Current" Custom-reset-current t]
21730 ["Reset to Saved" Custom-reset-saved t]
21731 ["Reset to Standard Settings" Custom-reset-standard t]))
21732 (message "\"Org\"-menu now contains full customization menu"))
21733 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21735 ;;;; Miscellaneous stuff
21737 ;;; Generally useful functions
21739 (defun org-get-at-eol (property n)
21740 "Get text property PROPERTY at the end of line less N characters."
21741 (get-text-property (- (point-at-eol) n) property))
21743 (defun org-find-text-property-in-string (prop s)
21744 "Return the first non-nil value of property PROP in string S."
21745 (or (get-text-property 0 prop s)
21746 (get-text-property (or (next-single-property-change 0 prop s) 0)
21747 prop s)))
21749 (defun org-display-warning (message)
21750 "Display the given MESSAGE as a warning."
21751 (display-warning 'org message :warning))
21753 (defun org-eval (form)
21754 "Eval FORM and return result."
21755 (condition-case error
21756 (eval form)
21757 (error (format "%%![Error: %s]" error))))
21759 (defun org-in-clocktable-p ()
21760 "Check if the cursor is in a clocktable."
21761 (let ((pos (point)) start)
21762 (save-excursion
21763 (end-of-line 1)
21764 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21765 (setq start (match-beginning 0))
21766 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21767 (>= (match-end 0) pos)
21768 start))))
21770 (defun org-in-verbatim-emphasis ()
21771 (save-match-data
21772 (and (org-in-regexp org-verbatim-re 2)
21773 (>= (point) (match-beginning 3))
21774 (<= (point) (match-end 4)))))
21776 (defun org-overlay-display (ovl text &optional face evap)
21777 "Make overlay OVL display TEXT with face FACE."
21778 (overlay-put ovl 'display text)
21779 (if face (overlay-put ovl 'face face))
21780 (if evap (overlay-put ovl 'evaporate t)))
21782 (defun org-overlay-before-string (ovl text &optional face evap)
21783 "Make overlay OVL display TEXT with face FACE."
21784 (if face (org-add-props text nil 'face face))
21785 (overlay-put ovl 'before-string text)
21786 (if evap (overlay-put ovl 'evaporate t)))
21788 (defun org-find-overlays (prop &optional pos delete)
21789 "Find all overlays specifying PROP at POS or point.
21790 If DELETE is non-nil, delete all those overlays."
21791 (let (found)
21792 (dolist (ov (overlays-at (or pos (point))) found)
21793 (cond ((not (overlay-get ov prop)))
21794 (delete (delete-overlay ov))
21795 (t (push ov found))))))
21797 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21798 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21799 (if (and marker (marker-buffer marker)
21800 (buffer-live-p (marker-buffer marker)))
21801 (progn
21802 (pop-to-buffer-same-window (marker-buffer marker))
21803 (when (or (> marker (point-max)) (< marker (point-min)))
21804 (widen))
21805 (goto-char marker)
21806 (org-show-context 'org-goto))
21807 (if bookmark
21808 (bookmark-jump bookmark)
21809 (error "Cannot find location"))))
21811 (defun org-quote-csv-field (s)
21812 "Quote field for inclusion in CSV material."
21813 (if (string-match "[\",]" s)
21814 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21817 (defun org-force-self-insert (N)
21818 "Needed to enforce self-insert under remapping."
21819 (interactive "p")
21820 (self-insert-command N))
21822 (defun org-shorten-string (s maxlength)
21823 "Shorten string S so that it is no longer than MAXLENGTH characters.
21824 If the string is shorter or has length MAXLENGTH, just return the
21825 original string. If it is longer, the functions finds a space in the
21826 string, breaks this string off at that locations and adds three dots
21827 as ellipsis. Including the ellipsis, the string will not be longer
21828 than MAXLENGTH. If finding a good breaking point in the string does
21829 not work, the string is just chopped off in the middle of a word
21830 if necessary."
21831 (if (<= (length s) maxlength)
21833 (let* ((n (max (- maxlength 4) 1))
21834 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21835 (if (string-match re s)
21836 (concat (match-string 1 s) "...")
21837 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21839 (defun org-get-indentation (&optional line)
21840 "Get the indentation of the current line, interpreting tabs.
21841 When LINE is given, assume it represents a line and compute its indentation."
21842 (if line
21843 (when (string-match "^ *" (org-remove-tabs line))
21844 (match-end 0))
21845 (save-excursion
21846 (beginning-of-line 1)
21847 (skip-chars-forward " \t")
21848 (current-column))))
21850 (defun org-get-string-indentation (s)
21851 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21852 (let ((n -1) (i 0) (w tab-width) c)
21853 (catch 'exit
21854 (while (< (setq n (1+ n)) (length s))
21855 (setq c (aref s n))
21856 (cond ((= c ?\ ) (setq i (1+ i)))
21857 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21858 (t (throw 'exit t)))))
21861 (defun org-remove-tabs (s &optional width)
21862 "Replace tabulators in S with spaces.
21863 Assumes that s is a single line, starting in column 0."
21864 (setq width (or width tab-width))
21865 (while (string-match "\t" s)
21866 (setq s (replace-match
21867 (make-string
21868 (- (* width (/ (+ (match-beginning 0) width) width))
21869 (match-beginning 0)) ?\ )
21870 t t s)))
21873 (defun org-fix-indentation (line ind)
21874 "Fix indentation in LINE.
21875 IND is a cons cell with target and minimum indentation.
21876 If the current indentation in LINE is smaller than the minimum,
21877 leave it alone. If it is larger than ind, set it to the target."
21878 (let* ((l (org-remove-tabs line))
21879 (i (org-get-indentation l))
21880 (i1 (car ind)) (i2 (cdr ind)))
21881 (when (>= i i2) (setq l (substring line i2)))
21882 (if (> i1 0)
21883 (concat (make-string i1 ?\ ) l)
21884 l)))
21886 (defun org-remove-indentation (code &optional n)
21887 "Remove maximum common indentation in string CODE and return it.
21888 N may optionally be the number of columns to remove. Return CODE
21889 as-is if removal failed."
21890 (with-temp-buffer
21891 (insert code)
21892 (if (org-do-remove-indentation n) (buffer-string) code)))
21894 (defun org-do-remove-indentation (&optional n)
21895 "Remove the maximum common indentation from the buffer.
21896 When optional argument N is a positive integer, remove exactly
21897 that much characters from indentation, if possible. Return nil
21898 if it fails."
21899 (catch :exit
21900 (goto-char (point-min))
21901 ;; Find maximum common indentation, if not specified.
21902 (let ((n (or n
21903 (let ((min-ind (point-max)))
21904 (save-excursion
21905 (while (re-search-forward "^[ \t]*\\S-" nil t)
21906 (let ((ind (1- (current-column))))
21907 (if (zerop ind) (throw :exit nil)
21908 (setq min-ind (min min-ind ind))))))
21909 min-ind))))
21910 (if (zerop n) (throw :exit nil)
21911 ;; Remove exactly N indentation, but give up if not possible.
21912 (while (not (eobp))
21913 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21914 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21915 ((< ind n) (throw :exit nil))
21916 (t (indent-line-to (- ind n))))
21917 (forward-line)))
21918 ;; Signal success.
21919 t))))
21921 (defun org-fill-template (template alist)
21922 "Find each %key of ALIST in TEMPLATE and replace it."
21923 (let ((case-fold-search nil))
21924 (dolist (entry (sort (copy-sequence alist)
21925 (lambda (a b) (< (length (car a)) (length (car b))))))
21926 (setq template
21927 (replace-regexp-in-string
21928 (concat "%" (regexp-quote (car entry)))
21929 (or (cdr entry) "") template t t)))
21930 template))
21932 (defun org-base-buffer (buffer)
21933 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21934 (if (not buffer)
21935 buffer
21936 (or (buffer-base-buffer buffer)
21937 buffer)))
21939 (defun org-wrap (string &optional width lines)
21940 "Wrap string to either a number of lines, or a width in characters.
21941 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21942 that costs. If there is a word longer than WIDTH, the text is actually
21943 wrapped to the length of that word.
21944 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21945 many lines, whatever width that takes.
21946 The return value is a list of lines, without newlines at the end."
21947 (let* ((words (org-split-string string "[ \t\n]+"))
21948 (maxword (apply 'max (mapcar 'org-string-width words)))
21949 w ll)
21950 (cond (width
21951 (org-do-wrap words (max maxword width)))
21952 (lines
21953 (setq w maxword)
21954 (setq ll (org-do-wrap words maxword))
21955 (if (<= (length ll) lines)
21957 (setq ll words)
21958 (while (> (length ll) lines)
21959 (setq w (1+ w))
21960 (setq ll (org-do-wrap words w)))
21961 ll))
21962 (t (error "Cannot wrap this")))))
21964 (defun org-do-wrap (words width)
21965 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21966 (let (lines line)
21967 (while words
21968 (setq line (pop words))
21969 (while (and words (< (+ (length line) (length (car words))) width))
21970 (setq line (concat line " " (pop words))))
21971 (setq lines (push line lines)))
21972 (nreverse lines)))
21974 (defun org-quote-vert (s)
21975 "Replace \"|\" with \"\\vert\"."
21976 (while (string-match "|" s)
21977 (setq s (replace-match "\\vert" t t s)))
21980 (defun org-uuidgen-p (s)
21981 "Is S an ID created by UUIDGEN?"
21982 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21984 (defun org-in-src-block-p (&optional inside)
21985 "Whether point is in a code source block.
21986 When INSIDE is non-nil, don't consider we are within a src block
21987 when point is at #+BEGIN_SRC or #+END_SRC."
21988 (let ((case-fold-search t))
21989 (or (and (eq (get-char-property (point) 'src-block) t))
21990 (and (not inside)
21991 (save-match-data
21992 (save-excursion
21993 (beginning-of-line)
21994 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21996 (defun org-context ()
21997 "Return a list of contexts of the current cursor position.
21998 If several contexts apply, all are returned.
21999 Each context entry is a list with a symbol naming the context, and
22000 two positions indicating start and end of the context. Possible
22001 contexts are:
22003 :headline anywhere in a headline
22004 :headline-stars on the leading stars in a headline
22005 :todo-keyword on a TODO keyword (including DONE) in a headline
22006 :tags on the TAGS in a headline
22007 :priority on the priority cookie in a headline
22008 :item on the first line of a plain list item
22009 :item-bullet on the bullet/number of a plain list item
22010 :checkbox on the checkbox in a plain list item
22011 :table in an Org table
22012 :table-special on a special filed in a table
22013 :table-table in a table.el table
22014 :clocktable in a clocktable
22015 :src-block in a source block
22016 :link on a hyperlink
22017 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22018 :target on a <<target>>
22019 :radio-target on a <<<radio-target>>>
22020 :latex-fragment on a LaTeX fragment
22021 :latex-preview on a LaTeX fragment with overlaid preview image
22023 This function expects the position to be visible because it uses font-lock
22024 faces as a help to recognize the following contexts: :table-special, :link,
22025 and :keyword."
22026 (let* ((f (get-text-property (point) 'face))
22027 (faces (if (listp f) f (list f)))
22028 (case-fold-search t)
22029 (p (point)) clist o)
22030 ;; First the large context
22031 (cond
22032 ((org-at-heading-p t)
22033 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22034 (when (progn
22035 (beginning-of-line 1)
22036 (looking-at org-todo-line-tags-regexp))
22037 (push (org-point-in-group p 1 :headline-stars) clist)
22038 (push (org-point-in-group p 2 :todo-keyword) clist)
22039 (push (org-point-in-group p 4 :tags) clist))
22040 (goto-char p)
22041 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22042 (when (looking-at "\\[#[A-Z0-9]\\]")
22043 (push (org-point-in-group p 0 :priority) clist)))
22045 ((org-at-item-p)
22046 (push (org-point-in-group p 2 :item-bullet) clist)
22047 (push (list :item (point-at-bol)
22048 (save-excursion (org-end-of-item) (point)))
22049 clist)
22050 (and (org-at-item-checkbox-p)
22051 (push (org-point-in-group p 0 :checkbox) clist)))
22053 ((org-at-table-p)
22054 (push (list :table (org-table-begin) (org-table-end)) clist)
22055 (when (memq 'org-formula faces)
22056 (push (list :table-special
22057 (previous-single-property-change p 'face)
22058 (next-single-property-change p 'face)) clist)))
22059 ((org-at-table-p 'any)
22060 (push (list :table-table) clist)))
22061 (goto-char p)
22063 (let ((case-fold-search t))
22064 ;; New the "medium" contexts: clocktables, source blocks
22065 (cond ((org-in-clocktable-p)
22066 (push (list :clocktable
22067 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22068 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22069 (match-beginning 1))
22070 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22071 (match-end 0))) clist))
22072 ((org-in-src-block-p)
22073 (push (list :src-block
22074 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22075 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22076 (match-beginning 1))
22077 (and (search-forward "#+END_SRC" nil t)
22078 (match-beginning 0))) clist))))
22079 (goto-char p)
22081 ;; Now the small context
22082 (cond
22083 ((org-at-timestamp-p)
22084 (push (org-point-in-group p 0 :timestamp) clist))
22085 ((memq 'org-link faces)
22086 (push (list :link
22087 (previous-single-property-change p 'face)
22088 (next-single-property-change p 'face)) clist))
22089 ((memq 'org-special-keyword faces)
22090 (push (list :keyword
22091 (previous-single-property-change p 'face)
22092 (next-single-property-change p 'face)) clist))
22093 ((org-at-target-p)
22094 (push (org-point-in-group p 0 :target) clist)
22095 (goto-char (1- (match-beginning 0)))
22096 (when (looking-at org-radio-target-regexp)
22097 (push (org-point-in-group p 0 :radio-target) clist))
22098 (goto-char p))
22099 ((setq o (cl-some
22100 (lambda (o)
22101 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22103 (overlays-at (point))))
22104 (push (list :latex-fragment
22105 (overlay-start o) (overlay-end o)) clist)
22106 (push (list :latex-preview
22107 (overlay-start o) (overlay-end o)) clist))
22108 ((org-inside-LaTeX-fragment-p)
22109 ;; FIXME: positions wrong.
22110 (push (list :latex-fragment (point) (point)) clist)))
22112 (setq clist (nreverse (delq nil clist)))
22113 clist))
22115 (defun org-in-regexp (regexp &optional nlines visually)
22116 "Check if point is inside a match of REGEXP.
22118 Normally only the current line is checked, but you can include
22119 NLINES extra lines around point into the search. If VISUALLY is
22120 set, require that the cursor is not after the match but really
22121 on, so that the block visually is on the match.
22123 Return nil or a cons cell (BEG . END) where BEG and END are,
22124 respectively, the positions at the beginning and the end of the
22125 match."
22126 (catch :exit
22127 (let ((pos (point))
22128 (eol (line-end-position (if nlines (1+ nlines) 1))))
22129 (save-excursion
22130 (beginning-of-line (- 1 (or nlines 0)))
22131 (while (and (re-search-forward regexp eol t)
22132 (<= (match-beginning 0) pos))
22133 (let ((end (match-end 0)))
22134 (when (or (> end pos) (and (= end pos) (not visually)))
22135 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22137 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22138 "Non-nil when point is between matches of START-RE and END-RE.
22140 Also return a non-nil value when point is on one of the matches.
22142 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22143 buffer positions. Default values are the positions of headlines
22144 surrounding the point.
22146 The functions returns a cons cell whose car (resp. cdr) is the
22147 position before START-RE (resp. after END-RE)."
22148 (save-match-data
22149 (let ((pos (point))
22150 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22151 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22152 beg end)
22153 (save-excursion
22154 ;; Point is on a block when on START-RE or if START-RE can be
22155 ;; found before it...
22156 (and (or (org-in-regexp start-re)
22157 (re-search-backward start-re limit-up t))
22158 (setq beg (match-beginning 0))
22159 ;; ... and END-RE after it...
22160 (goto-char (match-end 0))
22161 (re-search-forward end-re limit-down t)
22162 (> (setq end (match-end 0)) pos)
22163 ;; ... without another START-RE in-between.
22164 (goto-char (match-beginning 0))
22165 (not (re-search-backward start-re (1+ beg) t))
22166 ;; Return value.
22167 (cons beg end))))))
22169 (defun org-in-block-p (names)
22170 "Non-nil when point belongs to a block whose name belongs to NAMES.
22172 NAMES is a list of strings containing names of blocks.
22174 Return first block name matched, or nil. Beware that in case of
22175 nested blocks, the returned name may not belong to the closest
22176 block from point."
22177 (save-match-data
22178 (catch 'exit
22179 (let ((case-fold-search t)
22180 (lim-up (save-excursion (outline-previous-heading)))
22181 (lim-down (save-excursion (outline-next-heading))))
22182 (dolist (name names)
22183 (let ((n (regexp-quote name)))
22184 (when (org-between-regexps-p
22185 (concat "^[ \t]*#\\+begin_" n)
22186 (concat "^[ \t]*#\\+end_" n)
22187 lim-up lim-down)
22188 (throw 'exit n)))))
22189 nil)))
22191 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22192 "Call `multi-occur' with buffers for all agenda files."
22193 (interactive "sOrg-files matching: ")
22194 (let* ((files (org-agenda-files))
22195 (tnames (mapcar #'file-truename files))
22196 (extra org-agenda-text-search-extra-files))
22197 (when (eq (car extra) 'agenda-archives)
22198 (setq extra (cdr extra))
22199 (setq files (org-add-archive-files files)))
22200 (dolist (f extra)
22201 (unless (member (file-truename f) tnames)
22202 (unless (member f files) (setq files (append files (list f))))
22203 (setq tnames (append tnames (list (file-truename f))))))
22204 (multi-occur
22205 (mapcar (lambda (x)
22206 (with-current-buffer
22207 ;; FIXME: Why not just (find-file-noselect x)?
22208 ;; Is it to avoid the "revert buffer" prompt?
22209 (or (get-file-buffer x) (find-file-noselect x))
22210 (widen)
22211 (current-buffer)))
22212 files)
22213 regexp)))
22215 (add-hook 'occur-mode-find-occurrence-hook
22216 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22218 (defun org-occur-link-in-agenda-files ()
22219 "Create a link and search for it in the agendas.
22220 The link is not stored in `org-stored-links', it is just created
22221 for the search purpose."
22222 (interactive)
22223 (let ((link (condition-case nil
22224 (org-store-link nil)
22225 (error "Unable to create a link to here"))))
22226 (org-occur-in-agenda-files (regexp-quote link))))
22228 (defun org-reverse-string (string)
22229 "Return the reverse of STRING."
22230 (apply 'string (reverse (string-to-list string))))
22232 ;; defsubst org-uniquify must be defined before first use
22234 (defun org-uniquify-alist (alist)
22235 "Merge elements of ALIST with the same key.
22237 For example, in this alist:
22239 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22240 => \\='((a 1 3) (b 2))
22242 merge (a 1) and (a 3) into (a 1 3).
22244 The function returns the new ALIST."
22245 (let (rtn)
22246 (dolist (e alist rtn)
22247 (let (n)
22248 (if (not (assoc (car e) rtn))
22249 (push e rtn)
22250 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22251 (setq rtn (assq-delete-all (car e) rtn))
22252 (push n rtn))))))
22254 (defun org-delete-all (elts list)
22255 "Remove all elements in ELTS from LIST.
22256 Comparison is done with `equal'. It is a destructive operation
22257 that may remove elements by altering the list structure."
22258 (while elts
22259 (setq list (delete (pop elts) list)))
22260 list)
22262 (defun org-back-over-empty-lines ()
22263 "Move backwards over whitespace, to the beginning of the first empty line.
22264 Returns the number of empty lines passed."
22265 (let ((pos (point)))
22266 (if (cdr (assq 'heading org-blank-before-new-entry))
22267 (skip-chars-backward " \t\n\r")
22268 (unless (eobp)
22269 (forward-line -1)))
22270 (beginning-of-line 2)
22271 (goto-char (min (point) pos))
22272 (count-lines (point) pos)))
22274 (defun org-skip-whitespace ()
22275 (skip-chars-forward " \t\n\r"))
22277 (defun org-point-in-group (point group &optional context)
22278 "Check if POINT is in match-group GROUP.
22279 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22280 match. If the match group does not exist or point is not inside it,
22281 return nil."
22282 (and (match-beginning group)
22283 (>= point (match-beginning group))
22284 (<= point (match-end group))
22285 (if context
22286 (list context (match-beginning group) (match-end group))
22287 t)))
22289 (defun org-switch-to-buffer-other-window (&rest args)
22290 "Switch to buffer in a second window on the current frame.
22291 In particular, do not allow pop-up frames.
22292 Returns the newly created buffer."
22293 (org-no-popups
22294 (apply 'switch-to-buffer-other-window args)))
22296 (defun org-combine-plists (&rest plists)
22297 "Create a single property list from all plists in PLISTS.
22298 The process starts by copying the first list, and then setting properties
22299 from the other lists. Settings in the last list are the most significant
22300 ones and overrule settings in the other lists."
22301 (let ((rtn (copy-sequence (pop plists)))
22302 p v ls)
22303 (while plists
22304 (setq ls (pop plists))
22305 (while ls
22306 (setq p (pop ls) v (pop ls))
22307 (setq rtn (plist-put rtn p v))))
22308 rtn))
22310 (defun org-replace-escapes (string table)
22311 "Replace %-escapes in STRING with values in TABLE.
22312 TABLE is an association list with keys like \"%a\" and string values.
22313 The sequences in STRING may contain normal field width and padding information,
22314 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22315 so values can contain further %-escapes if they are define later in TABLE."
22316 (let ((tbl (copy-alist table))
22317 (case-fold-search nil)
22318 (pchg 0)
22319 re rpl)
22320 (dolist (e tbl)
22321 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22322 (when (and (cdr e) (string-match re (cdr e)))
22323 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22324 (safe "SREF"))
22325 (add-text-properties 0 3 (list 'sref sref) safe)
22326 (setcdr e (replace-match safe t t (cdr e)))))
22327 (while (string-match re string)
22328 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22329 (cdr e)))
22330 (setq string (replace-match rpl t t string))))
22331 (while (setq pchg (next-property-change pchg string))
22332 (let ((sref (get-text-property pchg 'sref string)))
22333 (when (and sref (string-match "SREF" string pchg))
22334 (setq string (replace-match sref t t string)))))
22335 string))
22337 (defun org-find-base-buffer-visiting (file)
22338 "Like `find-buffer-visiting' but always return the base buffer and
22339 not an indirect buffer."
22340 (let ((buf (or (get-file-buffer file)
22341 (find-buffer-visiting file))))
22342 (if buf
22343 (or (buffer-base-buffer buf) buf)
22344 nil)))
22346 ;;; TODO: Only called once, from ox-odt which should probably use
22347 ;;; org-export-inline-image-p or something.
22348 (defun org-file-image-p (file)
22349 "Return non-nil if FILE is an image."
22350 (save-match-data
22351 (string-match (image-file-name-regexp) file)))
22353 (defun org-get-cursor-date (&optional with-time)
22354 "Return the date at cursor in as a time.
22355 This works in the calendar and in the agenda, anywhere else it just
22356 returns the current time.
22357 If WITH-TIME is non-nil, returns the time of the event at point (in
22358 the agenda) or the current time of the day."
22359 (let (date day defd tp hod mod)
22360 (when with-time
22361 (setq tp (get-text-property (point) 'time))
22362 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22363 (setq hod (string-to-number (match-string 1 tp))
22364 mod (string-to-number (match-string 2 tp))))
22365 (or tp (let ((now (decode-time)))
22366 (setq hod (nth 2 now)
22367 mod (nth 1 now)))))
22368 (cond
22369 ((eq major-mode 'calendar-mode)
22370 (setq date (calendar-cursor-to-date)
22371 defd (encode-time 0 (or mod 0) (or hod 0)
22372 (nth 1 date) (nth 0 date) (nth 2 date))))
22373 ((eq major-mode 'org-agenda-mode)
22374 (setq day (get-text-property (point) 'day))
22375 (when day
22376 (setq date (calendar-gregorian-from-absolute day)
22377 defd (encode-time 0 (or mod 0) (or hod 0)
22378 (nth 1 date) (nth 0 date) (nth 2 date))))))
22379 (or defd (current-time))))
22381 (defun org-mark-subtree (&optional up)
22382 "Mark the current subtree.
22383 This puts point at the start of the current subtree, and mark at
22384 the end. If a numeric prefix UP is given, move up into the
22385 hierarchy of headlines by UP levels before marking the subtree."
22386 (interactive "P")
22387 (org-with-limited-levels
22388 (cond ((org-at-heading-p) (beginning-of-line))
22389 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22390 (t (outline-previous-visible-heading 1))))
22391 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22392 (if (called-interactively-p 'any)
22393 (call-interactively 'org-mark-element)
22394 (org-mark-element)))
22396 (defun org-file-newer-than-p (file time)
22397 "Non-nil if FILE is newer than TIME.
22398 FILE is a filename, as a string, TIME is a list of integers, as
22399 returned by, e.g., `current-time'."
22400 (and (file-exists-p file)
22401 ;; Only compare times up to whole seconds as some file-systems
22402 ;; (e.g. HFS+) do not retain any finer granularity. As
22403 ;; a consequence, make sure we return non-nil when the two
22404 ;; times are equal.
22405 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22406 (cl-subseq time 0 2)))))
22408 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22409 "Compile a SOURCE file using PROCESS.
22411 PROCESS is either a function or a list of shell commands, as
22412 strings. EXT is a file extension, without the leading dot, as
22413 a string. It is used to check if the process actually succeeded.
22415 PROCESS must create a file with the same base name and directory
22416 as SOURCE, but ending with EXT. The function then returns its
22417 filename. Otherwise, it raises an error. The error message can
22418 then be refined by providing string ERR-MSG, which is appended to
22419 the standard message.
22421 If PROCESS is a function, it is called with a single argument:
22422 the SOURCE file.
22424 If it is a list of commands, each of them is called using
22425 `shell-command'. By default, in each command, %b, %f, %F, %o and
22426 %O are replaced with, respectively, SOURCE base name, name, full
22427 name, directory and absolute output file name. It is possible,
22428 however, to use more place-holders by specifying them in optional
22429 argument SPEC, as an alist following the pattern
22431 (CHARACTER . REPLACEMENT-STRING).
22433 When PROCESS is a list of commands, optional argument LOG-BUF can
22434 be set to a buffer or a buffer name. `shell-command' then uses
22435 it for output."
22436 (let* ((base-name (file-name-base source))
22437 (full-name (file-truename source))
22438 (out-dir (or (file-name-directory source) "./"))
22439 (output (expand-file-name (concat base-name "." ext) out-dir))
22440 (time (current-time))
22441 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22442 (save-window-excursion
22443 (pcase process
22444 ((pred functionp) (funcall process (shell-quote-argument source)))
22445 ((pred consp)
22446 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22447 (spec (append spec
22448 `((?b . ,(shell-quote-argument base-name))
22449 (?f . ,(shell-quote-argument source))
22450 (?F . ,(shell-quote-argument full-name))
22451 (?o . ,(shell-quote-argument out-dir))
22452 (?O . ,(shell-quote-argument output))))))
22453 (dolist (command process)
22454 (shell-command (format-spec command spec) log-buf))
22455 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22456 (_ (error "No valid command to process %S%s" source err-msg))))
22457 ;; Check for process failure. Output file is expected to be
22458 ;; located in the same directory as SOURCE.
22459 (unless (org-file-newer-than-p output time)
22460 (error (format "File %S wasn't produced%s" output err-msg)))
22461 output))
22463 ;;; Indentation
22465 (defvar org-element-greater-elements)
22466 (defun org--get-expected-indentation (element contentsp)
22467 "Expected indentation column for current line, according to ELEMENT.
22468 ELEMENT is an element containing point. CONTENTSP is non-nil
22469 when indentation is to be computed according to contents of
22470 ELEMENT."
22471 (let ((type (org-element-type element))
22472 (start (org-element-property :begin element))
22473 (post-affiliated (org-element-property :post-affiliated element)))
22474 (org-with-wide-buffer
22475 (cond
22476 (contentsp
22477 (cl-case type
22478 ((diary-sexp footnote-definition) 0)
22479 ((headline inlinetask nil)
22480 (if (not org-adapt-indentation) 0
22481 (let ((level (org-current-level)))
22482 (if level (1+ level) 0))))
22483 ((item plain-list) (org-list-item-body-column post-affiliated))
22485 (goto-char start)
22486 (org-get-indentation))))
22487 ((memq type '(headline inlinetask nil))
22488 (if (org-match-line "[ \t]*$")
22489 (org--get-expected-indentation element t)
22491 ((memq type '(diary-sexp footnote-definition)) 0)
22492 ;; First paragraph of a footnote definition or an item.
22493 ;; Indent like parent.
22494 ((< (line-beginning-position) start)
22495 (org--get-expected-indentation
22496 (org-element-property :parent element) t))
22497 ;; At first line: indent according to previous sibling, if any,
22498 ;; ignoring footnote definitions and inline tasks, or parent's
22499 ;; contents.
22500 ((= (line-beginning-position) start)
22501 (catch 'exit
22502 (while t
22503 (if (= (point-min) start) (throw 'exit 0)
22504 (goto-char (1- start))
22505 (let* ((previous (org-element-at-point))
22506 (parent previous))
22507 (while (and parent (<= (org-element-property :end parent) start))
22508 (setq previous parent
22509 parent (org-element-property :parent parent)))
22510 (cond
22511 ((not previous) (throw 'exit 0))
22512 ((> (org-element-property :end previous) start)
22513 (throw 'exit (org--get-expected-indentation previous t)))
22514 ((memq (org-element-type previous)
22515 '(footnote-definition inlinetask))
22516 (setq start (org-element-property :begin previous)))
22517 (t (goto-char (org-element-property :begin previous))
22518 (throw 'exit
22519 (if (bolp) (org-get-indentation)
22520 ;; At first paragraph in an item or
22521 ;; a footnote definition.
22522 (org--get-expected-indentation
22523 (org-element-property :parent previous) t))))))))))
22524 ;; Otherwise, move to the first non-blank line above.
22526 (beginning-of-line)
22527 (let ((pos (point)))
22528 (skip-chars-backward " \r\t\n")
22529 (cond
22530 ;; Two blank lines end a footnote definition or a plain
22531 ;; list. When we indent an empty line after them, the
22532 ;; containing list or footnote definition is over, so it
22533 ;; qualifies as a previous sibling. Therefore, we indent
22534 ;; like its first line.
22535 ((and (memq type '(footnote-definition plain-list))
22536 (> (count-lines (point) pos) 2))
22537 (goto-char start)
22538 (org-get-indentation))
22539 ;; Line above is the first one of a paragraph at the
22540 ;; beginning of an item or a footnote definition. Indent
22541 ;; like parent.
22542 ((< (line-beginning-position) start)
22543 (org--get-expected-indentation
22544 (org-element-property :parent element) t))
22545 ;; Line above is the beginning of an element, i.e., point
22546 ;; was originally on the blank lines between element's start
22547 ;; and contents.
22548 ((= (line-beginning-position) post-affiliated)
22549 (org--get-expected-indentation element t))
22550 ;; POS is after contents in a greater element. Indent like
22551 ;; the beginning of the element.
22552 ((and (memq type org-element-greater-elements)
22553 (let ((cend (org-element-property :contents-end element)))
22554 (and cend (<= cend pos))))
22555 ;; As a special case, if point is at the end of a footnote
22556 ;; definition or an item, indent like the very last element
22557 ;; within. If that last element is an item, indent like
22558 ;; its contents.
22559 (if (memq type '(footnote-definition item plain-list))
22560 (let ((last (org-element-at-point)))
22561 (goto-char pos)
22562 (org--get-expected-indentation
22563 last (eq (org-element-type last) 'item)))
22564 (goto-char start)
22565 (org-get-indentation)))
22566 ;; In any other case, indent like the current line.
22567 (t (org-get-indentation)))))))))
22569 (defun org--align-node-property ()
22570 "Align node property at point.
22571 Alignment is done according to `org-property-format', which see."
22572 (when (save-excursion
22573 (beginning-of-line)
22574 (looking-at org-property-re))
22575 (replace-match
22576 (concat (match-string 4)
22577 (org-trim
22578 (format org-property-format (match-string 1) (match-string 3))))
22579 t t)))
22581 (defun org-indent-line ()
22582 "Indent line depending on context.
22584 Indentation is done according to the following rules:
22586 - Footnote definitions, diary sexps, headlines and inline tasks
22587 have to start at column 0.
22589 - On the very first line of an element, consider, in order, the
22590 next rules until one matches:
22592 1. If there's a sibling element before, ignoring footnote
22593 definitions and inline tasks, indent like its first line.
22595 2. If element has a parent, indent like its contents. More
22596 precisely, if parent is an item, indent after the
22597 description part, if any, or the bullet (see
22598 `org-list-description-max-indent'). Else, indent like
22599 parent's first line.
22601 3. Otherwise, indent relatively to current level, if
22602 `org-adapt-indentation' is non-nil, or to left margin.
22604 - On a blank line at the end of an element, indent according to
22605 the type of the element. More precisely
22607 1. If element is a plain list, an item, or a footnote
22608 definition, indent like the very last element within.
22610 2. If element is a paragraph, indent like its last non blank
22611 line.
22613 3. Otherwise, indent like its very first line.
22615 - In the code part of a source block, use language major mode
22616 to indent current line if `org-src-tab-acts-natively' is
22617 non-nil. If it is nil, do nothing.
22619 - Otherwise, indent like the first non-blank line above.
22621 The function doesn't indent an item as it could break the whole
22622 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22623 `\\[org-shiftmetaright]'.
22625 Also align node properties according to `org-property-format'."
22626 (interactive)
22627 (cond
22628 (orgstruct-is-++
22629 (let ((indent-line-function
22630 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22631 (indent-according-to-mode)))
22632 ((org-at-heading-p) 'noindent)
22634 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22635 (type (org-element-type element)))
22636 (cond ((and (memq type '(plain-list item))
22637 (= (line-beginning-position)
22638 (org-element-property :post-affiliated element)))
22639 'noindent)
22640 ((and (eq type 'latex-environment)
22641 (>= (point) (org-element-property :post-affiliated element))
22642 (< (point) (org-with-wide-buffer
22643 (goto-char (org-element-property :end element))
22644 (skip-chars-backward " \r\t\n")
22645 (line-beginning-position 2))))
22646 'noindent)
22647 ((and (eq type 'src-block)
22648 org-src-tab-acts-natively
22649 (> (line-beginning-position)
22650 (org-element-property :post-affiliated element))
22651 (< (line-beginning-position)
22652 (org-with-wide-buffer
22653 (goto-char (org-element-property :end element))
22654 (skip-chars-backward " \r\t\n")
22655 (line-beginning-position))))
22656 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22658 (let ((column (org--get-expected-indentation element nil)))
22659 ;; Preserve current column.
22660 (if (<= (current-column) (current-indentation))
22661 (indent-line-to column)
22662 (save-excursion (indent-line-to column))))
22663 ;; Align node property. Also preserve current column.
22664 (when (eq type 'node-property)
22665 (let ((column (current-column)))
22666 (org--align-node-property)
22667 (org-move-to-column column)))))))))
22669 (defun org-indent-region (start end)
22670 "Indent each non-blank line in the region.
22671 Called from a program, START and END specify the region to
22672 indent. The function will not indent contents of example blocks,
22673 verse blocks and export blocks as leading white spaces are
22674 assumed to be significant there."
22675 (interactive "r")
22676 (save-excursion
22677 (goto-char start)
22678 (skip-chars-forward " \r\t\n")
22679 (unless (eobp) (beginning-of-line))
22680 (let ((indent-to
22681 (lambda (ind pos)
22682 ;; Set IND as indentation for all lines between point and
22683 ;; POS. Blank lines are ignored. Leave point after POS
22684 ;; once done.
22685 (let ((limit (copy-marker pos)))
22686 (while (< (point) limit)
22687 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22688 (forward-line))
22689 (set-marker limit nil))))
22690 (end (copy-marker end)))
22691 (while (< (point) end)
22692 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22693 (let* ((element (org-element-at-point))
22694 (type (org-element-type element))
22695 (element-end (copy-marker (org-element-property :end element)))
22696 (ind (org--get-expected-indentation element nil)))
22697 (cond
22698 ;; Element indented as a single block. Example blocks
22699 ;; preserving indentation are a special case since the
22700 ;; "contents" must not be indented whereas the block
22701 ;; boundaries can.
22702 ((or (memq type '(export-block latex-environment))
22703 (and (eq type 'example-block)
22704 (not
22705 (or org-src-preserve-indentation
22706 (org-element-property :preserve-indent element)))))
22707 (let ((offset (- ind (org-get-indentation))))
22708 (unless (zerop offset)
22709 (indent-rigidly (org-element-property :begin element)
22710 (org-element-property :end element)
22711 offset)))
22712 (goto-char element-end))
22713 ;; Elements indented line wise. Be sure to exclude
22714 ;; example blocks (preserving indentation) and source
22715 ;; blocks from this category as they are treated
22716 ;; specially later.
22717 ((or (memq type '(paragraph table table-row))
22718 (not (or (org-element-property :contents-begin element)
22719 (memq type '(example-block src-block)))))
22720 (when (eq type 'node-property)
22721 (org--align-node-property)
22722 (beginning-of-line))
22723 (funcall indent-to ind (min element-end end)))
22724 ;; Elements consisting of three parts: before the
22725 ;; contents, the contents, and after the contents. The
22726 ;; contents are treated specially, according to the
22727 ;; element type, or not indented at all. Other parts are
22728 ;; indented as a single block.
22730 (let* ((post (copy-marker
22731 (org-element-property :post-affiliated element)))
22732 (cbeg
22733 (copy-marker
22734 (cond
22735 ((not (org-element-property :contents-begin element))
22736 ;; Fake contents for source blocks.
22737 (org-with-wide-buffer
22738 (goto-char post)
22739 (line-beginning-position 2)))
22740 ((memq type '(footnote-definition item plain-list))
22741 ;; Contents in these elements could start on
22742 ;; the same line as the beginning of the
22743 ;; element. Make sure we start indenting
22744 ;; from the second line.
22745 (org-with-wide-buffer
22746 (goto-char post)
22747 (end-of-line)
22748 (skip-chars-forward " \r\t\n")
22749 (if (eobp) (point) (line-beginning-position))))
22750 (t (org-element-property :contents-begin element)))))
22751 (cend (copy-marker
22752 (or (org-element-property :contents-end element)
22753 ;; Fake contents for source blocks.
22754 (org-with-wide-buffer
22755 (goto-char element-end)
22756 (skip-chars-backward " \r\t\n")
22757 (line-beginning-position)))
22758 t)))
22759 ;; Do not change items indentation individually as it
22760 ;; might break the list as a whole. On the other
22761 ;; hand, when at a plain list, indent it as a whole.
22762 (cond ((eq type 'plain-list)
22763 (let ((offset (- ind (org-get-indentation))))
22764 (unless (zerop offset)
22765 (indent-rigidly (org-element-property :begin element)
22766 (org-element-property :end element)
22767 offset))
22768 (goto-char cbeg)))
22769 ((eq type 'item) (goto-char cbeg))
22770 (t (funcall indent-to ind (min cbeg end))))
22771 (when (< (point) end)
22772 (cl-case type
22773 ((example-block verse-block))
22774 (src-block
22775 ;; In a source block, indent source code
22776 ;; according to language major mode, but only if
22777 ;; `org-src-tab-acts-natively' is non-nil.
22778 (when (and (< (point) end) org-src-tab-acts-natively)
22779 (ignore-errors
22780 (org-babel-do-in-edit-buffer
22781 (indent-region (point-min) (point-max))))))
22782 (t (org-indent-region (point) (min cend end))))
22783 (goto-char (min cend end))
22784 (when (< (point) end)
22785 (funcall indent-to ind (min element-end end))))
22786 (set-marker post nil)
22787 (set-marker cbeg nil)
22788 (set-marker cend nil))))
22789 (set-marker element-end nil))))
22790 (set-marker end nil))))
22792 (defun org-indent-drawer ()
22793 "Indent the drawer at point."
22794 (interactive)
22795 (unless (save-excursion
22796 (beginning-of-line)
22797 (looking-at-p org-drawer-regexp))
22798 (user-error "Not at a drawer"))
22799 (let ((element (org-element-at-point)))
22800 (unless (memq (org-element-type element) '(drawer property-drawer))
22801 (user-error "Not at a drawer"))
22802 (org-with-wide-buffer
22803 (org-indent-region (org-element-property :begin element)
22804 (org-element-property :end element))))
22805 (message "Drawer at point indented"))
22807 (defun org-indent-block ()
22808 "Indent the block at point."
22809 (interactive)
22810 (unless (save-excursion
22811 (beginning-of-line)
22812 (let ((case-fold-search t))
22813 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22814 (user-error "Not at a block"))
22815 (let ((element (org-element-at-point)))
22816 (unless (memq (org-element-type element)
22817 '(comment-block center-block dynamic-block example-block
22818 export-block quote-block special-block
22819 src-block verse-block))
22820 (user-error "Not at a block"))
22821 (org-with-wide-buffer
22822 (org-indent-region (org-element-property :begin element)
22823 (org-element-property :end element))))
22824 (message "Block at point indented"))
22827 ;;; Filling
22829 ;; We use our own fill-paragraph and auto-fill functions.
22831 ;; `org-fill-paragraph' relies on adaptive filling and context
22832 ;; checking. Appropriate `fill-prefix' is computed with
22833 ;; `org-adaptive-fill-function'.
22835 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22836 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22837 ;; `org-adaptive-fill-function' value. Internally,
22838 ;; `org-comment-line-break-function' breaks the line.
22840 ;; `org-setup-filling' installs filling and auto-filling related
22841 ;; variables during `org-mode' initialization.
22843 (defvar org-element-paragraph-separate) ; org-element.el
22844 (defun org-setup-filling ()
22845 (require 'org-element)
22846 ;; Prevent auto-fill from inserting unwanted new items.
22847 (when (boundp 'fill-nobreak-predicate)
22848 (setq-local
22849 fill-nobreak-predicate
22850 (org-uniquify
22851 (append fill-nobreak-predicate
22852 '(org-fill-line-break-nobreak-p
22853 org-fill-n-macro-as-item-nobreak-p
22854 org-fill-paragraph-with-timestamp-nobreak-p)))))
22855 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22856 (setq-local paragraph-start paragraph-ending)
22857 (setq-local paragraph-separate paragraph-ending))
22858 (setq-local fill-paragraph-function 'org-fill-paragraph)
22859 (setq-local auto-fill-inhibit-regexp nil)
22860 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22861 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22862 (setq-local comment-line-break-function 'org-comment-line-break-function))
22864 (defun org-fill-line-break-nobreak-p ()
22865 "Non-nil when a new line at point would create an Org line break."
22866 (save-excursion
22867 (skip-chars-backward "[ \t]")
22868 (skip-chars-backward "\\\\")
22869 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22871 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22872 "Non-nil when a new line at point would split a timestamp."
22873 (and (org-at-timestamp-p 'lax)
22874 (not (looking-at org-ts-regexp-both))))
22876 (defun org-fill-n-macro-as-item-nobreak-p ()
22877 "Non-nil when a new line at point would create a new list."
22878 ;; During export, a "n" macro followed by a dot or a closing
22879 ;; parenthesis can end up being parsed as a new list item.
22880 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22882 (declare-function message-in-body-p "message" ())
22883 (defvar orgtbl-line-start-regexp) ; From org-table.el
22884 (defun org-adaptive-fill-function ()
22885 "Compute a fill prefix for the current line.
22886 Return fill prefix, as a string, or nil if current line isn't
22887 meant to be filled. For convenience, if `adaptive-fill-regexp'
22888 matches in paragraphs or comments, use it."
22889 (catch 'exit
22890 (when (derived-mode-p 'message-mode)
22891 (save-excursion
22892 (beginning-of-line)
22893 (cond ((not (message-in-body-p)) (throw 'exit nil))
22894 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22895 ((looking-at message-cite-prefix-regexp)
22896 (throw 'exit (match-string-no-properties 0)))
22897 ((looking-at org-outline-regexp)
22898 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22899 (org-with-wide-buffer
22900 (unless (org-at-heading-p)
22901 (let* ((p (line-beginning-position))
22902 (element (save-excursion
22903 (beginning-of-line)
22904 (org-element-at-point)))
22905 (type (org-element-type element))
22906 (post-affiliated (org-element-property :post-affiliated element)))
22907 (unless (< p post-affiliated)
22908 (cl-case type
22909 (comment
22910 (save-excursion
22911 (beginning-of-line)
22912 (looking-at "[ \t]*")
22913 (concat (match-string 0) "# ")))
22914 (footnote-definition "")
22915 ((item plain-list)
22916 (make-string (org-list-item-body-column post-affiliated) ?\s))
22917 (paragraph
22918 ;; Fill prefix is usually the same as the current line,
22919 ;; unless the paragraph is at the beginning of an item.
22920 (let ((parent (org-element-property :parent element)))
22921 (save-excursion
22922 (beginning-of-line)
22923 (cond ((eq (org-element-type parent) 'item)
22924 (make-string (org-list-item-body-column
22925 (org-element-property :begin parent))
22926 ?\s))
22927 ((and adaptive-fill-regexp
22928 ;; Locally disable
22929 ;; `adaptive-fill-function' to let
22930 ;; `fill-context-prefix' handle
22931 ;; `adaptive-fill-regexp' variable.
22932 (let (adaptive-fill-function)
22933 (fill-context-prefix
22934 post-affiliated
22935 (org-element-property :end element)))))
22936 ((looking-at "[ \t]+") (match-string 0))
22937 (t "")))))
22938 (comment-block
22939 ;; Only fill contents if P is within block boundaries.
22940 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22941 (forward-line)
22942 (point)))
22943 (cend (save-excursion
22944 (goto-char (org-element-property :end element))
22945 (skip-chars-backward " \r\t\n")
22946 (line-beginning-position))))
22947 (when (and (>= p cbeg) (< p cend))
22948 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22949 (match-string 0)
22950 "")))))))))))
22952 (declare-function message-goto-body "message" ())
22953 (defvar message-cite-prefix-regexp) ; From message.el
22955 (defun org-fill-element (&optional justify)
22956 "Fill element at point, when applicable.
22958 This function only applies to comment blocks, comments, example
22959 blocks and paragraphs. Also, as a special case, re-align table
22960 when point is at one.
22962 If JUSTIFY is non-nil (interactively, with prefix argument),
22963 justify as well. If `sentence-end-double-space' is non-nil, then
22964 period followed by one space does not end a sentence, so don't
22965 break a line there. The variable `fill-column' controls the
22966 width for filling.
22968 For convenience, when point is at a plain list, an item or
22969 a footnote definition, try to fill the first paragraph within."
22970 (with-syntax-table org-mode-transpose-word-syntax-table
22971 ;; Move to end of line in order to get the first paragraph within
22972 ;; a plain list or a footnote definition.
22973 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22974 ;; First check if point is in a blank line at the beginning of
22975 ;; the buffer. In that case, ignore filling.
22976 (cl-case (org-element-type element)
22977 ;; Use major mode filling function is src blocks.
22978 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22979 ;; Align Org tables, leave table.el tables as-is.
22980 (table-row (org-table-align) t)
22981 (table
22982 (when (eq (org-element-property :type element) 'org)
22983 (save-excursion
22984 (goto-char (org-element-property :post-affiliated element))
22985 (org-table-align)))
22987 (paragraph
22988 ;; Paragraphs may contain `line-break' type objects.
22989 (let ((beg (max (point-min)
22990 (org-element-property :contents-begin element)))
22991 (end (min (point-max)
22992 (org-element-property :contents-end element))))
22993 ;; Do nothing if point is at an affiliated keyword.
22994 (if (< (line-end-position) beg) t
22995 (when (derived-mode-p 'message-mode)
22996 ;; In `message-mode', do not fill following citation
22997 ;; in current paragraph nor text before message body.
22998 (let ((body-start (save-excursion (message-goto-body))))
22999 (when body-start (setq beg (max body-start beg))))
23000 (when (save-excursion
23001 (re-search-forward
23002 (concat "^" message-cite-prefix-regexp) end t))
23003 (setq end (match-beginning 0))))
23004 ;; Fill paragraph, taking line breaks into account.
23005 (save-excursion
23006 (goto-char beg)
23007 (let ((cuts (list beg)))
23008 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23009 (when (eq 'line-break
23010 (org-element-type
23011 (save-excursion (backward-char)
23012 (org-element-context))))
23013 (push (point) cuts)))
23014 (dolist (c (delq end cuts))
23015 (fill-region-as-paragraph c end justify)
23016 (setq end c))))
23017 t)))
23018 ;; Contents of `comment-block' type elements should be
23019 ;; filled as plain text, but only if point is within block
23020 ;; markers.
23021 (comment-block
23022 (let* ((case-fold-search t)
23023 (beg (save-excursion
23024 (goto-char (org-element-property :begin element))
23025 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23026 (forward-line)
23027 (point)))
23028 (end (save-excursion
23029 (goto-char (org-element-property :end element))
23030 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23031 (line-beginning-position))))
23032 (if (or (< (point) beg) (> (point) end)) t
23033 (fill-region-as-paragraph
23034 (save-excursion (end-of-line)
23035 (re-search-backward "^[ \t]*$" beg 'move)
23036 (line-beginning-position))
23037 (save-excursion (beginning-of-line)
23038 (re-search-forward "^[ \t]*$" end 'move)
23039 (line-beginning-position))
23040 justify))))
23041 ;; Fill comments.
23042 (comment
23043 (let ((begin (org-element-property :post-affiliated element))
23044 (end (org-element-property :end element)))
23045 (when (and (>= (point) begin) (<= (point) end))
23046 (let ((begin (save-excursion
23047 (end-of-line)
23048 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23049 (progn (forward-line) (point))
23050 begin)))
23051 (end (save-excursion
23052 (end-of-line)
23053 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23054 (1- (line-beginning-position))
23055 (skip-chars-backward " \r\t\n")
23056 (line-end-position)))))
23057 ;; Do not fill comments when at a blank line.
23058 (when (> end begin)
23059 (let ((fill-prefix
23060 (save-excursion
23061 (beginning-of-line)
23062 (looking-at "[ \t]*#")
23063 (let ((comment-prefix (match-string 0)))
23064 (goto-char (match-end 0))
23065 (if (looking-at adaptive-fill-regexp)
23066 (concat comment-prefix (match-string 0))
23067 (concat comment-prefix " "))))))
23068 (save-excursion
23069 (fill-region-as-paragraph begin end justify))))))
23071 ;; Ignore every other element.
23072 (otherwise t)))))
23074 (defun org-fill-paragraph (&optional justify region)
23075 "Fill element at point, when applicable.
23077 This function only applies to comment blocks, comments, example
23078 blocks and paragraphs. Also, as a special case, re-align table
23079 when point is at one.
23081 For convenience, when point is at a plain list, an item or
23082 a footnote definition, try to fill the first paragraph within.
23084 If JUSTIFY is non-nil (interactively, with prefix argument),
23085 justify as well. If `sentence-end-double-space' is non-nil, then
23086 period followed by one space does not end a sentence, so don't
23087 break a line there. The variable `fill-column' controls the
23088 width for filling.
23090 The REGION argument is non-nil if called interactively; in that
23091 case, if Transient Mark mode is enabled and the mark is active,
23092 fill each of the elements in the active region, instead of just
23093 filling the current element."
23094 (interactive (progn
23095 (barf-if-buffer-read-only)
23096 (list (if current-prefix-arg 'full) t)))
23097 (cond
23098 ((and (derived-mode-p 'message-mode)
23099 (or (not (message-in-body-p))
23100 (save-excursion (move-beginning-of-line 1)
23101 (looking-at message-cite-prefix-regexp))))
23102 ;; First ensure filling is correct in message-mode.
23103 (let ((fill-paragraph-function
23104 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23105 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23106 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23107 (paragraph-separate
23108 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23109 (fill-paragraph nil)))
23110 ((and region transient-mark-mode mark-active
23111 (not (eq (region-beginning) (region-end))))
23112 (let ((origin (point-marker))
23113 (start (region-beginning)))
23114 (unwind-protect
23115 (progn
23116 (goto-char (region-end))
23117 (while (> (point) start)
23118 (org-backward-paragraph)
23119 (org-fill-element justify)))
23120 (goto-char origin)
23121 (set-marker origin nil))))
23122 (t (org-fill-element justify))))
23123 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23125 (defun org-auto-fill-function ()
23126 "Auto-fill function."
23127 ;; Check if auto-filling is meaningful.
23128 (let ((fc (current-fill-column)))
23129 (when (and fc (> (current-column) fc))
23130 (let* ((fill-prefix (org-adaptive-fill-function))
23131 ;; Enforce empty fill prefix, if required. Otherwise, it
23132 ;; will be computed again.
23133 (adaptive-fill-mode (not (equal fill-prefix ""))))
23134 (when fill-prefix (do-auto-fill))))))
23136 (defun org-comment-line-break-function (&optional soft)
23137 "Break line at point and indent, continuing comment if within one.
23138 The inserted newline is marked hard if variable
23139 `use-hard-newlines' is true, unless optional argument SOFT is
23140 non-nil."
23141 (if soft (insert-and-inherit ?\n) (newline 1))
23142 (save-excursion (forward-char -1) (delete-horizontal-space))
23143 (delete-horizontal-space)
23144 (indent-to-left-margin)
23145 (insert-before-markers-and-inherit fill-prefix))
23148 ;;; Fixed Width Areas
23150 (defun org-toggle-fixed-width ()
23151 "Toggle fixed-width markup.
23153 Add or remove fixed-width markup on current line, whenever it
23154 makes sense. Return an error otherwise.
23156 If a region is active and if it contains only fixed-width areas
23157 or blank lines, remove all fixed-width markup in it. If the
23158 region contains anything else, convert all non-fixed-width lines
23159 to fixed-width ones.
23161 Blank lines at the end of the region are ignored unless the
23162 region only contains such lines."
23163 (interactive)
23164 (if (not (org-region-active-p))
23165 ;; No region:
23167 ;; Remove fixed width marker only in a fixed-with element.
23169 ;; Add fixed width maker in paragraphs, in blank lines after
23170 ;; elements or at the beginning of a headline or an inlinetask,
23171 ;; and before any one-line elements (e.g., a clock).
23172 (progn
23173 (beginning-of-line)
23174 (let* ((element (org-element-at-point))
23175 (type (org-element-type element)))
23176 (cond
23177 ((and (eq type 'fixed-width)
23178 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23179 (replace-match
23180 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23181 ((and (memq type '(babel-call clock comment diary-sexp headline
23182 horizontal-rule keyword paragraph
23183 planning))
23184 (<= (org-element-property :post-affiliated element) (point)))
23185 (skip-chars-forward " \t")
23186 (insert ": "))
23187 ((and (looking-at-p "[ \t]*$")
23188 (or (eq type 'inlinetask)
23189 (save-excursion
23190 (skip-chars-forward " \r\t\n")
23191 (<= (org-element-property :end element) (point)))))
23192 (delete-region (point) (line-end-position))
23193 (org-indent-line)
23194 (insert ": "))
23195 (t (user-error "Cannot insert a fixed-width line here")))))
23196 ;; Region active.
23197 (let* ((begin (save-excursion
23198 (goto-char (region-beginning))
23199 (line-beginning-position)))
23200 (end (copy-marker
23201 (save-excursion
23202 (goto-char (region-end))
23203 (unless (eolp) (beginning-of-line))
23204 (if (save-excursion (re-search-backward "\\S-" begin t))
23205 (progn (skip-chars-backward " \r\t\n") (point))
23206 (point)))))
23207 (all-fixed-width-p
23208 (catch 'not-all-p
23209 (save-excursion
23210 (goto-char begin)
23211 (skip-chars-forward " \r\t\n")
23212 (when (eobp) (throw 'not-all-p nil))
23213 (while (< (point) end)
23214 (let ((element (org-element-at-point)))
23215 (if (eq (org-element-type element) 'fixed-width)
23216 (goto-char (org-element-property :end element))
23217 (throw 'not-all-p nil))))
23218 t))))
23219 (if all-fixed-width-p
23220 (save-excursion
23221 (goto-char begin)
23222 (while (< (point) end)
23223 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23224 (replace-match
23225 "" nil nil nil
23226 (if (= (line-end-position) (match-end 0)) 0 1)))
23227 (forward-line)))
23228 (let ((min-ind (point-max)))
23229 ;; Find minimum indentation across all lines.
23230 (save-excursion
23231 (goto-char begin)
23232 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23233 (setq min-ind 0)
23234 (catch 'zerop
23235 (while (< (point) end)
23236 (unless (looking-at-p "[ \t]*$")
23237 (let ((ind (org-get-indentation)))
23238 (setq min-ind (min min-ind ind))
23239 (when (zerop ind) (throw 'zerop t))))
23240 (forward-line)))))
23241 ;; Loop over all lines and add fixed-width markup everywhere
23242 ;; but in fixed-width lines.
23243 (save-excursion
23244 (goto-char begin)
23245 (while (< (point) end)
23246 (cond
23247 ((org-at-heading-p)
23248 (insert ": ")
23249 (forward-line)
23250 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23251 (insert ":")
23252 (forward-line)))
23253 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23254 (let* ((element (org-element-at-point))
23255 (element-end (org-element-property :end element)))
23256 (if (eq (org-element-type element) 'fixed-width)
23257 (progn (goto-char element-end)
23258 (skip-chars-backward " \r\t\n")
23259 (forward-line))
23260 (let ((limit (min end element-end)))
23261 (while (< (point) limit)
23262 (org-move-to-column min-ind t)
23263 (insert ": ")
23264 (forward-line))))))
23266 (org-move-to-column min-ind t)
23267 (insert ": ")
23268 (forward-line)))))))
23269 (set-marker end nil))))
23272 ;;; Comments
23274 ;; Org comments syntax is quite complex. It requires the entire line
23275 ;; to be just a comment. Also, even with the right syntax at the
23276 ;; beginning of line, some elements (e.g., verse-block or
23277 ;; example-block) don't accept comments. Usual Emacs comment commands
23278 ;; cannot cope with those requirements. Therefore, Org replaces them.
23280 ;; Org still relies on `comment-dwim', but cannot trust
23281 ;; `comment-only-p'. So, `comment-region-function' and
23282 ;; `uncomment-region-function' both point
23283 ;; to`org-comment-or-uncomment-region'. Eventually,
23284 ;; `org-insert-comment' takes care of insertion of comments at the
23285 ;; beginning of line.
23287 ;; `org-setup-comments-handling' install comments related variables
23288 ;; during `org-mode' initialization.
23290 (defun org-setup-comments-handling ()
23291 (interactive)
23292 (setq-local comment-use-syntax nil)
23293 (setq-local comment-start "# ")
23294 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23295 (setq-local comment-insert-comment-function 'org-insert-comment)
23296 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23297 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23299 (defun org-insert-comment ()
23300 "Insert an empty comment above current line.
23301 If the line is empty, insert comment at its beginning. When
23302 point is within a source block, comment according to the related
23303 major mode."
23304 (if (let ((element (org-element-at-point)))
23305 (and (eq (org-element-type element) 'src-block)
23306 (< (save-excursion
23307 (goto-char (org-element-property :post-affiliated element))
23308 (line-end-position))
23309 (point))
23310 (> (save-excursion
23311 (goto-char (org-element-property :end element))
23312 (skip-chars-backward " \r\t\n")
23313 (line-beginning-position))
23314 (point))))
23315 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23316 (beginning-of-line)
23317 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23318 (open-line 1))
23319 (org-indent-line)
23320 (insert "# ")))
23322 (defvar comment-empty-lines) ; From newcomment.el.
23323 (defun org-comment-or-uncomment-region (beg end &rest _)
23324 "Comment or uncomment each non-blank line in the region.
23325 Uncomment each non-blank line between BEG and END if it only
23326 contains commented lines. Otherwise, comment them. If region is
23327 strictly within a source block, use appropriate comment syntax."
23328 (if (let ((element (org-element-at-point)))
23329 (and (eq (org-element-type element) 'src-block)
23330 (< (save-excursion
23331 (goto-char (org-element-property :post-affiliated element))
23332 (line-end-position))
23333 beg)
23334 (>= (save-excursion
23335 (goto-char (org-element-property :end element))
23336 (skip-chars-backward " \r\t\n")
23337 (line-beginning-position))
23338 end)))
23339 ;; Translate region boundaries for the Org buffer to the source
23340 ;; buffer.
23341 (let ((offset (- end beg)))
23342 (save-excursion
23343 (goto-char beg)
23344 (org-babel-do-in-edit-buffer
23345 (comment-or-uncomment-region (point) (+ offset (point))))))
23346 (save-restriction
23347 ;; Restrict region
23348 (narrow-to-region (save-excursion (goto-char beg)
23349 (skip-chars-forward " \r\t\n" end)
23350 (line-beginning-position))
23351 (save-excursion (goto-char end)
23352 (skip-chars-backward " \r\t\n" beg)
23353 (line-end-position)))
23354 (let ((uncommentp
23355 ;; UNCOMMENTP is non-nil when every non blank line between
23356 ;; BEG and END is a comment.
23357 (save-excursion
23358 (goto-char (point-min))
23359 (while (and (not (eobp))
23360 (let ((element (org-element-at-point)))
23361 (and (eq (org-element-type element) 'comment)
23362 (goto-char (min (point-max)
23363 (org-element-property
23364 :end element)))))))
23365 (eobp))))
23366 (if uncommentp
23367 ;; Only blank lines and comments in region: uncomment it.
23368 (save-excursion
23369 (goto-char (point-min))
23370 (while (not (eobp))
23371 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23372 (replace-match "" nil nil nil 1))
23373 (forward-line)))
23374 ;; Comment each line in region.
23375 (let ((min-indent (point-max)))
23376 ;; First find the minimum indentation across all lines.
23377 (save-excursion
23378 (goto-char (point-min))
23379 (while (and (not (eobp)) (not (zerop min-indent)))
23380 (unless (looking-at "[ \t]*$")
23381 (setq min-indent (min min-indent (current-indentation))))
23382 (forward-line)))
23383 ;; Then loop over all lines.
23384 (save-excursion
23385 (goto-char (point-min))
23386 (while (not (eobp))
23387 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23388 ;; Don't get fooled by invisible text (e.g. link path)
23389 ;; when moving to column MIN-INDENT.
23390 (let ((buffer-invisibility-spec nil))
23391 (org-move-to-column min-indent t))
23392 (insert comment-start))
23393 (forward-line)))))))))
23395 (defun org-comment-dwim (_arg)
23396 "Call `comment-dwim' within a source edit buffer if needed."
23397 (interactive "*P")
23398 (if (org-in-src-block-p)
23399 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23400 (call-interactively 'comment-dwim)))
23403 ;;; Timestamps API
23405 ;; This section contains tools to operate on timestamp objects, as
23406 ;; returned by, e.g. `org-element-context'.
23408 (defun org-timestamp--to-internal-time (timestamp &optional end)
23409 "Encode TIMESTAMP object into Emacs internal time.
23410 Use end of date range or time range when END is non-nil."
23411 (apply #'encode-time
23412 (cons 0
23413 (mapcar
23414 (lambda (prop) (or (org-element-property prop timestamp) 0))
23415 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23416 '(:minute-start :hour-start :day-start :month-start
23417 :year-start))))))
23419 (defun org-timestamp-has-time-p (timestamp)
23420 "Non-nil when TIMESTAMP has a time specified."
23421 (org-element-property :hour-start timestamp))
23423 (defun org-timestamp-format (timestamp format &optional end utc)
23424 "Format a TIMESTAMP object into a string.
23426 FORMAT is a format specifier to be passed to
23427 `format-time-string'.
23429 When optional argument END is non-nil, use end of date-range or
23430 time-range, if possible.
23432 When optional argument UTC is non-nil, time will be expressed as
23433 Universal Time."
23434 (format-time-string
23435 format (org-timestamp--to-internal-time timestamp end)
23436 (and utc t)))
23438 (defun org-timestamp-split-range (timestamp &optional end)
23439 "Extract a TIMESTAMP object from a date or time range.
23441 END, when non-nil, means extract the end of the range.
23442 Otherwise, extract its start.
23444 Return a new timestamp object."
23445 (let ((type (org-element-property :type timestamp)))
23446 (if (memq type '(active inactive diary)) timestamp
23447 (let ((split-ts (org-element-copy timestamp)))
23448 ;; Set new type.
23449 (org-element-put-property
23450 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23451 ;; Copy start properties over end properties if END is
23452 ;; non-nil. Otherwise, copy end properties over `start' ones.
23453 (let ((p-alist '((:minute-start . :minute-end)
23454 (:hour-start . :hour-end)
23455 (:day-start . :day-end)
23456 (:month-start . :month-end)
23457 (:year-start . :year-end))))
23458 (dolist (p-cell p-alist)
23459 (org-element-put-property
23460 split-ts
23461 (funcall (if end #'car #'cdr) p-cell)
23462 (org-element-property
23463 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23464 ;; Eventually refresh `:raw-value'.
23465 (org-element-put-property split-ts :raw-value nil)
23466 (org-element-put-property
23467 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23469 (defun org-timestamp-translate (timestamp &optional boundary)
23470 "Translate TIMESTAMP object to custom format.
23472 Format string is defined in `org-time-stamp-custom-formats',
23473 which see.
23475 When optional argument BOUNDARY is non-nil, it is either the
23476 symbol `start' or `end'. In this case, only translate the
23477 starting or ending part of TIMESTAMP if it is a date or time
23478 range. Otherwise, translate both parts.
23480 Return timestamp as-is if `org-display-custom-times' is nil or if
23481 it has a `diary' type."
23482 (let ((type (org-element-property :type timestamp)))
23483 (if (or (not org-display-custom-times) (eq type 'diary))
23484 (org-element-interpret-data timestamp)
23485 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23486 org-time-stamp-custom-formats)))
23487 (if (and (not boundary) (memq type '(active-range inactive-range)))
23488 (concat (org-timestamp-format timestamp fmt)
23489 "--"
23490 (org-timestamp-format timestamp fmt t))
23491 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23495 ;;; Other stuff.
23497 (defvar reftex-docstruct-symbol)
23498 (defvar org--rds)
23500 (defun org-reftex-citation ()
23501 "Use reftex-citation to insert a citation into the buffer.
23502 This looks for a line like
23504 #+BIBLIOGRAPHY: foo plain option:-d
23506 and derives from it that foo.bib is the bibliography file relevant
23507 for this document. It then installs the necessary environment for RefTeX
23508 to work in this buffer and calls `reftex-citation' to insert a citation
23509 into the buffer.
23511 Export of such citations to both LaTeX and HTML is handled by the contributed
23512 package ox-bibtex by Taru Karttunen."
23513 (interactive)
23514 (let ((reftex-docstruct-symbol 'org--rds)
23515 org--rds bib)
23516 (org-with-wide-buffer
23517 (let ((case-fold-search t)
23518 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23519 (if (not (save-excursion
23520 (or (re-search-forward re nil t)
23521 (re-search-backward re nil t))))
23522 (user-error "No bibliography defined in file")
23523 (setq bib (concat (match-string 1) ".bib")
23524 org--rds (list (list 'bib bib))))))
23525 (call-interactively 'reftex-citation)))
23527 ;;;; Functions extending outline functionality
23529 (defun org-beginning-of-line (&optional n)
23530 "Go to the beginning of the current visible line.
23532 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23533 tags on the first attempt, and only move to after the tags when
23534 the cursor is already beyond the end of the headline.
23536 With argument N not nil or 1, move forward N - 1 lines first."
23537 (interactive "^p")
23538 (let ((origin (point))
23539 (special (pcase org-special-ctrl-a/e
23540 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23541 deactivate-mark)
23542 ;; First move to a visible line.
23543 (if (bound-and-true-p visual-line-mode)
23544 (beginning-of-visual-line n)
23545 (move-beginning-of-line n)
23546 ;; `move-beginning-of-line' may leave point after invisible
23547 ;; characters if line starts with such of these (e.g., with
23548 ;; a link at column 0). Really move to the beginning of the
23549 ;; current visible line.
23550 (beginning-of-line))
23551 (cond
23552 ;; No special behavior. Point is already at the beginning of
23553 ;; a line, logical or visual.
23554 ((not special))
23555 ;; `beginning-of-visual-line' left point before logical beginning
23556 ;; of line: point is at the beginning of a visual line. Bail
23557 ;; out.
23558 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23559 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23560 ;; At a headline, special position is before the title, but
23561 ;; after any TODO keyword or priority cookie.
23562 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23563 (line-end-position)))
23564 (bol (point)))
23565 (if (eq special 'reversed)
23566 (when (and (= origin bol) (eq last-command this-command))
23567 (goto-char refpos))
23568 (when (or (> origin refpos) (= origin bol))
23569 (goto-char refpos)))))
23570 ((and (looking-at org-list-full-item-re)
23571 (memq (org-element-type (save-match-data (org-element-at-point)))
23572 '(item plain-list)))
23573 ;; Set special position at first white space character after
23574 ;; bullet, and check-box, if any.
23575 (let ((after-bullet
23576 (let ((box (match-end 3)))
23577 (cond ((not box) (match-end 1))
23578 ((eq (char-after box) ?\s) (1+ box))
23579 (t box)))))
23580 (if (eq special 'reversed)
23581 (when (and (= (point) origin) (eq last-command this-command))
23582 (goto-char after-bullet))
23583 (when (or (> origin after-bullet) (= (point) origin))
23584 (goto-char after-bullet)))))
23585 ;; No special context. Point is already at beginning of line.
23586 (t nil))))
23588 (defun org-end-of-line (&optional n)
23589 "Go to the end of the line, but before ellipsis, if any.
23591 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23592 tags on the first attempt, and only move to after the tags when
23593 the cursor is already beyond the end of the headline.
23595 With argument N not nil or 1, move forward N - 1 lines first."
23596 (interactive "^p")
23597 (let ((origin (point))
23598 (special (pcase org-special-ctrl-a/e
23599 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23600 deactivate-mark)
23601 ;; First move to a visible line.
23602 (if (bound-and-true-p visual-line-mode)
23603 (beginning-of-visual-line n)
23604 (move-beginning-of-line n))
23605 (cond
23606 ;; At a headline, with tags.
23607 ((and special
23608 (save-excursion
23609 (beginning-of-line)
23610 (let ((case-fold-search nil))
23611 (looking-at org-complex-heading-regexp)))
23612 (match-end 5))
23613 (let ((tags (save-excursion
23614 (goto-char (match-beginning 5))
23615 (skip-chars-backward " \t")
23616 (point)))
23617 (visual-end (and (bound-and-true-p visual-line-mode)
23618 (save-excursion
23619 (end-of-visual-line)
23620 (point)))))
23621 ;; If `end-of-visual-line' brings us before end of line or
23622 ;; even tags, i.e., the headline spans over multiple visual
23623 ;; lines, move there.
23624 (cond ((and visual-end
23625 (< visual-end tags)
23626 (<= origin visual-end))
23627 (goto-char visual-end))
23628 ((eq special 'reversed)
23629 (if (and (= origin (line-end-position))
23630 (eq this-command last-command))
23631 (goto-char tags)
23632 (end-of-line)))
23634 (if (or (< origin tags) (= origin (line-end-position)))
23635 (goto-char tags)
23636 (end-of-line))))))
23637 ((bound-and-true-p visual-line-mode)
23638 (let ((bol (line-beginning-position)))
23639 (end-of-visual-line)
23640 ;; If `end-of-visual-line' gets us past the ellipsis at the
23641 ;; end of a line, backtrack and use `end-of-line' instead.
23642 (when (/= bol (line-beginning-position))
23643 (goto-char bol)
23644 (end-of-line))))
23645 (t (end-of-line)))))
23647 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23648 (define-key org-mode-map "\C-e" 'org-end-of-line)
23650 (defun org-backward-sentence (&optional _arg)
23651 "Go to beginning of sentence, or beginning of table field.
23652 This will call `backward-sentence' or `org-table-beginning-of-field',
23653 depending on context."
23654 (interactive)
23655 (let* ((element (org-element-at-point))
23656 (contents-begin (org-element-property :contents-begin element))
23657 (table (org-element-lineage element '(table) t)))
23658 (if (and table
23659 (> (point) contents-begin)
23660 (<= (point) (org-element-property :contents-end table)))
23661 (call-interactively #'org-table-beginning-of-field)
23662 (save-restriction
23663 (when (and contents-begin
23664 (< (point-min) contents-begin)
23665 (> (point) contents-begin))
23666 (narrow-to-region contents-begin
23667 (org-element-property :contents-end element)))
23668 (call-interactively #'backward-sentence)))))
23670 (defun org-forward-sentence (&optional _arg)
23671 "Go to end of sentence, or end of table field.
23672 This will call `forward-sentence' or `org-table-end-of-field',
23673 depending on context."
23674 (interactive)
23675 (let* ((element (org-element-at-point))
23676 (contents-end (org-element-property :contents-end element))
23677 (table (org-element-lineage element '(table) t)))
23678 (if (and table
23679 (>= (point) (org-element-property :contents-begin table))
23680 (< (point) contents-end))
23681 (call-interactively #'org-table-end-of-field)
23682 (save-restriction
23683 (when (and contents-end
23684 (> (point-max) contents-end)
23685 ;; Skip blank lines between elements.
23686 (< (org-element-property :end element)
23687 (save-excursion (goto-char contents-end)
23688 (skip-chars-forward " \r\t\n"))))
23689 (narrow-to-region (org-element-property :contents-begin element)
23690 contents-end))
23691 (call-interactively #'forward-sentence)))))
23693 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23694 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23696 (defun org-kill-line (&optional _arg)
23697 "Kill line, to tags or end of line."
23698 (interactive)
23699 (cond
23700 ((or (not org-special-ctrl-k)
23701 (bolp)
23702 (not (org-at-heading-p)))
23703 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23704 org-ctrl-k-protect-subtree
23705 (or (eq org-ctrl-k-protect-subtree 'error)
23706 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23707 (user-error "C-k aborted as it would kill a hidden subtree"))
23708 (call-interactively
23709 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23710 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23711 (kill-region (point) (match-beginning 1))
23712 (org-set-tags nil t))
23713 (t (kill-region (point) (point-at-eol)))))
23715 (define-key org-mode-map "\C-k" 'org-kill-line)
23717 (defun org-yank (&optional arg)
23718 "Yank. If the kill is a subtree, treat it specially.
23719 This command will look at the current kill and check if is a single
23720 subtree, or a series of subtrees[1]. If it passes the test, and if the
23721 cursor is at the beginning of a line or after the stars of a currently
23722 empty headline, then the yank is handled specially. How exactly depends
23723 on the value of the following variables.
23725 `org-yank-folded-subtrees'
23726 By default, this variable is non-nil, which results in
23727 subtree(s) being folded after insertion, except if doing so
23728 would swallow text after the yanked text.
23730 `org-yank-adjusted-subtrees'
23731 When non-nil (the default value is nil), the subtree will be
23732 promoted or demoted in order to fit into the local outline tree
23733 structure, which means that the level will be adjusted so that it
23734 becomes the smaller one of the two *visible* surrounding headings.
23736 Any prefix to this command will cause `yank' to be called directly with
23737 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23738 will just
23739 plainly yank the text as it is.
23741 \[1] The test checks if the first non-white line is a heading
23742 and if there are no other headings with fewer stars."
23743 (interactive "P")
23744 (org-yank-generic 'yank arg))
23746 (defun org-yank-generic (command arg)
23747 "Perform some yank-like command.
23749 This function implements the behavior described in the `org-yank'
23750 documentation. However, it has been generalized to work for any
23751 interactive command with similar behavior."
23753 ;; pretend to be command COMMAND
23754 (setq this-command command)
23756 (if arg
23757 (call-interactively command)
23759 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23760 (and (org-kill-is-subtree-p)
23761 (or (bolp)
23762 (and (looking-at "[ \t]*$")
23763 (string-match
23764 "\\`\\*+\\'"
23765 (buffer-substring (point-at-bol) (point)))))))
23766 swallowp)
23767 (cond
23768 ((and subtreep org-yank-folded-subtrees)
23769 (let ((beg (point))
23770 end)
23771 (if (and subtreep org-yank-adjusted-subtrees)
23772 (org-paste-subtree nil nil 'for-yank)
23773 (call-interactively command))
23775 (setq end (point))
23776 (goto-char beg)
23777 (when (and (bolp) subtreep
23778 (not (setq swallowp
23779 (org-yank-folding-would-swallow-text beg end))))
23780 (org-with-limited-levels
23781 (or (looking-at org-outline-regexp)
23782 (re-search-forward org-outline-regexp-bol end t))
23783 (while (and (< (point) end) (looking-at org-outline-regexp))
23784 (outline-hide-subtree)
23785 (org-cycle-show-empty-lines 'folded)
23786 (condition-case nil
23787 (outline-forward-same-level 1)
23788 (error (goto-char end))))))
23789 (when swallowp
23790 (message
23791 "Inserted text not folded because that would swallow text"))
23793 (goto-char end)
23794 (skip-chars-forward " \t\n\r")
23795 (beginning-of-line 1)
23796 (push-mark beg 'nomsg)))
23797 ((and subtreep org-yank-adjusted-subtrees)
23798 (let ((beg (point-at-bol)))
23799 (org-paste-subtree nil nil 'for-yank)
23800 (push-mark beg 'nomsg)))
23802 (call-interactively command))))))
23804 (defun org-yank-folding-would-swallow-text (beg end)
23805 "Would hide-subtree at BEG swallow any text after END?"
23806 (let (level)
23807 (org-with-limited-levels
23808 (save-excursion
23809 (goto-char beg)
23810 (when (or (looking-at org-outline-regexp)
23811 (re-search-forward org-outline-regexp-bol end t))
23812 (setq level (org-outline-level)))
23813 (goto-char end)
23814 (skip-chars-forward " \t\r\n\v\f")
23815 (not (or (eobp)
23816 (and (bolp) (looking-at-p org-outline-regexp)
23817 (<= (org-outline-level) level))))))))
23819 (define-key org-mode-map "\C-y" 'org-yank)
23821 (defun org-truely-invisible-p ()
23822 "Check if point is at a character currently not visible.
23823 This version does not only check the character property, but also
23824 `visible-mode'."
23825 (unless (bound-and-true-p visible-mode)
23826 (org-invisible-p)))
23828 (defun org-invisible-p2 ()
23829 "Check if point is at a character currently not visible.
23831 If the point is at EOL (and not at the beginning of a buffer too),
23832 move it back by one char before doing this check."
23833 (save-excursion
23834 (when (and (eolp) (not (bobp)))
23835 (backward-char 1))
23836 (org-invisible-p)))
23838 (defun org-back-to-heading (&optional invisible-ok)
23839 "Call `outline-back-to-heading', but provide a better error message."
23840 (condition-case nil
23841 (outline-back-to-heading invisible-ok)
23842 (error (error "Before first headline at position %d in buffer %s"
23843 (point) (current-buffer)))))
23845 (defun org-before-first-heading-p ()
23846 "Before first heading?"
23847 (save-excursion
23848 (end-of-line)
23849 (null (re-search-backward org-outline-regexp-bol nil t))))
23851 (defun org-at-heading-p (&optional ignored)
23852 (outline-on-heading-p t))
23854 (defun org-in-commented-heading-p (&optional no-inheritance)
23855 "Non-nil if point is under a commented heading.
23856 This function also checks ancestors of the current headline,
23857 unless optional argument NO-INHERITANCE is non-nil."
23858 (cond
23859 ((org-before-first-heading-p) nil)
23860 ((let ((headline (nth 4 (org-heading-components))))
23861 (and headline
23862 (let ((case-fold-search nil))
23863 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23864 headline)))))
23865 (no-inheritance nil)
23867 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23869 (defun org-at-comment-p nil
23870 "Is cursor in a commented line?"
23871 (save-excursion
23872 (save-match-data
23873 (beginning-of-line)
23874 (looking-at "^[ \t]*# "))))
23876 (defun org-at-drawer-p nil
23877 "Is cursor at a drawer keyword?"
23878 (save-excursion
23879 (move-beginning-of-line 1)
23880 (looking-at org-drawer-regexp)))
23882 (defun org-at-block-p nil
23883 "Is cursor at a block keyword?"
23884 (save-excursion
23885 (move-beginning-of-line 1)
23886 (looking-at org-block-regexp)))
23888 (defun org-point-at-end-of-empty-headline ()
23889 "If point is at the end of an empty headline, return t, else nil.
23890 If the heading only contains a TODO keyword, it is still still considered
23891 empty."
23892 (let ((case-fold-search nil))
23893 (and (looking-at "[ \t]*$")
23894 org-todo-line-regexp
23895 (save-excursion
23896 (beginning-of-line)
23897 (looking-at org-todo-line-regexp)
23898 (string= (match-string 3) "")))))
23900 (defun org-at-heading-or-item-p ()
23901 (or (org-at-heading-p) (org-at-item-p)))
23903 (defun org-at-target-p ()
23904 (or (org-in-regexp org-radio-target-regexp)
23905 (org-in-regexp org-target-regexp)))
23906 ;; Compatibility alias with Org versions < 7.8.03
23907 (defalias 'org-on-target-p 'org-at-target-p)
23909 (defun org-up-heading-all (arg)
23910 "Move to the heading line of which the present line is a subheading.
23911 This function considers both visible and invisible heading lines.
23912 With argument, move up ARG levels."
23913 (outline-up-heading arg t))
23915 (defun org-up-heading-safe ()
23916 "Move to the heading line of which the present line is a subheading.
23917 This version will not throw an error. It will return the level of the
23918 headline found, or nil if no higher level is found.
23920 Also, this function will be a lot faster than `outline-up-heading',
23921 because it relies on stars being the outline starters. This can really
23922 make a significant difference in outlines with very many siblings."
23923 (when (ignore-errors (org-back-to-heading t))
23924 (let ((level-up (1- (funcall outline-level))))
23925 (and (> level-up 0)
23926 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23927 (funcall outline-level)))))
23929 (defun org-first-sibling-p ()
23930 "Is this heading the first child of its parents?"
23931 (interactive)
23932 (let ((re org-outline-regexp-bol)
23933 level l)
23934 (unless (org-at-heading-p t)
23935 (user-error "Not at a heading"))
23936 (setq level (funcall outline-level))
23937 (save-excursion
23938 (if (not (re-search-backward re nil t))
23940 (setq l (funcall outline-level))
23941 (< l level)))))
23943 (defun org-goto-sibling (&optional previous)
23944 "Goto the next sibling, even if it is invisible.
23945 When PREVIOUS is set, go to the previous sibling instead. Returns t
23946 when a sibling was found. When none is found, return nil and don't
23947 move point."
23948 (let ((fun (if previous 're-search-backward 're-search-forward))
23949 (pos (point))
23950 (re org-outline-regexp-bol)
23951 level l)
23952 (when (ignore-errors (org-back-to-heading t))
23953 (setq level (funcall outline-level))
23954 (catch 'exit
23955 (or previous (forward-char 1))
23956 (while (funcall fun re nil t)
23957 (setq l (funcall outline-level))
23958 (when (< l level) (goto-char pos) (throw 'exit nil))
23959 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23960 (goto-char pos)
23961 nil))))
23963 (defun org-show-siblings ()
23964 "Show all siblings of the current headline."
23965 (save-excursion
23966 (while (org-goto-sibling) (org-flag-heading nil)))
23967 (save-excursion
23968 (while (org-goto-sibling 'previous)
23969 (org-flag-heading nil))))
23971 (defun org-goto-first-child ()
23972 "Goto the first child, even if it is invisible.
23973 Return t when a child was found. Otherwise don't move point and
23974 return nil."
23975 (let (level (pos (point)) (re org-outline-regexp-bol))
23976 (when (ignore-errors (org-back-to-heading t))
23977 (setq level (outline-level))
23978 (forward-char 1)
23979 (if (and (re-search-forward re nil t) (> (outline-level) level))
23980 (progn (goto-char (match-beginning 0)) t)
23981 (goto-char pos) nil))))
23983 (defun org-show-hidden-entry ()
23984 "Show an entry where even the heading is hidden."
23985 (save-excursion
23986 (org-show-entry)))
23988 (defun org-flag-heading (flag &optional entry)
23989 "Flag the current heading. FLAG non-nil means make invisible.
23990 When ENTRY is non-nil, show the entire entry."
23991 (save-excursion
23992 (org-back-to-heading t)
23993 ;; Check if we should show the entire entry
23994 (if entry
23995 (progn
23996 (org-show-entry)
23997 (save-excursion
23998 (and (outline-next-heading)
23999 (org-flag-heading nil))))
24000 (outline-flag-region (max (point-min) (1- (point)))
24001 (save-excursion (outline-end-of-heading) (point))
24002 flag))))
24004 (defun org-get-next-sibling ()
24005 "Move to next heading of the same level, and return point.
24006 If there is no such heading, return nil.
24007 This is like outline-next-sibling, but invisible headings are ok."
24008 (let ((level (funcall outline-level)))
24009 (outline-next-heading)
24010 (while (and (not (eobp)) (> (funcall outline-level) level))
24011 (outline-next-heading))
24012 (unless (or (eobp) (< (funcall outline-level) level))
24013 (point))))
24015 (defun org-get-last-sibling ()
24016 "Move to previous heading of the same level, and return point.
24017 If there is no such heading, return nil."
24018 (let ((opoint (point))
24019 (level (funcall outline-level)))
24020 (outline-previous-heading)
24021 (when (and (/= (point) opoint) (outline-on-heading-p t))
24022 (while (and (> (funcall outline-level) level)
24023 (not (bobp)))
24024 (outline-previous-heading))
24025 (unless (< (funcall outline-level) level)
24026 (point)))))
24028 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24029 "Goto to the end of a subtree."
24030 ;; This contains an exact copy of the original function, but it uses
24031 ;; `org-back-to-heading', to make it work also in invisible
24032 ;; trees. And is uses an invisible-ok argument.
24033 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24034 ;; Furthermore, when used inside Org, finding the end of a large subtree
24035 ;; with many children and grandchildren etc, this can be much faster
24036 ;; than the outline version.
24037 (org-back-to-heading invisible-ok)
24038 (let ((first t)
24039 (level (funcall outline-level)))
24040 (if (and (derived-mode-p 'org-mode) (< level 1000))
24041 ;; A true heading (not a plain list item), in Org
24042 ;; This means we can easily find the end by looking
24043 ;; only for the right number of stars. Using a regexp to do
24044 ;; this is so much faster than using a Lisp loop.
24045 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24046 (forward-char 1)
24047 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24048 ;; something else, do it the slow way
24049 (while (and (not (eobp))
24050 (or first (> (funcall outline-level) level)))
24051 (setq first nil)
24052 (outline-next-heading)))
24053 (unless to-heading
24054 (when (memq (preceding-char) '(?\n ?\^M))
24055 ;; Go to end of line before heading
24056 (forward-char -1)
24057 (when (memq (preceding-char) '(?\n ?\^M))
24058 ;; leave blank line before heading
24059 (forward-char -1)))))
24060 (point))
24062 (defun org-end-of-meta-data (&optional full)
24063 "Skip planning line and properties drawer in current entry.
24064 When optional argument FULL is non-nil, also skip empty lines,
24065 clocking lines and regular drawers at the beginning of the
24066 entry."
24067 (org-back-to-heading t)
24068 (forward-line)
24069 (when (looking-at-p org-planning-line-re) (forward-line))
24070 (when (looking-at org-property-drawer-re)
24071 (goto-char (match-end 0))
24072 (forward-line))
24073 (when (and full (not (org-at-heading-p)))
24074 (catch 'exit
24075 (let ((end (save-excursion (outline-next-heading) (point)))
24076 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24077 (while (not (eobp))
24078 (cond ((looking-at-p org-drawer-regexp)
24079 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24080 (forward-line)
24081 (throw 'exit t)))
24082 ((looking-at-p re) (forward-line))
24083 (t (throw 'exit t))))))))
24085 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24086 "Move forward to the ARG'th subheading at same level as this one.
24087 Stop at the first and last subheadings of a superior heading.
24088 Normally this only looks at visible headings, but when INVISIBLE-OK is
24089 non-nil it will also look at invisible ones."
24090 (interactive "p")
24091 (let ((backward? (and arg (< arg 0))))
24092 (if (org-before-first-heading-p)
24093 (if backward? (goto-char (point-min)) (outline-next-heading))
24094 (org-back-to-heading invisible-ok)
24095 (unless backward? (end-of-line)) ;do not match current headline
24096 (let ((level (- (match-end 0) (match-beginning 0) 1))
24097 (f (if backward? #'re-search-backward #'re-search-forward))
24098 (count (if arg (abs arg) 1))
24099 (result (point)))
24100 (while (and (> count 0)
24101 (funcall f org-outline-regexp-bol nil 'move))
24102 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24103 (cond ((< l level) (setq count 0))
24104 ((and (= l level)
24105 (or invisible-ok
24106 (not (org-invisible-p
24107 (line-beginning-position)))))
24108 (cl-decf count)
24109 (when (= l level) (setq result (point)))))))
24110 (goto-char result))
24111 (beginning-of-line))))
24113 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24114 "Move backward to the ARG'th subheading at same level as this one.
24115 Stop at the first and last subheadings of a superior heading."
24116 (interactive "p")
24117 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24119 (defun org-next-visible-heading (arg)
24120 "Move to the next visible heading.
24122 This function wraps `outline-next-visible-heading' with
24123 `org-with-limited-levels' in order to skip over inline tasks and
24124 respect customization of `org-odd-levels-only'."
24125 (interactive "p")
24126 (org-with-limited-levels
24127 (outline-next-visible-heading arg)))
24129 (defun org-previous-visible-heading (arg)
24130 "Move to the previous visible heading.
24132 This function wraps `outline-previous-visible-heading' with
24133 `org-with-limited-levels' in order to skip over inline tasks and
24134 respect customization of `org-odd-levels-only'."
24135 (interactive "p")
24136 (org-with-limited-levels
24137 (outline-previous-visible-heading arg)))
24139 (defun org-next-block (arg &optional backward block-regexp)
24140 "Jump to the next block.
24142 With a prefix argument ARG, jump forward ARG many blocks.
24144 When BACKWARD is non-nil, jump to the previous block.
24146 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24147 Match data is set according to this regexp when the function
24148 returns.
24150 Return point at beginning of the opening line of found block.
24151 Throw an error if no block is found."
24152 (interactive "p")
24153 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24154 (case-fold-search t)
24155 (search-fn (if backward #'re-search-backward #'re-search-forward))
24156 (count (or arg 1))
24157 (origin (point))
24158 last-element)
24159 (if backward (beginning-of-line) (end-of-line))
24160 (while (and (> count 0) (funcall search-fn re nil t))
24161 (let ((element (save-excursion
24162 (goto-char (match-beginning 0))
24163 (save-match-data (org-element-at-point)))))
24164 (when (and (memq (org-element-type element)
24165 '(center-block comment-block dynamic-block
24166 example-block export-block quote-block
24167 special-block src-block verse-block))
24168 (<= (match-beginning 0)
24169 (org-element-property :post-affiliated element)))
24170 (setq last-element element)
24171 (cl-decf count))))
24172 (if (= count 0)
24173 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24174 (save-match-data (org-show-context)))
24175 (goto-char origin)
24176 (user-error "No %s code blocks" (if backward "previous" "further")))))
24178 (defun org-previous-block (arg &optional block-regexp)
24179 "Jump to the previous block.
24180 With a prefix argument ARG, jump backward ARG many source blocks.
24181 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24182 (interactive "p")
24183 (org-next-block arg t block-regexp))
24185 (defun org-forward-paragraph ()
24186 "Move forward to beginning of next paragraph or equivalent.
24188 The function moves point to the beginning of the next visible
24189 structural element, which can be a paragraph, a table, a list
24190 item, etc. It also provides some special moves for convenience:
24192 - On an affiliated keyword, jump to the beginning of the
24193 relative element.
24194 - On an item or a footnote definition, move to the second
24195 element inside, if any.
24196 - On a table or a property drawer, jump after it.
24197 - On a verse or source block, stop after blank lines."
24198 (interactive)
24199 (unless (eobp)
24200 (let* ((deactivate-mark nil)
24201 (element (org-element-at-point))
24202 (type (org-element-type element))
24203 (post-affiliated (org-element-property :post-affiliated element))
24204 (contents-begin (org-element-property :contents-begin element))
24205 (contents-end (org-element-property :contents-end element))
24206 (end (let ((end (org-element-property :end element)) (parent element))
24207 (while (and (setq parent (org-element-property :parent parent))
24208 (= (org-element-property :contents-end parent) end))
24209 (setq end (org-element-property :end parent)))
24210 end)))
24211 (cond ((not element)
24212 (skip-chars-forward " \r\t\n")
24213 (or (eobp) (beginning-of-line)))
24214 ;; On affiliated keywords, move to element's beginning.
24215 ((< (point) post-affiliated)
24216 (goto-char post-affiliated))
24217 ;; At a table row, move to the end of the table. Similarly,
24218 ;; at a node property, move to the end of the property
24219 ;; drawer.
24220 ((memq type '(node-property table-row))
24221 (goto-char (org-element-property
24222 :end (org-element-property :parent element))))
24223 ((memq type '(property-drawer table)) (goto-char end))
24224 ;; Consider blank lines as separators in verse and source
24225 ;; blocks to ease editing.
24226 ((memq type '(src-block verse-block))
24227 (when (eq type 'src-block)
24228 (setq contents-end
24229 (save-excursion (goto-char end)
24230 (skip-chars-backward " \r\t\n")
24231 (line-beginning-position))))
24232 (beginning-of-line)
24233 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24234 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24235 (goto-char end)
24236 (skip-chars-forward " \r\t\n")
24237 (if (= (point) contents-end) (goto-char end)
24238 (beginning-of-line))))
24239 ;; With no contents, just skip element.
24240 ((not contents-begin) (goto-char end))
24241 ;; If contents are invisible, skip the element altogether.
24242 ((org-invisible-p (line-end-position))
24243 (cl-case type
24244 (headline
24245 (org-with-limited-levels (outline-next-visible-heading 1)))
24246 ;; At a plain list, make sure we move to the next item
24247 ;; instead of skipping the whole list.
24248 (plain-list (forward-char)
24249 (org-forward-paragraph))
24250 (otherwise (goto-char end))))
24251 ((>= (point) contents-end) (goto-char end))
24252 ((>= (point) contents-begin)
24253 ;; This can only happen on paragraphs and plain lists.
24254 (cl-case type
24255 (paragraph (goto-char end))
24256 ;; At a plain list, try to move to second element in
24257 ;; first item, if possible.
24258 (plain-list (end-of-line)
24259 (org-forward-paragraph))))
24260 ;; When contents start on the middle of a line (e.g. in
24261 ;; items and footnote definitions), try to reach first
24262 ;; element starting after current line.
24263 ((> (line-end-position) contents-begin)
24264 (end-of-line)
24265 (org-forward-paragraph))
24266 (t (goto-char contents-begin))))))
24268 (defun org-backward-paragraph ()
24269 "Move backward to start of previous paragraph or equivalent.
24271 The function moves point to the beginning of the current
24272 structural element, which can be a paragraph, a table, a list
24273 item, etc., or to the beginning of the previous visible one if
24274 point is already there. It also provides some special moves for
24275 convenience:
24277 - On an affiliated keyword, jump to the first one.
24278 - On a table or a property drawer, move to its beginning.
24279 - On a verse or source block, stop before blank lines."
24280 (interactive)
24281 (unless (bobp)
24282 (let* ((deactivate-mark nil)
24283 (element (org-element-at-point))
24284 (type (org-element-type element))
24285 (contents-begin (org-element-property :contents-begin element))
24286 (contents-end (org-element-property :contents-end element))
24287 (post-affiliated (org-element-property :post-affiliated element))
24288 (begin (org-element-property :begin element)))
24289 (cond
24290 ((not element) (goto-char (point-min)))
24291 ((= (point) begin)
24292 (backward-char)
24293 (org-backward-paragraph))
24294 ((<= (point) post-affiliated) (goto-char begin))
24295 ((memq type '(node-property table-row))
24296 (goto-char (org-element-property
24297 :post-affiliated (org-element-property :parent element))))
24298 ((memq type '(property-drawer table)) (goto-char begin))
24299 ((memq type '(src-block verse-block))
24300 (when (eq type 'src-block)
24301 (setq contents-begin
24302 (save-excursion (goto-char begin) (forward-line) (point))))
24303 (if (= (point) contents-begin) (goto-char post-affiliated)
24304 ;; Inside a verse block, see blank lines as paragraph
24305 ;; separators.
24306 (let ((origin (point)))
24307 (skip-chars-backward " \r\t\n" contents-begin)
24308 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24309 (skip-chars-forward " \r\t\n" origin)
24310 (if (= (point) origin) (goto-char contents-begin)
24311 (beginning-of-line))))))
24312 ((not contents-begin) (goto-char (or post-affiliated begin)))
24313 ((eq type 'paragraph)
24314 (goto-char contents-begin)
24315 ;; When at first paragraph in an item or a footnote definition,
24316 ;; move directly to beginning of line.
24317 (let ((parent-contents
24318 (org-element-property
24319 :contents-begin (org-element-property :parent element))))
24320 (when (and parent-contents (= parent-contents contents-begin))
24321 (beginning-of-line))))
24322 ;; At the end of a greater element, move to the beginning of the
24323 ;; last element within.
24324 ((>= (point) contents-end)
24325 (goto-char (1- contents-end))
24326 (org-backward-paragraph))
24327 (t (goto-char (or post-affiliated begin))))
24328 ;; Ensure we never leave point invisible.
24329 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24331 (defun org-forward-element ()
24332 "Move forward by one element.
24333 Move to the next element at the same level, when possible."
24334 (interactive)
24335 (cond ((eobp) (user-error "Cannot move further down"))
24336 ((org-with-limited-levels (org-at-heading-p))
24337 (let ((origin (point)))
24338 (goto-char (org-end-of-subtree nil t))
24339 (unless (org-with-limited-levels (org-at-heading-p))
24340 (goto-char origin)
24341 (user-error "Cannot move further down"))))
24343 (let* ((elem (org-element-at-point))
24344 (end (org-element-property :end elem))
24345 (parent (org-element-property :parent elem)))
24346 (cond ((and parent (= (org-element-property :contents-end parent) end))
24347 (goto-char (org-element-property :end parent)))
24348 ((integer-or-marker-p end) (goto-char end))
24349 (t (message "No element at point")))))))
24351 (defun org-backward-element ()
24352 "Move backward by one element.
24353 Move to the previous element at the same level, when possible."
24354 (interactive)
24355 (cond ((bobp) (user-error "Cannot move further up"))
24356 ((org-with-limited-levels (org-at-heading-p))
24357 ;; At a headline, move to the previous one, if any, or stay
24358 ;; here.
24359 (let ((origin (point)))
24360 (org-with-limited-levels (org-backward-heading-same-level 1))
24361 ;; When current headline has no sibling above, move to its
24362 ;; parent.
24363 (when (= (point) origin)
24364 (or (org-with-limited-levels (org-up-heading-safe))
24365 (progn (goto-char origin)
24366 (user-error "Cannot move further up"))))))
24368 (let* ((elem (org-element-at-point))
24369 (beg (org-element-property :begin elem)))
24370 (cond
24371 ;; Move to beginning of current element if point isn't
24372 ;; there already.
24373 ((null beg) (message "No element at point"))
24374 ((/= (point) beg) (goto-char beg))
24375 (t (goto-char beg)
24376 (skip-chars-backward " \r\t\n")
24377 (unless (bobp)
24378 (let ((prev (org-element-at-point)))
24379 (goto-char (org-element-property :begin prev))
24380 (while (and (setq prev (org-element-property :parent prev))
24381 (<= (org-element-property :end prev) beg))
24382 (goto-char (org-element-property :begin prev)))))))))))
24384 (defun org-up-element ()
24385 "Move to upper element."
24386 (interactive)
24387 (if (org-with-limited-levels (org-at-heading-p))
24388 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24389 (let* ((elem (org-element-at-point))
24390 (parent (org-element-property :parent elem)))
24391 (if parent (goto-char (org-element-property :begin parent))
24392 (if (org-with-limited-levels (org-before-first-heading-p))
24393 (user-error "No surrounding element")
24394 (org-with-limited-levels (org-back-to-heading)))))))
24396 (defun org-down-element ()
24397 "Move to inner element."
24398 (interactive)
24399 (let ((element (org-element-at-point)))
24400 (cond
24401 ((memq (org-element-type element) '(plain-list table))
24402 (goto-char (org-element-property :contents-begin element))
24403 (forward-char))
24404 ((memq (org-element-type element) org-element-greater-elements)
24405 ;; If contents are hidden, first disclose them.
24406 (when (org-invisible-p (line-end-position)) (org-cycle))
24407 (goto-char (or (org-element-property :contents-begin element)
24408 (user-error "No content for this element"))))
24409 (t (user-error "No inner element")))))
24411 (defun org-drag-element-backward ()
24412 "Move backward element at point."
24413 (interactive)
24414 (let ((elem (or (org-element-at-point)
24415 (user-error "No element at point"))))
24416 (if (eq (org-element-type elem) 'headline)
24417 ;; Preserve point when moving a whole tree, even if point was
24418 ;; on blank lines below the headline.
24419 (let ((offset (skip-chars-backward " \t\n")))
24420 (unwind-protect (org-move-subtree-up)
24421 (forward-char (- offset))))
24422 (let ((prev-elem
24423 (save-excursion
24424 (goto-char (org-element-property :begin elem))
24425 (skip-chars-backward " \r\t\n")
24426 (unless (bobp)
24427 (let* ((beg (org-element-property :begin elem))
24428 (prev (org-element-at-point))
24429 (up prev))
24430 (while (and (setq up (org-element-property :parent up))
24431 (<= (org-element-property :end up) beg))
24432 (setq prev up))
24433 prev)))))
24434 ;; Error out if no previous element or previous element is
24435 ;; a parent of the current one.
24436 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24437 (user-error "Cannot drag element backward")
24438 (let ((pos (point)))
24439 (org-element-swap-A-B prev-elem elem)
24440 (goto-char (+ (org-element-property :begin prev-elem)
24441 (- pos (org-element-property :begin elem))))))))))
24443 (defun org-drag-element-forward ()
24444 "Move forward element at point."
24445 (interactive)
24446 (let* ((pos (point))
24447 (elem (or (org-element-at-point)
24448 (user-error "No element at point"))))
24449 (when (= (point-max) (org-element-property :end elem))
24450 (user-error "Cannot drag element forward"))
24451 (goto-char (org-element-property :end elem))
24452 (let ((next-elem (org-element-at-point)))
24453 (when (or (org-element-nested-p elem next-elem)
24454 (and (eq (org-element-type next-elem) 'headline)
24455 (not (eq (org-element-type elem) 'headline))))
24456 (goto-char pos)
24457 (user-error "Cannot drag element forward"))
24458 ;; Compute new position of point: it's shifted by NEXT-ELEM
24459 ;; body's length (without final blanks) and by the length of
24460 ;; blanks between ELEM and NEXT-ELEM.
24461 (let ((size-next (- (save-excursion
24462 (goto-char (org-element-property :end next-elem))
24463 (skip-chars-backward " \r\t\n")
24464 (forward-line)
24465 ;; Small correction if buffer doesn't end
24466 ;; with a newline character.
24467 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24468 (org-element-property :begin next-elem)))
24469 (size-blank (- (org-element-property :end elem)
24470 (save-excursion
24471 (goto-char (org-element-property :end elem))
24472 (skip-chars-backward " \r\t\n")
24473 (forward-line)
24474 (point)))))
24475 (org-element-swap-A-B elem next-elem)
24476 (goto-char (+ pos size-next size-blank))))))
24478 (defun org-drag-line-forward (arg)
24479 "Drag the line at point ARG lines forward."
24480 (interactive "p")
24481 (dotimes (_ (abs arg))
24482 (let ((c (current-column)))
24483 (if (< 0 arg)
24484 (progn
24485 (beginning-of-line 2)
24486 (transpose-lines 1)
24487 (beginning-of-line 0))
24488 (transpose-lines 1)
24489 (beginning-of-line -1))
24490 (org-move-to-column c))))
24492 (defun org-drag-line-backward (arg)
24493 "Drag the line at point ARG lines backward."
24494 (interactive "p")
24495 (org-drag-line-forward (- arg)))
24497 (defun org-mark-element ()
24498 "Put point at beginning of this element, mark at end.
24500 Interactively, if this command is repeated or (in Transient Mark
24501 mode) if the mark is active, it marks the next element after the
24502 ones already marked."
24503 (interactive)
24504 (let (deactivate-mark)
24505 (if (and (called-interactively-p 'any)
24506 (or (and (eq last-command this-command) (mark t))
24507 (and transient-mark-mode mark-active)))
24508 (set-mark
24509 (save-excursion
24510 (goto-char (mark))
24511 (goto-char (org-element-property :end (org-element-at-point)))))
24512 (let ((element (org-element-at-point)))
24513 (end-of-line)
24514 (push-mark (org-element-property :end element) t t)
24515 (goto-char (org-element-property :begin element))))))
24517 (defun org-narrow-to-element ()
24518 "Narrow buffer to current element."
24519 (interactive)
24520 (let ((elem (org-element-at-point)))
24521 (cond
24522 ((eq (car elem) 'headline)
24523 (narrow-to-region
24524 (org-element-property :begin elem)
24525 (org-element-property :end elem)))
24526 ((memq (car elem) org-element-greater-elements)
24527 (narrow-to-region
24528 (org-element-property :contents-begin elem)
24529 (org-element-property :contents-end elem)))
24531 (narrow-to-region
24532 (org-element-property :begin elem)
24533 (org-element-property :end elem))))))
24535 (defun org-transpose-element ()
24536 "Transpose current and previous elements, keeping blank lines between.
24537 Point is moved after both elements."
24538 (interactive)
24539 (org-skip-whitespace)
24540 (let ((end (org-element-property :end (org-element-at-point))))
24541 (org-drag-element-backward)
24542 (goto-char end)))
24544 (defun org-unindent-buffer ()
24545 "Un-indent the visible part of the buffer.
24546 Relative indentation (between items, inside blocks, etc.) isn't
24547 modified."
24548 (interactive)
24549 (unless (eq major-mode 'org-mode)
24550 (user-error "Cannot un-indent a buffer not in Org mode"))
24551 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24552 (unindent-tree
24553 (lambda (contents)
24554 (dolist (element (reverse contents))
24555 (if (memq (org-element-type element) '(headline section))
24556 (funcall unindent-tree (org-element-contents element))
24557 (save-excursion
24558 (save-restriction
24559 (narrow-to-region
24560 (org-element-property :begin element)
24561 (org-element-property :end element))
24562 (org-do-remove-indentation))))))))
24563 (funcall unindent-tree (org-element-contents parse-tree))))
24565 (defun org-show-children (&optional level)
24566 "Show all direct subheadings of this heading.
24567 Prefix arg LEVEL is how many levels below the current level
24568 should be shown. Default is enough to cause the following
24569 heading to appear."
24570 (interactive "p")
24571 ;; If `orgstruct-mode' is active, use the slower version.
24572 (if orgstruct-mode (call-interactively #'outline-show-children)
24573 (save-excursion
24574 (org-back-to-heading t)
24575 (let* ((current-level (funcall outline-level))
24576 (max-level (org-get-valid-level
24577 current-level
24578 (if level (prefix-numeric-value level) 1)))
24579 (end (save-excursion (org-end-of-subtree t t)))
24580 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24581 (past-first-child nil)
24582 ;; Make sure to skip inlinetasks.
24583 (re (format regexp-fmt
24584 current-level
24585 (cond
24586 ((not (featurep 'org-inlinetask)) "")
24587 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24589 (t (1- org-inlinetask-min-level))))))
24590 ;; Display parent heading.
24591 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24592 (forward-line)
24593 ;; Display children. First child may be deeper than expected
24594 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24595 ;; MAX-LEVEL accordingly.
24596 (while (re-search-forward re end t)
24597 (unless past-first-child
24598 (setq re (format regexp-fmt
24599 current-level
24600 (max (funcall outline-level) max-level)))
24601 (setq past-first-child t))
24602 (outline-flag-region
24603 (line-end-position 0) (line-end-position) nil))))))
24605 (defun org-show-subtree ()
24606 "Show everything after this heading at deeper levels."
24607 (interactive)
24608 (outline-flag-region
24609 (point)
24610 (save-excursion
24611 (org-end-of-subtree t t))
24612 nil))
24614 (defun org-show-entry ()
24615 "Show the body directly following this heading.
24616 Show the heading too, if it is currently invisible."
24617 (interactive)
24618 (save-excursion
24619 (ignore-errors
24620 (org-back-to-heading t)
24621 (outline-flag-region
24622 (max (point-min) (1- (point)))
24623 (save-excursion
24624 (if (re-search-forward
24625 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24626 (match-beginning 1)
24627 (point-max)))
24628 nil)
24629 (org-cycle-hide-drawers 'children))))
24631 (defun org-make-options-regexp (kwds &optional extra)
24632 "Make a regular expression for keyword lines.
24633 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24634 when non-nil, is a regexp matching keywords names."
24635 (concat "^[ \t]*#\\+\\("
24636 (regexp-opt kwds)
24637 (and extra (concat (and kwds "\\|") extra))
24638 "\\):[ \t]*\\(.*\\)"))
24640 ;;;; Integration with and fixes for other packages
24642 ;;; Imenu support
24644 (defvar-local org-imenu-markers nil
24645 "All markers currently used by Imenu.")
24647 (defun org-imenu-new-marker (&optional pos)
24648 "Return a new marker for use by Imenu, and remember the marker."
24649 (let ((m (make-marker)))
24650 (move-marker m (or pos (point)))
24651 (push m org-imenu-markers)
24654 (defun org-imenu-get-tree ()
24655 "Produce the index for Imenu."
24656 (dolist (x org-imenu-markers) (move-marker x nil))
24657 (setq org-imenu-markers nil)
24658 (let* ((case-fold-search nil)
24659 (n org-imenu-depth)
24660 (re (concat "^" (org-get-limited-outline-regexp)))
24661 (subs (make-vector (1+ n) nil))
24662 (last-level 0)
24663 m level head0 head)
24664 (org-with-wide-buffer
24665 (goto-char (point-max))
24666 (while (re-search-backward re nil t)
24667 (setq level (org-reduced-level (funcall outline-level)))
24668 (when (and (<= level n)
24669 (looking-at org-complex-heading-regexp)
24670 (setq head0 (match-string-no-properties 4)))
24671 (setq head (org-link-display-format head0)
24672 m (org-imenu-new-marker))
24673 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24674 (if (>= level last-level)
24675 (push (cons head m) (aref subs level))
24676 (push (cons head (aref subs (1+ level))) (aref subs level))
24677 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24678 (setq last-level level))))
24679 (aref subs 1)))
24681 (eval-after-load "imenu"
24682 '(progn
24683 (add-hook 'imenu-after-jump-hook
24684 (lambda ()
24685 (when (derived-mode-p 'org-mode)
24686 (org-show-context 'org-goto))))))
24688 (defun org-link-display-format (s)
24689 "Replace links in string S with their description.
24690 If there is no description, use the link target."
24691 (save-match-data
24692 (replace-regexp-in-string
24693 org-bracket-link-analytic-regexp
24694 (lambda (m)
24695 (if (match-end 5) (match-string 5 m)
24696 (concat (match-string 1 m) (match-string 3 m))))
24697 s nil t)))
24699 (defun org-toggle-link-display ()
24700 "Toggle the literal or descriptive display of links."
24701 (interactive)
24702 (if org-descriptive-links
24703 (progn (org-remove-from-invisibility-spec '(org-link))
24704 (org-restart-font-lock)
24705 (setq org-descriptive-links nil))
24706 (progn (add-to-invisibility-spec '(org-link))
24707 (org-restart-font-lock)
24708 (setq org-descriptive-links t))))
24710 ;; Speedbar support
24712 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24713 "Overlay marking the agenda restriction line in speedbar.")
24714 (overlay-put org-speedbar-restriction-lock-overlay
24715 'face 'org-agenda-restriction-lock)
24716 (overlay-put org-speedbar-restriction-lock-overlay
24717 'help-echo "Agendas are currently limited to this item.")
24718 (delete-overlay org-speedbar-restriction-lock-overlay)
24720 (defun org-speedbar-set-agenda-restriction ()
24721 "Restrict future agenda commands to the location at point in speedbar.
24722 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24723 (interactive)
24724 (require 'org-agenda)
24725 (let (p m tp np dir txt)
24726 (cond
24727 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24728 'org-imenu t))
24729 (setq m (get-text-property p 'org-imenu-marker))
24730 (with-current-buffer (marker-buffer m)
24731 (goto-char m)
24732 (org-agenda-set-restriction-lock 'subtree)))
24733 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24734 'speedbar-function 'speedbar-find-file))
24735 (setq tp (previous-single-property-change
24736 (1+ p) 'speedbar-function)
24737 np (next-single-property-change
24738 tp 'speedbar-function)
24739 dir (speedbar-line-directory)
24740 txt (buffer-substring-no-properties (or tp (point-min))
24741 (or np (point-max))))
24742 (with-current-buffer (find-file-noselect
24743 (let ((default-directory dir))
24744 (expand-file-name txt)))
24745 (unless (derived-mode-p 'org-mode)
24746 (user-error "Cannot restrict to non-Org mode file"))
24747 (org-agenda-set-restriction-lock 'file)))
24748 (t (user-error "Don't know how to restrict Org mode agenda")))
24749 (move-overlay org-speedbar-restriction-lock-overlay
24750 (point-at-bol) (point-at-eol))
24751 (setq current-prefix-arg nil)
24752 (org-agenda-maybe-redo)))
24754 (defvar speedbar-file-key-map)
24755 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24756 (eval-after-load "speedbar"
24757 '(progn
24758 (speedbar-add-supported-extension ".org")
24759 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24760 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24761 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24762 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24763 (add-hook 'speedbar-visiting-tag-hook
24764 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24766 ;;; Fixes and Hacks for problems with other packages
24768 (defun org--flyspell-object-check-p (element)
24769 "Non-nil when Flyspell can check object at point.
24770 ELEMENT is the element at point."
24771 (let ((object (save-excursion
24772 (when (looking-at-p "\\>") (backward-char))
24773 (org-element-context element))))
24774 (cl-case (org-element-type object)
24775 ;; Prevent checks in links due to keybinding conflict with
24776 ;; Flyspell.
24777 ((code entity export-snippet inline-babel-call
24778 inline-src-block line-break latex-fragment link macro
24779 statistics-cookie target timestamp verbatim)
24780 nil)
24781 (footnote-reference
24782 ;; Only in inline footnotes, within the definition.
24783 (and (eq (org-element-property :type object) 'inline)
24784 (< (save-excursion
24785 (goto-char (org-element-property :begin object))
24786 (search-forward ":" nil t 2))
24787 (point))))
24788 (otherwise t))))
24790 (defun org-mode-flyspell-verify ()
24791 "Function used for `flyspell-generic-check-word-predicate'."
24792 (if (org-at-heading-p)
24793 ;; At a headline or an inlinetask, check title only. This is
24794 ;; faster than relying on `org-element-at-point'.
24795 (and (save-excursion (beginning-of-line)
24796 (and (let ((case-fold-search t))
24797 (not (looking-at-p "\\*+ END[ \t]*$")))
24798 (let ((case-fold-search nil))
24799 (looking-at org-complex-heading-regexp))))
24800 (match-beginning 4)
24801 (>= (point) (match-beginning 4))
24802 (or (not (match-beginning 5))
24803 (< (point) (match-beginning 5))))
24804 (let* ((element (org-element-at-point))
24805 (post-affiliated (org-element-property :post-affiliated element)))
24806 (cond
24807 ;; Ignore checks in all affiliated keywords but captions.
24808 ((< (point) post-affiliated)
24809 (and (save-excursion
24810 (beginning-of-line)
24811 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24812 (> (point) (match-end 0))
24813 (org--flyspell-object-check-p element)))
24814 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24815 ((let ((log (org-log-into-drawer)))
24816 (and log
24817 (let ((drawer (org-element-lineage element '(drawer))))
24818 (and drawer
24819 (eq (compare-strings
24820 log nil nil
24821 (org-element-property :drawer-name drawer) nil nil t)
24822 t)))))
24823 nil)
24825 (cl-case (org-element-type element)
24826 ((comment quote-section) t)
24827 (comment-block
24828 ;; Allow checks between block markers, not on them.
24829 (and (> (line-beginning-position) post-affiliated)
24830 (save-excursion
24831 (end-of-line)
24832 (skip-chars-forward " \r\t\n")
24833 (< (point) (org-element-property :end element)))))
24834 ;; Arbitrary list of keywords where checks are meaningful.
24835 ;; Make sure point is on the value part of the element.
24836 (keyword
24837 (and (member (org-element-property :key element)
24838 '("DESCRIPTION" "TITLE"))
24839 (save-excursion
24840 (search-backward ":" (line-beginning-position) t))))
24841 ;; Check is globally allowed in paragraphs verse blocks and
24842 ;; table rows (after affiliated keywords) but some objects
24843 ;; must not be affected.
24844 ((paragraph table-row verse-block)
24845 (let ((cbeg (org-element-property :contents-begin element))
24846 (cend (org-element-property :contents-end element)))
24847 (and cbeg (>= (point) cbeg) (< (point) cend)
24848 (org--flyspell-object-check-p element))))))))))
24849 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24851 (defun org-remove-flyspell-overlays-in (beg end)
24852 "Remove flyspell overlays in region."
24853 (and (bound-and-true-p flyspell-mode)
24854 (fboundp 'flyspell-delete-region-overlays)
24855 (flyspell-delete-region-overlays beg end)))
24857 (defvar flyspell-delayed-commands)
24858 (eval-after-load "flyspell"
24859 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24861 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24862 (eval-after-load "bookmark"
24863 '(if (boundp 'bookmark-after-jump-hook)
24864 ;; We can use the hook
24865 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24866 ;; Hook not available, use advice
24867 (defadvice bookmark-jump (after org-make-visible activate)
24868 "Make the position visible."
24869 (org-bookmark-jump-unhide))))
24871 ;; Make sure saveplace shows the location if it was hidden
24872 (eval-after-load "saveplace"
24873 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24874 "Make the position visible."
24875 (org-bookmark-jump-unhide)))
24877 ;; Make sure ecb shows the location if it was hidden
24878 (eval-after-load "ecb"
24879 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24880 "Make hierarchy visible when jumping into location from ECB tree buffer."
24881 (when (derived-mode-p 'org-mode)
24882 (org-show-context))))
24884 (defun org-bookmark-jump-unhide ()
24885 "Unhide the current position, to show the bookmark location."
24886 (and (derived-mode-p 'org-mode)
24887 (or (org-invisible-p)
24888 (save-excursion (goto-char (max (point-min) (1- (point))))
24889 (org-invisible-p)))
24890 (org-show-context 'bookmark-jump)))
24892 (defun org-mark-jump-unhide ()
24893 "Make the point visible with `org-show-context' after jumping to the mark."
24894 (when (and (derived-mode-p 'org-mode)
24895 (org-invisible-p))
24896 (org-show-context 'mark-goto)))
24898 (eval-after-load "simple"
24899 '(defadvice pop-to-mark-command (after org-make-visible activate)
24900 "Make the point visible with `org-show-context'."
24901 (org-mark-jump-unhide)))
24903 (eval-after-load "simple"
24904 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24905 "Make the point visible with `org-show-context'."
24906 (org-mark-jump-unhide)))
24908 (eval-after-load "simple"
24909 '(defadvice pop-global-mark (after org-make-visible activate)
24910 "Make the point visible with `org-show-context'."
24911 (org-mark-jump-unhide)))
24913 ;; Make session.el ignore our circular variable
24914 (defvar session-globals-exclude)
24915 (eval-after-load "session"
24916 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24918 ;;;; Finish up
24920 (provide 'org)
24922 (run-hooks 'org-load-hook)
24924 ;;; org.el ends here