Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob6a20073bdcd9174334baccb8fdaa9f4f9e70b4d1
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-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function
134 org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
135 (declare-function org-element-at-point "org-element" ())
136 (declare-function org-element-cache-refresh "org-element" (pos))
137 (declare-function org-element-cache-reset "org-element" (&optional all))
138 (declare-function org-element-contents "org-element" (element))
139 (declare-function org-element-context "org-element" (&optional element))
140 (declare-function org-element-copy "org-element" (datum))
141 (declare-function org-element-interpret-data "org-element" (data))
142 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
143 (declare-function org-element-link-parser "org-element" ())
144 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
145 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
146 (declare-function org-element-property "org-element" (property element))
147 (declare-function org-element-put-property "org-element" (element property value))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element-type "org-element" (element))
150 (declare-function org-element-update-syntax "org-element" ())
151 (declare-function org-id-find-id-file "org-id" (id))
152 (declare-function org-id-get-create "org-id" (&optional force))
153 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
154 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
155 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
156 (declare-function org-plot/gnuplot "org-plot" (&optional params))
157 (declare-function org-table-align "org-table" ())
158 (declare-function org-table-begin "org-table" (&optional table-type))
159 (declare-function org-table-beginning-of-field "org-table" (&optional n))
160 (declare-function org-table-blank-field "org-table" ())
161 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
162 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
163 (declare-function org-table-cut-region "org-table" (beg end))
164 (declare-function org-table-edit-field "org-table" (arg))
165 (declare-function org-table-end "org-table" (&optional table-type))
166 (declare-function org-table-end-of-field "org-table" (&optional n))
167 (declare-function org-table-insert-row "org-table" (&optional arg))
168 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
169 (declare-function org-table-maybe-eval-formula "org-table" ())
170 (declare-function org-table-maybe-recalculate-line "org-table" ())
171 (declare-function org-table-next-row "org-table" ())
172 (declare-function org-table-paste-rectangle "org-table" ())
173 (declare-function org-table-recalculate "org-table" (&optional all noalign))
174 (declare-function
175 org-table-sort-lines "org-table"
176 (&optional with-case sorting-type getkey-func compare-func interactive?))
177 (declare-function org-table-wrap-region "org-table" (arg))
178 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
179 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
180 (declare-function orgtbl-mode "org-table" (&optional arg))
181 (declare-function org-export-get-backend "ox" (name))
182 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
183 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
185 (defvar ffap-url-regexp) ;Silence byte-compiler
187 (defsubst org-uniquify (list)
188 "Non-destructively remove duplicate elements from LIST."
189 (let ((res (copy-sequence list))) (delete-dups res)))
191 (defsubst org-get-at-bol (property)
192 "Get text property PROPERTY at the beginning of line."
193 (get-text-property (point-at-bol) property))
195 (defsubst org-trim (s &optional keep-lead)
196 "Remove whitespace at the beginning and the end of string S.
197 When optional argument KEEP-LEAD is non-nil, removing blank lines
198 at the beginning of the string does not affect leading indentation."
199 (replace-regexp-in-string
200 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
201 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
203 ;; load languages based on value of `org-babel-load-languages'
204 (defvar org-babel-load-languages)
206 ;;;###autoload
207 (defun org-babel-do-load-languages (sym value)
208 "Load the languages defined in `org-babel-load-languages'."
209 (set-default sym value)
210 (dolist (pair org-babel-load-languages)
211 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
212 (if active
213 (require (intern (concat "ob-" lang)))
214 (funcall 'fmakunbound
215 (intern (concat "org-babel-execute:" lang)))
216 (funcall 'fmakunbound
217 (intern (concat "org-babel-expand-body:" lang)))))))
219 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
220 ;;;###autoload
221 (defun org-babel-load-file (file &optional compile)
222 "Load Emacs Lisp source code blocks in the Org FILE.
223 This function exports the source code using `org-babel-tangle'
224 and then loads the resulting file using `load-file'. With prefix
225 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
226 file to byte-code before it is loaded."
227 (interactive "fFile to load: \nP")
228 (let* ((age (lambda (file)
229 (float-time
230 (time-subtract (current-time)
231 (nth 5 (or (file-attributes (file-truename file))
232 (file-attributes file)))))))
233 (base-name (file-name-sans-extension file))
234 (exported-file (concat base-name ".el")))
235 ;; tangle if the Org file is newer than the elisp file
236 (unless (and (file-exists-p exported-file)
237 (> (funcall age file) (funcall age exported-file)))
238 ;; Tangle-file traversal returns reversed list of tangled files
239 ;; and we want to evaluate the first target.
240 (setq exported-file
241 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
242 (message "%s %s"
243 (if compile
244 (progn (byte-compile-file exported-file 'load)
245 "Compiled and loaded")
246 (progn (load-file exported-file) "Loaded"))
247 exported-file)))
249 (defcustom org-babel-load-languages '((emacs-lisp . t))
250 "Languages which can be evaluated in Org buffers.
251 This list can be used to load support for any of the languages
252 below, note that each language will depend on a different set of
253 system executables and/or Emacs modes. When a language is
254 \"loaded\", then code blocks in that language can be evaluated
255 with `org-babel-execute-src-block' bound by default to C-c
256 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
257 be set to remove code block evaluation from the C-c C-c
258 keybinding. By default only Emacs Lisp (which has no
259 requirements) is loaded."
260 :group 'org-babel
261 :set 'org-babel-do-load-languages
262 :version "24.1"
263 :type '(alist :tag "Babel Languages"
264 :key-type
265 (choice
266 (const :tag "Awk" awk)
267 (const :tag "C" C)
268 (const :tag "R" R)
269 (const :tag "Asymptote" asymptote)
270 (const :tag "Calc" calc)
271 (const :tag "Clojure" clojure)
272 (const :tag "CSS" css)
273 (const :tag "Ditaa" ditaa)
274 (const :tag "Dot" dot)
275 (const :tag "Ebnf2ps" ebnf2ps)
276 (const :tag "Emacs Lisp" emacs-lisp)
277 (const :tag "Forth" forth)
278 (const :tag "Fortran" fortran)
279 (const :tag "Gnuplot" gnuplot)
280 (const :tag "Haskell" haskell)
281 (const :tag "hledger" hledger)
282 (const :tag "IO" io)
283 (const :tag "J" J)
284 (const :tag "Java" java)
285 (const :tag "Javascript" js)
286 (const :tag "LaTeX" latex)
287 (const :tag "Ledger" ledger)
288 (const :tag "Lilypond" lilypond)
289 (const :tag "Lisp" lisp)
290 (const :tag "Makefile" makefile)
291 (const :tag "Maxima" maxima)
292 (const :tag "Matlab" matlab)
293 (const :tag "Mscgen" mscgen)
294 (const :tag "Ocaml" ocaml)
295 (const :tag "Octave" octave)
296 (const :tag "Org" org)
297 (const :tag "Perl" perl)
298 (const :tag "Pico Lisp" picolisp)
299 (const :tag "PlantUML" plantuml)
300 (const :tag "Python" python)
301 (const :tag "Ruby" ruby)
302 (const :tag "Sass" sass)
303 (const :tag "Scala" scala)
304 (const :tag "Scheme" scheme)
305 (const :tag "Screen" screen)
306 (const :tag "Shell Script" shell)
307 (const :tag "Shen" shen)
308 (const :tag "Sql" sql)
309 (const :tag "Sqlite" sqlite)
310 (const :tag "Stan" stan)
311 (const :tag "Vala" vala))
312 :value-type (boolean :tag "Activate" :value t)))
314 ;;;; Customization variables
315 (defcustom org-clone-delete-id nil
316 "Remove ID property of clones of a subtree.
317 When non-nil, clones of a subtree don't inherit the ID property.
318 Otherwise they inherit the ID property with a new unique
319 identifier."
320 :type 'boolean
321 :version "24.1"
322 :group 'org-id)
324 ;;; Version
325 (org-check-version)
327 ;;;###autoload
328 (defun org-version (&optional here full message)
329 "Show the Org version.
330 Interactively, or when MESSAGE is non-nil, show it in echo area.
331 With prefix argument, or when HERE is non-nil, insert it at point.
332 In non-interactive uses, a reduced version string is output unless
333 FULL is given."
334 (interactive (list current-prefix-arg t (not current-prefix-arg)))
335 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
336 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
337 (load-suffixes (list ".el"))
338 (org-install-dir
339 (ignore-errors (org-find-library-dir "org-loaddefs"))))
340 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
341 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
342 (let* ((load-suffixes save-load-suffixes)
343 (release (org-release))
344 (git-version (org-git-version))
345 (version (format "Org mode version %s (%s @ %s)"
346 release
347 git-version
348 (if org-install-dir
349 (if (string= org-dir org-install-dir)
350 org-install-dir
351 (concat "mixed installation! "
352 org-install-dir
353 " and "
354 org-dir))
355 "org-loaddefs.el can not be found!")))
356 (version1 (if full version release)))
357 (when here (insert version1))
358 (when message (message "%s" version1))
359 version1)))
361 (defconst org-version (org-version))
364 ;;; Syntax Constants
366 ;;;; Block
368 (defconst org-block-regexp
369 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
370 "Regular expression for hiding blocks.")
372 (defconst org-dblock-start-re
373 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
374 "Matches the start line of a dynamic block, with parameters.")
376 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
377 "Matches the end of a dynamic block.")
379 ;;;; Clock and Planning
381 (defconst org-clock-string "CLOCK:"
382 "String used as prefix for timestamps clocking work hours on an item.")
384 (defvar org-closed-string "CLOSED:"
385 "String used as the prefix for timestamps logging closing a TODO entry.")
387 (defvar org-deadline-string "DEADLINE:"
388 "String to mark deadline entries.
389 \\<org-mode-map>
390 A deadline is this string, followed by a time stamp. It must be
391 a word, terminated by a colon. You can insert a schedule keyword
392 and a timestamp with `\\[org-deadline]'.")
394 (defvar org-scheduled-string "SCHEDULED:"
395 "String to mark scheduled TODO entries.
396 \\<org-mode-map>
397 A schedule is this string, followed by a time stamp. It must be
398 a word, terminated by a colon. You can insert a schedule keyword
399 and a timestamp with `\\[org-schedule]'.")
401 (defconst org-ds-keyword-length
402 (+ 2
403 (apply #'max
404 (mapcar #'length
405 (list org-deadline-string org-scheduled-string
406 org-clock-string org-closed-string))))
407 "Maximum length of the DEADLINE and SCHEDULED keywords.")
409 (defconst org-planning-line-re
410 (concat "^[ \t]*"
411 (regexp-opt
412 (list org-closed-string org-deadline-string org-scheduled-string)
414 "Matches a line with planning info.
415 Matched keyword is in group 1.")
417 (defconst org-clock-line-re
418 (concat "^[ \t]*" org-clock-string)
419 "Matches a line with clock info.")
421 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
422 "Matches the DEADLINE keyword.")
424 (defconst org-deadline-time-regexp
425 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
426 "Matches the DEADLINE keyword together with a time stamp.")
428 (defconst org-deadline-time-hour-regexp
429 (concat "\\<" org-deadline-string
430 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
431 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
433 (defconst org-deadline-line-regexp
434 (concat "\\<\\(" org-deadline-string "\\).*")
435 "Matches the DEADLINE keyword and the rest of the line.")
437 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
438 "Matches the SCHEDULED keyword.")
440 (defconst org-scheduled-time-regexp
441 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
442 "Matches the SCHEDULED keyword together with a time stamp.")
444 (defconst org-scheduled-time-hour-regexp
445 (concat "\\<" org-scheduled-string
446 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
447 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
449 (defconst org-closed-time-regexp
450 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
451 "Matches the CLOSED keyword together with a time stamp.")
453 (defconst org-keyword-time-regexp
454 (concat "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string
457 org-clock-string)
459 " *[[<]\\([^]>]+\\)[]>]")
460 "Matches any of the 4 keywords, together with the time stamp.")
462 (defconst org-keyword-time-not-clock-regexp
463 (concat
464 "\\<"
465 (regexp-opt
466 (list org-scheduled-string org-deadline-string org-closed-string) t)
467 " *[[<]\\([^]>]+\\)[]>]")
468 "Matches any of the 3 keywords, together with the time stamp.")
470 (defconst org-maybe-keyword-time-regexp
471 (concat "\\(\\<"
472 (regexp-opt
473 (list org-scheduled-string org-deadline-string org-closed-string
474 org-clock-string)
476 "\\)?"
477 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
478 "\\|"
479 "<%%([^\r\n>]*>\\)")
480 "Matches a timestamp, possibly preceded by a keyword.")
482 (defconst org-all-time-keywords
483 (mapcar (lambda (w) (substring w 0 -1))
484 (list org-scheduled-string org-deadline-string
485 org-clock-string org-closed-string))
486 "List of time keywords.")
488 ;;;; Drawer
490 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
491 "Matches first or last line of a hidden block.
492 Group 1 contains drawer's name or \"END\".")
494 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
495 "Regular expression matching the first line of a property drawer.")
497 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
498 "Regular expression matching the last line of a property drawer.")
500 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
501 "Regular expression matching the first line of a clock drawer.")
503 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
504 "Regular expression matching the last line of a clock drawer.")
506 (defconst org-property-drawer-re
507 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
508 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
509 "[ \t]*:END:[ \t]*$")
510 "Matches an entire property drawer.")
512 (defconst org-clock-drawer-re
513 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
514 org-clock-drawer-end-re "\\)\n?")
515 "Matches an entire clock drawer.")
517 ;;;; Headline
519 (defconst org-heading-keyword-regexp-format
520 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
521 "Printf format for a regexp matching a headline with some keyword.
522 This regexp will match the headline of any node which has the
523 exact keyword that is put into the format. The keyword isn't in
524 any group by default, but the stars and the body are.")
526 (defconst org-heading-keyword-maybe-regexp-format
527 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
528 "Printf format for a regexp matching a headline, possibly with some keyword.
529 This regexp can match any headline with the specified keyword, or
530 without a keyword. The keyword isn't in any group by default,
531 but the stars and the body are.")
533 (defconst org-archive-tag "ARCHIVE"
534 "The tag that marks a subtree as archived.
535 An archived subtree does not open during visibility cycling, and does
536 not contribute to the agenda listings.")
538 (eval-and-compile
539 (defconst org-comment-string "COMMENT"
540 "Entries starting with this keyword will never be exported.
541 \\<org-mode-map>
542 An entry can be toggled between COMMENT and normal with
543 `\\[org-toggle-comment]'."))
546 ;;;; LaTeX Environments and Fragments
548 (defconst org-latex-regexps
549 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
550 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
551 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
552 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
553 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
554 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
555 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
556 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
557 "Regular expressions for matching embedded LaTeX.")
559 ;;;; Node Property
561 (defconst org-effort-property "Effort"
562 "The property that is being used to keep track of effort estimates.
563 Effort estimates given in this property need to have the format H:MM.")
565 ;;;; Table
567 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
568 "Detect an org-type or table-type table.")
570 (defconst org-table-line-regexp "^[ \t]*|"
571 "Detect an org-type table line.")
573 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
574 "Detect an org-type table line.")
576 (defconst org-table-hline-regexp "^[ \t]*|-"
577 "Detect an org-type table hline.")
579 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
580 "Detect a table-type table hline.")
582 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
583 "Detect the first line outside a table when searching from within it.
584 This works for both table types.")
586 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
587 "Detect a #+TBLFM line.")
589 ;;;; Timestamp
591 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
592 "Regular expression for fast time stamp matching.")
594 (defconst org-ts-regexp-inactive
595 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
596 "Regular expression for fast inactive time stamp matching.")
598 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
599 "Regular expression for fast time stamp matching.")
601 (defconst org-ts-regexp0
602 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
603 "Regular expression matching time strings for analysis.
604 This one does not require the space after the date, so it can be used
605 on a string that terminates immediately after the date.")
607 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
608 "Regular expression matching time strings for analysis.")
610 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
611 "Regular expression matching time stamps, with groups.")
613 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
614 "Regular expression matching time stamps (also [..]), with groups.")
616 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
617 "Regular expression matching a time stamp range.")
619 (defconst org-tr-regexp-both
620 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
621 "Regular expression matching a time stamp range.")
623 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
624 org-ts-regexp "\\)?")
625 "Regular expression matching a time stamp or time stamp range.")
627 (defconst org-tsr-regexp-both
628 (concat org-ts-regexp-both "\\(--?-?"
629 org-ts-regexp-both "\\)?")
630 "Regular expression matching a time stamp or time stamp range.
631 The time stamps may be either active or inactive.")
633 (defconst org-repeat-re
634 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
635 "Regular expression for specifying repeated events.
636 After a match, group 1 contains the repeat expression.")
638 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
639 "Formats for `format-time-string' which are used for time stamps.")
642 ;;; The custom variables
644 (defgroup org nil
645 "Outline-based notes management and organizer."
646 :tag "Org"
647 :group 'outlines
648 :group 'calendar)
650 (defcustom org-mode-hook nil
651 "Mode hook for Org mode, run after the mode was turned on."
652 :group 'org
653 :type 'hook)
655 (defcustom org-load-hook nil
656 "Hook that is run after org.el has been loaded."
657 :group 'org
658 :type 'hook)
660 (defcustom org-log-buffer-setup-hook nil
661 "Hook that is run after an Org log buffer is created."
662 :group 'org
663 :version "24.1"
664 :type 'hook)
666 (defvar org-modules) ; defined below
667 (defvar org-modules-loaded nil
668 "Have the modules been loaded already?")
670 (defun org-load-modules-maybe (&optional force)
671 "Load all extensions listed in `org-modules'."
672 (when (or force (not org-modules-loaded))
673 (dolist (ext org-modules)
674 (condition-case nil (require ext)
675 (error (message "Problems while trying to load feature `%s'" ext))))
676 (setq org-modules-loaded t)))
678 (defun org-set-modules (var value)
679 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
680 (set var value)
681 (when (featurep 'org)
682 (org-load-modules-maybe 'force)
683 (org-element-cache-reset 'all)))
685 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
686 "Modules that should always be loaded together with org.el.
688 If a description starts with <C>, the file is not part of Emacs
689 and loading it will require that you have downloaded and properly
690 installed the Org mode distribution.
692 You can also use this system to load external packages (i.e. neither Org
693 core modules, nor modules from the CONTRIB directory). Just add symbols
694 to the end of the list. If the package is called org-xyz.el, then you need
695 to add the symbol `xyz', and the package must have a call to:
697 (provide \\='org-xyz)
699 For export specific modules, see also `org-export-backends'."
700 :group 'org
701 :set 'org-set-modules
702 :version "24.4"
703 :package-version '(Org . "8.0")
704 :type
705 '(set :greedy t
706 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
707 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
708 (const :tag " crypt: Encryption of subtrees" org-crypt)
709 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
710 (const :tag " docview: Links to doc-view buffers" org-docview)
711 (const :tag " eww: Store link to url of eww" org-eww)
712 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
713 (const :tag " habit: Track your consistency with habits" org-habit)
714 (const :tag " id: Global IDs for identifying entries" org-id)
715 (const :tag " info: Links to Info nodes" org-info)
716 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
717 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
718 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
719 (const :tag " mouse: Additional mouse support" org-mouse)
720 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
721 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
722 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
724 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
725 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
726 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
727 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
728 (const :tag "C collector: Collect properties into tables" org-collector)
729 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
730 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
731 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
732 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
733 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
734 (const :tag "C eval: Include command output as text" org-eval)
735 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
736 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
737 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
738 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
739 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
740 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
741 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
742 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
743 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
744 (const :tag "C man: Support for links to manpages in Org mode" org-man)
745 (const :tag "C mew: Links to Mew folders/messages" org-mew)
746 (const :tag "C mtags: Support for muse-like tags" org-mtags)
747 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
748 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
749 (const :tag "C registry: A registry for Org links" org-registry)
750 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
751 (const :tag "C secretary: Team management with org-mode" org-secretary)
752 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
753 (const :tag "C toc: Table of contents for Org buffer" org-toc)
754 (const :tag "C track: Keep up with Org mode development" org-track)
755 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
756 (const :tag "C vm: Links to VM folders/messages" org-vm)
757 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
758 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
759 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
761 (defvar org-export-registered-backends) ; From ox.el.
762 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
763 (declare-function org-export-backend-name "ox" (backend) t)
764 (defcustom org-export-backends '(ascii html icalendar latex odt)
765 "List of export back-ends that should be always available.
767 If a description starts with <C>, the file is not part of Emacs
768 and loading it will require that you have downloaded and properly
769 installed the Org mode distribution.
771 Unlike to `org-modules', libraries in this list will not be
772 loaded along with Org, but only once the export framework is
773 needed.
775 This variable needs to be set before org.el is loaded. If you
776 need to make a change while Emacs is running, use the customize
777 interface or run the following code, where VAL stands for the new
778 value of the variable, after updating it:
780 (progn
781 (setq org-export-registered-backends
782 (cl-remove-if-not
783 (lambda (backend)
784 (let ((name (org-export-backend-name backend)))
785 (or (memq name val)
786 (catch \\='parentp
787 (dolist (b val)
788 (and (org-export-derived-backend-p b name)
789 (throw \\='parentp t)))))))
790 org-export-registered-backends))
791 (let ((new-list (mapcar #\\='org-export-backend-name
792 org-export-registered-backends)))
793 (dolist (backend val)
794 (cond
795 ((not (load (format \"ox-%s\" backend) t t))
796 (message \"Problems while trying to load export back-end \\=`%s\\='\"
797 backend))
798 ((not (memq backend new-list)) (push backend new-list))))
799 (set-default \\='org-export-backends new-list)))
801 Adding a back-end to this list will also pull the back-end it
802 depends on, if any."
803 :group 'org
804 :group 'org-export
805 :version "26.1"
806 :package-version '(Org . "9.0")
807 :initialize 'custom-initialize-set
808 :set (lambda (var val)
809 (if (not (featurep 'ox)) (set-default var val)
810 ;; Any back-end not required anymore (not present in VAL and not
811 ;; a parent of any back-end in the new value) is removed from the
812 ;; list of registered back-ends.
813 (setq org-export-registered-backends
814 (cl-remove-if-not
815 (lambda (backend)
816 (let ((name (org-export-backend-name backend)))
817 (or (memq name val)
818 (catch 'parentp
819 (dolist (b val)
820 (and (org-export-derived-backend-p b name)
821 (throw 'parentp t)))))))
822 org-export-registered-backends))
823 ;; Now build NEW-LIST of both new back-ends and required
824 ;; parents.
825 (let ((new-list (mapcar #'org-export-backend-name
826 org-export-registered-backends)))
827 (dolist (backend val)
828 (cond
829 ((not (load (format "ox-%s" backend) t t))
830 (message "Problems while trying to load export back-end `%s'"
831 backend))
832 ((not (memq backend new-list)) (push backend new-list))))
833 ;; Set VAR to that list with fixed dependencies.
834 (set-default var new-list))))
835 :type '(set :greedy t
836 (const :tag " ascii Export buffer to ASCII format" ascii)
837 (const :tag " beamer Export buffer to Beamer presentation" beamer)
838 (const :tag " html Export buffer to HTML format" html)
839 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
840 (const :tag " latex Export buffer to LaTeX format" latex)
841 (const :tag " man Export buffer to MAN format" man)
842 (const :tag " md Export buffer to Markdown format" md)
843 (const :tag " odt Export buffer to ODT format" odt)
844 (const :tag " org Export buffer to Org format" org)
845 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
846 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
847 (const :tag "C deck Export buffer to deck.js presentations" deck)
848 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
849 (const :tag "C groff Export buffer to Groff format" groff)
850 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
851 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
852 (const :tag "C s5 Export buffer to s5 presentations" s5)
853 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
855 (eval-after-load 'ox
856 '(dolist (backend org-export-backends)
857 (condition-case nil (require (intern (format "ox-%s" backend)))
858 (error (message "Problems while trying to load export back-end `%s'"
859 backend)))))
861 (defcustom org-support-shift-select nil
862 "Non-nil means make shift-cursor commands select text when possible.
863 \\<org-mode-map>\
865 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
866 start selecting a region, or enlarge regions started in this way.
867 In Org mode, in special contexts, these same keys are used for
868 other purposes, important enough to compete with shift selection.
869 Org tries to balance these needs by supporting `shift-select-mode'
870 outside these special contexts, under control of this variable.
872 The default of this variable is nil, to avoid confusing behavior. Shifted
873 cursor keys will then execute Org commands in the following contexts:
874 - on a headline, changing TODO state (left/right) and priority (up/down)
875 - on a time stamp, changing the time
876 - in a plain list item, changing the bullet type
877 - in a property definition line, switching between allowed values
878 - in the BEGIN line of a clock table (changing the time block).
879 Outside these contexts, the commands will throw an error.
881 When this variable is t and the cursor is not in a special
882 context, Org mode will support shift-selection for making and
883 enlarging regions. To make this more effective, the bullet
884 cycling will no longer happen anywhere in an item line, but only
885 if the cursor is exactly on the bullet.
887 If you set this variable to the symbol `always', then the keys
888 will not be special in headlines, property lines, and item lines,
889 to make shift selection work there as well. If this is what you
890 want, you can use the following alternative commands:
891 `\\[org-todo]' and `\\[org-priority]' \
892 to change TODO state and priority,
893 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
894 can be used to switch TODO sets,
895 `\\[org-ctrl-c-minus]' to cycle item bullet types,
896 and properties can be edited by hand or in column view.
898 However, when the cursor is on a timestamp, shift-cursor commands
899 will still edit the time stamp - this is just too good to give up."
900 :group 'org
901 :type '(choice
902 (const :tag "Never" nil)
903 (const :tag "When outside special context" t)
904 (const :tag "Everywhere except timestamps" always)))
906 (defcustom org-loop-over-headlines-in-active-region nil
907 "Shall some commands act upon headlines in the active region?
909 When set to t, some commands will be performed in all headlines
910 within the active region.
912 When set to `start-level', some commands will be performed in all
913 headlines within the active region, provided that these headlines
914 are of the same level than the first one.
916 When set to a string, those commands will be performed on the
917 matching headlines within the active region. Such string must be
918 a tags/property/todo match as it is used in the agenda tags view.
920 The list of commands is: `org-schedule', `org-deadline',
921 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
922 `org-archive-to-archive-sibling'. The archiving commands skip
923 already archived entries."
924 :type '(choice (const :tag "Don't loop" nil)
925 (const :tag "All headlines in active region" t)
926 (const :tag "In active region, headlines at the same level than the first one" start-level)
927 (string :tag "Tags/Property/Todo matcher"))
928 :version "24.1"
929 :group 'org-todo
930 :group 'org-archive)
932 (defgroup org-startup nil
933 "Options concerning startup of Org mode."
934 :tag "Org Startup"
935 :group 'org)
937 (defcustom org-startup-folded t
938 "Non-nil means entering Org mode will switch to OVERVIEW.
940 This can also be configured on a per-file basis by adding one of
941 the following lines anywhere in the buffer:
943 #+STARTUP: fold (or `overview', this is equivalent)
944 #+STARTUP: nofold (or `showall', this is equivalent)
945 #+STARTUP: content
946 #+STARTUP: showeverything
948 Set `org-agenda-inhibit-startup' to a non-nil value if you want
949 to ignore this option when Org opens agenda files for the first
950 time."
951 :group 'org-startup
952 :type '(choice
953 (const :tag "nofold: show all" nil)
954 (const :tag "fold: overview" t)
955 (const :tag "content: all headlines" content)
956 (const :tag "show everything, even drawers" showeverything)))
958 (defcustom org-startup-truncated t
959 "Non-nil means entering Org mode will set `truncate-lines'.
960 This is useful since some lines containing links can be very long and
961 uninteresting. Also tables look terrible when wrapped.
963 The variable `org-startup-truncated' allows to configure
964 truncation for Org mode different to the other modes that use the
965 variable `truncate-lines' and as a shortcut instead of putting
966 the variable `truncate-lines' into the `org-mode-hook'. If one
967 wants to configure truncation for Org mode not statically but
968 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
969 the variable `truncate-lines' has to be used because in such a
970 case it is too late to set the variable `org-startup-truncated'."
971 :group 'org-startup
972 :type 'boolean)
974 (defcustom org-startup-indented nil
975 "Non-nil means turn on `org-indent-mode' on startup.
976 This can also be configured on a per-file basis by adding one of
977 the following lines anywhere in the buffer:
979 #+STARTUP: indent
980 #+STARTUP: noindent"
981 :group 'org-structure
982 :type '(choice
983 (const :tag "Not" nil)
984 (const :tag "Globally (slow on startup in large files)" t)))
986 (defcustom org-use-sub-superscripts t
987 "Non-nil means interpret \"_\" and \"^\" for display.
989 If you want to control how Org exports those characters, see
990 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
991 used to be an alias for `org-export-with-sub-superscripts' in
992 Org <8.0, it is not anymore.
994 When this option is turned on, you can use TeX-like syntax for
995 sub- and superscripts within the buffer. Several characters after
996 \"_\" or \"^\" will be considered as a single item - so grouping
997 with {} is normally not needed. For example, the following things
998 will be parsed as single sub- or superscripts:
1000 10^24 or 10^tau several digits will be considered 1 item.
1001 10^-12 or 10^-tau a leading sign with digits or a word
1002 x^2-y^3 will be read as x^2 - y^3, because items are
1003 terminated by almost any nonword/nondigit char.
1004 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1006 Still, ambiguity is possible. So when in doubt, use {} to enclose
1007 the sub/superscript. If you set this variable to the symbol `{}',
1008 the braces are *required* in order to trigger interpretations as
1009 sub/superscript. This can be helpful in documents that need \"_\"
1010 frequently in plain text."
1011 :group 'org-startup
1012 :version "24.4"
1013 :package-version '(Org . "8.0")
1014 :type '(choice
1015 (const :tag "Always interpret" t)
1016 (const :tag "Only with braces" {})
1017 (const :tag "Never interpret" nil)))
1019 (defcustom org-startup-with-beamer-mode nil
1020 "Non-nil means turn on `org-beamer-mode' on startup.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1024 #+STARTUP: beamer"
1025 :group 'org-startup
1026 :version "24.1"
1027 :type 'boolean)
1029 (defcustom org-startup-align-all-tables nil
1030 "Non-nil means align all tables when visiting a file.
1031 This is useful when the column width in tables is forced with <N> cookies
1032 in table fields. Such tables will look correct only after the first re-align.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: align
1036 #+STARTUP: noalign"
1037 :group 'org-startup
1038 :type 'boolean)
1040 (defcustom org-startup-with-inline-images nil
1041 "Non-nil means show inline images when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: inlineimages
1045 #+STARTUP: noinlineimages"
1046 :group 'org-startup
1047 :version "24.1"
1048 :type 'boolean)
1050 (defcustom org-startup-with-latex-preview nil
1051 "Non-nil means preview LaTeX fragments when loading a new Org file.
1053 This can also be configured on a per-file basis by adding one of
1054 the following lines anywhere in the buffer:
1055 #+STARTUP: latexpreview
1056 #+STARTUP: nolatexpreview"
1057 :group 'org-startup
1058 :version "24.4"
1059 :package-version '(Org . "8.0")
1060 :type 'boolean)
1062 (defcustom org-insert-mode-line-in-empty-file nil
1063 "Non-nil means insert the first line setting Org mode in empty files.
1064 When the function `org-mode' is called interactively in an empty file, this
1065 normally means that the file name does not automatically trigger Org mode.
1066 To ensure that the file will always be in Org mode in the future, a
1067 line enforcing Org mode will be inserted into the buffer, if this option
1068 has been set."
1069 :group 'org-startup
1070 :type 'boolean)
1072 (defcustom org-replace-disputed-keys nil
1073 "Non-nil means use alternative key bindings for some keys.
1074 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1075 These keys are also used by other packages like shift-selection-mode'
1076 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1077 If you want to use Org mode together with one of these other modes,
1078 or more generally if you would like to move some Org mode commands to
1079 other keys, set this variable and configure the keys with the variable
1080 `org-disputed-keys'.
1082 This option is only relevant at load-time of Org mode, and must be set
1083 *before* org.el is loaded. Changing it requires a restart of Emacs to
1084 become effective."
1085 :group 'org-startup
1086 :type 'boolean)
1088 (defcustom org-use-extra-keys nil
1089 "Non-nil means use extra key sequence definitions for certain commands.
1090 This happens automatically if `window-system' is nil. This
1091 variable lets you do the same manually. You must set it before
1092 loading Org."
1093 :group 'org-startup
1094 :type 'boolean)
1096 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1098 (defcustom org-disputed-keys
1099 '(([(shift up)] . [(meta p)])
1100 ([(shift down)] . [(meta n)])
1101 ([(shift left)] . [(meta -)])
1102 ([(shift right)] . [(meta +)])
1103 ([(control shift right)] . [(meta shift +)])
1104 ([(control shift left)] . [(meta shift -)]))
1105 "Keys for which Org mode and other modes compete.
1106 This is an alist, cars are the default keys, second element specifies
1107 the alternative to use when `org-replace-disputed-keys' is t.
1109 Keys can be specified in any syntax supported by `define-key'.
1110 The value of this option takes effect only at Org mode startup,
1111 therefore you'll have to restart Emacs to apply it after changing."
1112 :group 'org-startup
1113 :type 'alist)
1115 (defun org-key (key)
1116 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1117 Or return the original if not disputed."
1118 (when org-replace-disputed-keys
1119 (let* ((nkey (key-description key))
1120 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1121 org-disputed-keys)))
1122 (setq key (if x (cdr x) key))))
1123 key)
1125 (defun org-defkey (keymap key def)
1126 "Define a key, possibly translated, as returned by `org-key'."
1127 (define-key keymap (org-key key) def))
1129 (defcustom org-ellipsis nil
1130 "The ellipsis to use in the Org mode outline.
1132 When nil, just use the standard three dots. When a non-empty string,
1133 use that string instead.
1135 The change affects only Org mode (which will then use its own display table).
1136 Changing this requires executing `\\[org-mode]' in a buffer to become
1137 effective."
1138 :group 'org-startup
1139 :type '(choice (const :tag "Default" nil)
1140 (string :tag "String" :value "...#"))
1141 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1143 (defvar org-display-table nil
1144 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1146 (defgroup org-keywords nil
1147 "Keywords in Org mode."
1148 :tag "Org Keywords"
1149 :group 'org)
1151 (defcustom org-closed-keep-when-no-todo nil
1152 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1153 :group 'org-todo
1154 :group 'org-keywords
1155 :version "24.4"
1156 :package-version '(Org . "8.0")
1157 :type 'boolean)
1159 (defgroup org-structure nil
1160 "Options concerning the general structure of Org files."
1161 :tag "Org Structure"
1162 :group 'org)
1164 (defgroup org-reveal-location nil
1165 "Options about how to make context of a location visible."
1166 :tag "Org Reveal Location"
1167 :group 'org-structure)
1169 (defcustom org-show-context-detail '((agenda . local)
1170 (bookmark-jump . lineage)
1171 (isearch . lineage)
1172 (default . ancestors))
1173 "Alist between context and visibility span when revealing a location.
1175 \\<org-mode-map>Some actions may move point into invisible
1176 locations. As a consequence, Org always expose a neighborhood
1177 around point. How much is shown depends on the initial action,
1178 or context. Valid contexts are
1180 agenda when exposing an entry from the agenda
1181 org-goto when using the command `org-goto' (`\\[org-goto]')
1182 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1183 tags-tree when constructing a sparse tree based on tags matches
1184 link-search when exposing search matches associated with a link
1185 mark-goto when exposing the jump goal of a mark
1186 bookmark-jump when exposing a bookmark location
1187 isearch when exiting from an incremental search
1188 default default for all contexts not set explicitly
1190 Allowed visibility spans are
1192 minimal show current headline; if point is not on headline,
1193 also show entry
1195 local show current headline, entry and next headline
1197 ancestors show current headline and its direct ancestors; if
1198 point is not on headline, also show entry
1200 lineage show current headline, its direct ancestors and all
1201 their children; if point is not on headline, also show
1202 entry and first child
1204 tree show current headline, its direct ancestors and all
1205 their children; if point is not on headline, also show
1206 entry and all children
1208 canonical show current headline, its direct ancestors along with
1209 their entries and children; if point is not located on
1210 the headline, also show current entry and all children
1212 As special cases, a nil or t value means show all contexts in
1213 `minimal' or `canonical' view, respectively.
1215 Some views can make displayed information very compact, but also
1216 make it harder to edit the location of the match. In such
1217 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1218 more context."
1219 :group 'org-reveal-location
1220 :version "26.1"
1221 :package-version '(Org . "9.0")
1222 :type '(choice
1223 (const :tag "Canonical" t)
1224 (const :tag "Minimal" nil)
1225 (repeat :greedy t :tag "Individual contexts"
1226 (cons
1227 (choice :tag "Context"
1228 (const agenda)
1229 (const org-goto)
1230 (const occur-tree)
1231 (const tags-tree)
1232 (const link-search)
1233 (const mark-goto)
1234 (const bookmark-jump)
1235 (const isearch)
1236 (const default))
1237 (choice :tag "Detail level"
1238 (const minimal)
1239 (const local)
1240 (const ancestors)
1241 (const lineage)
1242 (const tree)
1243 (const canonical))))))
1245 (defcustom org-indirect-buffer-display 'other-window
1246 "How should indirect tree buffers be displayed?
1248 This applies to indirect buffers created with the commands
1249 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1251 Valid values are:
1252 current-window Display in the current window
1253 other-window Just display in another window.
1254 dedicated-frame Create one new frame, and re-use it each time.
1255 new-frame Make a new frame each time. Note that in this case
1256 previously-made indirect buffers are kept, and you need to
1257 kill these buffers yourself."
1258 :group 'org-structure
1259 :group 'org-agenda-windows
1260 :type '(choice
1261 (const :tag "In current window" current-window)
1262 (const :tag "In current frame, other window" other-window)
1263 (const :tag "Each time a new frame" new-frame)
1264 (const :tag "One dedicated frame" dedicated-frame)))
1266 (defcustom org-use-speed-commands nil
1267 "Non-nil means activate single letter commands at beginning of a headline.
1268 This may also be a function to test for appropriate locations where speed
1269 commands should be active.
1271 For example, to activate speed commands when the point is on any
1272 star at the beginning of the headline, you can do this:
1274 (setq org-use-speed-commands
1275 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1276 :group 'org-structure
1277 :type '(choice
1278 (const :tag "Never" nil)
1279 (const :tag "At beginning of headline stars" t)
1280 (function)))
1282 (defcustom org-speed-commands-user nil
1283 "Alist of additional speed commands.
1284 This list will be checked before `org-speed-commands-default'
1285 when the variable `org-use-speed-commands' is non-nil
1286 and when the cursor is at the beginning of a headline.
1287 The car if each entry is a string with a single letter, which must
1288 be assigned to `self-insert-command' in the global map.
1289 The cdr is either a command to be called interactively, a function
1290 to be called, or a form to be evaluated.
1291 An entry that is just a list with a single string will be interpreted
1292 as a descriptive headline that will be added when listing the speed
1293 commands in the Help buffer using the `?' speed command."
1294 :group 'org-structure
1295 :type '(repeat :value ("k" . ignore)
1296 (choice :value ("k" . ignore)
1297 (list :tag "Descriptive Headline" (string :tag "Headline"))
1298 (cons :tag "Letter and Command"
1299 (string :tag "Command letter")
1300 (choice
1301 (function)
1302 (sexp))))))
1304 (defcustom org-bookmark-names-plist
1305 '(:last-capture "org-capture-last-stored"
1306 :last-refile "org-refile-last-stored"
1307 :last-capture-marker "org-capture-last-stored-marker")
1308 "Names for bookmarks automatically set by some Org commands.
1309 This can provide strings as names for a number of bookmarks Org sets
1310 automatically. The following keys are currently implemented:
1311 :last-capture
1312 :last-capture-marker
1313 :last-refile
1314 When a key does not show up in the property list, the corresponding bookmark
1315 is not set."
1316 :group 'org-structure
1317 :type 'plist)
1319 (defgroup org-cycle nil
1320 "Options concerning visibility cycling in Org mode."
1321 :tag "Org Cycle"
1322 :group 'org-structure)
1324 (defcustom org-cycle-skip-children-state-if-no-children t
1325 "Non-nil means skip CHILDREN state in entries that don't have any."
1326 :group 'org-cycle
1327 :type 'boolean)
1329 (defcustom org-cycle-max-level nil
1330 "Maximum level which should still be subject to visibility cycling.
1331 Levels higher than this will, for cycling, be treated as text, not a headline.
1332 When `org-odd-levels-only' is set, a value of N in this variable actually
1333 means 2N-1 stars as the limiting headline.
1334 When nil, cycle all levels.
1335 Note that the limiting level of cycling is also influenced by
1336 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1337 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1338 than its value."
1339 :group 'org-cycle
1340 :type '(choice
1341 (const :tag "No limit" nil)
1342 (integer :tag "Maximum level")))
1344 (defcustom org-hide-block-startup nil
1345 "Non-nil means entering Org mode will fold all blocks.
1346 This can also be set in on a per-file basis with
1348 #+STARTUP: hideblocks
1349 #+STARTUP: showblocks"
1350 :group 'org-startup
1351 :group 'org-cycle
1352 :type 'boolean)
1354 (defcustom org-cycle-global-at-bob nil
1355 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1357 This makes it possible to do global cycling without having to use `S-TAB'
1358 or `\\[universal-argument] TAB'. For this special case to work, the first \
1359 line of the buffer
1360 must not be a headline -- it may be empty or some other text.
1362 When used in this way, `org-cycle-hook' is disabled temporarily to make
1363 sure the cursor stays at the beginning of the buffer.
1365 When this option is nil, don't do anything special at the beginning of
1366 the buffer."
1367 :group 'org-cycle
1368 :type 'boolean)
1370 (defcustom org-cycle-level-after-item/entry-creation t
1371 "Non-nil means cycle entry level or item indentation in new empty entries.
1373 When the cursor is at the end of an empty headline, i.e., with only stars
1374 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1375 and then all possible ancestor states, before returning to the original state.
1376 This makes data entry extremely fast: M-RET to create a new headline,
1377 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1379 When the cursor is at the end of an empty plain list item, one TAB will
1380 make it a subitem, two or more tabs will back up to make this an item
1381 higher up in the item hierarchy."
1382 :group 'org-cycle
1383 :type 'boolean)
1385 (defcustom org-cycle-emulate-tab t
1386 "Where should `org-cycle' emulate TAB.
1387 nil Never
1388 white Only in completely white lines
1389 whitestart Only at the beginning of lines, before the first non-white char
1390 t Everywhere except in headlines
1391 exc-hl-bol Everywhere except at the start of a headline
1392 If TAB is used in a place where it does not emulate TAB, the current subtree
1393 visibility is cycled."
1394 :group 'org-cycle
1395 :type '(choice (const :tag "Never" nil)
1396 (const :tag "Only in completely white lines" white)
1397 (const :tag "Before first char in a line" whitestart)
1398 (const :tag "Everywhere except in headlines" t)
1399 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1401 (defcustom org-cycle-separator-lines 2
1402 "Number of empty lines needed to keep an empty line between collapsed trees.
1403 If you leave an empty line between the end of a subtree and the following
1404 headline, this empty line is hidden when the subtree is folded.
1405 Org mode will leave (exactly) one empty line visible if the number of
1406 empty lines is equal or larger to the number given in this variable.
1407 So the default 2 means at least 2 empty lines after the end of a subtree
1408 are needed to produce free space between a collapsed subtree and the
1409 following headline.
1411 If the number is negative, and the number of empty lines is at least -N,
1412 all empty lines are shown.
1414 Special case: when 0, never leave empty lines in collapsed view."
1415 :group 'org-cycle
1416 :type 'integer)
1417 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1419 (defcustom org-pre-cycle-hook nil
1420 "Hook that is run before visibility cycling is happening.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that will be set right after running this hook. The
1423 argument is a symbol. Before a global state change, it can have the values
1424 `overview', `content', or `all'. Before a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook)
1429 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1430 org-cycle-hide-drawers
1431 org-cycle-show-empty-lines
1432 org-optimize-window-after-visibility-change)
1433 "Hook that is run after `org-cycle' has changed the buffer visibility.
1434 The function(s) in this hook must accept a single argument which indicates
1435 the new state that was set by the most recent `org-cycle' command. The
1436 argument is a symbol. After a global state change, it can have the values
1437 `overview', `contents', or `all'. After a local state change, it can have
1438 the values `folded', `children', or `subtree'."
1439 :group 'org-cycle
1440 :type 'hook
1441 :version "26.1"
1442 :package-version '(Org . "8.3"))
1444 (defgroup org-edit-structure nil
1445 "Options concerning structure editing in Org mode."
1446 :tag "Org Edit Structure"
1447 :group 'org-structure)
1449 (defcustom org-odd-levels-only nil
1450 "Non-nil means skip even levels and only use odd levels for the outline.
1451 This has the effect that two stars are being added/taken away in
1452 promotion/demotion commands. It also influences how levels are
1453 handled by the exporters.
1454 Changing it requires restart of `font-lock-mode' to become effective
1455 for fontification also in regions already fontified.
1456 You may also set this on a per-file basis by adding one of the following
1457 lines to the buffer:
1459 #+STARTUP: odd
1460 #+STARTUP: oddeven"
1461 :group 'org-edit-structure
1462 :group 'org-appearance
1463 :type 'boolean)
1465 (defcustom org-adapt-indentation t
1466 "Non-nil means adapt indentation to outline node level.
1468 When this variable is set, Org assumes that you write outlines by
1469 indenting text in each node to align with the headline (after the
1470 stars). The following issues are influenced by this variable:
1472 - The indentation is increased by one space in a demotion
1473 command, and decreased by one in a promotion command. However,
1474 in the latter case, if shifting some line in the entry body
1475 would alter document structure (e.g., insert a new headline),
1476 indentation is not changed at all.
1478 - Property drawers and planning information is inserted indented
1479 when this variable is set. When nil, they will not be indented.
1481 - TAB indents a line relative to current level. The lines below
1482 a headline will be indented when this variable is set.
1484 Note that this is all about true indentation, by adding and
1485 removing space characters. See also `org-indent.el' which does
1486 level-dependent indentation in a virtual way, i.e. at display
1487 time in Emacs."
1488 :group 'org-edit-structure
1489 :type 'boolean)
1491 (defcustom org-special-ctrl-a/e nil
1492 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1494 When t, `C-a' will bring back the cursor to the beginning of the
1495 headline text, i.e. after the stars and after a possible TODO
1496 keyword. In an item, this will be the position after bullet and
1497 check-box, if any. When the cursor is already at that position,
1498 another `C-a' will bring it to the beginning of the line.
1500 `C-e' will jump to the end of the headline, ignoring the presence
1501 of tags in the headline. A second `C-e' will then jump to the
1502 true end of the line, after any tags. This also means that, when
1503 this variable is non-nil, `C-e' also will never jump beyond the
1504 end of the heading of a folded section, i.e. not after the
1505 ellipses.
1507 When set to the symbol `reversed', the first `C-a' or `C-e' works
1508 normally, going to the true line boundary first. Only a directly
1509 following, identical keypress will bring the cursor to the
1510 special positions.
1512 This may also be a cons cell where the behavior for `C-a' and
1513 `C-e' is set separately."
1514 :group 'org-edit-structure
1515 :type '(choice
1516 (const :tag "off" nil)
1517 (const :tag "on: after stars/bullet and before tags first" t)
1518 (const :tag "reversed: true line boundary first" reversed)
1519 (cons :tag "Set C-a and C-e separately"
1520 (choice :tag "Special C-a"
1521 (const :tag "off" nil)
1522 (const :tag "on: after stars/bullet first" t)
1523 (const :tag "reversed: before stars/bullet first" reversed))
1524 (choice :tag "Special C-e"
1525 (const :tag "off" nil)
1526 (const :tag "on: before tags first" t)
1527 (const :tag "reversed: after tags first" reversed)))))
1528 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1530 (defcustom org-special-ctrl-k nil
1531 "Non-nil means `C-k' will behave specially in headlines.
1532 When nil, `C-k' will call the default `kill-line' command.
1533 When t, the following will happen while the cursor is in the headline:
1535 - When the cursor is at the beginning of a headline, kill the entire
1536 line and possible the folded subtree below the line.
1537 - When in the middle of the headline text, kill the headline up to the tags.
1538 - When after the headline text, kill the tags."
1539 :group 'org-edit-structure
1540 :type 'boolean)
1542 (defcustom org-ctrl-k-protect-subtree nil
1543 "Non-nil means, do not delete a hidden subtree with C-k.
1544 When set to the symbol `error', simply throw an error when C-k is
1545 used to kill (part-of) a headline that has hidden text behind it.
1546 Any other non-nil value will result in a query to the user, if it is
1547 OK to kill that hidden subtree. When nil, kill without remorse."
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not protect hidden subtrees" nil)
1552 (const :tag "Protect hidden subtrees with a security query" t)
1553 (const :tag "Never kill a hidden subtree with C-k" error)))
1555 (defcustom org-special-ctrl-o t
1556 "Non-nil means, make `C-o' insert a row in tables."
1557 :group 'org-edit-structure
1558 :type 'boolean)
1560 (defcustom org-catch-invisible-edits nil
1561 "Check if in invisible region before inserting or deleting a character.
1562 Valid values are:
1564 nil Do not check, so just do invisible edits.
1565 error Throw an error and do nothing.
1566 show Make point visible, and do the requested edit.
1567 show-and-error Make point visible, then throw an error and abort the edit.
1568 smart Make point visible, and do insertion/deletion if it is
1569 adjacent to visible text and the change feels predictable.
1570 Never delete a previously invisible character or add in the
1571 middle or right after an invisible region. Basically, this
1572 allows insertion and backward-delete right before ellipses.
1573 FIXME: maybe in this case we should not even show?"
1574 :group 'org-edit-structure
1575 :version "24.1"
1576 :type '(choice
1577 (const :tag "Do not check" nil)
1578 (const :tag "Throw error when trying to edit" error)
1579 (const :tag "Unhide, but do not do the edit" show-and-error)
1580 (const :tag "Show invisible part and do the edit" show)
1581 (const :tag "Be smart and do the right thing" smart)))
1583 (defcustom org-yank-folded-subtrees t
1584 "Non-nil means when yanking subtrees, fold them.
1585 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1586 it starts with a heading and all other headings in it are either children
1587 or siblings, then fold all the subtrees. However, do this only if no
1588 text after the yank would be swallowed into a folded tree by this action."
1589 :group 'org-edit-structure
1590 :type 'boolean)
1592 (defcustom org-yank-adjusted-subtrees nil
1593 "Non-nil means when yanking subtrees, adjust the level.
1594 With this setting, `org-paste-subtree' is used to insert the subtree, see
1595 this function for details."
1596 :group 'org-edit-structure
1597 :type 'boolean)
1599 (defcustom org-M-RET-may-split-line '((default . t))
1600 "Non-nil means M-RET will split the line at the cursor position.
1601 When nil, it will go to the end of the line before making a
1602 new line.
1603 You may also set this option in a different way for different
1604 contexts. Valid contexts are:
1606 headline when creating a new headline
1607 item when creating a new item
1608 table in a table field
1609 default the value to be used for all contexts not explicitly
1610 customized"
1611 :group 'org-structure
1612 :group 'org-table
1613 :type '(choice
1614 (const :tag "Always" t)
1615 (const :tag "Never" nil)
1616 (repeat :greedy t :tag "Individual contexts"
1617 (cons
1618 (choice :tag "Context"
1619 (const headline)
1620 (const item)
1621 (const table)
1622 (const default))
1623 (boolean)))))
1626 (defcustom org-insert-heading-respect-content nil
1627 "Non-nil means insert new headings after the current subtree.
1628 \\<org-mode-map>
1629 When nil, the new heading is created directly after the current line.
1630 The commands `\\[org-insert-heading-respect-content]' and \
1631 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1632 for the duration of the command."
1633 :group 'org-structure
1634 :type 'boolean)
1636 (defcustom org-blank-before-new-entry '((heading . auto)
1637 (plain-list-item . auto))
1638 "Should `org-insert-heading' leave a blank line before new heading/item?
1639 The value is an alist, with `heading' and `plain-list-item' as CAR,
1640 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1641 which case Org will look at the surrounding headings/items and try to
1642 make an intelligent decision whether to insert a blank line or not."
1643 :group 'org-edit-structure
1644 :type '(list
1645 (cons (const heading)
1646 (choice (const :tag "Never" nil)
1647 (const :tag "Always" t)
1648 (const :tag "Auto" auto)))
1649 (cons (const plain-list-item)
1650 (choice (const :tag "Never" nil)
1651 (const :tag "Always" t)
1652 (const :tag "Auto" auto)))))
1654 (defcustom org-insert-heading-hook nil
1655 "Hook being run after inserting a new heading."
1656 :group 'org-edit-structure
1657 :type 'hook)
1659 (defcustom org-enable-fixed-width-editor t
1660 "Non-nil means lines starting with \":\" are treated as fixed-width.
1661 This currently only means they are never auto-wrapped.
1662 When nil, such lines will be treated like ordinary lines."
1663 :group 'org-edit-structure
1664 :type 'boolean)
1666 (defcustom org-goto-auto-isearch t
1667 "Non-nil means typing characters in `org-goto' starts incremental search.
1668 When nil, you can use these keybindings to navigate the buffer:
1670 q Quit the org-goto interface
1671 n Go to the next visible heading
1672 p Go to the previous visible heading
1673 f Go one heading forward on same level
1674 b Go one heading backward on same level
1675 u Go one heading up"
1676 :group 'org-edit-structure
1677 :type 'boolean)
1679 (defgroup org-sparse-trees nil
1680 "Options concerning sparse trees in Org mode."
1681 :tag "Org Sparse Trees"
1682 :group 'org-structure)
1684 (defcustom org-highlight-sparse-tree-matches t
1685 "Non-nil means highlight all matches that define a sparse tree.
1686 The highlights will automatically disappear the next time the buffer is
1687 changed by an edit command."
1688 :group 'org-sparse-trees
1689 :type 'boolean)
1691 (defcustom org-remove-highlights-with-change t
1692 "Non-nil means any change to the buffer will remove temporary highlights.
1693 \\<org-mode-map>\
1694 Such highlights are created by `org-occur' and `org-clock-display'.
1695 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1696 to get rid of the highlights.
1697 The highlights created by `org-toggle-latex-fragment' always need
1698 `\\[org-toggle-latex-fragment]' to be removed."
1699 :group 'org-sparse-trees
1700 :group 'org-time
1701 :type 'boolean)
1703 (defcustom org-occur-case-fold-search t
1704 "Non-nil means `org-occur' should be case-insensitive.
1705 If set to `smart' the search will be case-insensitive only if it
1706 doesn't specify any upper case character."
1707 :group 'org-sparse-trees
1708 :version "26.1"
1709 :type '(choice
1710 (const :tag "Case-sensitive" nil)
1711 (const :tag "Case-insensitive" t)
1712 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1714 (defcustom org-occur-hook '(org-first-headline-recenter)
1715 "Hook that is run after `org-occur' has constructed a sparse tree.
1716 This can be used to recenter the window to show as much of the structure
1717 as possible."
1718 :group 'org-sparse-trees
1719 :type 'hook)
1721 (defgroup org-imenu-and-speedbar nil
1722 "Options concerning imenu and speedbar in Org mode."
1723 :tag "Org Imenu and Speedbar"
1724 :group 'org-structure)
1726 (defcustom org-imenu-depth 2
1727 "The maximum level for Imenu access to Org headlines.
1728 This also applied for speedbar access."
1729 :group 'org-imenu-and-speedbar
1730 :type 'integer)
1732 (defgroup org-table nil
1733 "Options concerning tables in Org mode."
1734 :tag "Org Table"
1735 :group 'org)
1737 (defcustom org-enable-table-editor 'optimized
1738 "Non-nil means lines starting with \"|\" are handled by the table editor.
1739 When nil, such lines will be treated like ordinary lines.
1741 When equal to the symbol `optimized', the table editor will be optimized to
1742 do the following:
1743 - Automatic overwrite mode in front of whitespace in table fields.
1744 This makes the structure of the table stay in tact as long as the edited
1745 field does not exceed the column width.
1746 - Minimize the number of realigns. Normally, the table is aligned each time
1747 TAB or RET are pressed to move to another field. With optimization this
1748 happens only if changes to a field might have changed the column width.
1749 Optimization requires replacing the functions `self-insert-command',
1750 `delete-char', and `backward-delete-char' in Org buffers, with a
1751 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1752 good at guessing when a re-align will be necessary, but you can always
1753 force one with `\\[org-ctrl-c-ctrl-c]'.
1755 If you would like to use the optimized version in Org mode, but the
1756 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1758 This variable can be used to turn on and off the table editor during a session,
1759 but in order to toggle optimization, a restart is required.
1761 See also the variable `org-table-auto-blank-field'."
1762 :group 'org-table
1763 :type '(choice
1764 (const :tag "off" nil)
1765 (const :tag "on" t)
1766 (const :tag "on, optimized" optimized)))
1768 (defcustom org-self-insert-cluster-for-undo nil
1769 "Non-nil means cluster self-insert commands for undo when possible.
1770 If this is set, then, like in the Emacs command loop, 20 consecutive
1771 characters will be undone together.
1772 This is configurable, because there is some impact on typing performance."
1773 :group 'org-table
1774 :type 'boolean)
1776 (defcustom org-table-tab-recognizes-table.el t
1777 "Non-nil means TAB will automatically notice a table.el table.
1778 When it sees such a table, it moves point into it and - if necessary -
1779 calls `table-recognize-table'."
1780 :group 'org-table-editing
1781 :type 'boolean)
1783 (defgroup org-link nil
1784 "Options concerning links in Org mode."
1785 :tag "Org Link"
1786 :group 'org)
1788 (defvar-local org-link-abbrev-alist-local nil
1789 "Buffer-local version of `org-link-abbrev-alist', which see.
1790 The value of this is taken from the #+LINK lines.")
1792 (defcustom org-link-parameters
1793 '(("doi" :follow org--open-doi-link)
1794 ("elisp" :follow org--open-elisp-link)
1795 ("file" :complete org-file-complete-link)
1796 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1797 ("help" :follow org--open-help-link)
1798 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1799 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1800 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1801 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1802 ("shell" :follow org--open-shell-link))
1803 "An alist of properties that defines all the links in Org mode.
1804 The key in each association is a string of the link type.
1805 Subsequent optional elements make up a p-list of link properties.
1807 :follow - A function that takes the link path as an argument.
1809 :export - A function that takes the link path, description and
1810 export-backend as arguments.
1812 :store - A function responsible for storing the link. See the
1813 function `org-store-link-functions'.
1815 :complete - A function that inserts a link with completion. The
1816 function takes one optional prefix arg.
1818 :face - A face for the link, or a function that returns a face.
1819 The function takes one argument which is the link path. The
1820 default face is `org-link'.
1822 :mouse-face - The mouse-face. The default is `highlight'.
1824 :display - `full' will not fold the link in descriptive
1825 display. Default is `org-link'.
1827 :help-echo - A string or function that takes (window object position)
1828 as arguments and returns a string.
1830 :keymap - A keymap that is active on the link. The default is
1831 `org-mouse-map'.
1833 :htmlize-link - A function for the htmlize-link. Defaults
1834 to (list :uri \"type:path\")
1836 :activate-func - A function to run at the end of font-lock
1837 activation. The function must accept (link-start link-end path bracketp)
1838 as arguments."
1839 :group 'org-link
1840 :type '(alist :tag "Link display parameters"
1841 :value-type plist)
1842 :version "26.1"
1843 :package-version '(Org . "9.1"))
1845 (defun org-link-get-parameter (type key)
1846 "Get TYPE link property for KEY.
1847 TYPE is a string and KEY is a plist keyword."
1848 (plist-get
1849 (cdr (assoc type org-link-parameters))
1850 key))
1852 (defun org-link-set-parameters (type &rest parameters)
1853 "Set link TYPE properties to PARAMETERS.
1854 PARAMETERS should be :key val pairs."
1855 (let ((data (assoc type org-link-parameters)))
1856 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1857 (push (cons type parameters) org-link-parameters)
1858 (org-make-link-regexps)
1859 (org-element-update-syntax))))
1861 (defun org-link-types ()
1862 "Return a list of known link types."
1863 (mapcar #'car org-link-parameters))
1865 (defcustom org-link-abbrev-alist nil
1866 "Alist of link abbreviations.
1867 The car of each element is a string, to be replaced at the start of a link.
1868 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1869 links in Org buffers can have an optional tag after a double colon, e.g.,
1871 [[linkkey:tag][description]]
1873 The `linkkey' must be a single word, starting with a letter, followed
1874 by letters, numbers, `-' or `_'.
1876 If REPLACE is a string, the tag will simply be appended to create the link.
1877 If the string contains \"%s\", the tag will be inserted there. If the string
1878 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1879 at that point (see the function `url-hexify-string'). If the string contains
1880 the specifier \"%(my-function)\", then the custom function `my-function' will
1881 be invoked: this function takes the tag as its only argument and must return
1882 a string.
1884 REPLACE may also be a function that will be called with the tag as the
1885 only argument to create the link, which should be returned as a string.
1887 See the manual for examples."
1888 :group 'org-link
1889 :type '(repeat
1890 (cons
1891 (string :tag "Protocol")
1892 (choice
1893 (string :tag "Format")
1894 (function)))))
1896 (defcustom org-descriptive-links t
1897 "Non-nil means Org will display descriptive links.
1898 E.g. [[http://orgmode.org][Org website]] will be displayed as
1899 \"Org Website\", hiding the link itself and just displaying its
1900 description. When set to nil, Org will display the full links
1901 literally.
1903 You can interactively set the value of this variable by calling
1904 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1905 :group 'org-link
1906 :type 'boolean)
1908 (defcustom org-link-file-path-type 'adaptive
1909 "How the path name in file links should be stored.
1910 Valid values are:
1912 relative Relative to the current directory, i.e. the directory of the file
1913 into which the link is being inserted.
1914 absolute Absolute path, if possible with ~ for home directory.
1915 noabbrev Absolute path, no abbreviation of home directory.
1916 adaptive Use relative path for files in the current directory and sub-
1917 directories of it. For other files, use an absolute path."
1918 :group 'org-link
1919 :type '(choice
1920 (const relative)
1921 (const absolute)
1922 (const noabbrev)
1923 (const adaptive)))
1925 (defvaralias 'org-activate-links 'org-highlight-links)
1926 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1927 "Types of links that should be highlighted in Org files.
1929 This is a list of symbols, each one of them leading to the
1930 highlighting of a certain link type.
1932 You can still open links that are not highlighted.
1934 In principle, it does not hurt to turn on highlighting for all
1935 link types. There may be a small gain when turning off unused
1936 link types. The types are:
1938 bracket The recommended [[link][description]] or [[link]] links with hiding.
1939 angle Links in angular brackets that may contain whitespace like
1940 <bbdb:Carsten Dominik>.
1941 plain Plain links in normal text, no whitespace, like http://google.com.
1942 radio Text that is matched by a radio target, see manual for details.
1943 tag Tag settings in a headline (link to tag search).
1944 date Time stamps (link to calendar).
1945 footnote Footnote labels.
1947 If you set this variable during an Emacs session, use `org-mode-restart'
1948 in the Org buffer so that the change takes effect."
1949 :group 'org-link
1950 :group 'org-appearance
1951 :type '(set :greedy t
1952 (const :tag "Double bracket links" bracket)
1953 (const :tag "Angular bracket links" angle)
1954 (const :tag "Plain text links" plain)
1955 (const :tag "Radio target matches" radio)
1956 (const :tag "Tags" tag)
1957 (const :tag "Timestamps" date)
1958 (const :tag "Footnotes" footnote)))
1960 (defcustom org-make-link-description-function nil
1961 "Function to use for generating link descriptions from links.
1962 When nil, the link location will be used. This function must take
1963 two parameters: the first one is the link, the second one is the
1964 description generated by `org-insert-link'. The function should
1965 return the description to use."
1966 :group 'org-link
1967 :type '(choice (const nil) (function)))
1969 (defgroup org-link-store nil
1970 "Options concerning storing links in Org mode."
1971 :tag "Org Store Link"
1972 :group 'org-link)
1974 (defcustom org-url-hexify-p t
1975 "When non-nil, hexify URL when creating a link."
1976 :type 'boolean
1977 :version "24.3"
1978 :group 'org-link-store)
1980 (defcustom org-email-link-description-format "Email %c: %.30s"
1981 "Format of the description part of a link to an email or usenet message.
1982 The following %-escapes will be replaced by corresponding information:
1984 %F full \"From\" field
1985 %f name, taken from \"From\" field, address if no name
1986 %T full \"To\" field
1987 %t first name in \"To\" field, address if no name
1988 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1989 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1990 %s subject
1991 %d date
1992 %m message-id.
1994 You may use normal field width specification between the % and the letter.
1995 This is for example useful to limit the length of the subject.
1997 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1998 :group 'org-link-store
1999 :type 'string)
2001 (defcustom org-from-is-user-regexp
2002 (let (r1 r2)
2003 (when (and user-mail-address (not (string= user-mail-address "")))
2004 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
2005 (when (and user-full-name (not (string= user-full-name "")))
2006 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
2007 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
2008 "Regexp matched against the \"From:\" header of an email or usenet message.
2009 It should match if the message is from the user him/herself."
2010 :group 'org-link-store
2011 :type 'regexp)
2013 (defcustom org-context-in-file-links t
2014 "Non-nil means file links from `org-store-link' contain context.
2015 \\<org-mode-map>
2016 A search string will be added to the file name with :: as separator
2017 and used to find the context when the link is activated by the command
2018 `org-open-at-point'. When this option is t, the entire active region
2019 will be placed in the search string of the file link. If set to a
2020 positive integer, only the first n lines of context will be stored.
2022 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2023 \\[org-store-link]')
2024 negates this setting for the duration of the command."
2025 :group 'org-link-store
2026 :type '(choice boolean integer))
2028 (defcustom org-keep-stored-link-after-insertion nil
2029 "Non-nil means keep link in list for entire session.
2030 \\<org-mode-map>
2031 The command `org-store-link' adds a link pointing to the current
2032 location to an internal list. These links accumulate during a session.
2033 The command `org-insert-link' can be used to insert links into any
2034 Org file (offering completion for all stored links).
2036 When this option is nil, every link which has been inserted once using
2037 `\\[org-insert-link]' will be removed from the list, to make completing the \
2038 unused
2039 links more efficient."
2040 :group 'org-link-store
2041 :type 'boolean)
2043 (defgroup org-link-follow nil
2044 "Options concerning following links in Org mode."
2045 :tag "Org Follow Link"
2046 :group 'org-link)
2048 (defcustom org-link-translation-function nil
2049 "Function to translate links with different syntax to Org syntax.
2050 This can be used to translate links created for example by the Planner
2051 or emacs-wiki packages to Org syntax.
2052 The function must accept two parameters, a TYPE containing the link
2053 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2054 which is everything after the link protocol. It should return a cons
2055 with possibly modified values of type and path.
2056 Org contains a function for this, so if you set this variable to
2057 `org-translate-link-from-planner', you should be able follow many
2058 links created by planner."
2059 :group 'org-link-follow
2060 :type '(choice (const nil) (function)))
2062 (defcustom org-follow-link-hook nil
2063 "Hook that is run after a link has been followed."
2064 :group 'org-link-follow
2065 :type 'hook)
2067 (defcustom org-tab-follows-link nil
2068 "Non-nil means on links TAB will follow the link.
2069 Needs to be set before org.el is loaded.
2070 This really should not be used, it does not make sense, and the
2071 implementation is bad."
2072 :group 'org-link-follow
2073 :type 'boolean)
2075 (defcustom org-return-follows-link nil
2076 "Non-nil means on links RET will follow the link.
2077 In tables, the special behavior of RET has precedence."
2078 :group 'org-link-follow
2079 :type 'boolean)
2081 (defcustom org-mouse-1-follows-link
2082 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2083 "Non-nil means mouse-1 on a link will follow the link.
2084 A longer mouse click will still set point. Needs to be set
2085 before org.el is loaded."
2086 :group 'org-link-follow
2087 :version "24.4"
2088 :package-version '(Org . "8.3")
2089 :type '(choice
2090 (const :tag "A double click follows the link" double)
2091 (const :tag "Unconditionally follow the link with mouse-1" t)
2092 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2094 (defcustom org-mark-ring-length 4
2095 "Number of different positions to be recorded in the ring.
2096 Changing this requires a restart of Emacs to work correctly."
2097 :group 'org-link-follow
2098 :type 'integer)
2100 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2101 "Non-nil means internal fuzzy links can only match headlines.
2103 When nil, the a fuzzy link may point to a target or a named
2104 construct in the document. When set to the special value
2105 `query-to-create', offer to create a new headline when none
2106 matched.
2108 Spaces and statistics cookies are ignored during heading searches."
2109 :group 'org-link-follow
2110 :version "24.1"
2111 :type '(choice
2112 (const :tag "Use fuzzy text search" nil)
2113 (const :tag "Match only exact headline" t)
2114 (const :tag "Match exact headline or query to create it"
2115 query-to-create))
2116 :safe #'symbolp)
2118 (defcustom org-link-frame-setup
2119 '((vm . vm-visit-folder-other-frame)
2120 (vm-imap . vm-visit-imap-folder-other-frame)
2121 (gnus . org-gnus-no-new-news)
2122 (file . find-file-other-window)
2123 (wl . wl-other-frame))
2124 "Setup the frame configuration for following links.
2125 When following a link with Emacs, it may often be useful to display
2126 this link in another window or frame. This variable can be used to
2127 set this up for the different types of links.
2128 For VM, use any of
2129 `vm-visit-folder'
2130 `vm-visit-folder-other-window'
2131 `vm-visit-folder-other-frame'
2132 For Gnus, use any of
2133 `gnus'
2134 `gnus-other-frame'
2135 `org-gnus-no-new-news'
2136 For FILE, use any of
2137 `find-file'
2138 `find-file-other-window'
2139 `find-file-other-frame'
2140 For Wanderlust use any of
2141 `wl'
2142 `wl-other-frame'
2143 For the calendar, use the variable `calendar-setup'.
2144 For BBDB, it is currently only possible to display the matches in
2145 another window."
2146 :group 'org-link-follow
2147 :type '(list
2148 (cons (const vm)
2149 (choice
2150 (const vm-visit-folder)
2151 (const vm-visit-folder-other-window)
2152 (const vm-visit-folder-other-frame)))
2153 (cons (const vm-imap)
2154 (choice
2155 (const vm-visit-imap-folder)
2156 (const vm-visit-imap-folder-other-window)
2157 (const vm-visit-imap-folder-other-frame)))
2158 (cons (const gnus)
2159 (choice
2160 (const gnus)
2161 (const gnus-other-frame)
2162 (const org-gnus-no-new-news)))
2163 (cons (const file)
2164 (choice
2165 (const find-file)
2166 (const find-file-other-window)
2167 (const find-file-other-frame)))
2168 (cons (const wl)
2169 (choice
2170 (const wl)
2171 (const wl-other-frame)))))
2173 (defcustom org-display-internal-link-with-indirect-buffer nil
2174 "Non-nil means use indirect buffer to display infile links.
2175 Activating internal links (from one location in a file to another location
2176 in the same file) normally just jumps to the location. When the link is
2177 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2178 is displayed in
2179 another window. When this option is set, the other window actually displays
2180 an indirect buffer clone of the current buffer, to avoid any visibility
2181 changes to the current buffer."
2182 :group 'org-link-follow
2183 :type 'boolean)
2185 (defcustom org-open-non-existing-files nil
2186 "Non-nil means `org-open-file' will open non-existing files.
2187 When nil, an error will be generated.
2188 This variable applies only to external applications because they
2189 might choke on non-existing files. If the link is to a file that
2190 will be opened in Emacs, the variable is ignored."
2191 :group 'org-link-follow
2192 :type 'boolean)
2194 (defcustom org-open-directory-means-index-dot-org nil
2195 "Non-nil means a link to a directory really means to index.org.
2196 When nil, following a directory link will run dired or open a finder/explorer
2197 window on that directory."
2198 :group 'org-link-follow
2199 :type 'boolean)
2201 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2202 "Non-nil means ask for confirmation before executing shell links.
2203 Shell links can be dangerous: just think about a link
2205 [[shell:rm -rf ~/*][Google Search]]
2207 This link would show up in your Org document as \"Google Search\",
2208 but really it would remove your entire home directory.
2209 Therefore we advise against setting this variable to nil.
2210 Just change it to `y-or-n-p' if you want to confirm with a
2211 single keystroke rather than having to type \"yes\"."
2212 :group 'org-link-follow
2213 :type '(choice
2214 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2215 (const :tag "with y-or-n (faster)" y-or-n-p)
2216 (const :tag "no confirmation (dangerous)" nil)))
2217 (put 'org-confirm-shell-link-function
2218 'safe-local-variable
2219 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2221 (defcustom org-confirm-shell-link-not-regexp ""
2222 "A regexp to skip confirmation for shell links."
2223 :group 'org-link-follow
2224 :version "24.1"
2225 :type 'regexp)
2227 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2228 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2229 Elisp links can be dangerous: just think about a link
2231 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2233 This link would show up in your Org document as \"Google Search\",
2234 but really it would remove your entire home directory.
2235 Therefore we advise against setting this variable to nil.
2236 Just change it to `y-or-n-p' if you want to confirm with a
2237 single keystroke rather than having to type \"yes\"."
2238 :group 'org-link-follow
2239 :type '(choice
2240 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2241 (const :tag "with y-or-n (faster)" y-or-n-p)
2242 (const :tag "no confirmation (dangerous)" nil)))
2243 (put 'org-confirm-shell-link-function
2244 'safe-local-variable
2245 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2247 (defcustom org-confirm-elisp-link-not-regexp ""
2248 "A regexp to skip confirmation for Elisp links."
2249 :group 'org-link-follow
2250 :version "24.1"
2251 :type 'regexp)
2253 (defconst org-file-apps-defaults-gnu
2254 '((remote . emacs)
2255 (system . mailcap)
2256 (t . mailcap))
2257 "Default file applications on a UNIX or GNU/Linux system.
2258 See `org-file-apps'.")
2260 (defconst org-file-apps-defaults-macosx
2261 '((remote . emacs)
2262 (system . "open %s")
2263 ("ps.gz" . "gv %s")
2264 ("eps.gz" . "gv %s")
2265 ("dvi" . "xdvi %s")
2266 ("fig" . "xfig %s")
2267 (t . "open %s"))
2268 "Default file applications on a macOS system.
2269 The system \"open\" is known as a default, but we use X11 applications
2270 for some files for which the OS does not have a good default.
2271 See `org-file-apps'.")
2273 (defconst org-file-apps-defaults-windowsnt
2274 (list '(remote . emacs)
2275 (cons 'system (lambda (file _path)
2276 (with-no-warnings (w32-shell-execute "open" file))))
2277 (cons t (lambda (file _path)
2278 (with-no-warnings (w32-shell-execute "open" file)))))
2279 "Default file applications on a Windows NT system.
2280 The system \"open\" is used for most files.
2281 See `org-file-apps'.")
2283 (defcustom org-file-apps
2284 '((auto-mode . emacs)
2285 ("\\.mm\\'" . default)
2286 ("\\.x?html?\\'" . default)
2287 ("\\.pdf\\'" . default))
2288 "External applications for opening `file:path' items in a document.
2289 \\<org-mode-map>\
2291 Org mode uses system defaults for different file types, but
2292 you can use this variable to set the application for a given file
2293 extension. The entries in this list are cons cells where the car identifies
2294 files and the cdr the corresponding command.
2296 Possible values for the file identifier are:
2298 \"string\" A string as a file identifier can be interpreted in different
2299 ways, depending on its contents:
2301 - Alphanumeric characters only:
2302 Match links with this file extension.
2303 Example: (\"pdf\" . \"evince %s\")
2304 to open PDFs with evince.
2306 - Regular expression: Match links where the
2307 filename matches the regexp. If you want to
2308 use groups here, use shy groups.
2310 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2311 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2312 to open *.html and *.xhtml with firefox.
2314 - Regular expression which contains (non-shy) groups:
2315 Match links where the whole link, including \"::\", and
2316 anything after that, matches the regexp.
2317 In a custom command string, %1, %2, etc. are replaced with
2318 the parts of the link that were matched by the groups.
2319 For backwards compatibility, if a command string is given
2320 that does not use any of the group matches, this case is
2321 handled identically to the second one (i.e. match against
2322 file name only).
2323 In a custom function, you can access the group matches with
2324 (match-string n link).
2326 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2327 \"evince -p %1 %s\")
2328 to open [[file:document.pdf::5]] with evince at page 5.
2330 `directory' Matches a directory
2331 `remote' Matches a remote file, accessible through tramp or efs.
2332 Remote files most likely should be visited through Emacs
2333 because external applications cannot handle such paths.
2334 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2335 so all files Emacs knows how to handle. Using this with
2336 command `emacs' will open most files in Emacs. Beware that this
2337 will also open html files inside Emacs, unless you add
2338 (\"html\" . default) to the list as well.
2339 `system' The system command to open files, like `open' on Windows
2340 and macOS, and mailcap under GNU/Linux. This is the command
2341 that will be selected if you call `org-open-at-point' with a
2342 double prefix argument (`\\[universal-argument] \
2343 \\[universal-argument] \\[org-open-at-point]').
2344 t Default for files not matched by any of the other options.
2346 Possible values for the command are:
2348 `emacs' The file will be visited by the current Emacs process.
2349 `default' Use the default application for this file type, which is the
2350 association for t in the list, most likely in the system-specific
2351 part. This can be used to overrule an unwanted setting in the
2352 system-specific variable.
2353 `system' Use the system command for opening files, like \"open\".
2354 This command is specified by the entry whose car is `system'.
2355 Most likely, the system-specific version of this variable
2356 does define this command, but you can overrule/replace it
2357 here.
2358 `mailcap' Use command specified in the mailcaps.
2359 string A command to be executed by a shell; %s will be replaced
2360 by the path to the file.
2361 function A Lisp function, which will be called with two arguments:
2362 the file path and the original link string, without the
2363 \"file:\" prefix.
2365 For more examples, see the system specific constants
2366 `org-file-apps-defaults-macosx'
2367 `org-file-apps-defaults-windowsnt'
2368 `org-file-apps-defaults-gnu'."
2369 :group 'org-link-follow
2370 :type '(repeat
2371 (cons (choice :value ""
2372 (string :tag "Extension")
2373 (const :tag "System command to open files" system)
2374 (const :tag "Default for unrecognized files" t)
2375 (const :tag "Remote file" remote)
2376 (const :tag "Links to a directory" directory)
2377 (const :tag "Any files that have Emacs modes"
2378 auto-mode))
2379 (choice :value ""
2380 (const :tag "Visit with Emacs" emacs)
2381 (const :tag "Use default" default)
2382 (const :tag "Use the system command" system)
2383 (string :tag "Command")
2384 (function :tag "Function")))))
2386 (defcustom org-doi-server-url "http://dx.doi.org/"
2387 "The URL of the DOI server."
2388 :type 'string
2389 :version "24.3"
2390 :group 'org-link-follow)
2392 (defgroup org-refile nil
2393 "Options concerning refiling entries in Org mode."
2394 :tag "Org Refile"
2395 :group 'org)
2397 (defcustom org-directory "~/org"
2398 "Directory with Org files.
2399 This is just a default location to look for Org files. There is no need
2400 at all to put your files into this directory. It is used in the
2401 following situations:
2403 1. When a capture template specifies a target file that is not an
2404 absolute path. The path will then be interpreted relative to
2405 `org-directory'
2406 2. When the value of variable `org-agenda-files' is a single file, any
2407 relative paths in this file will be taken as relative to
2408 `org-directory'."
2409 :group 'org-refile
2410 :group 'org-capture
2411 :type 'directory)
2413 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2414 "Default target for storing notes.
2415 Used as a fall back file for org-capture.el, for templates that
2416 do not specify a target file."
2417 :group 'org-refile
2418 :group 'org-capture
2419 :type 'file)
2421 (defcustom org-goto-interface 'outline
2422 "The default interface to be used for `org-goto'.
2423 Allowed values are:
2424 outline The interface shows an outline of the relevant file
2425 and the correct heading is found by moving through
2426 the outline or by searching with incremental search.
2427 outline-path-completion Headlines in the current buffer are offered via
2428 completion. This is the interface also used by
2429 the refile command."
2430 :group 'org-refile
2431 :type '(choice
2432 (const :tag "Outline" outline)
2433 (const :tag "Outline-path-completion" outline-path-completion)))
2435 (defcustom org-goto-max-level 5
2436 "Maximum target level when running `org-goto' with refile interface."
2437 :group 'org-refile
2438 :type 'integer)
2440 (defcustom org-reverse-note-order nil
2441 "Non-nil means store new notes at the beginning of a file or entry.
2442 When nil, new notes will be filed to the end of a file or entry.
2443 This can also be a list with cons cells of regular expressions that
2444 are matched against file names, and values."
2445 :group 'org-capture
2446 :group 'org-refile
2447 :type '(choice
2448 (const :tag "Reverse always" t)
2449 (const :tag "Reverse never" nil)
2450 (repeat :tag "By file name regexp"
2451 (cons regexp boolean))))
2453 (defcustom org-log-refile nil
2454 "Information to record when a task is refiled.
2456 Possible values are:
2458 nil Don't add anything
2459 time Add a time stamp to the task
2460 note Prompt for a note and add it with template `org-log-note-headings'
2462 This option can also be set with on a per-file-basis with
2464 #+STARTUP: nologrefile
2465 #+STARTUP: logrefile
2466 #+STARTUP: lognoterefile
2468 You can have local logging settings for a subtree by setting the LOGGING
2469 property to one or more of these keywords.
2471 When bulk-refiling from the agenda, the value `note' is forbidden and
2472 will temporarily be changed to `time'."
2473 :group 'org-refile
2474 :group 'org-progress
2475 :version "24.1"
2476 :type '(choice
2477 (const :tag "No logging" nil)
2478 (const :tag "Record timestamp" time)
2479 (const :tag "Record timestamp with note." note)))
2481 (defcustom org-refile-targets nil
2482 "Targets for refiling entries with `\\[org-refile]'.
2483 This is a list of cons cells. Each cell contains:
2484 - a specification of the files to be considered, either a list of files,
2485 or a symbol whose function or variable value will be used to retrieve
2486 a file name or a list of file names. If you use `org-agenda-files' for
2487 that, all agenda files will be scanned for targets. Nil means consider
2488 headings in the current buffer.
2489 - A specification of how to find candidate refile targets. This may be
2490 any of:
2491 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2492 This tag has to be present in all target headlines, inheritance will
2493 not be considered.
2494 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2495 todo keyword.
2496 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2497 headlines that are refiling targets.
2498 - a cons cell (:level . N). Any headline of level N is considered a target.
2499 Note that, when `org-odd-levels-only' is set, level corresponds to
2500 order in hierarchy, not to the number of stars.
2501 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2502 Note that, when `org-odd-levels-only' is set, level corresponds to
2503 order in hierarchy, not to the number of stars.
2505 Each element of this list generates a set of possible targets.
2506 The union of these sets is presented (with completion) to
2507 the user by `org-refile'.
2509 You can set the variable `org-refile-target-verify-function' to a function
2510 to verify each headline found by the simple criteria above.
2512 When this variable is nil, all top-level headlines in the current buffer
2513 are used, equivalent to the value `((nil . (:level . 1))'."
2514 :group 'org-refile
2515 :type '(repeat
2516 (cons
2517 (choice :value org-agenda-files
2518 (const :tag "All agenda files" org-agenda-files)
2519 (const :tag "Current buffer" nil)
2520 (function) (variable) (file))
2521 (choice :tag "Identify target headline by"
2522 (cons :tag "Specific tag" (const :value :tag) (string))
2523 (cons :tag "TODO keyword" (const :value :todo) (string))
2524 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2525 (cons :tag "Level number" (const :value :level) (integer))
2526 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2528 (defcustom org-refile-target-verify-function nil
2529 "Function to verify if the headline at point should be a refile target.
2530 The function will be called without arguments, with point at the
2531 beginning of the headline. It should return t and leave point
2532 where it is if the headline is a valid target for refiling.
2534 If the target should not be selected, the function must return nil.
2535 In addition to this, it may move point to a place from where the search
2536 should be continued. For example, the function may decide that the entire
2537 subtree of the current entry should be excluded and move point to the end
2538 of the subtree."
2539 :group 'org-refile
2540 :type '(choice
2541 (const nil)
2542 (function)))
2544 (defcustom org-refile-use-cache nil
2545 "Non-nil means cache refile targets to speed up the process.
2546 \\<org-mode-map>\
2547 The cache for a particular file will be updated automatically when
2548 the buffer has been killed, or when any of the marker used for flagging
2549 refile targets no longer points at a live buffer.
2550 If you have added new entries to a buffer that might themselves be targets,
2551 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2552 if you find that easier, \
2553 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2554 \\[org-refile]'."
2555 :group 'org-refile
2556 :version "24.1"
2557 :type 'boolean)
2559 (defcustom org-refile-use-outline-path nil
2560 "Non-nil means provide refile targets as paths.
2561 So a level 3 headline will be available as level1/level2/level3.
2563 When the value is `file', also include the file name (without directory)
2564 into the path. In this case, you can also stop the completion after
2565 the file name, to get entries inserted as top level in the file.
2567 When `full-file-path', include the full file path.
2569 When `buffer-name', use the buffer name."
2570 :group 'org-refile
2571 :type '(choice
2572 (const :tag "Not" nil)
2573 (const :tag "Yes" t)
2574 (const :tag "Start with file name" file)
2575 (const :tag "Start with full file path" full-file-path)
2576 (const :tag "Start with buffer name" buffer-name)))
2578 (defcustom org-outline-path-complete-in-steps t
2579 "Non-nil means complete the outline path in hierarchical steps.
2580 When Org uses the refile interface to select an outline path (see
2581 `org-refile-use-outline-path'), the completion of the path can be
2582 done in a single go, or it can be done in steps down the headline
2583 hierarchy. Going in steps is probably the best if you do not use
2584 a special completion package like `ido' or `icicles'. However,
2585 when using these packages, going in one step can be very fast,
2586 while still showing the whole path to the entry."
2587 :group 'org-refile
2588 :type 'boolean)
2590 (defcustom org-refile-allow-creating-parent-nodes nil
2591 "Non-nil means allow the creation of new nodes as refile targets.
2592 New nodes are then created by adding \"/new node name\" to the completion
2593 of an existing node. When the value of this variable is `confirm',
2594 new node creation must be confirmed by the user (recommended).
2595 When nil, the completion must match an existing entry.
2597 Note that, if the new heading is not seen by the criteria
2598 listed in `org-refile-targets', multiple instances of the same
2599 heading would be created by trying again to file under the new
2600 heading."
2601 :group 'org-refile
2602 :type '(choice
2603 (const :tag "Never" nil)
2604 (const :tag "Always" t)
2605 (const :tag "Prompt for confirmation" confirm)))
2607 (defcustom org-refile-active-region-within-subtree nil
2608 "Non-nil means also refile active region within a subtree.
2610 By default `org-refile' doesn't allow refiling regions if they
2611 don't contain a set of subtrees, but it might be convenient to
2612 do so sometimes: in that case, the first line of the region is
2613 converted to a headline before refiling."
2614 :group 'org-refile
2615 :version "24.1"
2616 :type 'boolean)
2618 (defgroup org-todo nil
2619 "Options concerning TODO items in Org mode."
2620 :tag "Org TODO"
2621 :group 'org)
2623 (defgroup org-progress nil
2624 "Options concerning Progress logging in Org mode."
2625 :tag "Org Progress"
2626 :group 'org-time)
2628 (defvar org-todo-interpretation-widgets
2629 '((:tag "Sequence (cycling hits every state)" sequence)
2630 (:tag "Type (cycling directly to DONE)" type))
2631 "The available interpretation symbols for customizing `org-todo-keywords'.
2632 Interested libraries should add to this list.")
2634 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2635 "List of TODO entry keyword sequences and their interpretation.
2636 \\<org-mode-map>This is a list of sequences.
2638 Each sequence starts with a symbol, either `sequence' or `type',
2639 indicating if the keywords should be interpreted as a sequence of
2640 action steps, or as different types of TODO items. The first
2641 keywords are states requiring action - these states will select a headline
2642 for inclusion into the global TODO list Org produces. If one of the
2643 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2644 signify that no further action is necessary. If \"|\" is not found,
2645 the last keyword is treated as the only DONE state of the sequence.
2647 The command `\\[org-todo]' cycles an entry through these states, and one
2648 additional state where no keyword is present. For details about this
2649 cycling, see the manual.
2651 TODO keywords and interpretation can also be set on a per-file basis with
2652 the special #+SEQ_TODO and #+TYP_TODO lines.
2654 Each keyword can optionally specify a character for fast state selection
2655 \(in combination with the variable `org-use-fast-todo-selection')
2656 and specifiers for state change logging, using the same syntax that
2657 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2658 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2659 indicates to record a time stamp each time this state is selected.
2661 Each keyword may also specify if a timestamp or a note should be
2662 recorded when entering or leaving the state, by adding additional
2663 characters in the parenthesis after the keyword. This looks like this:
2664 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2665 record only the time of the state change. With X and Y being either
2666 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2667 Y when leaving the state if and only if the *target* state does not
2668 define X. You may omit any of the fast-selection key or X or /Y,
2669 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2671 For backward compatibility, this variable may also be just a list
2672 of keywords. In this case the interpretation (sequence or type) will be
2673 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2674 :group 'org-todo
2675 :group 'org-keywords
2676 :type '(choice
2677 (repeat :tag "Old syntax, just keywords"
2678 (string :tag "Keyword"))
2679 (repeat :tag "New syntax"
2680 (cons
2681 (choice
2682 :tag "Interpretation"
2683 ;;Quick and dirty way to see
2684 ;;`org-todo-interpretations'. This takes the
2685 ;;place of item arguments
2686 :convert-widget
2687 (lambda (widget)
2688 (widget-put widget
2689 :args (mapcar
2690 (lambda (x)
2691 (widget-convert
2692 (cons 'const x)))
2693 org-todo-interpretation-widgets))
2694 widget))
2695 (repeat
2696 (string :tag "Keyword"))))))
2698 (defvar-local org-todo-keywords-1 nil
2699 "All TODO and DONE keywords active in a buffer.")
2700 (defvar org-todo-keywords-for-agenda nil)
2701 (defvar org-done-keywords-for-agenda nil)
2702 (defvar org-todo-keyword-alist-for-agenda nil)
2703 (defvar org-tag-alist-for-agenda nil
2704 "Alist of all tags from all agenda files.")
2705 (defvar org-tag-groups-alist-for-agenda nil
2706 "Alist of all groups tags from all current agenda files.")
2707 (defvar-local org-tag-groups-alist nil)
2708 (defvar org-agenda-contributing-files nil)
2709 (defvar-local org-current-tag-alist nil
2710 "Alist of all tag groups in current buffer.
2711 This variable takes into consideration `org-tag-alist',
2712 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2713 (defvar-local org-not-done-keywords nil)
2714 (defvar-local org-done-keywords nil)
2715 (defvar-local org-todo-heads nil)
2716 (defvar-local org-todo-sets nil)
2717 (defvar-local org-todo-log-states nil)
2718 (defvar-local org-todo-kwd-alist nil)
2719 (defvar-local org-todo-key-alist nil)
2720 (defvar-local org-todo-key-trigger nil)
2722 (defcustom org-todo-interpretation 'sequence
2723 "Controls how TODO keywords are interpreted.
2724 This variable is in principle obsolete and is only used for
2725 backward compatibility, if the interpretation of todo keywords is
2726 not given already in `org-todo-keywords'. See that variable for
2727 more information."
2728 :group 'org-todo
2729 :group 'org-keywords
2730 :type '(choice (const sequence)
2731 (const type)))
2733 (defcustom org-use-fast-todo-selection t
2734 "\\<org-mode-map>\
2735 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2736 This variable describes if and under what circumstances the cycling
2737 mechanism for TODO keywords will be replaced by a single-key, direct
2738 selection scheme.
2740 When nil, fast selection is never used.
2742 When the symbol `prefix', it will be used when `org-todo' is called
2743 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2744 in an Org buffer, and
2745 `\\[universal-argument] t' in an agenda buffer.
2747 When t, fast selection is used by default. In this case, the prefix
2748 argument forces cycling instead.
2750 In all cases, the special interface is only used if access keys have
2751 actually been assigned by the user, i.e. if keywords in the configuration
2752 are followed by a letter in parenthesis, like TODO(t)."
2753 :group 'org-todo
2754 :type '(choice
2755 (const :tag "Never" nil)
2756 (const :tag "By default" t)
2757 (const :tag "Only with C-u C-c C-t" prefix)))
2759 (defcustom org-provide-todo-statistics t
2760 "Non-nil means update todo statistics after insert and toggle.
2761 ALL-HEADLINES means update todo statistics by including headlines
2762 with no TODO keyword as well, counting them as not done.
2763 A list of TODO keywords means the same, but skip keywords that are
2764 not in this list.
2765 When set to a list of two lists, the first list contains keywords
2766 to consider as TODO keywords, the second list contains keywords
2767 to consider as DONE keywords.
2769 When this is set, todo statistics is updated in the parent of the
2770 current entry each time a todo state is changed."
2771 :group 'org-todo
2772 :type '(choice
2773 (const :tag "Yes, only for TODO entries" t)
2774 (const :tag "Yes, including all entries" all-headlines)
2775 (repeat :tag "Yes, for TODOs in this list"
2776 (string :tag "TODO keyword"))
2777 (list :tag "Yes, for TODOs and DONEs in these lists"
2778 (repeat (string :tag "TODO keyword"))
2779 (repeat (string :tag "DONE keyword")))
2780 (other :tag "No TODO statistics" nil)))
2782 (defcustom org-hierarchical-todo-statistics t
2783 "Non-nil means TODO statistics covers just direct children.
2784 When nil, all entries in the subtree are considered.
2785 This has only an effect if `org-provide-todo-statistics' is set.
2786 To set this to nil for only a single subtree, use a COOKIE_DATA
2787 property and include the word \"recursive\" into the value."
2788 :group 'org-todo
2789 :type 'boolean)
2791 (defcustom org-after-todo-state-change-hook nil
2792 "Hook which is run after the state of a TODO item was changed.
2793 The new state (a string with a TODO keyword, or nil) is available in the
2794 Lisp variable `org-state'."
2795 :group 'org-todo
2796 :type 'hook)
2798 (defvar org-blocker-hook nil
2799 "Hook for functions that are allowed to block a state change.
2801 Functions in this hook should not modify the buffer.
2802 Each function gets as its single argument a property list,
2803 see `org-trigger-hook' for more information about this list.
2805 If any of the functions in this hook returns nil, the state change
2806 is blocked.")
2808 (defvar org-trigger-hook nil
2809 "Hook for functions that are triggered by a state change.
2811 Each function gets as its single argument a property list with at
2812 least the following elements:
2814 (:type type-of-change :position pos-at-entry-start
2815 :from old-state :to new-state)
2817 Depending on the type, more properties may be present.
2819 This mechanism is currently implemented for:
2821 TODO state changes
2822 ------------------
2823 :type todo-state-change
2824 :from previous state (keyword as a string), or nil, or a symbol
2825 `todo' or `done', to indicate the general type of state.
2826 :to new state, like in :from")
2828 (defcustom org-enforce-todo-dependencies nil
2829 "Non-nil means undone TODO entries will block switching the parent to DONE.
2830 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2831 be blocked if any prior sibling is not yet done.
2832 Finally, if the parent is blocked because of ordered siblings of its own,
2833 the child will also be blocked."
2834 :set (lambda (var val)
2835 (set var val)
2836 (if val
2837 (add-hook 'org-blocker-hook
2838 'org-block-todo-from-children-or-siblings-or-parent)
2839 (remove-hook 'org-blocker-hook
2840 'org-block-todo-from-children-or-siblings-or-parent)))
2841 :group 'org-todo
2842 :type 'boolean)
2844 (defcustom org-enforce-todo-checkbox-dependencies nil
2845 "Non-nil means unchecked boxes will block switching the parent to DONE.
2846 When this is nil, checkboxes have no influence on switching TODO states.
2847 When non-nil, you first need to check off all check boxes before the TODO
2848 entry can be switched to DONE.
2849 This variable needs to be set before org.el is loaded, and you need to
2850 restart Emacs after a change to make the change effective. The only way
2851 to change is while Emacs is running is through the customize interface."
2852 :set (lambda (var val)
2853 (set var val)
2854 (if val
2855 (add-hook 'org-blocker-hook
2856 'org-block-todo-from-checkboxes)
2857 (remove-hook 'org-blocker-hook
2858 'org-block-todo-from-checkboxes)))
2859 :group 'org-todo
2860 :type 'boolean)
2862 (defcustom org-treat-insert-todo-heading-as-state-change nil
2863 "Non-nil means inserting a TODO heading is treated as state change.
2864 So when the command `\\[org-insert-todo-heading]' is used, state change
2865 logging will apply if appropriate. When nil, the new TODO item will
2866 be inserted directly, and no logging will take place."
2867 :group 'org-todo
2868 :type 'boolean)
2870 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2871 "Non-nil means switching TODO states with S-cursor counts as state change.
2872 This is the default behavior. However, setting this to nil allows a
2873 convenient way to select a TODO state and bypass any logging associated
2874 with that."
2875 :group 'org-todo
2876 :type 'boolean)
2878 (defcustom org-todo-state-tags-triggers nil
2879 "Tag changes that should be triggered by TODO state changes.
2880 This is a list. Each entry is
2882 (state-change (tag . flag) .......)
2884 State-change can be a string with a state, and empty string to indicate the
2885 state that has no TODO keyword, or it can be one of the symbols `todo'
2886 or `done', meaning any not-done or done state, respectively."
2887 :group 'org-todo
2888 :group 'org-tags
2889 :type '(repeat
2890 (cons (choice :tag "When changing to"
2891 (const :tag "Not-done state" todo)
2892 (const :tag "Done state" done)
2893 (string :tag "State"))
2894 (repeat
2895 (cons :tag "Tag action"
2896 (string :tag "Tag")
2897 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2899 (defcustom org-log-done nil
2900 "Information to record when a task moves to the DONE state.
2902 Possible values are:
2904 nil Don't add anything, just change the keyword
2905 time Add a time stamp to the task
2906 note Prompt for a note and add it with template `org-log-note-headings'
2908 This option can also be set with on a per-file-basis with
2910 #+STARTUP: nologdone
2911 #+STARTUP: logdone
2912 #+STARTUP: lognotedone
2914 You can have local logging settings for a subtree by setting the LOGGING
2915 property to one or more of these keywords."
2916 :group 'org-todo
2917 :group 'org-progress
2918 :type '(choice
2919 (const :tag "No logging" nil)
2920 (const :tag "Record CLOSED timestamp" time)
2921 (const :tag "Record CLOSED timestamp with note." note)))
2923 ;; Normalize old uses of org-log-done.
2924 (cond
2925 ((eq org-log-done t) (setq org-log-done 'time))
2926 ((and (listp org-log-done) (memq 'done org-log-done))
2927 (setq org-log-done 'note)))
2929 (defcustom org-log-reschedule nil
2930 "Information to record when the scheduling date of a tasks is modified.
2932 Possible values are:
2934 nil Don't add anything, just change the date
2935 time Add a time stamp to the task
2936 note Prompt for a note and add it with template `org-log-note-headings'
2938 This option can also be set with on a per-file-basis with
2940 #+STARTUP: nologreschedule
2941 #+STARTUP: logreschedule
2942 #+STARTUP: lognotereschedule"
2943 :group 'org-todo
2944 :group 'org-progress
2945 :type '(choice
2946 (const :tag "No logging" nil)
2947 (const :tag "Record timestamp" time)
2948 (const :tag "Record timestamp with note." note)))
2950 (defcustom org-log-redeadline nil
2951 "Information to record when the deadline date of a tasks is modified.
2953 Possible values are:
2955 nil Don't add anything, just change the date
2956 time Add a time stamp to the task
2957 note Prompt for a note and add it with template `org-log-note-headings'
2959 This option can also be set with on a per-file-basis with
2961 #+STARTUP: nologredeadline
2962 #+STARTUP: logredeadline
2963 #+STARTUP: lognoteredeadline
2965 You can have local logging settings for a subtree by setting the LOGGING
2966 property to one or more of these keywords."
2967 :group 'org-todo
2968 :group 'org-progress
2969 :type '(choice
2970 (const :tag "No logging" nil)
2971 (const :tag "Record timestamp" time)
2972 (const :tag "Record timestamp with note." note)))
2974 (defcustom org-log-note-clock-out nil
2975 "Non-nil means record a note when clocking out of an item.
2976 This can also be configured on a per-file basis by adding one of
2977 the following lines anywhere in the buffer:
2979 #+STARTUP: lognoteclock-out
2980 #+STARTUP: nolognoteclock-out"
2981 :group 'org-todo
2982 :group 'org-progress
2983 :type 'boolean)
2985 (defcustom org-log-done-with-time t
2986 "Non-nil means the CLOSED time stamp will contain date and time.
2987 When nil, only the date will be recorded."
2988 :group 'org-progress
2989 :type 'boolean)
2991 (defcustom org-log-note-headings
2992 '((done . "CLOSING NOTE %t")
2993 (state . "State %-12s from %-12S %t")
2994 (note . "Note taken on %t")
2995 (reschedule . "Rescheduled from %S on %t")
2996 (delschedule . "Not scheduled, was %S on %t")
2997 (redeadline . "New deadline from %S on %t")
2998 (deldeadline . "Removed deadline, was %S on %t")
2999 (refile . "Refiled on %t")
3000 (clock-out . ""))
3001 "Headings for notes added to entries.
3003 The value is an alist, with the car being a symbol indicating the
3004 note context, and the cdr is the heading to be used. The heading
3005 may also be the empty string. The following placeholders can be
3006 used:
3008 %t a time stamp.
3009 %T an active time stamp instead the default inactive one
3010 %d a short-format time stamp.
3011 %D an active short-format time stamp.
3012 %s the new TODO state or time stamp (inactive), in double quotes.
3013 %S the old TODO state or time stamp (inactive), in double quotes.
3014 %u the user name.
3015 %U full user name.
3017 In fact, it is not a good idea to change the `state' entry,
3018 because Agenda Log mode depends on the format of these entries."
3019 :group 'org-todo
3020 :group 'org-progress
3021 :type '(list :greedy t
3022 (cons (const :tag "Heading when closing an item" done) string)
3023 (cons (const :tag
3024 "Heading when changing todo state (todo sequence only)"
3025 state) string)
3026 (cons (const :tag "Heading when just taking a note" note) string)
3027 (cons (const :tag "Heading when rescheduling" reschedule) string)
3028 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3029 (cons (const :tag "Heading when changing deadline" redeadline) string)
3030 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3031 (cons (const :tag "Heading when refiling" refile) string)
3032 (cons (const :tag "Heading when clocking out" clock-out) string)))
3034 (unless (assq 'note org-log-note-headings)
3035 (push '(note . "%t") org-log-note-headings))
3037 (defcustom org-log-into-drawer nil
3038 "Non-nil means insert state change notes and time stamps into a drawer.
3039 When nil, state changes notes will be inserted after the headline and
3040 any scheduling and clock lines, but not inside a drawer.
3042 The value of this variable should be the name of the drawer to use.
3043 LOGBOOK is proposed as the default drawer for this purpose, you can
3044 also set this to a string to define the drawer of your choice.
3046 A value of t is also allowed, representing \"LOGBOOK\".
3048 A value of t or nil can also be set with on a per-file-basis with
3050 #+STARTUP: logdrawer
3051 #+STARTUP: nologdrawer
3053 If this variable is set, `org-log-state-notes-insert-after-drawers'
3054 will be ignored.
3056 You can set the property LOG_INTO_DRAWER to overrule this setting for
3057 a subtree.
3059 Do not check directly this variable in a Lisp program. Call
3060 function `org-log-into-drawer' instead."
3061 :group 'org-todo
3062 :group 'org-progress
3063 :type '(choice
3064 (const :tag "Not into a drawer" nil)
3065 (const :tag "LOGBOOK" t)
3066 (string :tag "Other")))
3068 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3070 (defun org-log-into-drawer ()
3071 "Name of the log drawer, as a string, or nil.
3072 This is the value of `org-log-into-drawer'. However, if the
3073 current entry has or inherits a LOG_INTO_DRAWER property, it will
3074 be used instead of the default value."
3075 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3076 (cond ((equal p "nil") nil)
3077 ((equal p "t") "LOGBOOK")
3078 ((stringp p) p)
3079 (p "LOGBOOK")
3080 ((stringp org-log-into-drawer) org-log-into-drawer)
3081 (org-log-into-drawer "LOGBOOK"))))
3083 (defcustom org-log-state-notes-insert-after-drawers nil
3084 "Non-nil means insert state change notes after any drawers in entry.
3085 Only the drawers that *immediately* follow the headline and the
3086 deadline/scheduled line are skipped.
3087 When nil, insert notes right after the heading and perhaps the line
3088 with deadline/scheduling if present.
3090 This variable will have no effect if `org-log-into-drawer' is
3091 set."
3092 :group 'org-todo
3093 :group 'org-progress
3094 :type 'boolean)
3096 (defcustom org-log-states-order-reversed t
3097 "Non-nil means the latest state note will be directly after heading.
3098 When nil, the state change notes will be ordered according to time.
3100 This option can also be set with on a per-file-basis with
3102 #+STARTUP: logstatesreversed
3103 #+STARTUP: nologstatesreversed"
3104 :group 'org-todo
3105 :group 'org-progress
3106 :type 'boolean)
3108 (defcustom org-todo-repeat-to-state nil
3109 "The TODO state to which a repeater should return the repeating task.
3110 By default this is the first task in a TODO sequence, or the previous state
3111 in a TODO_TYP set. But you can specify another task here.
3112 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3113 :group 'org-todo
3114 :version "24.1"
3115 :type '(choice (const :tag "Head of sequence" nil)
3116 (string :tag "Specific state")))
3118 (defcustom org-log-repeat 'time
3119 "Non-nil means record moving through the DONE state when triggering repeat.
3120 An auto-repeating task is immediately switched back to TODO when
3121 marked DONE. If you are not logging state changes (by adding \"@\"
3122 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3123 record a closing note, there will be no record of the task moving
3124 through DONE. This variable forces taking a note anyway.
3126 nil Don't force a record
3127 time Record a time stamp
3128 note Prompt for a note and add it with template `org-log-note-headings'
3130 This option can also be set with on a per-file-basis with
3132 #+STARTUP: nologrepeat
3133 #+STARTUP: logrepeat
3134 #+STARTUP: lognoterepeat
3136 You can have local logging settings for a subtree by setting the LOGGING
3137 property to one or more of these keywords."
3138 :group 'org-todo
3139 :group 'org-progress
3140 :type '(choice
3141 (const :tag "Don't force a record" nil)
3142 (const :tag "Force recording the DONE state" time)
3143 (const :tag "Force recording a note with the DONE state" note)))
3146 (defgroup org-priorities nil
3147 "Priorities in Org mode."
3148 :tag "Org Priorities"
3149 :group 'org-todo)
3151 (defcustom org-enable-priority-commands t
3152 "Non-nil means priority commands are active.
3153 When nil, these commands will be disabled, so that you never accidentally
3154 set a priority."
3155 :group 'org-priorities
3156 :type 'boolean)
3158 (defcustom org-highest-priority ?A
3159 "The highest priority of TODO items. A character like ?A, ?B etc.
3160 Must have a smaller ASCII number than `org-lowest-priority'."
3161 :group 'org-priorities
3162 :type 'character)
3164 (defcustom org-lowest-priority ?C
3165 "The lowest priority of TODO items. A character like ?A, ?B etc.
3166 Must have a larger ASCII number than `org-highest-priority'."
3167 :group 'org-priorities
3168 :type 'character)
3170 (defcustom org-default-priority ?B
3171 "The default priority of TODO items.
3172 This is the priority an item gets if no explicit priority is given.
3173 When starting to cycle on an empty priority the first step in the cycle
3174 depends on `org-priority-start-cycle-with-default'. The resulting first
3175 step priority must not exceed the range from `org-highest-priority' to
3176 `org-lowest-priority' which means that `org-default-priority' has to be
3177 in this range exclusive or inclusive the range boundaries. Else the
3178 first step refuses to set the default and the second will fall back
3179 to (depending on the command used) the highest or lowest priority."
3180 :group 'org-priorities
3181 :type 'character)
3183 (defcustom org-priority-start-cycle-with-default t
3184 "Non-nil means start with default priority when starting to cycle.
3185 When this is nil, the first step in the cycle will be (depending on the
3186 command used) one higher or lower than the default priority.
3187 See also `org-default-priority'."
3188 :group 'org-priorities
3189 :type 'boolean)
3191 (defcustom org-get-priority-function nil
3192 "Function to extract the priority from a string.
3193 The string is normally the headline. If this is nil Org computes the
3194 priority from the priority cookie like [#A] in the headline. It returns
3195 an integer, increasing by 1000 for each priority level.
3196 The user can set a different function here, which should take a string
3197 as an argument and return the numeric priority."
3198 :group 'org-priorities
3199 :version "24.1"
3200 :type '(choice
3201 (const nil)
3202 (function)))
3204 (defgroup org-time nil
3205 "Options concerning time stamps and deadlines in Org mode."
3206 :tag "Org Time"
3207 :group 'org)
3209 (defcustom org-time-stamp-rounding-minutes '(0 5)
3210 "Number of minutes to round time stamps to.
3211 \\<org-mode-map>\
3212 These are two values, the first applies when first creating a time stamp.
3213 The second applies when changing it with the commands `S-up' and `S-down'.
3214 When changing the time stamp, this means that it will change in steps
3215 of N minutes, as given by the second value.
3217 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3218 numbers should be factors of 60, so for example 5, 10, 15.
3220 When this is larger than 1, you can still force an exact time stamp by using
3221 a double prefix argument to a time stamp command like \
3222 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3223 and by using a prefix arg to `S-up/down' to specify the exact number
3224 of minutes to shift."
3225 :group 'org-time
3226 :get (lambda (var) ; Make sure both elements are there
3227 (if (integerp (default-value var))
3228 (list (default-value var) 5)
3229 (default-value var)))
3230 :type '(list
3231 (integer :tag "when inserting times")
3232 (integer :tag "when modifying times")))
3234 ;; Normalize old customizations of this variable.
3235 (when (integerp org-time-stamp-rounding-minutes)
3236 (setq org-time-stamp-rounding-minutes
3237 (list org-time-stamp-rounding-minutes
3238 org-time-stamp-rounding-minutes)))
3240 (defcustom org-display-custom-times nil
3241 "Non-nil means overlay custom formats over all time stamps.
3242 The formats are defined through the variable `org-time-stamp-custom-formats'.
3243 To turn this on on a per-file basis, insert anywhere in the file:
3244 #+STARTUP: customtime"
3245 :group 'org-time
3246 :set 'set-default
3247 :type 'sexp)
3248 (make-variable-buffer-local 'org-display-custom-times)
3250 (defcustom org-time-stamp-custom-formats
3251 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3252 "Custom formats for time stamps. See `format-time-string' for the syntax.
3253 These are overlaid over the default ISO format if the variable
3254 `org-display-custom-times' is set. Time like %H:%M should be at the
3255 end of the second format. The custom formats are also honored by export
3256 commands, if custom time display is turned on at the time of export."
3257 :group 'org-time
3258 :type 'sexp)
3260 (defun org-time-stamp-format (&optional long inactive)
3261 "Get the right format for a time string."
3262 (let ((f (if long (cdr org-time-stamp-formats)
3263 (car org-time-stamp-formats))))
3264 (if inactive
3265 (concat "[" (substring f 1 -1) "]")
3266 f)))
3268 (defcustom org-deadline-warning-days 14
3269 "Number of days before expiration during which a deadline becomes active.
3270 This variable governs the display in sparse trees and in the agenda.
3271 When 0 or negative, it means use this number (the absolute value of it)
3272 even if a deadline has a different individual lead time specified.
3274 Custom commands can set this variable in the options section."
3275 :group 'org-time
3276 :group 'org-agenda-daily/weekly
3277 :type 'integer)
3279 (defcustom org-scheduled-delay-days 0
3280 "Number of days before a scheduled item becomes active.
3281 This variable governs the display in sparse trees and in the agenda.
3282 The default value (i.e. 0) means: don't delay scheduled item.
3283 When negative, it means use this number (the absolute value of it)
3284 even if a scheduled item has a different individual delay time
3285 specified.
3287 Custom commands can set this variable in the options section."
3288 :group 'org-time
3289 :group 'org-agenda-daily/weekly
3290 :version "24.4"
3291 :package-version '(Org . "8.0")
3292 :type 'integer)
3294 (defcustom org-read-date-prefer-future t
3295 "Non-nil means assume future for incomplete date input from user.
3296 This affects the following situations:
3297 1. The user gives a month but not a year.
3298 For example, if it is April and you enter \"feb 2\", this will be read
3299 as Feb 2, *next* year. \"May 5\", however, will be this year.
3300 2. The user gives a day, but no month.
3301 For example, if today is the 15th, and you enter \"3\", Org will read
3302 this as the third of *next* month. However, if you enter \"17\",
3303 it will be considered as *this* month.
3305 If you set this variable to the symbol `time', then also the following
3306 will work:
3308 3. If the user gives a time.
3309 If the time is before now, it will be interpreted as tomorrow.
3311 Currently none of this works for ISO week specifications.
3313 When this option is nil, the current day, month and year will always be
3314 used as defaults.
3316 See also `org-agenda-jump-prefer-future'."
3317 :group 'org-time
3318 :type '(choice
3319 (const :tag "Never" nil)
3320 (const :tag "Check month and day" t)
3321 (const :tag "Check month, day, and time" time)))
3323 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3324 "Should the agenda jump command prefer the future for incomplete dates?
3325 The default is to do the same as configured in `org-read-date-prefer-future'.
3326 But you can also set a deviating value here.
3327 This may t or nil, or the symbol `org-read-date-prefer-future'."
3328 :group 'org-agenda
3329 :group 'org-time
3330 :version "24.1"
3331 :type '(choice
3332 (const :tag "Use org-read-date-prefer-future"
3333 org-read-date-prefer-future)
3334 (const :tag "Never" nil)
3335 (const :tag "Always" t)))
3337 (defcustom org-read-date-force-compatible-dates t
3338 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3340 Depending on the system Emacs is running on, certain dates cannot
3341 be represented with the type used internally to represent time.
3342 Dates between 1970-1-1 and 2038-1-1 can always be represented
3343 correctly. Some systems allow for earlier dates, some for later,
3344 some for both. One way to find out it to insert any date into an
3345 Org buffer, putting the cursor on the year and hitting S-up and
3346 S-down to test the range.
3348 When this variable is set to t, the date/time prompt will not let
3349 you specify dates outside the 1970-2037 range, so it is certain that
3350 these dates will work in whatever version of Emacs you are
3351 running, and also that you can move a file from one Emacs implementation
3352 to another. WHenever Org is forcing the year for you, it will display
3353 a message and beep.
3355 When this variable is nil, Org will check if the date is
3356 representable in the specific Emacs implementation you are using.
3357 If not, it will force a year, usually the current year, and beep
3358 to remind you. Currently this setting is not recommended because
3359 the likelihood that you will open your Org files in an Emacs that
3360 has limited date range is not negligible.
3362 A workaround for this problem is to use diary sexp dates for time
3363 stamps outside of this range."
3364 :group 'org-time
3365 :version "24.1"
3366 :type 'boolean)
3368 (defcustom org-read-date-display-live t
3369 "Non-nil means display current interpretation of date prompt live.
3370 This display will be in an overlay, in the minibuffer."
3371 :group 'org-time
3372 :type 'boolean)
3374 (defcustom org-read-date-popup-calendar t
3375 "Non-nil means pop up a calendar when prompting for a date.
3376 In the calendar, the date can be selected with mouse-1. However, the
3377 minibuffer will also be active, and you can simply enter the date as well.
3378 When nil, only the minibuffer will be available."
3379 :group 'org-time
3380 :type 'boolean)
3381 (defvaralias 'org-popup-calendar-for-date-prompt
3382 'org-read-date-popup-calendar)
3384 (defcustom org-extend-today-until 0
3385 "The hour when your day really ends. Must be an integer.
3386 This has influence for the following applications:
3387 - When switching the agenda to \"today\". It it is still earlier than
3388 the time given here, the day recognized as TODAY is actually yesterday.
3389 - When a date is read from the user and it is still before the time given
3390 here, the current date and time will be assumed to be yesterday, 23:59.
3391 Also, timestamps inserted in capture templates follow this rule.
3393 IMPORTANT: This is a feature whose implementation is and likely will
3394 remain incomplete. Really, it is only here because past midnight seems to
3395 be the favorite working time of John Wiegley :-)"
3396 :group 'org-time
3397 :type 'integer)
3399 (defcustom org-use-effective-time nil
3400 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3401 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3402 \"effective time\" of any timestamps between midnight and 8am will be
3403 23:59 of the previous day."
3404 :group 'org-time
3405 :version "24.1"
3406 :type 'boolean)
3408 (defcustom org-use-last-clock-out-time-as-effective-time nil
3409 "When non-nil, use the last clock out time for `org-todo'.
3410 Note that this option has precedence over the combined use of
3411 `org-use-effective-time' and `org-extend-today-until'."
3412 :group 'org-time
3413 :version "24.4"
3414 :package-version '(Org . "8.0")
3415 :type 'boolean)
3417 (defcustom org-edit-timestamp-down-means-later nil
3418 "Non-nil means S-down will increase the time in a time stamp.
3419 When nil, S-up will increase."
3420 :group 'org-time
3421 :type 'boolean)
3423 (defcustom org-calendar-follow-timestamp-change t
3424 "Non-nil means make the calendar window follow timestamp changes.
3425 When a timestamp is modified and the calendar window is visible, it will be
3426 moved to the new date."
3427 :group 'org-time
3428 :type 'boolean)
3430 (defgroup org-tags nil
3431 "Options concerning tags in Org mode."
3432 :tag "Org Tags"
3433 :group 'org)
3435 (defcustom org-tag-alist nil
3436 "Default tags available in Org files.
3438 The value of this variable is an alist. Associations either:
3440 (TAG)
3441 (TAG . SELECT)
3442 (SPECIAL)
3444 where TAG is a tag as a string, SELECT is character, used to
3445 select that tag through the fast tag selection interface, and
3446 SPECIAL is one of the following keywords: `:startgroup',
3447 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3448 `:newline'. These keywords are used to define a hierarchy of
3449 tags. See manual for details.
3451 When this variable is nil, Org mode bases tag input on what is
3452 already in the buffer. The value can be overridden locally by
3453 using a TAGS keyword, e.g.,
3455 #+TAGS: tag1 tag2
3457 See also `org-tag-persistent-alist' to sidestep this behavior."
3458 :group 'org-tags
3459 :type '(repeat
3460 (choice
3461 (cons :tag "Tag with key"
3462 (string :tag "Tag name")
3463 (character :tag "Access char"))
3464 (list :tag "Tag" (string :tag "Tag name"))
3465 (const :tag "Start radio group" (:startgroup))
3466 (const :tag "Start tag group, non distinct" (:startgrouptag))
3467 (const :tag "Group tags delimiter" (:grouptags))
3468 (const :tag "End radio group" (:endgroup))
3469 (const :tag "End tag group, non distinct" (:endgrouptag))
3470 (const :tag "New line" (:newline)))))
3472 (defcustom org-tag-persistent-alist nil
3473 "Tags always available in Org files.
3475 The value of this variable is an alist. Associations either:
3477 (TAG)
3478 (TAG . SELECT)
3479 (SPECIAL)
3481 where TAG is a tag as a string, SELECT is a character, used to
3482 select that tag through the fast tag selection interface, and
3483 SPECIAL is one of the following keywords: `:startgroup',
3484 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3485 `:newline'. These keywords are used to define a hierarchy of
3486 tags. See manual for details.
3488 Unlike to `org-tag-alist', tags defined in this variable do not
3489 depend on a local TAGS keyword. Instead, to disable these tags
3490 on a per-file basis, insert anywhere in the file:
3492 #+STARTUP: noptag"
3493 :group 'org-tags
3494 :type '(repeat
3495 (choice
3496 (cons :tag "Tag with key"
3497 (string :tag "Tag name")
3498 (character :tag "Access char"))
3499 (list :tag "Tag" (string :tag "Tag name"))
3500 (const :tag "Start radio group" (:startgroup))
3501 (const :tag "Start tag group, non distinct" (:startgrouptag))
3502 (const :tag "Group tags delimiter" (:grouptags))
3503 (const :tag "End radio group" (:endgroup))
3504 (const :tag "End tag group, non distinct" (:endgrouptag))
3505 (const :tag "New line" (:newline)))))
3507 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3508 "If non-nil, always offer completion for all tags of all agenda files.
3509 Instead of customizing this variable directly, you might want to
3510 set it locally for capture buffers, because there no list of
3511 tags in that file can be created dynamically (there are none).
3513 (add-hook \\='org-capture-mode-hook
3514 (lambda ()
3515 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3516 :group 'org-tags
3517 :version "24.1"
3518 :type 'boolean)
3520 (defvar org-file-tags nil
3521 "List of tags that can be inherited by all entries in the file.
3522 The tags will be inherited if the variable `org-use-tag-inheritance'
3523 says they should be.
3524 This variable is populated from #+FILETAGS lines.")
3526 (defcustom org-use-fast-tag-selection 'auto
3527 "Non-nil means use fast tag selection scheme.
3528 This is a special interface to select and deselect tags with single keys.
3529 When nil, fast selection is never used.
3530 When the symbol `auto', fast selection is used if and only if selection
3531 characters for tags have been configured, either through the variable
3532 `org-tag-alist' or through a #+TAGS line in the buffer.
3533 When t, fast selection is always used and selection keys are assigned
3534 automatically if necessary."
3535 :group 'org-tags
3536 :type '(choice
3537 (const :tag "Always" t)
3538 (const :tag "Never" nil)
3539 (const :tag "When selection characters are configured" auto)))
3541 (defcustom org-fast-tag-selection-single-key nil
3542 "Non-nil means fast tag selection exits after first change.
3543 When nil, you have to press RET to exit it.
3544 During fast tag selection, you can toggle this flag with `C-c'.
3545 This variable can also have the value `expert'. In this case, the window
3546 displaying the tags menu is not even shown, until you press C-c again."
3547 :group 'org-tags
3548 :type '(choice
3549 (const :tag "No" nil)
3550 (const :tag "Yes" t)
3551 (const :tag "Expert" expert)))
3553 (defvar org-fast-tag-selection-include-todo nil
3554 "Non-nil means fast tags selection interface will also offer TODO states.
3555 This is an undocumented feature, you should not rely on it.")
3557 (defcustom org-tags-column -77
3558 "The column to which tags should be indented in a headline.
3559 If this number is positive, it specifies the column. If it is negative,
3560 it means that the tags should be flushright to that column. For example,
3561 -80 works well for a normal 80 character screen.
3562 When 0, place tags directly after headline text, with only one space in
3563 between."
3564 :group 'org-tags
3565 :type 'integer)
3567 (defcustom org-auto-align-tags t
3568 "Non-nil keeps tags aligned when modifying headlines.
3569 Some operations (i.e. demoting) change the length of a headline and
3570 therefore shift the tags around. With this option turned on, after
3571 each such operation the tags are again aligned to `org-tags-column'."
3572 :group 'org-tags
3573 :type 'boolean)
3575 (defcustom org-use-tag-inheritance t
3576 "Non-nil means tags in levels apply also for sublevels.
3577 When nil, only the tags directly given in a specific line apply there.
3578 This may also be a list of tags that should be inherited, or a regexp that
3579 matches tags that should be inherited. Additional control is possible
3580 with the variable `org-tags-exclude-from-inheritance' which gives an
3581 explicit list of tags to be excluded from inheritance, even if the value of
3582 `org-use-tag-inheritance' would select it for inheritance.
3584 If this option is t, a match early-on in a tree can lead to a large
3585 number of matches in the subtree when constructing the agenda or creating
3586 a sparse tree. If you only want to see the first match in a tree during
3587 a search, check out the variable `org-tags-match-list-sublevels'."
3588 :group 'org-tags
3589 :type '(choice
3590 (const :tag "Not" nil)
3591 (const :tag "Always" t)
3592 (repeat :tag "Specific tags" (string :tag "Tag"))
3593 (regexp :tag "Tags matched by regexp")))
3595 (defcustom org-tags-exclude-from-inheritance nil
3596 "List of tags that should never be inherited.
3597 This is a way to exclude a few tags from inheritance. For way to do
3598 the opposite, to actively allow inheritance for selected tags,
3599 see the variable `org-use-tag-inheritance'."
3600 :group 'org-tags
3601 :type '(repeat (string :tag "Tag")))
3603 (defun org-tag-inherit-p (tag)
3604 "Check if TAG is one that should be inherited."
3605 (cond
3606 ((member tag org-tags-exclude-from-inheritance) nil)
3607 ((eq org-use-tag-inheritance t) t)
3608 ((not org-use-tag-inheritance) nil)
3609 ((stringp org-use-tag-inheritance)
3610 (string-match org-use-tag-inheritance tag))
3611 ((listp org-use-tag-inheritance)
3612 (member tag org-use-tag-inheritance))
3613 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3615 (defcustom org-tags-match-list-sublevels t
3616 "Non-nil means list also sublevels of headlines matching a search.
3617 This variable applies to tags/property searches, and also to stuck
3618 projects because this search is based on a tags match as well.
3620 When set to the symbol `indented', sublevels are indented with
3621 leading dots.
3623 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3624 the sublevels of a headline matching a tag search often also match
3625 the same search. Listing all of them can create very long lists.
3626 Setting this variable to nil causes subtrees of a match to be skipped.
3628 This variable is semi-obsolete and probably should always be true. It
3629 is better to limit inheritance to certain tags using the variables
3630 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3631 :group 'org-tags
3632 :type '(choice
3633 (const :tag "No, don't list them" nil)
3634 (const :tag "Yes, do list them" t)
3635 (const :tag "List them, indented with leading dots" indented)))
3637 (defcustom org-tags-sort-function nil
3638 "When set, tags are sorted using this function as a comparator."
3639 :group 'org-tags
3640 :type '(choice
3641 (const :tag "No sorting" nil)
3642 (const :tag "Alphabetical" string<)
3643 (const :tag "Reverse alphabetical" string>)
3644 (function :tag "Custom function" nil)))
3646 (defvar org-tags-history nil
3647 "History of minibuffer reads for tags.")
3648 (defvar org-last-tags-completion-table nil
3649 "The last used completion table for tags.")
3650 (defvar org-after-tags-change-hook nil
3651 "Hook that is run after the tags in a line have changed.")
3653 (defgroup org-properties nil
3654 "Options concerning properties in Org mode."
3655 :tag "Org Properties"
3656 :group 'org)
3658 (defcustom org-property-format "%-10s %s"
3659 "How property key/value pairs should be formatted by `indent-line'.
3660 When `indent-line' hits a property definition, it will format the line
3661 according to this format, mainly to make sure that the values are
3662 lined-up with respect to each other."
3663 :group 'org-properties
3664 :type 'string)
3666 (defcustom org-properties-postprocess-alist nil
3667 "Alist of properties and functions to adjust inserted values.
3668 Elements of this alist must be of the form
3670 ([string] [function])
3672 where [string] must be a property name and [function] must be a
3673 lambda expression: this lambda expression must take one argument,
3674 the value to adjust, and return the new value as a string.
3676 For example, this element will allow the property \"Remaining\"
3677 to be updated wrt the relation between the \"Effort\" property
3678 and the clock summary:
3680 ((\"Remaining\" (lambda(value)
3681 (let ((clocksum (org-clock-sum-current-item))
3682 (effort (org-duration-to-minutes
3683 (org-entry-get (point) \"Effort\"))))
3684 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3685 :group 'org-properties
3686 :version "24.1"
3687 :type '(alist :key-type (string :tag "Property")
3688 :value-type (function :tag "Function")))
3690 (defcustom org-use-property-inheritance nil
3691 "Non-nil means properties apply also for sublevels.
3693 This setting is chiefly used during property searches. Turning it on can
3694 cause significant overhead when doing a search, which is why it is not
3695 on by default.
3697 When nil, only the properties directly given in the current entry count.
3698 When t, every property is inherited. The value may also be a list of
3699 properties that should have inheritance, or a regular expression matching
3700 properties that should be inherited.
3702 However, note that some special properties use inheritance under special
3703 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3704 and the properties ending in \"_ALL\" when they are used as descriptor
3705 for valid values of a property.
3707 Note for programmers:
3708 When querying an entry with `org-entry-get', you can control if inheritance
3709 should be used. By default, `org-entry-get' looks only at the local
3710 properties. You can request inheritance by setting the inherit argument
3711 to t (to force inheritance) or to `selective' (to respect the setting
3712 in this variable)."
3713 :group 'org-properties
3714 :type '(choice
3715 (const :tag "Not" nil)
3716 (const :tag "Always" t)
3717 (repeat :tag "Specific properties" (string :tag "Property"))
3718 (regexp :tag "Properties matched by regexp")))
3720 (defun org-property-inherit-p (property)
3721 "Return a non-nil value if PROPERTY should be inherited."
3722 (cond
3723 ((eq org-use-property-inheritance t) t)
3724 ((not org-use-property-inheritance) nil)
3725 ((stringp org-use-property-inheritance)
3726 (string-match org-use-property-inheritance property))
3727 ((listp org-use-property-inheritance)
3728 (member-ignore-case property org-use-property-inheritance))
3729 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3731 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3732 "The default column format, if no other format has been defined.
3733 This variable can be set on the per-file basis by inserting a line
3735 #+COLUMNS: %25ITEM ....."
3736 :group 'org-properties
3737 :type 'string)
3739 (defcustom org-columns-ellipses ".."
3740 "The ellipses to be used when a field in column view is truncated.
3741 When this is the empty string, as many characters as possible are shown,
3742 but then there will be no visual indication that the field has been truncated.
3743 When this is a string of length N, the last N characters of a truncated
3744 field are replaced by this string. If the column is narrower than the
3745 ellipses string, only part of the ellipses string will be shown."
3746 :group 'org-properties
3747 :type 'string)
3749 (defconst org-global-properties-fixed
3750 '(("VISIBILITY_ALL" . "folded children content all")
3751 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3752 "List of property/value pairs that can be inherited by any entry.
3754 These are fixed values, for the preset properties. The user variable
3755 that can be used to add to this list is `org-global-properties'.
3757 The entries in this list are cons cells where the car is a property
3758 name and cdr is a string with the value. If the value represents
3759 multiple items like an \"_ALL\" property, separate the items by
3760 spaces.")
3762 (defcustom org-global-properties nil
3763 "List of property/value pairs that can be inherited by any entry.
3765 This list will be combined with the constant `org-global-properties-fixed'.
3767 The entries in this list are cons cells where the car is a property
3768 name and cdr is a string with the value.
3770 You can set buffer-local values for the same purpose in the variable
3771 `org-file-properties' this by adding lines like
3773 #+PROPERTY: NAME VALUE"
3774 :group 'org-properties
3775 :type '(repeat
3776 (cons (string :tag "Property")
3777 (string :tag "Value"))))
3779 (defvar-local org-file-properties nil
3780 "List of property/value pairs that can be inherited by any entry.
3781 Valid for the current buffer.
3782 This variable is populated from #+PROPERTY lines.")
3784 (defgroup org-agenda nil
3785 "Options concerning agenda views in Org mode."
3786 :tag "Org Agenda"
3787 :group 'org)
3789 (defvar-local org-category nil
3790 "Variable used by org files to set a category for agenda display.
3791 Such files should use a file variable to set it, for example
3793 # -*- mode: org; org-category: \"ELisp\"
3795 or contain a special line
3797 #+CATEGORY: ELisp
3799 If the file does not specify a category, then file's base name
3800 is used instead.")
3801 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3803 (defcustom org-agenda-files nil
3804 "The files to be used for agenda display.
3806 If an entry is a directory, all files in that directory that are matched
3807 by `org-agenda-file-regexp' will be part of the file list.
3809 If the value of the variable is not a list but a single file name, then
3810 the list of agenda files is actually stored and maintained in that file,
3811 one agenda file per line. In this file paths can be given relative to
3812 `org-directory'. Tilde expansion and environment variable substitution
3813 are also made.
3815 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3816 and removed with `\\[org-remove-file]'."
3817 :group 'org-agenda
3818 :type '(choice
3819 (repeat :tag "List of files and directories" file)
3820 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3822 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3823 "Regular expression to match files for `org-agenda-files'.
3824 If any element in the list in that variable contains a directory instead
3825 of a normal file, all files in that directory that are matched by this
3826 regular expression will be included."
3827 :group 'org-agenda
3828 :type 'regexp)
3830 (defcustom org-agenda-text-search-extra-files nil
3831 "List of extra files to be searched by text search commands.
3832 These files will be searched in addition to the agenda files by the
3833 commands `org-search-view' (`\\[org-agenda] s') \
3834 and `org-occur-in-agenda-files'.
3835 Note that these files will only be searched for text search commands,
3836 not for the other agenda views like todo lists, tag searches or the weekly
3837 agenda. This variable is intended to list notes and possibly archive files
3838 that should also be searched by these two commands.
3839 In fact, if the first element in the list is the symbol `agenda-archives',
3840 then all archive files of all agenda files will be added to the search
3841 scope."
3842 :group 'org-agenda
3843 :type '(set :greedy t
3844 (const :tag "Agenda Archives" agenda-archives)
3845 (repeat :inline t (file))))
3847 (defvaralias 'org-agenda-multi-occur-extra-files
3848 'org-agenda-text-search-extra-files)
3850 (defcustom org-agenda-skip-unavailable-files nil
3851 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3852 A nil value means to remove them, after a query, from the list."
3853 :group 'org-agenda
3854 :type 'boolean)
3856 (defcustom org-calendar-to-agenda-key [?c]
3857 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3858 The command `org-calendar-goto-agenda' will be bound to this key. The
3859 default is the character `c' because then `c' can be used to switch back and
3860 forth between agenda and calendar."
3861 :group 'org-agenda
3862 :type 'sexp)
3864 (defcustom org-calendar-insert-diary-entry-key [?i]
3865 "The key to be installed in `calendar-mode-map' for adding diary entries.
3866 This option is irrelevant until `org-agenda-diary-file' has been configured
3867 to point to an Org file. When that is the case, the command
3868 `org-agenda-diary-entry' will be bound to the key given here, by default
3869 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3870 if you want to continue doing this, you need to change this to a different
3871 key."
3872 :group 'org-agenda
3873 :type 'sexp)
3875 (defcustom org-agenda-diary-file 'diary-file
3876 "File to which to add new entries with the `i' key in agenda and calendar.
3877 When this is the symbol `diary-file', the functionality in the Emacs
3878 calendar will be used to add entries to the `diary-file'. But when this
3879 points to a file, `org-agenda-diary-entry' will be used instead."
3880 :group 'org-agenda
3881 :type '(choice
3882 (const :tag "The standard Emacs diary file" diary-file)
3883 (file :tag "Special Org file diary entries")))
3885 (eval-after-load "calendar"
3886 '(progn
3887 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3888 'org-calendar-goto-agenda)
3889 (add-hook 'calendar-mode-hook
3890 (lambda ()
3891 (unless (eq org-agenda-diary-file 'diary-file)
3892 (define-key calendar-mode-map
3893 org-calendar-insert-diary-entry-key
3894 'org-agenda-diary-entry))))))
3896 (defgroup org-latex nil
3897 "Options for embedding LaTeX code into Org mode."
3898 :tag "Org LaTeX"
3899 :group 'org)
3901 (defcustom org-format-latex-options
3902 '(:foreground default :background default :scale 1.0
3903 :html-foreground "Black" :html-background "Transparent"
3904 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3905 "Options for creating images from LaTeX fragments.
3906 This is a property list with the following properties:
3907 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3908 `default' means use the foreground of the default face.
3909 `auto' means use the foreground from the text face.
3910 :background the background color, or \"Transparent\".
3911 `default' means use the background of the default face.
3912 `auto' means use the background from the text face.
3913 :scale a scaling factor for the size of the images, to get more pixels
3914 :html-foreground, :html-background, :html-scale
3915 the same numbers for HTML export.
3916 :matchers a list indicating which matchers should be used to
3917 find LaTeX fragments. Valid members of this list are:
3918 \"begin\" find environments
3919 \"$1\" find single characters surrounded by $.$
3920 \"$\" find math expressions surrounded by $...$
3921 \"$$\" find math expressions surrounded by $$....$$
3922 \"\\(\" find math expressions surrounded by \\(...\\)
3923 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3924 :group 'org-latex
3925 :type 'plist)
3927 (defcustom org-format-latex-signal-error t
3928 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3929 When nil, just push out a message."
3930 :group 'org-latex
3931 :version "24.1"
3932 :type 'boolean)
3934 (defcustom org-latex-to-mathml-jar-file nil
3935 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3936 Use this to specify additional executable file say a jar file.
3938 When using MathToWeb as the converter, specify the full-path to
3939 your mathtoweb.jar file."
3940 :group 'org-latex
3941 :version "24.1"
3942 :type '(choice
3943 (const :tag "None" nil)
3944 (file :tag "JAR file" :must-match t)))
3946 (defcustom org-latex-to-mathml-convert-command nil
3947 "Command to convert LaTeX fragments to MathML.
3948 Replace format-specifiers in the command as noted below and use
3949 `shell-command' to convert LaTeX to MathML.
3950 %j: Executable file in fully expanded form as specified by
3951 `org-latex-to-mathml-jar-file'.
3952 %I: Input LaTeX file in fully expanded form.
3953 %i: The latex fragment to be converted.
3954 %o: Output MathML file.
3956 This command is used by `org-create-math-formula'.
3958 When using MathToWeb as the converter, set this option to
3959 \"java -jar %j -unicode -force -df %o %I\".
3961 When using LaTeXML set this option to
3962 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3963 :group 'org-latex
3964 :version "24.1"
3965 :type '(choice
3966 (const :tag "None" nil)
3967 (string :tag "\nShell command")))
3969 (defcustom org-preview-latex-default-process 'dvipng
3970 "The default process to convert LaTeX fragments to image files.
3971 All available processes and theirs documents can be found in
3972 `org-preview-latex-process-alist', which see."
3973 :group 'org-latex
3974 :version "26.1"
3975 :package-version '(Org . "9.0")
3976 :type 'symbol)
3978 (defcustom org-preview-latex-process-alist
3979 '((dvipng
3980 :programs ("latex" "dvipng")
3981 :description "dvi > png"
3982 :message "you need to install the programs: latex and dvipng."
3983 :image-input-type "dvi"
3984 :image-output-type "png"
3985 :image-size-adjust (1.0 . 1.0)
3986 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3987 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3988 (dvisvgm
3989 :programs ("latex" "dvisvgm")
3990 :description "dvi > svg"
3991 :message "you need to install the programs: latex and dvisvgm."
3992 :use-xcolor t
3993 :image-input-type "dvi"
3994 :image-output-type "svg"
3995 :image-size-adjust (1.7 . 1.5)
3996 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3997 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3998 (imagemagick
3999 :programs ("latex" "convert")
4000 :description "pdf > png"
4001 :message "you need to install the programs: latex and imagemagick."
4002 :use-xcolor t
4003 :image-input-type "pdf"
4004 :image-output-type "png"
4005 :image-size-adjust (1.0 . 1.0)
4006 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4007 :image-converter
4008 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4009 "Definitions of external processes for LaTeX previewing.
4010 Org mode can use some external commands to generate TeX snippet's images for
4011 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4012 `org-create-formula-image' how to call them.
4014 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4015 PROPERTIES accepts the following attributes:
4017 :programs list of strings, required programs.
4018 :description string, describe the process.
4019 :message string, message it when required programs cannot be found.
4020 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4021 :image-output-type string, output file type of image converter (e.g., \"png\").
4022 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4023 deal with background and foreground color of image.
4024 Otherwise, dvipng style background and foreground color
4025 format are generated. You may then refer to them in
4026 command options with \"%F\" and \"%B\".
4027 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4028 image size showed in buffer and the cdr element is for
4029 HTML file. This option is only useful for process
4030 developers, users should use variable
4031 `org-format-latex-options' instead.
4032 :post-clean list of strings, files matched are to be cleaned up once
4033 the image is generated. When nil, the files with \".dvi\",
4034 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4035 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4036 be cleaned up.
4037 :latex-header list of strings, the LaTeX header of the snippet file.
4038 When nil, the fallback value is used instead, which is
4039 controlled by `org-format-latex-header',
4040 `org-latex-default-packages-alist' and
4041 `org-latex-packages-alist', which see.
4042 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4043 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4044 replaced with values defined below.
4045 :image-converter list of image converter commands strings. Each of them is
4046 given to the shell and supports any of the following
4047 place-holders defined below.
4049 Place-holders used by `:image-converter' and `:latex-compiler':
4051 %f input file name
4052 %b base name of input file
4053 %o base directory of input file
4054 %O absolute output file name
4056 Place-holders only used by `:image-converter':
4058 %F foreground of image
4059 %B background of image
4060 %D dpi, which is used to adjust image size by some processing commands.
4061 %S the image size scale ratio, which is used to adjust image size by some
4062 processing commands."
4063 :group 'org-latex
4064 :version "26.1"
4065 :package-version '(Org . "9.0")
4066 :type '(alist :tag "LaTeX to image backends"
4067 :value-type (plist)))
4069 (defcustom org-preview-latex-image-directory "ltximg/"
4070 "Path to store latex preview images.
4071 A relative path here creates many directories relative to the
4072 processed org files paths. An absolute path puts all preview
4073 images at the same place."
4074 :group 'org-latex
4075 :version "26.1"
4076 :package-version '(Org . "9.0")
4077 :type 'string)
4079 (defun org-format-latex-mathml-available-p ()
4080 "Return t if `org-latex-to-mathml-convert-command' is usable."
4081 (save-match-data
4082 (when (and (boundp 'org-latex-to-mathml-convert-command)
4083 org-latex-to-mathml-convert-command)
4084 (let ((executable (car (split-string
4085 org-latex-to-mathml-convert-command))))
4086 (when (executable-find executable)
4087 (if (string-match
4088 "%j" org-latex-to-mathml-convert-command)
4089 (file-readable-p org-latex-to-mathml-jar-file)
4090 t))))))
4092 (defcustom org-format-latex-header "\\documentclass{article}
4093 \\usepackage[usenames]{color}
4094 \[PACKAGES]
4095 \[DEFAULT-PACKAGES]
4096 \\pagestyle{empty} % do not remove
4097 % The settings below are copied from fullpage.sty
4098 \\setlength{\\textwidth}{\\paperwidth}
4099 \\addtolength{\\textwidth}{-3cm}
4100 \\setlength{\\oddsidemargin}{1.5cm}
4101 \\addtolength{\\oddsidemargin}{-2.54cm}
4102 \\setlength{\\evensidemargin}{\\oddsidemargin}
4103 \\setlength{\\textheight}{\\paperheight}
4104 \\addtolength{\\textheight}{-\\headheight}
4105 \\addtolength{\\textheight}{-\\headsep}
4106 \\addtolength{\\textheight}{-\\footskip}
4107 \\addtolength{\\textheight}{-3cm}
4108 \\setlength{\\topmargin}{1.5cm}
4109 \\addtolength{\\topmargin}{-2.54cm}"
4110 "The document header used for processing LaTeX fragments.
4111 It is imperative that this header make sure that no page number
4112 appears on the page. The package defined in the variables
4113 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4114 will either replace the placeholder \"[PACKAGES]\" in this
4115 header, or they will be appended."
4116 :group 'org-latex
4117 :type 'string)
4119 (defun org-set-packages-alist (var val)
4120 "Set the packages alist and make sure it has 3 elements per entry."
4121 (set var (mapcar (lambda (x)
4122 (if (and (consp x) (= (length x) 2))
4123 (list (car x) (nth 1 x) t)
4125 val)))
4127 (defun org-get-packages-alist (var)
4128 "Get the packages alist and make sure it has 3 elements per entry."
4129 (mapcar (lambda (x)
4130 (if (and (consp x) (= (length x) 2))
4131 (list (car x) (nth 1 x) t)
4133 (default-value var)))
4135 (defcustom org-latex-default-packages-alist
4136 '(("AUTO" "inputenc" t ("pdflatex"))
4137 ("T1" "fontenc" t ("pdflatex"))
4138 ("" "graphicx" t)
4139 ("" "grffile" t)
4140 ("" "longtable" nil)
4141 ("" "wrapfig" nil)
4142 ("" "rotating" nil)
4143 ("normalem" "ulem" t)
4144 ("" "amsmath" t)
4145 ("" "textcomp" t)
4146 ("" "amssymb" t)
4147 ("" "capt-of" nil)
4148 ("" "hyperref" nil))
4149 "Alist of default packages to be inserted in the header.
4151 Change this only if one of the packages here causes an
4152 incompatibility with another package you are using.
4154 The packages in this list are needed by one part or another of
4155 Org mode to function properly:
4157 - inputenc, fontenc: for basic font and character selection
4158 - graphicx: for including images
4159 - grffile: allow periods and spaces in graphics file names
4160 - longtable: For multipage tables
4161 - wrapfig: for figure placement
4162 - rotating: for sideways figures and tables
4163 - ulem: for underline and strike-through
4164 - amsmath: for subscript and superscript and math environments
4165 - textcomp, amssymb: for various symbols used
4166 for interpreting the entities in `org-entities'. You can skip
4167 some of these packages if you don't use any of their symbols.
4168 - capt-of: for captions outside of floats
4169 - hyperref: for cross references
4171 Therefore you should not modify this variable unless you know
4172 what you are doing. The one reason to change it anyway is that
4173 you might be loading some other package that conflicts with one
4174 of the default packages. Each element is either a cell or
4175 a string.
4177 A cell is of the format
4179 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4181 If SNIPPET-FLAG is non-nil, the package also needs to be included
4182 when compiling LaTeX snippets into images for inclusion into
4183 non-LaTeX output. COMPILERS is a list of compilers that should
4184 include the package, see `org-latex-compiler'. If the document
4185 compiler is not in the list, and the list is non-nil, the package
4186 will not be inserted in the final document.
4188 A string will be inserted as-is in the header of the document."
4189 :group 'org-latex
4190 :group 'org-export-latex
4191 :set 'org-set-packages-alist
4192 :get 'org-get-packages-alist
4193 :version "26.1"
4194 :package-version '(Org . "8.3")
4195 :type '(repeat
4196 (choice
4197 (list :tag "options/package pair"
4198 (string :tag "options")
4199 (string :tag "package")
4200 (boolean :tag "Snippet"))
4201 (string :tag "A line of LaTeX"))))
4203 (defcustom org-latex-packages-alist nil
4204 "Alist of packages to be inserted in every LaTeX header.
4206 These will be inserted after `org-latex-default-packages-alist'.
4207 Each element is either a cell or a string.
4209 A cell is of the format:
4211 (\"options\" \"package\" SNIPPET-FLAG)
4213 SNIPPET-FLAG, when non-nil, indicates that this package is also
4214 needed when turning LaTeX snippets into images for inclusion into
4215 non-LaTeX output.
4217 A string will be inserted as-is in the header of the document.
4219 Make sure that you only list packages here which:
4221 - you want in every file;
4222 - do not conflict with the setup in `org-format-latex-header';
4223 - do not conflict with the default packages in
4224 `org-latex-default-packages-alist'."
4225 :group 'org-latex
4226 :group 'org-export-latex
4227 :set 'org-set-packages-alist
4228 :get 'org-get-packages-alist
4229 :type '(repeat
4230 (choice
4231 (list :tag "options/package pair"
4232 (string :tag "options")
4233 (string :tag "package")
4234 (boolean :tag "Snippet"))
4235 (string :tag "A line of LaTeX"))))
4237 (defgroup org-appearance nil
4238 "Settings for Org mode appearance."
4239 :tag "Org Appearance"
4240 :group 'org)
4242 (defcustom org-level-color-stars-only nil
4243 "Non-nil means fontify only the stars in each headline.
4244 When nil, the entire headline is fontified.
4245 Changing it requires restart of `font-lock-mode' to become effective
4246 also in regions already fontified."
4247 :group 'org-appearance
4248 :type 'boolean)
4250 (defcustom org-hide-leading-stars nil
4251 "Non-nil means hide the first N-1 stars in a headline.
4252 This works by using the face `org-hide' for these stars. This
4253 face is white for a light background, and black for a dark
4254 background. You may have to customize the face `org-hide' to
4255 make this work.
4256 Changing it requires restart of `font-lock-mode' to become effective
4257 also in regions already fontified.
4258 You may also set this on a per-file basis by adding one of the following
4259 lines to the buffer:
4261 #+STARTUP: hidestars
4262 #+STARTUP: showstars"
4263 :group 'org-appearance
4264 :type 'boolean)
4266 (defcustom org-hidden-keywords nil
4267 "List of symbols corresponding to keywords to be hidden the org buffer.
4268 For example, a value \\='(title) for this list will make the document's title
4269 appear in the buffer without the initial #+TITLE: keyword."
4270 :group 'org-appearance
4271 :version "24.1"
4272 :type '(set (const :tag "#+AUTHOR" author)
4273 (const :tag "#+DATE" date)
4274 (const :tag "#+EMAIL" email)
4275 (const :tag "#+TITLE" title)))
4277 (defcustom org-custom-properties nil
4278 "List of properties (as strings) with a special meaning.
4279 The default use of these custom properties is to let the user
4280 hide them with `org-toggle-custom-properties-visibility'."
4281 :group 'org-properties
4282 :group 'org-appearance
4283 :version "24.3"
4284 :type '(repeat (string :tag "Property Name")))
4286 (defcustom org-fontify-done-headline nil
4287 "Non-nil means change the face of a headline if it is marked DONE.
4288 Normally, only the TODO/DONE keyword indicates the state of a headline.
4289 When this is non-nil, the headline after the keyword is set to the
4290 `org-headline-done' as an additional indication."
4291 :group 'org-appearance
4292 :type 'boolean)
4294 (defcustom org-fontify-emphasized-text t
4295 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4296 Changing this variable requires a restart of Emacs to take effect."
4297 :group 'org-appearance
4298 :type 'boolean)
4300 (defcustom org-fontify-whole-heading-line nil
4301 "Non-nil means fontify the whole line for headings.
4302 This is useful when setting a background color for the
4303 org-level-* faces."
4304 :group 'org-appearance
4305 :type 'boolean)
4307 (defcustom org-highlight-latex-and-related nil
4308 "Non-nil means highlight LaTeX related syntax in the buffer.
4309 When non nil, the value should be a list containing any of the
4310 following symbols:
4311 `latex' Highlight LaTeX snippets and environments.
4312 `script' Highlight subscript and superscript.
4313 `entities' Highlight entities."
4314 :group 'org-appearance
4315 :version "24.4"
4316 :package-version '(Org . "8.0")
4317 :type '(choice
4318 (const :tag "No highlighting" nil)
4319 (set :greedy t :tag "Highlight"
4320 (const :tag "LaTeX snippets and environments" latex)
4321 (const :tag "Subscript and superscript" script)
4322 (const :tag "Entities" entities))))
4324 (defcustom org-hide-emphasis-markers nil
4325 "Non-nil mean font-lock should hide the emphasis marker characters."
4326 :group 'org-appearance
4327 :type 'boolean)
4329 (defcustom org-hide-macro-markers nil
4330 "Non-nil mean font-lock should hide the brackets marking macro calls."
4331 :group 'org-appearance
4332 :type 'boolean)
4334 (defcustom org-pretty-entities nil
4335 "Non-nil means show entities as UTF8 characters.
4336 When nil, the \\name form remains in the buffer."
4337 :group 'org-appearance
4338 :version "24.1"
4339 :type 'boolean)
4341 (defcustom org-pretty-entities-include-sub-superscripts t
4342 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4343 :group 'org-appearance
4344 :version "24.1"
4345 :type 'boolean)
4347 (defvar org-emph-re nil
4348 "Regular expression for matching emphasis.
4349 After a match, the match groups contain these elements:
4350 0 The match of the full regular expression, including the characters
4351 before and after the proper match
4352 1 The character before the proper match, or empty at beginning of line
4353 2 The proper match, including the leading and trailing markers
4354 3 The leading marker like * or /, indicating the type of highlighting
4355 4 The text between the emphasis markers, not including the markers
4356 5 The character after the match, empty at the end of a line")
4358 (defvar org-verbatim-re nil
4359 "Regular expression for matching verbatim text.")
4361 (defvar org-emphasis-regexp-components) ; defined just below
4362 (defvar org-emphasis-alist) ; defined just below
4363 (defun org-set-emph-re (var val)
4364 "Set variable and compute the emphasis regular expression."
4365 (set var val)
4366 (when (and (boundp 'org-emphasis-alist)
4367 (boundp 'org-emphasis-regexp-components)
4368 org-emphasis-alist org-emphasis-regexp-components)
4369 (pcase-let*
4370 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4371 (body (if (<= nl 0) body
4372 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4373 (template
4374 (format (concat "\\([%s]\\|^\\)" ;before markers
4375 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4376 "\\([%s]\\|$\\)") ;after markers
4377 pre border border body border post)))
4378 (setq org-emph-re (format template "*/_+"))
4379 (setq org-verbatim-re (format template "=~")))))
4381 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4382 ;; set this option proved cumbersome. See this message/thread:
4383 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4384 (defvar org-emphasis-regexp-components
4385 '("- \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4386 "Components used to build the regular expression for emphasis.
4387 This is a list with five entries. Terminology: In an emphasis string
4388 like \" *strong word* \", we call the initial space PREMATCH, the final
4389 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4390 and \"trong wor\" is the body. The different components in this variable
4391 specify what is allowed/forbidden in each part:
4393 pre Chars allowed as prematch. Beginning of line will be allowed too.
4394 post Chars allowed as postmatch. End of line will be allowed too.
4395 border The chars *forbidden* as border characters.
4396 body-regexp A regexp like \".\" to match a body character. Don't use
4397 non-shy groups here, and don't allow newline here.
4398 newline The maximum number of newlines allowed in an emphasis exp.
4400 You need to reload Org or to restart Emacs after customizing this.")
4402 (defcustom org-emphasis-alist
4403 '(("*" bold)
4404 ("/" italic)
4405 ("_" underline)
4406 ("=" org-verbatim verbatim)
4407 ("~" org-code verbatim)
4408 ("+" (:strike-through t)))
4409 "Alist of characters and faces to emphasize text.
4410 Text starting and ending with a special character will be emphasized,
4411 for example *bold*, _underlined_ and /italic/. This variable sets the
4412 marker characters and the face to be used by font-lock for highlighting
4413 in Org buffers.
4415 You need to reload Org or to restart Emacs after customizing this."
4416 :group 'org-appearance
4417 :set 'org-set-emph-re
4418 :version "24.4"
4419 :package-version '(Org . "8.0")
4420 :type '(repeat
4421 (list
4422 (string :tag "Marker character")
4423 (choice
4424 (face :tag "Font-lock-face")
4425 (plist :tag "Face property list"))
4426 (option (const verbatim)))))
4428 (defvar org-protecting-blocks '("src" "example" "export")
4429 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4430 This is needed for font-lock setup.")
4432 ;;; Functions and variables from their packages
4433 ;; Declared here to avoid compiler warnings
4434 (defvar mark-active)
4436 ;; Various packages
4437 (declare-function calc-eval "calc" (str &optional separator &rest args))
4438 (declare-function calendar-forward-day "cal-move" (arg))
4439 (declare-function calendar-goto-date "cal-move" (date))
4440 (declare-function calendar-goto-today "cal-move" ())
4441 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4442 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4443 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4444 (declare-function cdlatex-tab "ext:cdlatex" ())
4445 (declare-function dired-get-filename
4446 "dired"
4447 (&optional localp no-error-if-not-filep))
4448 (declare-function iswitchb-read-buffer
4449 "iswitchb"
4450 (prompt &optional
4451 default require-match _predicate start matches-set))
4452 (declare-function org-agenda-change-all-lines
4453 "org-agenda"
4454 (newhead hdmarker &optional fixface just-this))
4455 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4456 "org-agenda"
4457 (&optional end))
4458 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4459 (declare-function org-agenda-format-item
4460 "org-agenda"
4461 (extra txt &optional level category tags dotime
4462 remove-re habitp))
4463 (declare-function org-agenda-maybe-redo "org-agenda" ())
4464 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4465 (declare-function org-agenda-save-markers-for-cut-and-paste
4466 "org-agenda"
4467 (beg end))
4468 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4469 (declare-function org-agenda-skip "org-agenda" ())
4470 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4471 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4472 (declare-function org-indent-mode "org-indent" (&optional arg))
4473 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4474 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4475 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4476 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4477 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4478 (declare-function parse-time-string "parse-time" (string))
4479 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4481 (defvar align-mode-rules-list)
4482 (defvar calc-embedded-close-formula)
4483 (defvar calc-embedded-open-formula)
4484 (defvar calc-embedded-open-mode)
4485 (defvar font-lock-unfontify-region-function)
4486 (defvar iswitchb-temp-buflist)
4487 (defvar org-agenda-tags-todo-honor-ignore-options)
4488 (defvar remember-data-file)
4489 (defvar texmathp-why)
4491 ;;;###autoload
4492 (defun turn-on-orgtbl ()
4493 "Unconditionally turn on `orgtbl-mode'."
4494 (require 'org-table)
4495 (orgtbl-mode 1))
4497 (defun org-at-table-p (&optional table-type)
4498 "Non-nil if the cursor is inside an Org table.
4499 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4500 If `org-enable-table-editor' is nil, return nil unconditionally."
4501 (and
4502 org-enable-table-editor
4503 (save-excursion
4504 (beginning-of-line)
4505 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4506 (or (not (derived-mode-p 'org-mode))
4507 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4508 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4510 (defun org-at-table.el-p ()
4511 "Non-nil when point is at a table.el table."
4512 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4513 (let ((element (org-element-at-point)))
4514 (and (eq (org-element-type element) 'table)
4515 (eq (org-element-property :type element) 'table.el)))))
4517 (defun org-at-table-hline-p ()
4518 "Non-nil when point is inside a hline in a table.
4519 Assume point is already in a table. If `org-enable-table-editor'
4520 is nil, return nil unconditionally."
4521 (and org-enable-table-editor
4522 (save-excursion
4523 (beginning-of-line)
4524 (looking-at org-table-hline-regexp))))
4526 (defun org-table-map-tables (function &optional quietly)
4527 "Apply FUNCTION to the start of all tables in the buffer."
4528 (org-with-wide-buffer
4529 (goto-char (point-min))
4530 (while (re-search-forward org-table-any-line-regexp nil t)
4531 (unless quietly
4532 (message "Mapping tables: %d%%"
4533 (floor (* 100.0 (point)) (buffer-size))))
4534 (beginning-of-line 1)
4535 (when (and (looking-at org-table-line-regexp)
4536 ;; Exclude tables in src/example/verbatim/clocktable blocks
4537 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4538 (save-excursion (funcall function))
4539 (or (looking-at org-table-line-regexp)
4540 (forward-char 1)))
4541 (re-search-forward org-table-any-border-regexp nil 1)))
4542 (unless quietly (message "Mapping tables: done")))
4544 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4545 (declare-function org-clock-update-mode-line "org-clock" ())
4546 (declare-function org-resolve-clocks "org-clock"
4547 (&optional also-non-dangling-p prompt last-valid))
4549 (defun org-at-TBLFM-p (&optional pos)
4550 "Non-nil when point (or POS) is in #+TBLFM line."
4551 (save-excursion
4552 (goto-char (or pos (point)))
4553 (beginning-of-line)
4554 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4555 (eq (org-element-type (org-element-at-point)) 'table))))
4557 (defvar org-clock-start-time)
4558 (defvar org-clock-marker (make-marker)
4559 "Marker recording the last clock-in.")
4560 (defvar org-clock-hd-marker (make-marker)
4561 "Marker recording the last clock-in, but the headline position.")
4562 (defvar org-clock-heading ""
4563 "The heading of the current clock entry.")
4564 (defun org-clock-is-active ()
4565 "Return the buffer where the clock is currently running.
4566 Return nil if no clock is running."
4567 (marker-buffer org-clock-marker))
4569 (defun org-check-running-clock ()
4570 "Check if the current buffer contains the running clock.
4571 If yes, offer to stop it and to save the buffer with the changes."
4572 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4573 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4574 (buffer-name))))
4575 (org-clock-out)
4576 (when (y-or-n-p "Save changed buffer?")
4577 (save-buffer))))
4579 (defun org-clocktable-try-shift (dir n)
4580 "Check if this line starts a clock table, if yes, shift the time block."
4581 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4582 (org-clocktable-shift dir n)))
4584 ;;;###autoload
4585 (defun org-clock-persistence-insinuate ()
4586 "Set up hooks for clock persistence."
4587 (require 'org-clock)
4588 (add-hook 'org-mode-hook 'org-clock-load)
4589 (add-hook 'kill-emacs-hook 'org-clock-save))
4591 (defgroup org-archive nil
4592 "Options concerning archiving in Org mode."
4593 :tag "Org Archive"
4594 :group 'org-structure)
4596 (defcustom org-archive-location "%s_archive::"
4597 "The location where subtrees should be archived.
4599 The value of this variable is a string, consisting of two parts,
4600 separated by a double-colon. The first part is a filename and
4601 the second part is a headline.
4603 When the filename is omitted, archiving happens in the same file.
4604 %s in the filename will be replaced by the current file
4605 name (without the directory part). Archiving to a different file
4606 is useful to keep archived entries from contributing to the
4607 Org Agenda.
4609 The archived entries will be filed as subtrees of the specified
4610 headline. When the headline is omitted, the subtrees are simply
4611 filed away at the end of the file, as top-level entries. Also in
4612 the heading you can use %s to represent the file name, this can be
4613 useful when using the same archive for a number of different files.
4615 Here are a few examples:
4616 \"%s_archive::\"
4617 If the current file is Projects.org, archive in file
4618 Projects.org_archive, as top-level trees. This is the default.
4620 \"::* Archived Tasks\"
4621 Archive in the current file, under the top-level headline
4622 \"* Archived Tasks\".
4624 \"~/org/archive.org::\"
4625 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4627 \"~/org/archive.org::* From %s\"
4628 Archive in file ~/org/archive.org (absolute path), under headlines
4629 \"From FILENAME\" where file name is the current file name.
4631 \"~/org/datetree.org::datetree/* Finished Tasks\"
4632 The \"datetree/\" string is special, signifying to archive
4633 items to the datetree. Items are placed in either the CLOSED
4634 date of the item, or the current date if there is no CLOSED date.
4635 The heading will be a subentry to the current date. There doesn't
4636 need to be a heading, but there always needs to be a slash after
4637 datetree. For example, to store archived items directly in the
4638 datetree, use \"~/org/datetree.org::datetree/\".
4640 \"basement::** Finished Tasks\"
4641 Archive in file ./basement (relative path), as level 3 trees
4642 below the level 2 heading \"** Finished Tasks\".
4644 You may set this option on a per-file basis by adding to the buffer a
4645 line like
4647 #+ARCHIVE: basement::** Finished Tasks
4649 You may also define it locally for a subtree by setting an ARCHIVE property
4650 in the entry. If such a property is found in an entry, or anywhere up
4651 the hierarchy, it will be used."
4652 :group 'org-archive
4653 :type 'string)
4655 (defcustom org-agenda-skip-archived-trees t
4656 "Non-nil means the agenda will skip any items located in archived trees.
4657 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4658 variable is no longer recommended, you should leave it at the value t.
4659 Instead, use the key `v' to cycle the archives-mode in the agenda."
4660 :group 'org-archive
4661 :group 'org-agenda-skip
4662 :type 'boolean)
4664 (defcustom org-columns-skip-archived-trees t
4665 "Non-nil means ignore archived trees when creating column view."
4666 :group 'org-archive
4667 :group 'org-properties
4668 :type 'boolean)
4670 (defcustom org-cycle-open-archived-trees nil
4671 "Non-nil means `org-cycle' will open archived trees.
4672 An archived tree is a tree marked with the tag ARCHIVE.
4673 When nil, archived trees will stay folded. You can still open them with
4674 normal outline commands like `show-all', but not with the cycling commands."
4675 :group 'org-archive
4676 :group 'org-cycle
4677 :type 'boolean)
4679 (defcustom org-sparse-tree-open-archived-trees nil
4680 "Non-nil means sparse tree construction shows matches in archived trees.
4681 When nil, matches in these trees are highlighted, but the trees are kept in
4682 collapsed state."
4683 :group 'org-archive
4684 :group 'org-sparse-trees
4685 :type 'boolean)
4687 (defcustom org-sparse-tree-default-date-type nil
4688 "The default date type when building a sparse tree.
4689 When this is nil, a date is a scheduled or a deadline timestamp.
4690 Otherwise, these types are allowed:
4692 all: all timestamps
4693 active: only active timestamps (<...>)
4694 inactive: only inactive timestamps ([...])
4695 scheduled: only scheduled timestamps
4696 deadline: only deadline timestamps"
4697 :type '(choice (const :tag "Scheduled or deadline" nil)
4698 (const :tag "All timestamps" all)
4699 (const :tag "Only active timestamps" active)
4700 (const :tag "Only inactive timestamps" inactive)
4701 (const :tag "Only scheduled timestamps" scheduled)
4702 (const :tag "Only deadline timestamps" deadline)
4703 (const :tag "Only closed timestamps" closed))
4704 :version "26.1"
4705 :package-version '(Org . "8.3")
4706 :group 'org-sparse-trees)
4708 (defun org-cycle-hide-archived-subtrees (state)
4709 "Re-hide all archived subtrees after a visibility state change.
4710 STATE should be one of the symbols listed in the docstring of
4711 `org-cycle-hook'."
4712 (when (and (not org-cycle-open-archived-trees)
4713 (not (memq state '(overview folded))))
4714 (save-excursion
4715 (let* ((globalp (memq state '(contents all)))
4716 (beg (if globalp (point-min) (point)))
4717 (end (if globalp (point-max) (org-end-of-subtree t))))
4718 (org-hide-archived-subtrees beg end)
4719 (goto-char beg)
4720 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4721 (message "%s" (substitute-command-keys
4722 "Subtree is archived and stays closed. Use \
4723 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4725 (defun org-force-cycle-archived ()
4726 "Cycle subtree even if it is archived."
4727 (interactive)
4728 (setq this-command 'org-cycle)
4729 (let ((org-cycle-open-archived-trees t))
4730 (call-interactively 'org-cycle)))
4732 (defun org-hide-archived-subtrees (beg end)
4733 "Re-hide all archived subtrees after a visibility state change."
4734 (org-with-wide-buffer
4735 (let ((case-fold-search nil)
4736 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4737 (goto-char beg)
4738 ;; Include headline point is currently on.
4739 (beginning-of-line)
4740 (while (and (< (point) end) (re-search-forward re end t))
4741 (when (member org-archive-tag (org-get-tags))
4742 (org-flag-subtree t)
4743 (org-end-of-subtree t))))))
4745 (declare-function outline-end-of-heading "outline" ())
4746 (declare-function outline-flag-region "outline" (from to flag))
4747 (defun org-flag-subtree (flag)
4748 (save-excursion
4749 (org-back-to-heading t)
4750 (outline-end-of-heading)
4751 (outline-flag-region (point)
4752 (progn (org-end-of-subtree t) (point))
4753 flag)))
4755 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4757 ;; Declare Column View Code
4759 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4760 (declare-function org-columns-compute "org-colview" (property))
4762 ;; Declare ID code
4764 (declare-function org-id-store-link "org-id")
4765 (declare-function org-id-locations-load "org-id")
4766 (declare-function org-id-locations-save "org-id")
4767 (defvar org-id-track-globally)
4769 ;;; Variables for pre-computed regular expressions, all buffer local
4771 (defvar-local org-todo-regexp nil
4772 "Matches any of the TODO state keywords.
4773 Since TODO keywords are case-sensitive, `case-fold-search' is
4774 expected to be bound to nil when matching against this regexp.")
4776 (defvar-local org-not-done-regexp nil
4777 "Matches any of the TODO state keywords except the last one.
4778 Since TODO keywords are case-sensitive, `case-fold-search' is
4779 expected to be bound to nil when matching against this regexp.")
4781 (defvar-local org-not-done-heading-regexp nil
4782 "Matches a TODO headline that is not done.
4783 Since TODO keywords are case-sensitive, `case-fold-search' is
4784 expected to be bound to nil when matching against this regexp.")
4786 (defvar-local org-todo-line-regexp nil
4787 "Matches a headline and puts TODO state into group 2 if present.
4788 Since TODO keywords are case-sensitive, `case-fold-search' is
4789 expected to be bound to nil when matching against this regexp.")
4791 (defvar-local org-complex-heading-regexp nil
4792 "Matches a headline and puts everything into groups:
4794 group 1: Stars
4795 group 2: The TODO keyword, maybe
4796 group 3: Priority cookie
4797 group 4: True headline
4798 group 5: Tags
4800 Since TODO keywords are case-sensitive, `case-fold-search' is
4801 expected to be bound to nil when matching against this regexp.")
4803 (defvar-local org-complex-heading-regexp-format nil
4804 "Printf format to make regexp to match an exact headline.
4805 This regexp will match the headline of any node which has the
4806 exact headline text that is put into the format, but may have any
4807 TODO state, priority and tags.")
4809 (defvar-local org-todo-line-tags-regexp nil
4810 "Matches a headline and puts TODO state into group 2 if present.
4811 Also put tags into group 4 if tags are present.")
4813 (defconst org-plain-time-of-day-regexp
4814 (concat
4815 "\\(\\<[012]?[0-9]"
4816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4817 "\\(--?"
4818 "\\(\\<[012]?[0-9]"
4819 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4820 "\\)?")
4821 "Regular expression to match a plain time or time range.
4822 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4823 groups carry important information:
4824 0 the full match
4825 1 the first time, range or not
4826 8 the second time, if it is a range.")
4828 (defconst org-plain-time-extension-regexp
4829 (concat
4830 "\\(\\<[012]?[0-9]"
4831 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4832 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4833 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4834 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4835 groups carry important information:
4836 0 the full match
4837 7 hours of duration
4838 9 minutes of duration")
4840 (defconst org-stamp-time-of-day-regexp
4841 (concat
4842 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4843 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4844 "\\(--?"
4845 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4846 "Regular expression to match a timestamp time or time range.
4847 After a match, the following groups carry important information:
4848 0 the full match
4849 1 date plus weekday, for back referencing to make sure both times are on the same day
4850 2 the first time, range or not
4851 4 the second time, if it is a range.")
4853 (defconst org-startup-options
4854 '(("fold" org-startup-folded t)
4855 ("overview" org-startup-folded t)
4856 ("nofold" org-startup-folded nil)
4857 ("showall" org-startup-folded nil)
4858 ("showeverything" org-startup-folded showeverything)
4859 ("content" org-startup-folded content)
4860 ("indent" org-startup-indented t)
4861 ("noindent" org-startup-indented nil)
4862 ("hidestars" org-hide-leading-stars t)
4863 ("showstars" org-hide-leading-stars nil)
4864 ("odd" org-odd-levels-only t)
4865 ("oddeven" org-odd-levels-only nil)
4866 ("align" org-startup-align-all-tables t)
4867 ("noalign" org-startup-align-all-tables nil)
4868 ("inlineimages" org-startup-with-inline-images t)
4869 ("noinlineimages" org-startup-with-inline-images nil)
4870 ("latexpreview" org-startup-with-latex-preview t)
4871 ("nolatexpreview" org-startup-with-latex-preview nil)
4872 ("customtime" org-display-custom-times t)
4873 ("logdone" org-log-done time)
4874 ("lognotedone" org-log-done note)
4875 ("nologdone" org-log-done nil)
4876 ("lognoteclock-out" org-log-note-clock-out t)
4877 ("nolognoteclock-out" org-log-note-clock-out nil)
4878 ("logrepeat" org-log-repeat state)
4879 ("lognoterepeat" org-log-repeat note)
4880 ("logdrawer" org-log-into-drawer t)
4881 ("nologdrawer" org-log-into-drawer nil)
4882 ("logstatesreversed" org-log-states-order-reversed t)
4883 ("nologstatesreversed" org-log-states-order-reversed nil)
4884 ("nologrepeat" org-log-repeat nil)
4885 ("logreschedule" org-log-reschedule time)
4886 ("lognotereschedule" org-log-reschedule note)
4887 ("nologreschedule" org-log-reschedule nil)
4888 ("logredeadline" org-log-redeadline time)
4889 ("lognoteredeadline" org-log-redeadline note)
4890 ("nologredeadline" org-log-redeadline nil)
4891 ("logrefile" org-log-refile time)
4892 ("lognoterefile" org-log-refile note)
4893 ("nologrefile" org-log-refile nil)
4894 ("fninline" org-footnote-define-inline t)
4895 ("nofninline" org-footnote-define-inline nil)
4896 ("fnlocal" org-footnote-section nil)
4897 ("fnauto" org-footnote-auto-label t)
4898 ("fnprompt" org-footnote-auto-label nil)
4899 ("fnconfirm" org-footnote-auto-label confirm)
4900 ("fnplain" org-footnote-auto-label plain)
4901 ("fnadjust" org-footnote-auto-adjust t)
4902 ("nofnadjust" org-footnote-auto-adjust nil)
4903 ("constcgs" constants-unit-system cgs)
4904 ("constSI" constants-unit-system SI)
4905 ("noptag" org-tag-persistent-alist nil)
4906 ("hideblocks" org-hide-block-startup t)
4907 ("nohideblocks" org-hide-block-startup nil)
4908 ("beamer" org-startup-with-beamer-mode t)
4909 ("entitiespretty" org-pretty-entities t)
4910 ("entitiesplain" org-pretty-entities nil))
4911 "Variable associated with STARTUP options for org-mode.
4912 Each element is a list of three items: the startup options (as written
4913 in the #+STARTUP line), the corresponding variable, and the value to set
4914 this variable to if the option is found. An optional forth element PUSH
4915 means to push this value onto the list in the variable.")
4917 (defcustom org-group-tags t
4918 "When non-nil (the default), use group tags.
4919 This can be turned on/off through `org-toggle-tags-groups'."
4920 :group 'org-tags
4921 :group 'org-startup
4922 :type 'boolean)
4924 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4926 (defun org-toggle-tags-groups ()
4927 "Toggle support for group tags.
4928 Support for group tags is controlled by the option
4929 `org-group-tags', which is non-nil by default."
4930 (interactive)
4931 (setq org-group-tags (not org-group-tags))
4932 (cond ((and (derived-mode-p 'org-agenda-mode)
4933 org-group-tags)
4934 (org-agenda-redo))
4935 ((derived-mode-p 'org-mode)
4936 (let ((org-inhibit-startup t)) (org-mode))))
4937 (message "Groups tags support has been turned %s"
4938 (if org-group-tags "on" "off")))
4940 (defun org-set-regexps-and-options (&optional tags-only)
4941 "Precompute regular expressions used in the current buffer.
4942 When optional argument TAGS-ONLY is non-nil, only compute tags
4943 related expressions."
4944 (when (derived-mode-p 'org-mode)
4945 (let ((alist (org--setup-collect-keywords
4946 (org-make-options-regexp
4947 (append '("FILETAGS" "TAGS" "SETUPFILE")
4948 (and (not tags-only)
4949 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4950 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4951 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4952 ;; Startup options. Get this early since it does change
4953 ;; behavior for other options (e.g., tags).
4954 (let ((startup (cdr (assq 'startup alist))))
4955 (dolist (option startup)
4956 (let ((entry (assoc-string option org-startup-options t)))
4957 (when entry
4958 (let ((var (nth 1 entry))
4959 (val (nth 2 entry)))
4960 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4961 (unless (listp (symbol-value var))
4962 (set (make-local-variable var) nil))
4963 (add-to-list var val)))))))
4964 (setq-local org-file-tags
4965 (mapcar #'org-add-prop-inherited
4966 (cdr (assq 'filetags alist))))
4967 (setq org-current-tag-alist
4968 (append org-tag-persistent-alist
4969 (let ((tags (cdr (assq 'tags alist))))
4970 (if tags (org-tag-string-to-alist tags)
4971 org-tag-alist))))
4972 (setq org-tag-groups-alist
4973 (org-tag-alist-to-groups org-current-tag-alist))
4974 (unless tags-only
4975 ;; File properties.
4976 (setq-local org-file-properties (cdr (assq 'property alist)))
4977 ;; Archive location.
4978 (let ((archive (cdr (assq 'archive alist))))
4979 (when archive (setq-local org-archive-location archive)))
4980 ;; Category.
4981 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4982 (when cat
4983 (setq-local org-category (intern cat))
4984 (setq-local org-file-properties
4985 (org--update-property-plist
4986 "CATEGORY" cat org-file-properties))))
4987 ;; Columns.
4988 (let ((column (cdr (assq 'columns alist))))
4989 (when column (setq-local org-columns-default-format column)))
4990 ;; Constants.
4991 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4992 ;; Link abbreviations.
4993 (let ((links (cdr (assq 'link alist))))
4994 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4995 ;; Priorities.
4996 (let ((priorities (cdr (assq 'priorities alist))))
4997 (when priorities
4998 (setq-local org-highest-priority (nth 0 priorities))
4999 (setq-local org-lowest-priority (nth 1 priorities))
5000 (setq-local org-default-priority (nth 2 priorities))))
5001 ;; Scripts.
5002 (let ((scripts (assq 'scripts alist)))
5003 (when scripts
5004 (setq-local org-use-sub-superscripts (cdr scripts))))
5005 ;; TODO keywords.
5006 (setq-local org-todo-kwd-alist nil)
5007 (setq-local org-todo-key-alist nil)
5008 (setq-local org-todo-key-trigger nil)
5009 (setq-local org-todo-keywords-1 nil)
5010 (setq-local org-done-keywords nil)
5011 (setq-local org-todo-heads nil)
5012 (setq-local org-todo-sets nil)
5013 (setq-local org-todo-log-states nil)
5014 (let ((todo-sequences
5015 (or (nreverse (cdr (assq 'todo alist)))
5016 (let ((d (default-value 'org-todo-keywords)))
5017 (if (not (stringp (car d))) d
5018 ;; XXX: Backward compatibility code.
5019 (list (cons org-todo-interpretation d)))))))
5020 (dolist (sequence todo-sequences)
5021 (let* ((sequence (or (run-hook-with-args-until-success
5022 'org-todo-setup-filter-hook sequence)
5023 sequence))
5024 (sequence-type (car sequence))
5025 (keywords (cdr sequence))
5026 (sep (member "|" keywords))
5027 names alist)
5028 (dolist (k (remove "|" keywords))
5029 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5031 (error "Invalid TODO keyword %s" k))
5032 (let ((name (match-string 1 k))
5033 (key (match-string 2 k))
5034 (log (org-extract-log-state-settings k)))
5035 (push name names)
5036 (push (cons name (and key (string-to-char key))) alist)
5037 (when log (push log org-todo-log-states))))
5038 (let* ((names (nreverse names))
5039 (done (if sep (org-remove-keyword-keys (cdr sep))
5040 (last names)))
5041 (head (car names))
5042 (tail (list sequence-type head (car done) (org-last done))))
5043 (add-to-list 'org-todo-heads head 'append)
5044 (push names org-todo-sets)
5045 (setq org-done-keywords (append org-done-keywords done nil))
5046 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5047 (setq org-todo-key-alist
5048 (append org-todo-key-alist
5049 (and alist
5050 (append '((:startgroup))
5051 (nreverse alist)
5052 '((:endgroup))))))
5053 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5054 (setq org-todo-sets (nreverse org-todo-sets)
5055 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5056 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5057 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5058 ;; Compute the regular expressions and other local variables.
5059 ;; Using `org-outline-regexp-bol' would complicate them much,
5060 ;; because of the fixed white space at the end of that string.
5061 (unless org-done-keywords
5062 (setq org-done-keywords
5063 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5064 (setq org-not-done-keywords
5065 (org-delete-all org-done-keywords
5066 (copy-sequence org-todo-keywords-1))
5067 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5068 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5069 org-not-done-heading-regexp
5070 (format org-heading-keyword-regexp-format org-not-done-regexp)
5071 org-todo-line-regexp
5072 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5073 org-complex-heading-regexp
5074 (concat "^\\(\\*+\\)"
5075 "\\(?: +" org-todo-regexp "\\)?"
5076 "\\(?: +\\(\\[#.\\]\\)\\)?"
5077 "\\(?: +\\(.*?\\)\\)??"
5078 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5079 "[ \t]*$")
5080 org-complex-heading-regexp-format
5081 (concat "^\\(\\*+\\)"
5082 "\\(?: +" org-todo-regexp "\\)?"
5083 "\\(?: +\\(\\[#.\\]\\)\\)?"
5084 "\\(?: +"
5085 ;; Stats cookies can be stuck to body.
5086 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5087 "\\(%s\\)"
5088 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5089 "\\)"
5090 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5091 "[ \t]*$")
5092 org-todo-line-tags-regexp
5093 (concat "^\\(\\*+\\)"
5094 "\\(?: +" org-todo-regexp "\\)?"
5095 "\\(?: +\\(.*?\\)\\)??"
5096 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5097 "[ \t]*$"))
5098 (org-compute-latex-and-related-regexp)))))
5100 (defun org--setup-collect-keywords (regexp &optional files alist)
5101 "Return setup keywords values as an alist.
5103 REGEXP matches a subset of setup keywords. FILES is a list of
5104 file names already visited. It is used to avoid circular setup
5105 files. ALIST, when non-nil, is the alist computed so far.
5107 Return value contains the following keys: `archive', `category',
5108 `columns', `constants', `filetags', `link', `priorities',
5109 `property', `scripts', `startup', `tags' and `todo'."
5110 (org-with-wide-buffer
5111 (goto-char (point-min))
5112 (let ((case-fold-search t))
5113 (while (re-search-forward regexp nil t)
5114 (let ((element (org-element-at-point)))
5115 (when (eq (org-element-type element) 'keyword)
5116 (let ((key (org-element-property :key element))
5117 (value (org-element-property :value element)))
5118 (cond
5119 ((equal key "ARCHIVE")
5120 (when (org-string-nw-p value)
5121 (push (cons 'archive value) alist)))
5122 ((equal key "CATEGORY") (push (cons 'category value) alist))
5123 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5124 ((equal key "CONSTANTS")
5125 (let* ((constants (assq 'constants alist))
5126 (store (cdr constants)))
5127 (dolist (pair (org-split-string value))
5128 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5129 pair)
5130 (let* ((name (match-string 1 pair))
5131 (value (match-string 2 pair))
5132 (old (assoc name store)))
5133 (if old (setcdr old value)
5134 (push (cons name value) store)))))
5135 (if constants (setcdr constants store)
5136 (push (cons 'constants store) alist))))
5137 ((equal key "FILETAGS")
5138 (when (org-string-nw-p value)
5139 (let ((old (assq 'filetags alist))
5140 (new (apply #'nconc
5141 (mapcar (lambda (x) (org-split-string x ":"))
5142 (org-split-string value)))))
5143 (if old (setcdr old (append new (cdr old)))
5144 (push (cons 'filetags new) alist)))))
5145 ((equal key "LINK")
5146 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5147 (let ((links (assq 'link alist))
5148 (pair (cons (match-string-no-properties 1 value)
5149 (match-string-no-properties 2 value))))
5150 (if links (push pair (cdr links))
5151 (push (list 'link pair) alist)))))
5152 ((equal key "OPTIONS")
5153 (when (and (org-string-nw-p value)
5154 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5155 (push (cons 'scripts (read (match-string 1 value))) alist)))
5156 ((equal key "PRIORITIES")
5157 (push (cons 'priorities
5158 (let ((prio (org-split-string value)))
5159 (if (< (length prio) 3) '(?A ?C ?B)
5160 (mapcar #'string-to-char prio))))
5161 alist))
5162 ((equal key "PROPERTY")
5163 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5164 (let* ((property (assq 'property alist))
5165 (value (org--update-property-plist
5166 (match-string-no-properties 1 value)
5167 (match-string-no-properties 2 value)
5168 (cdr property))))
5169 (if property (setcdr property value)
5170 (push (cons 'property value) alist)))))
5171 ((equal key "STARTUP")
5172 (let ((startup (assq 'startup alist)))
5173 (if startup
5174 (setcdr startup
5175 (append (cdr startup) (org-split-string value)))
5176 (push (cons 'startup (org-split-string value)) alist))))
5177 ((equal key "TAGS")
5178 (let ((tag-cell (assq 'tags alist)))
5179 (if tag-cell
5180 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5181 (push (cons 'tags value) alist))))
5182 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5183 (let ((todo (assq 'todo alist))
5184 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5185 (org-split-string value))))
5186 (if todo (push value (cdr todo))
5187 (push (list 'todo value) alist))))
5188 ((equal key "SETUPFILE")
5189 (unless buffer-read-only ; Do not check in Gnus messages.
5190 (let ((f (and (org-string-nw-p value)
5191 (expand-file-name
5192 (org-unbracket-string "\"" "\"" value)))))
5193 (when (and f (file-readable-p f) (not (member f files)))
5194 (with-temp-buffer
5195 (setq default-directory (file-name-directory f))
5196 (insert-file-contents f)
5197 (setq alist
5198 ;; Fake Org mode to benefit from cache
5199 ;; without recurring needlessly.
5200 (let ((major-mode 'org-mode))
5201 (org--setup-collect-keywords
5202 regexp (cons f files) alist)))))))))))))))
5203 alist)
5205 (defun org-tag-string-to-alist (s)
5206 "Return tag alist associated to string S.
5207 S is a value for TAGS keyword or produced with
5208 `org-tag-alist-to-string'. Return value is an alist suitable for
5209 `org-tag-alist' or `org-tag-persistent-alist'."
5210 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5211 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5212 "\\|{.+?}\\)" ; regular expression
5213 "\\(?:(\\(.\\))\\)?\\'"))
5214 alist group-flag)
5215 (dolist (tokens lines (cdr (nreverse alist)))
5216 (push '(:newline) alist)
5217 (while tokens
5218 (let ((token (pop tokens)))
5219 (pcase token
5220 ("{"
5221 (push '(:startgroup) alist)
5222 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5223 ("}"
5224 (push '(:endgroup) alist)
5225 (setq group-flag nil))
5226 ("["
5227 (push '(:startgrouptag) alist)
5228 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5229 ("]"
5230 (push '(:endgrouptag) alist)
5231 (setq group-flag nil))
5232 (":"
5233 (push '(:grouptags) alist))
5234 ((guard (string-match tag-re token))
5235 (let ((tag (match-string 1 token))
5236 (key (and (match-beginning 2)
5237 (string-to-char (match-string 2 token)))))
5238 ;; Push all tags in groups, no matter if they already
5239 ;; appear somewhere else in the list.
5240 (when (or group-flag (not (assoc tag alist)))
5241 (push (cons tag key) alist))))))))))
5243 (defun org-tag-alist-to-string (alist &optional skip-key)
5244 "Return tag string associated to ALIST.
5246 ALIST is an alist, as defined in `org-tag-alist' or
5247 `org-tag-persistent-alist', or produced with
5248 `org-tag-string-to-alist'.
5250 Return value is a string suitable as a value for \"TAGS\"
5251 keyword.
5253 When optional argument SKIP-KEY is non-nil, skip selection keys
5254 next to tags."
5255 (mapconcat (lambda (token)
5256 (pcase token
5257 (`(:startgroup) "{")
5258 (`(:endgroup) "}")
5259 (`(:startgrouptag) "[")
5260 (`(:endgrouptag) "]")
5261 (`(:grouptags) ":")
5262 (`(:newline) "\\n")
5263 ((and
5264 (guard (not skip-key))
5265 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5266 (format "%s(%c)" tag key))
5267 (`(,(and tag (pred stringp)) . ,_) tag)
5268 (_ (user-error "Invalid tag token: %S" token))))
5269 alist
5270 " "))
5272 (defun org-tag-alist-to-groups (alist)
5273 "Return group alist from tag ALIST.
5274 ALIST is an alist, as defined in `org-tag-alist' or
5275 `org-tag-persistent-alist', or produced with
5276 `org-tag-string-to-alist'. Return value is an alist following
5277 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5278 a string, summarizing TAGS, as a list of strings."
5279 (let (groups group-status current-group)
5280 (dolist (token alist (nreverse groups))
5281 (pcase token
5282 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5283 (`(,(or :endgroup :endgrouptag))
5284 (when (eq group-status 'append)
5285 (push (nreverse current-group) groups))
5286 (setq group-status nil))
5287 (`(:grouptags) (setq group-status 'append))
5288 ((and `(,tag . ,_) (guard group-status))
5289 (if (eq group-status 'append) (push tag current-group)
5290 (setq current-group (list tag))))
5291 (_ nil)))))
5293 (defvar org--file-cache (make-hash-table :test #'equal)
5294 "Hash table to store contents of files referenced via a URL.
5295 This is the cache of file URLs read using `org-file-contents'.")
5297 (defun org-reset-file-cache ()
5298 "Reset the cache of files downloaded by `org-file-contents'."
5299 (clrhash org--file-cache))
5301 (defun org-file-url-p (file)
5302 "Non-nil if FILE is a URL."
5303 (require 'ffap)
5304 (string-match-p ffap-url-regexp file))
5306 (defun org-file-contents (file &optional noerror nocache)
5307 "Return the contents of FILE, as a string.
5309 FILE can be a file name or URL.
5311 If FILE is a URL, download the contents. If the URL contents are
5312 already cached in the `org--file-cache' hash table, the download step
5313 is skipped.
5315 If NOERROR is non-nil, ignore the error when unable to read the FILE
5316 from file or URL.
5318 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5319 is available. This option applies only if FILE is a URL."
5320 (let* ((is-url (org-file-url-p file))
5321 (cache (and is-url
5322 (not nocache)
5323 (gethash file org--file-cache))))
5324 (cond
5325 (cache)
5326 (is-url
5327 (with-current-buffer (url-retrieve-synchronously file)
5328 (goto-char (point-min))
5329 ;; Move point to after the url-retrieve header.
5330 (search-forward "\n\n" nil :move)
5331 ;; Search for the success code only in the url-retrieve header.
5332 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5333 ;; Update the cache `org--file-cache' and return contents.
5334 (puthash file
5335 (buffer-substring-no-properties (point) (point-max))
5336 org--file-cache)
5337 (funcall (if noerror #'message #'user-error)
5338 "Unable to fetch file from %S"
5339 file))))
5341 (with-temp-buffer
5342 (condition-case err
5343 (progn
5344 (insert-file-contents file)
5345 (buffer-string))
5346 (file-error
5347 (funcall (if noerror #'message #'user-error)
5348 (error-message-string err)))))))))
5350 (defun org-extract-log-state-settings (x)
5351 "Extract the log state setting from a TODO keyword string.
5352 This will extract info from a string like \"WAIT(w@/!)\"."
5353 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5354 (let ((kw (match-string 1 x))
5355 (log1 (and (match-end 3) (match-string 3 x)))
5356 (log2 (and (match-end 4) (match-string 4 x))))
5357 (and (or log1 log2)
5358 (list kw
5359 (and log1 (if (equal log1 "!") 'time 'note))
5360 (and log2 (if (equal log2 "!") 'time 'note)))))))
5362 (defun org-remove-keyword-keys (list)
5363 "Remove a pair of parenthesis at the end of each string in LIST."
5364 (mapcar (lambda (x)
5365 (if (string-match "(.*)$" x)
5366 (substring x 0 (match-beginning 0))
5368 list))
5370 (defun org-assign-fast-keys (alist)
5371 "Assign fast keys to a keyword-key alist.
5372 Respect keys that are already there."
5373 (let (new e (alt ?0))
5374 (while (setq e (pop alist))
5375 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5376 (cdr e)) ;; Key already assigned.
5377 (push e new)
5378 (let ((clist (string-to-list (downcase (car e))))
5379 (used (append new alist)))
5380 (when (= (car clist) ?@)
5381 (pop clist))
5382 (while (and clist (rassoc (car clist) used))
5383 (pop clist))
5384 (unless clist
5385 (while (rassoc alt used)
5386 (cl-incf alt)))
5387 (push (cons (car e) (or (car clist) alt)) new))))
5388 (nreverse new)))
5390 ;;; Some variables used in various places
5392 (defvar org-window-configuration nil
5393 "Used in various places to store a window configuration.")
5394 (defvar org-selected-window nil
5395 "Used in various places to store a window configuration.")
5396 (defvar org-finish-function nil
5397 "Function to be called when `C-c C-c' is used.
5398 This is for getting out of special buffers like capture.")
5399 (defvar org-last-state)
5401 ;; Defined somewhere in this file, but used before definition.
5402 (defvar org-entities) ;; defined in org-entities.el
5403 (defvar org-struct-menu)
5404 (defvar org-org-menu)
5405 (defvar org-tbl-menu)
5407 ;;;; Define the Org mode
5409 ;; We use a before-change function to check if a table might need
5410 ;; an update.
5411 (defvar org-table-may-need-update t
5412 "Indicates that a table might need an update.
5413 This variable is set by `org-before-change-function'.
5414 `org-table-align' sets it back to nil.")
5415 (defun org-before-change-function (_beg _end)
5416 "Every change indicates that a table might need an update."
5417 (setq org-table-may-need-update t))
5418 (defvar org-mode-map)
5419 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5420 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5421 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5422 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5423 (defvar org-table-buffer-is-an nil)
5425 (defvar bidi-paragraph-direction)
5426 (defvar buffer-face-mode-face)
5428 (require 'outline)
5430 ;; Other stuff we need.
5431 (require 'time-date)
5432 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5433 (require 'easymenu)
5434 (autoload 'easy-menu-add "easymenu")
5435 (require 'overlay)
5437 ;; (require 'org-macs) moved higher up in the file before it is first used
5438 (require 'org-entities)
5439 ;; (require 'org-compat) moved higher up in the file before it is first used
5440 (require 'org-faces)
5441 (require 'org-list)
5442 (require 'org-pcomplete)
5443 (require 'org-src)
5444 (require 'org-footnote)
5445 (require 'org-macro)
5447 ;; babel
5448 (require 'ob)
5450 ;;;###autoload
5451 (define-derived-mode org-mode outline-mode "Org"
5452 "Outline-based notes management and organizer, alias
5453 \"Carsten's outline-mode for keeping track of everything.\"
5455 Org mode develops organizational tasks around a NOTES file which
5456 contains information about projects as plain text. Org mode is
5457 implemented on top of Outline mode, which is ideal to keep the content
5458 of large files well structured. It supports ToDo items, deadlines and
5459 time stamps, which magically appear in the diary listing of the Emacs
5460 calendar. Tables are easily created with a built-in table editor.
5461 Plain text URL-like links connect to websites, emails (VM), Usenet
5462 messages (Gnus), BBDB entries, and any files related to the project.
5463 For printing and sharing of notes, an Org file (or a part of it)
5464 can be exported as a structured ASCII or HTML file.
5466 The following commands are available:
5468 \\{org-mode-map}"
5470 ;; Get rid of Outline menus, they are not needed
5471 ;; Need to do this here because define-derived-mode sets up
5472 ;; the keymap so late. Still, it is a waste to call this each time
5473 ;; we switch another buffer into Org mode.
5474 (define-key org-mode-map [menu-bar headings] 'undefined)
5475 (define-key org-mode-map [menu-bar hide] 'undefined)
5476 (define-key org-mode-map [menu-bar show] 'undefined)
5478 (org-load-modules-maybe)
5479 (org-install-agenda-files-menu)
5480 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5481 (add-to-invisibility-spec '(org-cwidth))
5482 (add-to-invisibility-spec '(org-hide-block . t))
5483 (setq-local outline-regexp org-outline-regexp)
5484 (setq-local outline-level 'org-outline-level)
5485 (setq bidi-paragraph-direction 'left-to-right)
5486 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5487 (unless org-display-table
5488 (setq org-display-table (make-display-table)))
5489 (set-display-table-slot
5490 org-display-table 4
5491 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5492 org-ellipsis)))
5493 (setq buffer-display-table org-display-table))
5494 (org-set-regexps-and-options)
5495 (org-set-font-lock-defaults)
5496 (when (and org-tag-faces (not org-tags-special-faces-re))
5497 ;; tag faces set outside customize.... force initialization.
5498 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5499 ;; Calc embedded
5500 (setq-local calc-embedded-open-mode "# ")
5501 ;; Modify a few syntax entries
5502 (modify-syntax-entry ?@ "w")
5503 (modify-syntax-entry ?\" "\"")
5504 (modify-syntax-entry ?\\ "_")
5505 (modify-syntax-entry ?~ "_")
5506 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5507 ;; Activate before-change-function
5508 (setq-local org-table-may-need-update t)
5509 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5510 ;; Check for running clock before killing a buffer
5511 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5512 ;; Initialize macros templates.
5513 (org-macro-initialize-templates)
5514 ;; Initialize radio targets.
5515 (org-update-radio-target-regexp)
5516 ;; Indentation.
5517 (setq-local indent-line-function 'org-indent-line)
5518 (setq-local indent-region-function 'org-indent-region)
5519 ;; Filling and auto-filling.
5520 (org-setup-filling)
5521 ;; Comments.
5522 (org-setup-comments-handling)
5523 ;; Initialize cache.
5524 (org-element-cache-reset)
5525 ;; Beginning/end of defun
5526 (setq-local beginning-of-defun-function 'org-backward-element)
5527 (setq-local end-of-defun-function
5528 (lambda ()
5529 (if (not (org-at-heading-p))
5530 (org-forward-element)
5531 (org-forward-element)
5532 (forward-char -1))))
5533 ;; Next error for sparse trees
5534 (setq-local next-error-function 'org-occur-next-match)
5535 ;; Make sure dependence stuff works reliably, even for users who set it
5536 ;; too late :-(
5537 (if org-enforce-todo-dependencies
5538 (add-hook 'org-blocker-hook
5539 'org-block-todo-from-children-or-siblings-or-parent)
5540 (remove-hook 'org-blocker-hook
5541 'org-block-todo-from-children-or-siblings-or-parent))
5542 (if org-enforce-todo-checkbox-dependencies
5543 (add-hook 'org-blocker-hook
5544 'org-block-todo-from-checkboxes)
5545 (remove-hook 'org-blocker-hook
5546 'org-block-todo-from-checkboxes))
5548 ;; Align options lines
5549 (setq-local
5550 align-mode-rules-list
5551 '((org-in-buffer-settings
5552 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5553 (modes . '(org-mode)))))
5555 ;; Imenu
5556 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5558 ;; Make isearch reveal context
5559 (setq-local outline-isearch-open-invisible-function
5560 (lambda (&rest _) (org-show-context 'isearch)))
5562 ;; Setup the pcomplete hooks
5563 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5564 (setq-local pcomplete-command-name-function 'org-command-at-point)
5565 (setq-local pcomplete-default-completion-function 'ignore)
5566 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5567 (setq-local pcomplete-termination-string "")
5568 (setq-local buffer-face-mode-face 'org-default)
5570 ;; If empty file that did not turn on Org mode automatically, make
5571 ;; it to.
5572 (when (and org-insert-mode-line-in-empty-file
5573 (called-interactively-p 'any)
5574 (= (point-min) (point-max)))
5575 (insert "# -*- mode: org -*-\n\n"))
5576 (unless org-inhibit-startup
5577 (org-unmodified
5578 (when org-startup-with-beamer-mode (org-beamer-mode))
5579 (when org-startup-align-all-tables
5580 (org-table-map-tables #'org-table-align t))
5581 (when org-startup-with-inline-images (org-display-inline-images))
5582 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5583 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5584 (when org-startup-truncated (setq truncate-lines t))
5585 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5586 (org-refresh-effort-properties)))
5587 ;; Try to set `org-hide' face correctly.
5588 (let ((foreground (org-find-invisible-foreground)))
5589 (when foreground
5590 (set-face-foreground 'org-hide foreground))))
5592 ;; Update `customize-package-emacs-version-alist'
5593 (add-to-list 'customize-package-emacs-version-alist
5594 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5595 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5596 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5597 ("9.0" . "26.1")))
5599 (defvar org-mode-transpose-word-syntax-table
5600 (let ((st (make-syntax-table text-mode-syntax-table)))
5601 (dolist (c org-emphasis-alist st)
5602 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5604 (when (fboundp 'abbrev-table-put)
5605 (abbrev-table-put org-mode-abbrev-table
5606 :parents (list text-mode-abbrev-table)))
5608 (defun org-find-invisible-foreground ()
5609 (let ((candidates (remove
5610 "unspecified-bg"
5611 (nconc
5612 (list (face-background 'default)
5613 (face-background 'org-default))
5614 (mapcar
5615 (lambda (alist)
5616 (when (boundp alist)
5617 (cdr (assq 'background-color (symbol-value alist)))))
5618 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5619 (list (face-foreground 'org-hide))))))
5620 (car (remove nil candidates))))
5622 (defun org-current-time (&optional rounding-minutes past)
5623 "Current time, possibly rounded to ROUNDING-MINUTES.
5624 When ROUNDING-MINUTES is not an integer, fall back on the car of
5625 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5626 the rounding returns a past time."
5627 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5628 (car org-time-stamp-rounding-minutes)))
5629 (time (decode-time)) res)
5630 (if (< r 1)
5631 (current-time)
5632 (setq res
5633 (apply 'encode-time
5634 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5635 (nthcdr 2 time))))
5636 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5637 (seconds-to-time (- (float-time res) (* r 60)))
5638 res))))
5640 (defun org-today ()
5641 "Return today date, considering `org-extend-today-until'."
5642 (time-to-days
5643 (time-subtract (current-time)
5644 (list 0 (* 3600 org-extend-today-until) 0))))
5646 ;;;; Font-Lock stuff, including the activators
5648 (defvar org-mouse-map (make-sparse-keymap))
5649 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5650 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5651 (when org-mouse-1-follows-link
5652 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5653 (when org-tab-follows-link
5654 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5655 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5657 (require 'font-lock)
5659 (defconst org-non-link-chars "]\t\n\r<>")
5660 (defvar org-link-types-re nil
5661 "Matches a link that has a url-like prefix like \"http:\"")
5662 (defvar org-link-re-with-space nil
5663 "Matches a link with spaces, optional angular brackets around it.")
5664 (defvar org-link-re-with-space2 nil
5665 "Matches a link with spaces, optional angular brackets around it.")
5666 (defvar org-link-re-with-space3 nil
5667 "Matches a link with spaces, only for internal part in bracket links.")
5668 (defvar org-angle-link-re nil
5669 "Matches link with angular brackets, spaces are allowed.")
5670 (defvar org-plain-link-re nil
5671 "Matches plain link, without spaces.")
5672 (defvar org-bracket-link-regexp nil
5673 "Matches a link in double brackets.")
5674 (defvar org-bracket-link-analytic-regexp nil
5675 "Regular expression used to analyze links.
5676 Here is what the match groups contain after a match:
5677 1: http:
5678 2: http
5679 3: path
5680 4: [desc]
5681 5: desc")
5682 (defvar org-bracket-link-analytic-regexp++ nil
5683 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5684 (defvar org-any-link-re nil
5685 "Regular expression matching any link.")
5687 (defconst org-match-sexp-depth 3
5688 "Number of stacked braces for sub/superscript matching.")
5690 (defun org-create-multibrace-regexp (left right n)
5691 "Create a regular expression which will match a balanced sexp.
5692 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5693 as single character strings.
5694 The regexp returned will match the entire expression including the
5695 delimiters. It will also define a single group which contains the
5696 match except for the outermost delimiters. The maximum depth of
5697 stacked delimiters is N. Escaping delimiters is not possible."
5698 (let* ((nothing (concat "[^" left right "]*?"))
5699 (or "\\|")
5700 (re nothing)
5701 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5702 (while (> n 1)
5703 (setq n (1- n)
5704 re (concat re or next)
5705 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5706 (concat left "\\(" re "\\)" right)))
5708 (defconst org-match-substring-regexp
5709 (concat
5710 "\\(\\S-\\)\\([_^]\\)\\("
5711 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5712 "\\|"
5713 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5714 "\\|"
5715 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5716 "The regular expression matching a sub- or superscript.")
5718 (defconst org-match-substring-with-braces-regexp
5719 (concat
5720 "\\(\\S-\\)\\([_^]\\)"
5721 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5722 "The regular expression matching a sub- or superscript, forcing braces.")
5724 (defun org-make-link-regexps ()
5725 "Update the link regular expressions.
5726 This should be called after the variable `org-link-parameters' has changed."
5727 (let ((types-re (regexp-opt (org-link-types) t)))
5728 (setq org-link-types-re
5729 (concat "\\`" types-re ":")
5730 org-link-re-with-space
5731 (concat "<?" types-re ":"
5732 "\\([^" org-non-link-chars " ]"
5733 "[^" org-non-link-chars "]*"
5734 "[^" org-non-link-chars " ]\\)>?")
5735 org-link-re-with-space2
5736 (concat "<?" types-re ":"
5737 "\\([^" org-non-link-chars " ]"
5738 "[^\t\n\r]*"
5739 "[^" org-non-link-chars " ]\\)>?")
5740 org-link-re-with-space3
5741 (concat "<?" types-re ":"
5742 "\\([^" org-non-link-chars " ]"
5743 "[^\t\n\r]*\\)")
5744 org-angle-link-re
5745 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5746 types-re)
5747 org-plain-link-re
5748 (concat
5749 "\\<" types-re ":"
5750 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5751 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5752 org-bracket-link-regexp
5753 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5754 org-bracket-link-analytic-regexp
5755 (concat
5756 "\\[\\["
5757 "\\(" types-re ":\\)?"
5758 "\\([^]]+\\)"
5759 "\\]"
5760 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5761 "\\]")
5762 org-bracket-link-analytic-regexp++
5763 (concat
5764 "\\[\\["
5765 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5766 "\\([^]]+\\)"
5767 "\\]"
5768 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5769 "\\]")
5770 org-any-link-re
5771 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5772 org-angle-link-re "\\)\\|\\("
5773 org-plain-link-re "\\)"))))
5775 (org-make-link-regexps)
5777 (defvar org-emph-face nil)
5779 (defun org-do-emphasis-faces (limit)
5780 "Run through the buffer and emphasize strings."
5781 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5782 (car org-emphasis-regexp-components))))
5783 (catch :exit
5784 (while (re-search-forward quick-re limit t)
5785 (let* ((marker (match-string 2))
5786 (verbatim? (member marker '("~" "="))))
5787 (when (save-excursion
5788 (goto-char (match-beginning 0))
5789 ;; Do not match headline stars. Do not consider
5790 ;; stars of a headline as closing marker for bold
5791 ;; markup either. Do not match table hlines.
5792 (and
5793 (not (looking-at-p org-outline-regexp-bol))
5794 (not (and (equal marker "+")
5795 (org-match-line
5796 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5797 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5798 (not (string-match-p
5799 (concat org-outline-regexp-bol "\\'")
5800 (match-string 0)))))
5801 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5802 (font-lock-prepend-text-property
5803 (match-beginning 2) (match-end 2) 'face face)
5804 (when verbatim?
5805 (org-remove-flyspell-overlays-in
5806 (match-beginning 0) (match-end 0)))
5807 (add-text-properties (match-beginning 2) (match-end 2)
5808 '(font-lock-multiline t org-emphasis t))
5809 (when org-hide-emphasis-markers
5810 (add-text-properties (match-end 4) (match-beginning 5)
5811 '(invisible org-link))
5812 (add-text-properties (match-beginning 3) (match-end 3)
5813 '(invisible org-link)))
5814 (throw :exit t))))))))
5816 (defun org-emphasize (&optional char)
5817 "Insert or change an emphasis, i.e. a font like bold or italic.
5818 If there is an active region, change that region to a new emphasis.
5819 If there is no region, just insert the marker characters and position
5820 the cursor between them.
5821 CHAR should be the marker character. If it is a space, it means to
5822 remove the emphasis of the selected region.
5823 If CHAR is not given (for example in an interactive call) it will be
5824 prompted for."
5825 (interactive)
5826 (let ((erc org-emphasis-regexp-components)
5827 (string "") beg end move s)
5828 (if (org-region-active-p)
5829 (setq beg (region-beginning)
5830 end (region-end)
5831 string (buffer-substring beg end))
5832 (setq move t))
5834 (unless char
5835 (message "Emphasis marker or tag: [%s]"
5836 (mapconcat #'car org-emphasis-alist ""))
5837 (setq char (read-char-exclusive)))
5838 (if (equal char ?\s)
5839 (setq s ""
5840 move nil)
5841 (unless (assoc (char-to-string char) org-emphasis-alist)
5842 (user-error "No such emphasis marker: \"%c\"" char))
5843 (setq s (char-to-string char)))
5844 (while (and (> (length string) 1)
5845 (equal (substring string 0 1) (substring string -1))
5846 (assoc (substring string 0 1) org-emphasis-alist))
5847 (setq string (substring string 1 -1)))
5848 (setq string (concat s string s))
5849 (when beg (delete-region beg end))
5850 (unless (or (bolp)
5851 (string-match (concat "[" (nth 0 erc) "\n]")
5852 (char-to-string (char-before (point)))))
5853 (insert " "))
5854 (unless (or (eobp)
5855 (string-match (concat "[" (nth 1 erc) "\n]")
5856 (char-to-string (char-after (point)))))
5857 (insert " ") (backward-char 1))
5858 (insert string)
5859 (and move (backward-char 1))))
5861 (defconst org-nonsticky-props
5862 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5864 (defsubst org-rear-nonsticky-at (pos)
5865 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5867 (defun org-activate-links (limit)
5868 "Add link properties to links.
5869 This includes angle, plain, and bracket links."
5870 (catch :exit
5871 (while (re-search-forward org-any-link-re limit t)
5872 (let* ((start (match-beginning 0))
5873 (end (match-end 0))
5874 (style (cond ((eq ?< (char-after start)) 'angle)
5875 ((eq ?\[ (char-after (1+ start))) 'bracket)
5876 (t 'plain))))
5877 (when (and (memq style org-highlight-links)
5878 ;; Do not confuse plain links with tags.
5879 (not (and (eq style 'plain)
5880 (let ((face (get-text-property
5881 (max (1- start) (point-min)) 'face)))
5882 (if (consp face) (memq 'org-tag face)
5883 (eq 'org-tag face))))))
5884 (let* ((link-object (save-excursion
5885 (goto-char start)
5886 (save-match-data (org-element-link-parser))))
5887 (link (org-element-property :raw-link link-object))
5888 (type (org-element-property :type link-object))
5889 (path (org-element-property :path link-object))
5890 (properties ;for link's visible part
5891 (list
5892 'face (pcase (org-link-get-parameter type :face)
5893 ((and (pred functionp) face) (funcall face path))
5894 ((and (pred facep) face) face)
5895 ((and (pred consp) face) face) ;anonymous
5896 (_ 'org-link))
5897 'mouse-face (or (org-link-get-parameter type :mouse-face)
5898 'highlight)
5899 'keymap (or (org-link-get-parameter type :keymap)
5900 org-mouse-map)
5901 'help-echo (pcase (org-link-get-parameter type :help-echo)
5902 ((and (pred stringp) echo) echo)
5903 ((and (pred functionp) echo) echo)
5904 (_ (concat "LINK: " link)))
5905 'htmlize-link (pcase (org-link-get-parameter type
5906 :htmlize-link)
5907 ((and (pred functionp) f) (funcall f))
5908 (_ `(:uri ,link)))
5909 'font-lock-multiline t)))
5910 (org-remove-flyspell-overlays-in start end)
5911 (org-rear-nonsticky-at end)
5912 (if (not (eq 'bracket style))
5913 (add-text-properties start end properties)
5914 ;; Handle invisible parts in bracket links.
5915 (remove-text-properties start end '(invisible nil))
5916 (let ((hidden
5917 (append `(invisible
5918 ,(or (org-link-get-parameter type :display)
5919 'org-link))
5920 properties))
5921 (visible-start (or (match-beginning 4) (match-beginning 2)))
5922 (visible-end (or (match-end 4) (match-end 2))))
5923 (add-text-properties start visible-start hidden)
5924 (add-text-properties visible-start visible-end properties)
5925 (add-text-properties visible-end end hidden)
5926 (org-rear-nonsticky-at visible-start)
5927 (org-rear-nonsticky-at visible-end)))
5928 (let ((f (org-link-get-parameter type :activate-func)))
5929 (when (functionp f)
5930 (funcall f start end path (eq style 'bracket))))
5931 (throw :exit t))))) ;signal success
5932 nil))
5934 (defun org-activate-code (limit)
5935 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5936 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5937 (remove-text-properties (match-beginning 0) (match-end 0)
5938 '(display t invisible t intangible t))
5941 (defcustom org-src-fontify-natively t
5942 "When non-nil, fontify code in code blocks.
5943 See also the `org-block' face."
5944 :type 'boolean
5945 :version "24.4"
5946 :package-version '(Org . "8.3")
5947 :group 'org-appearance
5948 :group 'org-babel)
5950 (defcustom org-allow-promoting-top-level-subtree nil
5951 "When non-nil, allow promoting a top level subtree.
5952 The leading star of the top level headline will be replaced
5953 by a #."
5954 :type 'boolean
5955 :version "24.1"
5956 :group 'org-appearance)
5958 (defun org-fontify-meta-lines-and-blocks (limit)
5959 (condition-case nil
5960 (org-fontify-meta-lines-and-blocks-1 limit)
5961 (error (message "org-mode fontification error in %S at %d"
5962 (current-buffer)
5963 (line-number-at-pos)))))
5965 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5966 "Fontify #+ lines and blocks."
5967 (let ((case-fold-search t))
5968 (when (re-search-forward
5969 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5970 limit t)
5971 (let ((beg (match-beginning 0))
5972 (block-start (match-end 0))
5973 (block-end nil)
5974 (lang (match-string 7))
5975 (beg1 (line-beginning-position 2))
5976 (dc1 (downcase (match-string 2)))
5977 (dc3 (downcase (match-string 3)))
5978 end end1 quoting block-type)
5979 (cond
5980 ((and (match-end 4) (equal dc3 "+begin"))
5981 ;; Truly a block
5982 (setq block-type (downcase (match-string 5))
5983 quoting (member block-type org-protecting-blocks))
5984 (when (re-search-forward
5985 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5986 nil t) ;; on purpose, we look further than LIMIT
5987 (setq end (min (point-max) (match-end 0))
5988 end1 (min (point-max) (1- (match-beginning 0))))
5989 (setq block-end (match-beginning 0))
5990 (when quoting
5991 (org-remove-flyspell-overlays-in beg1 end1)
5992 (remove-text-properties beg end
5993 '(display t invisible t intangible t)))
5994 (add-text-properties
5995 beg end '(font-lock-fontified t font-lock-multiline t))
5996 (add-text-properties beg beg1 '(face org-meta-line))
5997 (org-remove-flyspell-overlays-in beg beg1)
5998 (add-text-properties ; For end_src
5999 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6000 (org-remove-flyspell-overlays-in end1 end)
6001 (cond
6002 ((and lang (not (string= lang "")) org-src-fontify-natively)
6003 (org-src-font-lock-fontify-block lang block-start block-end)
6004 (add-text-properties beg1 block-end '(src-block t)))
6005 (quoting
6006 (add-text-properties beg1 (min (point-max) (1+ end1))
6007 (list 'face
6008 (list :inherit
6009 (let ((face-name
6010 (intern (format "org-block-%s" lang))))
6011 (append (and (facep face-name) (list face-name))
6012 '(org-block))))))) ; end of source block
6013 ((not org-fontify-quote-and-verse-blocks))
6014 ((string= block-type "quote")
6015 (add-face-text-property
6016 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6017 ((string= block-type "verse")
6018 (add-face-text-property
6019 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6020 (add-text-properties beg beg1 '(face org-block-begin-line))
6021 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6022 '(face org-block-end-line))
6024 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6025 (org-remove-flyspell-overlays-in
6026 (match-beginning 0)
6027 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6028 (add-text-properties
6029 beg (match-end 3)
6030 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6031 '(font-lock-fontified t invisible t)
6032 '(font-lock-fontified t face org-document-info-keyword)))
6033 (add-text-properties
6034 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6035 (if (string-equal dc1 "+title:")
6036 '(font-lock-fontified t face org-document-title)
6037 '(font-lock-fontified t face org-document-info))))
6038 ((string-prefix-p "+caption" dc1)
6039 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6040 (remove-text-properties (match-beginning 0) (match-end 0)
6041 '(display t invisible t intangible t))
6042 ;; Handle short captions.
6043 (save-excursion
6044 (beginning-of-line)
6045 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6046 (add-text-properties (line-beginning-position) (match-end 1)
6047 '(font-lock-fontified t face org-meta-line))
6048 (add-text-properties (match-end 0) (line-end-position)
6049 '(font-lock-fontified t face org-block))
6051 ((member dc3 '(" " ""))
6052 (org-remove-flyspell-overlays-in beg (match-end 0))
6053 (add-text-properties
6054 beg (match-end 0)
6055 '(font-lock-fontified t face font-lock-comment-face)))
6056 (t ;; just any other in-buffer setting, but not indented
6057 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6058 (remove-text-properties (match-beginning 0) (match-end 0)
6059 '(display t invisible t intangible t))
6060 (add-text-properties beg (match-end 0)
6061 '(font-lock-fontified t face org-meta-line))
6062 t))))))
6064 (defun org-fontify-drawers (limit)
6065 "Fontify drawers."
6066 (when (re-search-forward org-drawer-regexp limit t)
6067 (add-text-properties
6068 (match-beginning 0) (match-end 0)
6069 '(font-lock-fontified t face org-special-keyword))
6070 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6073 (defun org-fontify-macros (limit)
6074 "Fontify macros."
6075 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6076 (add-text-properties
6077 (match-beginning 0) (match-end 0)
6078 '(font-lock-fontified t face org-macro))
6079 (when org-hide-macro-markers
6080 (add-text-properties (match-end 2) (match-beginning 2)
6081 '(invisible t))
6082 (add-text-properties (match-beginning 1) (match-end 1)
6083 '(invisible t)))
6084 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6087 (defun org-activate-footnote-links (limit)
6088 "Add text properties for footnotes."
6089 (let ((fn (org-footnote-next-reference-or-definition limit)))
6090 (when fn
6091 (let* ((beg (nth 1 fn))
6092 (end (nth 2 fn))
6093 (label (car fn))
6094 (referencep (/= (line-beginning-position) beg)))
6095 (when (and referencep (nth 3 fn))
6096 (save-excursion
6097 (goto-char beg)
6098 (search-forward (or label "fn:"))
6099 (org-remove-flyspell-overlays-in beg (match-end 0))))
6100 (add-text-properties beg end
6101 (list 'mouse-face 'highlight
6102 'keymap org-mouse-map
6103 'help-echo
6104 (if referencep "Footnote reference"
6105 "Footnote definition")
6106 'font-lock-fontified t
6107 'font-lock-multiline t
6108 'face 'org-footnote))))))
6110 (defun org-activate-dates (limit)
6111 "Add text properties for dates."
6112 (when (and (re-search-forward org-tsr-regexp-both limit t)
6113 (not (equal (char-before (match-beginning 0)) 91)))
6114 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6115 (add-text-properties (match-beginning 0) (match-end 0)
6116 (list 'mouse-face 'highlight
6117 'keymap org-mouse-map))
6118 (org-rear-nonsticky-at (match-end 0))
6119 (when org-display-custom-times
6120 ;; If it's a date range, activate custom time for second date.
6121 (when (match-end 3)
6122 (org-display-custom-time (match-beginning 3) (match-end 3)))
6123 (org-display-custom-time (match-beginning 1) (match-end 1)))
6126 (defvar-local org-target-link-regexp nil
6127 "Regular expression matching radio targets in plain text.")
6129 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6130 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6131 border border border))
6132 "Regular expression matching a link target.")
6134 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6135 "Regular expression matching a radio target.")
6137 (defconst org-any-target-regexp
6138 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6139 "Regular expression matching any target.")
6141 (defun org-activate-target-links (limit)
6142 "Add text properties for target matches."
6143 (when org-target-link-regexp
6144 (let ((case-fold-search t))
6145 (when (re-search-forward org-target-link-regexp limit t)
6146 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6147 (add-text-properties (match-beginning 1) (match-end 1)
6148 (list 'mouse-face 'highlight
6149 'keymap org-mouse-map
6150 'help-echo "Radio target link"
6151 'org-linked-text t))
6152 (org-rear-nonsticky-at (match-end 1))
6153 t))))
6155 (defun org-update-radio-target-regexp ()
6156 "Find all radio targets in this file and update the regular expression.
6157 Also refresh fontification if needed."
6158 (interactive)
6159 (let ((old-regexp org-target-link-regexp)
6160 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6161 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6162 (targets
6163 (org-with-wide-buffer
6164 (goto-char (point-min))
6165 (let (rtn)
6166 (while (re-search-forward org-radio-target-regexp nil t)
6167 ;; Make sure point is really within the object.
6168 (backward-char)
6169 (let ((obj (org-element-context)))
6170 (when (eq (org-element-type obj) 'radio-target)
6171 (cl-pushnew (org-element-property :value obj) rtn
6172 :test #'equal))))
6173 rtn))))
6174 (setq org-target-link-regexp
6175 (and targets
6176 (concat before-re
6177 (mapconcat
6178 (lambda (x)
6179 (replace-regexp-in-string
6180 " +" "\\s-+" (regexp-quote x) t t))
6181 targets
6182 "\\|")
6183 after-re)))
6184 (unless (equal old-regexp org-target-link-regexp)
6185 ;; Clean-up cache.
6186 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6187 ((not org-target-link-regexp) old-regexp)
6189 (concat before-re
6190 (mapconcat
6191 (lambda (re)
6192 (substring re (length before-re)
6193 (- (length after-re))))
6194 (list old-regexp org-target-link-regexp)
6195 "\\|")
6196 after-re)))))
6197 (org-with-wide-buffer
6198 (goto-char (point-min))
6199 (while (re-search-forward regexp nil t)
6200 (org-element-cache-refresh (match-beginning 1)))))
6201 ;; Re fontify buffer.
6202 (when (memq 'radio org-highlight-links)
6203 (org-restart-font-lock)))))
6205 (defun org-hide-wide-columns (limit)
6206 (let (s e)
6207 (setq s (text-property-any (point) (or limit (point-max))
6208 'org-cwidth t))
6209 (when s
6210 (setq e (next-single-property-change s 'org-cwidth))
6211 (add-text-properties s e '(invisible org-cwidth))
6212 (goto-char e)
6213 t)))
6215 (defvar org-latex-and-related-regexp nil
6216 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6218 (defun org-compute-latex-and-related-regexp ()
6219 "Compute regular expression for LaTeX, entities and sub/superscript.
6220 Result depends on variable `org-highlight-latex-and-related'."
6221 (setq-local
6222 org-latex-and-related-regexp
6223 (let* ((re-sub
6224 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6225 ((eq org-use-sub-superscripts '{})
6226 (list org-match-substring-with-braces-regexp))
6227 (org-use-sub-superscripts (list org-match-substring-regexp))))
6228 (re-latex
6229 (when (memq 'latex org-highlight-latex-and-related)
6230 (let ((matchers (plist-get org-format-latex-options :matchers)))
6231 (delq nil
6232 (mapcar (lambda (x)
6233 (and (member (car x) matchers) (nth 1 x)))
6234 org-latex-regexps)))))
6235 (re-entities
6236 (when (memq 'entities org-highlight-latex-and-related)
6237 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6238 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6240 (defun org-do-latex-and-related (limit)
6241 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6242 LIMIT bounds the search for syntax to highlight. Stop at first
6243 highlighted object, if any. Return t if some highlighting was
6244 done, nil otherwise."
6245 (when (org-string-nw-p org-latex-and-related-regexp)
6246 (catch 'found
6247 (while (re-search-forward org-latex-and-related-regexp limit t)
6248 (unless
6249 (cl-some
6250 (lambda (f)
6251 (memq f '(org-code org-verbatim underline org-special-keyword)))
6252 (save-excursion
6253 (goto-char (1+ (match-beginning 0)))
6254 (face-at-point nil t)))
6255 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6256 '(?_ ?^))
6258 0)))
6259 (font-lock-prepend-text-property
6260 (+ offset (match-beginning 0)) (match-end 0)
6261 'face 'org-latex-and-related)
6262 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6263 '(font-lock-multiline t)))
6264 (throw 'found t)))
6265 nil)))
6267 (defun org-restart-font-lock ()
6268 "Restart `font-lock-mode', to force refontification."
6269 (when (and (boundp 'font-lock-mode) font-lock-mode)
6270 (font-lock-mode -1)
6271 (font-lock-mode 1)))
6273 (defun org-activate-tags (limit)
6274 (when (re-search-forward
6275 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6276 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6277 (add-text-properties (match-beginning 1) (match-end 1)
6278 (list 'mouse-face 'highlight
6279 'keymap org-mouse-map))
6280 (org-rear-nonsticky-at (match-end 1))
6283 (defun org-outline-level ()
6284 "Compute the outline level of the heading at point.
6286 If this is called at a normal headline, the level is the number
6287 of stars. Use `org-reduced-level' to remove the effect of
6288 `org-odd-levels'. Unlike to `org-current-level', this function
6289 takes into consideration inlinetasks."
6290 (org-with-wide-buffer
6291 (end-of-line)
6292 (if (re-search-backward org-outline-regexp-bol nil t)
6293 (1- (- (match-end 0) (match-beginning 0)))
6294 0)))
6296 (defvar org-font-lock-keywords nil)
6298 (defsubst org-re-property (property &optional literal allow-null value)
6299 "Return a regexp matching a PROPERTY line.
6301 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6302 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6303 non-nil, match properties even without a value.
6305 Match group 3 is set to the value when it exists. If there is no
6306 value and ALLOW-NULL is non-nil, it is set to the empty string.
6308 With optional argument VALUE, match only property lines with
6309 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6310 unless LITERAL is non-nil."
6311 (concat
6312 "^\\(?4:[ \t]*\\)"
6313 (format "\\(?1::\\(?2:%s\\):\\)"
6314 (if literal property (regexp-quote property)))
6315 (cond (value
6316 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6317 (if literal value (regexp-quote value))))
6318 (allow-null
6319 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6321 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6323 (defconst org-property-re
6324 (org-re-property "\\S-+" 'literal t)
6325 "Regular expression matching a property line.
6326 There are four matching groups:
6327 1: :PROPKEY: including the leading and trailing colon,
6328 2: PROPKEY without the leading and trailing colon,
6329 3: PROPVAL without leading or trailing spaces,
6330 4: the indentation of the current line,
6331 5: trailing whitespace.")
6333 (defvar org-font-lock-hook nil
6334 "Functions to be called for special font lock stuff.")
6336 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6338 (defvar org-font-lock-set-keywords-hook nil
6339 "Functions that can manipulate `org-font-lock-extra-keywords'.
6340 This is called after `org-font-lock-extra-keywords' is defined, but before
6341 it is installed to be used by font lock. This can be useful if something
6342 needs to be inserted at a specific position in the font-lock sequence.")
6344 (defun org-font-lock-hook (limit)
6345 "Run `org-font-lock-hook' within LIMIT."
6346 (run-hook-with-args 'org-font-lock-hook limit))
6348 (defun org-set-font-lock-defaults ()
6349 "Set font lock defaults for the current buffer."
6350 (let* ((em org-fontify-emphasized-text)
6351 (lk org-highlight-links)
6352 (org-font-lock-extra-keywords
6353 (list
6354 ;; Call the hook
6355 '(org-font-lock-hook)
6356 ;; Headlines
6357 `(,(if org-fontify-whole-heading-line
6358 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6359 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6360 (1 (org-get-level-face 1))
6361 (2 (org-get-level-face 2))
6362 (3 (org-get-level-face 3)))
6363 ;; Table lines
6364 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6365 (1 'org-table t))
6366 ;; Table internals
6367 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6368 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6369 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6370 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6371 ;; Drawers
6372 '(org-fontify-drawers)
6373 ;; Properties
6374 (list org-property-re
6375 '(1 'org-special-keyword t)
6376 '(3 'org-property-value t))
6377 ;; Link related fontification.
6378 '(org-activate-links)
6379 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6380 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6381 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6382 (when (memq 'footnote lk) '(org-activate-footnote-links))
6383 ;; Targets.
6384 (list org-any-target-regexp '(0 'org-target t))
6385 ;; Diary sexps.
6386 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6387 ;; Macro
6388 '(org-fontify-macros)
6389 '(org-hide-wide-columns (0 nil append))
6390 ;; TODO keyword
6391 (list (format org-heading-keyword-regexp-format
6392 org-todo-regexp)
6393 '(2 (org-get-todo-face 2) t))
6394 ;; DONE
6395 (if org-fontify-done-headline
6396 (list (format org-heading-keyword-regexp-format
6397 (concat
6398 "\\(?:"
6399 (mapconcat 'regexp-quote org-done-keywords "\\|")
6400 "\\)"))
6401 '(2 'org-headline-done t))
6402 nil)
6403 ;; Priorities
6404 '(org-font-lock-add-priority-faces)
6405 ;; Tags
6406 '(org-font-lock-add-tag-faces)
6407 ;; Tags groups
6408 (when (and org-group-tags org-tag-groups-alist)
6409 (list (concat org-outline-regexp-bol ".+\\(:"
6410 (regexp-opt (mapcar 'car org-tag-groups-alist))
6411 ":\\).*$")
6412 '(1 'org-tag-group prepend)))
6413 ;; Special keywords
6414 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6415 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6416 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6417 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6418 ;; Emphasis
6419 (when em '(org-do-emphasis-faces))
6420 ;; Checkboxes
6421 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6422 1 'org-checkbox prepend)
6423 (when (cdr (assq 'checkbox org-list-automatic-rules))
6424 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6425 (0 (org-get-checkbox-statistics-face) t)))
6426 ;; Description list items
6427 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6428 1 'org-list-dt prepend)
6429 ;; ARCHIVEd headings
6430 (list (concat
6431 org-outline-regexp-bol
6432 "\\(.*:" org-archive-tag ":.*\\)")
6433 '(1 'org-archived prepend))
6434 ;; Specials
6435 '(org-do-latex-and-related)
6436 '(org-fontify-entities)
6437 '(org-raise-scripts)
6438 ;; Code
6439 '(org-activate-code (1 'org-code t))
6440 ;; COMMENT
6441 (list (format
6442 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6443 org-todo-regexp
6444 org-comment-string)
6445 '(9 'org-special-keyword t))
6446 ;; Blocks and meta lines
6447 '(org-fontify-meta-lines-and-blocks))))
6448 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6449 (run-hooks 'org-font-lock-set-keywords-hook)
6450 ;; Now set the full font-lock-keywords
6451 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6452 (setq-local font-lock-defaults
6453 '(org-font-lock-keywords t nil nil backward-paragraph))
6454 (kill-local-variable 'font-lock-keywords)
6455 nil))
6457 (defun org-toggle-pretty-entities ()
6458 "Toggle the composition display of entities as UTF8 characters."
6459 (interactive)
6460 (setq-local org-pretty-entities (not org-pretty-entities))
6461 (org-restart-font-lock)
6462 (if org-pretty-entities
6463 (message "Entities are now displayed as UTF8 characters")
6464 (save-restriction
6465 (widen)
6466 (decompose-region (point-min) (point-max))
6467 (message "Entities are now displayed as plain text"))))
6469 (defvar-local org-custom-properties-overlays nil
6470 "List of overlays used for custom properties.")
6472 (defun org-toggle-custom-properties-visibility ()
6473 "Display or hide properties in `org-custom-properties'."
6474 (interactive)
6475 (if org-custom-properties-overlays
6476 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6477 (setq org-custom-properties-overlays nil))
6478 (when org-custom-properties
6479 (org-with-wide-buffer
6480 (goto-char (point-min))
6481 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6482 (while (re-search-forward regexp nil t)
6483 (let ((end (cdr (save-match-data (org-get-property-block)))))
6484 (when (and end (< (point) end))
6485 ;; Hide first custom property in current drawer.
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 ;; Hide additional custom properties in the same drawer.
6491 (while (re-search-forward regexp end t)
6492 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6493 (overlay-put o 'invisible t)
6494 (overlay-put o 'org-custom-property t)
6495 (push o org-custom-properties-overlays)))))
6496 ;; Each entry is limited to a single property drawer.
6497 (outline-next-heading)))))))
6499 (defun org-fontify-entities (limit)
6500 "Find an entity to fontify."
6501 (let (ee)
6502 (when org-pretty-entities
6503 (catch 'match
6504 ;; "\_ "-family is left out on purpose. Only the first one,
6505 ;; i.e., "\_ ", could be fontified anyway, and it would be
6506 ;; confusing when adding a second white space character.
6507 (while (re-search-forward
6508 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6509 limit t)
6510 (when (and (not (org-at-comment-p))
6511 (setq ee (org-entity-get (match-string 1)))
6512 (= (length (nth 6 ee)) 1))
6513 (let* ((end (if (equal (match-string 2) "{}")
6514 (match-end 2)
6515 (match-end 1))))
6516 (add-text-properties
6517 (match-beginning 0) end
6518 (list 'font-lock-fontified t))
6519 (compose-region (match-beginning 0) end
6520 (nth 6 ee) nil)
6521 (backward-char 1)
6522 (throw 'match t))))
6523 nil))))
6525 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6526 "Fontify string S like in Org mode."
6527 (with-temp-buffer
6528 (insert s)
6529 (let ((org-odd-levels-only odd-levels))
6530 (org-mode)
6531 (org-font-lock-ensure)
6532 (buffer-string))))
6534 (defvar org-m nil)
6535 (defvar org-l nil)
6536 (defvar org-f nil)
6537 (defun org-get-level-face (n)
6538 "Get the right face for match N in font-lock matching of headlines."
6539 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6540 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6541 (if org-cycle-level-faces
6542 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6543 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6544 (cond
6545 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6546 ((eq n 2) org-f)
6547 (t (unless org-level-color-stars-only org-f))))
6549 (defun org-face-from-face-or-color (context inherit face-or-color)
6550 "Create a face list that inherits INHERIT, but sets the foreground color.
6551 When FACE-OR-COLOR is not a string, just return it."
6552 (if (stringp face-or-color)
6553 (list :inherit inherit
6554 (cdr (assoc context org-faces-easy-properties))
6555 face-or-color)
6556 face-or-color))
6558 (defun org-get-todo-face (kwd)
6559 "Get the right face for a TODO keyword KWD.
6560 If KWD is a number, get the corresponding match group."
6561 (when (numberp kwd) (setq kwd (match-string kwd)))
6562 (or (org-face-from-face-or-color
6563 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6564 (and (member kwd org-done-keywords) 'org-done)
6565 'org-todo))
6567 (defun org-get-priority-face (priority)
6568 "Get the right face for PRIORITY.
6569 PRIORITY is a character."
6570 (or (org-face-from-face-or-color
6571 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6572 'org-priority))
6574 (defun org-get-tag-face (tag)
6575 "Get the right face for TAG.
6576 If TAG is a number, get the corresponding match group."
6577 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6578 (or (org-face-from-face-or-color
6579 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6580 'org-tag)))
6582 (defun org-font-lock-add-priority-faces (limit)
6583 "Add the special priority faces."
6584 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6585 (add-text-properties
6586 (match-beginning 1) (match-end 1)
6587 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6588 'font-lock-fontified t))))
6590 (defun org-font-lock-add-tag-faces (limit)
6591 "Add the special tag faces."
6592 (when (and org-tag-faces org-tags-special-faces-re)
6593 (while (re-search-forward org-tags-special-faces-re limit t)
6594 (add-text-properties (match-beginning 1) (match-end 1)
6595 (list 'face (org-get-tag-face 1)
6596 'font-lock-fontified t))
6597 (backward-char 1))))
6599 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6600 "Remove fontification and activation overlays from links."
6601 (font-lock-default-unfontify-region beg end)
6602 (let* ((buffer-undo-list t)
6603 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6604 (inhibit-modification-hooks t)
6605 deactivate-mark buffer-file-name buffer-file-truename)
6606 (decompose-region beg end)
6607 (remove-text-properties beg end
6608 '(mouse-face t keymap t org-linked-text t
6609 invisible t intangible t
6610 org-emphasis t))
6611 (org-remove-font-lock-display-properties beg end)))
6613 (defconst org-script-display '(((raise -0.3) (height 0.7))
6614 ((raise 0.3) (height 0.7))
6615 ((raise -0.5))
6616 ((raise 0.5)))
6617 "Display properties for showing superscripts and subscripts.")
6619 (defun org-remove-font-lock-display-properties (beg end)
6620 "Remove specific display properties that have been added by font lock.
6621 The will remove the raise properties that are used to show superscripts
6622 and subscripts."
6623 (let (next prop)
6624 (while (< beg end)
6625 (setq next (next-single-property-change beg 'display nil end)
6626 prop (get-text-property beg 'display))
6627 (when (member prop org-script-display)
6628 (put-text-property beg next 'display nil))
6629 (setq beg next))))
6631 (defun org-raise-scripts (limit)
6632 "Add raise properties to sub/superscripts."
6633 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6634 (re-search-forward
6635 (if (eq org-use-sub-superscripts t)
6636 org-match-substring-regexp
6637 org-match-substring-with-braces-regexp)
6638 limit t))
6639 (let* ((pos (point)) table-p comment-p
6640 (mpos (match-beginning 3))
6641 (emph-p (get-text-property mpos 'org-emphasis))
6642 (link-p (get-text-property mpos 'mouse-face))
6643 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6644 (goto-char (point-at-bol))
6645 (setq table-p (looking-at-p org-table-dataline-regexp)
6646 comment-p (looking-at-p "^[ \t]*#[ +]"))
6647 (goto-char pos)
6648 ;; Handle a_b^c
6649 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6650 (unless (or comment-p emph-p link-p keyw-p)
6651 (put-text-property (match-beginning 3) (match-end 0)
6652 'display
6653 (if (equal (char-after (match-beginning 2)) ?^)
6654 (nth (if table-p 3 1) org-script-display)
6655 (nth (if table-p 2 0) org-script-display)))
6656 (add-text-properties (match-beginning 2) (match-end 2)
6657 (list 'invisible t))
6658 (when (and (eq (char-after (match-beginning 3)) ?{)
6659 (eq (char-before (match-end 3)) ?}))
6660 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6661 (list 'invisible t))
6662 (add-text-properties (1- (match-end 3)) (match-end 3)
6663 (list 'invisible t))))
6664 t)))
6666 ;;;; Visibility cycling, including org-goto and indirect buffer
6668 ;;; Cycling
6670 (defvar-local org-cycle-global-status nil)
6671 (put 'org-cycle-global-status 'org-state t)
6672 (defvar-local org-cycle-subtree-status nil)
6673 (put 'org-cycle-subtree-status 'org-state t)
6675 (defvar org-inlinetask-min-level)
6677 (defun org-unlogged-message (&rest args)
6678 "Display a message, but avoid logging it in the *Messages* buffer."
6679 (let ((message-log-max nil))
6680 (apply 'message args)))
6682 ;;;###autoload
6683 (defun org-cycle (&optional arg)
6684 "TAB-action and visibility cycling for Org mode.
6686 This is the command invoked in Org mode by the `TAB' key. Its main
6687 purpose is outline visibility cycling, but it also invokes other actions
6688 in special contexts.
6690 When this function is called with a `\\[universal-argument]' prefix, rotate \
6691 the entire
6692 buffer through 3 states (global cycling)
6693 1. OVERVIEW: Show only top-level headlines.
6694 2. CONTENTS: Show all headlines of all levels, but no body text.
6695 3. SHOW ALL: Show everything.
6697 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6698 switch to the startup visibility,
6699 determined by the variable `org-startup-folded', and by any VISIBILITY
6700 properties in the buffer.
6702 With a `\\[universal-argument] \\[universal-argument] \
6703 \\[universal-argument]' prefix argument, show the entire buffer, including
6704 any drawers.
6706 When inside a table, re-align the table and move to the next field.
6708 When point is at the beginning of a headline, rotate the subtree started
6709 by this line through 3 different states (local cycling)
6710 1. FOLDED: Only the main headline is shown.
6711 2. CHILDREN: The main headline and the direct children are shown.
6712 From this state, you can move to one of the children
6713 and zoom in further.
6714 3. SUBTREE: Show the entire subtree, including body text.
6715 If there is no subtree, switch directly from CHILDREN to FOLDED.
6717 When point is at the beginning of an empty headline and the variable
6718 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6719 of the headline by demoting and promoting it to likely levels. This
6720 speeds up creation document structure by pressing `TAB' once or several
6721 times right after creating a new headline.
6723 When there is a numeric prefix, go up to a heading with level ARG, do
6724 a `show-subtree' and return to the previous cursor position. If ARG
6725 is negative, go up that many levels.
6727 When point is not at the beginning of a headline, execute the global
6728 binding for `TAB', which is re-indenting the line. See the option
6729 `org-cycle-emulate-tab' for details.
6731 As a special case, if point is at the beginning of the buffer and there is
6732 no headline in line 1, this function will act as if called with prefix arg
6733 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6734 prefix arg, but only
6735 if the variable `org-cycle-global-at-bob' is t."
6736 (interactive "P")
6737 (org-load-modules-maybe)
6738 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6739 (and org-cycle-level-after-item/entry-creation
6740 (or (org-cycle-level)
6741 (org-cycle-item-indentation))))
6742 (let* ((limit-level
6743 (or org-cycle-max-level
6744 (and (boundp 'org-inlinetask-min-level)
6745 org-inlinetask-min-level
6746 (1- org-inlinetask-min-level))))
6747 (nstars (and limit-level
6748 (if org-odd-levels-only
6749 (and limit-level (1- (* limit-level 2)))
6750 limit-level)))
6751 (org-outline-regexp
6752 (if (not (derived-mode-p 'org-mode))
6753 outline-regexp
6754 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6755 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6756 (not (looking-at org-outline-regexp))))
6757 (org-cycle-hook
6758 (if bob-special
6759 (delq 'org-optimize-window-after-visibility-change
6760 (copy-sequence org-cycle-hook))
6761 org-cycle-hook))
6762 (pos (point)))
6764 (cond
6766 ((equal arg '(16))
6767 (setq last-command 'dummy)
6768 (org-set-startup-visibility)
6769 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6771 ((equal arg '(64))
6772 (outline-show-all)
6773 (org-unlogged-message "Entire buffer visible, including drawers"))
6775 ((equal arg '(4)) (org-cycle-internal-global))
6777 ;; Try hiding block at point.
6778 ((org-hide-block-toggle-maybe))
6780 ;; Try cdlatex TAB completion
6781 ((org-try-cdlatex-tab))
6783 ;; Table: enter it or move to the next field.
6784 ((org-at-table-p 'any)
6785 (if (org-at-table.el-p)
6786 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6787 Use `\\[org-edit-special]' to edit table.el tables"))
6788 (if arg (org-table-edit-field t)
6789 (org-table-justify-field-maybe)
6790 (call-interactively 'org-table-next-field))))
6792 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6794 ;; Global cycling: delegate to `org-cycle-internal-global'.
6795 (bob-special (org-cycle-internal-global))
6797 ;; Drawers: delegate to `org-flag-drawer'.
6798 ((save-excursion
6799 (beginning-of-line 1)
6800 (looking-at org-drawer-regexp))
6801 (org-flag-drawer ; toggle block visibility
6802 (not (get-char-property (match-end 0) 'invisible))))
6804 ;; Show-subtree, ARG levels up from here.
6805 ((integerp arg)
6806 (save-excursion
6807 (org-back-to-heading)
6808 (outline-up-heading (if (< arg 0) (- arg)
6809 (- (funcall outline-level) arg)))
6810 (org-show-subtree)))
6812 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6813 ((and (featurep 'org-inlinetask)
6814 (org-inlinetask-at-task-p)
6815 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6816 (org-inlinetask-toggle-visibility))
6818 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6819 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6820 (save-excursion (move-beginning-of-line 1)
6821 (looking-at org-outline-regexp)))
6822 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6823 (org-cycle-internal-local))
6825 ;; From there: TAB emulation and template completion.
6826 (buffer-read-only (org-back-to-heading))
6828 ((run-hook-with-args-until-success
6829 'org-tab-after-check-for-cycling-hook))
6831 ((org-try-structure-completion))
6833 ((run-hook-with-args-until-success
6834 'org-tab-before-tab-emulation-hook))
6836 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6837 (or (not (bolp))
6838 (not (looking-at org-outline-regexp))))
6839 (call-interactively (global-key-binding "\t")))
6841 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6842 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6843 (or (and (eq org-cycle-emulate-tab 'white)
6844 (= (match-end 0) (point-at-eol)))
6845 (and (eq org-cycle-emulate-tab 'whitestart)
6846 (>= (match-end 0) pos))))
6848 (eq org-cycle-emulate-tab t))
6849 (call-interactively (global-key-binding "\t")))
6851 (t (save-excursion
6852 (org-back-to-heading)
6853 (org-cycle)))))))
6855 (defun org-cycle-internal-global ()
6856 "Do the global cycling action."
6857 ;; Hack to avoid display of messages for .org attachments in Gnus
6858 (let ((ga (string-match "\\*fontification" (buffer-name))))
6859 (cond
6860 ((and (eq last-command this-command)
6861 (eq org-cycle-global-status 'overview))
6862 ;; We just created the overview - now do table of contents
6863 ;; This can be slow in very large buffers, so indicate action
6864 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6865 (unless ga (org-unlogged-message "CONTENTS..."))
6866 (org-content)
6867 (unless ga (org-unlogged-message "CONTENTS...done"))
6868 (setq org-cycle-global-status 'contents)
6869 (run-hook-with-args 'org-cycle-hook 'contents))
6871 ((and (eq last-command this-command)
6872 (eq org-cycle-global-status 'contents))
6873 ;; We just showed the table of contents - now show everything
6874 (run-hook-with-args 'org-pre-cycle-hook 'all)
6875 (outline-show-all)
6876 (unless ga (org-unlogged-message "SHOW ALL"))
6877 (setq org-cycle-global-status 'all)
6878 (run-hook-with-args 'org-cycle-hook 'all))
6881 ;; Default action: go to overview
6882 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6883 (org-overview)
6884 (unless ga (org-unlogged-message "OVERVIEW"))
6885 (setq org-cycle-global-status 'overview)
6886 (run-hook-with-args 'org-cycle-hook 'overview)))))
6888 (defvar org-called-with-limited-levels nil
6889 "Non-nil when `org-with-limited-levels' is currently active.")
6891 (defun org-invisible-p (&optional pos)
6892 "Non-nil if the character after POS is invisible.
6893 If POS is nil, use `point' instead."
6894 (get-char-property (or pos (point)) 'invisible))
6896 (defun org-cycle-internal-local ()
6897 "Do the local cycling action."
6898 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6899 ;; First, determine end of headline (EOH), end of subtree or item
6900 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6901 (save-excursion
6902 (if (org-at-item-p)
6903 (progn
6904 (beginning-of-line)
6905 (setq struct (org-list-struct))
6906 (setq eoh (point-at-eol))
6907 (setq eos (org-list-get-item-end-before-blank (point) struct))
6908 (setq has-children (org-list-has-child-p (point) struct)))
6909 (org-back-to-heading)
6910 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6911 (setq eos (save-excursion (org-end-of-subtree t t)
6912 (when (bolp) (backward-char)) (point)))
6913 (setq has-children
6914 (or (save-excursion
6915 (let ((level (funcall outline-level)))
6916 (outline-next-heading)
6917 (and (org-at-heading-p t)
6918 (> (funcall outline-level) level))))
6919 (save-excursion
6920 (org-list-search-forward (org-item-beginning-re) eos t)))))
6921 ;; Determine end invisible part of buffer (EOL)
6922 (beginning-of-line 2)
6923 (while (and (not (eobp)) ;This is like `next-line'.
6924 (get-char-property (1- (point)) 'invisible))
6925 (goto-char (next-single-char-property-change (point) 'invisible))
6926 (and (eolp) (beginning-of-line 2)))
6927 (setq eol (point)))
6928 ;; Find out what to do next and set `this-command'
6929 (cond
6930 ((= eos eoh)
6931 ;; Nothing is hidden behind this heading
6932 (unless (org-before-first-heading-p)
6933 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6934 (org-unlogged-message "EMPTY ENTRY")
6935 (setq org-cycle-subtree-status nil)
6936 (save-excursion
6937 (goto-char eos)
6938 (outline-next-heading)
6939 (when (org-invisible-p) (org-flag-heading nil))))
6940 ((and (or (>= eol eos)
6941 (not (string-match "\\S-" (buffer-substring eol eos))))
6942 (or has-children
6943 (not (setq children-skipped
6944 org-cycle-skip-children-state-if-no-children))))
6945 ;; Entire subtree is hidden in one line: children view
6946 (unless (org-before-first-heading-p)
6947 (run-hook-with-args 'org-pre-cycle-hook 'children))
6948 (if (org-at-item-p)
6949 (org-list-set-item-visibility (point-at-bol) struct 'children)
6950 (org-show-entry)
6951 (org-with-limited-levels (org-show-children))
6952 ;; FIXME: This slows down the func way too much.
6953 ;; How keep drawers hidden in subtree anyway?
6954 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6955 ;; (org-cycle-hide-drawers 'subtree))
6957 ;; Fold every list in subtree to top-level items.
6958 (when (eq org-cycle-include-plain-lists 'integrate)
6959 (save-excursion
6960 (org-back-to-heading)
6961 (while (org-list-search-forward (org-item-beginning-re) eos t)
6962 (beginning-of-line 1)
6963 (let* ((struct (org-list-struct))
6964 (prevs (org-list-prevs-alist struct))
6965 (end (org-list-get-bottom-point struct)))
6966 (dolist (e (org-list-get-all-items (point) struct prevs))
6967 (org-list-set-item-visibility e struct 'folded))
6968 (goto-char (if (< end eos) end eos)))))))
6969 (org-unlogged-message "CHILDREN")
6970 (save-excursion
6971 (goto-char eos)
6972 (outline-next-heading)
6973 (when (org-invisible-p) (org-flag-heading nil)))
6974 (setq org-cycle-subtree-status 'children)
6975 (unless (org-before-first-heading-p)
6976 (run-hook-with-args 'org-cycle-hook 'children)))
6977 ((or children-skipped
6978 (and (eq last-command this-command)
6979 (eq org-cycle-subtree-status 'children)))
6980 ;; We just showed the children, or no children are there,
6981 ;; now show everything.
6982 (unless (org-before-first-heading-p)
6983 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6984 (outline-flag-region eoh eos nil)
6985 (org-unlogged-message
6986 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6987 (setq org-cycle-subtree-status 'subtree)
6988 (unless (org-before-first-heading-p)
6989 (run-hook-with-args 'org-cycle-hook 'subtree)))
6991 ;; Default action: hide the subtree.
6992 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6993 (outline-flag-region eoh eos t)
6994 (org-unlogged-message "FOLDED")
6995 (setq org-cycle-subtree-status 'folded)
6996 (unless (org-before-first-heading-p)
6997 (run-hook-with-args 'org-cycle-hook 'folded))))))
6999 ;;;###autoload
7000 (defun org-global-cycle (&optional arg)
7001 "Cycle the global visibility. For details see `org-cycle'.
7002 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7003 With a numeric prefix, show all headlines up to that level."
7004 (interactive "P")
7005 (let ((org-cycle-include-plain-lists
7006 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7007 (cond
7008 ((integerp arg)
7009 (outline-show-all)
7010 (outline-hide-sublevels arg)
7011 (setq org-cycle-global-status 'contents))
7012 ((equal arg '(4))
7013 (org-set-startup-visibility)
7014 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7016 (org-cycle '(4))))))
7018 (defun org-set-startup-visibility ()
7019 "Set the visibility required by startup options and properties."
7020 (cond
7021 ((eq org-startup-folded t)
7022 (org-overview))
7023 ((eq org-startup-folded 'content)
7024 (org-content))
7025 ((or (eq org-startup-folded 'showeverything)
7026 (eq org-startup-folded nil))
7027 (outline-show-all)))
7028 (unless (eq org-startup-folded 'showeverything)
7029 (when org-hide-block-startup (org-hide-block-all))
7030 (org-set-visibility-according-to-property 'no-cleanup)
7031 (org-cycle-hide-archived-subtrees 'all)
7032 (org-cycle-hide-drawers 'all)
7033 (org-cycle-show-empty-lines t)))
7035 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7036 "Switch subtree visibilities according to :VISIBILITY: property."
7037 (interactive)
7038 (org-with-wide-buffer
7039 (goto-char (point-min))
7040 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7041 (if (not (org-at-property-p)) (outline-next-heading)
7042 (let ((state (match-string 3)))
7043 (save-excursion
7044 (org-back-to-heading t)
7045 (outline-hide-subtree)
7046 (org-reveal)
7047 (cond
7048 ((equal state "folded")
7049 (outline-hide-subtree))
7050 ((equal state "children")
7051 (org-show-hidden-entry)
7052 (org-show-children))
7053 ((equal state "content")
7054 (save-excursion
7055 (save-restriction
7056 (org-narrow-to-subtree)
7057 (org-content))))
7058 ((member state '("all" "showall"))
7059 (outline-show-subtree)))))))
7060 (unless no-cleanup
7061 (org-cycle-hide-archived-subtrees 'all)
7062 (org-cycle-hide-drawers 'all)
7063 (org-cycle-show-empty-lines 'all))))
7065 ;; This function uses outline-regexp instead of the more fundamental
7066 ;; org-outline-regexp so that org-cycle-global works outside of Org
7067 ;; buffers, where outline-regexp is needed.
7068 (defun org-overview ()
7069 "Switch to overview mode, showing only top-level headlines.
7070 This shows all headlines with a level equal or greater than the level
7071 of the first headline in the buffer. This is important, because if the
7072 first headline is not level one, then (hide-sublevels 1) gives confusing
7073 results."
7074 (interactive)
7075 (save-excursion
7076 (let ((level
7077 (save-excursion
7078 (goto-char (point-min))
7079 (when (re-search-forward (concat "^" outline-regexp) nil t)
7080 (goto-char (match-beginning 0))
7081 (funcall outline-level)))))
7082 (and level (outline-hide-sublevels level)))))
7084 (defun org-content (&optional arg)
7085 "Show all headlines in the buffer, like a table of contents.
7086 With numerical argument N, show content up to level N."
7087 (interactive "P")
7088 (org-overview)
7089 (save-excursion
7090 ;; Visit all headings and show their offspring
7091 (and (integerp arg) (org-overview))
7092 (goto-char (point-max))
7093 (catch 'exit
7094 (while (and (progn (condition-case nil
7095 (outline-previous-visible-heading 1)
7096 (error (goto-char (point-min))))
7098 (looking-at org-outline-regexp))
7099 (if (integerp arg)
7100 (org-show-children (1- arg))
7101 (outline-show-branches))
7102 (when (bobp) (throw 'exit nil))))))
7104 (defun org-optimize-window-after-visibility-change (state)
7105 "Adjust the window after a change in outline visibility.
7106 This function is the default value of the hook `org-cycle-hook'."
7107 (when (get-buffer-window (current-buffer))
7108 (cond
7109 ((eq state 'content) nil)
7110 ((eq state 'all) nil)
7111 ((eq state 'folded) nil)
7112 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7113 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7115 (defun org-remove-empty-overlays-at (pos)
7116 "Remove outline overlays that do not contain non-white stuff."
7117 (dolist (o (overlays-at pos))
7118 (and (eq 'outline (overlay-get o 'invisible))
7119 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7120 (overlay-end o))))
7121 (delete-overlay o))))
7123 (defun org-clean-visibility-after-subtree-move ()
7124 "Fix visibility issues after moving a subtree."
7125 ;; First, find a reasonable region to look at:
7126 ;; Start two siblings above, end three below
7127 (let* ((beg (save-excursion
7128 (and (org-get-last-sibling)
7129 (org-get-last-sibling))
7130 (point)))
7131 (end (save-excursion
7132 (and (org-get-next-sibling)
7133 (org-get-next-sibling)
7134 (org-get-next-sibling))
7135 (if (org-at-heading-p)
7136 (point-at-eol)
7137 (point))))
7138 (level (looking-at "\\*+"))
7139 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7140 (save-excursion
7141 (save-restriction
7142 (narrow-to-region beg end)
7143 (when re
7144 ;; Properly fold already folded siblings
7145 (goto-char (point-min))
7146 (while (re-search-forward re nil t)
7147 (when (and (not (org-invisible-p))
7148 (save-excursion
7149 (goto-char (point-at-eol)) (org-invisible-p)))
7150 (outline-hide-entry))))
7151 (org-cycle-show-empty-lines 'overview)
7152 (org-cycle-hide-drawers 'overview)))))
7154 (defun org-cycle-show-empty-lines (state)
7155 "Show empty lines above all visible headlines.
7156 The region to be covered depends on STATE when called through
7157 `org-cycle-hook'. Lisp program can use t for STATE to get the
7158 entire buffer covered. Note that an empty line is only shown if there
7159 are at least `org-cycle-separator-lines' empty lines before the headline."
7160 (when (/= org-cycle-separator-lines 0)
7161 (save-excursion
7162 (let* ((n (abs org-cycle-separator-lines))
7163 (re (cond
7164 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7165 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7166 (t (let ((ns (number-to-string (- n 2))))
7167 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7168 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7169 beg end)
7170 (cond
7171 ((memq state '(overview contents t))
7172 (setq beg (point-min) end (point-max)))
7173 ((memq state '(children folded))
7174 (setq beg (point)
7175 end (progn (org-end-of-subtree t t)
7176 (line-beginning-position 2)))))
7177 (when beg
7178 (goto-char beg)
7179 (while (re-search-forward re end t)
7180 (unless (get-char-property (match-end 1) 'invisible)
7181 (let ((e (match-end 1))
7182 (b (if (>= org-cycle-separator-lines 0)
7183 (match-beginning 1)
7184 (save-excursion
7185 (goto-char (match-beginning 0))
7186 (skip-chars-backward " \t\n")
7187 (line-end-position)))))
7188 (outline-flag-region b e nil))))))))
7189 ;; Never hide empty lines at the end of the file.
7190 (save-excursion
7191 (goto-char (point-max))
7192 (outline-previous-heading)
7193 (outline-end-of-heading)
7194 (when (and (looking-at "[ \t\n]+")
7195 (= (match-end 0) (point-max)))
7196 (outline-flag-region (point) (match-end 0) nil))))
7198 (defun org-show-empty-lines-in-parent ()
7199 "Move to the parent and re-show empty lines before visible headlines."
7200 (save-excursion
7201 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7202 (org-cycle-show-empty-lines context))))
7204 (defun org-files-list ()
7205 "Return `org-agenda-files' list, plus all open Org files.
7206 This is useful for operations that need to scan all of a user's
7207 open and agenda-wise Org files."
7208 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7209 (dolist (buf (buffer-list))
7210 (with-current-buffer buf
7211 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7212 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7213 files))
7215 (defsubst org-entry-beginning-position ()
7216 "Return the beginning position of the current entry."
7217 (save-excursion (org-back-to-heading t) (point)))
7219 (defsubst org-entry-end-position ()
7220 "Return the end position of the current entry."
7221 (save-excursion (outline-next-heading) (point)))
7223 (defun org-cycle-hide-drawers (state &optional exceptions)
7224 "Re-hide all drawers after a visibility state change.
7225 STATE should be one of the symbols listed in the docstring of
7226 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7227 a list of strings specifying which drawers should not be hidden."
7228 (when (and (derived-mode-p 'org-mode)
7229 (not (memq state '(overview folded contents))))
7230 (save-excursion
7231 (let* ((globalp (eq state 'all))
7232 (beg (if globalp (point-min) (point)))
7233 (end (if globalp (point-max)
7234 (if (eq state 'children)
7235 (save-excursion (outline-next-heading) (point))
7236 (org-end-of-subtree t)))))
7237 (goto-char beg)
7238 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7239 (unless (member-ignore-case (match-string 1) exceptions)
7240 (let ((drawer (org-element-at-point)))
7241 (when (memq (org-element-type drawer) '(drawer property-drawer))
7242 (org-flag-drawer t drawer)
7243 ;; Make sure to skip drawer entirely or we might flag
7244 ;; it another time when matching its ending line with
7245 ;; `org-drawer-regexp'.
7246 (goto-char (org-element-property :end drawer))))))))))
7248 (defun org-flag-drawer (flag &optional element)
7249 "When FLAG is non-nil, hide the drawer we are at.
7250 Otherwise make it visible. When optional argument ELEMENT is
7251 a parsed drawer, as returned by `org-element-at-point', hide or
7252 show that drawer instead."
7253 (let ((drawer (or element
7254 (and (save-excursion
7255 (beginning-of-line)
7256 (looking-at-p org-drawer-regexp))
7257 (org-element-at-point)))))
7258 (when (memq (org-element-type drawer) '(drawer property-drawer))
7259 (let ((post (org-element-property :post-affiliated drawer)))
7260 (save-excursion
7261 (outline-flag-region
7262 (progn (goto-char post) (line-end-position))
7263 (progn (goto-char (org-element-property :end drawer))
7264 (skip-chars-backward " \r\t\n")
7265 (line-end-position))
7266 flag))
7267 ;; When the drawer is hidden away, make sure point lies in
7268 ;; a visible part of the buffer.
7269 (when (and flag (> (line-beginning-position) post))
7270 (goto-char post))))))
7272 (defun org-subtree-end-visible-p ()
7273 "Is the end of the current subtree visible?"
7274 (pos-visible-in-window-p
7275 (save-excursion (org-end-of-subtree t) (point))))
7277 (defun org-first-headline-recenter ()
7278 "Move cursor to the first headline and recenter the headline."
7279 (let ((window (get-buffer-window)))
7280 (when window
7281 (goto-char (point-min))
7282 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7283 (set-window-start window (line-beginning-position))))))
7285 ;;; Saving and restoring visibility
7287 (defun org-outline-overlay-data (&optional use-markers)
7288 "Return a list of the locations of all outline overlays.
7289 These are overlays with the `invisible' property value `outline'.
7290 The return value is a list of cons cells, with start and stop
7291 positions for each overlay.
7292 If USE-MARKERS is set, return the positions as markers."
7293 (let (beg end)
7294 (org-with-wide-buffer
7295 (delq nil
7296 (mapcar (lambda (o)
7297 (when (eq (overlay-get o 'invisible) 'outline)
7298 (setq beg (overlay-start o)
7299 end (overlay-end o))
7300 (and beg end (> end beg)
7301 (if use-markers
7302 (cons (copy-marker beg)
7303 (copy-marker end t))
7304 (cons beg end)))))
7305 (overlays-in (point-min) (point-max)))))))
7307 (defun org-set-outline-overlay-data (data)
7308 "Create visibility overlays for all positions in DATA.
7309 DATA should have been made by `org-outline-overlay-data'."
7310 (org-with-wide-buffer
7311 (outline-show-all)
7312 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7314 ;;; Folding of blocks
7316 (defvar-local org-hide-block-overlays nil
7317 "Overlays hiding blocks.")
7319 (defun org-block-map (function &optional start end)
7320 "Call FUNCTION at the head of all source blocks in the current buffer.
7321 Optional arguments START and END can be used to limit the range."
7322 (let ((start (or start (point-min)))
7323 (end (or end (point-max))))
7324 (save-excursion
7325 (goto-char start)
7326 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7327 (save-excursion
7328 (save-match-data
7329 (goto-char (match-beginning 0))
7330 (funcall function)))))))
7332 (defun org-hide-block-toggle-all ()
7333 "Toggle the visibility of all blocks in the current buffer."
7334 (org-block-map 'org-hide-block-toggle))
7336 (defun org-hide-block-all ()
7337 "Fold all blocks in the current buffer."
7338 (interactive)
7339 (org-show-block-all)
7340 (org-block-map 'org-hide-block-toggle-maybe))
7342 (defun org-show-block-all ()
7343 "Unfold all blocks in the current buffer."
7344 (interactive)
7345 (mapc #'delete-overlay org-hide-block-overlays)
7346 (setq org-hide-block-overlays nil))
7348 (defun org-hide-block-toggle-maybe ()
7349 "Toggle visibility of block at point.
7350 Unlike to `org-hide-block-toggle', this function does not throw
7351 an error. Return a non-nil value when toggling is successful."
7352 (interactive)
7353 (ignore-errors (org-hide-block-toggle)))
7355 (defun org-hide-block-toggle (&optional force)
7356 "Toggle the visibility of the current block.
7357 When optional argument FORCE is `off', make block visible. If it
7358 is non-nil, hide it unconditionally. Throw an error when not at
7359 a block. Return a non-nil value when toggling is successful."
7360 (interactive)
7361 (let ((element (org-element-at-point)))
7362 (unless (memq (org-element-type element)
7363 '(center-block comment-block dynamic-block example-block
7364 export-block quote-block special-block
7365 src-block verse-block))
7366 (user-error "Not at a block"))
7367 (let* ((start (save-excursion
7368 (goto-char (org-element-property :post-affiliated element))
7369 (line-end-position)))
7370 (end (save-excursion
7371 (goto-char (org-element-property :end element))
7372 (skip-chars-backward " \r\t\n")
7373 (line-end-position)))
7374 (overlays (overlays-at start)))
7375 (cond
7376 ;; Do nothing when not before or at the block opening line or
7377 ;; at the block closing line.
7378 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7379 ((and (not (eq force 'off))
7380 (not (memq t (mapcar
7381 (lambda (o)
7382 (eq (overlay-get o 'invisible) 'org-hide-block))
7383 overlays))))
7384 (let ((ov (make-overlay start end)))
7385 (overlay-put ov 'invisible 'org-hide-block)
7386 ;; Make the block accessible to `isearch'.
7387 (overlay-put
7388 ov 'isearch-open-invisible
7389 (lambda (ov)
7390 (when (memq ov org-hide-block-overlays)
7391 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7392 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7393 (delete-overlay ov))))
7394 (push ov org-hide-block-overlays)
7395 ;; When the block is hidden away, make sure point is left in
7396 ;; a visible part of the buffer.
7397 (when (> (line-beginning-position) start)
7398 (goto-char start)
7399 (beginning-of-line))
7400 ;; Signal successful toggling.
7402 ((or (not force) (eq force 'off))
7403 (dolist (ov overlays t)
7404 (when (memq ov org-hide-block-overlays)
7405 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7406 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7407 (delete-overlay ov))))))))
7409 ;; Remove overlays when changing major mode
7410 (add-hook 'org-mode-hook
7411 (lambda () (add-hook 'change-major-mode-hook
7412 'org-show-block-all 'append 'local)))
7414 ;;; Org-goto
7416 (defvar org-goto-window-configuration nil)
7417 (defvar org-goto-marker nil)
7418 (defvar org-goto-map)
7419 (defun org-goto-map ()
7420 "Set the keymap `org-goto'."
7421 (setq org-goto-map
7422 (let ((map (make-sparse-keymap)))
7423 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7424 mouse-drag-region universal-argument org-occur)))
7425 (dolist (cmd cmds)
7426 (substitute-key-definition cmd cmd map global-map)))
7427 (suppress-keymap map)
7428 (org-defkey map "\C-m" 'org-goto-ret)
7429 (org-defkey map [(return)] 'org-goto-ret)
7430 (org-defkey map [(left)] 'org-goto-left)
7431 (org-defkey map [(right)] 'org-goto-right)
7432 (org-defkey map [(control ?g)] 'org-goto-quit)
7433 (org-defkey map "\C-i" 'org-cycle)
7434 (org-defkey map [(tab)] 'org-cycle)
7435 (org-defkey map [(down)] 'outline-next-visible-heading)
7436 (org-defkey map [(up)] 'outline-previous-visible-heading)
7437 (if org-goto-auto-isearch
7438 (if (fboundp 'define-key-after)
7439 (define-key-after map [t] 'org-goto-local-auto-isearch)
7440 nil)
7441 (org-defkey map "q" 'org-goto-quit)
7442 (org-defkey map "n" 'outline-next-visible-heading)
7443 (org-defkey map "p" 'outline-previous-visible-heading)
7444 (org-defkey map "f" 'outline-forward-same-level)
7445 (org-defkey map "b" 'outline-backward-same-level)
7446 (org-defkey map "u" 'outline-up-heading))
7447 (org-defkey map "/" 'org-occur)
7448 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7449 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7450 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7451 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7452 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7453 map)))
7455 (defconst org-goto-help
7456 "Browse buffer copy, to find location or copy text.%s
7457 RET=jump to location C-g=quit and return to previous location
7458 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7460 (defvar org-goto-start-pos) ; dynamically scoped parameter
7462 (defun org-goto (&optional alternative-interface)
7463 "Look up a different location in the current file, keeping current visibility.
7465 When you want look-up or go to a different location in a
7466 document, the fastest way is often to fold the entire buffer and
7467 then dive into the tree. This method has the disadvantage, that
7468 the previous location will be folded, which may not be what you
7469 want.
7471 This command works around this by showing a copy of the current
7472 buffer in an indirect buffer, in overview mode. You can dive
7473 into the tree in that copy, use org-occur and incremental search
7474 to find a location. When pressing RET or `Q', the command
7475 returns to the original buffer in which the visibility is still
7476 unchanged. After RET it will also jump to the location selected
7477 in the indirect buffer and expose the headline hierarchy above.
7479 With a prefix argument, use the alternative interface: e.g., if
7480 `org-goto-interface' is `outline' use `outline-path-completion'."
7481 (interactive "P")
7482 (org-goto-map)
7483 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7484 (org-refile-use-outline-path t)
7485 (org-refile-target-verify-function nil)
7486 (interface
7487 (if (not alternative-interface)
7488 org-goto-interface
7489 (if (eq org-goto-interface 'outline)
7490 'outline-path-completion
7491 'outline)))
7492 (org-goto-start-pos (point))
7493 (selected-point
7494 (if (eq interface 'outline)
7495 (car (org-get-location (current-buffer) org-goto-help))
7496 (let ((pa (org-refile-get-location "Goto")))
7497 (org-refile-check-position pa)
7498 (nth 3 pa)))))
7499 (if selected-point
7500 (progn
7501 (org-mark-ring-push org-goto-start-pos)
7502 (goto-char selected-point)
7503 (when (or (org-invisible-p) (org-invisible-p2))
7504 (org-show-context 'org-goto)))
7505 (message "Quit"))))
7507 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7508 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7509 (defvar org-goto-local-auto-isearch-map) ; defined below
7511 (defun org-get-location (_buf help)
7512 "Let the user select a location in current buffer.
7513 This function uses a recursive edit. It returns the selected position
7514 or nil."
7515 (org-no-popups
7516 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7517 (isearch-hide-immediately nil)
7518 (isearch-search-fun-function
7519 (lambda () 'org-goto-local-search-headings))
7520 (org-goto-selected-point org-goto-exit-command))
7521 (save-excursion
7522 (save-window-excursion
7523 (delete-other-windows)
7524 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7525 (pop-to-buffer-same-window
7526 (condition-case nil
7527 (make-indirect-buffer (current-buffer) "*org-goto*")
7528 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7529 (with-output-to-temp-buffer "*Org Help*"
7530 (princ (format help (if org-goto-auto-isearch
7531 " Just type for auto-isearch."
7532 " n/p/f/b/u to navigate, q to quit."))))
7533 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7534 (setq buffer-read-only nil)
7535 (let ((org-startup-truncated t)
7536 (org-startup-folded nil)
7537 (org-startup-align-all-tables nil))
7538 (org-mode)
7539 (org-overview))
7540 (setq buffer-read-only t)
7541 (if (and (boundp 'org-goto-start-pos)
7542 (integer-or-marker-p org-goto-start-pos))
7543 (progn (goto-char org-goto-start-pos)
7544 (when (org-invisible-p)
7545 (org-show-set-visibility 'lineage)))
7546 (goto-char (point-min)))
7547 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7548 (message "Select location and press RET")
7549 (use-local-map org-goto-map)
7550 (recursive-edit)))
7551 (kill-buffer "*org-goto*")
7552 (cons org-goto-selected-point org-goto-exit-command))))
7554 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7555 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7556 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7557 (if (fboundp 'isearch-other-control-char)
7558 (progn
7559 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7560 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7561 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7562 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7563 (define-key org-goto-local-auto-isearch-map [return] nil))
7565 (defun org-goto-local-search-headings (string bound noerror)
7566 "Search and make sure that any matches are in headlines."
7567 (catch 'return
7568 (while (if isearch-forward
7569 (search-forward string bound noerror)
7570 (search-backward string bound noerror))
7571 (when (save-match-data
7572 (and (save-excursion
7573 (beginning-of-line)
7574 (looking-at org-complex-heading-regexp))
7575 (or (not (match-beginning 5))
7576 (< (point) (match-beginning 5)))))
7577 (throw 'return (point))))))
7579 (defun org-goto-local-auto-isearch ()
7580 "Start isearch."
7581 (interactive)
7582 (goto-char (point-min))
7583 (let ((keys (this-command-keys)))
7584 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7585 (isearch-mode t)
7586 (isearch-process-search-char (string-to-char keys)))))
7588 (defun org-goto-ret (&optional _arg)
7589 "Finish `org-goto' by going to the new location."
7590 (interactive "P")
7591 (setq org-goto-selected-point (point))
7592 (setq org-goto-exit-command 'return)
7593 (throw 'exit nil))
7595 (defun org-goto-left ()
7596 "Finish `org-goto' by going to the new location."
7597 (interactive)
7598 (if (org-at-heading-p)
7599 (progn
7600 (beginning-of-line 1)
7601 (setq org-goto-selected-point (point)
7602 org-goto-exit-command 'left)
7603 (throw 'exit nil))
7604 (user-error "Not on a heading")))
7606 (defun org-goto-right ()
7607 "Finish `org-goto' by going to the new location."
7608 (interactive)
7609 (if (org-at-heading-p)
7610 (progn
7611 (setq org-goto-selected-point (point)
7612 org-goto-exit-command 'right)
7613 (throw 'exit nil))
7614 (user-error "Not on a heading")))
7616 (defun org-goto-quit ()
7617 "Finish `org-goto' without cursor motion."
7618 (interactive)
7619 (setq org-goto-selected-point nil)
7620 (setq org-goto-exit-command 'quit)
7621 (throw 'exit nil))
7623 ;;; Indirect buffer display of subtrees
7625 (defvar org-indirect-dedicated-frame nil
7626 "This is the frame being used for indirect tree display.")
7627 (defvar org-last-indirect-buffer nil)
7629 (defun org-tree-to-indirect-buffer (&optional arg)
7630 "Create indirect buffer and narrow it to current subtree.
7632 With a numerical prefix ARG, go up to this level and then take that tree.
7633 If ARG is negative, go up that many levels.
7635 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7636 indirect buffer previously made with this command, to avoid proliferation of
7637 indirect buffers. However, when you call the command with a \
7638 `\\[universal-argument]' prefix, or
7639 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7640 so that you can work with several indirect buffers at the same time. If
7641 `org-indirect-buffer-display' is `dedicated-frame', the \
7642 `\\[universal-argument]' prefix also
7643 requests that a new frame be made for the new buffer, so that the dedicated
7644 frame is not changed."
7645 (interactive "P")
7646 (let ((cbuf (current-buffer))
7647 (cwin (selected-window))
7648 (pos (point))
7649 beg end level heading ibuf)
7650 (save-excursion
7651 (org-back-to-heading t)
7652 (when (numberp arg)
7653 (setq level (org-outline-level))
7654 (when (< arg 0) (setq arg (+ level arg)))
7655 (while (> (setq level (org-outline-level)) arg)
7656 (org-up-heading-safe)))
7657 (setq beg (point)
7658 heading (org-get-heading 'no-tags))
7659 (org-end-of-subtree t t)
7660 (when (org-at-heading-p) (backward-char 1))
7661 (setq end (point)))
7662 (when (and (buffer-live-p org-last-indirect-buffer)
7663 (not (eq org-indirect-buffer-display 'new-frame))
7664 (not arg))
7665 (kill-buffer org-last-indirect-buffer))
7666 (setq ibuf (org-get-indirect-buffer cbuf heading)
7667 org-last-indirect-buffer ibuf)
7668 (cond
7669 ((or (eq org-indirect-buffer-display 'new-frame)
7670 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7671 (select-frame (make-frame))
7672 (delete-other-windows)
7673 (pop-to-buffer-same-window ibuf)
7674 (org-set-frame-title heading))
7675 ((eq org-indirect-buffer-display 'dedicated-frame)
7676 (raise-frame
7677 (select-frame (or (and org-indirect-dedicated-frame
7678 (frame-live-p org-indirect-dedicated-frame)
7679 org-indirect-dedicated-frame)
7680 (setq org-indirect-dedicated-frame (make-frame)))))
7681 (delete-other-windows)
7682 (pop-to-buffer-same-window ibuf)
7683 (org-set-frame-title (concat "Indirect: " heading)))
7684 ((eq org-indirect-buffer-display 'current-window)
7685 (pop-to-buffer-same-window ibuf))
7686 ((eq org-indirect-buffer-display 'other-window)
7687 (pop-to-buffer ibuf))
7688 (t (error "Invalid value")))
7689 (narrow-to-region beg end)
7690 (outline-show-all)
7691 (goto-char pos)
7692 (run-hook-with-args 'org-cycle-hook 'all)
7693 (and (window-live-p cwin) (select-window cwin))))
7695 (defun org-get-indirect-buffer (&optional buffer heading)
7696 (setq buffer (or buffer (current-buffer)))
7697 (let ((n 1) (base (buffer-name buffer)) bname)
7698 (while (buffer-live-p
7699 (get-buffer
7700 (setq bname
7701 (concat base "-"
7702 (if heading (concat heading "-" (number-to-string n))
7703 (number-to-string n))))))
7704 (setq n (1+ n)))
7705 (condition-case nil
7706 (make-indirect-buffer buffer bname 'clone)
7707 (error (make-indirect-buffer buffer bname)))))
7709 (defun org-set-frame-title (title)
7710 "Set the title of the current frame to the string TITLE."
7711 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7713 ;;;; Structure editing
7715 ;;; Inserting headlines
7717 (defun org--line-empty-p (n)
7718 "Is the Nth next line empty?
7720 Counts the current line as N = 1 and the previous line as N = 0;
7721 see `beginning-of-line'."
7722 (save-excursion
7723 (and (not (bobp))
7724 (or (beginning-of-line n) t)
7725 (save-match-data
7726 (looking-at "[ \t]*$")))))
7728 (defun org-previous-line-empty-p ()
7729 "Is the previous line a blank line?
7730 When NEXT is non-nil, check the next line instead."
7731 (org--line-empty-p 0))
7733 (defun org-next-line-empty-p ()
7734 "Is the previous line a blank line?
7735 When NEXT is non-nil, check the next line instead."
7736 (org--line-empty-p 2))
7738 (defun org--blank-before-heading-p (&optional parent)
7739 "Non-nil when an empty line should precede a new heading here.
7740 When optional argument PARENT is non-nil, consider parent
7741 headline instead of current one."
7742 (pcase (assq 'heading org-blank-before-new-entry)
7743 (`(heading . auto)
7744 (save-excursion
7745 (org-with-limited-levels
7746 (unless (and (org-before-first-heading-p)
7747 (not (outline-next-heading)))
7748 (org-back-to-heading t)
7749 (when parent (org-up-heading-safe))
7750 (cond ((not (bobp))
7751 (org-previous-line-empty-p))
7752 ((outline-next-heading)
7753 (org-previous-line-empty-p))
7754 ;; Ignore trailing spaces on last buffer line.
7755 ((progn (skip-chars-backward " \t") (bolp))
7756 (org-previous-line-empty-p))
7757 (t nil))))))
7758 (`(heading . ,value) value)
7759 (_ nil)))
7761 (defun org-insert-heading (&optional arg invisible-ok top)
7762 "Insert a new heading or an item with the same depth at point.
7764 If point is at the beginning of a heading, insert a new heading
7765 or a new headline above the current one. When at the beginning
7766 of a regular line of text, turn it into a heading.
7768 If point is in the middle of a line, split it and create a new
7769 headline with the text in the current line after point (see
7770 `org-M-RET-may-split-line' on how to modify this behavior). As
7771 a special case, on a headline, splitting can only happen on the
7772 title itself. E.g., this excludes breaking stars or tags.
7774 With a `\\[universal-argument]' prefix, set \
7775 `org-insert-heading-respect-content' to
7776 a non-nil value for the duration of the command. This forces the
7777 insertion of a heading after the current subtree, independently
7778 on the location of point.
7780 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7781 insert the heading at the end of the tree
7782 above the current heading. For example, if point is within a
7783 2nd-level heading, then it will insert a 2nd-level heading at
7784 the end of the 1st-level parent subtree.
7786 When INVISIBLE-OK is set, stop at invisible headlines when going
7787 back. This is important for non-interactive uses of the
7788 command.
7790 When optional argument TOP is non-nil, insert a level 1 heading,
7791 unconditionally."
7792 (interactive "P")
7793 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7794 (level (org-current-level))
7795 (stars (make-string (if (and level (not top)) level 1) ?*)))
7796 (cond
7797 ((or org-insert-heading-respect-content
7798 (member arg '((4) (16)))
7799 (and (not invisible-ok)
7800 (invisible-p (max (1- (point)) (point-min)))))
7801 ;; Position point at the location of insertion.
7802 (if (not level) ;before first headline
7803 (org-with-limited-levels (outline-next-heading))
7804 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7805 ;; is nil.
7806 (org-with-limited-levels (org-back-to-heading invisible-ok))
7807 (cond ((equal arg '(16))
7808 (org-up-heading-safe)
7809 (org-end-of-subtree t t))
7811 (org-end-of-subtree t t))))
7812 (unless (bolp) (insert "\n")) ;ensure final newline
7813 (unless (and blank? (org-previous-line-empty-p))
7814 (org-N-empty-lines-before-current (if blank? 1 0)))
7815 (insert stars " \n")
7816 (forward-char -1))
7817 ;; At a headline...
7818 ((org-at-heading-p)
7819 (cond ((bolp)
7820 (when blank? (save-excursion (insert "\n")))
7821 (save-excursion (insert stars " \n"))
7822 (unless (and blank? (org-previous-line-empty-p))
7823 (org-N-empty-lines-before-current (if blank? 1 0)))
7824 (end-of-line))
7825 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7826 (org-match-line org-complex-heading-regexp)
7827 (org-pos-in-match-range (point) 4))
7828 ;; Grab the text that should moved to the new headline.
7829 ;; Preserve tags.
7830 (let ((split (delete-and-extract-region (point) (match-end 4))))
7831 (if (looking-at "[ \t]*$") (replace-match "")
7832 (org-set-tags nil t))
7833 (end-of-line)
7834 (when blank? (insert "\n"))
7835 (insert "\n" stars " ")
7836 (when (org-string-nw-p split) (insert split))
7837 (when (eobp) (save-excursion (insert "\n")))))
7839 (end-of-line)
7840 (when blank? (insert "\n"))
7841 (insert "\n" stars " ")
7842 (when (eobp) (save-excursion (insert "\n"))))))
7843 ;; On regular text, turn line into a headline or split, if
7844 ;; appropriate.
7845 ((bolp)
7846 (insert stars " ")
7847 (unless (and blank? (org-previous-line-empty-p))
7848 (org-N-empty-lines-before-current (if blank? 1 0))))
7850 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7851 (end-of-line))
7852 (insert "\n" stars " ")
7853 (unless (and blank? (org-previous-line-empty-p))
7854 (org-N-empty-lines-before-current (if blank? 1 0))))))
7855 (run-hooks 'org-insert-heading-hook))
7857 (defun org-N-empty-lines-before-current (n)
7858 "Make the number of empty lines before current exactly N.
7859 So this will delete or add empty lines."
7860 (let ((column (current-column)))
7861 (beginning-of-line)
7862 (unless (bobp)
7863 (let ((start (save-excursion
7864 (skip-chars-backward " \r\t\n")
7865 (line-end-position))))
7866 (delete-region start (line-end-position 0))))
7867 (insert (make-string n ?\n))
7868 (move-to-column column)))
7870 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7871 "Return the heading of the current entry, without the stars.
7872 When NO-TAGS is non-nil, don't include tags.
7873 When NO-TODO is non-nil, don't include TODO keywords.
7874 When NO-PRIORITY is non-nil, don't include priority cookie.
7875 When NO-COMMENT is non-nil, don't include COMMENT string."
7876 (save-excursion
7877 (org-back-to-heading t)
7878 (let ((case-fold-search nil))
7879 (looking-at org-complex-heading-regexp)
7880 (let ((todo (and (not no-todo) (match-string 2)))
7881 (priority (and (not no-priority) (match-string 3)))
7882 (headline (pcase (match-string 4)
7883 (`nil "")
7884 ((and (guard no-comment) h)
7885 (replace-regexp-in-string
7886 (eval-when-compile
7887 (format "\\`%s[ \t]+" org-comment-string))
7888 "" h))
7889 (h h)))
7890 (tags (and (not no-tags) (match-string 5))))
7891 (mapconcat #'identity
7892 (delq nil (list todo priority headline tags))
7893 " ")))))
7895 (defvar orgstruct-mode) ; defined below
7897 (defun org-heading-components ()
7898 "Return the components of the current heading.
7899 This is a list with the following elements:
7900 - the level as an integer
7901 - the reduced level, different if `org-odd-levels-only' is set.
7902 - the TODO keyword, or nil
7903 - the priority character, like ?A, or nil if no priority is given
7904 - the headline text itself, or the tags string if no headline text
7905 - the tags string, or nil."
7906 (save-excursion
7907 (org-back-to-heading t)
7908 (when (let (case-fold-search)
7909 (looking-at
7910 (if orgstruct-mode
7911 org-heading-regexp
7912 org-complex-heading-regexp)))
7913 (if orgstruct-mode
7914 (list (length (match-string 1))
7915 (org-reduced-level (length (match-string 1)))
7918 (match-string 2)
7919 nil)
7920 (list (length (match-string 1))
7921 (org-reduced-level (length (match-string 1)))
7922 (match-string-no-properties 2)
7923 (and (match-end 3) (aref (match-string 3) 2))
7924 (match-string-no-properties 4)
7925 (match-string-no-properties 5))))))
7927 (defun org-get-entry ()
7928 "Get the entry text, after heading, entire subtree."
7929 (save-excursion
7930 (org-back-to-heading t)
7931 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7933 (defun org-edit-headline (&optional heading)
7934 "Edit the current headline.
7935 Set it to HEADING when provided."
7936 (interactive)
7937 (org-with-wide-buffer
7938 (org-back-to-heading t)
7939 (let ((case-fold-search nil))
7940 (when (looking-at org-complex-heading-regexp)
7941 (let* ((old (match-string-no-properties 4))
7942 (new (save-match-data
7943 (org-trim (or heading (read-string "Edit: " old))))))
7944 (unless (equal old new)
7945 (if old (replace-match new t t nil 4)
7946 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7947 (insert " " new))
7948 (org-set-tags nil t)
7949 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7951 (defun org-insert-heading-after-current ()
7952 "Insert a new heading with same level as current, after current subtree."
7953 (interactive)
7954 (org-back-to-heading)
7955 (org-insert-heading)
7956 (org-move-subtree-down)
7957 (end-of-line 1))
7959 (defun org-insert-heading-respect-content (&optional invisible-ok)
7960 "Insert heading with `org-insert-heading-respect-content' set to t."
7961 (interactive)
7962 (org-insert-heading '(4) invisible-ok))
7964 (defun org-insert-todo-heading-respect-content (&optional force-state)
7965 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7966 (interactive)
7967 (org-insert-todo-heading force-state '(4)))
7969 (defun org-insert-todo-heading (arg &optional force-heading)
7970 "Insert a new heading with the same level and TODO state as current heading.
7972 If the heading has no TODO state, or if the state is DONE, use
7973 the first state (TODO by default). Also with one prefix arg,
7974 force first state. With two prefix args, force inserting at the
7975 end of the parent subtree.
7977 When called at a plain list item, insert a new item with an
7978 unchecked check box."
7979 (interactive "P")
7980 (when (or force-heading (not (org-insert-item 'checkbox)))
7981 (org-insert-heading (or (and (equal arg '(16)) '(16))
7982 force-heading))
7983 (save-excursion
7984 (org-back-to-heading)
7985 (outline-previous-heading)
7986 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7987 (let* ((new-mark-x
7988 (if (or (equal arg '(4))
7989 (not (match-beginning 2))
7990 (member (match-string 2) org-done-keywords))
7991 (car org-todo-keywords-1)
7992 (match-string 2)))
7993 (new-mark
7995 (run-hook-with-args-until-success
7996 'org-todo-get-default-hook new-mark-x nil)
7997 new-mark-x)))
7998 (beginning-of-line 1)
7999 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8000 (if org-treat-insert-todo-heading-as-state-change
8001 (org-todo new-mark)
8002 (insert new-mark " "))))
8003 (when org-provide-todo-statistics
8004 (org-update-parent-todo-statistics))))
8006 (defun org-insert-subheading (arg)
8007 "Insert a new subheading and demote it.
8008 Works for outline headings and for plain lists alike."
8009 (interactive "P")
8010 (org-insert-heading arg)
8011 (cond
8012 ((org-at-heading-p) (org-do-demote))
8013 ((org-at-item-p) (org-indent-item))))
8015 (defun org-insert-todo-subheading (arg)
8016 "Insert a new subheading with TODO keyword or checkbox and demote it.
8017 Works for outline headings and for plain lists alike."
8018 (interactive "P")
8019 (org-insert-todo-heading arg)
8020 (cond
8021 ((org-at-heading-p) (org-do-demote))
8022 ((org-at-item-p) (org-indent-item))))
8024 ;;; Promotion and Demotion
8026 (defvar org-after-demote-entry-hook nil
8027 "Hook run after an entry has been demoted.
8028 The cursor will be at the beginning of the entry.
8029 When a subtree is being demoted, the hook will be called for each node.")
8031 (defvar org-after-promote-entry-hook nil
8032 "Hook run after an entry has been promoted.
8033 The cursor will be at the beginning of the entry.
8034 When a subtree is being promoted, the hook will be called for each node.")
8036 (defun org-promote-subtree ()
8037 "Promote the entire subtree.
8038 See also `org-promote'."
8039 (interactive)
8040 (save-excursion
8041 (org-with-limited-levels (org-map-tree 'org-promote)))
8042 (org-fix-position-after-promote))
8044 (defun org-demote-subtree ()
8045 "Demote the entire subtree.
8046 See `org-demote' and `org-promote'."
8047 (interactive)
8048 (save-excursion
8049 (org-with-limited-levels (org-map-tree 'org-demote)))
8050 (org-fix-position-after-promote))
8052 (defun org-do-promote ()
8053 "Promote the current heading higher up the tree.
8054 If the region is active in `transient-mark-mode', promote all
8055 headings in the region."
8056 (interactive)
8057 (save-excursion
8058 (if (org-region-active-p)
8059 (org-map-region 'org-promote (region-beginning) (region-end))
8060 (org-promote)))
8061 (org-fix-position-after-promote))
8063 (defun org-do-demote ()
8064 "Demote the current heading lower down the tree.
8065 If the region is active in `transient-mark-mode', demote all
8066 headings in the region."
8067 (interactive)
8068 (save-excursion
8069 (if (org-region-active-p)
8070 (org-map-region 'org-demote (region-beginning) (region-end))
8071 (org-demote)))
8072 (org-fix-position-after-promote))
8074 (defun org-fix-position-after-promote ()
8075 "Fix cursor position and indentation after demoting/promoting."
8076 (let ((pos (point)))
8077 (when (save-excursion
8078 (beginning-of-line)
8079 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8080 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8081 (cond ((eobp) (insert " "))
8082 ((eolp) (insert " "))
8083 ((equal (char-after) ?\s) (forward-char 1))))))
8085 (defun org-current-level ()
8086 "Return the level of the current entry, or nil if before the first headline.
8087 The level is the number of stars at the beginning of the
8088 headline. Use `org-reduced-level' to remove the effect of
8089 `org-odd-levels'. Unlike to `org-outline-level', this function
8090 ignores inlinetasks."
8091 (let ((level (org-with-limited-levels (org-outline-level))))
8092 (and (> level 0) level)))
8094 (defun org-get-previous-line-level ()
8095 "Return the outline depth of the last headline before the current line.
8096 Returns 0 for the first headline in the buffer, and nil if before the
8097 first headline."
8098 (and (org-current-level)
8099 (or (and (/= (line-beginning-position) (point-min))
8100 (save-excursion (beginning-of-line 0) (org-current-level)))
8101 0)))
8103 (defun org-reduced-level (l)
8104 "Compute the effective level of a heading.
8105 This takes into account the setting of `org-odd-levels-only'."
8106 (cond
8107 ((zerop l) 0)
8108 (org-odd-levels-only (1+ (floor (/ l 2))))
8109 (t l)))
8111 (defun org-level-increment ()
8112 "Return the number of stars that will be added or removed at a
8113 time to headlines when structure editing, based on the value of
8114 `org-odd-levels-only'."
8115 (if org-odd-levels-only 2 1))
8117 (defun org-get-valid-level (level &optional change)
8118 "Rectify a level change under the influence of `org-odd-levels-only'.
8119 LEVEL is a current level, CHANGE is by how much the level should
8120 be modified. Even if CHANGE is nil, LEVEL may be returned
8121 modified because even level numbers will become the next higher
8122 odd number. Returns values greater than 0."
8123 (if org-odd-levels-only
8124 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8125 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8126 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8127 (max 1 (+ level (or change 0)))))
8129 (defun org-promote ()
8130 "Promote the current heading higher up the tree."
8131 (org-with-wide-buffer
8132 (org-back-to-heading t)
8133 (let* ((after-change-functions (remq 'flyspell-after-change-function
8134 after-change-functions))
8135 (level (save-match-data (funcall outline-level)))
8136 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8137 (diff (abs (- level (length up-head) -1))))
8138 (cond
8139 ((and (= level 1) org-allow-promoting-top-level-subtree)
8140 (replace-match "# " nil t))
8141 ((= level 1)
8142 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8143 (t (replace-match up-head nil t)))
8144 (unless (= level 1)
8145 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8146 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8147 (run-hooks 'org-after-promote-entry-hook))))
8149 (defun org-demote ()
8150 "Demote the current heading lower down the tree."
8151 (org-with-wide-buffer
8152 (org-back-to-heading t)
8153 (let* ((after-change-functions (remq 'flyspell-after-change-function
8154 after-change-functions))
8155 (level (save-match-data (funcall outline-level)))
8156 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8157 (diff (abs (- level (length down-head) -1))))
8158 (replace-match down-head nil t)
8159 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8160 (when org-adapt-indentation (org-fixup-indentation diff))
8161 (run-hooks 'org-after-demote-entry-hook))))
8163 (defun org-cycle-level ()
8164 "Cycle the level of an empty headline through possible states.
8165 This goes first to child, then to parent, level, then up the hierarchy.
8166 After top level, it switches back to sibling level."
8167 (interactive)
8168 (let ((org-adapt-indentation nil))
8169 (when (org-point-at-end-of-empty-headline)
8170 (setq this-command 'org-cycle-level) ; Only needed for caching
8171 (let ((cur-level (org-current-level))
8172 (prev-level (org-get-previous-line-level)))
8173 (cond
8174 ;; If first headline in file, promote to top-level.
8175 ((= prev-level 0)
8176 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8177 do (org-do-promote)))
8178 ;; If same level as prev, demote one.
8179 ((= prev-level cur-level)
8180 (org-do-demote))
8181 ;; If parent is top-level, promote to top level if not already.
8182 ((= prev-level 1)
8183 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8184 do (org-do-promote)))
8185 ;; If top-level, return to prev-level.
8186 ((= cur-level 1)
8187 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8188 do (org-do-demote)))
8189 ;; If less than prev-level, promote one.
8190 ((< cur-level prev-level)
8191 (org-do-promote))
8192 ;; If deeper than prev-level, promote until higher than
8193 ;; prev-level.
8194 ((> cur-level prev-level)
8195 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8196 do (org-do-promote))))
8197 t))))
8199 (defun org-map-tree (fun)
8200 "Call FUN for every heading underneath the current one."
8201 (org-back-to-heading t)
8202 (let ((level (funcall outline-level)))
8203 (save-excursion
8204 (funcall fun)
8205 (while (and (progn
8206 (outline-next-heading)
8207 (> (funcall outline-level) level))
8208 (not (eobp)))
8209 (funcall fun)))))
8211 (defun org-map-region (fun beg end)
8212 "Call FUN for every heading between BEG and END."
8213 (let ((org-ignore-region t))
8214 (save-excursion
8215 (setq end (copy-marker end))
8216 (goto-char beg)
8217 (when (and (re-search-forward org-outline-regexp-bol nil t)
8218 (< (point) end))
8219 (funcall fun))
8220 (while (and (progn
8221 (outline-next-heading)
8222 (< (point) end))
8223 (not (eobp)))
8224 (funcall fun)))))
8226 (defun org-fixup-indentation (diff)
8227 "Change the indentation in the current entry by DIFF.
8229 DIFF is an integer. Indentation is done according to the
8230 following rules:
8232 - Planning information and property drawers are always indented
8233 according to the new level of the headline;
8235 - Footnote definitions and their contents are ignored;
8237 - Inlinetasks' boundaries are not shifted;
8239 - Empty lines are ignored;
8241 - Other lines' indentation are shifted by DIFF columns, unless
8242 it would introduce a structural change in the document, in
8243 which case no shifting is done at all.
8245 Assume point is at a heading or an inlinetask beginning."
8246 (org-with-wide-buffer
8247 (narrow-to-region (line-beginning-position)
8248 (save-excursion
8249 (if (org-with-limited-levels (org-at-heading-p))
8250 (org-with-limited-levels (outline-next-heading))
8251 (org-inlinetask-goto-end))
8252 (point)))
8253 (forward-line)
8254 ;; Indent properly planning info and property drawer.
8255 (when (looking-at-p org-planning-line-re)
8256 (org-indent-line)
8257 (forward-line))
8258 (when (looking-at org-property-drawer-re)
8259 (goto-char (match-end 0))
8260 (forward-line)
8261 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8262 (catch 'no-shift
8263 (when (zerop diff) (throw 'no-shift nil))
8264 ;; If DIFF is negative, first check if a shift is possible at all
8265 ;; (e.g., it doesn't break structure). This can only happen if
8266 ;; some contents are not properly indented.
8267 (let ((case-fold-search t))
8268 (when (< diff 0)
8269 (let ((diff (- diff))
8270 (forbidden-re (concat org-outline-regexp
8271 "\\|"
8272 (substring org-footnote-definition-re 1))))
8273 (save-excursion
8274 (while (not (eobp))
8275 (cond
8276 ((looking-at-p "[ \t]*$") (forward-line))
8277 ((and (looking-at-p org-footnote-definition-re)
8278 (let ((e (org-element-at-point)))
8279 (and (eq (org-element-type e) 'footnote-definition)
8280 (goto-char (org-element-property :end e))))))
8281 ((looking-at-p org-outline-regexp) (forward-line))
8282 ;; Give up if shifting would move before column 0 or
8283 ;; if it would introduce a headline or a footnote
8284 ;; definition.
8286 (skip-chars-forward " \t")
8287 (let ((ind (current-column)))
8288 (when (or (< ind diff)
8289 (and (= ind diff) (looking-at-p forbidden-re)))
8290 (throw 'no-shift nil)))
8291 ;; Ignore contents of example blocks and source
8292 ;; blocks if their indentation is meant to be
8293 ;; preserved. Jump to block's closing line.
8294 (beginning-of-line)
8295 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8296 (let ((e (org-element-at-point)))
8297 (and (memq (org-element-type e)
8298 '(example-block src-block))
8299 (or org-src-preserve-indentation
8300 (org-element-property :preserve-indent e))
8301 (goto-char (org-element-property :end e))
8302 (progn (skip-chars-backward " \r\t\n")
8303 (beginning-of-line)
8304 t))))
8305 (forward-line))))))))
8306 ;; Shift lines but footnote definitions, inlinetasks boundaries
8307 ;; by DIFF. Also skip contents of source or example blocks
8308 ;; when indentation is meant to be preserved.
8309 (while (not (eobp))
8310 (cond
8311 ((and (looking-at-p org-footnote-definition-re)
8312 (let ((e (org-element-at-point)))
8313 (and (eq (org-element-type e) 'footnote-definition)
8314 (goto-char (org-element-property :end e))))))
8315 ((looking-at-p org-outline-regexp) (forward-line))
8316 ((looking-at-p "[ \t]*$") (forward-line))
8318 (indent-line-to (+ (org-get-indentation) diff))
8319 (beginning-of-line)
8320 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8321 (let ((e (org-element-at-point)))
8322 (and (memq (org-element-type e)
8323 '(example-block src-block))
8324 (or org-src-preserve-indentation
8325 (org-element-property :preserve-indent e))
8326 (goto-char (org-element-property :end e))
8327 (progn (skip-chars-backward " \r\t\n")
8328 (beginning-of-line)
8329 t))))
8330 (forward-line)))))))))
8332 (defun org-convert-to-odd-levels ()
8333 "Convert an Org file with all levels allowed to one with odd levels.
8334 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8335 level 5 etc."
8336 (interactive)
8337 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8338 (let ((outline-level 'org-outline-level)
8339 (org-odd-levels-only nil) n)
8340 (save-excursion
8341 (goto-char (point-min))
8342 (while (re-search-forward "^\\*\\*+ " nil t)
8343 (setq n (- (length (match-string 0)) 2))
8344 (while (>= (setq n (1- n)) 0)
8345 (org-demote))
8346 (end-of-line 1))))))
8348 (defun org-convert-to-oddeven-levels ()
8349 "Convert an Org file with only odd levels to one with odd/even levels.
8350 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8351 file contains a section with an even level, conversion would
8352 destroy the structure of the file. An error is signaled in this
8353 case."
8354 (interactive)
8355 (goto-char (point-min))
8356 ;; First check if there are no even levels
8357 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8358 (org-show-set-visibility 'canonical)
8359 (error "Not all levels are odd in this file. Conversion not possible"))
8360 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8361 (let ((outline-regexp org-outline-regexp)
8362 (outline-level 'org-outline-level)
8363 (org-odd-levels-only nil) n)
8364 (save-excursion
8365 (goto-char (point-min))
8366 (while (re-search-forward "^\\*\\*+ " nil t)
8367 (setq n (/ (1- (length (match-string 0))) 2))
8368 (while (>= (setq n (1- n)) 0)
8369 (org-promote))
8370 (end-of-line 1))))))
8372 (defun org-tr-level (n)
8373 "Make N odd if required."
8374 (if org-odd-levels-only (1+ (/ n 2)) n))
8376 ;;; Vertical tree motion, cutting and pasting of subtrees
8378 (defun org-move-subtree-up (&optional arg)
8379 "Move the current subtree up past ARG headlines of the same level."
8380 (interactive "p")
8381 (org-move-subtree-down (- (prefix-numeric-value arg))))
8383 (defun org-move-subtree-down (&optional arg)
8384 "Move the current subtree down past ARG headlines of the same level."
8385 (interactive "p")
8386 (setq arg (prefix-numeric-value arg))
8387 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8388 'org-get-last-sibling))
8389 (ins-point (make-marker))
8390 (cnt (abs arg))
8391 (col (current-column))
8392 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8393 ;; Select the tree
8394 (org-back-to-heading)
8395 (setq beg0 (point))
8396 (save-excursion
8397 (setq ne-beg (org-back-over-empty-lines))
8398 (setq beg (point)))
8399 (save-match-data
8400 (save-excursion (outline-end-of-heading)
8401 (setq folded (org-invisible-p)))
8402 (progn (org-end-of-subtree nil t)
8403 (unless (eobp) (backward-char))))
8404 (outline-next-heading)
8405 (setq ne-end (org-back-over-empty-lines))
8406 (setq end (point))
8407 (goto-char beg0)
8408 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8409 ;; include less whitespace
8410 (save-excursion
8411 (goto-char beg)
8412 (forward-line (- ne-beg ne-end))
8413 (setq beg (point))))
8414 ;; Find insertion point, with error handling
8415 (while (> cnt 0)
8416 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8417 (progn (goto-char beg0)
8418 (user-error "Cannot move past superior level or buffer limit")))
8419 (setq cnt (1- cnt)))
8420 (when (> arg 0)
8421 ;; Moving forward - still need to move over subtree
8422 (org-end-of-subtree t t)
8423 (save-excursion
8424 (org-back-over-empty-lines)
8425 (or (bolp) (newline))))
8426 (setq ne-ins (org-back-over-empty-lines))
8427 (move-marker ins-point (point))
8428 (setq txt (buffer-substring beg end))
8429 (org-save-markers-in-region beg end)
8430 (delete-region beg end)
8431 (org-remove-empty-overlays-at beg)
8432 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8433 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8434 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8435 (let ((bbb (point)))
8436 (insert-before-markers txt)
8437 (org-reinstall-markers-in-region bbb)
8438 (move-marker ins-point bbb))
8439 (or (bolp) (insert "\n"))
8440 (setq ins-end (point))
8441 (goto-char ins-point)
8442 (org-skip-whitespace)
8443 (when (and (< arg 0)
8444 (org-first-sibling-p)
8445 (> ne-ins ne-beg))
8446 ;; Move whitespace back to beginning
8447 (save-excursion
8448 (goto-char ins-end)
8449 (let ((kill-whole-line t))
8450 (kill-line (- ne-ins ne-beg)) (point)))
8451 (insert (make-string (- ne-ins ne-beg) ?\n)))
8452 (move-marker ins-point nil)
8453 (if folded
8454 (outline-hide-subtree)
8455 (org-show-entry)
8456 (org-show-children)
8457 (org-cycle-hide-drawers 'children))
8458 (org-clean-visibility-after-subtree-move)
8459 ;; move back to the initial column we were at
8460 (move-to-column col)))
8462 (defvar org-subtree-clip ""
8463 "Clipboard for cut and paste of subtrees.
8464 This is actually only a copy of the kill, because we use the normal kill
8465 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8467 (defvar org-subtree-clip-folded nil
8468 "Was the last copied subtree folded?
8469 This is used to fold the tree back after pasting.")
8471 (defun org-cut-subtree (&optional n)
8472 "Cut the current subtree into the clipboard.
8473 With prefix arg N, cut this many sequential subtrees.
8474 This is a short-hand for marking the subtree and then cutting it."
8475 (interactive "p")
8476 (org-copy-subtree n 'cut))
8478 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8479 "Copy the current subtree it in the clipboard.
8480 With prefix arg N, copy this many sequential subtrees.
8481 This is a short-hand for marking the subtree and then copying it.
8482 If CUT is non-nil, actually cut the subtree.
8483 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8484 of some markers in the region, even if CUT is non-nil. This is
8485 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8486 (interactive "p")
8487 (let (beg end folded (beg0 (point)))
8488 (if (called-interactively-p 'any)
8489 (org-back-to-heading nil) ; take what looks like a subtree
8490 (org-back-to-heading t)) ; take what is really there
8491 (setq beg (point))
8492 (skip-chars-forward " \t\r\n")
8493 (save-match-data
8494 (if nosubtrees
8495 (outline-next-heading)
8496 (save-excursion (outline-end-of-heading)
8497 (setq folded (org-invisible-p)))
8498 (ignore-errors (org-forward-heading-same-level (1- n) t))
8499 (org-end-of-subtree t t)))
8500 ;; Include the end of an inlinetask
8501 (when (and (featurep 'org-inlinetask)
8502 (looking-at-p (concat (org-inlinetask-outline-regexp)
8503 "END[ \t]*$")))
8504 (end-of-line))
8505 (setq end (point))
8506 (goto-char beg0)
8507 (when (> end beg)
8508 (setq org-subtree-clip-folded folded)
8509 (when (or cut force-store-markers)
8510 (org-save-markers-in-region beg end))
8511 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8512 (setq org-subtree-clip (current-kill 0))
8513 (message "%s: Subtree(s) with %d characters"
8514 (if cut "Cut" "Copied")
8515 (length org-subtree-clip)))))
8517 (defun org-paste-subtree (&optional level tree for-yank remove)
8518 "Paste the clipboard as a subtree, with modification of headline level.
8519 The entire subtree is promoted or demoted in order to match a new headline
8520 level.
8522 If the cursor is at the beginning of a headline, the same level as
8523 that headline is used to paste the tree.
8525 If not, the new level is derived from the *visible* headings
8526 before and after the insertion point, and taken to be the inferior headline
8527 level of the two. So if the previous visible heading is level 3 and the
8528 next is level 4 (or vice versa), level 4 will be used for insertion.
8529 This makes sure that the subtree remains an independent subtree and does
8530 not swallow low level entries.
8532 You can also force a different level, either by using a numeric prefix
8533 argument, or by inserting the heading marker by hand. For example, if the
8534 cursor is after \"*****\", then the tree will be shifted to level 5.
8536 If optional TREE is given, use this text instead of the kill ring.
8538 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8539 move back over whitespace before inserting, and move point to the end of
8540 the inserted text when done.
8542 When REMOVE is non-nil, remove the subtree from the clipboard."
8543 (interactive "P")
8544 (setq tree (or tree (and kill-ring (current-kill 0))))
8545 (unless (org-kill-is-subtree-p tree)
8546 (user-error "%s"
8547 (substitute-command-keys
8548 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8549 (org-with-limited-levels
8550 (let* ((visp (not (org-invisible-p)))
8551 (txt tree)
8552 (^re_ "\\(\\*+\\)[ \t]*")
8553 (old-level (if (string-match org-outline-regexp-bol txt)
8554 (- (match-end 0) (match-beginning 0) 1)
8555 -1))
8556 (force-level (cond (level (prefix-numeric-value level))
8557 ((and (looking-at "[ \t]*$")
8558 (string-match
8559 "^\\*+$" (buffer-substring
8560 (point-at-bol) (point))))
8561 (- (match-end 0) (match-beginning 0)))
8562 ((and (bolp)
8563 (looking-at org-outline-regexp))
8564 (- (match-end 0) (point) 1))))
8565 (previous-level (save-excursion
8566 (condition-case nil
8567 (progn
8568 (outline-previous-visible-heading 1)
8569 (if (looking-at ^re_)
8570 (- (match-end 0) (match-beginning 0) 1)
8572 (error 1))))
8573 (next-level (save-excursion
8574 (condition-case nil
8575 (progn
8576 (or (looking-at org-outline-regexp)
8577 (outline-next-visible-heading 1))
8578 (if (looking-at ^re_)
8579 (- (match-end 0) (match-beginning 0) 1)
8581 (error 1))))
8582 (new-level (or force-level (max previous-level next-level)))
8583 (shift (if (or (= old-level -1)
8584 (= new-level -1)
8585 (= old-level new-level))
8587 (- new-level old-level)))
8588 (delta (if (> shift 0) -1 1))
8589 (func (if (> shift 0) 'org-demote 'org-promote))
8590 (org-odd-levels-only nil)
8591 beg end newend)
8592 ;; Remove the forced level indicator
8593 (when force-level
8594 (delete-region (point-at-bol) (point)))
8595 ;; Paste
8596 (beginning-of-line (if (bolp) 1 2))
8597 (setq beg (point))
8598 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8599 (insert-before-markers txt)
8600 (unless (string-suffix-p "\n" txt) (insert "\n"))
8601 (setq newend (point))
8602 (org-reinstall-markers-in-region beg)
8603 (setq end (point))
8604 (goto-char beg)
8605 (skip-chars-forward " \t\n\r")
8606 (setq beg (point))
8607 (when (and (org-invisible-p) visp)
8608 (save-excursion (outline-show-heading)))
8609 ;; Shift if necessary
8610 (unless (= shift 0)
8611 (save-restriction
8612 (narrow-to-region beg end)
8613 (while (not (= shift 0))
8614 (org-map-region func (point-min) (point-max))
8615 (setq shift (+ delta shift)))
8616 (goto-char (point-min))
8617 (setq newend (point-max))))
8618 (when (or (called-interactively-p 'interactive) for-yank)
8619 (message "Clipboard pasted as level %d subtree" new-level))
8620 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8621 kill-ring
8622 (eq org-subtree-clip (current-kill 0))
8623 org-subtree-clip-folded)
8624 ;; The tree was folded before it was killed/copied
8625 (outline-hide-subtree))
8626 (and for-yank (goto-char newend))
8627 (and remove (setq kill-ring (cdr kill-ring))))))
8629 (defun org-kill-is-subtree-p (&optional txt)
8630 "Check if the current kill is an outline subtree, or a set of trees.
8631 Returns nil if kill does not start with a headline, or if the first
8632 headline level is not the largest headline level in the tree.
8633 So this will actually accept several entries of equal levels as well,
8634 which is OK for `org-paste-subtree'.
8635 If optional TXT is given, check this string instead of the current kill."
8636 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8637 (re (org-get-limited-outline-regexp))
8638 (^re (concat "^" re))
8639 (start-level (and kill
8640 (string-match
8641 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8642 kill)
8643 (- (match-end 2) (match-beginning 2) 1)))
8644 (start (1+ (or (match-beginning 2) -1))))
8645 (if (not start-level)
8646 (progn
8647 nil) ;; does not even start with a heading
8648 (catch 'exit
8649 (while (setq start (string-match ^re kill (1+ start)))
8650 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8651 (throw 'exit nil)))
8652 t))))
8654 (defvar org-markers-to-move nil
8655 "Markers that should be moved with a cut-and-paste operation.
8656 Those markers are stored together with their positions relative to
8657 the start of the region.")
8659 (defun org-save-markers-in-region (beg end)
8660 "Check markers in region.
8661 If these markers are between BEG and END, record their position relative
8662 to BEG, so that after moving the block of text, we can put the markers back
8663 into place.
8664 This function gets called just before an entry or tree gets cut from the
8665 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8666 called immediately, to move the markers with the entries."
8667 (setq org-markers-to-move nil)
8668 (when (featurep 'org-clock)
8669 (org-clock-save-markers-for-cut-and-paste beg end))
8670 (when (featurep 'org-agenda)
8671 (org-agenda-save-markers-for-cut-and-paste beg end)))
8673 (defun org-check-and-save-marker (marker beg end)
8674 "Check if MARKER is between BEG and END.
8675 If yes, remember the marker and the distance to BEG."
8676 (when (and (marker-buffer marker)
8677 (equal (marker-buffer marker) (current-buffer))
8678 (>= marker beg) (< marker end))
8679 (push (cons marker (- marker beg)) org-markers-to-move)))
8681 (defun org-reinstall-markers-in-region (beg)
8682 "Move all remembered markers to their position relative to BEG."
8683 (dolist (x org-markers-to-move)
8684 (move-marker (car x) (+ beg (cdr x))))
8685 (setq org-markers-to-move nil))
8687 (defun org-narrow-to-subtree ()
8688 "Narrow buffer to the current subtree."
8689 (interactive)
8690 (save-excursion
8691 (save-match-data
8692 (org-with-limited-levels
8693 (narrow-to-region
8694 (progn (org-back-to-heading t) (point))
8695 (progn (org-end-of-subtree t t)
8696 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8697 (point)))))))
8699 (defun org-narrow-to-block ()
8700 "Narrow buffer to the current block."
8701 (interactive)
8702 (let* ((case-fold-search t)
8703 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8704 "^[ \t]*#\\+end_.*")))
8705 (if blockp
8706 (narrow-to-region (car blockp) (cdr blockp))
8707 (user-error "Not in a block"))))
8709 (defun org-clone-subtree-with-time-shift (n &optional shift)
8710 "Clone the task (subtree) at point N times.
8711 The clones will be inserted as siblings.
8713 In interactive use, the user will be prompted for the number of
8714 clones to be produced. If the entry has a timestamp, the user
8715 will also be prompted for a time shift, which may be a repeater
8716 as used in time stamps, for example `+3d'. To disable this,
8717 you can call the function with a universal prefix argument.
8719 When a valid repeater is given and the entry contains any time
8720 stamps, the clones will become a sequence in time, with time
8721 stamps in the subtree shifted for each clone produced. If SHIFT
8722 is nil or the empty string, time stamps will be left alone. The
8723 ID property of the original subtree is removed.
8725 In each clone, all the CLOCK entries will be removed. This
8726 prevents Org from considering that the clocked times overlap.
8728 If the original subtree did contain time stamps with a repeater,
8729 the following will happen:
8730 - the repeater will be removed in each clone
8731 - an additional clone will be produced, with the current, unshifted
8732 date(s) in the entry.
8733 - the original entry will be placed *after* all the clones, with
8734 repeater intact.
8735 - the start days in the repeater in the original entry will be shifted
8736 to past the last clone.
8737 In this way you can spell out a number of instances of a repeating task,
8738 and still retain the repeater to cover future instances of the task.
8740 As described above, N+1 clones are produced when the original
8741 subtree has a repeater. Setting N to 0, then, can be used to
8742 remove the repeater from a subtree and create a shifted clone
8743 with the original repeater."
8744 (interactive "nNumber of clones to produce: ")
8745 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8746 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8747 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8748 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8749 (shift
8750 (or shift
8751 (if (and (not (equal current-prefix-arg '(4)))
8752 (save-excursion
8753 (goto-char beg)
8754 (re-search-forward org-ts-regexp-both end-of-tree t)))
8755 (read-from-minibuffer
8756 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8757 ""))) ;No time shift
8758 (doshift
8759 (and (org-string-nw-p shift)
8760 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8761 shift)
8762 (user-error "Invalid shift specification %s" shift)))))
8763 (goto-char end-of-tree)
8764 (unless (bolp) (insert "\n"))
8765 (let* ((end (point))
8766 (template (buffer-substring beg end))
8767 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8768 (shift-what (pcase (and doshift (match-string 2 shift))
8769 (`nil nil)
8770 ("d" 'day)
8771 ("w" (setq shift-n (* 7 shift-n)) 'day)
8772 ("m" 'month)
8773 ("y" 'year)
8774 (_ (error "Unsupported time unit"))))
8775 (nmin 1)
8776 (nmax n)
8777 (n-no-remove -1)
8778 (idprop (org-entry-get nil "ID")))
8779 (when (and doshift
8780 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8781 template))
8782 (delete-region beg end)
8783 (setq end beg)
8784 (setq nmin 0)
8785 (setq nmax (1+ nmax))
8786 (setq n-no-remove nmax))
8787 (goto-char end)
8788 (cl-loop for n from nmin to nmax do
8789 (insert
8790 ;; Prepare clone.
8791 (with-temp-buffer
8792 (insert template)
8793 (org-mode)
8794 (goto-char (point-min))
8795 (org-show-subtree)
8796 (and idprop (if org-clone-delete-id
8797 (org-entry-delete nil "ID")
8798 (org-id-get-create t)))
8799 (unless (= n 0)
8800 (while (re-search-forward org-clock-line-re nil t)
8801 (delete-region (line-beginning-position)
8802 (line-beginning-position 2)))
8803 (goto-char (point-min))
8804 (while (re-search-forward org-drawer-regexp nil t)
8805 (org-remove-empty-drawer-at (point))))
8806 (goto-char (point-min))
8807 (when doshift
8808 (while (re-search-forward org-ts-regexp-both nil t)
8809 (org-timestamp-change (* n shift-n) shift-what))
8810 (unless (= n n-no-remove)
8811 (goto-char (point-min))
8812 (while (re-search-forward org-ts-regexp nil t)
8813 (save-excursion
8814 (goto-char (match-beginning 0))
8815 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8816 (delete-region (match-beginning 1) (match-end 1)))))))
8817 (buffer-string)))))
8818 (goto-char beg)))
8820 ;;; Outline Sorting
8822 (defun org-sort (&optional with-case)
8823 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8824 Optional argument WITH-CASE means sort case-sensitively."
8825 (interactive "P")
8826 (org-call-with-arg
8827 (cond ((org-at-table-p) #'org-table-sort-lines)
8828 ((org-at-item-p) #'org-sort-list)
8829 (t #'org-sort-entries))
8830 with-case))
8832 (defun org-sort-remove-invisible (s)
8833 "Remove invisible part of links and emphasis markers from string S."
8834 (remove-text-properties 0 (length s) org-rm-props s)
8835 (replace-regexp-in-string
8836 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8837 (replace-regexp-in-string
8838 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8839 (org-link-display-format s)
8840 t t) t t))
8842 (defvar org-priority-regexp) ; defined later in the file
8844 (defvar org-after-sorting-entries-or-items-hook nil
8845 "Hook that is run after a bunch of entries or items have been sorted.
8846 When children are sorted, the cursor is in the parent line when this
8847 hook gets called. When a region or a plain list is sorted, the cursor
8848 will be in the first entry of the sorted region/list.")
8850 (defun org-sort-entries
8851 (&optional with-case sorting-type getkey-func compare-func property
8852 interactive?)
8853 "Sort entries on a certain level of an outline tree.
8854 If there is an active region, the entries in the region are sorted.
8855 Else, if the cursor is before the first entry, sort the top-level items.
8856 Else, the children of the entry at point are sorted.
8858 Sorting can be alphabetically, numerically, by date/time as given by
8859 a time stamp, by a property, by priority order, or by a custom function.
8861 The command prompts for the sorting type unless it has been given to the
8862 function through the SORTING-TYPE argument, which needs to be a character,
8863 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8864 the precise meaning of each character:
8866 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8867 c By creation time, which is assumed to be the first inactive time stamp
8868 at the beginning of a line.
8869 d By deadline date/time.
8870 k By clocking time.
8871 n Numerically, by converting the beginning of the entry/item to a number.
8872 o By order of TODO keywords.
8873 p By priority according to the cookie.
8874 r By the value of a property.
8875 s By scheduled date/time.
8876 t By date/time, either the first active time stamp in the entry, or, if
8877 none exist, by the first inactive one.
8879 Capital letters will reverse the sort order.
8881 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8882 called with point at the beginning of the record. It must return a
8883 value that is compatible with COMPARE-FUNC, the function used to
8884 compare entries.
8886 Comparing entries ignores case by default. However, with an optional argument
8887 WITH-CASE, the sorting considers case as well.
8889 Sorting is done against the visible part of the headlines, it ignores hidden
8890 links.
8892 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8894 A non-nil value for INTERACTIVE? is used to signal that this
8895 function is being called interactively."
8896 (interactive (list current-prefix-arg nil nil nil nil t))
8897 (let ((case-func (if with-case 'identity 'downcase))
8898 start beg end stars re re2
8899 txt what tmp)
8900 ;; Find beginning and end of region to sort
8901 (cond
8902 ((org-region-active-p)
8903 ;; we will sort the region
8904 (setq end (region-end)
8905 what "region")
8906 (goto-char (region-beginning))
8907 (unless (org-at-heading-p) (outline-next-heading))
8908 (setq start (point)))
8909 ((or (org-at-heading-p)
8910 (ignore-errors (progn (org-back-to-heading) t)))
8911 ;; we will sort the children of the current headline
8912 (org-back-to-heading)
8913 (setq start (point)
8914 end (progn (org-end-of-subtree t t)
8915 (or (bolp) (insert "\n"))
8916 (when (>= (org-back-over-empty-lines) 1)
8917 (forward-line 1))
8918 (point))
8919 what "children")
8920 (goto-char start)
8921 (outline-show-subtree)
8922 (outline-next-heading))
8924 ;; we will sort the top-level entries in this file
8925 (goto-char (point-min))
8926 (or (org-at-heading-p) (outline-next-heading))
8927 (setq start (point))
8928 (goto-char (point-max))
8929 (beginning-of-line 1)
8930 (when (looking-at ".*?\\S-")
8931 ;; File ends in a non-white line
8932 (end-of-line 1)
8933 (insert "\n"))
8934 (setq end (point-max))
8935 (setq what "top-level")
8936 (goto-char start)
8937 (outline-show-all)))
8939 (setq beg (point))
8940 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8942 (looking-at "\\(\\*+\\)")
8943 (setq stars (match-string 1)
8944 re (concat "^" (regexp-quote stars) " +")
8945 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8946 txt (buffer-substring beg end))
8947 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8948 (when (and (not (equal stars "*")) (string-match re2 txt))
8949 (user-error "Region to sort contains a level above the first entry"))
8951 (unless sorting-type
8952 (message
8953 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8954 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8955 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8956 what)
8957 (setq sorting-type (read-char-exclusive)))
8959 (unless getkey-func
8960 (and (= (downcase sorting-type) ?f)
8961 (setq getkey-func
8962 (or (and interactive?
8963 (org-read-function
8964 "Function for extracting keys: "))
8965 (error "Missing key extractor")))))
8967 (and (= (downcase sorting-type) ?r)
8968 (not property)
8969 (setq property
8970 (completing-read "Property: "
8971 (mapcar #'list (org-buffer-property-keys t))
8972 nil t)))
8974 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8975 (message "Sorting entries...")
8977 (save-restriction
8978 (narrow-to-region start end)
8979 (let ((restore-clock?
8980 ;; The clock marker is lost when using `sort-subr'; mark
8981 ;; the clock with temporary `:org-clock-marker-backup'
8982 ;; text property.
8983 (when (and (eq (org-clocking-buffer) (current-buffer))
8984 (<= start (marker-position org-clock-marker))
8985 (>= end (marker-position org-clock-marker)))
8986 (org-with-silent-modifications
8987 (put-text-property (1- org-clock-marker) org-clock-marker
8988 :org-clock-marker-backup t))
8990 (dcst (downcase sorting-type))
8991 (case-fold-search nil)
8992 (now (current-time)))
8993 (sort-subr
8994 (/= dcst sorting-type)
8995 ;; This function moves to the beginning character of the "record" to
8996 ;; be sorted.
8997 (lambda nil
8998 (if (re-search-forward re nil t)
8999 (goto-char (match-beginning 0))
9000 (goto-char (point-max))))
9001 ;; This function moves to the last character of the "record" being
9002 ;; sorted.
9003 (lambda nil
9004 (save-match-data
9005 (condition-case nil
9006 (outline-forward-same-level 1)
9007 (error
9008 (goto-char (point-max))))))
9009 ;; This function returns the value that gets sorted against.
9010 (lambda nil
9011 (cond
9012 ((= dcst ?n)
9013 (if (looking-at org-complex-heading-regexp)
9014 (string-to-number (org-sort-remove-invisible (match-string 4)))
9015 nil))
9016 ((= dcst ?a)
9017 (if (looking-at org-complex-heading-regexp)
9018 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9019 nil))
9020 ((= dcst ?k)
9021 (or (get-text-property (point) :org-clock-minutes) 0))
9022 ((= dcst ?t)
9023 (let ((end (save-excursion (outline-next-heading) (point))))
9024 (if (or (re-search-forward org-ts-regexp end t)
9025 (re-search-forward org-ts-regexp-both end t))
9026 (org-time-string-to-seconds (match-string 0))
9027 (float-time now))))
9028 ((= dcst ?c)
9029 (let ((end (save-excursion (outline-next-heading) (point))))
9030 (if (re-search-forward
9031 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9032 end t)
9033 (org-time-string-to-seconds (match-string 0))
9034 (float-time now))))
9035 ((= dcst ?s)
9036 (let ((end (save-excursion (outline-next-heading) (point))))
9037 (if (re-search-forward org-scheduled-time-regexp end t)
9038 (org-time-string-to-seconds (match-string 1))
9039 (float-time now))))
9040 ((= dcst ?d)
9041 (let ((end (save-excursion (outline-next-heading) (point))))
9042 (if (re-search-forward org-deadline-time-regexp end t)
9043 (org-time-string-to-seconds (match-string 1))
9044 (float-time now))))
9045 ((= dcst ?p)
9046 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9047 (string-to-char (match-string 2))
9048 org-default-priority))
9049 ((= dcst ?r)
9050 (or (org-entry-get nil property) ""))
9051 ((= dcst ?o)
9052 (when (looking-at org-complex-heading-regexp)
9053 (let* ((m (match-string 2))
9054 (s (if (member m org-done-keywords) '- '+)))
9055 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9056 ((= dcst ?f)
9057 (if getkey-func
9058 (progn
9059 (setq tmp (funcall getkey-func))
9060 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9061 tmp)
9062 (error "Invalid key function `%s'" getkey-func)))
9063 (t (error "Invalid sorting type `%c'" sorting-type))))
9065 (cond
9066 ((= dcst ?a) 'string<)
9067 ((= dcst ?f)
9068 (or compare-func
9069 (and interactive?
9070 (org-read-function
9071 (concat "Function for comparing keys "
9072 "(empty for default `sort-subr' predicate): ")
9073 'allow-empty))))
9074 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9075 (when restore-clock?
9076 (move-marker org-clock-marker
9077 (1+ (next-single-property-change
9078 start :org-clock-marker-backup)))
9079 (remove-text-properties (1- org-clock-marker) org-clock-marker
9080 '(:org-clock-marker-backup t)))))
9081 (run-hooks 'org-after-sorting-entries-or-items-hook)
9082 (message "Sorting entries...done")))
9084 ;;; The orgstruct minor mode
9086 ;; Define a minor mode which can be used in other modes in order to
9087 ;; integrate the Org mode structure editing commands.
9089 ;; This is really a hack, because the Org mode structure commands use
9090 ;; keys which normally belong to the major mode. Here is how it
9091 ;; works: The minor mode defines all the keys necessary to operate the
9092 ;; structure commands, but wraps the commands into a function which
9093 ;; tests if the cursor is currently at a headline or a plain list
9094 ;; item. If that is the case, the structure command is used,
9095 ;; temporarily setting many Org mode variables like regular
9096 ;; expressions for filling etc. However, when any of those keys is
9097 ;; used at a different location, function uses `key-binding' to look
9098 ;; up if the key has an associated command in another currently active
9099 ;; keymap (minor modes, major mode, global), and executes that
9100 ;; command. There might be problems if any of the keys is otherwise
9101 ;; used as a prefix key.
9103 (defcustom orgstruct-heading-prefix-regexp ""
9104 "Regexp that matches the custom prefix of Org headlines in
9105 orgstruct(++)-mode."
9106 :group 'org
9107 :version "24.4"
9108 :package-version '(Org . "8.3")
9109 :type 'regexp)
9110 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9112 (defcustom orgstruct-setup-hook nil
9113 "Hook run after orgstruct-mode-map is filled."
9114 :group 'org
9115 :version "24.4"
9116 :package-version '(Org . "8.0")
9117 :type 'hook)
9119 (defvar orgstruct-initialized nil)
9121 (defvar org-local-vars nil
9122 "List of local variables, for use by `orgstruct-mode'.")
9124 ;;;###autoload
9125 (define-minor-mode orgstruct-mode
9126 "Toggle the minor mode `orgstruct-mode'.
9127 This mode is for using Org mode structure commands in other
9128 modes. The following keys behave as if Org mode were active, if
9129 the cursor is on a headline, or on a plain list item (both as
9130 defined by Org mode)."
9131 nil " OrgStruct" (make-sparse-keymap)
9132 (funcall (if orgstruct-mode
9133 'add-to-invisibility-spec
9134 'remove-from-invisibility-spec)
9135 '(outline . t))
9136 (when orgstruct-mode
9137 (org-load-modules-maybe)
9138 (unless orgstruct-initialized
9139 (orgstruct-setup)
9140 (setq orgstruct-initialized t))))
9142 ;;;###autoload
9143 (defun turn-on-orgstruct ()
9144 "Unconditionally turn on `orgstruct-mode'."
9145 (orgstruct-mode 1))
9147 (defvar-local orgstruct-is-++ nil
9148 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9149 (defvar-local org-fb-vars nil)
9150 (defun orgstruct++-mode (&optional arg)
9151 "Toggle `orgstruct-mode', the enhanced version of it.
9152 In addition to setting orgstruct-mode, this also exports all
9153 indentation and autofilling variables from Org mode into the
9154 buffer. It will also recognize item context in multiline items."
9155 (interactive "P")
9156 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9157 (if (< arg 1)
9158 (progn (orgstruct-mode -1)
9159 (dolist (v org-fb-vars)
9160 (set (make-local-variable (car v))
9161 (if (eq (car-safe (cadr v)) 'quote)
9162 (cl-cadadr v)
9163 (nth 1 v)))))
9164 (orgstruct-mode 1)
9165 (setq org-fb-vars nil)
9166 (unless org-local-vars
9167 (setq org-local-vars (org-get-local-variables)))
9168 (let (var val)
9169 (dolist (x org-local-vars)
9170 (when (string-match
9171 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9172 \\|fill-prefix\\|indent-\\)"
9173 (symbol-name (car x)))
9174 (setq var (car x) val (nth 1 x))
9175 (push (list var `(quote ,(eval var))) org-fb-vars)
9176 (set (make-local-variable var)
9177 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9178 (setq-local orgstruct-is-++ t))))
9180 ;;;###autoload
9181 (defun turn-on-orgstruct++ ()
9182 "Unconditionally turn on `orgstruct++-mode'."
9183 (orgstruct++-mode 1))
9185 (defun orgstruct-error ()
9186 "Error when there is no default binding for a structure key."
9187 (interactive)
9188 (funcall (if (fboundp 'user-error)
9189 'user-error
9190 'error)
9191 "This key has no function outside structure elements"))
9193 (defun orgstruct-setup ()
9194 "Setup orgstruct keymap."
9195 (dolist (cell '((org-demote . t)
9196 (org-metaleft . t)
9197 (org-metaright . t)
9198 (org-promote . t)
9199 (org-shiftmetaleft . t)
9200 (org-shiftmetaright . t)
9201 org-backward-element
9202 org-backward-heading-same-level
9203 org-ctrl-c-ret
9204 org-ctrl-c-minus
9205 org-ctrl-c-star
9206 org-cycle
9207 org-force-cycle-archived
9208 org-forward-heading-same-level
9209 org-insert-heading
9210 org-insert-heading-respect-content
9211 org-kill-note-or-show-branches
9212 org-mark-subtree
9213 org-meta-return
9214 org-metadown
9215 org-metaup
9216 org-narrow-to-subtree
9217 org-promote-subtree
9218 org-reveal
9219 org-shiftdown
9220 org-shiftleft
9221 org-shiftmetadown
9222 org-shiftmetaup
9223 org-shiftright
9224 org-shifttab
9225 org-shifttab
9226 org-shiftup
9227 org-show-children
9228 org-show-subtree
9229 org-sort
9230 org-up-element
9231 outline-demote
9232 outline-next-visible-heading
9233 outline-previous-visible-heading
9234 outline-promote
9235 outline-up-heading))
9236 (let ((f (or (car-safe cell) cell))
9237 (disable-when-heading-prefix (cdr-safe cell)))
9238 (when (fboundp f)
9239 (let ((new-bindings))
9240 (dolist (binding (nconc (where-is-internal f org-mode-map)
9241 (where-is-internal f outline-mode-map)))
9242 (push binding new-bindings)
9243 ;; TODO use local-function-key-map
9244 (dolist (rep '(("<tab>" . "TAB")
9245 ("<return>" . "RET")
9246 ("<escape>" . "ESC")
9247 ("<delete>" . "DEL")))
9248 (setq binding (read-kbd-macro
9249 (let ((case-fold-search))
9250 (replace-regexp-in-string
9251 (regexp-quote (cdr rep))
9252 (car rep)
9253 (key-description binding)))))
9254 (cl-pushnew binding new-bindings :test 'equal)))
9255 (dolist (binding new-bindings)
9256 (let ((key (lookup-key orgstruct-mode-map binding)))
9257 (when (or (not key) (numberp key))
9258 (ignore-errors
9259 (org-defkey orgstruct-mode-map
9260 binding
9261 (orgstruct-make-binding
9262 f binding disable-when-heading-prefix))))))))))
9263 (run-hooks 'orgstruct-setup-hook))
9265 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9266 "Create a function for binding in the structure minor mode.
9267 FUN is the command to call inside a table. KEY is the key that
9268 should be checked in for a command to execute outside of tables.
9269 Non-nil `disable-when-heading-prefix' means to disable the command
9270 if `orgstruct-heading-prefix-regexp' is not empty."
9271 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9272 (let ((nname name)
9273 (i 0))
9274 (while (fboundp (intern nname))
9275 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9276 (setq name (intern nname)))
9277 (eval
9278 (let ((bindings '((org-heading-regexp
9279 (concat "^"
9280 orgstruct-heading-prefix-regexp
9281 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9282 (org-outline-regexp
9283 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9284 (org-outline-regexp-bol
9285 (concat "^" org-outline-regexp))
9286 (outline-regexp org-outline-regexp)
9287 (outline-heading-end-regexp "\n")
9288 (outline-level 'org-outline-level)
9289 (outline-heading-alist))))
9290 `(defun ,name (arg)
9291 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9292 "Outside of structure, run the binding of `"
9293 (key-description key) "'."
9294 (when disable-when-heading-prefix
9295 (concat
9296 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9297 "back to the default binding due to limitations of Org's implementation of\n"
9298 "`" (symbol-name fun) "'.")))
9299 (interactive "p")
9300 (let* ((disable
9301 ,(and disable-when-heading-prefix
9302 '(not (string= orgstruct-heading-prefix-regexp ""))))
9303 (fallback
9304 (or disable
9305 (not
9306 (let* ,bindings
9307 (org-context-p 'headline 'item
9308 ,(when (memq fun
9309 '(org-insert-heading
9310 org-insert-heading-respect-content
9311 org-meta-return))
9312 '(when orgstruct-is-++
9313 'item-body))))))))
9314 (if fallback
9315 (let* ((orgstruct-mode)
9316 (binding
9317 (let ((key ,key))
9318 (catch 'exit
9319 (dolist
9320 (rep
9321 '(nil
9322 ("<\\([^>]*\\)tab>" . "\\1TAB")
9323 ("<\\([^>]*\\)return>" . "\\1RET")
9324 ("<\\([^>]*\\)escape>" . "\\1ESC")
9325 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9326 nil)
9327 (when rep
9328 (setq key (read-kbd-macro
9329 (let ((case-fold-search))
9330 (replace-regexp-in-string
9331 (car rep)
9332 (cdr rep)
9333 (key-description key))))))
9334 (when (key-binding key)
9335 (throw 'exit (key-binding key))))))))
9336 (if (keymapp binding)
9337 (org-set-transient-map binding)
9338 (let ((func (or binding
9339 (unless disable
9340 'orgstruct-error))))
9341 (when func
9342 (call-interactively func)))))
9343 (org-run-like-in-org-mode
9344 (lambda ()
9345 (interactive)
9346 (let* ,bindings
9347 (call-interactively ',fun)))))))))
9348 name))
9350 (defun org-contextualize-keys (alist contexts)
9351 "Return valid elements in ALIST depending on CONTEXTS.
9353 `org-agenda-custom-commands' or `org-capture-templates' are the
9354 values used for ALIST, and `org-agenda-custom-commands-contexts'
9355 or `org-capture-templates-contexts' are the associated contexts
9356 definitions."
9357 (let ((contexts
9358 ;; normalize contexts
9359 (mapcar
9360 (lambda(c) (cond ((listp (cadr c))
9361 (list (car c) (car c) (nth 1 c)))
9362 ((string= "" (cadr c))
9363 (list (car c) (car c) (nth 2 c)))
9364 (t c)))
9365 contexts))
9366 (a alist) r s)
9367 ;; loop over all commands or templates
9368 (dolist (c a)
9369 (let (vrules repl)
9370 (cond
9371 ((not (assoc (car c) contexts))
9372 (push c r))
9373 ((and (assoc (car c) contexts)
9374 (setq vrules (org-contextualize-validate-key
9375 (car c) contexts)))
9376 (mapc (lambda (vr)
9377 (unless (equal (car vr) (cadr vr))
9378 (setq repl vr)))
9379 vrules)
9380 (if (not repl) (push c r)
9381 (push (cadr repl) s)
9382 (push
9383 (cons (car c)
9384 (cdr (or (assoc (cadr repl) alist)
9385 (error "Undefined key `%s' as contextual replacement for `%s'"
9386 (cadr repl) (car c)))))
9387 r))))))
9388 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9389 (delq
9391 (delete-dups
9392 (mapcar (lambda (x)
9393 (let ((tpl (car x)))
9394 (unless (delq
9396 (mapcar (lambda (y)
9397 (equal y tpl))
9399 x)))
9400 (reverse r))))))
9402 (defun org-contextualize-validate-key (key contexts)
9403 "Check CONTEXTS for agenda or capture KEY."
9404 (let (res)
9405 (dolist (r contexts)
9406 (dolist (rr (car (last r)))
9407 (when
9408 (and (equal key (car r))
9409 (if (functionp rr) (funcall rr)
9410 (or (and (eq (car rr) 'in-file)
9411 (buffer-file-name)
9412 (string-match (cdr rr) (buffer-file-name)))
9413 (and (eq (car rr) 'in-mode)
9414 (string-match (cdr rr) (symbol-name major-mode)))
9415 (and (eq (car rr) 'in-buffer)
9416 (string-match (cdr rr) (buffer-name)))
9417 (when (and (eq (car rr) 'not-in-file)
9418 (buffer-file-name))
9419 (not (string-match (cdr rr) (buffer-file-name))))
9420 (when (eq (car rr) 'not-in-mode)
9421 (not (string-match (cdr rr) (symbol-name major-mode))))
9422 (when (eq (car rr) 'not-in-buffer)
9423 (not (string-match (cdr rr) (buffer-name)))))))
9424 (push r res))))
9425 (delete-dups (delq nil res))))
9427 (defun org-context-p (&rest contexts)
9428 "Check if local context is any of CONTEXTS.
9429 Possible values in the list of contexts are `table', `headline', and `item'."
9430 (let ((pos (point)))
9431 (goto-char (point-at-bol))
9432 (prog1 (or (and (memq 'table contexts)
9433 (looking-at "[ \t]*|"))
9434 (and (memq 'headline contexts)
9435 (looking-at org-outline-regexp))
9436 (and (memq 'item contexts)
9437 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9438 (and (memq 'item-body contexts)
9439 (org-in-item-p)))
9440 (goto-char pos))))
9442 ;;;###autoload
9443 (defun org-run-like-in-org-mode (cmd)
9444 "Run a command, pretending that the current buffer is in Org mode.
9445 This will temporarily bind local variables that are typically bound in
9446 Org mode to the values they have in Org mode, and then interactively
9447 call CMD."
9448 (org-load-modules-maybe)
9449 (unless org-local-vars
9450 (setq org-local-vars (org-get-local-variables)))
9451 (let (binds)
9452 (dolist (var org-local-vars)
9453 (when (or (not (boundp (car var)))
9454 (eq (symbol-value (car var))
9455 (default-value (car var))))
9456 (push (list (car var) `(quote ,(cadr var))) binds)))
9457 (eval `(let ,binds
9458 (call-interactively (quote ,cmd))))))
9460 (defun org-get-category (&optional pos force-refresh)
9461 "Get the category applying to position POS."
9462 (save-match-data
9463 (when force-refresh (org-refresh-category-properties))
9464 (let ((pos (or pos (point))))
9465 (or (get-text-property pos 'org-category)
9466 (progn (org-refresh-category-properties)
9467 (get-text-property pos 'org-category))))))
9469 ;;; Refresh properties
9471 (defun org-refresh-properties (dprop tprop)
9472 "Refresh buffer text properties.
9473 DPROP is the drawer property and TPROP is either the
9474 corresponding text property to set, or an alist with each element
9475 being a text property (as a symbol) and a function to apply to
9476 the value of the drawer property."
9477 (let* ((case-fold-search t)
9478 (inhibit-read-only t)
9479 (inherit? (org-property-inherit-p dprop))
9480 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9481 (global (and inherit? (org--property-global-value dprop nil))))
9482 (org-with-silent-modifications
9483 (org-with-point-at 1
9484 ;; Set global values (e.g., values defined through
9485 ;; "#+PROPERTY:" keywords) to the whole buffer.
9486 (when global (put-text-property (point-min) (point-max) tprop global))
9487 ;; Set local values.
9488 (while (re-search-forward property-re nil t)
9489 (when (org-at-property-p)
9490 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9491 (outline-next-heading))))))
9493 (defun org-refresh-property (tprop p &optional inherit)
9494 "Refresh the buffer text property TPROP from the drawer property P.
9495 The refresh happens only for the current headline, or the whole
9496 sub-tree if optional argument INHERIT is non-nil."
9497 (unless (org-before-first-heading-p)
9498 (save-excursion
9499 (org-back-to-heading t)
9500 (let ((start (point))
9501 (end (save-excursion
9502 (if inherit (org-end-of-subtree t t)
9503 (or (outline-next-heading) (point-max))))))
9504 (if (symbolp tprop)
9505 ;; TPROP is a text property symbol.
9506 (put-text-property start end tprop p)
9507 ;; TPROP is an alist with (property . function) elements.
9508 (pcase-dolist (`(,prop . ,f) tprop)
9509 (put-text-property start end prop (funcall f p))))))))
9511 (defun org-refresh-category-properties ()
9512 "Refresh category text properties in the buffer."
9513 (let ((case-fold-search t)
9514 (inhibit-read-only t)
9515 (default-category
9516 (cond ((null org-category)
9517 (if buffer-file-name
9518 (file-name-sans-extension
9519 (file-name-nondirectory buffer-file-name))
9520 "???"))
9521 ((symbolp org-category) (symbol-name org-category))
9522 (t org-category))))
9523 (org-with-silent-modifications
9524 (org-with-wide-buffer
9525 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9526 ;; This is the default category for the buffer. If none is
9527 ;; found, fall-back to `org-category' or buffer file name.
9528 (put-text-property
9529 (point-min) (point-max)
9530 'org-category
9531 (catch 'buffer-category
9532 (goto-char (point-max))
9533 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9534 (let ((element (org-element-at-point)))
9535 (when (eq (org-element-type element) 'keyword)
9536 (throw 'buffer-category
9537 (org-element-property :value element)))))
9538 default-category))
9539 ;; Set sub-tree specific categories.
9540 (goto-char (point-min))
9541 (let ((regexp (org-re-property "CATEGORY")))
9542 (while (re-search-forward regexp nil t)
9543 (let ((value (match-string-no-properties 3)))
9544 (when (org-at-property-p)
9545 (put-text-property
9546 (save-excursion (org-back-to-heading t) (point))
9547 (save-excursion (org-end-of-subtree t t) (point))
9548 'org-category
9549 value)))))))))
9551 (defun org-refresh-stats-properties ()
9552 "Refresh stats text properties in the buffer."
9553 (org-with-silent-modifications
9554 (org-with-point-at 1
9555 (let ((regexp (concat org-outline-regexp-bol
9556 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9557 (while (re-search-forward regexp nil t)
9558 (let* ((numerator (string-to-number (match-string 1)))
9559 (denominator (and (match-end 2)
9560 (string-to-number (match-string 2))))
9561 (stats (cond ((not denominator) numerator) ;percent
9562 ((= denominator 0) 0)
9563 (t (/ (* numerator 100) denominator)))))
9564 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9565 'org-stats stats)))))))
9567 (defun org-refresh-effort-properties ()
9568 "Refresh effort properties"
9569 (org-refresh-properties
9570 org-effort-property
9571 '((effort . identity)
9572 (effort-minutes . org-duration-to-minutes))))
9574 ;;;; Link Stuff
9576 ;;; Link abbreviations
9578 (defun org-link-expand-abbrev (link)
9579 "Apply replacements as defined in `org-link-abbrev-alist'."
9580 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9581 (let* ((key (match-string 1 link))
9582 (as (or (assoc key org-link-abbrev-alist-local)
9583 (assoc key org-link-abbrev-alist)))
9584 (tag (and (match-end 2) (match-string 3 link)))
9585 rpl)
9586 (if (not as)
9587 link
9588 (setq rpl (cdr as))
9589 (cond
9590 ((symbolp rpl) (funcall rpl tag))
9591 ((string-match "%(\\([^)]+\\))" rpl)
9592 (replace-match
9593 (save-match-data
9594 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9595 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9596 ((string-match "%h" rpl)
9597 (replace-match (url-hexify-string (or tag "")) t t rpl))
9598 (t (concat rpl tag)))))
9599 link))
9601 ;;; Storing and inserting links
9603 (defvar org-insert-link-history nil
9604 "Minibuffer history for links inserted with `org-insert-link'.")
9606 (defvar org-stored-links nil
9607 "Contains the links stored with `org-store-link'.")
9609 (defvar org-store-link-plist nil
9610 "Plist with info about the most recently link created with `org-store-link'.")
9612 (defun org-store-link-functions ()
9613 "Return a list of functions that are called to create and store a link.
9614 The functions defined in the :store property of
9615 `org-link-parameters'.
9617 Each function will be called in turn until one returns a non-nil
9618 value. Each function should check if it is responsible for
9619 creating this link (for example by looking at the major mode).
9620 If not, it must exit and return nil. If yes, it should return
9621 a non-nil value after calling `org-store-link-props' with a list
9622 of properties and values. Special properties are:
9624 :type The link prefix, like \"http\". This must be given.
9625 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9626 This is obligatory as well.
9627 :description Optional default description for the second pair
9628 of brackets in an Org mode link. The user can still change
9629 this when inserting this link into an Org mode buffer.
9631 In addition to these, any additional properties can be specified
9632 and then used in capture templates."
9633 (cl-loop for link in org-link-parameters
9634 with store-func
9635 do (setq store-func (org-link-get-parameter (car link) :store))
9636 if store-func
9637 collect store-func))
9639 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9640 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9642 ;;;###autoload
9643 (defun org-store-link (arg)
9644 "Store an org-link to the current location.
9645 \\<org-mode-map>
9646 This link is added to `org-stored-links' and can later be inserted
9647 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9649 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9650 A single
9651 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9652 `org-gnus-prefer-web-links' for links to Usenet articles.
9654 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9655 skipping storing functions that are not
9656 part of Org core.
9658 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9659 prefix ARG forces storing a link for each line in the
9660 active region."
9661 (interactive "P")
9662 (org-load-modules-maybe)
9663 (if (and (equal arg '(64)) (org-region-active-p))
9664 (save-excursion
9665 (let ((end (region-end)))
9666 (goto-char (region-beginning))
9667 (set-mark (point))
9668 (while (< (point-at-eol) end)
9669 (move-end-of-line 1) (activate-mark)
9670 (let (current-prefix-arg)
9671 (call-interactively 'org-store-link))
9672 (move-beginning-of-line 2)
9673 (set-mark (point)))))
9674 (setq org-store-link-plist nil)
9675 (let (link cpltxt desc description search
9676 txt custom-id agenda-link sfuns sfunsn)
9677 (cond
9679 ;; Store a link using an external link type
9680 ((and (not (equal arg '(16)))
9681 (setq sfuns
9682 (delq
9683 nil (mapcar (lambda (f)
9684 (let (fs) (if (funcall f) (push f fs))))
9685 (org-store-link-functions)))
9686 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9687 (or (and (cdr sfuns)
9688 (funcall (intern
9689 (completing-read
9690 "Which function for creating the link? "
9691 sfunsn nil t (car sfunsn)))))
9692 (funcall (caar sfuns)))
9693 (setq link (plist-get org-store-link-plist :link)
9694 desc (or (plist-get org-store-link-plist
9695 :description)
9696 link))))
9698 ;; Store a link from a source code buffer.
9699 ((org-src-edit-buffer-p)
9700 (let ((coderef-format (org-src-coderef-format)))
9701 (cond ((save-excursion
9702 (beginning-of-line)
9703 (looking-at (org-src-coderef-regexp coderef-format)))
9704 (setq link (format "(%s)" (match-string-no-properties 3))))
9705 ((called-interactively-p 'any)
9706 (let ((label (read-string "Code line label: ")))
9707 (end-of-line)
9708 (setq link (format coderef-format label))
9709 (let ((gc (- 79 (length link))))
9710 (if (< (current-column) gc)
9711 (org-move-to-column gc t)
9712 (insert " ")))
9713 (insert link)
9714 (setq link (concat "(" label ")"))
9715 (setq desc nil)))
9716 (t (setq link nil)))))
9718 ;; We are in the agenda, link to referenced location
9719 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9720 (let ((m (or (get-text-property (point) 'org-hd-marker)
9721 (get-text-property (point) 'org-marker))))
9722 (when m
9723 (org-with-point-at m
9724 (setq agenda-link
9725 (if (called-interactively-p 'any)
9726 (call-interactively 'org-store-link)
9727 (org-store-link nil)))))))
9729 ((eq major-mode 'calendar-mode)
9730 (let ((cd (calendar-cursor-to-date)))
9731 (setq link
9732 (format-time-string
9733 (car org-time-stamp-formats)
9734 (apply 'encode-time
9735 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9736 nil nil nil))))
9737 (org-store-link-props :type "calendar" :date cd)))
9739 ((eq major-mode 'help-mode)
9740 (setq link (concat "help:" (save-excursion
9741 (goto-char (point-min))
9742 (looking-at "^[^ ]+")
9743 (match-string 0))))
9744 (org-store-link-props :type "help"))
9746 ((eq major-mode 'w3-mode)
9747 (setq cpltxt (if (and (buffer-name)
9748 (not (string-match "Untitled" (buffer-name))))
9749 (buffer-name)
9750 (url-view-url t))
9751 link (url-view-url t))
9752 (org-store-link-props :type "w3" :url (url-view-url t)))
9754 ((eq major-mode 'image-mode)
9755 (setq cpltxt (concat "file:"
9756 (abbreviate-file-name buffer-file-name))
9757 link cpltxt)
9758 (org-store-link-props :type "image" :file buffer-file-name))
9760 ;; In dired, store a link to the file of the current line
9761 ((derived-mode-p 'dired-mode)
9762 (let ((file (dired-get-filename nil t)))
9763 (setq file (if file
9764 (abbreviate-file-name
9765 (expand-file-name (dired-get-filename nil t)))
9766 ;; otherwise, no file so use current directory.
9767 default-directory))
9768 (setq cpltxt (concat "file:" file)
9769 link cpltxt)))
9771 ((setq search (run-hook-with-args-until-success
9772 'org-create-file-search-functions))
9773 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9774 "::" search))
9775 (setq cpltxt (or description link)))
9777 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9778 (org-with-limited-levels
9779 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9780 (cond
9781 ;; Store a link using the target at point
9782 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9783 (setq cpltxt
9784 (concat "file:"
9785 (abbreviate-file-name
9786 (buffer-file-name (buffer-base-buffer)))
9787 "::" (match-string 1))
9788 link cpltxt))
9789 ((and (featurep 'org-id)
9790 (or (eq org-id-link-to-org-use-id t)
9791 (and (called-interactively-p 'any)
9792 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9793 (and (eq org-id-link-to-org-use-id
9794 'create-if-interactive-and-no-custom-id)
9795 (not custom-id))))
9796 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9797 ;; Store a link using the ID at point
9798 (setq link (condition-case nil
9799 (prog1 (org-id-store-link)
9800 (setq desc (or (plist-get org-store-link-plist
9801 :description)
9802 "")))
9803 (error
9804 ;; Probably before first headline, link only to file
9805 (concat "file:"
9806 (abbreviate-file-name
9807 (buffer-file-name (buffer-base-buffer))))))))
9809 ;; Just link to current headline
9810 (setq cpltxt (concat "file:"
9811 (abbreviate-file-name
9812 (buffer-file-name (buffer-base-buffer)))))
9813 ;; Add a context search string
9814 (when (org-xor org-context-in-file-links
9815 (equal arg '(4)))
9816 (let* ((element (org-element-at-point))
9817 (name (org-element-property :name element)))
9818 (setq txt (cond
9819 ((org-at-heading-p) nil)
9820 (name)
9821 ((org-region-active-p)
9822 (buffer-substring (region-beginning) (region-end)))))
9823 (when (or (null txt) (string-match "\\S-" txt))
9824 (setq cpltxt
9825 (concat cpltxt "::"
9826 (condition-case nil
9827 (org-make-org-heading-search-string txt)
9828 (error "")))
9829 desc (or name
9830 (nth 4 (ignore-errors (org-heading-components)))
9831 "NONE")))))
9832 (when (string-match "::\\'" cpltxt)
9833 (setq cpltxt (substring cpltxt 0 -2)))
9834 (setq link cpltxt)))))
9836 ((buffer-file-name (buffer-base-buffer))
9837 ;; Just link to this file here.
9838 (setq cpltxt (concat "file:"
9839 (abbreviate-file-name
9840 (buffer-file-name (buffer-base-buffer)))))
9841 ;; Add a context string.
9842 (when (org-xor org-context-in-file-links
9843 (equal arg '(4)))
9844 (setq txt (if (org-region-active-p)
9845 (buffer-substring (region-beginning) (region-end))
9846 (buffer-substring (point-at-bol) (point-at-eol))))
9847 ;; Only use search option if there is some text.
9848 (when (string-match "\\S-" txt)
9849 (setq cpltxt
9850 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9851 desc "NONE")))
9852 (setq link cpltxt))
9854 ((called-interactively-p 'interactive)
9855 (user-error "No method for storing a link from this buffer"))
9857 (t (setq link nil)))
9859 ;; We're done setting link and desc, clean up
9860 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9861 (setq link (or link cpltxt)
9862 desc (or desc cpltxt))
9863 (cond ((not desc))
9864 ((equal desc "NONE") (setq desc nil))
9865 (t (setq desc
9866 (replace-regexp-in-string
9867 org-bracket-link-analytic-regexp
9868 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9869 desc))))
9870 ;; Return the link
9871 (if (not (and (or (called-interactively-p 'any)
9872 executing-kbd-macro)
9873 link))
9874 (or agenda-link (and link (org-make-link-string link desc)))
9875 (push (list link desc) org-stored-links)
9876 (message "Stored: %s" (or desc link))
9877 (when custom-id
9878 (setq link (concat "file:" (abbreviate-file-name
9879 (buffer-file-name)) "::#" custom-id))
9880 (push (list link desc) org-stored-links))
9881 (car org-stored-links)))))
9883 (defun org-store-link-props (&rest plist)
9884 "Store link properties, extract names, addresses and dates."
9885 (let ((x (plist-get plist :from)))
9886 (when x
9887 (let ((adr (mail-extract-address-components x)))
9888 (setq plist (plist-put plist :fromname (car adr)))
9889 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9890 (let ((x (plist-get plist :to)))
9891 (when x
9892 (let ((adr (mail-extract-address-components x)))
9893 (setq plist (plist-put plist :toname (car adr)))
9894 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9895 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9896 (when x
9897 (setq plist (plist-put plist :date-timestamp
9898 (format-time-string
9899 (org-time-stamp-format t) x)))
9900 (setq plist (plist-put plist :date-timestamp-inactive
9901 (format-time-string
9902 (org-time-stamp-format t t) x)))))
9903 (let ((from (plist-get plist :from))
9904 (to (plist-get plist :to)))
9905 (when (and from to org-from-is-user-regexp)
9906 (setq plist
9907 (plist-put plist :fromto
9908 (if (string-match org-from-is-user-regexp from)
9909 (concat "to %t")
9910 (concat "from %f"))))))
9911 (setq org-store-link-plist plist))
9913 (defun org-add-link-props (&rest plist)
9914 "Add these properties to the link property list."
9915 (let (key value)
9916 (while plist
9917 (setq key (pop plist) value (pop plist))
9918 (setq org-store-link-plist
9919 (plist-put org-store-link-plist key value)))))
9921 (defun org-email-link-description (&optional fmt)
9922 "Return the description part of an email link.
9923 This takes information from `org-store-link-plist' and formats it
9924 according to FMT (default from `org-email-link-description-format')."
9925 (setq fmt (or fmt org-email-link-description-format))
9926 (let* ((p org-store-link-plist)
9927 (to (plist-get p :toaddress))
9928 (from (plist-get p :fromaddress))
9929 (table
9930 (list
9931 (cons "%c" (plist-get p :fromto))
9932 (cons "%F" (plist-get p :from))
9933 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9934 (cons "%T" (plist-get p :to))
9935 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9936 (cons "%s" (plist-get p :subject))
9937 (cons "%d" (plist-get p :date))
9938 (cons "%m" (plist-get p :message-id)))))
9939 (when (string-match "%c" fmt)
9940 ;; Check if the user wrote this message
9941 (if (and org-from-is-user-regexp from to
9942 (save-match-data (string-match org-from-is-user-regexp from)))
9943 (setq fmt (replace-match "to %t" t t fmt))
9944 (setq fmt (replace-match "from %f" t t fmt))))
9945 (org-replace-escapes fmt table)))
9947 (defun org-make-org-heading-search-string (&optional string)
9948 "Make search string for the current headline or STRING."
9949 (let ((s (or string
9950 (and (derived-mode-p 'org-mode)
9951 (save-excursion
9952 (org-back-to-heading t)
9953 (org-element-property :raw-value (org-element-at-point))))))
9954 (lines org-context-in-file-links))
9955 (or string (setq s (concat "*" s))) ; Add * for headlines
9956 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9957 (when (and string (integerp lines) (> lines 0))
9958 (let ((slines (org-split-string s "\n")))
9959 (when (< lines (length slines))
9960 (setq s (mapconcat
9961 'identity
9962 (reverse (nthcdr (- (length slines) lines)
9963 (reverse slines))) "\n")))))
9964 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9966 (defun org-make-link-string (link &optional description)
9967 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9968 (unless (org-string-nw-p link) (error "Empty link"))
9969 (let ((uri (cond ((string-match org-link-types-re link)
9970 (concat (match-string 1 link)
9971 (org-link-escape (substring link (match-end 1)))))
9972 ;; For readability, url-encode internal links only
9973 ;; when absolutely needed (i.e, when they contain
9974 ;; square brackets). File links however, are
9975 ;; encoded since, e.g., spaces are significant.
9976 ((or (file-name-absolute-p link)
9977 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9978 (org-link-escape link))
9979 (t link)))
9980 (description
9981 (and (org-string-nw-p description)
9982 ;; Remove brackets from description, as they are fatal.
9983 (replace-regexp-in-string
9984 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9985 (org-trim description)))))
9986 (format "[[%s]%s]"
9988 (if description (format "[%s]" description) ""))))
9990 (defconst org-link-escape-chars
9991 ;;%20 %5B %5D %25
9992 '(?\s ?\[ ?\] ?%)
9993 "List of characters that should be escaped in a link when stored to Org.
9994 This is the list that is used for internal purposes.")
9996 (defun org-link-escape (text &optional table merge)
9997 "Return percent escaped representation of TEXT.
9998 TEXT is a string with the text to escape.
9999 Optional argument TABLE is a list with characters that should be
10000 escaped. When nil, `org-link-escape-chars' is used.
10001 If optional argument MERGE is set, merge TABLE into
10002 `org-link-escape-chars'."
10003 (let ((characters-to-encode
10004 (cond ((null table) org-link-escape-chars)
10005 (merge (append org-link-escape-chars table))
10006 (t table))))
10007 (mapconcat
10008 (lambda (c)
10009 (if (or (memq c characters-to-encode)
10010 (and org-url-hexify-p (or (< c 32) (> c 126))))
10011 (mapconcat (lambda (e) (format "%%%.2X" e))
10012 (or (encode-coding-char c 'utf-8)
10013 (error "Unable to percent escape character: %c" c))
10015 (char-to-string c)))
10016 text "")))
10018 (defun org-link-unescape (str)
10019 "Unhex hexified Unicode parts in string STR.
10020 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10021 reciprocal of `org-link-escape', which see."
10022 (if (org-string-nw-p str)
10023 (replace-regexp-in-string
10024 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10025 str))
10027 (defun org-link-unescape-compound (hex)
10028 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10029 Note: this function also decodes single byte encodings like
10030 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10031 (save-match-data
10032 (let* ((bytes (cdr (split-string hex "%")))
10033 (ret "")
10034 (eat 0)
10035 (sum 0))
10036 (while bytes
10037 (let* ((val (string-to-number (pop bytes) 16))
10038 (shift-xor
10039 (if (= 0 eat)
10040 (cond
10041 ((>= val 252) (cons 6 252))
10042 ((>= val 248) (cons 5 248))
10043 ((>= val 240) (cons 4 240))
10044 ((>= val 224) (cons 3 224))
10045 ((>= val 192) (cons 2 192))
10046 (t (cons 0 0)))
10047 (cons 6 128))))
10048 (when (>= val 192) (setq eat (car shift-xor)))
10049 (setq val (logxor val (cdr shift-xor)))
10050 (setq sum (+ (lsh sum (car shift-xor)) val))
10051 (when (> eat 0) (setq eat (- eat 1)))
10052 (cond
10053 ((= 0 eat) ;multi byte
10054 (setq ret (concat ret (char-to-string sum)))
10055 (setq sum 0))
10056 ((not bytes) ; single byte(s)
10057 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10058 ret)))
10060 (defun org-link-unescape-single-byte-sequence (hex)
10061 "Unhexify hex-encoded single byte character sequences."
10062 (mapconcat (lambda (byte)
10063 (char-to-string (string-to-number byte 16)))
10064 (cdr (split-string hex "%")) ""))
10066 (defun org-xor (a b)
10067 "Exclusive or."
10068 (if a (not b) b))
10070 (defun org-fixup-message-id-for-http (s)
10071 "Replace special characters in a message id, so it can be used in an http query."
10072 (when (string-match "%" s)
10073 (setq s (mapconcat (lambda (c)
10074 (if (eq c ?%)
10075 "%25"
10076 (char-to-string c)))
10077 s "")))
10078 (while (string-match "<" s)
10079 (setq s (replace-match "%3C" t t s)))
10080 (while (string-match ">" s)
10081 (setq s (replace-match "%3E" t t s)))
10082 (while (string-match "@" s)
10083 (setq s (replace-match "%40" t t s)))
10086 (defun org-link-prettify (link)
10087 "Return a human-readable representation of LINK.
10088 The car of LINK must be a raw link.
10089 The cdr of LINK must be either a link description or nil."
10090 (let ((desc (or (cadr link) "<no description>")))
10091 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10092 "<" (car link) ">")))
10094 ;;;###autoload
10095 (defun org-insert-link-global ()
10096 "Insert a link like Org mode does.
10097 This command can be called in any mode to insert a link in Org syntax."
10098 (interactive)
10099 (org-load-modules-maybe)
10100 (org-run-like-in-org-mode 'org-insert-link))
10102 (defun org-insert-all-links (arg &optional pre post)
10103 "Insert all links in `org-stored-links'.
10104 When a universal prefix, do not delete the links from `org-stored-links'.
10105 When `ARG' is a number, insert the last N link(s).
10106 `PRE' and `POST' are optional arguments to define a string to
10107 prepend or to append."
10108 (interactive "P")
10109 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10110 (links (copy-sequence org-stored-links))
10111 (pr (or pre "- "))
10112 (po (or post "\n"))
10113 (cnt 1) l)
10114 (if (null org-stored-links)
10115 (message "No link to insert")
10116 (while (and (or (listp arg) (>= arg cnt))
10117 (setq l (if (listp arg)
10118 (pop links)
10119 (pop org-stored-links))))
10120 (setq cnt (1+ cnt))
10121 (insert pr)
10122 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10123 (insert po)))))
10125 (defun org-insert-last-stored-link (arg)
10126 "Insert the last link stored in `org-stored-links'."
10127 (interactive "p")
10128 (org-insert-all-links arg "" "\n"))
10130 (defun org-link-fontify-links-to-this-file ()
10131 "Fontify links to the current file in `org-stored-links'."
10132 (let ((f (buffer-file-name)) a b)
10133 (setq a (mapcar (lambda(l)
10134 (let ((ll (car l)))
10135 (when (and (string-match "^file:\\(.+\\)::" ll)
10136 (equal f (expand-file-name (match-string 1 ll))))
10137 ll)))
10138 org-stored-links))
10139 (when (featurep 'org-id)
10140 (setq b (mapcar (lambda(l)
10141 (let ((ll (car l)))
10142 (when (and (string-match "^id:\\(.+\\)$" ll)
10143 (equal f (expand-file-name
10144 (or (org-id-find-id-file
10145 (match-string 1 ll)) ""))))
10146 ll)))
10147 org-stored-links)))
10148 (mapcar (lambda(l)
10149 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10150 (delq nil (append a b)))))
10152 (defvar org--links-history nil)
10153 (defun org-insert-link (&optional complete-file link-location default-description)
10154 "Insert a link. At the prompt, enter the link.
10156 Completion can be used to insert any of the link protocol prefixes in use.
10158 The history can be used to select a link previously stored with
10159 `org-store-link'. When the empty string is entered (i.e. if you just
10160 press `RET' at the prompt), the link defaults to the most recently
10161 stored link. As `SPC' triggers completion in the minibuffer, you need to
10162 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10164 You will also be prompted for a description, and if one is given, it will
10165 be displayed in the buffer instead of the link.
10167 If there is already a link at point, this command will allow you to edit
10168 link and description parts.
10170 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10171 file name can be
10172 selected using completion. The path to the file will be relative to the
10173 current directory if the file is in the current directory or a subdirectory.
10174 Otherwise, the link will be the absolute path as completed in the minibuffer
10175 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10176 option `org-link-file-path-type'.
10178 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10179 absolute path even if the file is in
10180 the current directory or below.
10182 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10183 prefix negates `org-keep-stored-link-after-insertion'.
10185 If `org-make-link-description-function' is non-nil, this function will be
10186 called with the link target, and the result will be the default
10187 link description.
10189 If the LINK-LOCATION parameter is non-nil, this value will be used as
10190 the link location instead of reading one interactively.
10192 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10193 as the default description."
10194 (interactive "P")
10195 (let* ((wcf (current-window-configuration))
10196 (origbuf (current-buffer))
10197 (region (when (org-region-active-p)
10198 (buffer-substring (region-beginning) (region-end))))
10199 (remove (and region (list (region-beginning) (region-end))))
10200 (desc region)
10201 (link link-location)
10202 (abbrevs org-link-abbrev-alist-local)
10203 entry all-prefixes auto-desc)
10204 (cond
10205 (link-location) ; specified by arg, just use it.
10206 ((org-in-regexp org-bracket-link-regexp 1)
10207 ;; We do have a link at point, and we are going to edit it.
10208 (setq remove (list (match-beginning 0) (match-end 0)))
10209 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10210 (setq link (read-string "Link: "
10211 (org-link-unescape
10212 (match-string-no-properties 1)))))
10213 ((or (org-in-regexp org-angle-link-re)
10214 (org-in-regexp org-plain-link-re))
10215 ;; Convert to bracket link
10216 (setq remove (list (match-beginning 0) (match-end 0))
10217 link (read-string "Link: "
10218 (org-unbracket-string "<" ">" (match-string 0)))))
10219 ((member complete-file '((4) (16)))
10220 ;; Completing read for file names.
10221 (setq link (org-file-complete-link complete-file)))
10223 ;; Read link, with completion for stored links.
10224 (org-link-fontify-links-to-this-file)
10225 (org-switch-to-buffer-other-window "*Org Links*")
10226 (with-current-buffer "*Org Links*"
10227 (erase-buffer)
10228 (insert "Insert a link.
10229 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10230 (when org-stored-links
10231 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10232 (insert (mapconcat 'org-link-prettify
10233 (reverse org-stored-links) "\n")))
10234 (goto-char (point-min)))
10235 (let ((cw (selected-window)))
10236 (select-window (get-buffer-window "*Org Links*" 'visible))
10237 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10238 (unless (pos-visible-in-window-p (point-max))
10239 (org-fit-window-to-buffer))
10240 (and (window-live-p cw) (select-window cw)))
10241 (setq all-prefixes (append (mapcar 'car abbrevs)
10242 (mapcar 'car org-link-abbrev-alist)
10243 (org-link-types)))
10244 (unwind-protect
10245 ;; Fake a link history, containing the stored links.
10246 (let ((org--links-history
10247 (append (mapcar #'car org-stored-links)
10248 org-insert-link-history)))
10249 (setq link
10250 (org-completing-read
10251 "Link: "
10252 (append
10253 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10254 (mapcar #'car org-stored-links))
10255 nil nil nil
10256 'org--links-history
10257 (caar org-stored-links)))
10258 (unless (org-string-nw-p link) (user-error "No link selected"))
10259 (dolist (l org-stored-links)
10260 (when (equal link (cadr l))
10261 (setq link (car l))
10262 (setq auto-desc t)))
10263 (when (or (member link all-prefixes)
10264 (and (equal ":" (substring link -1))
10265 (member (substring link 0 -1) all-prefixes)
10266 (setq link (substring link 0 -1))))
10267 (setq link (with-current-buffer origbuf
10268 (org-link-try-special-completion link)))))
10269 (set-window-configuration wcf)
10270 (kill-buffer "*Org Links*"))
10271 (setq entry (assoc link org-stored-links))
10272 (or entry (push link org-insert-link-history))
10273 (setq desc (or desc (nth 1 entry)))))
10275 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10276 (not org-keep-stored-link-after-insertion))
10277 (setq org-stored-links (delq (assoc link org-stored-links)
10278 org-stored-links)))
10280 (when (and (string-match org-plain-link-re link)
10281 (not (string-match org-ts-regexp link)))
10282 ;; URL-like link, normalize the use of angular brackets.
10283 (setq link (org-unbracket-string "<" ">" link)))
10285 ;; Check if we are linking to the current file with a search
10286 ;; option If yes, simplify the link by using only the search
10287 ;; option.
10288 (when (and buffer-file-name
10289 (let ((case-fold-search nil))
10290 (string-match "\\`file:\\(.+?\\)::" link)))
10291 (let ((path (match-string-no-properties 1 link))
10292 (search (substring-no-properties link (match-end 0))))
10293 (save-match-data
10294 (when (equal (file-truename buffer-file-name) (file-truename path))
10295 ;; We are linking to this same file, with a search option
10296 (setq link search)))))
10298 ;; Check if we can/should use a relative path. If yes, simplify the link
10299 (let ((case-fold-search nil))
10300 (when (string-match "\\`\\(file\\|docview\\):" link)
10301 (let* ((type (match-string-no-properties 0 link))
10302 (path (substring-no-properties link (match-end 0)))
10303 (origpath path))
10304 (cond
10305 ((or (eq org-link-file-path-type 'absolute)
10306 (equal complete-file '(16)))
10307 (setq path (abbreviate-file-name (expand-file-name path))))
10308 ((eq org-link-file-path-type 'noabbrev)
10309 (setq path (expand-file-name path)))
10310 ((eq org-link-file-path-type 'relative)
10311 (setq path (file-relative-name path)))
10313 (save-match-data
10314 (if (string-match (concat "^" (regexp-quote
10315 (expand-file-name
10316 (file-name-as-directory
10317 default-directory))))
10318 (expand-file-name path))
10319 ;; We are linking a file with relative path name.
10320 (setq path (substring (expand-file-name path)
10321 (match-end 0)))
10322 (setq path (abbreviate-file-name (expand-file-name path)))))))
10323 (setq link (concat type path))
10324 (when (equal desc origpath)
10325 (setq desc path)))))
10327 (if org-make-link-description-function
10328 (setq desc
10329 (or (condition-case nil
10330 (funcall org-make-link-description-function link desc)
10331 (error (progn (message "Can't get link description from `%s'"
10332 (symbol-name org-make-link-description-function))
10333 (sit-for 2) nil)))
10334 (read-string "Description: " default-description)))
10335 (if default-description (setq desc default-description)
10336 (setq desc (or (and auto-desc desc)
10337 (read-string "Description: " desc)))))
10339 (unless (string-match "\\S-" desc) (setq desc nil))
10340 (when remove (apply 'delete-region remove))
10341 (insert (org-make-link-string link desc))
10342 ;; Redisplay so as the new link has proper invisible characters.
10343 (sit-for 0)))
10345 (defun org-link-try-special-completion (type)
10346 "If there is completion support for link type TYPE, offer it."
10347 (let ((fun (org-link-get-parameter type :complete)))
10348 (if (functionp fun)
10349 (funcall fun)
10350 (read-string "Link (no completion support): " (concat type ":")))))
10352 (defun org-file-complete-link (&optional arg)
10353 "Create a file link using completion."
10354 (let ((file (read-file-name "File: "))
10355 (pwd (file-name-as-directory (expand-file-name ".")))
10356 (pwd1 (file-name-as-directory (abbreviate-file-name
10357 (expand-file-name ".")))))
10358 (cond ((equal arg '(16))
10359 (concat "file:"
10360 (abbreviate-file-name (expand-file-name file))))
10361 ((string-match
10362 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10363 (concat "file:" (match-string 1 file)))
10364 ((string-match
10365 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10366 (expand-file-name file))
10367 (concat "file:"
10368 (match-string 1 (expand-file-name file))))
10369 (t (concat "file:" file)))))
10371 (defun org-completing-read (&rest args)
10372 "Completing-read with SPACE being a normal character."
10373 (let ((enable-recursive-minibuffers t)
10374 (minibuffer-local-completion-map
10375 (copy-keymap minibuffer-local-completion-map)))
10376 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10377 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10378 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10379 'org-time-stamp-inactive)
10380 (apply #'completing-read args)))
10382 ;;; Opening/following a link
10384 (defvar org-link-search-failed nil)
10386 (defvar org-open-link-functions nil
10387 "Hook for functions finding a plain text link.
10388 These functions must take a single argument, the link content.
10389 They will be called for links that look like [[link text][description]]
10390 when LINK TEXT does not have a protocol like \"http:\" and does not look
10391 like a filename (e.g. \"./blue.png\").
10393 These functions will be called *before* Org attempts to resolve the
10394 link by doing text searches in the current buffer - so if you want a
10395 link \"[[target]]\" to still find \"<<target>>\", your function should
10396 handle this as a special case.
10398 When the function does handle the link, it must return a non-nil value.
10399 If it decides that it is not responsible for this link, it must return
10400 nil to indicate that that Org can continue with other options like
10401 exact and fuzzy text search.")
10403 (defun org-next-link (&optional search-backward)
10404 "Move forward to the next link.
10405 If the link is in hidden text, expose it."
10406 (interactive "P")
10407 (when (and org-link-search-failed (eq this-command last-command))
10408 (goto-char (point-min))
10409 (message "Link search wrapped back to beginning of buffer"))
10410 (setq org-link-search-failed nil)
10411 (let* ((pos (point))
10412 (ct (org-context))
10413 (a (assq :link ct))
10414 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10415 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10416 ((looking-at org-any-link-re)
10417 ;; Don't stay stuck at link without an org-link face
10418 (forward-char (if search-backward -1 1))))
10419 (if (funcall srch-fun org-any-link-re nil t)
10420 (progn
10421 (goto-char (match-beginning 0))
10422 (when (org-invisible-p) (org-show-context)))
10423 (goto-char pos)
10424 (setq org-link-search-failed t)
10425 (message "No further link found"))))
10427 (defun org-previous-link ()
10428 "Move backward to the previous link.
10429 If the link is in hidden text, expose it."
10430 (interactive)
10431 (funcall 'org-next-link t))
10433 (defun org-translate-link (s)
10434 "Translate a link string if a translation function has been defined."
10435 (with-temp-buffer
10436 (insert (org-trim s))
10437 (org-trim (org-element-interpret-data (org-element-context)))))
10439 (defun org-translate-link-from-planner (type path)
10440 "Translate a link from Emacs Planner syntax so that Org can follow it.
10441 This is still an experimental function, your mileage may vary."
10442 (cond
10443 ((member type '("http" "https" "news" "ftp"))
10444 ;; standard Internet links are the same.
10445 nil)
10446 ((and (equal type "irc") (string-match "^//" path))
10447 ;; Planner has two / at the beginning of an irc link, we have 1.
10448 ;; We should have zero, actually....
10449 (setq path (substring path 1)))
10450 ((and (equal type "lisp") (string-match "^/" path))
10451 ;; Planner has a slash, we do not.
10452 (setq type "elisp" path (substring path 1)))
10453 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10454 ;; A typical message link. Planner has the id after the final slash,
10455 ;; we separate it with a hash mark
10456 (setq path (concat (match-string 1 path) "#"
10457 (org-unbracket-string "<" ">" (match-string 2 path))))))
10458 (cons type path))
10460 (defun org-find-file-at-mouse (ev)
10461 "Open file link or URL at mouse."
10462 (interactive "e")
10463 (mouse-set-point ev)
10464 (org-open-at-point 'in-emacs))
10466 (defun org-open-at-mouse (ev)
10467 "Open file link or URL at mouse.
10468 See the docstring of `org-open-file' for details."
10469 (interactive "e")
10470 (mouse-set-point ev)
10471 (when (eq major-mode 'org-agenda-mode)
10472 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10473 (org-open-at-point))
10475 (defvar org-window-config-before-follow-link nil
10476 "The window configuration before following a link.
10477 This is saved in case the need arises to restore it.")
10479 ;;;###autoload
10480 (defun org-open-at-point-global ()
10481 "Follow a link or time-stamp like Org mode does.
10482 This command can be called in any mode to follow an external link
10483 or a time-stamp that has Org mode syntax. Its behavior is
10484 undefined when called on internal links (e.g., fuzzy links).
10485 Raise an error when there is nothing to follow. "
10486 (interactive)
10487 (cond ((org-in-regexp org-any-link-re)
10488 (org-open-link-from-string (match-string-no-properties 0)))
10489 ((or (org-in-regexp org-ts-regexp-both nil t)
10490 (org-in-regexp org-tsr-regexp-both nil t))
10491 (org-follow-timestamp-link))
10492 (t (user-error "No link found"))))
10494 ;;;###autoload
10495 (defun org-open-link-from-string (s &optional arg reference-buffer)
10496 "Open a link in the string S, as if it was in Org mode."
10497 (interactive "sLink: \nP")
10498 (let ((reference-buffer (or reference-buffer (current-buffer))))
10499 (with-temp-buffer
10500 (let ((org-inhibit-startup (not reference-buffer)))
10501 (org-mode)
10502 (insert s)
10503 (goto-char (point-min))
10504 (when reference-buffer
10505 (setq org-link-abbrev-alist-local
10506 (with-current-buffer reference-buffer
10507 org-link-abbrev-alist-local)))
10508 (org-open-at-point arg reference-buffer)))))
10510 (defvar org-open-at-point-functions nil
10511 "Hook that is run when following a link at point.
10513 Functions in this hook must return t if they identify and follow
10514 a link at point. If they don't find anything interesting at point,
10515 they must return nil.")
10517 (defvar org-link-search-inhibit-query nil)
10518 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10519 (defun org--open-doi-link (path)
10520 "Open a \"doi\" type link.
10521 PATH is a the path to search for, as a string."
10522 (browse-url (url-encode-url (concat org-doi-server-url path))))
10524 (defun org--open-elisp-link (path)
10525 "Open a \"elisp\" type link.
10526 PATH is the sexp to evaluate, as a string."
10527 (let ((cmd path))
10528 (if (or (and (org-string-nw-p
10529 org-confirm-elisp-link-not-regexp)
10530 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10531 (not org-confirm-elisp-link-function)
10532 (funcall org-confirm-elisp-link-function
10533 (format "Execute \"%s\" as elisp? "
10534 (org-add-props cmd nil 'face 'org-warning))))
10535 (message "%s => %s" cmd
10536 (if (eq (string-to-char cmd) ?\()
10537 (eval (read cmd))
10538 (call-interactively (read cmd))))
10539 (user-error "Abort"))))
10541 (defun org--open-help-link (path)
10542 "Open a \"help\" type link.
10543 PATH is a symbol name, as a string."
10544 (pcase (intern path)
10545 ((and (pred fboundp) variable) (describe-function variable))
10546 ((and (pred boundp) function) (describe-variable function))
10547 (name (user-error "Unknown function or variable: %s" name))))
10549 (defun org--open-shell-link (path)
10550 "Open a \"shell\" type link.
10551 PATH is the command to execute, as a string."
10552 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10553 (cmd path))
10554 (if (or (and (org-string-nw-p
10555 org-confirm-shell-link-not-regexp)
10556 (string-match
10557 org-confirm-shell-link-not-regexp cmd))
10558 (not org-confirm-shell-link-function)
10559 (funcall org-confirm-shell-link-function
10560 (format "Execute \"%s\" in shell? "
10561 (org-add-props cmd nil
10562 'face 'org-warning))))
10563 (progn
10564 (message "Executing %s" cmd)
10565 (shell-command cmd buf)
10566 (when (featurep 'midnight)
10567 (setq clean-buffer-list-kill-buffer-names
10568 (cons (buffer-name buf)
10569 clean-buffer-list-kill-buffer-names))))
10570 (user-error "Abort"))))
10572 (defun org-open-at-point (&optional arg reference-buffer)
10573 "Open link, timestamp, footnote or tags at point.
10575 When point is on a link, follow it. Normally, files will be
10576 opened by an appropriate application. If the optional prefix
10577 argument ARG is non-nil, Emacs will visit the file. With
10578 a double prefix argument, try to open outside of Emacs, in the
10579 application the system uses for this file type.
10581 When point is on a timestamp, open the agenda at the day
10582 specified.
10584 When point is a footnote definition, move to the first reference
10585 found. If it is on a reference, move to the associated
10586 definition.
10588 When point is on a headline, display a list of every link in the
10589 entry, so it is possible to pick one, or all, of them. If point
10590 is on a tag, call `org-tags-view' instead.
10592 When optional argument REFERENCE-BUFFER is non-nil, it should
10593 specify a buffer from where the link search should happen. This
10594 is used internally by `org-open-link-from-string'.
10596 On top of syntactically correct links, this function will also
10597 try to open links and time-stamps in comments, example
10598 blocks... i.e., whenever point is on something looking like
10599 a timestamp or a link."
10600 (interactive "P")
10601 ;; On a code block, open block's results.
10602 (unless (call-interactively 'org-babel-open-src-block-result)
10603 (org-load-modules-maybe)
10604 (setq org-window-config-before-follow-link (current-window-configuration))
10605 (org-remove-occur-highlights nil nil t)
10606 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10607 (let* ((context
10608 ;; Only consider supported types, even if they are not
10609 ;; the closest one.
10610 (org-element-lineage
10611 (org-element-context)
10612 '(clock footnote-definition footnote-reference headline
10613 inlinetask link timestamp)
10615 (type (org-element-type context))
10616 (value (org-element-property :value context)))
10617 (cond
10618 ;; On a headline or an inlinetask, but not on a timestamp,
10619 ;; a link, a footnote reference.
10620 ((memq type '(headline inlinetask))
10621 (org-match-line org-complex-heading-regexp)
10622 (if (and (match-beginning 5)
10623 (>= (point) (match-beginning 5))
10624 (< (point) (match-end 5)))
10625 ;; On tags.
10626 (org-tags-view arg (substring (match-string 5) 0 -1))
10627 ;; Not on tags.
10628 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10629 (`(nil . ,_)
10630 (require 'org-attach)
10631 (org-attach-reveal 'if-exists))
10632 (`(,links . ,links-end)
10633 (dolist (link (if (stringp links) (list links) links))
10634 (search-forward link nil links-end)
10635 (goto-char (match-beginning 0))
10636 (org-open-at-point))))))
10637 ;; On a footnote reference or at definition's label.
10638 ((or (eq type 'footnote-reference)
10639 (and (eq type 'footnote-definition)
10640 (save-excursion
10641 ;; Do not validate action when point is on the
10642 ;; spaces right after the footnote label, in
10643 ;; order to be on par with behaviour on links.
10644 (skip-chars-forward " \t")
10645 (let ((begin
10646 (org-element-property :contents-begin context)))
10647 (if begin (< (point) begin)
10648 (= (org-element-property :post-affiliated context)
10649 (line-beginning-position)))))))
10650 (org-footnote-action))
10651 ;; No valid context. Ignore catch-all types like `headline'.
10652 ;; If point is on something looking like a link or
10653 ;; a time-stamp, try opening it. It may be useful in
10654 ;; comments, example blocks...
10655 ((memq type '(footnote-definition headline inlinetask nil))
10656 (call-interactively #'org-open-at-point-global))
10657 ;; On a clock line, make sure point is on the timestamp
10658 ;; before opening it.
10659 ((and (eq type 'clock)
10660 value
10661 (>= (point) (org-element-property :begin value))
10662 (<= (point) (org-element-property :end value)))
10663 (org-follow-timestamp-link))
10664 ;; Do nothing on white spaces after an object.
10665 ((>= (point)
10666 (save-excursion
10667 (goto-char (org-element-property :end context))
10668 (skip-chars-backward " \t")
10669 (point)))
10670 (user-error "No link found"))
10671 ((eq type 'timestamp) (org-follow-timestamp-link))
10672 ((eq type 'link)
10673 (let ((type (org-element-property :type context))
10674 (path (org-link-unescape (org-element-property :path context))))
10675 ;; Switch back to REFERENCE-BUFFER needed when called in
10676 ;; a temporary buffer through `org-open-link-from-string'.
10677 (with-current-buffer (or reference-buffer (current-buffer))
10678 (cond
10679 ((equal type "file")
10680 (if (string-match "[*?{]" (file-name-nondirectory path))
10681 (dired path)
10682 ;; Look into `org-link-parameters' in order to find
10683 ;; a DEDICATED-FUNCTION to open file. The function
10684 ;; will be applied on raw link instead of parsed
10685 ;; link due to the limitation in `org-add-link-type'
10686 ;; ("open" function called with a single argument).
10687 ;; If no such function is found, fallback to
10688 ;; `org-open-file'.
10689 (let* ((option (org-element-property :search-option context))
10690 (app (org-element-property :application context))
10691 (dedicated-function
10692 (org-link-get-parameter
10693 (if app (concat type "+" app) type)
10694 :follow)))
10695 (if dedicated-function
10696 (funcall dedicated-function
10697 (concat path
10698 (and option (concat "::" option))))
10699 (apply #'org-open-file
10700 path
10701 (cond (arg)
10702 ((equal app "emacs") 'emacs)
10703 ((equal app "sys") 'system))
10704 (cond ((not option) nil)
10705 ((string-match-p "\\`[0-9]+\\'" option)
10706 (list (string-to-number option)))
10707 (t (list nil
10708 (org-link-unescape option)))))))))
10709 ((functionp (org-link-get-parameter type :follow))
10710 (funcall (org-link-get-parameter type :follow) path))
10711 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10712 (unless (run-hook-with-args-until-success
10713 'org-open-link-functions path)
10714 (if (not arg) (org-mark-ring-push)
10715 (switch-to-buffer-other-window
10716 (org-get-buffer-for-internal-link (current-buffer))))
10717 (let ((destination
10718 (org-with-wide-buffer
10719 (if (equal type "radio")
10720 (org-search-radio-target
10721 (org-element-property :path context))
10722 (org-link-search
10723 (if (member type '("custom-id" "coderef"))
10724 (org-element-property :raw-link context)
10725 path)
10726 ;; Prevent fuzzy links from matching
10727 ;; themselves.
10728 (and (equal type "fuzzy")
10729 (+ 2 (org-element-property :begin context)))))
10730 (point))))
10731 (unless (and (<= (point-min) destination)
10732 (>= (point-max) destination))
10733 (widen))
10734 (goto-char destination))))
10735 (t (browse-url-at-point))))))
10736 (t (user-error "No link found")))))
10737 (run-hook-with-args 'org-follow-link-hook)))
10739 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10740 "Offer links in the current entry and return the selected link.
10741 If there is only one link, return it.
10742 If NTH is an integer, return the NTH link found.
10743 If ZERO is a string, check also this string for a link, and if
10744 there is one, return it."
10745 (with-current-buffer buffer
10746 (org-with-wide-buffer
10747 (goto-char marker)
10748 (let ((cnt ?0)
10749 have-zero end links link c)
10750 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10751 (push (match-string 0 zero) links)
10752 (setq cnt (1- cnt) have-zero t))
10753 (save-excursion
10754 (org-back-to-heading t)
10755 (setq end (save-excursion (outline-next-heading) (point)))
10756 (while (re-search-forward org-any-link-re end t)
10757 (push (match-string 0) links))
10758 (setq links (org-uniquify (reverse links))))
10759 (cond
10760 ((null links)
10761 (message "No links"))
10762 ((equal (length links) 1)
10763 (setq link (car links)))
10764 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10765 (setq link (nth (if have-zero nth (1- nth)) links)))
10766 (t ; we have to select a link
10767 (save-excursion
10768 (save-window-excursion
10769 (delete-other-windows)
10770 (with-output-to-temp-buffer "*Select Link*"
10771 (dolist (l links)
10772 (cond
10773 ((not (string-match org-bracket-link-regexp l))
10774 (princ (format "[%c] %s\n" (cl-incf cnt)
10775 (org-unbracket-string "<" ">" l))))
10776 ((match-end 3)
10777 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10778 (match-string 3 l) (match-string 1 l))))
10779 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10780 (match-string 1 l)))))))
10781 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10782 (message "Select link to open, RET to open all:")
10783 (setq c (read-char-exclusive))
10784 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10785 (when (equal c ?q) (user-error "Abort"))
10786 (if (equal c ?\C-m)
10787 (setq link links)
10788 (setq nth (- c ?0))
10789 (when have-zero (setq nth (1+ nth)))
10790 (unless (and (integerp nth) (>= (length links) nth))
10791 (user-error "Invalid link selection"))
10792 (setq link (nth (1- nth) links)))))
10793 (cons link end)))))
10795 ;; TODO: These functions are deprecated since `org-open-at-point'
10796 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10797 (defun org-open-file-with-system (path)
10798 "Open file at PATH using the system way of opening it."
10799 (org-open-file path 'system))
10800 (defun org-open-file-with-emacs (path)
10801 "Open file at PATH in Emacs."
10802 (org-open-file path 'emacs))
10805 ;;; File search
10807 (defvar org-create-file-search-functions nil
10808 "List of functions to construct the right search string for a file link.
10809 These functions are called in turn with point at the location to
10810 which the link should point.
10812 A function in the hook should first test if it would like to
10813 handle this file type, for example by checking the `major-mode'
10814 or the file extension. If it decides not to handle this file, it
10815 should just return nil to give other functions a chance. If it
10816 does handle the file, it must return the search string to be used
10817 when following the link. The search string will be part of the
10818 file link, given after a double colon, and `org-open-at-point'
10819 will automatically search for it. If special measures must be
10820 taken to make the search successful, another function should be
10821 added to the companion hook `org-execute-file-search-functions',
10822 which see.
10824 A function in this hook may also use `setq' to set the variable
10825 `description' to provide a suggestion for the descriptive text to
10826 be used for this link when it gets inserted into an Org buffer
10827 with \\[org-insert-link].")
10829 (defvar org-execute-file-search-functions nil
10830 "List of functions to execute a file search triggered by a link.
10832 Functions added to this hook must accept a single argument, the
10833 search string that was part of the file link, the part after the
10834 double colon. The function must first check if it would like to
10835 handle this search, for example by checking the `major-mode' or
10836 the file extension. If it decides not to handle this search, it
10837 should just return nil to give other functions a chance. If it
10838 does handle the search, it must return a non-nil value to keep
10839 other functions from trying.
10841 Each function can access the current prefix argument through the
10842 variable `current-prefix-arg'. Note that a single prefix is used
10843 to force opening a link in Emacs, so it may be good to only use a
10844 numeric or double prefix to guide the search function.
10846 In case this is needed, a function in this hook can also restore
10847 the window configuration before `org-open-at-point' was called using:
10849 (set-window-configuration org-window-config-before-follow-link)")
10851 (defun org-search-radio-target (target)
10852 "Search a radio target matching TARGET in current buffer.
10853 White spaces are not significant."
10854 (let ((re (format "<<<%s>>>"
10855 (mapconcat #'regexp-quote
10856 (org-split-string target "[ \t\n]+")
10857 "[ \t]+\\(?:\n[ \t]*\\)?")))
10858 (origin (point)))
10859 (goto-char (point-min))
10860 (catch :radio-match
10861 (while (re-search-forward re nil t)
10862 (backward-char)
10863 (let ((object (org-element-context)))
10864 (when (eq (org-element-type object) 'radio-target)
10865 (goto-char (org-element-property :begin object))
10866 (org-show-context 'link-search)
10867 (throw :radio-match nil))))
10868 (goto-char origin)
10869 (user-error "No match for radio target: %s" target))))
10871 (defun org-link-search (s &optional avoid-pos stealth)
10872 "Search for a search string S.
10874 If S starts with \"#\", it triggers a custom ID search.
10876 If S is enclosed within parenthesis, it initiates a coderef
10877 search.
10879 If S is surrounded by forward slashes, it is interpreted as
10880 a regular expression. In Org mode files, this will create an
10881 `org-occur' sparse tree. In ordinary files, `occur' will be used
10882 to list matches. If the current buffer is in `dired-mode', grep
10883 will be used to search in all files.
10885 When AVOID-POS is given, ignore matches near that position.
10887 When optional argument STEALTH is non-nil, do not modify
10888 visibility around point, thus ignoring `org-show-context-detail'
10889 variable.
10891 Search is case-insensitive and ignores white spaces. Return type
10892 of matched result, which is either `dedicated' or `fuzzy'."
10893 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10894 (let* ((case-fold-search t)
10895 (origin (point))
10896 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10897 (starred (eq (string-to-char normalized) ?*))
10898 (words (split-string (if starred (substring s 1) s)))
10899 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10900 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10901 type)
10902 (cond
10903 ;; Check if there are any special search functions.
10904 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10905 ((eq (string-to-char s) ?#)
10906 ;; Look for a custom ID S if S starts with "#".
10907 (let* ((id (substring normalized 1))
10908 (match (org-find-property "CUSTOM_ID" id)))
10909 (if match (progn (goto-char match) (setf type 'dedicated))
10910 (error "No match for custom ID: %s" id))))
10911 ((string-match "\\`(\\(.*\\))\\'" normalized)
10912 ;; Look for coderef targets if S is enclosed within parenthesis.
10913 (let ((coderef (match-string-no-properties 1 normalized))
10914 (re (substring s-single-re 1 -1)))
10915 (goto-char (point-min))
10916 (catch :coderef-match
10917 (while (re-search-forward re nil t)
10918 (let ((element (org-element-at-point)))
10919 (when (and (memq (org-element-type element)
10920 '(example-block src-block))
10921 ;; Build proper regexp according to current
10922 ;; block's label format.
10923 (let ((label-fmt
10924 (regexp-quote
10925 (or (org-element-property :label-fmt element)
10926 org-coderef-label-format))))
10927 (save-excursion
10928 (beginning-of-line)
10929 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10930 (format label-fmt coderef))))))
10931 (setq type 'dedicated)
10932 (goto-char (match-beginning 1))
10933 (throw :coderef-match nil))))
10934 (goto-char origin)
10935 (error "No match for coderef: %s" coderef))))
10936 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10937 ;; Look for a regular expression.
10938 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10939 (match-string 1 s)))
10940 ;; From here, we handle fuzzy links.
10942 ;; Look for targets, only if not in a headline search.
10943 ((and (not starred)
10944 (let ((target (format "<<%s>>" s-multi-re)))
10945 (catch :target-match
10946 (goto-char (point-min))
10947 (while (re-search-forward target nil t)
10948 (backward-char)
10949 (let ((context (org-element-context)))
10950 (when (eq (org-element-type context) 'target)
10951 (setq type 'dedicated)
10952 (goto-char (org-element-property :begin context))
10953 (throw :target-match t))))
10954 nil))))
10955 ;; Look for elements named after S, only if not in a headline
10956 ;; search.
10957 ((and (not starred)
10958 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10959 (catch :name-match
10960 (goto-char (point-min))
10961 (while (re-search-forward name nil t)
10962 (let ((element (org-element-at-point)))
10963 (when (equal words
10964 (split-string
10965 (org-element-property :name element)))
10966 (setq type 'dedicated)
10967 (beginning-of-line)
10968 (throw :name-match t))))
10969 nil))))
10970 ;; Regular text search. Prefer headlines in Org mode buffers.
10971 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10972 ;; statistics cookies and tags.
10973 ((and (derived-mode-p 'org-mode)
10974 (let ((title-re
10975 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10976 org-outline-regexp-bol
10977 org-comment-string
10978 (mapconcat #'regexp-quote words ".+")))
10979 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10980 (comment-re (eval-when-compile
10981 (format "\\`%s[ \t]+" org-comment-string))))
10982 (goto-char (point-min))
10983 (catch :found
10984 (while (re-search-forward title-re nil t)
10985 (when (equal words
10986 (split-string
10987 (replace-regexp-in-string
10988 cookie-re ""
10989 (replace-regexp-in-string
10990 comment-re "" (org-get-heading t t t)))))
10991 (throw :found t)))
10992 nil)))
10993 (beginning-of-line)
10994 (setq type 'dedicated))
10995 ;; Offer to create non-existent headline depending on
10996 ;; `org-link-search-must-match-exact-headline'.
10997 ((and (derived-mode-p 'org-mode)
10998 (not org-link-search-inhibit-query)
10999 (eq org-link-search-must-match-exact-headline 'query-to-create)
11000 (yes-or-no-p "No match - create this as a new heading? "))
11001 (goto-char (point-max))
11002 (unless (bolp) (newline))
11003 (org-insert-heading nil t t)
11004 (insert s "\n")
11005 (beginning-of-line 0))
11006 ;; Only headlines are looked after. No need to process
11007 ;; further: throw an error.
11008 ((and (derived-mode-p 'org-mode)
11009 (or starred org-link-search-must-match-exact-headline))
11010 (goto-char origin)
11011 (error "No match for fuzzy expression: %s" normalized))
11012 ;; Regular text search.
11013 ((catch :fuzzy-match
11014 (goto-char (point-min))
11015 (while (re-search-forward s-multi-re nil t)
11016 ;; Skip match if it contains AVOID-POS or it is included in
11017 ;; a link with a description but outside the description.
11018 (unless (or (and avoid-pos
11019 (<= (match-beginning 0) avoid-pos)
11020 (> (match-end 0) avoid-pos))
11021 (and (save-match-data
11022 (org-in-regexp org-bracket-link-regexp))
11023 (match-beginning 3)
11024 (or (> (match-beginning 3) (point))
11025 (<= (match-end 3) (point)))
11026 (org-element-lineage
11027 (save-match-data (org-element-context))
11028 '(link) t)))
11029 (goto-char (match-beginning 0))
11030 (setq type 'fuzzy)
11031 (throw :fuzzy-match t)))
11032 nil))
11033 ;; All failed. Throw an error.
11034 (t (goto-char origin)
11035 (error "No match for fuzzy expression: %s" normalized)))
11036 ;; Disclose surroundings of match, if appropriate.
11037 (when (and (derived-mode-p 'org-mode) (not stealth))
11038 (org-show-context 'link-search))
11039 type))
11041 (defun org-get-buffer-for-internal-link (buffer)
11042 "Return a buffer to be used for displaying the link target of internal links."
11043 (cond
11044 ((not org-display-internal-link-with-indirect-buffer)
11045 buffer)
11046 ((string-suffix-p "(Clone)" (buffer-name buffer))
11047 (message "Buffer is already a clone, not making another one")
11048 ;; we also do not modify visibility in this case
11049 buffer)
11050 (t ; make a new indirect buffer for displaying the link
11051 (let* ((bn (buffer-name buffer))
11052 (ibn (concat bn "(Clone)"))
11053 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11054 (with-current-buffer ib (org-overview))
11055 ib))))
11057 (defun org-do-occur (regexp &optional cleanup)
11058 "Call the Emacs command `occur'.
11059 If CLEANUP is non-nil, remove the printout of the regular expression
11060 in the *Occur* buffer. This is useful if the regex is long and not useful
11061 to read."
11062 (occur regexp)
11063 (when cleanup
11064 (let ((cwin (selected-window)) win beg end)
11065 (when (setq win (get-buffer-window "*Occur*"))
11066 (select-window win))
11067 (goto-char (point-min))
11068 (when (re-search-forward "match[a-z]+" nil t)
11069 (setq beg (match-end 0))
11070 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11071 (setq end (1- (match-beginning 0)))))
11072 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11073 (goto-char (point-min))
11074 (select-window cwin))))
11076 ;;; The mark ring for links jumps
11078 (defvar org-mark-ring nil
11079 "Mark ring for positions before jumps in Org mode.")
11080 (defvar org-mark-ring-last-goto nil
11081 "Last position in the mark ring used to go back.")
11082 ;; Fill and close the ring
11083 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11084 (dotimes (_ org-mark-ring-length)
11085 (push (make-marker) org-mark-ring))
11086 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11087 org-mark-ring)
11089 (defun org-mark-ring-push (&optional pos buffer)
11090 "Put the current position or POS into the mark ring and rotate it."
11091 (interactive)
11092 (setq pos (or pos (point)))
11093 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11094 (move-marker (car org-mark-ring)
11095 (or pos (point))
11096 (or buffer (current-buffer)))
11097 (message "%s"
11098 (substitute-command-keys
11099 "Position saved to mark ring, go back with \
11100 `\\[org-mark-ring-goto]'.")))
11102 (defun org-mark-ring-goto (&optional n)
11103 "Jump to the previous position in the mark ring.
11104 With prefix arg N, jump back that many stored positions. When
11105 called several times in succession, walk through the entire ring.
11106 Org mode commands jumping to a different position in the current file,
11107 or to another Org file, automatically push the old position onto the ring."
11108 (interactive "p")
11109 (let (p m)
11110 (if (eq last-command this-command)
11111 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11112 (setq p org-mark-ring))
11113 (setq org-mark-ring-last-goto p)
11114 (setq m (car p))
11115 (pop-to-buffer-same-window (marker-buffer m))
11116 (goto-char m)
11117 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11119 (defun org-add-angle-brackets (s)
11120 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11121 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11124 ;;; Following specific links
11126 (defvar org-agenda-buffer-tmp-name)
11127 (defvar org-agenda-start-on-weekday)
11128 (defun org-follow-timestamp-link ()
11129 "Open an agenda view for the time-stamp date/range at point."
11130 (cond
11131 ((org-at-date-range-p t)
11132 (let ((org-agenda-start-on-weekday)
11133 (t1 (match-string 1))
11134 (t2 (match-string 2)) tt1 tt2)
11135 (setq tt1 (time-to-days (org-time-string-to-time t1))
11136 tt2 (time-to-days (org-time-string-to-time t2)))
11137 (let ((org-agenda-buffer-tmp-name
11138 (format "*Org Agenda(a:%s)"
11139 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11140 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11141 ((org-at-timestamp-p 'lax)
11142 (let ((org-agenda-buffer-tmp-name
11143 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11144 (org-agenda-list nil (time-to-days (org-time-string-to-time
11145 (substring (match-string 1) 0 10)))
11146 1)))
11147 (t (error "This should not happen"))))
11150 ;;; Following file links
11151 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11152 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11153 (declare-function mailcap-mime-info
11154 "mailcap" (string &optional request no-decode))
11155 (defvar org-wait nil)
11156 (defun org-open-file (path &optional in-emacs line search)
11157 "Open the file at PATH.
11158 First, this expands any special file name abbreviations. Then the
11159 configuration variable `org-file-apps' is checked if it contains an
11160 entry for this file type, and if yes, the corresponding command is launched.
11162 If no application is found, Emacs simply visits the file.
11164 With optional prefix argument IN-EMACS, Emacs will visit the file.
11165 With a double \\[universal-argument] \\[universal-argument] \
11166 prefix arg, Org tries to avoid opening in Emacs
11167 and to use an external application to visit the file.
11169 Optional LINE specifies a line to go to, optional SEARCH a string
11170 to search for. If LINE or SEARCH is given, the file will be
11171 opened in Emacs, unless an entry from org-file-apps that makes
11172 use of groups in a regexp matches.
11174 If you want to change the way frames are used when following a
11175 link, please customize `org-link-frame-setup'.
11177 If the file does not exist, an error is thrown."
11178 (let* ((file (if (equal path "")
11179 buffer-file-name
11180 (substitute-in-file-name (expand-file-name path))))
11181 (file-apps (append org-file-apps (org-default-apps)))
11182 (apps (cl-remove-if
11183 'org-file-apps-entry-match-against-dlink-p file-apps))
11184 (apps-dlink (cl-remove-if-not
11185 'org-file-apps-entry-match-against-dlink-p file-apps))
11186 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11187 (dirp (unless remp (file-directory-p file)))
11188 (file (if (and dirp org-open-directory-means-index-dot-org)
11189 (concat (file-name-as-directory file) "index.org")
11190 file))
11191 (a-m-a-p (assq 'auto-mode apps))
11192 (dfile (downcase file))
11193 ;; Reconstruct the original link from the PATH, LINE and
11194 ;; SEARCH args.
11195 (link (cond (line (concat file "::" (number-to-string line)))
11196 (search (concat file "::" search))
11197 (t file)))
11198 (dlink (downcase link))
11199 (ext
11200 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11201 (match-string 1 dfile)))
11202 (save-position-maybe
11203 (let ((old-buffer (current-buffer))
11204 (old-pos (point))
11205 (old-mode major-mode))
11206 (lambda ()
11207 (and (derived-mode-p 'org-mode)
11208 (eq old-mode 'org-mode)
11209 (or (not (eq old-buffer (current-buffer)))
11210 (not (eq old-pos (point))))
11211 (org-mark-ring-push old-pos old-buffer)))))
11212 cmd link-match-data)
11213 (cond
11214 ((member in-emacs '((16) system))
11215 (setq cmd (cdr (assq 'system apps))))
11216 (in-emacs (setq cmd 'emacs))
11218 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11219 (and dirp (cdr (assq 'directory apps)))
11220 ;; First, try matching against apps-dlink if we
11221 ;; get a match here, store the match data for
11222 ;; later.
11223 (let ((match (assoc-default dlink apps-dlink
11224 'string-match)))
11225 (if match
11226 (progn (setq link-match-data (match-data))
11227 match)
11228 (progn (setq in-emacs (or in-emacs line search))
11229 nil))) ; if we have no match in apps-dlink,
11230 ; always open the file in emacs if line or search
11231 ; is given (for backwards compatibility)
11232 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11233 'string-match)
11234 (cdr (assoc ext apps))
11235 (cdr (assq t apps))))))
11236 (when (eq cmd 'system)
11237 (setq cmd (cdr (assq 'system apps))))
11238 (when (eq cmd 'default)
11239 (setq cmd (cdr (assoc t apps))))
11240 (when (eq cmd 'mailcap)
11241 (require 'mailcap)
11242 (mailcap-parse-mailcaps)
11243 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11244 (command (mailcap-mime-info mime-type)))
11245 (if (stringp command)
11246 (setq cmd command)
11247 (setq cmd 'emacs))))
11248 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11249 (not (file-exists-p file))
11250 (not org-open-non-existing-files))
11251 (user-error "No such file: %s" file))
11252 (cond
11253 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11254 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11255 (while (string-match "['\"]%s['\"]" cmd)
11256 (setq cmd (replace-match "%s" t t cmd)))
11257 (setq cmd (replace-regexp-in-string
11258 "%s"
11259 (shell-quote-argument (convert-standard-filename file))
11261 nil t))
11263 ;; Replace "%1", "%2" etc. in command with group matches from regex
11264 (save-match-data
11265 (let ((match-index 1)
11266 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11267 (set-match-data link-match-data)
11268 (while (<= match-index number-of-groups)
11269 (let ((regex (concat "%" (number-to-string match-index)))
11270 (replace-with (match-string match-index dlink)))
11271 (while (string-match regex cmd)
11272 (setq cmd (replace-match replace-with t t cmd))))
11273 (setq match-index (+ match-index 1)))))
11275 (save-window-excursion
11276 (message "Running %s...done" cmd)
11277 (start-process-shell-command cmd nil cmd)
11278 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11279 ((or (stringp cmd)
11280 (eq cmd 'emacs))
11281 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11282 (widen)
11283 (cond (line (org-goto-line line)
11284 (when (derived-mode-p 'org-mode) (org-reveal)))
11285 (search (condition-case err
11286 (org-link-search search)
11287 ;; Save position before error-ing out so user
11288 ;; can easily move back to the original buffer.
11289 (error (funcall save-position-maybe)
11290 (error (nth 1 err)))))))
11291 ((functionp cmd)
11292 (save-match-data
11293 (set-match-data link-match-data)
11294 (condition-case nil
11295 (funcall cmd file link)
11296 ;; FIXME: Remove this check when most default installations
11297 ;; of Emacs have at least Org 9.0.
11298 ((debug wrong-number-of-arguments wrong-type-argument
11299 invalid-function)
11300 (user-error "Please see Org News for version 9.0 about \
11301 `org-file-apps'--Lisp error: %S" cmd)))))
11302 ((consp cmd)
11303 ;; FIXME: Remove this check when most default installations of
11304 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11305 ;; fall back to `org-link-frame-setup' for an old usage of
11306 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11307 (user-error "Please see Org News for version 9.0 about \
11308 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11309 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11310 (funcall save-position-maybe)))
11312 (defun org-file-apps-entry-match-against-dlink-p (entry)
11313 "This function returns non-nil if `entry' uses a regular
11314 expression which should be matched against the whole link by
11315 org-open-file.
11317 It assumes that is the case when the entry uses a regular
11318 expression which has at least one grouping construct and the
11319 action is either a lisp form or a command string containing
11320 `%1', i.e. using at least one subexpression match as a
11321 parameter."
11322 (let ((selector (car entry))
11323 (action (cdr entry)))
11324 (if (stringp selector)
11325 (and (> (regexp-opt-depth selector) 0)
11326 (or (and (stringp action)
11327 (string-match "%[0-9]" action))
11328 (consp action)))
11329 nil)))
11331 (defun org-default-apps ()
11332 "Return the default applications for this operating system."
11333 (cond
11334 ((eq system-type 'darwin)
11335 org-file-apps-defaults-macosx)
11336 ((eq system-type 'windows-nt)
11337 org-file-apps-defaults-windowsnt)
11338 (t org-file-apps-defaults-gnu)))
11340 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11341 "Convert extensions to regular expressions in the cars of LIST.
11342 Also, weed out any non-string entries, because the return value is used
11343 only for regexp matching.
11344 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11345 point to the symbol `emacs', indicating that the file should
11346 be opened in Emacs."
11347 (append
11348 (delq nil
11349 (mapcar (lambda (x)
11350 (unless (not (stringp (car x)))
11351 (if (string-match "\\W" (car x))
11353 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11354 list))
11355 (when add-auto-mode
11356 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11358 (defvar ange-ftp-name-format)
11359 (defun org-file-remote-p (file)
11360 "Test whether FILE specifies a location on a remote system.
11361 Return non-nil if the location is indeed remote.
11363 For example, the filename \"/user@host:/foo\" specifies a location
11364 on the system \"/user@host:\"."
11365 (cond ((fboundp 'file-remote-p)
11366 (file-remote-p file))
11367 ((fboundp 'tramp-handle-file-remote-p)
11368 (tramp-handle-file-remote-p file))
11369 ((and (boundp 'ange-ftp-name-format)
11370 (string-match (car ange-ftp-name-format) file))
11371 t)))
11374 ;;;; Refiling
11376 (defun org-get-org-file ()
11377 "Read a filename, with default directory `org-directory'."
11378 (let ((default (or org-default-notes-file remember-data-file)))
11379 (read-file-name (format "File name [%s]: " default)
11380 (file-name-as-directory org-directory)
11381 default)))
11383 (defun org-notes-order-reversed-p ()
11384 "Check if the current file should receive notes in reversed order."
11385 (cond
11386 ((not org-reverse-note-order) nil)
11387 ((eq t org-reverse-note-order) t)
11388 ((not (listp org-reverse-note-order)) nil)
11389 (t (catch 'exit
11390 (dolist (entry org-reverse-note-order)
11391 (when (string-match (car entry) buffer-file-name)
11392 (throw 'exit (cdr entry))))))))
11394 (defvar org-refile-target-table nil
11395 "The list of refile targets, created by `org-refile'.")
11397 (defvar org-agenda-new-buffers nil
11398 "Buffers created to visit agenda files.")
11400 (defvar org-refile-cache nil
11401 "Cache for refile targets.")
11403 (defvar org-refile-markers nil
11404 "All the markers used for caching refile locations.")
11406 (defun org-refile-marker (pos)
11407 "Get a new refile marker, but only if caching is in use."
11408 (if (not org-refile-use-cache)
11410 (let ((m (make-marker)))
11411 (move-marker m pos)
11412 (push m org-refile-markers)
11413 m)))
11415 (defun org-refile-cache-clear ()
11416 "Clear the refile cache and disable all the markers."
11417 (dolist (m org-refile-markers) (move-marker m nil))
11418 (setq org-refile-markers nil)
11419 (setq org-refile-cache nil)
11420 (message "Refile cache has been cleared"))
11422 (defun org-refile-cache-check-set (set)
11423 "Check if all the markers in the cache still have live buffers."
11424 (let (marker)
11425 (catch 'exit
11426 (while (and set (setq marker (nth 3 (pop set))))
11427 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11428 (when (and marker (null (marker-buffer marker)))
11429 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11430 (sit-for 3)
11431 (throw 'exit nil)))
11432 t)))
11434 (defun org-refile-cache-put (set &rest identifiers)
11435 "Push the refile targets SET into the cache, under IDENTIFIERS."
11436 (let* ((key (sha1 (prin1-to-string identifiers)))
11437 (entry (assoc key org-refile-cache)))
11438 (if entry
11439 (setcdr entry set)
11440 (push (cons key set) org-refile-cache))))
11442 (defun org-refile-cache-get (&rest identifiers)
11443 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11444 (cond
11445 ((not org-refile-cache) nil)
11446 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11448 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11449 org-refile-cache))))
11450 (and set (org-refile-cache-check-set set) set)))))
11452 (defvar org-outline-path-cache nil
11453 "Alist between buffer positions and outline paths.
11454 It value is an alist (POSITION . PATH) where POSITION is the
11455 buffer position at the beginning of an entry and PATH is a list
11456 of strings describing the outline path for that entry, in reverse
11457 order.")
11459 (defun org-refile-get-targets (&optional default-buffer)
11460 "Produce a table with refile targets."
11461 (let ((case-fold-search nil)
11462 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11463 (entries (or org-refile-targets '((nil . (:level . 1)))))
11464 targets tgs files desc descre)
11465 (message "Getting targets...")
11466 (with-current-buffer (or default-buffer (current-buffer))
11467 (dolist (entry entries)
11468 (setq files (car entry) desc (cdr entry))
11469 (cond
11470 ((null files) (setq files (list (current-buffer))))
11471 ((eq files 'org-agenda-files)
11472 (setq files (org-agenda-files 'unrestricted)))
11473 ((and (symbolp files) (fboundp files))
11474 (setq files (funcall files)))
11475 ((and (symbolp files) (boundp files))
11476 (setq files (symbol-value files))))
11477 (when (stringp files) (setq files (list files)))
11478 (cond
11479 ((eq (car desc) :tag)
11480 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11481 ((eq (car desc) :todo)
11482 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11483 ((eq (car desc) :regexp)
11484 (setq descre (cdr desc)))
11485 ((eq (car desc) :level)
11486 (setq descre (concat "^\\*\\{" (number-to-string
11487 (if org-odd-levels-only
11488 (1- (* 2 (cdr desc)))
11489 (cdr desc)))
11490 "\\}[ \t]")))
11491 ((eq (car desc) :maxlevel)
11492 (setq descre (concat "^\\*\\{1," (number-to-string
11493 (if org-odd-levels-only
11494 (1- (* 2 (cdr desc)))
11495 (cdr desc)))
11496 "\\}[ \t]")))
11497 (t (error "Bad refiling target description %s" desc)))
11498 (dolist (f files)
11499 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11501 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11502 (progn
11503 (when (bufferp f)
11504 (setq f (buffer-file-name (buffer-base-buffer f))))
11505 (setq f (and f (expand-file-name f)))
11506 (when (eq org-refile-use-outline-path 'file)
11507 (push (list (file-name-nondirectory f) f nil nil) tgs))
11508 (when (eq org-refile-use-outline-path 'buffer-name)
11509 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11510 (when (eq org-refile-use-outline-path 'full-file-path)
11511 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11512 (org-with-wide-buffer
11513 (goto-char (point-min))
11514 (setq org-outline-path-cache nil)
11515 (while (re-search-forward descre nil t)
11516 (beginning-of-line)
11517 (let ((case-fold-search nil))
11518 (looking-at org-complex-heading-regexp))
11519 (let ((begin (point))
11520 (heading (match-string-no-properties 4)))
11521 (unless (or (and
11522 org-refile-target-verify-function
11523 (not
11524 (funcall org-refile-target-verify-function)))
11525 (not heading))
11526 (let ((re (format org-complex-heading-regexp-format
11527 (regexp-quote heading)))
11528 (target
11529 (if (not org-refile-use-outline-path) heading
11530 (mapconcat
11531 #'identity
11532 (append
11533 (pcase org-refile-use-outline-path
11534 (`file (list (file-name-nondirectory
11535 (buffer-file-name
11536 (buffer-base-buffer)))))
11537 (`full-file-path
11538 (list (buffer-file-name
11539 (buffer-base-buffer))))
11540 (`buffer-name
11541 (list (buffer-name
11542 (buffer-base-buffer))))
11543 (_ nil))
11544 (mapcar (lambda (s) (replace-regexp-in-string
11545 "/" "\\/" s nil t))
11546 (org-get-outline-path t t)))
11547 "/"))))
11548 (push (list target f re (org-refile-marker (point)))
11549 tgs)))
11550 (when (= (point) begin)
11551 ;; Verification function has not moved point.
11552 (end-of-line)))))))
11553 (when org-refile-use-cache
11554 (org-refile-cache-put tgs (buffer-file-name) descre))
11555 (setq targets (append tgs targets))))))
11556 (message "Getting targets...done")
11557 (delete-dups (nreverse targets))))
11559 (defun org--get-outline-path-1 (&optional use-cache)
11560 "Return outline path to current headline.
11562 Outline path is a list of strings, in reverse order. When
11563 optional argument USE-CACHE is non-nil, make use of a cache. See
11564 `org-get-outline-path' for details.
11566 Assume buffer is widened and point is on a headline."
11567 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11568 (let ((p (point))
11569 (heading (let ((case-fold-search nil))
11570 (looking-at org-complex-heading-regexp)
11571 (if (not (match-end 4)) ""
11572 ;; Remove statistics cookies.
11573 (org-trim
11574 (org-link-display-format
11575 (replace-regexp-in-string
11576 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11577 (match-string-no-properties 4))))))))
11578 (if (org-up-heading-safe)
11579 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11580 (when use-cache
11581 (push (cons p path) org-outline-path-cache))
11582 path)
11583 ;; This is a new root node. Since we assume we are moving
11584 ;; forward, we can drop previous cache so as to limit number
11585 ;; of associations there.
11586 (let ((path (list heading)))
11587 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11588 path)))))
11590 (defun org-get-outline-path (&optional with-self use-cache)
11591 "Return the outline path to the current entry.
11593 An outline path is a list of ancestors for current headline, as
11594 a list of strings. Statistics cookies are removed and links are
11595 replaced with their description, if any, or their path otherwise.
11597 When optional argument WITH-SELF is non-nil, the path also
11598 includes the current headline.
11600 When optional argument USE-CACHE is non-nil, cache outline paths
11601 between calls to this function so as to avoid backtracking. This
11602 argument is useful when planning to find more than one outline
11603 path in the same document. In that case, there are two
11604 conditions to satisfy:
11605 - `org-outline-path-cache' is set to nil before starting the
11606 process;
11607 - outline paths are computed by increasing buffer positions."
11608 (org-with-wide-buffer
11609 (and (or (and with-self (org-back-to-heading t))
11610 (org-up-heading-safe))
11611 (reverse (org--get-outline-path-1 use-cache)))))
11613 (defun org-format-outline-path (path &optional width prefix separator)
11614 "Format the outline path PATH for display.
11615 WIDTH is the maximum number of characters that is available.
11616 PREFIX is a prefix to be included in the returned string,
11617 such as the file name.
11618 SEPARATOR is inserted between the different parts of the path,
11619 the default is \"/\"."
11620 (setq width (or width 79))
11621 (setq path (delq nil path))
11622 (unless (> width 0)
11623 (user-error "Argument `width' must be positive"))
11624 (setq separator (or separator "/"))
11625 (let* ((org-odd-levels-only nil)
11626 (fpath (concat
11627 prefix (and prefix path separator)
11628 (mapconcat
11629 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11630 (cl-loop for head in path
11631 for n from 0
11632 collect (org-add-props
11633 head nil 'face
11634 (nth (% n org-n-level-faces) org-level-faces)))
11635 separator))))
11636 (when (> (length fpath) width)
11637 (if (< width 7)
11638 ;; It's unlikely that `width' will be this small, but don't
11639 ;; waste characters by adding ".." if it is.
11640 (setq fpath (substring fpath 0 width))
11641 (setf (substring fpath (- width 2)) "..")))
11642 fpath))
11644 (defun org-display-outline-path (&optional file current separator just-return-string)
11645 "Display the current outline path in the echo area.
11647 If FILE is non-nil, prepend the output with the file name.
11648 If CURRENT is non-nil, append the current heading to the output.
11649 SEPARATOR is passed through to `org-format-outline-path'. It separates
11650 the different parts of the path and defaults to \"/\".
11651 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11652 (interactive "P")
11653 (let* (case-fold-search
11654 (bfn (buffer-file-name (buffer-base-buffer)))
11655 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11656 res)
11657 (when current (setq path (append path
11658 (save-excursion
11659 (org-back-to-heading t)
11660 (when (looking-at org-complex-heading-regexp)
11661 (list (match-string 4)))))))
11662 (setq res
11663 (org-format-outline-path
11664 path
11665 (1- (frame-width))
11666 (and file bfn (concat (file-name-nondirectory bfn) separator))
11667 separator))
11668 (if just-return-string
11669 (org-no-properties res)
11670 (org-unlogged-message "%s" res))))
11672 (defvar org-refile-history nil
11673 "History for refiling operations.")
11675 (defvar org-after-refile-insert-hook nil
11676 "Hook run after `org-refile' has inserted its stuff at the new location.
11677 Note that this is still *before* the stuff will be removed from
11678 the *old* location.")
11680 (defvar org-capture-last-stored-marker)
11681 (defvar org-refile-keep nil
11682 "Non-nil means `org-refile' will copy instead of refile.")
11684 (defun org-copy ()
11685 "Like `org-refile', but copy."
11686 (interactive)
11687 (let ((org-refile-keep t))
11688 (funcall 'org-refile nil nil nil "Copy")))
11690 (defun org-refile (&optional arg default-buffer rfloc msg)
11691 "Move the entry or entries at point to another heading.
11693 The list of target headings is compiled using the information in
11694 `org-refile-targets', which see.
11696 At the target location, the entry is filed as a subitem of the
11697 target heading. Depending on `org-reverse-note-order', the new
11698 subitem will either be the first or the last subitem.
11700 If there is an active region, all entries in that region will be
11701 refiled. However, the region must fulfill the requirement that
11702 the first heading sets the top-level of the moved text.
11704 With a `\\[universal-argument]' ARG, the command will only visit the target \
11705 location
11706 and not actually move anything.
11708 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11709 location where the last
11710 refiling operation has put the subtree.
11712 With a numeric prefix argument of `2', refile to the running clock.
11714 With a numeric prefix argument of `3', emulate `org-refile-keep'
11715 being set to t and copy to the target location, don't move it.
11716 Beware that keeping refiled entries may result in duplicated ID
11717 properties.
11719 RFLOC can be a refile location obtained in a different way.
11721 MSG is a string to replace \"Refile\" in the default prompt with
11722 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11724 See also `org-refile-use-outline-path'.
11726 If you are using target caching (see `org-refile-use-cache'), you
11727 have to clear the target cache in order to find new targets.
11728 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11729 prefix argument (`C-u C-u C-u C-c C-w')."
11730 (interactive "P")
11731 (if (member arg '(0 (64)))
11732 (org-refile-cache-clear)
11733 (let* ((actionmsg (cond (msg msg)
11734 ((equal arg 3) "Refile (and keep)")
11735 (t "Refile")))
11736 (regionp (org-region-active-p))
11737 (region-start (and regionp (region-beginning)))
11738 (region-end (and regionp (region-end)))
11739 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11740 pos it nbuf file level reversed)
11741 (setq last-command nil)
11742 (when regionp
11743 (goto-char region-start)
11744 (or (bolp) (goto-char (point-at-bol)))
11745 (setq region-start (point))
11746 (unless (or (org-kill-is-subtree-p
11747 (buffer-substring region-start region-end))
11748 (prog1 org-refile-active-region-within-subtree
11749 (let ((s (point-at-eol)))
11750 (org-toggle-heading)
11751 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11752 (user-error "The region is not a (sequence of) subtree(s)")))
11753 (if (equal arg '(16))
11754 (org-refile-goto-last-stored)
11755 (when (or
11756 (and (equal arg 2)
11757 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11758 (prog1
11759 (setq it (list (or org-clock-heading "running clock")
11760 (buffer-file-name
11761 (marker-buffer org-clock-hd-marker))
11763 (marker-position org-clock-hd-marker)))
11764 (setq arg nil)))
11765 (setq it
11766 (or rfloc
11767 (let (heading-text)
11768 (save-excursion
11769 (unless (and arg (listp arg))
11770 (org-back-to-heading t)
11771 (setq heading-text
11772 (replace-regexp-in-string
11773 org-bracket-link-regexp
11774 "\\3"
11775 (or (nth 4 (org-heading-components))
11776 ""))))
11777 (org-refile-get-location
11778 (cond ((and arg (listp arg)) "Goto")
11779 (regionp (concat actionmsg " region to"))
11780 (t (concat actionmsg " subtree \""
11781 heading-text "\" to")))
11782 default-buffer
11783 (and (not (equal '(4) arg))
11784 org-refile-allow-creating-parent-nodes)))))))
11785 (setq file (nth 1 it)
11786 pos (nth 3 it))
11787 (when (and (not arg)
11789 (equal (buffer-file-name) file)
11790 (if regionp
11791 (and (>= pos region-start)
11792 (<= pos region-end))
11793 (and (>= pos (point))
11794 (< pos (save-excursion
11795 (org-end-of-subtree t t))))))
11796 (error "Cannot refile to position inside the tree or region"))
11797 (setq nbuf (or (find-buffer-visiting file)
11798 (find-file-noselect file)))
11799 (if (and arg (not (equal arg 3)))
11800 (progn
11801 (pop-to-buffer-same-window nbuf)
11802 (goto-char (cond (pos)
11803 ((org-notes-order-reversed-p) (point-min))
11804 (t (point-max))))
11805 (org-show-context 'org-goto))
11806 (if regionp
11807 (progn
11808 (org-kill-new (buffer-substring region-start region-end))
11809 (org-save-markers-in-region region-start region-end))
11810 (org-copy-subtree 1 nil t))
11811 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11812 (find-file-noselect file)))
11813 (setq reversed (org-notes-order-reversed-p))
11814 (org-with-wide-buffer
11815 (if pos
11816 (progn
11817 (goto-char pos)
11818 (setq level (org-get-valid-level (funcall outline-level) 1))
11819 (goto-char
11820 (if reversed
11821 (or (outline-next-heading) (point-max))
11822 (or (save-excursion (org-get-next-sibling))
11823 (org-end-of-subtree t t)
11824 (point-max)))))
11825 (setq level 1)
11826 (if (not reversed)
11827 (goto-char (point-max))
11828 (goto-char (point-min))
11829 (or (outline-next-heading) (goto-char (point-max)))))
11830 (unless (bolp) (newline))
11831 (org-paste-subtree level nil nil t)
11832 (when org-log-refile
11833 (org-add-log-setup 'refile nil nil org-log-refile)
11834 (unless (eq org-log-refile 'note)
11835 (save-excursion (org-add-log-note))))
11836 (and org-auto-align-tags
11837 (let ((org-loop-over-headlines-in-active-region nil))
11838 (org-set-tags nil t)))
11839 (let ((bookmark-name (plist-get org-bookmark-names-plist
11840 :last-refile)))
11841 (when bookmark-name
11842 (with-demoted-errors
11843 (bookmark-set bookmark-name))))
11844 ;; If we are refiling for capture, make sure that the
11845 ;; last-capture pointers point here
11846 (when (bound-and-true-p org-capture-is-refiling)
11847 (let ((bookmark-name (plist-get org-bookmark-names-plist
11848 :last-capture-marker)))
11849 (when bookmark-name
11850 (with-demoted-errors
11851 (bookmark-set bookmark-name))))
11852 (move-marker org-capture-last-stored-marker (point)))
11853 (when (fboundp 'deactivate-mark) (deactivate-mark))
11854 (run-hooks 'org-after-refile-insert-hook)))
11855 (unless org-refile-keep
11856 (if regionp
11857 (delete-region (point) (+ (point) (- region-end region-start)))
11858 (delete-region
11859 (and (org-back-to-heading t) (point))
11860 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11861 (when (featurep 'org-inlinetask)
11862 (org-inlinetask-remove-END-maybe))
11863 (setq org-markers-to-move nil)
11864 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11866 (defun org-refile-goto-last-stored ()
11867 "Go to the location where the last refile was stored."
11868 (interactive)
11869 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11870 (message "This is the location of the last refile"))
11872 (defun org-refile--get-location (refloc tbl)
11873 "When user refile to REFLOC, find the associated target in TBL.
11874 Also check `org-refile-target-table'."
11875 (car (delq
11877 (mapcar
11878 (lambda (r) (or (assoc r tbl)
11879 (assoc r org-refile-target-table)))
11880 (list (replace-regexp-in-string "/$" "" refloc)
11881 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11883 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11884 "Prompt the user for a refile location, using PROMPT.
11885 PROMPT should not be suffixed with a colon and a space, because
11886 this function appends the default value from
11887 `org-refile-history' automatically, if that is not empty."
11888 (let ((org-refile-targets org-refile-targets)
11889 (org-refile-use-outline-path org-refile-use-outline-path))
11890 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11891 (unless org-refile-target-table
11892 (user-error "No refile targets"))
11893 (let* ((cbuf (current-buffer))
11894 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11895 (cfunc (if (and org-refile-use-outline-path
11896 org-outline-path-complete-in-steps)
11897 #'org-olpath-completing-read
11898 #'completing-read))
11899 (extra (if org-refile-use-outline-path "/" ""))
11900 (cbnex (concat (buffer-name) extra))
11901 (filename (and cfn (expand-file-name cfn)))
11902 (tbl (mapcar
11903 (lambda (x)
11904 (if (and (not (member org-refile-use-outline-path
11905 '(file full-file-path)))
11906 (not (equal filename (nth 1 x))))
11907 (cons (concat (car x) extra " ("
11908 (file-name-nondirectory (nth 1 x)) ")")
11909 (cdr x))
11910 (cons (concat (car x) extra) (cdr x))))
11911 org-refile-target-table))
11912 (completion-ignore-case t)
11913 cdef
11914 (prompt (concat prompt
11915 (or (and (car org-refile-history)
11916 (concat " (default " (car org-refile-history) ")"))
11917 (and (assoc cbnex tbl) (setq cdef cbnex)
11918 (concat " (default " cbnex ")"))) ": "))
11919 pa answ parent-target child parent old-hist)
11920 (setq old-hist org-refile-history)
11921 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11922 nil 'org-refile-history (or cdef (car org-refile-history))))
11923 (if (setq pa (org-refile--get-location answ tbl))
11924 (progn
11925 (org-refile-check-position pa)
11926 (when (or (not org-refile-history)
11927 (not (eq old-hist org-refile-history))
11928 (not (equal (car pa) (car org-refile-history))))
11929 (setq org-refile-history
11930 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11931 org-refile-history
11932 (cdr org-refile-history))))
11933 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11934 (pop org-refile-history)))
11936 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11937 (progn
11938 (setq parent (match-string 1 answ)
11939 child (match-string 2 answ))
11940 (setq parent-target (org-refile--get-location parent tbl))
11941 (when (and parent-target
11942 (or (eq new-nodes t)
11943 (and (eq new-nodes 'confirm)
11944 (y-or-n-p (format "Create new node \"%s\"? "
11945 child)))))
11946 (org-refile-new-child parent-target child)))
11947 (user-error "Invalid target location")))))
11949 (declare-function org-string-nw-p "org-macs" (s))
11950 (defun org-refile-check-position (refile-pointer)
11951 "Check if the refile pointer matches the headline to which it points."
11952 (let* ((file (nth 1 refile-pointer))
11953 (re (nth 2 refile-pointer))
11954 (pos (nth 3 refile-pointer))
11955 buffer)
11956 (if (and (not (markerp pos)) (not file))
11957 (user-error "Please indicate a target file in the refile path")
11958 (when (org-string-nw-p re)
11959 (setq buffer (if (markerp pos)
11960 (marker-buffer pos)
11961 (or (find-buffer-visiting file)
11962 (find-file-noselect file))))
11963 (with-current-buffer buffer
11964 (org-with-wide-buffer
11965 (goto-char pos)
11966 (beginning-of-line 1)
11967 (unless (looking-at-p re)
11968 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11970 (defun org-refile-new-child (parent-target child)
11971 "Use refile target PARENT-TARGET to add new CHILD below it."
11972 (unless parent-target
11973 (error "Cannot find parent for new node"))
11974 (let ((file (nth 1 parent-target))
11975 (pos (nth 3 parent-target))
11976 level)
11977 (with-current-buffer (or (find-buffer-visiting file)
11978 (find-file-noselect file))
11979 (org-with-wide-buffer
11980 (if pos
11981 (goto-char pos)
11982 (goto-char (point-max))
11983 (unless (bolp) (newline)))
11984 (when (looking-at org-outline-regexp)
11985 (setq level (funcall outline-level))
11986 (org-end-of-subtree t t))
11987 (org-back-over-empty-lines)
11988 (insert "\n" (make-string
11989 (if pos (org-get-valid-level level 1) 1) ?*)
11990 " " child "\n")
11991 (beginning-of-line 0)
11992 (list (concat (car parent-target) "/" child) file "" (point))))))
11994 (defun org-olpath-completing-read (prompt collection &rest args)
11995 "Read an outline path like a file name."
11996 (let ((thetable collection))
11997 (apply #'completing-read
11998 prompt
11999 (lambda (string predicate &optional flag)
12000 (cond
12001 ((eq flag nil) (try-completion string thetable))
12002 ((eq flag t)
12003 (let ((l (length string)))
12004 (mapcar (lambda (x)
12005 (let ((r (substring x l))
12006 (f (if (string-match " ([^)]*)$" x)
12007 (match-string 0 x)
12008 "")))
12009 (if (string-match "/" r)
12010 (concat string (substring r 0 (match-end 0)) f)
12011 x)))
12012 (all-completions string thetable predicate))))
12013 ;; Exact match?
12014 ((eq flag 'lambda) (assoc string thetable))))
12015 args)))
12017 ;;;; Dynamic blocks
12019 (defun org-find-dblock (name)
12020 "Find the first dynamic block with name NAME in the buffer.
12021 If not found, stay at current position and return nil."
12022 (let ((case-fold-search t) pos)
12023 (save-excursion
12024 (goto-char (point-min))
12025 (setq pos (and (re-search-forward
12026 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12027 (match-beginning 0))))
12028 (when pos (goto-char pos))
12029 pos))
12031 (defun org-create-dblock (plist)
12032 "Create a dynamic block section, with parameters taken from PLIST.
12033 PLIST must contain a :name entry which is used as the name of the block."
12034 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12035 (end-of-line 1)
12036 (newline))
12037 (let ((col (current-column))
12038 (name (plist-get plist :name)))
12039 (insert "#+BEGIN: " name)
12040 (while plist
12041 (if (eq (car plist) :name)
12042 (setq plist (cddr plist))
12043 (insert " " (prin1-to-string (pop plist)))))
12044 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12045 (beginning-of-line -2)))
12047 (defun org-prepare-dblock ()
12048 "Prepare dynamic block for refresh.
12049 This empties the block, puts the cursor at the insert position and returns
12050 the property list including an extra property :name with the block name."
12051 (unless (looking-at org-dblock-start-re)
12052 (user-error "Not at a dynamic block"))
12053 (let* ((begdel (1+ (match-end 0)))
12054 (name (org-no-properties (match-string 1)))
12055 (params (append (list :name name)
12056 (read (concat "(" (match-string 3) ")")))))
12057 (save-excursion
12058 (beginning-of-line 1)
12059 (skip-chars-forward " \t")
12060 (setq params (plist-put params :indentation-column (current-column))))
12061 (unless (re-search-forward org-dblock-end-re nil t)
12062 (error "Dynamic block not terminated"))
12063 (setq params
12064 (append params
12065 (list :content (buffer-substring
12066 begdel (match-beginning 0)))))
12067 (delete-region begdel (match-beginning 0))
12068 (goto-char begdel)
12069 (open-line 1)
12070 params))
12072 (defun org-map-dblocks (&optional command)
12073 "Apply COMMAND to all dynamic blocks in the current buffer.
12074 If COMMAND is not given, use `org-update-dblock'."
12075 (let ((cmd (or command 'org-update-dblock)))
12076 (save-excursion
12077 (goto-char (point-min))
12078 (while (re-search-forward org-dblock-start-re nil t)
12079 (goto-char (match-beginning 0))
12080 (save-excursion
12081 (condition-case nil
12082 (funcall cmd)
12083 (error (message "Error during update of dynamic block"))))
12084 (unless (re-search-forward org-dblock-end-re nil t)
12085 (error "Dynamic block not terminated"))))))
12087 (defun org-dblock-update (&optional arg)
12088 "User command for updating dynamic blocks.
12089 Update the dynamic block at point. With prefix ARG, update all dynamic
12090 blocks in the buffer."
12091 (interactive "P")
12092 (if arg
12093 (org-update-all-dblocks)
12094 (or (looking-at org-dblock-start-re)
12095 (org-beginning-of-dblock))
12096 (org-update-dblock)))
12098 (defun org-update-dblock ()
12099 "Update the dynamic block at point.
12100 This means to empty the block, parse for parameters and then call
12101 the correct writing function."
12102 (interactive)
12103 (save-excursion
12104 (let* ((win (selected-window))
12105 (pos (point))
12106 (line (org-current-line))
12107 (params (org-prepare-dblock))
12108 (name (plist-get params :name))
12109 (indent (plist-get params :indentation-column))
12110 (cmd (intern (concat "org-dblock-write:" name))))
12111 (message "Updating dynamic block `%s' at line %d..." name line)
12112 (funcall cmd params)
12113 (message "Updating dynamic block `%s' at line %d...done" name line)
12114 (goto-char pos)
12115 (when (and indent (> indent 0))
12116 (setq indent (make-string indent ?\ ))
12117 (save-excursion
12118 (select-window win)
12119 (org-beginning-of-dblock)
12120 (forward-line 1)
12121 (while (not (looking-at org-dblock-end-re))
12122 (insert indent)
12123 (beginning-of-line 2))
12124 (when (looking-at org-dblock-end-re)
12125 (and (looking-at "[ \t]+")
12126 (replace-match ""))
12127 (insert indent)))))))
12129 (defun org-beginning-of-dblock ()
12130 "Find the beginning of the dynamic block at point.
12131 Error if there is no such block at point."
12132 (let ((pos (point))
12133 beg)
12134 (end-of-line 1)
12135 (if (and (re-search-backward org-dblock-start-re nil t)
12136 (setq beg (match-beginning 0))
12137 (re-search-forward org-dblock-end-re nil t)
12138 (> (match-end 0) pos))
12139 (goto-char beg)
12140 (goto-char pos)
12141 (error "Not in a dynamic block"))))
12143 (defun org-update-all-dblocks ()
12144 "Update all dynamic blocks in the buffer.
12145 This function can be used in a hook."
12146 (interactive)
12147 (when (derived-mode-p 'org-mode)
12148 (org-map-dblocks 'org-update-dblock)))
12151 ;;;; Completion
12153 (declare-function org-export-backend-options "ox" (cl-x) t)
12154 (defun org-get-export-keywords ()
12155 "Return a list of all currently understood export keywords.
12156 Export keywords include options, block names, attributes and
12157 keywords relative to each registered export back-end."
12158 (let (keywords)
12159 (dolist (backend
12160 (bound-and-true-p org-export-registered-backends)
12161 (delq nil keywords))
12162 ;; Back-end name (for keywords, like #+LATEX:)
12163 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12164 (dolist (option-entry (org-export-backend-options backend))
12165 ;; Back-end options.
12166 (push (nth 1 option-entry) keywords)))))
12168 (defconst org-options-keywords
12169 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12170 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12171 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12172 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12173 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12175 (defcustom org-structure-template-alist
12176 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12177 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12178 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12179 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12180 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12181 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12182 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12183 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12184 ("L" "#+LaTeX: ")
12185 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12186 ("H" "#+HTML: ")
12187 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12188 ("A" "#+ASCII: ")
12189 ("i" "#+INDEX: ?")
12190 ("I" "#+INCLUDE: %file ?"))
12191 "Structure completion elements.
12192 This is a list of abbreviation keys and values. The value gets inserted
12193 if you type `<' followed by the key and then press the completion key,
12194 usually `TAB'. %file will be replaced by a file name after prompting
12195 for the file using completion. The cursor will be placed at the position
12196 of the `?' in the template.
12197 There are two templates for each key, the first uses the original Org syntax,
12198 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12199 the default when the /org-mtags.el/ module has been loaded. See also the
12200 variable `org-mtags-prefer-muse-templates'."
12201 :group 'org-completion
12202 :type '(repeat
12203 (list
12204 (string :tag "Key")
12205 (string :tag "Template")))
12206 :version "26.1"
12207 :package-version '(Org . "8.3"))
12209 (defun org-try-structure-completion ()
12210 "Try to complete a structure template before point.
12211 This looks for strings like \"<e\" on an otherwise empty line and
12212 expands them."
12213 (let ((l (buffer-substring (point-at-bol) (point)))
12215 (when (and (looking-at "[ \t]*$")
12216 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12217 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12218 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12219 (match-beginning 1)) a)
12220 t)))
12222 (defun org-complete-expand-structure-template (start cell)
12223 "Expand a structure template."
12224 (let ((rpl (nth 1 cell))
12225 (ind ""))
12226 (delete-region start (point))
12227 (when (string-match "\\`[ \t]*#\\+" rpl)
12228 (cond
12229 ((bolp))
12230 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12231 (setq ind (buffer-substring (point-at-bol) (point))))
12232 (t (newline))))
12233 (setq start (point))
12234 (when (string-match "%file" rpl)
12235 (setq rpl (replace-match
12236 (concat
12237 "\""
12238 (save-match-data
12239 (abbreviate-file-name (read-file-name "Include file: ")))
12240 "\"")
12241 t t rpl)))
12242 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12243 (concat "\n" ind)))
12244 (insert rpl)
12245 (when (re-search-backward "\\?" start t) (delete-char 1))))
12247 ;;;; TODO, DEADLINE, Comments
12249 (defun org-toggle-comment ()
12250 "Change the COMMENT state of an entry."
12251 (interactive)
12252 (save-excursion
12253 (org-back-to-heading)
12254 (let ((case-fold-search nil))
12255 (looking-at org-complex-heading-regexp))
12256 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12257 (skip-chars-forward " \t")
12258 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12259 (if (org-in-commented-heading-p t)
12260 (delete-region (point)
12261 (progn (search-forward " " (line-end-position) 'move)
12262 (skip-chars-forward " \t")
12263 (point)))
12264 (insert org-comment-string)
12265 (unless (eolp) (insert " ")))))
12267 (defvar org-last-todo-state-is-todo nil
12268 "This is non-nil when the last TODO state change led to a TODO state.
12269 If the last change removed the TODO tag or switched to DONE, then
12270 this is nil.")
12272 (defvar org-setting-tags nil) ; dynamically skipped
12274 (defvar org-todo-setup-filter-hook nil
12275 "Hook for functions that pre-filter todo specs.
12276 Each function takes a todo spec and returns either nil or the spec
12277 transformed into canonical form." )
12279 (defvar org-todo-get-default-hook nil
12280 "Hook for functions that get a default item for todo.
12281 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12282 nil or a string to be used for the todo mark." )
12284 (defvar org-agenda-headline-snapshot-before-repeat)
12286 (defun org-current-effective-time ()
12287 "Return current time adjusted for `org-extend-today-until' variable."
12288 (let* ((ct (org-current-time))
12289 (dct (decode-time ct))
12290 (ct1
12291 (cond
12292 (org-use-last-clock-out-time-as-effective-time
12293 (or (org-clock-get-last-clock-out-time) ct))
12294 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12295 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12296 (t ct))))
12297 ct1))
12299 (defun org-todo-yesterday (&optional arg)
12300 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12301 (interactive "P")
12302 (if (eq major-mode 'org-agenda-mode)
12303 (apply 'org-agenda-todo-yesterday arg)
12304 (let* ((org-use-effective-time t)
12305 (hour (nth 2 (decode-time (org-current-time))))
12306 (org-extend-today-until (1+ hour)))
12307 (org-todo arg))))
12309 (defvar org-block-entry-blocking ""
12310 "First entry preventing the TODO state change.")
12312 (defun org-cancel-repeater ()
12313 "Cancel a repeater by setting its numeric value to zero."
12314 (interactive)
12315 (save-excursion
12316 (org-back-to-heading t)
12317 (let ((bound1 (point))
12318 (bound0 (save-excursion (outline-next-heading) (point))))
12319 (when (and (re-search-forward
12320 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12321 org-deadline-time-regexp "\\)\\|\\("
12322 org-ts-regexp "\\)")
12323 bound0 t)
12324 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12325 bound1 t))
12326 (replace-match "0" t nil nil 1)))))
12328 (defvar org-state)
12329 (defvar org-blocked-by-checkboxes)
12330 (defun org-todo (&optional arg)
12331 "Change the TODO state of an item.
12333 The state of an item is given by a keyword at the start of the heading,
12334 like
12335 *** TODO Write paper
12336 *** DONE Call mom
12338 The different keywords are specified in the variable `org-todo-keywords'.
12339 By default the available states are \"TODO\" and \"DONE\". So, for this
12340 example: when the item starts with TODO, it is changed to DONE.
12341 When it starts with DONE, the DONE is removed. And when neither TODO nor
12342 DONE are present, add TODO at the beginning of the heading.
12344 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12345 state.
12346 With numeric prefix ARG, switch to that state.
12347 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12348 next set of TODO \
12349 keywords (nextset).
12350 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12351 prefix, circumvent any state blocking.
12352 With a numeric prefix arg of 0, inhibit note taking for the change.
12353 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12355 When called through ELisp, arg is also interpreted in the following way:
12356 `none' -> empty state
12357 \"\" -> switch to empty state
12358 `done' -> switch to DONE
12359 `nextset' -> switch to the next set of keywords
12360 `previousset' -> switch to the previous set of keywords
12361 \"WAITING\" -> switch to the specified keyword, but only if it
12362 really is a member of `org-todo-keywords'."
12363 (interactive "P")
12364 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12365 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12366 'region-start-level 'region))
12367 org-loop-over-headlines-in-active-region)
12368 (org-map-entries
12369 `(org-todo ,arg)
12370 org-loop-over-headlines-in-active-region
12371 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12372 (when (equal arg '(16)) (setq arg 'nextset))
12373 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12374 (let ((org-blocker-hook org-blocker-hook)
12375 commentp
12376 case-fold-search)
12377 (when (equal arg '(64))
12378 (setq arg nil org-blocker-hook nil))
12379 (when (and org-blocker-hook
12380 (or org-inhibit-blocking
12381 (org-entry-get nil "NOBLOCKING")))
12382 (setq org-blocker-hook nil))
12383 (save-excursion
12384 (catch 'exit
12385 (org-back-to-heading t)
12386 (when (org-in-commented-heading-p t)
12387 (org-toggle-comment)
12388 (setq commentp t))
12389 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12390 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12391 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12392 (let* ((match-data (match-data))
12393 (startpos (point-at-bol))
12394 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12395 (org-log-done org-log-done)
12396 (org-log-repeat org-log-repeat)
12397 (org-todo-log-states org-todo-log-states)
12398 (org-inhibit-logging
12399 (if (equal arg 0)
12400 (progn (setq arg nil) 'note) org-inhibit-logging))
12401 (this (match-string 1))
12402 (hl-pos (match-beginning 0))
12403 (head (org-get-todo-sequence-head this))
12404 (ass (assoc head org-todo-kwd-alist))
12405 (interpret (nth 1 ass))
12406 (done-word (nth 3 ass))
12407 (final-done-word (nth 4 ass))
12408 (org-last-state (or this ""))
12409 (completion-ignore-case t)
12410 (member (member this org-todo-keywords-1))
12411 (tail (cdr member))
12412 (org-state (cond
12413 ((and org-todo-key-trigger
12414 (or (and (equal arg '(4))
12415 (eq org-use-fast-todo-selection 'prefix))
12416 (and (not arg) org-use-fast-todo-selection
12417 (not (eq org-use-fast-todo-selection
12418 'prefix)))))
12419 ;; Use fast selection.
12420 (org-fast-todo-selection))
12421 ((and (equal arg '(4))
12422 (or (not org-use-fast-todo-selection)
12423 (not org-todo-key-trigger)))
12424 ;; Read a state with completion.
12425 (completing-read
12426 "State: " (mapcar #'list org-todo-keywords-1)
12427 nil t))
12428 ((eq arg 'right)
12429 (if this
12430 (if tail (car tail) nil)
12431 (car org-todo-keywords-1)))
12432 ((eq arg 'left)
12433 (unless (equal member org-todo-keywords-1)
12434 (if this
12435 (nth (- (length org-todo-keywords-1)
12436 (length tail) 2)
12437 org-todo-keywords-1)
12438 (org-last org-todo-keywords-1))))
12439 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12440 (setq arg nil))) ;hack to fall back to cycling
12441 (arg
12442 ;; User or caller requests a specific state.
12443 (cond
12444 ((equal arg "") nil)
12445 ((eq arg 'none) nil)
12446 ((eq arg 'done) (or done-word (car org-done-keywords)))
12447 ((eq arg 'nextset)
12448 (or (car (cdr (member head org-todo-heads)))
12449 (car org-todo-heads)))
12450 ((eq arg 'previousset)
12451 (let ((org-todo-heads (reverse org-todo-heads)))
12452 (or (car (cdr (member head org-todo-heads)))
12453 (car org-todo-heads))))
12454 ((car (member arg org-todo-keywords-1)))
12455 ((stringp arg)
12456 (user-error "State `%s' not valid in this file" arg))
12457 ((nth (1- (prefix-numeric-value arg))
12458 org-todo-keywords-1))))
12459 ((null member) (or head (car org-todo-keywords-1)))
12460 ((equal this final-done-word) nil) ;-> make empty
12461 ((null tail) nil) ;-> first entry
12462 ((memq interpret '(type priority))
12463 (if (eq this-command last-command)
12464 (car tail)
12465 (if (> (length tail) 0)
12466 (or done-word (car org-done-keywords))
12467 nil)))
12469 (car tail))))
12470 (org-state (or
12471 (run-hook-with-args-until-success
12472 'org-todo-get-default-hook org-state org-last-state)
12473 org-state))
12474 (next (if org-state (concat " " org-state " ") " "))
12475 (change-plist (list :type 'todo-state-change :from this :to org-state
12476 :position startpos))
12477 dolog now-done-p)
12478 (when org-blocker-hook
12479 (let (org-blocked-by-checkboxes block-reason)
12480 (setq org-last-todo-state-is-todo
12481 (not (member this org-done-keywords)))
12482 (unless (save-excursion
12483 (save-match-data
12484 (org-with-wide-buffer
12485 (run-hook-with-args-until-failure
12486 'org-blocker-hook change-plist))))
12487 (setq block-reason (if org-blocked-by-checkboxes
12488 "contained checkboxes"
12489 (format "\"%s\"" org-block-entry-blocking)))
12490 (if (called-interactively-p 'interactive)
12491 (user-error "TODO state change from %s to %s blocked (by %s)"
12492 this org-state block-reason)
12493 ;; Fail silently.
12494 (message "TODO state change from %s to %s blocked (by %s)"
12495 this org-state block-reason)
12496 (throw 'exit nil)))))
12497 (store-match-data match-data)
12498 (replace-match next t t)
12499 (cond ((equal this org-state)
12500 (message "TODO state was already %s" (org-trim next)))
12501 ((not (pos-visible-in-window-p hl-pos))
12502 (message "TODO state changed to %s" (org-trim next))))
12503 (unless head
12504 (setq head (org-get-todo-sequence-head org-state)
12505 ass (assoc head org-todo-kwd-alist)
12506 interpret (nth 1 ass)
12507 done-word (nth 3 ass)
12508 final-done-word (nth 4 ass)))
12509 (when (memq arg '(nextset previousset))
12510 (message "Keyword-Set %d/%d: %s"
12511 (- (length org-todo-sets) -1
12512 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12513 (length org-todo-sets)
12514 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12515 (setq org-last-todo-state-is-todo
12516 (not (member org-state org-done-keywords)))
12517 (setq now-done-p (and (member org-state org-done-keywords)
12518 (not (member this org-done-keywords))))
12519 (and logging (org-local-logging logging))
12520 (when (and (or org-todo-log-states org-log-done)
12521 (not (eq org-inhibit-logging t))
12522 (not (memq arg '(nextset previousset))))
12523 ;; We need to look at recording a time and note.
12524 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12525 (nth 2 (assoc this org-todo-log-states))))
12526 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12527 (setq dolog 'time))
12528 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12529 (and org-state
12530 (member org-state org-not-done-keywords)
12531 (not (member this org-not-done-keywords))))
12532 ;; This is now a todo state and was not one before
12533 ;; If there was a CLOSED time stamp, get rid of it.
12534 (org-add-planning-info nil nil 'closed))
12535 (when (and now-done-p org-log-done)
12536 ;; It is now done, and it was not done before.
12537 (org-add-planning-info 'closed (org-current-effective-time))
12538 (when (and (not dolog) (eq 'note org-log-done))
12539 (org-add-log-setup 'done org-state this 'note)))
12540 (when (and org-state dolog)
12541 ;; This is a non-nil state, and we need to log it.
12542 (org-add-log-setup 'state org-state this dolog)))
12543 ;; Fixup tag positioning.
12544 (org-todo-trigger-tag-changes org-state)
12545 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12546 (when org-provide-todo-statistics
12547 (org-update-parent-todo-statistics))
12548 (run-hooks 'org-after-todo-state-change-hook)
12549 (when (and arg (not (member org-state org-done-keywords)))
12550 (setq head (org-get-todo-sequence-head org-state)))
12551 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12552 ;; Do we need to trigger a repeat?
12553 (when now-done-p
12554 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12555 ;; This is for the agenda, take a snapshot of the headline.
12556 (save-match-data
12557 (setq org-agenda-headline-snapshot-before-repeat
12558 (org-get-heading))))
12559 (org-auto-repeat-maybe org-state))
12560 ;; Fixup cursor location if close to the keyword.
12561 (when (and (outline-on-heading-p)
12562 (not (bolp))
12563 (save-excursion (beginning-of-line 1)
12564 (looking-at org-todo-line-regexp))
12565 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12566 (goto-char (or (match-end 2) (match-end 1)))
12567 (and (looking-at " ") (just-one-space)))
12568 (when org-trigger-hook
12569 (save-excursion
12570 (run-hook-with-args 'org-trigger-hook change-plist)))
12571 (when commentp (org-toggle-comment))))))))
12573 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12574 "Block turning an entry into a TODO, using the hierarchy.
12575 This checks whether the current task should be blocked from state
12576 changes. Such blocking occurs when:
12578 1. The task has children which are not all in a completed state.
12580 2. A task has a parent with the property :ORDERED:, and there
12581 are siblings prior to the current task with incomplete
12582 status.
12584 3. The parent of the task is blocked because it has siblings that should
12585 be done first, or is child of a block grandparent TODO entry."
12587 (if (not org-enforce-todo-dependencies)
12588 t ; if locally turned off don't block
12589 (catch 'dont-block
12590 ;; If this is not a todo state change, or if this entry is already DONE,
12591 ;; do not block
12592 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12593 (member (plist-get change-plist :from)
12594 (cons 'done org-done-keywords))
12595 (member (plist-get change-plist :to)
12596 (cons 'todo org-not-done-keywords))
12597 (not (plist-get change-plist :to)))
12598 (throw 'dont-block t))
12599 ;; If this task has children, and any are undone, it's blocked
12600 (save-excursion
12601 (org-back-to-heading t)
12602 (let ((this-level (funcall outline-level)))
12603 (outline-next-heading)
12604 (let ((child-level (funcall outline-level)))
12605 (while (and (not (eobp))
12606 (> child-level this-level))
12607 ;; this todo has children, check whether they are all
12608 ;; completed
12609 (when (and (not (org-entry-is-done-p))
12610 (org-entry-is-todo-p))
12611 (setq org-block-entry-blocking (org-get-heading))
12612 (throw 'dont-block nil))
12613 (outline-next-heading)
12614 (setq child-level (funcall outline-level))))))
12615 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12616 ;; any previous siblings are undone, it's blocked
12617 (save-excursion
12618 (org-back-to-heading t)
12619 (let* ((pos (point))
12620 (parent-pos (and (org-up-heading-safe) (point)))
12621 (case-fold-search nil))
12622 (unless parent-pos (throw 'dont-block t)) ; no parent
12623 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12624 (forward-line 1)
12625 (re-search-forward org-not-done-heading-regexp pos t))
12626 (setq org-block-entry-blocking (match-string 0))
12627 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12628 ;; Search further up the hierarchy, to see if an ancestor is blocked
12629 (while t
12630 (goto-char parent-pos)
12631 (unless (looking-at org-not-done-heading-regexp)
12632 (throw 'dont-block t)) ; do not block, parent is not a TODO
12633 (setq pos (point))
12634 (setq parent-pos (and (org-up-heading-safe) (point)))
12635 (unless parent-pos (throw 'dont-block t)) ; no parent
12636 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12637 (forward-line 1)
12638 (re-search-forward org-not-done-heading-regexp pos t)
12639 (setq org-block-entry-blocking (org-get-heading)))
12640 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12642 (defcustom org-track-ordered-property-with-tag nil
12643 "Should the ORDERED property also be shown as a tag?
12644 The ORDERED property decides if an entry should require subtasks to be
12645 completed in sequence. Since a property is not very visible, setting
12646 this option means that toggling the ORDERED property with the command
12647 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12648 not relevant for the behavior, but it makes things more visible.
12650 Note that toggling the tag with tags commands will not change the property
12651 and therefore not influence behavior!
12653 This can be t, meaning the tag ORDERED should be used, It can also be a
12654 string to select a different tag for this task."
12655 :group 'org-todo
12656 :type '(choice
12657 (const :tag "No tracking" nil)
12658 (const :tag "Track with ORDERED tag" t)
12659 (string :tag "Use other tag")))
12661 (defun org-toggle-ordered-property ()
12662 "Toggle the ORDERED property of the current entry.
12663 For better visibility, you can track the value of this property with a tag.
12664 See variable `org-track-ordered-property-with-tag'."
12665 (interactive)
12666 (let* ((t1 org-track-ordered-property-with-tag)
12667 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12668 (save-excursion
12669 (org-back-to-heading)
12670 (if (org-entry-get nil "ORDERED")
12671 (progn
12672 (org-delete-property "ORDERED")
12673 (and tag (org-toggle-tag tag 'off))
12674 (message "Subtasks can be completed in arbitrary order"))
12675 (org-entry-put nil "ORDERED" "t")
12676 (and tag (org-toggle-tag tag 'on))
12677 (message "Subtasks must be completed in sequence")))))
12679 (defun org-block-todo-from-checkboxes (change-plist)
12680 "Block turning an entry into a TODO, using checkboxes.
12681 This checks whether the current task should be blocked from state
12682 changes because there are unchecked boxes in this entry."
12683 (if (not org-enforce-todo-checkbox-dependencies)
12684 t ; if locally turned off don't block
12685 (catch 'dont-block
12686 ;; If this is not a todo state change, or if this entry is already DONE,
12687 ;; do not block
12688 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12689 (member (plist-get change-plist :from)
12690 (cons 'done org-done-keywords))
12691 (member (plist-get change-plist :to)
12692 (cons 'todo org-not-done-keywords))
12693 (not (plist-get change-plist :to)))
12694 (throw 'dont-block t))
12695 ;; If this task has checkboxes that are not checked, it's blocked
12696 (save-excursion
12697 (org-back-to-heading t)
12698 (let ((beg (point)) end)
12699 (outline-next-heading)
12700 (setq end (point))
12701 (goto-char beg)
12702 (when (org-list-search-forward
12703 (concat (org-item-beginning-re)
12704 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12705 "\\[[- ]\\]")
12706 end t)
12707 (when (boundp 'org-blocked-by-checkboxes)
12708 (setq org-blocked-by-checkboxes t))
12709 (throw 'dont-block nil))))
12710 t))) ; do not block
12712 (defun org-entry-blocked-p ()
12713 "Non-nil if entry at point is blocked."
12714 (and (not (org-entry-get nil "NOBLOCKING"))
12715 (member (org-entry-get nil "TODO") org-not-done-keywords)
12716 (not (run-hook-with-args-until-failure
12717 'org-blocker-hook
12718 (list :type 'todo-state-change
12719 :position (point)
12720 :from 'todo
12721 :to 'done)))))
12723 (defun org-update-statistics-cookies (all)
12724 "Update the statistics cookie, either from TODO or from checkboxes.
12725 This should be called with the cursor in a line with a statistics
12726 cookie. When called with a \\[universal-argument] prefix, update
12727 all statistics cookies in the buffer."
12728 (interactive "P")
12729 (if all
12730 (progn
12731 (org-update-checkbox-count 'all)
12732 (org-map-entries 'org-update-parent-todo-statistics))
12733 (if (not (org-at-heading-p))
12734 (org-update-checkbox-count)
12735 (let ((pos (point-marker))
12736 end l1 l2)
12737 (ignore-errors (org-back-to-heading t))
12738 (if (not (org-at-heading-p))
12739 (org-update-checkbox-count)
12740 (setq l1 (org-outline-level))
12741 (setq end (save-excursion
12742 (outline-next-heading)
12743 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12744 (point)))
12745 (if (and (save-excursion
12746 (re-search-forward
12747 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12748 (not (save-excursion (re-search-forward
12749 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12750 (org-update-checkbox-count)
12751 (if (and l2 (> l2 l1))
12752 (progn
12753 (goto-char end)
12754 (org-update-parent-todo-statistics))
12755 (goto-char pos)
12756 (beginning-of-line 1)
12757 (while (re-search-forward
12758 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12759 (point-at-eol) t)
12760 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12761 (goto-char pos)
12762 (move-marker pos nil)))))
12764 (defvar org-entry-property-inherited-from) ;; defined below
12765 (defun org-update-parent-todo-statistics ()
12766 "Update any statistics cookie in the parent of the current headline.
12767 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12768 the entire subtree and this will travel up the hierarchy and update
12769 statistics everywhere."
12770 (let* ((prop (save-excursion (org-up-heading-safe)
12771 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12772 (recursive (or (not org-hierarchical-todo-statistics)
12773 (and prop (string-match "\\<recursive\\>" prop))))
12774 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12776 (first t)
12777 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12778 level ltoggle l1 new ndel
12779 (cnt-all 0) (cnt-done 0) is-percent kwd
12780 checkbox-beg cookie-present)
12781 (catch 'exit
12782 (save-excursion
12783 (beginning-of-line 1)
12784 (setq ltoggle (funcall outline-level))
12785 ;; Three situations are to consider:
12787 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12788 ;; to the top-level ancestor on the headline;
12790 ;; 2. If parent has "recursive" property, repeat up to the
12791 ;; headline setting that property, taking inheritance into
12792 ;; account;
12794 ;; 3. Else, move up to direct parent and proceed only once.
12795 (while (and (setq level (org-up-heading-safe))
12796 (or recursive first)
12797 (>= (point) lim))
12798 (setq first nil cookie-present nil)
12799 (unless (and level
12800 (not (string-match
12801 "\\<checkbox\\>"
12802 (downcase (or (org-entry-get nil "COOKIE_DATA")
12803 "")))))
12804 (throw 'exit nil))
12805 (while (re-search-forward box-re (point-at-eol) t)
12806 (setq cnt-all 0 cnt-done 0 cookie-present t)
12807 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12808 (save-match-data
12809 (unless (outline-next-heading) (throw 'exit nil))
12810 (while (and (looking-at org-complex-heading-regexp)
12811 (> (setq l1 (length (match-string 1))) level))
12812 (setq kwd (and (or recursive (= l1 ltoggle))
12813 (match-string 2)))
12814 (if (or (eq org-provide-todo-statistics 'all-headlines)
12815 (and (eq org-provide-todo-statistics t)
12816 (or (member kwd org-done-keywords)))
12817 (and (listp org-provide-todo-statistics)
12818 (stringp (car org-provide-todo-statistics))
12819 (or (member kwd org-provide-todo-statistics)
12820 (member kwd org-done-keywords)))
12821 (and (listp org-provide-todo-statistics)
12822 (listp (car org-provide-todo-statistics))
12823 (or (member kwd (car org-provide-todo-statistics))
12824 (and (member kwd org-done-keywords)
12825 (member kwd (cadr org-provide-todo-statistics))))))
12826 (setq cnt-all (1+ cnt-all))
12827 (and (eq org-provide-todo-statistics t)
12829 (setq cnt-all (1+ cnt-all))))
12830 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12831 (member kwd org-done-keywords))
12832 (and (listp org-provide-todo-statistics)
12833 (listp (car org-provide-todo-statistics))
12834 (member kwd org-done-keywords)
12835 (member kwd (cadr org-provide-todo-statistics)))
12836 (and (listp org-provide-todo-statistics)
12837 (stringp (car org-provide-todo-statistics))
12838 (member kwd org-done-keywords)))
12839 (setq cnt-done (1+ cnt-done)))
12840 (outline-next-heading)))
12841 (setq new
12842 (if is-percent
12843 (format "[%d%%]" (floor (* 100.0 cnt-done)
12844 (max 1 cnt-all)))
12845 (format "[%d/%d]" cnt-done cnt-all))
12846 ndel (- (match-end 0) checkbox-beg))
12847 (goto-char checkbox-beg)
12848 (insert new)
12849 (delete-region (point) (+ (point) ndel))
12850 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12851 (when cookie-present
12852 (run-hook-with-args 'org-after-todo-statistics-hook
12853 cnt-done (- cnt-all cnt-done))))))
12854 (run-hooks 'org-todo-statistics-hook)))
12856 (defvar org-after-todo-statistics-hook nil
12857 "Hook that is called after a TODO statistics cookie has been updated.
12858 Each function is called with two arguments: the number of not-done entries
12859 and the number of done entries.
12861 For example, the following function, when added to this hook, will switch
12862 an entry to DONE when all children are done, and back to TODO when new
12863 entries are set to a TODO status. Note that this hook is only called
12864 when there is a statistics cookie in the headline!
12866 (defun org-summary-todo (n-done n-not-done)
12867 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12868 (let (org-log-done org-log-states) ; turn off logging
12869 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12872 (defvar org-todo-statistics-hook nil
12873 "Hook that is run whenever Org thinks TODO statistics should be updated.
12874 This hook runs even if there is no statistics cookie present, in which case
12875 `org-after-todo-statistics-hook' would not run.")
12877 (defun org-todo-trigger-tag-changes (state)
12878 "Apply the changes defined in `org-todo-state-tags-triggers'."
12879 (let ((l org-todo-state-tags-triggers)
12880 changes)
12881 (when (or (not state) (equal state ""))
12882 (setq changes (append changes (cdr (assoc "" l)))))
12883 (when (and (stringp state) (> (length state) 0))
12884 (setq changes (append changes (cdr (assoc state l)))))
12885 (when (member state org-not-done-keywords)
12886 (setq changes (append changes (cdr (assq 'todo l)))))
12887 (when (member state org-done-keywords)
12888 (setq changes (append changes (cdr (assq 'done l)))))
12889 (dolist (c changes)
12890 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12892 (defun org-local-logging (value)
12893 "Get logging settings from a property VALUE."
12894 ;; Directly set the variables, they are already local.
12895 (setq org-log-done nil
12896 org-log-repeat nil
12897 org-todo-log-states nil)
12898 (dolist (w (org-split-string value))
12899 (let (a)
12900 (cond
12901 ((setq a (assoc w org-startup-options))
12902 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12903 (set (nth 1 a) (nth 2 a))))
12904 ((setq a (org-extract-log-state-settings w))
12905 (and (member (car a) org-todo-keywords-1)
12906 (push a org-todo-log-states)))))))
12908 (defun org-get-todo-sequence-head (kwd)
12909 "Return the head of the TODO sequence to which KWD belongs.
12910 If KWD is not set, check if there is a text property remembering the
12911 right sequence."
12912 (let (p)
12913 (cond
12914 ((not kwd)
12915 (or (get-text-property (point-at-bol) 'org-todo-head)
12916 (progn
12917 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12918 nil (point-at-eol)))
12919 (get-text-property p 'org-todo-head))))
12920 ((not (member kwd org-todo-keywords-1))
12921 (car org-todo-keywords-1))
12922 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12924 (defun org-fast-todo-selection ()
12925 "Fast TODO keyword selection with single keys.
12926 Returns the new TODO keyword, or nil if no state change should occur."
12927 (let* ((fulltable org-todo-key-alist)
12928 (done-keywords org-done-keywords) ;; needed for the faces.
12929 (maxlen (apply 'max (mapcar
12930 (lambda (x)
12931 (if (stringp (car x)) (string-width (car x)) 0))
12932 fulltable)))
12933 (expert nil)
12934 (fwidth (+ maxlen 3 1 3))
12935 (ncol (/ (- (window-width) 4) fwidth))
12936 tg cnt e c tbl
12937 groups ingroup)
12938 (save-excursion
12939 (save-window-excursion
12940 (if expert
12941 (set-buffer (get-buffer-create " *Org todo*"))
12942 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12943 (erase-buffer)
12944 (setq-local org-done-keywords done-keywords)
12945 (setq tbl fulltable cnt 0)
12946 (while (setq e (pop tbl))
12947 (cond
12948 ((equal e '(:startgroup))
12949 (push '() groups) (setq ingroup t)
12950 (unless (= cnt 0)
12951 (setq cnt 0)
12952 (insert "\n"))
12953 (insert "{ "))
12954 ((equal e '(:endgroup))
12955 (setq ingroup nil cnt 0)
12956 (insert "}\n"))
12957 ((equal e '(:newline))
12958 (unless (= cnt 0)
12959 (setq cnt 0)
12960 (insert "\n")
12961 (setq e (car tbl))
12962 (while (equal (car tbl) '(:newline))
12963 (insert "\n")
12964 (setq tbl (cdr tbl)))))
12966 (setq tg (car e) c (cdr e))
12967 (when ingroup (push tg (car groups)))
12968 (setq tg (org-add-props tg nil 'face
12969 (org-get-todo-face tg)))
12970 (when (and (= cnt 0) (not ingroup)) (insert " "))
12971 (insert "[" c "] " tg (make-string
12972 (- fwidth 4 (length tg)) ?\ ))
12973 (when (= (setq cnt (1+ cnt)) ncol)
12974 (insert "\n")
12975 (when ingroup (insert " "))
12976 (setq cnt 0)))))
12977 (insert "\n")
12978 (goto-char (point-min))
12979 (unless expert (org-fit-window-to-buffer))
12980 (message "[a-z..]:Set [SPC]:clear")
12981 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12982 (cond
12983 ((or (= c ?\C-g)
12984 (and (= c ?q) (not (rassoc c fulltable))))
12985 (setq quit-flag t))
12986 ((= c ?\ ) nil)
12987 ((setq e (rassoc c fulltable) tg (car e))
12989 (t (setq quit-flag t)))))))
12991 (defun org-entry-is-todo-p ()
12992 (member (org-get-todo-state) org-not-done-keywords))
12994 (defun org-entry-is-done-p ()
12995 (member (org-get-todo-state) org-done-keywords))
12997 (defun org-get-todo-state ()
12998 "Return the TODO keyword of the current subtree."
12999 (save-excursion
13000 (org-back-to-heading t)
13001 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13002 (match-end 2)
13003 (match-string 2))))
13005 (defun org-at-date-range-p (&optional inactive-ok)
13006 "Non-nil if point is inside a date range.
13008 When optional argument INACTIVE-OK is non-nil, also consider
13009 inactive time ranges.
13011 When this function returns a non-nil value, match data is set
13012 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13013 on INACTIVE-OK."
13014 (interactive)
13015 (save-excursion
13016 (catch 'exit
13017 (let ((pos (point)))
13018 (skip-chars-backward "^[<\r\n")
13019 (skip-chars-backward "<[")
13020 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13021 (>= (match-end 0) pos)
13022 (throw 'exit t))
13023 (skip-chars-backward "^<[\r\n")
13024 (skip-chars-backward "<[")
13025 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13026 (>= (match-end 0) pos)
13027 (throw 'exit t)))
13028 nil)))
13030 (defun org-get-repeat (&optional timestamp)
13031 "Check if there is a time-stamp with repeater in this entry.
13033 Return the repeater, as a string, or nil. Also return nil when
13034 this function is called before first heading.
13036 When optional argument TIMESTAMP is a string, extract the
13037 repeater from there instead."
13038 (save-match-data
13039 (cond (timestamp
13040 (and (string-match org-repeat-re timestamp)
13041 (match-string-no-properties 1 timestamp)))
13042 ((org-before-first-heading-p) nil)
13044 (save-excursion
13045 (org-back-to-heading t)
13046 (let ((end (org-entry-end-position)))
13047 (catch :repeat
13048 (while (re-search-forward org-repeat-re end t)
13049 (when (save-match-data (org-at-timestamp-p 'agenda))
13050 (throw :repeat (match-string-no-properties 1)))))))))))
13052 (defvar org-last-changed-timestamp)
13053 (defvar org-last-inserted-timestamp)
13054 (defvar org-log-post-message)
13055 (defvar org-log-note-purpose)
13056 (defvar org-log-note-how nil)
13057 (defvar org-log-note-extra)
13058 (defun org-auto-repeat-maybe (done-word)
13059 "Check if the current headline contains a repeated time-stamp.
13061 If yes, set TODO state back to what it was and change the base date
13062 of repeating deadline/scheduled time stamps to new date.
13064 This function is run automatically after each state change to a DONE state."
13065 (let* ((repeat (org-get-repeat))
13066 (aa (assoc org-last-state org-todo-kwd-alist))
13067 (interpret (nth 1 aa))
13068 (head (nth 2 aa))
13069 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13070 (msg "Entry repeats: ")
13071 (org-log-done nil)
13072 (org-todo-log-states nil)
13073 (end (copy-marker (org-entry-end-position))))
13074 (unwind-protect
13075 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13076 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13077 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13078 org-todo-repeat-to-state)))
13079 (org-todo (cond
13080 ((and to-state (member to-state org-todo-keywords-1))
13081 to-state)
13082 ((eq interpret 'type) org-last-state)
13083 (head)
13084 (t 'none))))
13085 (org-back-to-heading t)
13086 (org-add-planning-info nil nil 'closed)
13087 ;; When `org-log-repeat' is non-nil or entry contains
13088 ;; a clock, set LAST_REPEAT property.
13089 (when (or org-log-repeat
13090 (catch :clock
13091 (while (re-search-forward org-clock-line-re end t)
13092 (when (org-at-clock-log-p) (throw :clock t)))))
13093 (org-entry-put nil "LAST_REPEAT" (format-time-string
13094 (org-time-stamp-format t t)
13095 (current-time))))
13096 (when org-log-repeat
13097 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13098 (memq 'org-add-log-note post-command-hook))
13099 ;; We are already setup for some record.
13100 (when (eq org-log-repeat 'note)
13101 ;; Make sure we take a note, not only a time stamp.
13102 (setq org-log-note-how 'note))
13103 ;; Set up for taking a record.
13104 (org-add-log-setup 'state
13105 (or done-word (car org-done-keywords))
13106 org-last-state
13107 org-log-repeat)))
13108 (let ((planning-re (regexp-opt
13109 (list org-scheduled-string org-deadline-string))))
13110 (while (re-search-forward org-ts-regexp end t)
13111 (let* ((ts (match-string 0))
13112 (planning? (org-at-planning-p))
13113 (type (if (not planning?) "Plain:"
13114 (save-excursion
13115 (re-search-backward
13116 planning-re (line-beginning-position) t)
13117 (match-string 0)))))
13118 (cond
13119 ;; Ignore fake time-stamps (e.g., within comments).
13120 ((not (org-at-timestamp-p 'agenda)))
13121 ;; Time-stamps without a repeater are usually
13122 ;; skipped. However, a SCHEDULED time-stamp without
13123 ;; one is removed, as they are no longer relevant.
13124 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13125 ts))
13126 (when (equal type org-scheduled-string)
13127 (org-remove-timestamp-with-keyword type)))
13129 (let ((n (string-to-number (match-string 2 ts)))
13130 (what (match-string 3 ts)))
13131 (when (equal what "w") (setq n (* n 7) what "d"))
13132 (when (and (equal what "h")
13133 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13134 ts)))
13135 (user-error
13136 "Cannot repeat in Repeat in %d hour(s) because no hour \
13137 has been set"
13139 ;; Preparation, see if we need to modify the start
13140 ;; date for the change.
13141 (when (match-end 1)
13142 (let ((time (save-match-data
13143 (org-time-string-to-time ts))))
13144 (cond
13145 ((equal (match-string 1 ts) ".")
13146 ;; Shift starting date to today
13147 (org-timestamp-change
13148 (- (org-today) (time-to-days time))
13149 'day))
13150 ((equal (match-string 1 ts) "+")
13151 (let ((nshiftmax 10)
13152 (nshift 0))
13153 (while (or (= nshift 0)
13154 (not (time-less-p (current-time) time)))
13155 (when (= (cl-incf nshift) nshiftmax)
13156 (or (y-or-n-p
13157 (format "%d repeater intervals were not \
13158 enough to shift date past today. Continue? "
13159 nshift))
13160 (user-error "Abort")))
13161 (org-timestamp-change n (cdr (assoc what whata)))
13162 (org-in-regexp org-ts-regexp3)
13163 (setq ts (match-string 1))
13164 (setq time
13165 (save-match-data
13166 (org-time-string-to-time ts)))))
13167 (org-timestamp-change (- n) (cdr (assoc what whata)))
13168 ;; Rematch, so that we have everything in place
13169 ;; for the real shift.
13170 (org-in-regexp org-ts-regexp3)
13171 (setq ts (match-string 1))
13172 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13173 ts)))))
13174 (save-excursion
13175 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13176 (setq msg
13177 (concat
13178 msg type " " org-last-changed-timestamp " "))))))))
13179 (setq org-log-post-message msg)
13180 (message "%s" msg))
13181 (set-marker end nil))))
13183 (defun org-show-todo-tree (arg)
13184 "Make a compact tree which shows all headlines marked with TODO.
13185 The tree will show the lines where the regexp matches, and all higher
13186 headlines above the match.
13187 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13188 With a numeric prefix N, construct a sparse tree for the Nth element
13189 of `org-todo-keywords-1'."
13190 (interactive "P")
13191 (let ((case-fold-search nil)
13192 (kwd-re
13193 (cond ((null arg) org-not-done-regexp)
13194 ((equal arg '(4))
13195 (let ((kwd
13196 (completing-read "Keyword (or KWD1|KWD2|...): "
13197 (mapcar #'list org-todo-keywords-1))))
13198 (concat "\\("
13199 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13200 "\\)\\>")))
13201 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13202 (regexp-quote (nth (1- (prefix-numeric-value arg))
13203 org-todo-keywords-1)))
13204 (t (user-error "Invalid prefix argument: %s" arg)))))
13205 (message "%d TODO entries found"
13206 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13208 (defun org--deadline-or-schedule (arg type time)
13209 "Insert DEADLINE or SCHEDULE information in current entry.
13210 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13211 `org-schedule' for information about ARG and TIME arguments."
13212 (let* ((deadline? (eq type 'deadline))
13213 (keyword (if deadline? org-deadline-string org-scheduled-string))
13214 (log (if deadline? org-log-redeadline org-log-reschedule))
13215 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13216 (old-date-time (and old-date (org-time-string-to-time old-date)))
13217 ;; Save repeater cookie from either TIME or current scheduled
13218 ;; time stamp. We are going to insert it back at the end of
13219 ;; the process.
13220 (repeater (or (and (org-string-nw-p time)
13221 ;; We use `org-repeat-re' because we need
13222 ;; to tell the difference between a real
13223 ;; repeater and a time delta, e.g. "+2d".
13224 (string-match org-repeat-re time)
13225 (match-string 1 time))
13226 (and (org-string-nw-p old-date)
13227 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13228 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13229 old-date)
13230 (match-string 1 old-date)))))
13231 (pcase arg
13232 (`(4)
13233 (when (and old-date log)
13234 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13235 nil old-date log))
13236 (org-remove-timestamp-with-keyword keyword)
13237 (message (if deadline? "Item no longer has a deadline."
13238 "Item is no longer scheduled.")))
13239 (`(16)
13240 (save-excursion
13241 (org-back-to-heading t)
13242 (let ((regexp (if deadline? org-deadline-time-regexp
13243 org-scheduled-time-regexp)))
13244 (if (not (re-search-forward regexp (line-end-position 2) t))
13245 (user-error (if deadline? "No deadline information to update"
13246 "No scheduled information to update"))
13247 (let* ((rpl0 (match-string 1))
13248 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13249 (msg (if deadline? "Warn starting from" "Delay until")))
13250 (replace-match
13251 (concat keyword
13252 " <" rpl
13253 (format " -%dd"
13254 (abs (- (time-to-days
13255 (save-match-data
13256 (org-read-date
13257 nil t nil msg old-date-time)))
13258 (time-to-days old-date-time))))
13259 ">") t t))))))
13261 (org-add-planning-info type time 'closed)
13262 (when (and old-date
13264 (not (equal old-date org-last-inserted-timestamp)))
13265 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13266 org-last-inserted-timestamp
13267 old-date
13268 log))
13269 (when repeater
13270 (save-excursion
13271 (org-back-to-heading t)
13272 (when (re-search-forward
13273 (concat keyword " " org-last-inserted-timestamp)
13274 (line-end-position 2)
13276 (goto-char (1- (match-end 0)))
13277 (insert " " repeater)
13278 (setq org-last-inserted-timestamp
13279 (concat (substring org-last-inserted-timestamp 0 -1)
13280 " " repeater
13281 (substring org-last-inserted-timestamp -1))))))
13282 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13283 org-last-inserted-timestamp)))))
13285 (defun org-deadline (arg &optional time)
13286 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13287 With one universal prefix argument, remove any deadline from the item.
13288 With two universal prefix arguments, prompt for a warning delay.
13289 With argument TIME, set the deadline at the corresponding date. TIME
13290 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13291 (interactive "P")
13292 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13293 (org-map-entries
13294 (lambda () (org--deadline-or-schedule arg 'deadline time))
13296 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13297 'region-start-level
13298 'region)
13299 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13300 (org--deadline-or-schedule arg 'deadline time)))
13302 (defun org-schedule (arg &optional time)
13303 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13304 With one universal prefix argument, remove any scheduling date from the item.
13305 With two universal prefix arguments, prompt for a delay cookie.
13306 With argument TIME, scheduled at the corresponding date. TIME can
13307 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13308 (interactive "P")
13309 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13310 (org-map-entries
13311 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13313 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13314 'region-start-level
13315 'region)
13316 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13317 (org--deadline-or-schedule arg 'scheduled time)))
13319 (defun org-get-scheduled-time (pom &optional inherit)
13320 "Get the scheduled time as a time tuple, of a format suitable
13321 for calling org-schedule with, or if there is no scheduling,
13322 returns nil."
13323 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13324 (when time
13325 (apply 'encode-time (org-parse-time-string time)))))
13327 (defun org-get-deadline-time (pom &optional inherit)
13328 "Get the deadline as a time tuple, of a format suitable for
13329 calling org-deadline with, or if there is no scheduling, returns
13330 nil."
13331 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13332 (when time
13333 (apply 'encode-time (org-parse-time-string time)))))
13335 (defun org-remove-timestamp-with-keyword (keyword)
13336 "Remove all time stamps with KEYWORD in the current entry."
13337 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13338 beg)
13339 (save-excursion
13340 (org-back-to-heading t)
13341 (setq beg (point))
13342 (outline-next-heading)
13343 (while (re-search-backward re beg t)
13344 (replace-match "")
13345 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13346 (equal (char-before) ?\ ))
13347 (backward-delete-char 1)
13348 (when (string-match "^[ \t]*$" (buffer-substring
13349 (point-at-bol) (point-at-eol)))
13350 (delete-region (point-at-bol)
13351 (min (point-max) (1+ (point-at-eol))))))))))
13353 (defvar org-time-was-given) ; dynamically scoped parameter
13354 (defvar org-end-time-was-given) ; dynamically scoped parameter
13356 (defun org-at-planning-p ()
13357 "Non-nil when point is on a planning info line."
13358 ;; This is as accurate and faster than `org-element-at-point' since
13359 ;; planning info location is fixed in the section.
13360 (org-with-wide-buffer
13361 (beginning-of-line)
13362 (and (looking-at-p org-planning-line-re)
13363 (eq (point)
13364 (ignore-errors
13365 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13366 (org-back-to-heading t)
13367 (org-with-limited-levels (org-back-to-heading t)))
13368 (line-beginning-position 2))))))
13370 (defun org-add-planning-info (what &optional time &rest remove)
13371 "Insert new timestamp with keyword in the planning line.
13372 WHAT indicates what kind of time stamp to add. It is a symbol
13373 among `closed', `deadline', `scheduled' and nil. TIME indicates
13374 the time to use. If none is given, the user is prompted for
13375 a date. REMOVE indicates what kind of entries to remove. An old
13376 WHAT entry will also be removed."
13377 (let (org-time-was-given org-end-time-was-given default-time default-input)
13378 (catch 'exit
13379 (when (and (memq what '(scheduled deadline))
13380 (or (not time)
13381 (and (stringp time)
13382 (string-match "^[-+]+[0-9]" time))))
13383 ;; Try to get a default date/time from existing timestamp
13384 (save-excursion
13385 (org-back-to-heading t)
13386 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13387 (when (re-search-forward (if (eq what 'scheduled)
13388 org-scheduled-time-regexp
13389 org-deadline-time-regexp)
13390 end t)
13391 (setq ts (match-string 1)
13392 default-time (apply 'encode-time (org-parse-time-string ts))
13393 default-input (and ts (org-get-compact-tod ts)))))))
13394 (when what
13395 (setq time
13396 (if (stringp time)
13397 ;; This is a string (relative or absolute), set
13398 ;; proper date.
13399 (apply #'encode-time
13400 (org-read-date-analyze
13401 time default-time (decode-time default-time)))
13402 ;; If necessary, get the time from the user
13403 (or time (org-read-date nil 'to-time nil nil
13404 default-time default-input)))))
13406 (org-with-wide-buffer
13407 (org-back-to-heading t)
13408 (forward-line)
13409 (unless (bolp) (insert "\n"))
13410 (cond ((looking-at-p org-planning-line-re)
13411 ;; Move to current indentation.
13412 (skip-chars-forward " \t")
13413 ;; Check if we have to remove something.
13414 (dolist (type (if what (cons what remove) remove))
13415 (save-excursion
13416 (when (re-search-forward
13417 (cl-case type
13418 (closed org-closed-time-regexp)
13419 (deadline org-deadline-time-regexp)
13420 (scheduled org-scheduled-time-regexp)
13421 (otherwise
13422 (error "Invalid planning type: %s" type)))
13423 (line-end-position) t)
13424 ;; Delete until next keyword or end of line.
13425 (delete-region
13426 (match-beginning 0)
13427 (if (re-search-forward org-keyword-time-not-clock-regexp
13428 (line-end-position)
13430 (match-beginning 0)
13431 (line-end-position))))))
13432 ;; If there is nothing more to add and no more keyword
13433 ;; is left, remove the line completely.
13434 (if (and (looking-at-p "[ \t]*$") (not what))
13435 (delete-region (line-beginning-position)
13436 (line-beginning-position 2))
13437 ;; If we removed last keyword, do not leave trailing
13438 ;; white space at the end of line.
13439 (let ((p (point)))
13440 (save-excursion
13441 (end-of-line)
13442 (unless (= (skip-chars-backward " \t" p) 0)
13443 (delete-region (point) (line-end-position)))))))
13444 ((not what) (throw 'exit nil)) ; Nothing to do.
13445 (t (insert-before-markers "\n")
13446 (backward-char 1)
13447 (when org-adapt-indentation
13448 (indent-to-column (1+ (org-outline-level))))))
13449 (when what
13450 ;; Insert planning keyword.
13451 (insert (cl-case what
13452 (closed org-closed-string)
13453 (deadline org-deadline-string)
13454 (scheduled org-scheduled-string)
13455 (otherwise (error "Invalid planning type: %s" what)))
13456 " ")
13457 ;; Insert associated timestamp.
13458 (let ((ts (org-insert-time-stamp
13459 time
13460 (or org-time-was-given
13461 (and (eq what 'closed) org-log-done-with-time))
13462 (eq what 'closed)
13463 nil nil (list org-end-time-was-given))))
13464 (unless (eolp) (insert " "))
13465 ts))))))
13467 (defvar org-log-note-marker (make-marker)
13468 "Marker pointing at the entry where the note is to be inserted.")
13469 (defvar org-log-note-purpose nil)
13470 (defvar org-log-note-state nil)
13471 (defvar org-log-note-previous-state nil)
13472 (defvar org-log-note-extra nil)
13473 (defvar org-log-note-window-configuration nil)
13474 (defvar org-log-note-return-to (make-marker))
13475 (defvar org-log-note-effective-time nil
13476 "Remembered current time so that dynamically scoped
13477 `org-extend-today-until' affects timestamps in state change log")
13479 (defvar org-log-post-message nil
13480 "Message to be displayed after a log note has been stored.
13481 The auto-repeater uses this.")
13483 (defun org-add-note ()
13484 "Add a note to the current entry.
13485 This is done in the same way as adding a state change note."
13486 (interactive)
13487 (org-add-log-setup 'note))
13489 (defun org-log-beginning (&optional create)
13490 "Return expected start of log notes in current entry.
13491 When optional argument CREATE is non-nil, the function creates
13492 a drawer to store notes, if necessary. Returned position ignores
13493 narrowing."
13494 (org-with-wide-buffer
13495 (let ((drawer (org-log-into-drawer)))
13496 (cond
13497 (drawer
13498 (org-end-of-meta-data)
13499 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13500 (end (if (org-at-heading-p) (point)
13501 (save-excursion (outline-next-heading) (point))))
13502 (case-fold-search t))
13503 (catch 'exit
13504 ;; Try to find existing drawer.
13505 (while (re-search-forward regexp end t)
13506 (let ((element (org-element-at-point)))
13507 (when (eq (org-element-type element) 'drawer)
13508 (let ((cend (org-element-property :contents-end element)))
13509 (when (and (not org-log-states-order-reversed) cend)
13510 (goto-char cend)))
13511 (throw 'exit nil))))
13512 ;; No drawer found. Create one, if permitted.
13513 (when create
13514 (unless (bolp) (insert "\n"))
13515 (let ((beg (point)))
13516 (insert ":" drawer ":\n:END:\n")
13517 (org-indent-region beg (point)))
13518 (end-of-line -1)))))
13520 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13521 (skip-chars-forward " \t\n")
13522 (beginning-of-line)
13523 (unless org-log-states-order-reversed
13524 (org-skip-over-state-notes)
13525 (skip-chars-backward " \t\n")
13526 (forward-line)))))
13527 (if (bolp) (point) (line-beginning-position 2))))
13529 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13530 "Set up the post command hook to take a note.
13531 If this is about to TODO state change, the new state is expected in STATE.
13532 HOW is an indicator what kind of note should be created.
13533 EXTRA is additional text that will be inserted into the notes buffer."
13534 (move-marker org-log-note-marker (point))
13535 (setq org-log-note-purpose purpose
13536 org-log-note-state state
13537 org-log-note-previous-state prev-state
13538 org-log-note-how how
13539 org-log-note-extra extra
13540 org-log-note-effective-time (org-current-effective-time))
13541 (add-hook 'post-command-hook 'org-add-log-note 'append))
13543 (defun org-skip-over-state-notes ()
13544 "Skip past the list of State notes in an entry."
13545 (when (ignore-errors (goto-char (org-in-item-p)))
13546 (let* ((struct (org-list-struct))
13547 (prevs (org-list-prevs-alist struct))
13548 (regexp
13549 (concat "[ \t]*- +"
13550 (replace-regexp-in-string
13551 " +" " +"
13552 (org-replace-escapes
13553 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13554 `(("%d" . ,org-ts-regexp-inactive)
13555 ("%D" . ,org-ts-regexp)
13556 ("%s" . "\"\\S-+\"")
13557 ("%S" . "\"\\S-+\"")
13558 ("%t" . ,org-ts-regexp-inactive)
13559 ("%T" . ,org-ts-regexp)
13560 ("%u" . ".*?")
13561 ("%U" . ".*?")))))))
13562 (while (looking-at-p regexp)
13563 (goto-char (or (org-list-get-next-item (point) struct prevs)
13564 (org-list-get-item-end (point) struct)))))))
13566 (defun org-add-log-note (&optional _purpose)
13567 "Pop up a window for taking a note, and add this note later."
13568 (remove-hook 'post-command-hook 'org-add-log-note)
13569 (setq org-log-note-window-configuration (current-window-configuration))
13570 (delete-other-windows)
13571 (move-marker org-log-note-return-to (point))
13572 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13573 (goto-char org-log-note-marker)
13574 (org-switch-to-buffer-other-window "*Org Note*")
13575 (erase-buffer)
13576 (if (memq org-log-note-how '(time state))
13577 (org-store-log-note)
13578 (let ((org-inhibit-startup t)) (org-mode))
13579 (insert (format "# Insert note for %s.
13580 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13581 (cond
13582 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13583 ((eq org-log-note-purpose 'done) "closed todo item")
13584 ((eq org-log-note-purpose 'state)
13585 (format "state change from \"%s\" to \"%s\""
13586 (or org-log-note-previous-state "")
13587 (or org-log-note-state "")))
13588 ((eq org-log-note-purpose 'reschedule)
13589 "rescheduling")
13590 ((eq org-log-note-purpose 'delschedule)
13591 "no longer scheduled")
13592 ((eq org-log-note-purpose 'redeadline)
13593 "changing deadline")
13594 ((eq org-log-note-purpose 'deldeadline)
13595 "removing deadline")
13596 ((eq org-log-note-purpose 'refile)
13597 "refiling")
13598 ((eq org-log-note-purpose 'note)
13599 "this entry")
13600 (t (error "This should not happen")))))
13601 (when org-log-note-extra (insert org-log-note-extra))
13602 (setq-local org-finish-function 'org-store-log-note)
13603 (run-hooks 'org-log-buffer-setup-hook)))
13605 (defvar org-note-abort nil) ; dynamically scoped
13606 (defun org-store-log-note ()
13607 "Finish taking a log note, and insert it to where it belongs."
13608 (let ((txt (prog1 (buffer-string)
13609 (kill-buffer)))
13610 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13611 lines)
13612 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13613 (setq txt (replace-match "" t t txt)))
13614 (when (string-match "\\s-+\\'" txt)
13615 (setq txt (replace-match "" t t txt)))
13616 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13617 (when (org-string-nw-p note)
13618 (setq note
13619 (org-replace-escapes
13620 note
13621 (list (cons "%u" (user-login-name))
13622 (cons "%U" user-full-name)
13623 (cons "%t" (format-time-string
13624 (org-time-stamp-format 'long 'inactive)
13625 org-log-note-effective-time))
13626 (cons "%T" (format-time-string
13627 (org-time-stamp-format 'long nil)
13628 org-log-note-effective-time))
13629 (cons "%d" (format-time-string
13630 (org-time-stamp-format nil 'inactive)
13631 org-log-note-effective-time))
13632 (cons "%D" (format-time-string
13633 (org-time-stamp-format nil nil)
13634 org-log-note-effective-time))
13635 (cons "%s" (cond
13636 ((not org-log-note-state) "")
13637 ((string-match-p org-ts-regexp
13638 org-log-note-state)
13639 (format "\"[%s]\""
13640 (substring org-log-note-state 1 -1)))
13641 (t (format "\"%s\"" org-log-note-state))))
13642 (cons "%S"
13643 (cond
13644 ((not org-log-note-previous-state) "")
13645 ((string-match-p org-ts-regexp
13646 org-log-note-previous-state)
13647 (format "\"[%s]\""
13648 (substring
13649 org-log-note-previous-state 1 -1)))
13650 (t (format "\"%s\""
13651 org-log-note-previous-state)))))))
13652 (when lines (setq note (concat note " \\\\")))
13653 (push note lines))
13654 (when (and lines (not org-note-abort))
13655 (with-current-buffer (marker-buffer org-log-note-marker)
13656 (org-with-wide-buffer
13657 ;; Find location for the new note.
13658 (goto-char org-log-note-marker)
13659 (set-marker org-log-note-marker nil)
13660 ;; Note associated to a clock is to be located right after
13661 ;; the clock. Do not move point.
13662 (unless (eq org-log-note-purpose 'clock-out)
13663 (goto-char (org-log-beginning t)))
13664 ;; Make sure point is at the beginning of an empty line.
13665 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13666 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13667 ;; In an existing list, add a new item at the top level.
13668 ;; Otherwise, indent line like a regular one.
13669 (let ((itemp (org-in-item-p)))
13670 (if itemp
13671 (indent-line-to
13672 (let ((struct (save-excursion
13673 (goto-char itemp) (org-list-struct))))
13674 (org-list-get-ind (org-list-get-top-point struct) struct)))
13675 (org-indent-line)))
13676 (insert (org-list-bullet-string "-") (pop lines))
13677 (let ((ind (org-list-item-body-column (line-beginning-position))))
13678 (dolist (line lines)
13679 (insert "\n")
13680 (indent-line-to ind)
13681 (insert line)))
13682 (message "Note stored")
13683 (org-back-to-heading t)
13684 (org-cycle-hide-drawers 'children))
13685 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13686 ;; from within `org-add-log-note' because `buffer-undo-list'
13687 ;; is then modified outside of `org-with-remote-undo'.
13688 (when (eq this-command 'org-agenda-todo)
13689 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13690 ;; Don't add undo information when called from `org-agenda-todo'.
13691 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13692 (set-window-configuration org-log-note-window-configuration)
13693 (with-current-buffer (marker-buffer org-log-note-return-to)
13694 (goto-char org-log-note-return-to))
13695 (move-marker org-log-note-return-to nil)
13696 (when org-log-post-message (message "%s" org-log-post-message))))
13698 (defun org-remove-empty-drawer-at (pos)
13699 "Remove an empty drawer at position POS.
13700 POS may also be a marker."
13701 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13702 (org-with-wide-buffer
13703 (goto-char pos)
13704 (let ((drawer (org-element-at-point)))
13705 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13706 (not (org-element-property :contents-begin drawer)))
13707 (delete-region (org-element-property :begin drawer)
13708 (progn (goto-char (org-element-property :end drawer))
13709 (skip-chars-backward " \r\t\n")
13710 (forward-line)
13711 (point))))))))
13713 (defvar org-ts-type nil)
13714 (defun org-sparse-tree (&optional arg type)
13715 "Create a sparse tree, prompt for the details.
13716 This command can create sparse trees. You first need to select the type
13717 of match used to create the tree:
13719 t Show all TODO entries.
13720 T Show entries with a specific TODO keyword.
13721 m Show entries selected by a tags/property match.
13722 p Enter a property name and its value (both with completion on existing
13723 names/values) and show entries with that property.
13724 r Show entries matching a regular expression (`/' can be used as well).
13725 b Show deadlines and scheduled items before a date.
13726 a Show deadlines and scheduled items after a date.
13727 d Show deadlines due within `org-deadline-warning-days'.
13728 D Show deadlines and scheduled items between a date range."
13729 (interactive "P")
13730 (setq type (or type org-sparse-tree-default-date-type))
13731 (setq org-ts-type type)
13732 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13733 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13734 \[c]ycle through date types: %s"
13735 (cl-case type
13736 (all "all timestamps")
13737 (scheduled "only scheduled")
13738 (deadline "only deadline")
13739 (active "only active timestamps")
13740 (inactive "only inactive timestamps")
13741 (closed "with a closed time-stamp")
13742 (otherwise "scheduled/deadline")))
13743 (let ((answer (read-char-exclusive)))
13744 (cl-case answer
13746 (org-sparse-tree
13748 (cadr
13749 (memq type '(nil all scheduled deadline active inactive closed)))))
13750 (?d (call-interactively 'org-check-deadlines))
13751 (?b (call-interactively 'org-check-before-date))
13752 (?a (call-interactively 'org-check-after-date))
13753 (?D (call-interactively 'org-check-dates-range))
13754 (?t (call-interactively 'org-show-todo-tree))
13755 (?T (org-show-todo-tree '(4)))
13756 (?m (call-interactively 'org-match-sparse-tree))
13757 ((?p ?P)
13758 (let* ((kwd (completing-read
13759 "Property: " (mapcar #'list (org-buffer-property-keys))))
13760 (value (completing-read
13761 "Value: " (mapcar #'list (org-property-values kwd)))))
13762 (unless (string-match "\\`{.*}\\'" value)
13763 (setq value (concat "\"" value "\"")))
13764 (org-match-sparse-tree arg (concat kwd "=" value))))
13765 ((?r ?R ?/) (call-interactively 'org-occur))
13766 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13768 (defvar-local org-occur-highlights nil
13769 "List of overlays used for occur matches.")
13770 (defvar-local org-occur-parameters nil
13771 "Parameters of the active org-occur calls.
13772 This is a list, each call to org-occur pushes as cons cell,
13773 containing the regular expression and the callback, onto the list.
13774 The list can contain several entries if `org-occur' has been called
13775 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13776 will only contain one set of parameters. When the highlights are
13777 removed (for example with `C-c C-c', or with the next edit (depending
13778 on `org-remove-highlights-with-change'), this variable is emptied
13779 as well.")
13781 (defun org-occur (regexp &optional keep-previous callback)
13782 "Make a compact tree which shows all matches of REGEXP.
13784 The tree will show the lines where the regexp matches, and any other context
13785 defined in `org-show-context-detail', which see.
13787 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13788 done by a previous call to `org-occur' will be kept, to allow stacking of
13789 calls to this command.
13791 Optional argument CALLBACK can be a function of no argument. In this case,
13792 it is called with point at the end of the match, match data being set
13793 accordingly. Current match is shown only if the return value is non-nil.
13794 The function must neither move point nor alter narrowing."
13795 (interactive "sRegexp: \nP")
13796 (when (equal regexp "")
13797 (user-error "Regexp cannot be empty"))
13798 (unless keep-previous
13799 (org-remove-occur-highlights nil nil t))
13800 (push (cons regexp callback) org-occur-parameters)
13801 (let ((cnt 0))
13802 (save-excursion
13803 (goto-char (point-min))
13804 (when (or (not keep-previous) ; do not want to keep
13805 (not org-occur-highlights)) ; no previous matches
13806 ;; hide everything
13807 (org-overview))
13808 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13809 (isearch-no-upper-case-p regexp t)
13810 org-occur-case-fold-search)))
13811 (while (re-search-forward regexp nil t)
13812 (when (or (not callback)
13813 (save-match-data (funcall callback)))
13814 (setq cnt (1+ cnt))
13815 (when org-highlight-sparse-tree-matches
13816 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13817 (org-show-context 'occur-tree)))))
13818 (when org-remove-highlights-with-change
13819 (add-hook 'before-change-functions 'org-remove-occur-highlights
13820 nil 'local))
13821 (unless org-sparse-tree-open-archived-trees
13822 (org-hide-archived-subtrees (point-min) (point-max)))
13823 (run-hooks 'org-occur-hook)
13824 (when (called-interactively-p 'interactive)
13825 (message "%d match(es) for regexp %s" cnt regexp))
13826 cnt))
13828 (defun org-occur-next-match (&optional n _reset)
13829 "Function for `next-error-function' to find sparse tree matches.
13830 N is the number of matches to move, when negative move backwards.
13831 This function always goes back to the starting point when no
13832 match is found."
13833 (let* ((limit (if (< n 0) (point-min) (point-max)))
13834 (search-func (if (< n 0)
13835 'previous-single-char-property-change
13836 'next-single-char-property-change))
13837 (n (abs n))
13838 (pos (point))
13840 (catch 'exit
13841 (while (setq p1 (funcall search-func (point) 'org-type))
13842 (when (equal p1 limit)
13843 (goto-char pos)
13844 (user-error "No more matches"))
13845 (when (equal (get-char-property p1 'org-type) 'org-occur)
13846 (setq n (1- n))
13847 (when (= n 0)
13848 (goto-char p1)
13849 (throw 'exit (point))))
13850 (goto-char p1))
13851 (goto-char p1)
13852 (user-error "No more matches"))))
13854 (defun org-show-context (&optional key)
13855 "Make sure point and context are visible.
13856 Optional argument KEY, when non-nil, is a symbol. See
13857 `org-show-context-detail' for allowed values and how much is to
13858 be shown."
13859 (org-show-set-visibility
13860 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13861 ((cdr (assq key org-show-context-detail)))
13862 (t (cdr (assq 'default org-show-context-detail))))))
13864 (defun org-show-set-visibility (detail)
13865 "Set visibility around point according to DETAIL.
13866 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13867 `tree', `canonical' or t. See `org-show-context-detail' for more
13868 information."
13869 ;; Show current heading and possibly its entry, following headline
13870 ;; or all children.
13871 (if (and (org-at-heading-p) (not (eq detail 'local)))
13872 (org-flag-heading nil)
13873 (org-show-entry)
13874 ;; If point is hidden within a drawer or a block, make sure to
13875 ;; expose it.
13876 (dolist (o (overlays-at (point)))
13877 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13878 (delete-overlay o)))
13879 (unless (org-before-first-heading-p)
13880 (org-with-limited-levels
13881 (cl-case detail
13882 ((tree canonical t) (org-show-children))
13883 ((nil minimal ancestors))
13884 (t (save-excursion
13885 (outline-next-heading)
13886 (org-flag-heading nil)))))))
13887 ;; Show all siblings.
13888 (when (eq detail 'lineage) (org-show-siblings))
13889 ;; Show ancestors, possibly with their children.
13890 (when (memq detail '(ancestors lineage tree canonical t))
13891 (save-excursion
13892 (while (org-up-heading-safe)
13893 (org-flag-heading nil)
13894 (when (memq detail '(canonical t)) (org-show-entry))
13895 (when (memq detail '(tree canonical t)) (org-show-children))))))
13897 (defvar org-reveal-start-hook nil
13898 "Hook run before revealing a location.")
13900 (defun org-reveal (&optional siblings)
13901 "Show current entry, hierarchy above it, and the following headline.
13903 This can be used to show a consistent set of context around
13904 locations exposed with `org-show-context'.
13906 With optional argument SIBLINGS, on each level of the hierarchy all
13907 siblings are shown. This repairs the tree structure to what it would
13908 look like when opened with hierarchical calls to `org-cycle'.
13910 With a \\[universal-argument] \\[universal-argument] prefix, \
13911 go to the parent and show the entire tree."
13912 (interactive "P")
13913 (run-hooks 'org-reveal-start-hook)
13914 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13915 ((equal siblings '(16))
13916 (save-excursion
13917 (when (org-up-heading-safe)
13918 (org-show-subtree)
13919 (run-hook-with-args 'org-cycle-hook 'subtree))))
13920 (t (org-show-set-visibility 'lineage))))
13922 (defun org-highlight-new-match (beg end)
13923 "Highlight from BEG to END and mark the highlight is an occur headline."
13924 (let ((ov (make-overlay beg end)))
13925 (overlay-put ov 'face 'secondary-selection)
13926 (overlay-put ov 'org-type 'org-occur)
13927 (push ov org-occur-highlights)))
13929 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13930 "Remove the occur highlights from the buffer.
13931 BEG and END are ignored. If NOREMOVE is nil, remove this function
13932 from the `before-change-functions' in the current buffer."
13933 (interactive)
13934 (unless org-inhibit-highlight-removal
13935 (mapc #'delete-overlay org-occur-highlights)
13936 (setq org-occur-highlights nil)
13937 (setq org-occur-parameters nil)
13938 (unless noremove
13939 (remove-hook 'before-change-functions
13940 'org-remove-occur-highlights 'local))))
13942 ;;;; Priorities
13944 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13945 "Regular expression matching the priority indicator.")
13947 (defvar org-remove-priority-next-time nil)
13949 (defun org-priority-up ()
13950 "Increase the priority of the current item."
13951 (interactive)
13952 (org-priority 'up))
13954 (defun org-priority-down ()
13955 "Decrease the priority of the current item."
13956 (interactive)
13957 (org-priority 'down))
13959 (defun org-priority (&optional action _show)
13960 "Change the priority of an item.
13961 ACTION can be `set', `up', `down', or a character."
13962 (interactive "P")
13963 (if (equal action '(4))
13964 (org-show-priority)
13965 (unless org-enable-priority-commands
13966 (user-error "Priority commands are disabled"))
13967 (setq action (or action 'set))
13968 (let (current new news have remove)
13969 (save-excursion
13970 (org-back-to-heading t)
13971 (when (looking-at org-priority-regexp)
13972 (setq current (string-to-char (match-string 2))
13973 have t))
13974 (cond
13975 ((eq action 'remove)
13976 (setq remove t new ?\ ))
13977 ((or (eq action 'set)
13978 (integerp action))
13979 (if (not (eq action 'set))
13980 (setq new action)
13981 (message "Priority %c-%c, SPC to remove: "
13982 org-highest-priority org-lowest-priority)
13983 (save-match-data
13984 (setq new (read-char-exclusive))))
13985 (when (and (= (upcase org-highest-priority) org-highest-priority)
13986 (= (upcase org-lowest-priority) org-lowest-priority))
13987 (setq new (upcase new)))
13988 (cond ((equal new ?\ ) (setq remove t))
13989 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13990 (user-error "Priority must be between `%c' and `%c'"
13991 org-highest-priority org-lowest-priority))))
13992 ((eq action 'up)
13993 (setq new (if have
13994 (1- current) ; normal cycling
13995 ;; last priority was empty
13996 (if (eq last-command this-command)
13997 org-lowest-priority ; wrap around empty to lowest
13998 ;; default
13999 (if org-priority-start-cycle-with-default
14000 org-default-priority
14001 (1- org-default-priority))))))
14002 ((eq action 'down)
14003 (setq new (if have
14004 (1+ current) ; normal cycling
14005 ;; last priority was empty
14006 (if (eq last-command this-command)
14007 org-highest-priority ; wrap around empty to highest
14008 ;; default
14009 (if org-priority-start-cycle-with-default
14010 org-default-priority
14011 (1+ org-default-priority))))))
14012 (t (user-error "Invalid action")))
14013 (when (or (< (upcase new) org-highest-priority)
14014 (> (upcase new) org-lowest-priority))
14015 (if (and (memq action '(up down))
14016 (not have) (not (eq last-command this-command)))
14017 ;; `new' is from default priority
14018 (error
14019 "The default can not be set, see `org-default-priority' why")
14020 ;; normal cycling: `new' is beyond highest/lowest priority
14021 ;; and is wrapped around to the empty priority
14022 (setq remove t)))
14023 (setq news (format "%c" new))
14024 (if have
14025 (if remove
14026 (replace-match "" t t nil 1)
14027 (replace-match news t t nil 2))
14028 (if remove
14029 (user-error "No priority cookie found in line")
14030 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14031 (if (match-end 2)
14032 (progn
14033 (goto-char (match-end 2))
14034 (insert " [#" news "]"))
14035 (goto-char (match-beginning 3))
14036 (insert "[#" news "] "))))
14037 (org-set-tags nil 'align))
14038 (if remove
14039 (message "Priority removed")
14040 (message "Priority of current item set to %s" news)))))
14042 (defun org-show-priority ()
14043 "Show the priority of the current item.
14044 This priority is composed of the main priority given with the [#A] cookies,
14045 and by additional input from the age of a schedules or deadline entry."
14046 (interactive)
14047 (let ((pri (if (eq major-mode 'org-agenda-mode)
14048 (org-get-at-bol 'priority)
14049 (save-excursion
14050 (save-match-data
14051 (beginning-of-line)
14052 (and (looking-at org-heading-regexp)
14053 (org-get-priority (match-string 0))))))))
14054 (message "Priority is %d" (if pri pri -1000))))
14056 (defun org-get-priority (s)
14057 "Find priority cookie and return priority."
14058 (save-match-data
14059 (if (functionp org-get-priority-function)
14060 (funcall org-get-priority-function)
14061 (if (not (string-match org-priority-regexp s))
14062 (* 1000 (- org-lowest-priority org-default-priority))
14063 (* 1000 (- org-lowest-priority
14064 (string-to-char (match-string 2 s))))))))
14066 ;;;; Tags
14068 (defvar org-agenda-archives-mode)
14069 (defvar org-map-continue-from nil
14070 "Position from where mapping should continue.
14071 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14073 (defvar org-scanner-tags nil
14074 "The current tag list while the tags scanner is running.")
14076 (defvar org-trust-scanner-tags nil
14077 "Should `org-get-tags-at' use the tags for the scanner.
14078 This is for internal dynamical scoping only.
14079 When this is non-nil, the function `org-get-tags-at' will return the value
14080 of `org-scanner-tags' instead of building the list by itself. This
14081 can lead to large speed-ups when the tags scanner is used in a file with
14082 many entries, and when the list of tags is retrieved, for example to
14083 obtain a list of properties. Building the tags list for each entry in such
14084 a file becomes an N^2 operation - but with this variable set, it scales
14085 as N.")
14087 (defvar org--matcher-tags-todo-only nil)
14089 (defun org-scan-tags (action matcher todo-only &optional start-level)
14090 "Scan headline tags with inheritance and produce output ACTION.
14092 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14093 or `agenda' to produce an entry list for an agenda view. It can also be
14094 a Lisp form or a function that should be called at each matched headline, in
14095 this case the return value is a list of all return values from these calls.
14097 MATCHER is a function accepting three arguments, returning
14098 a non-nil value whenever a given set of tags qualifies a headline
14099 for inclusion. See `org-make-tags-matcher' for more information.
14100 As a special case, it can also be set to t (respectively nil) in
14101 order to match all (respectively none) headline.
14103 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14104 included in the output.
14106 START-LEVEL can be a string with asterisks, reducing the scope to
14107 headlines matching this string."
14108 (require 'org-agenda)
14109 (let* ((re (concat "^"
14110 (if start-level
14111 ;; Get the correct level to match
14112 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14113 org-outline-regexp)
14114 " *\\(\\<\\("
14115 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14116 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14117 (props (list 'face 'default
14118 'done-face 'org-agenda-done
14119 'undone-face 'default
14120 'mouse-face 'highlight
14121 'org-not-done-regexp org-not-done-regexp
14122 'org-todo-regexp org-todo-regexp
14123 'org-complex-heading-regexp org-complex-heading-regexp
14124 'help-echo
14125 (format "mouse-2 or RET jump to org file %s"
14126 (abbreviate-file-name
14127 (or (buffer-file-name (buffer-base-buffer))
14128 (buffer-name (buffer-base-buffer)))))))
14129 (org-map-continue-from nil)
14130 lspos tags tags-list
14131 (tags-alist (list (cons 0 org-file-tags)))
14132 (llast 0) rtn rtn1 level category i txt
14133 todo marker entry priority
14134 ts-date ts-date-type ts-date-pair)
14135 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14136 (setq action (list 'lambda nil action)))
14137 (save-excursion
14138 (goto-char (point-min))
14139 (when (eq action 'sparse-tree)
14140 (org-overview)
14141 (org-remove-occur-highlights))
14142 (while (let (case-fold-search)
14143 (re-search-forward re nil t))
14144 (setq org-map-continue-from nil)
14145 (catch :skip
14146 (setq todo
14147 ;; TODO: is the 1-2 difference a bug?
14148 (when (match-end 1) (match-string-no-properties 2))
14149 tags (when (match-end 4) (match-string-no-properties 4)))
14150 (goto-char (setq lspos (match-beginning 0)))
14151 (setq level (org-reduced-level (org-outline-level))
14152 category (org-get-category))
14153 (when (eq action 'agenda)
14154 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14155 ts-date (car ts-date-pair)
14156 ts-date-type (cdr ts-date-pair)))
14157 (setq i llast llast level)
14158 ;; remove tag lists from same and sublevels
14159 (while (>= i level)
14160 (when (setq entry (assoc i tags-alist))
14161 (setq tags-alist (delete entry tags-alist)))
14162 (setq i (1- i)))
14163 ;; add the next tags
14164 (when tags
14165 (setq tags (org-split-string tags ":")
14166 tags-alist
14167 (cons (cons level tags) tags-alist)))
14168 ;; compile tags for current headline
14169 (setq tags-list
14170 (if org-use-tag-inheritance
14171 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14172 tags)
14173 org-scanner-tags tags-list)
14174 (when org-use-tag-inheritance
14175 (setcdr (car tags-alist)
14176 (mapcar (lambda (x)
14177 (setq x (copy-sequence x))
14178 (org-add-prop-inherited x))
14179 (cdar tags-alist))))
14180 (when (and tags org-use-tag-inheritance
14181 (or (not (eq t org-use-tag-inheritance))
14182 org-tags-exclude-from-inheritance))
14183 ;; Selective inheritance, remove uninherited ones.
14184 (setcdr (car tags-alist)
14185 (org-remove-uninherited-tags (cdar tags-alist))))
14186 (when (and
14188 ;; eval matcher only when the todo condition is OK
14189 (and (or (not todo-only) (member todo org-todo-keywords-1))
14190 (if (functionp matcher)
14191 (let ((case-fold-search t) (org-trust-scanner-tags t))
14192 (funcall matcher todo tags-list level))
14193 matcher))
14195 ;; Call the skipper, but return t if it does not
14196 ;; skip, so that the `and' form continues evaluating.
14197 (progn
14198 (unless (eq action 'sparse-tree) (org-agenda-skip))
14201 ;; Check if timestamps are deselecting this entry
14202 (or (not todo-only)
14203 (and (member todo org-todo-keywords-1)
14204 (or (not org-agenda-tags-todo-honor-ignore-options)
14205 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14207 ;; select this headline
14208 (cond
14209 ((eq action 'sparse-tree)
14210 (and org-highlight-sparse-tree-matches
14211 (org-get-heading) (match-end 0)
14212 (org-highlight-new-match
14213 (match-beginning 1) (match-end 1)))
14214 (org-show-context 'tags-tree))
14215 ((eq action 'agenda)
14216 (setq txt (org-agenda-format-item
14218 (concat
14219 (if (eq org-tags-match-list-sublevels 'indented)
14220 (make-string (1- level) ?.) "")
14221 (org-get-heading))
14222 (make-string level ?\s)
14223 category
14224 tags-list)
14225 priority (org-get-priority txt))
14226 (goto-char lspos)
14227 (setq marker (org-agenda-new-marker))
14228 (org-add-props txt props
14229 'org-marker marker 'org-hd-marker marker 'org-category category
14230 'todo-state todo
14231 'ts-date ts-date
14232 'priority priority
14233 'type (concat "tagsmatch" ts-date-type))
14234 (push txt rtn))
14235 ((functionp action)
14236 (setq org-map-continue-from nil)
14237 (save-excursion
14238 (setq rtn1 (funcall action))
14239 (push rtn1 rtn)))
14240 (t (user-error "Invalid action")))
14242 ;; if we are to skip sublevels, jump to end of subtree
14243 (unless org-tags-match-list-sublevels
14244 (org-end-of-subtree t)
14245 (backward-char 1))))
14246 ;; Get the correct position from where to continue
14247 (if org-map-continue-from
14248 (goto-char org-map-continue-from)
14249 (and (= (point) lspos) (end-of-line 1)))))
14250 (when (and (eq action 'sparse-tree)
14251 (not org-sparse-tree-open-archived-trees))
14252 (org-hide-archived-subtrees (point-min) (point-max)))
14253 (nreverse rtn)))
14255 (defun org-remove-uninherited-tags (tags)
14256 "Remove all tags that are not inherited from the list TAGS."
14257 (cond
14258 ((eq org-use-tag-inheritance t)
14259 (if org-tags-exclude-from-inheritance
14260 (org-delete-all org-tags-exclude-from-inheritance tags)
14261 tags))
14262 ((not org-use-tag-inheritance) nil)
14263 ((stringp org-use-tag-inheritance)
14264 (delq nil (mapcar
14265 (lambda (x)
14266 (if (and (string-match org-use-tag-inheritance x)
14267 (not (member x org-tags-exclude-from-inheritance)))
14268 x nil))
14269 tags)))
14270 ((listp org-use-tag-inheritance)
14271 (delq nil (mapcar
14272 (lambda (x)
14273 (if (member x org-use-tag-inheritance) x nil))
14274 tags)))))
14276 (defun org-match-sparse-tree (&optional todo-only match)
14277 "Create a sparse tree according to tags string MATCH.
14279 MATCH is a string with match syntax. It can contain a selection
14280 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14281 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14282 those. See the manual for details.
14284 If optional argument TODO-ONLY is non-nil, only select lines that
14285 are also TODO tasks."
14286 (interactive "P")
14287 (org-agenda-prepare-buffers (list (current-buffer)))
14288 (let ((org--matcher-tags-todo-only todo-only))
14289 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14290 org--matcher-tags-todo-only)))
14292 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14294 (defvar org-cached-props nil)
14295 (defun org-cached-entry-get (pom property)
14296 (if (or (eq t org-use-property-inheritance)
14297 (and (stringp org-use-property-inheritance)
14298 (let ((case-fold-search t))
14299 (string-match-p org-use-property-inheritance property)))
14300 (and (listp org-use-property-inheritance)
14301 (member-ignore-case property org-use-property-inheritance)))
14302 ;; Caching is not possible, check it directly.
14303 (org-entry-get pom property 'inherit)
14304 ;; Get all properties, so we can do complicated checks easily.
14305 (cdr (assoc-string property
14306 (or org-cached-props
14307 (setq org-cached-props (org-entry-properties pom)))
14308 t))))
14310 (defun org-global-tags-completion-table (&optional files)
14311 "Return the list of all tags in all agenda buffer/files.
14312 Optional FILES argument is a list of files which can be used
14313 instead of the agenda files."
14314 (save-excursion
14315 (org-uniquify
14316 (delq nil
14317 (apply #'append
14318 (mapcar
14319 (lambda (file)
14320 (set-buffer (find-file-noselect file))
14321 (mapcar (lambda (x)
14322 (and (stringp (car-safe x))
14323 (list (car-safe x))))
14324 (or org-current-tag-alist (org-get-buffer-tags))))
14325 (if (car-safe files) files
14326 (org-agenda-files))))))))
14328 (defun org-make-tags-matcher (match)
14329 "Create the TAGS/TODO matcher form for the selection string MATCH.
14331 Returns a cons of the selection string MATCH and a function
14332 implementing the matcher.
14334 The matcher is to be called at an Org entry, with point on the
14335 headline, and returns non-nil if the entry matches the selection
14336 string MATCH. It must be called with three arguments: the TODO
14337 keyword at the entry (or nil if none), the list of all tags at
14338 the entry including inherited ones and the reduced level of the
14339 headline. Additionally, the category of the entry, if any, must
14340 be specified as the text property `org-category' on the headline.
14342 This function sets the variable `org--matcher-tags-todo-only' to
14343 a non-nil value if the matcher restricts matching to TODO
14344 entries, otherwise it is not touched.
14346 See also `org-scan-tags'."
14347 (unless match
14348 ;; Get a new match request, with completion against the global
14349 ;; tags table and the local tags in current buffer.
14350 (let ((org-last-tags-completion-table
14351 (org-uniquify
14352 (delq nil (append (org-get-buffer-tags)
14353 (org-global-tags-completion-table))))))
14354 (setq match
14355 (completing-read
14356 "Match: "
14357 'org-tags-completion-function nil nil nil 'org-tags-history))))
14359 (let ((match0 match)
14360 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14361 (start 0)
14362 tagsmatch todomatch tagsmatcher todomatcher)
14364 ;; Expand group tags.
14365 (setq match (org-tags-expand match))
14367 ;; Check if there is a TODO part of this match, which would be the
14368 ;; part after a "/". To make sure that this slash is not part of
14369 ;; a property value to be matched against, we also check that
14370 ;; there is no / after that slash. First, find the last slash.
14371 (let ((s 0))
14372 (while (string-match "/+" match s)
14373 (setq start (match-beginning 0))
14374 (setq s (match-end 0))))
14375 (if (and (string-match "/+" match start)
14376 (not (string-match-p "\"" match start)))
14377 ;; Match contains also a TODO-matching request.
14378 (progn
14379 (setq tagsmatch (substring match 0 (match-beginning 0)))
14380 (setq todomatch (substring match (match-end 0)))
14381 (when (string-prefix-p "!" todomatch)
14382 (setq org--matcher-tags-todo-only t)
14383 (setq todomatch (substring todomatch 1)))
14384 (when (string-match "\\`\\s-*\\'" todomatch)
14385 (setq todomatch nil)))
14386 ;; Only matching tags.
14387 (setq tagsmatch match)
14388 (setq todomatch nil))
14390 ;; Make the tags matcher.
14391 (when (org-string-nw-p tagsmatch)
14392 (let ((orlist nil)
14393 (orterms (org-split-string tagsmatch "|"))
14394 term)
14395 (while (setq term (pop orterms))
14396 (while (and (equal (substring term -1) "\\") orterms)
14397 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14398 (while (string-match re term)
14399 (let* ((rest (substring term (match-end 0)))
14400 (minus (and (match-end 1)
14401 (equal (match-string 1 term) "-")))
14402 (tag (save-match-data
14403 (replace-regexp-in-string
14404 "\\\\-" "-" (match-string 2 term))))
14405 (regexp (eq (string-to-char tag) ?{))
14406 (levelp (match-end 4))
14407 (propp (match-end 5))
14409 (cond
14410 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14411 (levelp
14412 `(,(org-op-to-function (match-string 3 term))
14413 level
14414 ,(string-to-number (match-string 4 term))))
14415 (propp
14416 (let* ((gv (pcase (upcase (match-string 5 term))
14417 ("CATEGORY"
14418 '(get-text-property (point) 'org-category))
14419 ("TODO" 'todo)
14420 (p `(org-cached-entry-get nil ,p))))
14421 (pv (match-string 7 term))
14422 (regexp (eq (string-to-char pv) ?{))
14423 (strp (eq (string-to-char pv) ?\"))
14424 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14425 (po (org-op-to-function (match-string 6 term)
14426 (if timep 'time strp))))
14427 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14428 (when timep (setq pv (org-matcher-time pv)))
14429 (cond ((and regexp (eq po 'org<>))
14430 `(not (string-match ,pv (or ,gv ""))))
14431 (regexp `(string-match ,pv (or ,gv "")))
14432 (strp `(,po (or ,gv "") ,pv))
14434 `(,po
14435 (string-to-number (or ,gv ""))
14436 ,(string-to-number pv))))))
14437 (t `(member ,tag tags-list)))))
14438 (push (if minus `(not ,mm) mm) tagsmatcher)
14439 (setq term rest)))
14440 (push `(and ,@tagsmatcher) orlist)
14441 (setq tagsmatcher nil))
14442 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14444 ;; Make the TODO matcher.
14445 (when (org-string-nw-p todomatch)
14446 (let ((orlist nil))
14447 (dolist (term (org-split-string todomatch "|"))
14448 (while (string-match re term)
14449 (let* ((minus (and (match-end 1)
14450 (equal (match-string 1 term) "-")))
14451 (kwd (match-string 2 term))
14452 (regexp (eq (string-to-char kwd) ?{))
14453 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14454 `(equal todo ,kwd))))
14455 (push (if minus `(not ,mm) mm) todomatcher))
14456 (setq term (substring term (match-end 0))))
14457 (push (if (> (length todomatcher) 1)
14458 (cons 'and todomatcher)
14459 (car todomatcher))
14460 orlist)
14461 (setq todomatcher nil))
14462 (setq todomatcher (cons 'or orlist))))
14464 ;; Return the string and function of the matcher. If no
14465 ;; tags-specific or todo-specific matcher exists, match
14466 ;; everything.
14467 (let ((matcher (if (and tagsmatcher todomatcher)
14468 `(and ,tagsmatcher ,todomatcher)
14469 (or tagsmatcher todomatcher t))))
14470 (when org--matcher-tags-todo-only
14471 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14472 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14474 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14475 "Expand group tags in MATCH.
14477 This replaces every group tag in MATCH with a regexp tag search.
14478 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14479 will be replaced like this:
14481 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14482 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14483 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14485 Replacing by a regexp preserves the structure of the match.
14486 E.g., this expansion
14488 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14490 will match anything tagged with \"Lab\" and \"Home\", or tagged
14491 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14493 A group tag in MATCH can contain regular expressions of its own.
14494 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14495 will be replaced like this:
14497 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14499 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14500 assumed to be a single group tag, and the function will return
14501 the list of tags in this group.
14503 When DOWNCASE is non-nil, expand downcased TAGS."
14504 (if org-group-tags
14505 (let* ((case-fold-search t)
14506 (stable org-mode-syntax-table)
14507 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14508 (taggroups (if downcased
14509 (mapcar (lambda (tg) (mapcar #'downcase tg))
14510 taggroups)
14511 taggroups))
14512 (taggroups-keys (mapcar #'car taggroups))
14513 (return-match (if downcased (downcase match) match))
14514 (count 0)
14515 (work-already-expanded tags-already-expanded)
14516 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14517 ;; @ and _ are allowed as word-components in tags.
14518 (modify-syntax-entry ?@ "w" stable)
14519 (modify-syntax-entry ?_ "w" stable)
14520 ;; Temporarily replace regexp-expressions in the match-expression.
14521 (while (string-match "{.+?}" return-match)
14522 (cl-incf count)
14523 (push (match-string 0 return-match) regexps-in-match)
14524 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14525 (while (and taggroups-keys
14526 (with-syntax-table stable
14527 (string-match
14528 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14529 (regexp-opt taggroups-keys) "\\>\\)")
14530 return-match)))
14531 (let* ((dir (match-string 1 return-match))
14532 (tag (match-string 2 return-match))
14533 (tag (if downcased (downcase tag) tag)))
14534 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14535 (member tag work-already-expanded))
14536 (setq tags-in-group (assoc tag taggroups))
14537 (push tag work-already-expanded)
14538 ;; Recursively expand each tag in the group, if the tag hasn't
14539 ;; already been expanded. Restore the match-data after all recursive calls.
14540 (save-match-data
14541 (let (tags-expanded)
14542 (dolist (x (cdr tags-in-group))
14543 (if (and (member x taggroups-keys)
14544 (not (member x work-already-expanded)))
14545 (setq tags-expanded
14546 (delete-dups
14547 (append
14548 (org-tags-expand x t downcased
14549 work-already-expanded)
14550 tags-expanded)))
14551 (setq tags-expanded
14552 (append (list x) tags-expanded)))
14553 (setq work-already-expanded
14554 (delete-dups
14555 (append tags-expanded
14556 work-already-expanded))))
14557 (setq tags-in-group
14558 (delete-dups (cons (car tags-in-group)
14559 tags-expanded)))))
14560 ;; Filter tag-regexps from tags.
14561 (setq regexp-in-group-escaped
14562 (delq nil (mapcar (lambda (x)
14563 (if (stringp x)
14564 (and (equal "{" (substring x 0 1))
14565 (equal "}" (substring x -1))
14568 tags-in-group))
14569 regexp-in-group
14570 (mapcar (lambda (x)
14571 (substring x 1 -1))
14572 regexp-in-group-escaped)
14573 tags-in-group
14574 (delq nil (mapcar (lambda (x)
14575 (if (stringp x)
14576 (and (not (equal "{" (substring x 0 1)))
14577 (not (equal "}" (substring x -1)))
14580 tags-in-group)))
14581 ;; If single-as-list, do no more in the while-loop.
14582 (if (not single-as-list)
14583 (progn
14584 (when regexp-in-group
14585 (setq regexp-in-group
14586 (concat "\\|"
14587 (mapconcat 'identity regexp-in-group
14588 "\\|"))))
14589 (setq tags-in-group
14590 (concat dir
14591 "{\\<"
14592 (regexp-opt tags-in-group)
14593 "\\>"
14594 regexp-in-group
14595 "}"))
14596 (when (stringp tags-in-group)
14597 (org-add-props tags-in-group '(grouptag t)))
14598 (setq return-match
14599 (replace-match tags-in-group t t return-match)))
14600 (setq tags-in-group
14601 (append regexp-in-group-escaped tags-in-group))))
14602 (setq taggroups-keys (delete tag taggroups-keys))))
14603 ;; Add the regular expressions back into the match-expression again.
14604 (while regexps-in-match
14605 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14606 (pop regexps-in-match)
14607 return-match t t))
14608 (cl-decf count))
14609 (if single-as-list
14610 (if tags-in-group tags-in-group (list return-match))
14611 return-match))
14612 (if single-as-list
14613 (list (if downcased (downcase match) match))
14614 match)))
14616 (defun org-op-to-function (op &optional stringp)
14617 "Turn an operator into the appropriate function."
14618 (setq op
14619 (cond
14620 ((equal op "<" ) '(< string< org-time<))
14621 ((equal op ">" ) '(> org-string> org-time>))
14622 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14623 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14624 ((member op '("=" "==")) '(= string= org-time=))
14625 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14626 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14628 (defun org<> (a b) (not (= a b)))
14629 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14630 (defun org-string>= (a b) (not (string< a b)))
14631 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14632 (defun org-string<> (a b) (not (string= a b)))
14633 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14634 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14635 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14636 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14637 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14638 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14639 (defun org-2ft (s)
14640 "Convert S to a floating point time.
14641 If S is already a number, just return it. If it is a string, parse
14642 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14643 (cond
14644 ((numberp s) s)
14645 ((stringp s)
14646 (condition-case nil
14647 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14648 (error 0.)))
14649 (t 0.)))
14651 (defun org-time-today ()
14652 "Time in seconds today at 0:00.
14653 Returns the float number of seconds since the beginning of the
14654 epoch to the beginning of today (00:00)."
14655 (float-time (apply 'encode-time
14656 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14658 (defun org-matcher-time (s)
14659 "Interpret a time comparison value."
14660 (save-match-data
14661 (cond
14662 ((string= s "<now>") (float-time))
14663 ((string= s "<today>") (org-time-today))
14664 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14665 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14666 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14667 (+ (org-time-today)
14668 (* (string-to-number (match-string 1 s))
14669 (cdr (assoc (match-string 2 s)
14670 '(("d" . 86400.0) ("w" . 604800.0)
14671 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14672 (t (org-2ft s)))))
14674 (defun org-match-any-p (re list)
14675 "Does re match any element of list?"
14676 (setq list (mapcar (lambda (x) (string-match re x)) list))
14677 (delq nil list))
14679 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14680 (defvar org-tags-overlay (make-overlay 1 1))
14681 (delete-overlay org-tags-overlay)
14683 (defun org-get-local-tags-at (&optional pos)
14684 "Get a list of tags defined in the current headline."
14685 (org-get-tags-at pos 'local))
14687 (defun org-get-local-tags ()
14688 "Get a list of tags defined in the current headline."
14689 (org-get-tags-at nil 'local))
14691 (defun org-get-tags-at (&optional pos local)
14692 "Get a list of all headline tags applicable at POS.
14693 POS defaults to point. If tags are inherited, the list contains
14694 the targets in the same sequence as the headlines appear, i.e.
14695 the tags of the current headline come last.
14696 When LOCAL is non-nil, only return tags from the current headline,
14697 ignore inherited ones."
14698 (interactive)
14699 (if (and org-trust-scanner-tags
14700 (or (not pos) (equal pos (point)))
14701 (not local))
14702 org-scanner-tags
14703 (let (tags ltags lastpos parent)
14704 (save-excursion
14705 (save-restriction
14706 (widen)
14707 (goto-char (or pos (point)))
14708 (save-match-data
14709 (catch 'done
14710 (condition-case nil
14711 (progn
14712 (org-back-to-heading t)
14713 (while (not (equal lastpos (point)))
14714 (setq lastpos (point))
14715 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14716 (setq ltags (org-split-string
14717 (match-string-no-properties 1) ":"))
14718 (when parent
14719 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14720 (setq tags (append
14721 (if parent
14722 (org-remove-uninherited-tags ltags)
14723 ltags)
14724 tags)))
14725 (or org-use-tag-inheritance (throw 'done t))
14726 (when local (throw 'done t))
14727 (or (org-up-heading-safe) (error nil))
14728 (setq parent t)))
14729 (error nil)))))
14730 (if local
14731 tags
14732 (reverse (delete-dups
14733 (reverse (append
14734 (org-remove-uninherited-tags
14735 org-file-tags)
14736 tags)))))))))
14738 (defun org-add-prop-inherited (s)
14739 (add-text-properties 0 (length s) '(inherited t) s)
14742 (defun org-toggle-tag (tag &optional onoff)
14743 "Toggle the tag TAG for the current line.
14744 If ONOFF is `on' or `off', don't toggle but set to this state."
14745 (save-excursion
14746 (org-back-to-heading t)
14747 (let ((current
14748 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14749 (line-end-position) t)
14750 (let ((tags (match-string 1)))
14751 ;; Clear current tags.
14752 (replace-match "")
14753 ;; Reverse the tags list so any new tag is appended to
14754 ;; the current list of tags.
14755 (nreverse (org-split-string tags ":")))))
14756 res)
14757 (pcase onoff
14758 (`off (setq current (delete tag current)))
14759 ((or `on (guard (not (member tag current))))
14760 (setq res t)
14761 (cl-pushnew tag current :test #'equal))
14762 (_ (setq current (delete tag current))))
14763 (end-of-line)
14764 (if current
14765 (progn
14766 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14767 (org-set-tags nil t))
14768 (delete-horizontal-space))
14769 (run-hooks 'org-after-tags-change-hook)
14770 res)))
14772 (defun org--align-tags-here (to-col)
14773 "Align tags on the current headline to TO-COL.
14774 Assume point is on a headline."
14775 (let ((pos (point)))
14776 (beginning-of-line)
14777 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14778 (>= pos (match-beginning 2)))
14779 ;; No tags or point within tags: do not align.
14780 (goto-char pos)
14781 (goto-char (match-beginning 1))
14782 (let ((shift (max (- (if (>= to-col 0) to-col
14783 (- (abs to-col) (string-width (match-string 2))))
14784 (current-column))
14785 1)))
14786 (replace-match (make-string shift ?\s) nil nil nil 1)
14787 ;; Preserve initial position, if possible. In any case, stop
14788 ;; before tags.
14789 (when (< pos (point)) (goto-char pos))))))
14791 (defun org-set-tags-command (&optional arg just-align)
14792 "Call the set-tags command for the current entry."
14793 (interactive "P")
14794 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14795 (org-set-tags arg just-align)
14796 (save-excursion
14797 (unless (and (org-region-active-p)
14798 org-loop-over-headlines-in-active-region)
14799 (org-back-to-heading t))
14800 (org-set-tags arg just-align))))
14802 (defun org-set-tags-to (data)
14803 "Set the tags of the current entry to DATA, replacing the current tags.
14804 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14805 If DATA is nil or the empty string, any tags will be removed."
14806 (interactive "sTags: ")
14807 (setq data
14808 (cond
14809 ((eq data nil) "")
14810 ((equal data "") "")
14811 ((stringp data)
14812 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14813 ":"))
14814 ((listp data)
14815 (concat ":" (mapconcat 'identity data ":") ":"))))
14816 (when data
14817 (save-excursion
14818 (org-back-to-heading t)
14819 (when (let ((case-fold-search nil))
14820 (looking-at org-complex-heading-regexp))
14821 (if (match-end 5)
14822 (progn
14823 (goto-char (match-beginning 5))
14824 (insert data)
14825 (delete-region (point) (point-at-eol))
14826 (org-set-tags nil 'align))
14827 (goto-char (point-at-eol))
14828 (insert " " data)
14829 (org-set-tags nil 'align)))
14830 (beginning-of-line 1)
14831 (when (looking-at ".*?\\([ \t]+\\)$")
14832 (delete-region (match-beginning 1) (match-end 1))))))
14834 (defun org-align-all-tags ()
14835 "Align the tags in all headings."
14836 (interactive)
14837 (save-excursion
14838 (or (ignore-errors (org-back-to-heading t))
14839 (outline-next-heading))
14840 (if (org-at-heading-p)
14841 (org-set-tags t)
14842 (message "No headings"))))
14844 (defvar org-indent-indentation-per-level)
14845 (defun org-set-tags (&optional arg just-align)
14846 "Set the tags for the current headline.
14847 With prefix ARG, realign all tags in headings in the current buffer.
14848 When JUST-ALIGN is non-nil, only align tags."
14849 (interactive "P")
14850 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14851 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14852 'region-start-level
14853 'region))
14854 org-loop-over-headlines-in-active-region)
14855 (org-map-entries
14856 ;; We don't use ARG and JUST-ALIGN here because these args
14857 ;; are not useful when looping over headlines.
14858 #'org-set-tags
14859 org-loop-over-headlines-in-active-region
14861 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14862 (let ((org-setting-tags t))
14863 (if arg
14864 (save-excursion
14865 (goto-char (point-min))
14866 (while (re-search-forward org-outline-regexp-bol nil t)
14867 (org-set-tags nil t)
14868 (end-of-line))
14869 (message "All tags realigned to column %d" org-tags-column))
14870 (let* ((current (org-get-tags-string))
14871 (tags
14872 (if just-align current
14873 ;; Get a new set of tags from the user.
14874 (save-excursion
14875 (let* ((seen)
14876 (table
14877 (setq
14878 org-last-tags-completion-table
14879 ;; Uniquify tags in alists, yet preserve
14880 ;; structure (i.e., keywords).
14881 (delq nil
14882 (mapcar
14883 (lambda (pair)
14884 (let ((head (car pair)))
14885 (cond ((symbolp head) pair)
14886 ((member head seen) nil)
14887 (t (push head seen)
14888 pair))))
14889 (append
14890 (or org-current-tag-alist
14891 (org-get-buffer-tags))
14892 (and
14893 org-complete-tags-always-offer-all-agenda-tags
14894 (org-global-tags-completion-table
14895 (org-agenda-files))))))))
14896 (current-tags (org-split-string current ":"))
14897 (inherited-tags
14898 (nreverse (nthcdr (length current-tags)
14899 (nreverse (org-get-tags-at))))))
14900 (replace-regexp-in-string
14901 "\\([-+&]+\\|,\\)"
14903 (if (or (eq t org-use-fast-tag-selection)
14904 (and org-use-fast-tag-selection
14905 (delq nil (mapcar #'cdr table))))
14906 (org-fast-tag-selection
14907 current-tags inherited-tags table
14908 (and org-fast-tag-selection-include-todo
14909 org-todo-key-alist))
14910 (let ((org-add-colon-after-tag-completion
14911 (< 1 (length table))))
14912 (org-trim
14913 (completing-read
14914 "Tags: "
14915 #'org-tags-completion-function
14916 nil nil current 'org-tags-history))))))))))
14918 (when org-tags-sort-function
14919 (setq tags
14920 (mapconcat
14921 #'identity
14922 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14923 org-tags-sort-function)
14924 ":")))
14926 (if (or (string= ":" tags)
14927 (string= "::" tags))
14928 (setq tags ""))
14929 (if (not (org-string-nw-p tags)) (setq tags "")
14930 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14931 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14933 ;; Insert new tags at the correct column.
14934 (unless (equal current tags)
14935 (save-excursion
14936 (beginning-of-line)
14937 (let ((case-fold-search nil))
14938 (looking-at org-complex-heading-regexp))
14939 ;; Remove current tags, if any.
14940 (when (match-end 5) (replace-match "" nil nil nil 5))
14941 ;; Insert new tags, if any. Otherwise, remove trailing
14942 ;; white spaces.
14943 (end-of-line)
14944 (if (not (equal tags ""))
14945 ;; When text is being inserted on an invisible
14946 ;; region boundary, it can be inadvertently sucked
14947 ;; into invisibility.
14948 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14949 (skip-chars-backward " \t")
14950 (delete-region (point) (line-end-position)))))
14951 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14952 ;; is on.
14953 (unless (equal tags "")
14954 (let* ((level (save-excursion
14955 (beginning-of-line)
14956 (skip-chars-forward "\\*")))
14957 (offset (if (bound-and-true-p org-indent-mode)
14958 (* (1- org-indent-indentation-per-level)
14959 (1- level))
14961 (tags-column
14962 (+ org-tags-column
14963 (if (> org-tags-column 0) (- offset) offset))))
14964 (org--align-tags-here tags-column))))
14965 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14967 (defun org-change-tag-in-region (beg end tag off)
14968 "Add or remove TAG for each entry in the region.
14969 This works in the agenda, and also in an Org buffer."
14970 (interactive
14971 (list (region-beginning) (region-end)
14972 (let ((org-last-tags-completion-table
14973 (if (derived-mode-p 'org-mode)
14974 (org-uniquify
14975 (delq nil (append (org-get-buffer-tags)
14976 (org-global-tags-completion-table))))
14977 (org-global-tags-completion-table))))
14978 (completing-read
14979 "Tag: " 'org-tags-completion-function nil nil nil
14980 'org-tags-history))
14981 (progn
14982 (message "[s]et or [r]emove? ")
14983 (equal (read-char-exclusive) ?r))))
14984 (when (fboundp 'deactivate-mark) (deactivate-mark))
14985 (let ((agendap (equal major-mode 'org-agenda-mode))
14986 l1 l2 m buf pos newhead (cnt 0))
14987 (goto-char end)
14988 (setq l2 (1- (org-current-line)))
14989 (goto-char beg)
14990 (setq l1 (org-current-line))
14991 (cl-loop for l from l1 to l2 do
14992 (org-goto-line l)
14993 (setq m (get-text-property (point) 'org-hd-marker))
14994 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14995 (and agendap m))
14996 (setq buf (if agendap (marker-buffer m) (current-buffer))
14997 pos (if agendap m (point)))
14998 (with-current-buffer buf
14999 (save-excursion
15000 (save-restriction
15001 (goto-char pos)
15002 (setq cnt (1+ cnt))
15003 (org-toggle-tag tag (if off 'off 'on))
15004 (setq newhead (org-get-heading)))))
15005 (and agendap (org-agenda-change-all-lines newhead m))))
15006 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15008 (defun org-tags-completion-function (string _predicate &optional flag)
15009 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15010 (confirm (lambda (x) (stringp (car x)))))
15011 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15012 (setq s1 (match-string 1 string)
15013 s2 (match-string 2 string))
15014 (setq s1 "" s2 string))
15015 (cond
15016 ((eq flag nil)
15017 ;; try completion
15018 (setq rtn (try-completion s2 ctable confirm))
15019 (when (stringp rtn)
15020 (setq rtn
15021 (concat s1 s2 (substring rtn (length s2))
15022 (if (and org-add-colon-after-tag-completion
15023 (assoc rtn ctable))
15024 ":" ""))))
15025 rtn)
15026 ((eq flag t)
15027 ;; all-completions
15028 (all-completions s2 ctable confirm))
15029 ((eq flag 'lambda)
15030 ;; exact match?
15031 (assoc s2 ctable)))))
15033 (defun org-fast-tag-insert (kwd tags face &optional end)
15034 "Insert KDW, and the TAGS, the latter with face FACE.
15035 Also insert END."
15036 (insert (format "%-12s" (concat kwd ":"))
15037 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15038 (or end "")))
15040 (defun org-fast-tag-show-exit (flag)
15041 (save-excursion
15042 (org-goto-line 3)
15043 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15044 (replace-match ""))
15045 (when flag
15046 (end-of-line 1)
15047 (org-move-to-column (- (window-width) 19) t)
15048 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15050 (defun org-set-current-tags-overlay (current prefix)
15051 "Add an overlay to CURRENT tag with PREFIX."
15052 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15053 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15054 (org-overlay-display org-tags-overlay (concat prefix s))))
15056 (defvar org-last-tag-selection-key nil)
15057 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15058 "Fast tag selection with single keys.
15059 CURRENT is the current list of tags in the headline, INHERITED is the
15060 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15061 possibly with grouping information. TODO-TABLE is a similar table with
15062 TODO keywords, should these have keys assigned to them.
15063 If the keys are nil, a-z are automatically assigned.
15064 Returns the new tags string, or nil to not change the current settings."
15065 (let* ((fulltable (append table todo-table))
15066 (maxlen (apply 'max (mapcar
15067 (lambda (x)
15068 (if (stringp (car x)) (string-width (car x)) 0))
15069 fulltable)))
15070 (buf (current-buffer))
15071 (expert (eq org-fast-tag-selection-single-key 'expert))
15072 (buffer-tags nil)
15073 (fwidth (+ maxlen 3 1 3))
15074 (ncol (/ (- (window-width) 4) fwidth))
15075 (i-face 'org-done)
15076 (c-face 'org-todo)
15077 tg cnt e c char c1 c2 ntable tbl rtn
15078 ov-start ov-end ov-prefix
15079 (exit-after-next org-fast-tag-selection-single-key)
15080 (done-keywords org-done-keywords)
15081 groups ingroup intaggroup)
15082 (save-excursion
15083 (beginning-of-line 1)
15084 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15085 (setq ov-start (match-beginning 1)
15086 ov-end (match-end 1)
15087 ov-prefix "")
15088 (setq ov-start (1- (point-at-eol))
15089 ov-end (1+ ov-start))
15090 (skip-chars-forward "^\n\r")
15091 (setq ov-prefix
15092 (concat
15093 (buffer-substring (1- (point)) (point))
15094 (if (> (current-column) org-tags-column)
15096 (make-string (- org-tags-column (current-column)) ?\ ))))))
15097 (move-overlay org-tags-overlay ov-start ov-end)
15098 (save-window-excursion
15099 (if expert
15100 (set-buffer (get-buffer-create " *Org tags*"))
15101 (delete-other-windows)
15102 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15103 (org-switch-to-buffer-other-window " *Org tags*"))
15104 (erase-buffer)
15105 (setq-local org-done-keywords done-keywords)
15106 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15107 (org-fast-tag-insert "Current" current c-face "\n\n")
15108 (org-fast-tag-show-exit exit-after-next)
15109 (org-set-current-tags-overlay current ov-prefix)
15110 (setq tbl fulltable char ?a cnt 0)
15111 (while (setq e (pop tbl))
15112 (cond
15113 ((eq (car e) :startgroup)
15114 (push '() groups) (setq ingroup t)
15115 (unless (zerop cnt)
15116 (setq cnt 0)
15117 (insert "\n"))
15118 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15119 ((eq (car e) :endgroup)
15120 (setq ingroup nil cnt 0)
15121 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15122 ((eq (car e) :startgrouptag)
15123 (setq intaggroup t)
15124 (unless (zerop cnt)
15125 (setq cnt 0)
15126 (insert "\n"))
15127 (insert "[ "))
15128 ((eq (car e) :endgrouptag)
15129 (setq intaggroup nil cnt 0)
15130 (insert "]\n"))
15131 ((equal e '(:newline))
15132 (unless (zerop cnt)
15133 (setq cnt 0)
15134 (insert "\n")
15135 (setq e (car tbl))
15136 (while (equal (car tbl) '(:newline))
15137 (insert "\n")
15138 (setq tbl (cdr tbl)))))
15139 ((equal e '(:grouptags)) (insert " : "))
15141 (setq tg (copy-sequence (car e)) c2 nil)
15142 (if (cdr e)
15143 (setq c (cdr e))
15144 ;; automatically assign a character.
15145 (setq c1 (string-to-char
15146 (downcase (substring
15147 tg (if (= (string-to-char tg) ?@) 1 0)))))
15148 (if (or (rassoc c1 ntable) (rassoc c1 table))
15149 (while (or (rassoc char ntable) (rassoc char table))
15150 (setq char (1+ char)))
15151 (setq c2 c1))
15152 (setq c (or c2 char)))
15153 (when ingroup (push tg (car groups)))
15154 (setq tg (org-add-props tg nil 'face
15155 (cond
15156 ((not (assoc tg table))
15157 (org-get-todo-face tg))
15158 ((member tg current) c-face)
15159 ((member tg inherited) i-face))))
15160 (when (equal (caar tbl) :grouptags)
15161 (org-add-props tg nil 'face 'org-tag-group))
15162 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15163 (insert "[" c "] " tg (make-string
15164 (- fwidth 4 (length tg)) ?\ ))
15165 (push (cons tg c) ntable)
15166 (when (= (cl-incf cnt) ncol)
15167 (insert "\n")
15168 (when (or ingroup intaggroup) (insert " "))
15169 (setq cnt 0)))))
15170 (setq ntable (nreverse ntable))
15171 (insert "\n")
15172 (goto-char (point-min))
15173 (unless expert (org-fit-window-to-buffer))
15174 (setq rtn
15175 (catch 'exit
15176 (while t
15177 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15178 (if (not groups) "no " "")
15179 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15180 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15181 (setq org-last-tag-selection-key c)
15182 (cond
15183 ((= c ?\r) (throw 'exit t))
15184 ((= c ?!)
15185 (setq groups (not groups))
15186 (goto-char (point-min))
15187 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15188 ((= c ?\C-c)
15189 (if (not expert)
15190 (org-fast-tag-show-exit
15191 (setq exit-after-next (not exit-after-next)))
15192 (setq expert nil)
15193 (delete-other-windows)
15194 (set-window-buffer (split-window-vertically) " *Org tags*")
15195 (org-switch-to-buffer-other-window " *Org tags*")
15196 (org-fit-window-to-buffer)))
15197 ((or (= c ?\C-g)
15198 (and (= c ?q) (not (rassoc c ntable))))
15199 (delete-overlay org-tags-overlay)
15200 (setq quit-flag t))
15201 ((= c ?\ )
15202 (setq current nil)
15203 (when exit-after-next (setq exit-after-next 'now)))
15204 ((= c ?\t)
15205 (condition-case nil
15206 (setq tg (completing-read
15207 "Tag: "
15208 (or buffer-tags
15209 (with-current-buffer buf
15210 (setq buffer-tags
15211 (org-get-buffer-tags))))))
15212 (quit (setq tg "")))
15213 (when (string-match "\\S-" tg)
15214 (cl-pushnew (list tg) buffer-tags :test #'equal)
15215 (if (member tg current)
15216 (setq current (delete tg current))
15217 (push tg current)))
15218 (when exit-after-next (setq exit-after-next 'now)))
15219 ((setq e (rassoc c todo-table) tg (car e))
15220 (with-current-buffer buf
15221 (save-excursion (org-todo tg)))
15222 (when exit-after-next (setq exit-after-next 'now)))
15223 ((setq e (rassoc c ntable) tg (car e))
15224 (if (member tg current)
15225 (setq current (delete tg current))
15226 (cl-loop for g in groups do
15227 (when (member tg g)
15228 (dolist (x g) (setq current (delete x current)))))
15229 (push tg current))
15230 (when exit-after-next (setq exit-after-next 'now))))
15232 ;; Create a sorted list
15233 (setq current
15234 (sort current
15235 (lambda (a b)
15236 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15237 (when (eq exit-after-next 'now) (throw 'exit t))
15238 (goto-char (point-min))
15239 (beginning-of-line 2)
15240 (delete-region (point) (point-at-eol))
15241 (org-fast-tag-insert "Current" current c-face)
15242 (org-set-current-tags-overlay current ov-prefix)
15243 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15244 (setq tg (match-string 1))
15245 (add-text-properties
15246 (match-beginning 1) (match-end 1)
15247 (list 'face
15248 (cond
15249 ((member tg current) c-face)
15250 ((member tg inherited) i-face)
15251 (t (get-text-property (match-beginning 1) 'face))))))
15252 (goto-char (point-min)))))
15253 (delete-overlay org-tags-overlay)
15254 (if rtn
15255 (mapconcat 'identity current ":")
15256 nil))))
15258 (defun org-get-tags-string ()
15259 "Get the TAGS string in the current headline."
15260 (unless (org-at-heading-p t)
15261 (user-error "Not on a heading"))
15262 (save-excursion
15263 (beginning-of-line 1)
15264 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15265 (match-string-no-properties 1)
15266 "")))
15268 (defun org-get-tags ()
15269 "Get the list of tags specified in the current headline."
15270 (org-split-string (org-get-tags-string) ":"))
15272 (defun org-get-buffer-tags ()
15273 "Get a table of all tags used in the buffer, for completion."
15274 (org-with-wide-buffer
15275 (goto-char (point-min))
15276 (let ((tag-re (concat org-outline-regexp-bol
15277 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15278 tags)
15279 (while (re-search-forward tag-re nil t)
15280 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15281 (push tag tags)))
15282 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15284 ;;;; The mapping API
15286 (defvar org-agenda-skip-comment-trees)
15287 (defvar org-agenda-skip-function)
15288 (defun org-map-entries (func &optional match scope &rest skip)
15289 "Call FUNC at each headline selected by MATCH in SCOPE.
15291 FUNC is a function or a lisp form. The function will be called without
15292 arguments, with the cursor positioned at the beginning of the headline.
15293 The return values of all calls to the function will be collected and
15294 returned as a list.
15296 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15297 does not need to preserve point. After evaluation, the cursor will be
15298 moved to the end of the line (presumably of the headline of the
15299 processed entry) and search continues from there. Under some
15300 circumstances, this may not produce the wanted results. For example,
15301 if you have removed (e.g. archived) the current (sub)tree it could
15302 mean that the next entry will be skipped entirely. In such cases, you
15303 can specify the position from where search should continue by making
15304 FUNC set the variable `org-map-continue-from' to the desired buffer
15305 position.
15307 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15308 Only headlines that are matched by this query will be considered during
15309 the iteration. When MATCH is nil or t, all headlines will be
15310 visited by the iteration.
15312 SCOPE determines the scope of this command. It can be any of:
15314 nil The current buffer, respecting the restriction if any
15315 tree The subtree started with the entry at point
15316 region The entries within the active region, if any
15317 region-start-level
15318 The entries within the active region, but only those at
15319 the same level than the first one.
15320 file The current buffer, without restriction
15321 file-with-archives
15322 The current buffer, and any archives associated with it
15323 agenda All agenda files
15324 agenda-with-archives
15325 All agenda files with any archive files associated with them
15326 \(file1 file2 ...)
15327 If this is a list, all files in the list will be scanned
15329 The remaining args are treated as settings for the skipping facilities of
15330 the scanner. The following items can be given here:
15332 archive skip trees with the archive tag
15333 comment skip trees with the COMMENT keyword
15334 function or Emacs Lisp form:
15335 will be used as value for `org-agenda-skip-function', so
15336 whenever the function returns a position, FUNC will not be
15337 called for that entry and search will continue from the
15338 position returned
15340 If your function needs to retrieve the tags including inherited tags
15341 at the *current* entry, you can use the value of the variable
15342 `org-scanner-tags' which will be much faster than getting the value
15343 with `org-get-tags-at'. If your function gets properties with
15344 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15345 to t around the call to `org-entry-properties' to get the same speedup.
15346 Note that if your function moves around to retrieve tags and properties at
15347 a *different* entry, you cannot use these techniques."
15348 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15349 (not (org-region-active-p)))
15350 (let* ((org-agenda-archives-mode nil) ; just to make sure
15351 (org-agenda-skip-archived-trees (memq 'archive skip))
15352 (org-agenda-skip-comment-trees (memq 'comment skip))
15353 (org-agenda-skip-function
15354 (car (org-delete-all '(comment archive) skip)))
15355 (org-tags-match-list-sublevels t)
15356 (start-level (eq scope 'region-start-level))
15357 matcher res
15358 org-todo-keywords-for-agenda
15359 org-done-keywords-for-agenda
15360 org-todo-keyword-alist-for-agenda
15361 org-tag-alist-for-agenda
15362 org--matcher-tags-todo-only)
15364 (cond
15365 ((eq match t) (setq matcher t))
15366 ((eq match nil) (setq matcher t))
15367 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15369 (save-excursion
15370 (save-restriction
15371 (cond ((eq scope 'tree)
15372 (org-back-to-heading t)
15373 (org-narrow-to-subtree)
15374 (setq scope nil))
15375 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15376 (org-region-active-p))
15377 ;; If needed, set start-level to a string like "2"
15378 (when start-level
15379 (save-excursion
15380 (goto-char (region-beginning))
15381 (unless (org-at-heading-p) (outline-next-heading))
15382 (setq start-level (org-current-level))))
15383 (narrow-to-region (region-beginning)
15384 (save-excursion
15385 (goto-char (region-end))
15386 (unless (and (bolp) (org-at-heading-p))
15387 (outline-next-heading))
15388 (point)))
15389 (setq scope nil)))
15391 (if (not scope)
15392 (progn
15393 (org-agenda-prepare-buffers
15394 (and buffer-file-name (list buffer-file-name)))
15395 (setq res
15396 (org-scan-tags
15397 func matcher org--matcher-tags-todo-only start-level)))
15398 ;; Get the right scope
15399 (cond
15400 ((and scope (listp scope) (symbolp (car scope)))
15401 (setq scope (eval scope)))
15402 ((eq scope 'agenda)
15403 (setq scope (org-agenda-files t)))
15404 ((eq scope 'agenda-with-archives)
15405 (setq scope (org-agenda-files t))
15406 (setq scope (org-add-archive-files scope)))
15407 ((eq scope 'file)
15408 (setq scope (and buffer-file-name (list buffer-file-name))))
15409 ((eq scope 'file-with-archives)
15410 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15411 (org-agenda-prepare-buffers scope)
15412 (dolist (file scope)
15413 (with-current-buffer (org-find-base-buffer-visiting file)
15414 (org-with-wide-buffer
15415 (goto-char (point-min))
15416 (setq res
15417 (append
15419 (org-scan-tags
15420 func matcher org--matcher-tags-todo-only)))))))))
15421 res)))
15423 ;;; Properties API
15425 (defconst org-special-properties
15426 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15427 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15428 "The special properties valid in Org mode.
15429 These are properties that are not defined in the property drawer,
15430 but in some other way.")
15432 (defconst org-default-properties
15433 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15434 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15435 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15436 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15437 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15438 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15439 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15440 "Some properties that are used by Org mode for various purposes.
15441 Being in this list makes sure that they are offered for completion.")
15443 (defun org--valid-property-p (property)
15444 "Non nil when string PROPERTY is a valid property name."
15445 (not
15446 (or (equal property "")
15447 (string-match-p "\\s-" property))))
15449 (defun org--update-property-plist (key val props)
15450 "Associate KEY to VAL in alist PROPS.
15451 Modifications are made by side-effect. Return new alist."
15452 (let* ((appending (string= (substring key -1) "+"))
15453 (key (if appending (substring key 0 -1) key))
15454 (old (assoc-string key props t)))
15455 (if (not old) (cons (cons key val) props)
15456 (setcdr old (if appending (concat (cdr old) " " val) val))
15457 props)))
15459 (defun org-get-property-block (&optional beg force)
15460 "Return the (beg . end) range of the body of the property drawer.
15461 BEG is the beginning of the current subtree, or of the part
15462 before the first headline. If it is not given, it will be found.
15463 If the drawer does not exist, create it if FORCE is non-nil, or
15464 return nil."
15465 (org-with-wide-buffer
15466 (when beg (goto-char beg))
15467 (unless (org-before-first-heading-p)
15468 (let ((beg (cond (beg)
15469 ((or (not (featurep 'org-inlinetask))
15470 (org-inlinetask-in-task-p))
15471 (org-back-to-heading t))
15472 (t (org-with-limited-levels (org-back-to-heading t))))))
15473 (forward-line)
15474 (when (looking-at-p org-planning-line-re) (forward-line))
15475 (cond ((looking-at org-property-drawer-re)
15476 (forward-line)
15477 (cons (point) (progn (goto-char (match-end 0))
15478 (line-beginning-position))))
15479 (force
15480 (goto-char beg)
15481 (org-insert-property-drawer)
15482 (let ((pos (save-excursion (search-forward ":END:")
15483 (line-beginning-position))))
15484 (cons pos pos))))))))
15486 (defun org-at-property-p ()
15487 "Non-nil when point is inside a property drawer.
15488 See `org-property-re' for match data, if applicable."
15489 (save-excursion
15490 (beginning-of-line)
15491 (and (looking-at org-property-re)
15492 (let ((property-drawer (save-match-data (org-get-property-block))))
15493 (and property-drawer
15494 (>= (point) (car property-drawer))
15495 (< (point) (cdr property-drawer)))))))
15497 (defun org-property-action ()
15498 "Do an action on properties."
15499 (interactive)
15500 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15501 (let ((c (read-char-exclusive)))
15502 (cl-case c
15503 (?s (call-interactively #'org-set-property))
15504 (?d (call-interactively #'org-delete-property))
15505 (?D (call-interactively #'org-delete-property-globally))
15506 (?c (call-interactively #'org-compute-property-at-point))
15507 (otherwise (user-error "No such property action %c" c)))))
15509 (defun org-inc-effort ()
15510 "Increment the value of the effort property in the current entry."
15511 (interactive)
15512 (org-set-effort nil t))
15514 (defvar org-clock-effort) ; Defined in org-clock.el.
15515 (defvar org-clock-current-task) ; Defined in org-clock.el.
15516 (defun org-set-effort (&optional value increment)
15517 "Set the effort property of the current entry.
15518 With numerical prefix arg, use the nth allowed value, 0 stands for the
15519 10th allowed value.
15521 When INCREMENT is non-nil, set the property to the next allowed value."
15522 (interactive "P")
15523 (when (equal value 0) (setq value 10))
15524 (let* ((completion-ignore-case t)
15525 (prop org-effort-property)
15526 (cur (org-entry-get nil prop))
15527 (allowed (org-property-get-allowed-values nil prop 'table))
15528 (existing (mapcar 'list (org-property-values prop)))
15529 (heading (nth 4 (org-heading-components)))
15531 (val (cond
15532 ((stringp value) value)
15533 ((and allowed (integerp value))
15534 (or (car (nth (1- value) allowed))
15535 (car (org-last allowed))))
15536 ((and allowed increment)
15537 (or (cl-caadr (member (list cur) allowed))
15538 (user-error "Allowed effort values are not set")))
15539 (allowed
15540 (message "Select 1-9,0, [RET%s]: %s"
15541 (if cur (concat "=" cur) "")
15542 (mapconcat 'car allowed " "))
15543 (setq rpl (read-char-exclusive))
15544 (if (equal rpl ?\r)
15546 (setq rpl (- rpl ?0))
15547 (when (equal rpl 0) (setq rpl 10))
15548 (if (and (> rpl 0) (<= rpl (length allowed)))
15549 (car (nth (1- rpl) allowed))
15550 (org-completing-read "Effort: " allowed nil))))
15552 (org-completing-read
15553 (concat "Effort" (and cur (string-match "\\S-" cur)
15554 (concat " [" cur "]"))
15555 ": ")
15556 existing nil nil "" nil cur)))))
15557 (unless (equal (org-entry-get nil prop) val)
15558 (org-entry-put nil prop val))
15559 (org-refresh-property
15560 '((effort . identity)
15561 (effort-minutes . org-duration-to-minutes))
15562 val)
15563 (when (equal heading (bound-and-true-p org-clock-current-task))
15564 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15565 (org-clock-update-mode-line))
15566 (message "%s is now %s" prop val)))
15568 (defun org-entry-properties (&optional pom which)
15569 "Get all properties of the current entry.
15571 When POM is a buffer position, get all properties from the entry
15572 there instead.
15574 This includes the TODO keyword, the tags, time strings for
15575 deadline, scheduled, and clocking, and any additional properties
15576 defined in the entry.
15578 If WHICH is nil or `all', get all properties. If WHICH is
15579 `special' or `standard', only get that subclass. If WHICH is
15580 a string, only get that property.
15582 Return value is an alist. Keys are properties, as upcased
15583 strings."
15584 (org-with-point-at pom
15585 (when (and (derived-mode-p 'org-mode)
15586 (ignore-errors (org-back-to-heading t)))
15587 (catch 'exit
15588 (let* ((beg (point))
15589 (specific (and (stringp which) (upcase which)))
15590 (which (cond ((not specific) which)
15591 ((member specific org-special-properties) 'special)
15592 (t 'standard)))
15593 props)
15594 ;; Get the special properties, like TODO and TAGS.
15595 (when (memq which '(nil all special))
15596 (when (or (not specific) (string= specific "CLOCKSUM"))
15597 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15598 (when clocksum
15599 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15600 props)))
15601 (when specific (throw 'exit props)))
15602 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15603 (let ((clocksumt (get-text-property (point)
15604 :org-clock-minutes-today)))
15605 (when clocksumt
15606 (push (cons "CLOCKSUM_T"
15607 (org-duration-from-minutes clocksumt))
15608 props)))
15609 (when specific (throw 'exit props)))
15610 (when (or (not specific) (string= specific "ITEM"))
15611 (let ((case-fold-search nil))
15612 (when (looking-at org-complex-heading-regexp)
15613 (push (cons "ITEM"
15614 (let ((title (match-string-no-properties 4)))
15615 (if (org-string-nw-p title)
15616 (org-remove-tabs title)
15617 "")))
15618 props)))
15619 (when specific (throw 'exit props)))
15620 (when (or (not specific) (string= specific "TODO"))
15621 (let ((case-fold-search nil))
15622 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15623 (push (cons "TODO" (match-string-no-properties 2)) props)))
15624 (when specific (throw 'exit props)))
15625 (when (or (not specific) (string= specific "PRIORITY"))
15626 (push (cons "PRIORITY"
15627 (if (looking-at org-priority-regexp)
15628 (match-string-no-properties 2)
15629 (char-to-string org-default-priority)))
15630 props)
15631 (when specific (throw 'exit props)))
15632 (when (or (not specific) (string= specific "FILE"))
15633 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15634 props)
15635 (when specific (throw 'exit props)))
15636 (when (or (not specific) (string= specific "TAGS"))
15637 (let ((value (org-string-nw-p (org-get-tags-string))))
15638 (when value (push (cons "TAGS" value) props)))
15639 (when specific (throw 'exit props)))
15640 (when (or (not specific) (string= specific "ALLTAGS"))
15641 (let ((value (org-get-tags-at)))
15642 (when value
15643 (push (cons "ALLTAGS"
15644 (format ":%s:" (mapconcat #'identity value ":")))
15645 props)))
15646 (when specific (throw 'exit props)))
15647 (when (or (not specific) (string= specific "BLOCKED"))
15648 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15649 (when specific (throw 'exit props)))
15650 (when (or (not specific)
15651 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15652 (forward-line)
15653 (when (looking-at-p org-planning-line-re)
15654 (end-of-line)
15655 (let ((bol (line-beginning-position))
15656 ;; Backward compatibility: time keywords used to
15657 ;; be configurable (before 8.3). Make sure we
15658 ;; get the correct keyword.
15659 (key-assoc `(("CLOSED" . ,org-closed-string)
15660 ("DEADLINE" . ,org-deadline-string)
15661 ("SCHEDULED" . ,org-scheduled-string))))
15662 (dolist (pair (if specific (list (assoc specific key-assoc))
15663 key-assoc))
15664 (save-excursion
15665 (when (search-backward (cdr pair) bol t)
15666 (goto-char (match-end 0))
15667 (skip-chars-forward " \t")
15668 (and (looking-at org-ts-regexp-both)
15669 (push (cons (car pair)
15670 (match-string-no-properties 0))
15671 props)))))))
15672 (when specific (throw 'exit props)))
15673 (when (or (not specific)
15674 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15675 (let ((find-ts
15676 (lambda (end ts)
15677 ;; Fix next time-stamp before END. TS is the
15678 ;; list of time-stamps found so far.
15679 (let ((ts ts)
15680 (regexp (cond
15681 ((string= specific "TIMESTAMP")
15682 org-ts-regexp)
15683 ((string= specific "TIMESTAMP_IA")
15684 org-ts-regexp-inactive)
15685 ((assoc "TIMESTAMP_IA" ts)
15686 org-ts-regexp)
15687 ((assoc "TIMESTAMP" ts)
15688 org-ts-regexp-inactive)
15689 (t org-ts-regexp-both))))
15690 (catch 'next
15691 (while (re-search-forward regexp end t)
15692 (backward-char)
15693 (let ((object (org-element-context)))
15694 ;; Accept to match timestamps in node
15695 ;; properties, too.
15696 (when (memq (org-element-type object)
15697 '(node-property timestamp))
15698 (let ((type
15699 (org-element-property :type object)))
15700 (cond
15701 ((and (memq type '(active active-range))
15702 (not (equal specific "TIMESTAMP_IA")))
15703 (unless (assoc "TIMESTAMP" ts)
15704 (push (cons "TIMESTAMP"
15705 (org-element-property
15706 :raw-value object))
15708 (when specific (throw 'exit ts))))
15709 ((and (memq type '(inactive inactive-range))
15710 (not (string= specific "TIMESTAMP")))
15711 (unless (assoc "TIMESTAMP_IA" ts)
15712 (push (cons "TIMESTAMP_IA"
15713 (org-element-property
15714 :raw-value object))
15716 (when specific (throw 'exit ts))))))
15717 ;; Both timestamp types are found,
15718 ;; move to next part.
15719 (when (= (length ts) 2) (throw 'next ts)))))
15720 ts)))))
15721 (goto-char beg)
15722 ;; First look for timestamps within headline.
15723 (let ((ts (funcall find-ts (line-end-position) nil)))
15724 (if (= (length ts) 2) (setq props (nconc ts props))
15725 ;; Then find timestamps in the section, skipping
15726 ;; planning line.
15727 (let ((end (save-excursion (outline-next-heading))))
15728 (forward-line)
15729 (when (looking-at-p org-planning-line-re) (forward-line))
15730 (setq props (nconc (funcall find-ts end ts) props))))))))
15731 ;; Get the standard properties, like :PROP:.
15732 (when (memq which '(nil all standard))
15733 ;; If we are looking after a specific property, delegate
15734 ;; to `org-entry-get', which is faster. However, make an
15735 ;; exception for "CATEGORY", since it can be also set
15736 ;; through keywords (i.e. #+CATEGORY).
15737 (if (and specific (not (equal specific "CATEGORY")))
15738 (let ((value (org-entry-get beg specific nil t)))
15739 (throw 'exit (and value (list (cons specific value)))))
15740 (let ((range (org-get-property-block beg)))
15741 (when range
15742 (let ((end (cdr range)) seen-base)
15743 (goto-char (car range))
15744 ;; Unlike to `org--update-property-plist', we
15745 ;; handle the case where base values is found
15746 ;; after its extension. We also forbid standard
15747 ;; properties to be named as special properties.
15748 (while (re-search-forward org-property-re end t)
15749 (let* ((key (upcase (match-string-no-properties 2)))
15750 (extendp (string-match-p "\\+\\'" key))
15751 (key-base (if extendp (substring key 0 -1) key))
15752 (value (match-string-no-properties 3)))
15753 (cond
15754 ((member-ignore-case key-base org-special-properties))
15755 (extendp
15756 (setq props
15757 (org--update-property-plist key value props)))
15758 ((member key seen-base))
15759 (t (push key seen-base)
15760 (let ((p (assoc-string key props t)))
15761 (if p (setcdr p (concat value " " (cdr p)))
15762 (push (cons key value) props))))))))))))
15763 (unless (assoc "CATEGORY" props)
15764 (push (cons "CATEGORY" (org-get-category beg)) props)
15765 (when (string= specific "CATEGORY") (throw 'exit props)))
15766 ;; Return value.
15767 props)))))
15769 (defun org--property-local-values (property literal-nil)
15770 "Return value for PROPERTY in current entry.
15771 Value is a list whose car is the base value for PROPERTY and cdr
15772 a list of accumulated values. Return nil if neither is found in
15773 the entry. Also return nil when PROPERTY is set to \"nil\",
15774 unless LITERAL-NIL is non-nil."
15775 (let ((range (org-get-property-block)))
15776 (when range
15777 (goto-char (car range))
15778 (let* ((case-fold-search t)
15779 (end (cdr range))
15780 (value
15781 ;; Base value.
15782 (save-excursion
15783 (let ((v (and (re-search-forward
15784 (org-re-property property nil t) end t)
15785 (match-string-no-properties 3))))
15786 (list (if literal-nil v (org-not-nil v)))))))
15787 ;; Find additional values.
15788 (let* ((property+ (org-re-property (concat property "+") nil t)))
15789 (while (re-search-forward property+ end t)
15790 (push (match-string-no-properties 3) value)))
15791 ;; Return final values.
15792 (and (not (equal value '(nil))) (nreverse value))))))
15794 (defun org--property-global-value (property literal-nil)
15795 "Return value for PROPERTY in current buffer.
15796 Return value is a string. Return nil if property is not set
15797 globally. Also return nil when PROPERTY is set to \"nil\",
15798 unless LITERAL-NIL is non-nil."
15799 (let ((global
15800 (cdr (or (assoc-string property org-file-properties t)
15801 (assoc-string property org-global-properties t)
15802 (assoc-string property org-global-properties-fixed t)))))
15803 (if literal-nil global (org-not-nil global))))
15805 (defun org-entry-get (pom property &optional inherit literal-nil)
15806 "Get value of PROPERTY for entry or content at point-or-marker POM.
15808 If INHERIT is non-nil and the entry does not have the property,
15809 then also check higher levels of the hierarchy. If INHERIT is
15810 the symbol `selective', use inheritance only if the setting in
15811 `org-use-property-inheritance' selects PROPERTY for inheritance.
15813 If the property is present but empty, the return value is the
15814 empty string. If the property is not present at all, nil is
15815 returned. In any other case, return the value as a string.
15816 Search is case-insensitive.
15818 If LITERAL-NIL is set, return the string value \"nil\" as
15819 a string, do not interpret it as the list atom nil. This is used
15820 for inheritance when a \"nil\" value can supersede a non-nil
15821 value higher up the hierarchy."
15822 (org-with-point-at pom
15823 (cond
15824 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15825 ;; We need a special property. Use `org-entry-properties' to
15826 ;; retrieve it, but specify the wanted property.
15827 (cdr (assoc-string property (org-entry-properties nil property))))
15828 ((and inherit
15829 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15830 (org-entry-get-with-inheritance property literal-nil))
15832 (let* ((local (org--property-local-values property literal-nil))
15833 (value (and local (mapconcat #'identity (delq nil local) " "))))
15834 (if literal-nil value (org-not-nil value)))))))
15836 (defun org-property-or-variable-value (var &optional inherit)
15837 "Check if there is a property fixing the value of VAR.
15838 If yes, return this value. If not, return the current value of the variable."
15839 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15840 (if (and prop (stringp prop) (string-match "\\S-" prop))
15841 (read prop)
15842 (symbol-value var))))
15844 (defun org-entry-delete (pom property)
15845 "Delete PROPERTY from entry at point-or-marker POM.
15846 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15847 non-nil when a property was removed."
15848 (org-with-point-at pom
15849 (pcase (org-get-property-block)
15850 (`(,begin . ,origin)
15851 (let* ((end (copy-marker origin))
15852 (re (org-re-property
15853 (concat (regexp-quote property) "\\+?") t t)))
15854 (goto-char begin)
15855 (while (re-search-forward re end t)
15856 (delete-region (match-beginning 0) (line-beginning-position 2)))
15857 ;; If drawer is empty, remove it altogether.
15858 (when (= begin end)
15859 (delete-region (line-beginning-position 0)
15860 (line-beginning-position 2)))
15861 ;; Return non-nil if some property was removed.
15862 (prog1 (/= end origin) (set-marker end nil))))
15863 (_ nil))))
15865 ;; Multi-values properties are properties that contain multiple values
15866 ;; These values are assumed to be single words, separated by whitespace.
15867 (defun org-entry-add-to-multivalued-property (pom property value)
15868 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15869 (let* ((old (org-entry-get pom property))
15870 (values (and old (org-split-string old "[ \t]"))))
15871 (setq value (org-entry-protect-space value))
15872 (unless (member value values)
15873 (setq values (append values (list value)))
15874 (org-entry-put pom property
15875 (mapconcat 'identity values " ")))))
15877 (defun org-entry-remove-from-multivalued-property (pom property value)
15878 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15879 (let* ((old (org-entry-get pom property))
15880 (values (and old (org-split-string old "[ \t]"))))
15881 (setq value (org-entry-protect-space value))
15882 (when (member value values)
15883 (setq values (delete value values))
15884 (org-entry-put pom property
15885 (mapconcat 'identity values " ")))))
15887 (defun org-entry-member-in-multivalued-property (pom property value)
15888 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15889 (let* ((old (org-entry-get pom property))
15890 (values (and old (org-split-string old "[ \t]"))))
15891 (setq value (org-entry-protect-space value))
15892 (member value values)))
15894 (defun org-entry-get-multivalued-property (pom property)
15895 "Return a list of values in a multivalued property."
15896 (let* ((value (org-entry-get pom property))
15897 (values (and value (org-split-string value "[ \t]"))))
15898 (mapcar 'org-entry-restore-space values)))
15900 (defun org-entry-put-multivalued-property (pom property &rest values)
15901 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15902 VALUES should be a list of strings. Spaces will be protected."
15903 (org-entry-put pom property
15904 (mapconcat 'org-entry-protect-space values " "))
15905 (let* ((value (org-entry-get pom property))
15906 (values (and value (org-split-string value "[ \t]"))))
15907 (mapcar 'org-entry-restore-space values)))
15909 (defun org-entry-protect-space (s)
15910 "Protect spaces and newline in string S."
15911 (while (string-match " " s)
15912 (setq s (replace-match "%20" t t s)))
15913 (while (string-match "\n" s)
15914 (setq s (replace-match "%0A" t t s)))
15917 (defun org-entry-restore-space (s)
15918 "Restore spaces and newline in string S."
15919 (while (string-match "%20" s)
15920 (setq s (replace-match " " t t s)))
15921 (while (string-match "%0A" s)
15922 (setq s (replace-match "\n" t t s)))
15925 (defvar org-entry-property-inherited-from (make-marker)
15926 "Marker pointing to the entry from where a property was inherited.
15927 Each call to `org-entry-get-with-inheritance' will set this marker to the
15928 location of the entry where the inheritance search matched. If there was
15929 no match, the marker will point nowhere.
15930 Note that also `org-entry-get' calls this function, if the INHERIT flag
15931 is set.")
15933 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15934 "Get PROPERTY of entry or content at point, search higher levels if needed.
15935 The search will stop at the first ancestor which has the property defined.
15936 If the value found is \"nil\", return nil to show that the property
15937 should be considered as undefined (this is the meaning of nil here).
15938 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15939 (move-marker org-entry-property-inherited-from nil)
15940 (org-with-wide-buffer
15941 (let (value)
15942 (catch 'exit
15943 (while t
15944 (let ((v (org--property-local-values property literal-nil)))
15945 (when v
15946 (setq value
15947 (concat (mapconcat #'identity (delq nil v) " ")
15948 (and value " ")
15949 value)))
15950 (cond
15951 ((car v)
15952 (org-back-to-heading t)
15953 (move-marker org-entry-property-inherited-from (point))
15954 (throw 'exit nil))
15955 ((org-up-heading-safe))
15957 (let ((global (org--property-global-value property literal-nil)))
15958 (cond ((not global))
15959 (value (setq value (concat global " " value)))
15960 (t (setq value global))))
15961 (throw 'exit nil))))))
15962 (if literal-nil value (org-not-nil value)))))
15964 (defvar org-property-changed-functions nil
15965 "Hook called when the value of a property has changed.
15966 Each hook function should accept two arguments, the name of the property
15967 and the new value.")
15969 (defun org-entry-put (pom property value)
15970 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15972 If the value is nil, it is converted to the empty string. If it
15973 is not a string, an error is raised. Also raise an error on
15974 invalid property names.
15976 PROPERTY can be any regular property (see
15977 `org-special-properties'). It can also be \"TODO\",
15978 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15980 For the last two properties, VALUE may have any of the special
15981 values \"earlier\" and \"later\". The function then increases or
15982 decreases scheduled or deadline date by one day."
15983 (cond ((null value) (setq value ""))
15984 ((not (stringp value)) (error "Properties values should be strings"))
15985 ((not (org--valid-property-p property))
15986 (user-error "Invalid property name: \"%s\"" property)))
15987 (org-with-point-at pom
15988 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15989 (org-back-to-heading t)
15990 (org-with-limited-levels (org-back-to-heading t)))
15991 (let ((beg (point)))
15992 (cond
15993 ((equal property "TODO")
15994 (cond ((not (org-string-nw-p value)) (setq value 'none))
15995 ((not (member value org-todo-keywords-1))
15996 (user-error "\"%s\" is not a valid TODO state" value)))
15997 (org-todo value)
15998 (org-set-tags nil 'align))
15999 ((equal property "PRIORITY")
16000 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16001 (org-set-tags nil 'align))
16002 ((equal property "SCHEDULED")
16003 (forward-line)
16004 (if (and (looking-at-p org-planning-line-re)
16005 (re-search-forward
16006 org-scheduled-time-regexp (line-end-position) t))
16007 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16008 ((string= value "later") (org-timestamp-change 1 'day))
16009 ((string= value "") (org-schedule '(4)))
16010 (t (org-schedule nil value)))
16011 (if (member value '("earlier" "later" ""))
16012 (call-interactively #'org-schedule)
16013 (org-schedule nil value))))
16014 ((equal property "DEADLINE")
16015 (forward-line)
16016 (if (and (looking-at-p org-planning-line-re)
16017 (re-search-forward
16018 org-deadline-time-regexp (line-end-position) t))
16019 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16020 ((string= value "later") (org-timestamp-change 1 'day))
16021 ((string= value "") (org-deadline '(4)))
16022 (t (org-deadline nil value)))
16023 (if (member value '("earlier" "later" ""))
16024 (call-interactively #'org-deadline)
16025 (org-deadline nil value))))
16026 ((member property org-special-properties)
16027 (error "The %s property cannot be set with `org-entry-put'" property))
16029 (let* ((range (org-get-property-block beg 'force))
16030 (end (cdr range))
16031 (case-fold-search t))
16032 (goto-char (car range))
16033 (if (re-search-forward (org-re-property property nil t) end t)
16034 (progn (delete-region (match-beginning 0) (match-end 0))
16035 (goto-char (match-beginning 0)))
16036 (goto-char end)
16037 (insert "\n")
16038 (backward-char))
16039 (insert ":" property ":")
16040 (when value (insert " " value))
16041 (org-indent-line)))))
16042 (run-hook-with-args 'org-property-changed-functions property value)))
16044 (defun org-buffer-property-keys
16045 (&optional specials defaults columns ignore-malformed)
16046 "Get all property keys in the current buffer.
16048 When SPECIALS is non-nil, also list the special properties that
16049 reflect things like tags and TODO state.
16051 When DEFAULTS is non-nil, also include properties that has
16052 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16053 DESCRIPTION, LOCATION, and LOGGING and others.
16055 When COLUMNS in non-nil, also include property names given in
16056 COLUMN formats in the current buffer.
16058 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16059 automatically performed, such drawers will be silently ignored."
16060 (let ((case-fold-search t)
16061 (props (append
16062 (and specials org-special-properties)
16063 (and defaults (cons org-effort-property org-default-properties))
16064 nil)))
16065 (org-with-wide-buffer
16066 (goto-char (point-min))
16067 (while (re-search-forward org-property-start-re nil t)
16068 (let ((range (org-get-property-block)))
16069 (catch 'skip
16070 (unless range
16071 (when (and (not ignore-malformed)
16072 (not (org-before-first-heading-p))
16073 (y-or-n-p (format "Malformed drawer at %d, repair?"
16074 (line-beginning-position))))
16075 (org-get-property-block nil t))
16076 (throw 'skip nil))
16077 (goto-char (car range))
16078 (let ((begin (car range))
16079 (end (cdr range)))
16080 ;; Make sure that found property block is not located
16081 ;; before current point, as it would generate an infloop.
16082 ;; It can happen, for example, in the following
16083 ;; situation:
16085 ;; * Headline
16086 ;; :PROPERTIES:
16087 ;; ...
16088 ;; :END:
16089 ;; *************** Inlinetask
16090 ;; #+BEGIN_EXAMPLE
16091 ;; :PROPERTIES:
16092 ;; #+END_EXAMPLE
16094 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16095 (while (< (point) end)
16096 (let ((p (progn (looking-at org-property-re)
16097 (match-string-no-properties 2))))
16098 ;; Only add true property name, not extension symbol.
16099 (push (if (not (string-match-p "\\+\\'" p)) p
16100 (substring p 0 -1))
16101 props))
16102 (forward-line))))
16103 (outline-next-heading)))
16104 (when columns
16105 (goto-char (point-min))
16106 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16107 (let ((element (org-element-at-point)))
16108 (when (memq (org-element-type element) '(keyword node-property))
16109 (let ((value (org-element-property :value element))
16110 (start 0))
16111 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16112 (setq start (match-end 0))
16113 (let ((p (match-string-no-properties 1 value)))
16114 (unless (member-ignore-case p org-special-properties)
16115 (push p props))))))))))
16116 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16118 (defun org-property-values (key)
16119 "List all non-nil values of property KEY in current buffer."
16120 (org-with-wide-buffer
16121 (goto-char (point-min))
16122 (let ((case-fold-search t)
16123 (re (org-re-property key))
16124 values)
16125 (while (re-search-forward re nil t)
16126 (push (org-entry-get (point) key) values))
16127 (delete-dups values))))
16129 (defun org-insert-property-drawer ()
16130 "Insert a property drawer into the current entry."
16131 (org-with-wide-buffer
16132 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16133 (org-back-to-heading t)
16134 (org-with-limited-levels (org-back-to-heading t)))
16135 (forward-line)
16136 (when (looking-at-p org-planning-line-re) (forward-line))
16137 (unless (looking-at-p org-property-drawer-re)
16138 ;; Make sure we start editing a line from current entry, not from
16139 ;; next one. It prevents extending text properties or overlays
16140 ;; belonging to the latter.
16141 (when (bolp) (backward-char))
16142 (let ((begin (1+ (point)))
16143 (inhibit-read-only t))
16144 (insert "\n:PROPERTIES:\n:END:")
16145 (when (eobp) (insert "\n"))
16146 (org-indent-region begin (point))))))
16148 (defun org-insert-drawer (&optional arg drawer)
16149 "Insert a drawer at point.
16151 When optional argument ARG is non-nil, insert a property drawer.
16153 Optional argument DRAWER, when non-nil, is a string representing
16154 drawer's name. Otherwise, the user is prompted for a name.
16156 If a region is active, insert the drawer around that region
16157 instead.
16159 Point is left between drawer's boundaries."
16160 (interactive "P")
16161 (let* ((drawer (if arg "PROPERTIES"
16162 (or drawer (read-from-minibuffer "Drawer: ")))))
16163 (cond
16164 ;; With C-u, fall back on `org-insert-property-drawer'
16165 (arg (org-insert-property-drawer))
16166 ;; Check validity of suggested drawer's name.
16167 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16168 (user-error "Invalid drawer name"))
16169 ;; With an active region, insert a drawer at point.
16170 ((not (org-region-active-p))
16171 (progn
16172 (unless (bolp) (insert "\n"))
16173 (insert (format ":%s:\n\n:END:\n" drawer))
16174 (forward-line -2)))
16175 ;; Otherwise, insert the drawer at point
16177 (let ((rbeg (region-beginning))
16178 (rend (copy-marker (region-end))))
16179 (unwind-protect
16180 (progn
16181 (goto-char rbeg)
16182 (beginning-of-line)
16183 (when (save-excursion
16184 (re-search-forward org-outline-regexp-bol rend t))
16185 (user-error "Drawers cannot contain headlines"))
16186 ;; Position point at the beginning of the first
16187 ;; non-blank line in region. Insert drawer's opening
16188 ;; there, then indent it.
16189 (org-skip-whitespace)
16190 (beginning-of-line)
16191 (insert ":" drawer ":\n")
16192 (forward-line -1)
16193 (indent-for-tab-command)
16194 ;; Move point to the beginning of the first blank line
16195 ;; after the last non-blank line in region. Insert
16196 ;; drawer's closing, then indent it.
16197 (goto-char rend)
16198 (skip-chars-backward " \r\t\n")
16199 (insert "\n:END:")
16200 (deactivate-mark t)
16201 (indent-for-tab-command)
16202 (unless (eolp) (insert "\n")))
16203 ;; Clear marker, whatever the outcome of insertion is.
16204 (set-marker rend nil)))))))
16206 (defvar org-property-set-functions-alist nil
16207 "Property set function alist.
16208 Each entry should have the following format:
16210 (PROPERTY . READ-FUNCTION)
16212 The read function will be called with the same argument as
16213 `org-completing-read'.")
16215 (defun org-set-property-function (property)
16216 "Get the function that should be used to set PROPERTY.
16217 This is computed according to `org-property-set-functions-alist'."
16218 (or (cdr (assoc property org-property-set-functions-alist))
16219 'org-completing-read))
16221 (defun org-read-property-value (property)
16222 "Read PROPERTY value from user."
16223 (let* ((completion-ignore-case t)
16224 (allowed (org-property-get-allowed-values nil property 'table))
16225 (cur (org-entry-get nil property))
16226 (prompt (concat property " value"
16227 (if (and cur (string-match "\\S-" cur))
16228 (concat " [" cur "]") "") ": "))
16229 (set-function (org-set-property-function property))
16230 (val (if allowed
16231 (funcall set-function prompt allowed nil
16232 (not (get-text-property 0 'org-unrestricted
16233 (caar allowed))))
16234 (funcall set-function prompt
16235 (mapcar 'list (org-property-values property))
16236 nil nil "" nil cur))))
16237 (org-trim val)))
16239 (defvar org-last-set-property nil)
16240 (defvar org-last-set-property-value nil)
16241 (defun org-read-property-name ()
16242 "Read a property name."
16243 (let ((completion-ignore-case t)
16244 (default-prop (or (and (org-at-property-p)
16245 (match-string-no-properties 2))
16246 org-last-set-property)))
16247 (org-completing-read
16248 (concat "Property"
16249 (if default-prop (concat " [" default-prop "]") "")
16250 ": ")
16251 (mapcar #'list (org-buffer-property-keys nil t t))
16252 nil nil nil nil default-prop)))
16254 (defun org-set-property-and-value (use-last)
16255 "Allow to set [PROPERTY]: [value] direction from prompt.
16256 When use-default, don't even ask, just use the last
16257 \"[PROPERTY]: [value]\" string from the history."
16258 (interactive "P")
16259 (let* ((completion-ignore-case t)
16260 (pv (or (and use-last org-last-set-property-value)
16261 (org-completing-read
16262 "Enter a \"[Property]: [value]\" pair: "
16263 nil nil nil nil nil
16264 org-last-set-property-value)))
16265 prop val)
16266 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16267 (setq prop (match-string 1 pv)
16268 val (match-string 2 pv))
16269 (org-set-property prop val))))
16271 (defun org-set-property (property value)
16272 "In the current entry, set PROPERTY to VALUE.
16274 When called interactively, this will prompt for a property name, offering
16275 completion on existing and default properties. And then it will prompt
16276 for a value, offering completion either on allowed values (via an inherited
16277 xxx_ALL property) or on existing values in other instances of this property
16278 in the current file.
16280 Throw an error when trying to set a property with an invalid name."
16281 (interactive (list nil nil))
16282 (let ((property (or property (org-read-property-name))))
16283 ;; `org-entry-put' also makes the following check, but this one
16284 ;; avoids polluting `org-last-set-property' and
16285 ;; `org-last-set-property-value' needlessly.
16286 (unless (org--valid-property-p property)
16287 (user-error "Invalid property name: \"%s\"" property))
16288 (let ((value (or value (org-read-property-value property)))
16289 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16290 (setq org-last-set-property property)
16291 (setq org-last-set-property-value (concat property ": " value))
16292 ;; Possibly postprocess the inserted value:
16293 (when fn (setq value (funcall fn value)))
16294 (unless (equal (org-entry-get nil property) value)
16295 (org-entry-put nil property value)))))
16297 (defun org-find-property (property &optional value)
16298 "Find first entry in buffer that sets PROPERTY.
16300 When optional argument VALUE is non-nil, only consider an entry
16301 if it contains PROPERTY set to this value. If PROPERTY should be
16302 explicitly set to nil, use string \"nil\" for VALUE.
16304 Return position where the entry begins, or nil if there is no
16305 such entry. If narrowing is in effect, only search the visible
16306 part of the buffer."
16307 (save-excursion
16308 (goto-char (point-min))
16309 (let ((case-fold-search t)
16310 (re (org-re-property property nil (not value) value)))
16311 (catch 'exit
16312 (while (re-search-forward re nil t)
16313 (when (if value (org-at-property-p)
16314 (org-entry-get (point) property nil t))
16315 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16317 (defun org-delete-property (property)
16318 "In the current entry, delete PROPERTY."
16319 (interactive
16320 (let* ((completion-ignore-case t)
16321 (cat (org-entry-get (point) "CATEGORY"))
16322 (props0 (org-entry-properties nil 'standard))
16323 (props (if cat props0
16324 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16325 (prop (if (< 1 (length props))
16326 (completing-read "Property: " props nil t)
16327 (caar props))))
16328 (list prop)))
16329 (if (not property)
16330 (message "No property to delete in this entry")
16331 (org-entry-delete nil property)
16332 (message "Property \"%s\" deleted" property)))
16334 (defun org-delete-property-globally (property)
16335 "Remove PROPERTY globally, from all entries.
16336 This function ignores narrowing, if any."
16337 (interactive
16338 (let* ((completion-ignore-case t)
16339 (prop (completing-read
16340 "Globally remove property: "
16341 (mapcar #'list (org-buffer-property-keys)))))
16342 (list prop)))
16343 (org-with-wide-buffer
16344 (goto-char (point-min))
16345 (let ((count 0)
16346 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16347 (while (re-search-forward re nil t)
16348 (when (org-entry-delete (point) property) (cl-incf count)))
16349 (message "Property \"%s\" removed from %d entries" property count))))
16351 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16353 (defun org-compute-property-at-point ()
16354 "Compute the property at point.
16355 This looks for an enclosing column format, extracts the operator and
16356 then applies it to the property in the column format's scope."
16357 (interactive)
16358 (unless (org-at-property-p)
16359 (user-error "Not at a property"))
16360 (let ((prop (match-string-no-properties 2)))
16361 (org-columns-get-format-and-top-level)
16362 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16363 (user-error "No operator defined for property %s" prop))
16364 (org-columns-compute prop)))
16366 (defvar org-property-allowed-value-functions nil
16367 "Hook for functions supplying allowed values for a specific property.
16368 The functions must take a single argument, the name of the property, and
16369 return a flat list of allowed values. If \":ETC\" is one of
16370 the values, this means that these values are intended as defaults for
16371 completion, but that other values should be allowed too.
16372 The functions must return nil if they are not responsible for this
16373 property.")
16375 (defun org-property-get-allowed-values (pom property &optional table)
16376 "Get allowed values for the property PROPERTY.
16377 When TABLE is non-nil, return an alist that can directly be used for
16378 completion."
16379 (let (vals)
16380 (cond
16381 ((equal property "TODO")
16382 (setq vals (org-with-point-at pom
16383 (append org-todo-keywords-1 '("")))))
16384 ((equal property "PRIORITY")
16385 (let ((n org-lowest-priority))
16386 (while (>= n org-highest-priority)
16387 (push (char-to-string n) vals)
16388 (setq n (1- n)))))
16389 ((equal property "CATEGORY"))
16390 ((member property org-special-properties))
16391 ((setq vals (run-hook-with-args-until-success
16392 'org-property-allowed-value-functions property)))
16394 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16395 (when (and vals (string-match "\\S-" vals))
16396 (setq vals (car (read-from-string (concat "(" vals ")"))))
16397 (setq vals (mapcar (lambda (x)
16398 (cond ((stringp x) x)
16399 ((numberp x) (number-to-string x))
16400 ((symbolp x) (symbol-name x))
16401 (t "???")))
16402 vals)))))
16403 (when (member ":ETC" vals)
16404 (setq vals (remove ":ETC" vals))
16405 (org-add-props (car vals) '(org-unrestricted t)))
16406 (if table (mapcar 'list vals) vals)))
16408 (defun org-property-previous-allowed-value (&optional _previous)
16409 "Switch to the next allowed value for this property."
16410 (interactive)
16411 (org-property-next-allowed-value t))
16413 (defun org-property-next-allowed-value (&optional previous)
16414 "Switch to the next allowed value for this property."
16415 (interactive)
16416 (unless (org-at-property-p)
16417 (user-error "Not at a property"))
16418 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16419 (key (match-string 2))
16420 (value (match-string 3))
16421 (allowed (or (org-property-get-allowed-values (point) key)
16422 (and (member value '("[ ]" "[-]" "[X]"))
16423 '("[ ]" "[X]"))))
16424 (heading (save-match-data (nth 4 (org-heading-components))))
16425 nval)
16426 (unless allowed
16427 (user-error "Allowed values for this property have not been defined"))
16428 (when previous (setq allowed (reverse allowed)))
16429 (when (member value allowed)
16430 (setq nval (car (cdr (member value allowed)))))
16431 (setq nval (or nval (car allowed)))
16432 (when (equal nval value)
16433 (user-error "Only one allowed value for this property"))
16434 (org-at-property-p)
16435 (replace-match (concat " :" key ": " nval) t t)
16436 (org-indent-line)
16437 (beginning-of-line 1)
16438 (skip-chars-forward " \t")
16439 (when (equal prop org-effort-property)
16440 (org-refresh-property
16441 '((effort . identity)
16442 (effort-minutes . org-duration-to-minutes))
16443 nval)
16444 (when (string= org-clock-current-task heading)
16445 (setq org-clock-effort nval)
16446 (org-clock-update-mode-line)))
16447 (run-hook-with-args 'org-property-changed-functions key nval)))
16449 (defun org-find-olp (path &optional this-buffer)
16450 "Return a marker pointing to the entry at outline path OLP.
16451 If anything goes wrong, throw an error.
16452 You can wrap this call to catch the error like this:
16454 (condition-case msg
16455 (org-mobile-locate-entry (match-string 4))
16456 (error (nth 1 msg)))
16458 The return value will then be either a string with the error message,
16459 or a marker if everything is OK.
16461 If THIS-BUFFER is set, the outline path does not contain a file,
16462 only headings."
16463 (let* ((file (if this-buffer buffer-file-name (pop path)))
16464 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16465 (level 1)
16466 (lmin 1)
16467 (lmax 1)
16468 end found flevel)
16469 (unless buffer (error "File not found :%s" file))
16470 (with-current-buffer buffer
16471 (unless (derived-mode-p 'org-mode)
16472 (error "Buffer %s needs to be in Org mode" buffer))
16473 (org-with-wide-buffer
16474 (goto-char (point-min))
16475 (dolist (heading path)
16476 (let ((re (format org-complex-heading-regexp-format
16477 (regexp-quote heading)))
16478 (cnt 0))
16479 (while (re-search-forward re end t)
16480 (setq level (- (match-end 1) (match-beginning 1)))
16481 (when (and (>= level lmin) (<= level lmax))
16482 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16483 (when (= cnt 0)
16484 (error "Heading not found on level %d: %s" lmax heading))
16485 (when (> cnt 1)
16486 (error "Heading not unique on level %d: %s" lmax heading))
16487 (goto-char found)
16488 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16489 (setq end (save-excursion (org-end-of-subtree t t)))))
16490 (when (org-at-heading-p)
16491 (point-marker))))))
16493 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16494 "Find node HEADING in BUFFER.
16495 Return a marker to the heading if it was found, or nil if not.
16496 If POS-ONLY is set, return just the position instead of a marker.
16498 The heading text must match exact, but it may have a TODO keyword,
16499 a priority cookie and tags in the standard locations."
16500 (with-current-buffer (or buffer (current-buffer))
16501 (org-with-wide-buffer
16502 (goto-char (point-min))
16503 (let (case-fold-search)
16504 (when (re-search-forward
16505 (format org-complex-heading-regexp-format
16506 (regexp-quote heading)) nil t)
16507 (if pos-only
16508 (match-beginning 0)
16509 (move-marker (make-marker) (match-beginning 0))))))))
16511 (defun org-find-exact-heading-in-directory (heading &optional dir)
16512 "Find Org node headline HEADING in all .org files in directory DIR.
16513 When the target headline is found, return a marker to this location."
16514 (let ((files (directory-files (or dir default-directory)
16515 t "\\`[^.#].*\\.org\\'"))
16516 visiting m buffer)
16517 (catch 'found
16518 (dolist (file files)
16519 (message "trying %s" file)
16520 (setq visiting (org-find-base-buffer-visiting file))
16521 (setq buffer (or visiting (find-file-noselect file)))
16522 (setq m (org-find-exact-headline-in-buffer
16523 heading buffer))
16524 (when (and (not m) (not visiting)) (kill-buffer buffer))
16525 (and m (throw 'found m))))))
16527 (defun org-find-entry-with-id (ident)
16528 "Locate the entry that contains the ID property with exact value IDENT.
16529 IDENT can be a string, a symbol or a number, this function will search for
16530 the string representation of it.
16531 Return the position where this entry starts, or nil if there is no such entry."
16532 (interactive "sID: ")
16533 (let ((id (cond
16534 ((stringp ident) ident)
16535 ((symbolp ident) (symbol-name ident))
16536 ((numberp ident) (number-to-string ident))
16537 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16538 (org-with-wide-buffer (org-find-property "ID" id))))
16540 ;;;; Timestamps
16542 (defvar org-last-changed-timestamp nil)
16543 (defvar org-last-inserted-timestamp nil
16544 "The last time stamp inserted with `org-insert-time-stamp'.")
16546 (defun org-time-stamp (arg &optional inactive)
16547 "Prompt for a date/time and insert a time stamp.
16549 If the user specifies a time like HH:MM or if this command is
16550 called with at least one prefix argument, the time stamp contains
16551 the date and the time. Otherwise, only the date is included.
16553 All parts of a date not specified by the user are filled in from
16554 the timestamp at point, if any, or the current date/time
16555 otherwise.
16557 If there is already a timestamp at the cursor, it is replaced.
16559 With two universal prefix arguments, insert an active timestamp
16560 with the current time without prompting the user.
16562 When called from lisp, the timestamp is inactive if INACTIVE is
16563 non-nil."
16564 (interactive "P")
16565 (let* ((ts (cond
16566 ((org-at-date-range-p t)
16567 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16568 ((org-at-timestamp-p 'lax) (match-string 0))))
16569 ;; Default time is either the timestamp at point or today.
16570 ;; When entering a range, only the range start is considered.
16571 (default-time (if (not ts) (current-time)
16572 (apply #'encode-time (org-parse-time-string ts))))
16573 (default-input (and ts (org-get-compact-tod ts)))
16574 (repeater (and ts
16575 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16576 (match-string 0 ts)))
16577 org-time-was-given
16578 org-end-time-was-given
16579 (time
16580 (and (if (equal arg '(16)) (current-time)
16581 ;; Preserve `this-command' and `last-command'.
16582 (let ((this-command this-command)
16583 (last-command last-command))
16584 (org-read-date
16585 arg 'totime nil nil default-time default-input
16586 inactive))))))
16587 (cond
16588 ((and ts
16589 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16590 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16591 (insert "--")
16592 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16594 ;; Make sure we're on a timestamp. When in the middle of a date
16595 ;; range, move arbitrarily to range end.
16596 (unless (org-at-timestamp-p 'lax)
16597 (skip-chars-forward "-")
16598 (org-at-timestamp-p 'lax))
16599 (replace-match "")
16600 (setq org-last-changed-timestamp
16601 (org-insert-time-stamp
16602 time (or org-time-was-given arg)
16603 inactive nil nil (list org-end-time-was-given)))
16604 (when repeater
16605 (backward-char)
16606 (insert " " repeater)
16607 (setq org-last-changed-timestamp
16608 (concat (substring org-last-inserted-timestamp 0 -1)
16609 " " repeater ">")))
16610 (message "Timestamp updated"))
16611 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16612 (t (org-insert-time-stamp
16613 time (or org-time-was-given arg) inactive nil nil
16614 (list org-end-time-was-given))))))
16616 ;; FIXME: can we use this for something else, like computing time differences?
16617 (defun org-get-compact-tod (s)
16618 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16619 (let* ((t1 (match-string 1 s))
16620 (h1 (string-to-number (match-string 2 s)))
16621 (m1 (string-to-number (match-string 3 s)))
16622 (t2 (and (match-end 4) (match-string 5 s)))
16623 (h2 (and t2 (string-to-number (match-string 6 s))))
16624 (m2 (and t2 (string-to-number (match-string 7 s))))
16625 dh dm)
16626 (if (not t2)
16628 (setq dh (- h2 h1) dm (- m2 m1))
16629 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16630 (concat t1 "+" (number-to-string dh)
16631 (and (/= 0 dm) (format ":%02d" dm)))))))
16633 (defun org-time-stamp-inactive (&optional arg)
16634 "Insert an inactive time stamp.
16635 An inactive time stamp is enclosed in square brackets instead of angle
16636 brackets. It is inactive in the sense that it does not trigger agenda entries,
16637 does not link to the calendar and cannot be changed with the S-cursor keys.
16638 So these are more for recording a certain time/date."
16639 (interactive "P")
16640 (org-time-stamp arg 'inactive))
16642 (defvar org-date-ovl (make-overlay 1 1))
16643 (overlay-put org-date-ovl 'face 'org-date-selected)
16644 (delete-overlay org-date-ovl)
16646 (defvar org-ans1) ; dynamically scoped parameter
16647 (defvar org-ans2) ; dynamically scoped parameter
16649 (defvar org-plain-time-of-day-regexp) ; defined below
16651 (defvar org-overriding-default-time nil) ; dynamically scoped
16652 (defvar org-read-date-overlay nil)
16653 (defvar org-dcst nil) ; dynamically scoped
16654 (defvar org-read-date-history nil)
16655 (defvar org-read-date-final-answer nil)
16656 (defvar org-read-date-analyze-futurep nil)
16657 (defvar org-read-date-analyze-forced-year nil)
16658 (defvar org-read-date-inactive)
16660 (defvar org-read-date-minibuffer-local-map
16661 (let* ((map (make-sparse-keymap)))
16662 (set-keymap-parent map minibuffer-local-map)
16663 (org-defkey map (kbd ".")
16664 (lambda () (interactive)
16665 ;; Are we at the beginning of the prompt?
16666 (if (looking-back "^[^:]+: "
16667 (let ((inhibit-field-text-motion t))
16668 (line-beginning-position)))
16669 (org-eval-in-calendar '(calendar-goto-today))
16670 (insert "."))))
16671 (org-defkey map (kbd "C-.")
16672 (lambda () (interactive)
16673 (org-eval-in-calendar '(calendar-goto-today))))
16674 (org-defkey map [(meta shift left)]
16675 (lambda () (interactive)
16676 (org-eval-in-calendar '(calendar-backward-month 1))))
16677 (org-defkey map [(meta shift right)]
16678 (lambda () (interactive)
16679 (org-eval-in-calendar '(calendar-forward-month 1))))
16680 (org-defkey map [(meta shift up)]
16681 (lambda () (interactive)
16682 (org-eval-in-calendar '(calendar-backward-year 1))))
16683 (org-defkey map [(meta shift down)]
16684 (lambda () (interactive)
16685 (org-eval-in-calendar '(calendar-forward-year 1))))
16686 (org-defkey map [?\e (shift left)]
16687 (lambda () (interactive)
16688 (org-eval-in-calendar '(calendar-backward-month 1))))
16689 (org-defkey map [?\e (shift right)]
16690 (lambda () (interactive)
16691 (org-eval-in-calendar '(calendar-forward-month 1))))
16692 (org-defkey map [?\e (shift up)]
16693 (lambda () (interactive)
16694 (org-eval-in-calendar '(calendar-backward-year 1))))
16695 (org-defkey map [?\e (shift down)]
16696 (lambda () (interactive)
16697 (org-eval-in-calendar '(calendar-forward-year 1))))
16698 (org-defkey map [(shift up)]
16699 (lambda () (interactive)
16700 (org-eval-in-calendar '(calendar-backward-week 1))))
16701 (org-defkey map [(shift down)]
16702 (lambda () (interactive)
16703 (org-eval-in-calendar '(calendar-forward-week 1))))
16704 (org-defkey map [(shift left)]
16705 (lambda () (interactive)
16706 (org-eval-in-calendar '(calendar-backward-day 1))))
16707 (org-defkey map [(shift right)]
16708 (lambda () (interactive)
16709 (org-eval-in-calendar '(calendar-forward-day 1))))
16710 (org-defkey map "!"
16711 (lambda () (interactive)
16712 (org-eval-in-calendar '(diary-view-entries))
16713 (message "")))
16714 (org-defkey map ">"
16715 (lambda () (interactive)
16716 (org-eval-in-calendar '(calendar-scroll-left 1))))
16717 (org-defkey map "<"
16718 (lambda () (interactive)
16719 (org-eval-in-calendar '(calendar-scroll-right 1))))
16720 (org-defkey map "\C-v"
16721 (lambda () (interactive)
16722 (org-eval-in-calendar
16723 '(calendar-scroll-left-three-months 1))))
16724 (org-defkey map "\M-v"
16725 (lambda () (interactive)
16726 (org-eval-in-calendar
16727 '(calendar-scroll-right-three-months 1))))
16728 map)
16729 "Keymap for minibuffer commands when using `org-read-date'.")
16731 (defvar org-def)
16732 (defvar org-defdecode)
16733 (defvar org-with-time)
16735 (defvar calendar-setup) ; Dynamically scoped.
16736 (defun org-read-date (&optional with-time to-time from-string prompt
16737 default-time default-input inactive)
16738 "Read a date, possibly a time, and make things smooth for the user.
16739 The prompt will suggest to enter an ISO date, but you can also enter anything
16740 which will at least partially be understood by `parse-time-string'.
16741 Unrecognized parts of the date will default to the current day, month, year,
16742 hour and minute. If this command is called to replace a timestamp at point,
16743 or to enter the second timestamp of a range, the default time is taken
16744 from the existing stamp. Furthermore, the command prefers the future,
16745 so if you are giving a date where the year is not given, and the day-month
16746 combination is already past in the current year, it will assume you
16747 mean next year. For details, see the manual. A few examples:
16749 3-2-5 --> 2003-02-05
16750 feb 15 --> currentyear-02-15
16751 2/15 --> currentyear-02-15
16752 sep 12 9 --> 2009-09-12
16753 12:45 --> today 12:45
16754 22 sept 0:34 --> currentyear-09-22 0:34
16755 12 --> currentyear-currentmonth-12
16756 Fri --> nearest Friday after today
16757 -Tue --> last Tuesday
16758 etc.
16760 Furthermore you can specify a relative date by giving, as the *first* thing
16761 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16762 change in days weeks, months, years.
16763 With a single plus or minus, the date is relative to today. With a double
16764 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16765 +4d --> four days from today
16766 +4 --> same as above
16767 +2w --> two weeks from today
16768 ++5 --> five days from default date
16770 The function understands only English month and weekday abbreviations.
16772 While prompting, a calendar is popped up - you can also select the
16773 date with the mouse (button 1). The calendar shows a period of three
16774 months. To scroll it to other months, use the keys `>' and `<'.
16775 If you don't like the calendar, turn it off with
16776 (setq org-read-date-popup-calendar nil)
16778 With optional argument TO-TIME, the date will immediately be converted
16779 to an internal time.
16780 With an optional argument WITH-TIME, the prompt will suggest to
16781 also insert a time. Note that when WITH-TIME is not set, you can
16782 still enter a time, and this function will inform the calling routine
16783 about this change. The calling routine may then choose to change the
16784 format used to insert the time stamp into the buffer to include the time.
16785 With optional argument FROM-STRING, read from this string instead from
16786 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16787 the time/date that is used for everything that is not specified by the
16788 user."
16789 (require 'parse-time)
16790 (let* ((org-with-time with-time)
16791 (org-time-stamp-rounding-minutes
16792 (if (equal org-with-time '(16))
16793 '(0 0)
16794 org-time-stamp-rounding-minutes))
16795 (org-dcst org-display-custom-times)
16796 (ct (org-current-time))
16797 (org-def (or org-overriding-default-time default-time ct))
16798 (org-defdecode (decode-time org-def))
16799 (cur-frame (selected-frame))
16800 (mouse-autoselect-window nil) ; Don't let the mouse jump
16801 (calendar-setup
16802 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16803 (calendar-move-hook nil)
16804 (calendar-view-diary-initially-flag nil)
16805 (calendar-view-holidays-initially-flag nil)
16806 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16807 ;; Rationalize `org-def' and `org-defdecode', if required.
16808 (when (< (nth 2 org-defdecode) org-extend-today-until)
16809 (setf (nth 2 org-defdecode) -1)
16810 (setf (nth 1 org-defdecode) 59)
16811 (setq org-def (apply #'encode-time org-defdecode))
16812 (setq org-defdecode (decode-time org-def)))
16813 (let* ((timestr (format-time-string
16814 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16815 org-def))
16816 (prompt (concat (if prompt (concat prompt " ") "")
16817 (format "Date+time [%s]: " timestr))))
16818 (cond
16819 (from-string (setq ans from-string))
16820 (org-read-date-popup-calendar
16821 (save-excursion
16822 (save-window-excursion
16823 (calendar)
16824 (when (eq calendar-setup 'calendar-only)
16825 (setq cal-frame
16826 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16827 (select-frame cal-frame))
16828 (org-eval-in-calendar '(setq cursor-type nil) t)
16829 (unwind-protect
16830 (progn
16831 (calendar-forward-day (- (time-to-days org-def)
16832 (calendar-absolute-from-gregorian
16833 (calendar-current-date))))
16834 (org-eval-in-calendar nil t)
16835 (let* ((old-map (current-local-map))
16836 (map (copy-keymap calendar-mode-map))
16837 (minibuffer-local-map
16838 (copy-keymap org-read-date-minibuffer-local-map)))
16839 (org-defkey map (kbd "RET") 'org-calendar-select)
16840 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16841 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16842 (unwind-protect
16843 (progn
16844 (use-local-map map)
16845 (setq org-read-date-inactive inactive)
16846 (add-hook 'post-command-hook 'org-read-date-display)
16847 (setq org-ans0
16848 (read-string prompt
16849 default-input
16850 'org-read-date-history
16851 nil))
16852 ;; org-ans0: from prompt
16853 ;; org-ans1: from mouse click
16854 ;; org-ans2: from calendar motion
16855 (setq ans
16856 (concat org-ans0 " " (or org-ans1 org-ans2))))
16857 (remove-hook 'post-command-hook 'org-read-date-display)
16858 (use-local-map old-map)
16859 (when org-read-date-overlay
16860 (delete-overlay org-read-date-overlay)
16861 (setq org-read-date-overlay nil)))))
16862 (bury-buffer "*Calendar*")
16863 (when cal-frame
16864 (delete-frame cal-frame)
16865 (select-frame-set-input-focus cur-frame))))))
16867 (t ; Naked prompt only
16868 (unwind-protect
16869 (setq ans (read-string prompt default-input
16870 'org-read-date-history timestr))
16871 (when org-read-date-overlay
16872 (delete-overlay org-read-date-overlay)
16873 (setq org-read-date-overlay nil))))))
16875 (setq final (org-read-date-analyze ans org-def org-defdecode))
16877 (when org-read-date-analyze-forced-year
16878 (message "Year was forced into %s"
16879 (if org-read-date-force-compatible-dates
16880 "compatible range (1970-2037)"
16881 "range representable on this machine"))
16882 (ding))
16884 ;; One round trip to get rid of 34th of August and stuff like that....
16885 (setq final (decode-time (apply 'encode-time final)))
16887 (setq org-read-date-final-answer ans)
16889 (if to-time
16890 (apply 'encode-time final)
16891 (if (and (boundp 'org-time-was-given) org-time-was-given)
16892 (format "%04d-%02d-%02d %02d:%02d"
16893 (nth 5 final) (nth 4 final) (nth 3 final)
16894 (nth 2 final) (nth 1 final))
16895 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16897 (defun org-read-date-display ()
16898 "Display the current date prompt interpretation in the minibuffer."
16899 (when org-read-date-display-live
16900 (when org-read-date-overlay
16901 (delete-overlay org-read-date-overlay))
16902 (when (minibufferp (current-buffer))
16903 (save-excursion
16904 (end-of-line 1)
16905 (while (not (equal (buffer-substring
16906 (max (point-min) (- (point) 4)) (point))
16907 " "))
16908 (insert " ")))
16909 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16910 " " (or org-ans1 org-ans2)))
16911 (org-end-time-was-given nil)
16912 (f (org-read-date-analyze ans org-def org-defdecode))
16913 (fmts (if org-dcst
16914 org-time-stamp-custom-formats
16915 org-time-stamp-formats))
16916 (fmt (if (or org-with-time
16917 (and (boundp 'org-time-was-given) org-time-was-given))
16918 (cdr fmts)
16919 (car fmts)))
16920 (txt (format-time-string fmt (apply 'encode-time f)))
16921 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16922 (txt (concat "=> " txt)))
16923 (when (and org-end-time-was-given
16924 (string-match org-plain-time-of-day-regexp txt))
16925 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16926 org-end-time-was-given
16927 (substring txt (match-end 0)))))
16928 (when org-read-date-analyze-futurep
16929 (setq txt (concat txt " (=>F)")))
16930 (setq org-read-date-overlay
16931 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16932 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16934 (defun org-read-date-analyze (ans def defdecode)
16935 "Analyze the combined answer of the date prompt."
16936 ;; FIXME: cleanup and comment
16937 ;; Pass `current-time' result to `decode-time' (instead of calling
16938 ;; without arguments) so that only `current-time' has to be
16939 ;; overridden in tests.
16940 (let ((org-def def)
16941 (org-defdecode defdecode)
16942 (nowdecode (decode-time (current-time)))
16943 delta deltan deltaw deltadef year month day
16944 hour minute second wday pm h2 m2 tl wday1
16945 iso-year iso-weekday iso-week iso-date futurep kill-year)
16946 (setq org-read-date-analyze-futurep nil
16947 org-read-date-analyze-forced-year nil)
16948 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16949 (setq ans "+0"))
16951 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16952 (setq ans (replace-match "" t t ans)
16953 deltan (car delta)
16954 deltaw (nth 1 delta)
16955 deltadef (nth 2 delta)))
16957 ;; Check if there is an iso week date in there. If yes, store the
16958 ;; info and postpone interpreting it until the rest of the parsing
16959 ;; is done.
16960 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16961 (setq iso-year (when (match-end 1)
16962 (org-small-year-to-year
16963 (string-to-number (match-string 1 ans))))
16964 iso-weekday (when (match-end 3)
16965 (string-to-number (match-string 3 ans)))
16966 iso-week (string-to-number (match-string 2 ans)))
16967 (setq ans (replace-match "" t t ans)))
16969 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16970 (when (string-match
16971 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16972 (setq year (if (match-end 2)
16973 (string-to-number (match-string 2 ans))
16974 (progn (setq kill-year t)
16975 (string-to-number (format-time-string "%Y"))))
16976 month (string-to-number (match-string 3 ans))
16977 day (string-to-number (match-string 4 ans)))
16978 (setq year (org-small-year-to-year year))
16979 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16980 t nil ans)))
16982 ;; Help matching dotted european dates
16983 (when (string-match
16984 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16985 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16986 (setq kill-year t)
16987 (string-to-number (format-time-string "%Y")))
16988 day (string-to-number (match-string 1 ans))
16989 month (string-to-number (match-string 2 ans))
16990 ans (replace-match (format "%04d-%02d-%02d" year month day)
16991 t nil ans)))
16993 ;; Help matching american dates, like 5/30 or 5/30/7
16994 (when (string-match
16995 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16996 (setq year (if (match-end 4)
16997 (string-to-number (match-string 4 ans))
16998 (progn (setq kill-year t)
16999 (string-to-number (format-time-string "%Y"))))
17000 month (string-to-number (match-string 1 ans))
17001 day (string-to-number (match-string 2 ans)))
17002 (setq year (org-small-year-to-year year))
17003 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17004 t nil ans)))
17005 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17006 ;; If there is a time with am/pm, and *no* time without it, we convert
17007 ;; so that matching will be successful.
17008 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17009 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17010 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17011 (setq hour (string-to-number (match-string 1 ans))
17012 minute (if (match-end 3)
17013 (string-to-number (match-string 3 ans))
17015 pm (equal ?p
17016 (string-to-char (downcase (match-string 4 ans)))))
17017 (if (and (= hour 12) (not pm))
17018 (setq hour 0)
17019 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17020 (setq ans (replace-match (format "%02d:%02d" hour minute)
17021 t t ans))))
17023 ;; Check if a time range is given as a duration
17024 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17025 (setq hour (string-to-number (match-string 1 ans))
17026 h2 (+ hour (string-to-number (match-string 3 ans)))
17027 minute (string-to-number (match-string 2 ans))
17028 m2 (+ minute (if (match-end 5) (string-to-number
17029 (match-string 5 ans))0)))
17030 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17031 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17032 t t ans)))
17034 ;; Check if there is a time range
17035 (when (boundp 'org-end-time-was-given)
17036 (setq org-time-was-given nil)
17037 (when (and (string-match org-plain-time-of-day-regexp ans)
17038 (match-end 8))
17039 (setq org-end-time-was-given (match-string 8 ans))
17040 (setq ans (concat (substring ans 0 (match-beginning 7))
17041 (substring ans (match-end 7))))))
17043 (setq tl (parse-time-string ans)
17044 day (or (nth 3 tl) (nth 3 org-defdecode))
17045 month
17046 (cond ((nth 4 tl))
17047 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17048 ;; Day was specified. Make sure DAY+MONTH
17049 ;; combination happens in the future.
17050 ((nth 3 tl)
17051 (setq futurep t)
17052 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17053 (nth 4 nowdecode)))
17054 (t (nth 4 org-defdecode)))
17055 year
17056 (cond ((and (not kill-year) (nth 5 tl)))
17057 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17058 ;; Month was guessed in the future and is at least
17059 ;; equal to NOWDECODE's. Fix year accordingly.
17060 (futurep
17061 (if (or (> month (nth 4 nowdecode))
17062 (>= day (nth 3 nowdecode)))
17063 (nth 5 nowdecode)
17064 (1+ (nth 5 nowdecode))))
17065 ;; Month was specified. Make sure MONTH+YEAR
17066 ;; combination happens in the future.
17067 ((nth 4 tl)
17068 (setq futurep t)
17069 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17070 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17071 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17072 (t (nth 5 nowdecode))))
17073 (t (nth 5 org-defdecode)))
17074 hour (or (nth 2 tl) (nth 2 org-defdecode))
17075 minute (or (nth 1 tl) (nth 1 org-defdecode))
17076 second (or (nth 0 tl) 0)
17077 wday (nth 6 tl))
17079 (when (and (eq org-read-date-prefer-future 'time)
17080 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17081 (equal day (nth 3 nowdecode))
17082 (equal month (nth 4 nowdecode))
17083 (equal year (nth 5 nowdecode))
17084 (nth 2 tl)
17085 (or (< (nth 2 tl) (nth 2 nowdecode))
17086 (and (= (nth 2 tl) (nth 2 nowdecode))
17087 (nth 1 tl)
17088 (< (nth 1 tl) (nth 1 nowdecode)))))
17089 (setq day (1+ day)
17090 futurep t))
17092 ;; Special date definitions below
17093 (cond
17094 (iso-week
17095 ;; There was an iso week
17096 (require 'cal-iso)
17097 (setq futurep nil)
17098 (setq year (or iso-year year)
17099 day (or iso-weekday wday 1)
17100 wday nil ; to make sure that the trigger below does not match
17101 iso-date (calendar-gregorian-from-absolute
17102 (calendar-iso-to-absolute
17103 (list iso-week day year))))
17104 ; FIXME: Should we also push ISO weeks into the future?
17105 ; (when (and org-read-date-prefer-future
17106 ; (not iso-year)
17107 ; (< (calendar-absolute-from-gregorian iso-date)
17108 ; (time-to-days (current-time))))
17109 ; (setq year (1+ year)
17110 ; iso-date (calendar-gregorian-from-absolute
17111 ; (calendar-iso-to-absolute
17112 ; (list iso-week day year)))))
17113 (setq month (car iso-date)
17114 year (nth 2 iso-date)
17115 day (nth 1 iso-date)))
17116 (deltan
17117 (setq futurep nil)
17118 (unless deltadef
17119 ;; Pass `current-time' result to `decode-time' (instead of
17120 ;; calling without arguments) so that only `current-time' has
17121 ;; to be overridden in tests.
17122 (let ((now (decode-time (current-time))))
17123 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17124 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17125 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17126 ((equal deltaw "m") (setq month (+ month deltan)))
17127 ((equal deltaw "y") (setq year (+ year deltan)))))
17128 ((and wday (not (nth 3 tl)))
17129 ;; Weekday was given, but no day, so pick that day in the week
17130 ;; on or after the derived date.
17131 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17132 (unless (equal wday wday1)
17133 (setq day (+ day (% (- wday wday1 -7) 7))))))
17134 (when (and (boundp 'org-time-was-given)
17135 (nth 2 tl))
17136 (setq org-time-was-given t))
17137 (when (< year 100) (setq year (+ 2000 year)))
17138 ;; Check of the date is representable
17139 (if org-read-date-force-compatible-dates
17140 (progn
17141 (when (< year 1970)
17142 (setq year 1970 org-read-date-analyze-forced-year t))
17143 (when (> year 2037)
17144 (setq year 2037 org-read-date-analyze-forced-year t)))
17145 (condition-case nil
17146 (ignore (encode-time second minute hour day month year))
17147 (error
17148 (setq year (nth 5 org-defdecode))
17149 (setq org-read-date-analyze-forced-year t))))
17150 (setq org-read-date-analyze-futurep futurep)
17151 (list second minute hour day month year)))
17153 (defvar parse-time-weekdays)
17154 (defun org-read-date-get-relative (s today default)
17155 "Check string S for special relative date string.
17156 TODAY and DEFAULT are internal times, for today and for a default.
17157 Return shift list (N what def-flag)
17158 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17159 N is the number of WHATs to shift.
17160 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17161 the DEFAULT date rather than TODAY."
17162 (require 'parse-time)
17163 (when (and
17164 (string-match
17165 (concat
17166 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17167 "\\([0-9]+\\)?"
17168 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17169 "\\([ \t]\\|$\\)") s)
17170 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17171 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17172 (string-to-char (substring (match-string 1 s) -1))
17173 ?+))
17174 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17175 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17176 (what (if (match-end 3) (match-string 3 s) "d"))
17177 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17178 (date (if rel default today))
17179 (wday (nth 6 (decode-time date)))
17180 delta)
17181 (if wday1
17182 (progn
17183 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17184 (when (= delta 0) (setq delta 7))
17185 (when (= dir ?-)
17186 (setq delta (- delta 7))
17187 (when (= delta 0) (setq delta -7)))
17188 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17189 (list delta "d" rel))
17190 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17192 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17193 "Turn a user-specified date into the internal representation.
17194 The internal representation needed by the calendar is (month day year).
17195 This is a wrapper to handle the brain-dead convention in calendar that
17196 user function argument order change dependent on argument order."
17197 (pcase calendar-date-style
17198 (`american (list arg1 arg2 arg3))
17199 (`european (list arg2 arg1 arg3))
17200 (`iso (list arg2 arg3 arg1))))
17202 (defun org-eval-in-calendar (form &optional keepdate)
17203 "Eval FORM in the calendar window and return to current window.
17204 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17205 (let ((sf (selected-frame))
17206 (sw (selected-window)))
17207 (select-window (get-buffer-window "*Calendar*" t))
17208 (eval form)
17209 (when (and (not keepdate) (calendar-cursor-to-date))
17210 (let* ((date (calendar-cursor-to-date))
17211 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17212 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17213 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17214 (select-window sw)
17215 (select-frame-set-input-focus sf)))
17217 (defun org-calendar-select ()
17218 "Return to `org-read-date' with the date currently selected.
17219 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17220 (interactive)
17221 (when (calendar-cursor-to-date)
17222 (let* ((date (calendar-cursor-to-date))
17223 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17224 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17225 (when (active-minibuffer-window) (exit-minibuffer))))
17227 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17228 "Insert a date stamp for the date given by the internal TIME.
17229 See `format-time-string' for the format of TIME.
17230 WITH-HM means use the stamp format that includes the time of the day.
17231 INACTIVE means use square brackets instead of angular ones, so that the
17232 stamp will not contribute to the agenda.
17233 PRE and POST are optional strings to be inserted before and after the
17234 stamp.
17235 The command returns the inserted time stamp."
17236 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17237 stamp)
17238 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17239 (insert-before-markers (or pre ""))
17240 (when (listp extra)
17241 (setq extra (car extra))
17242 (if (and (stringp extra)
17243 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17244 (setq extra (format "-%02d:%02d"
17245 (string-to-number (match-string 1 extra))
17246 (string-to-number (match-string 2 extra))))
17247 (setq extra nil)))
17248 (when extra
17249 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17250 (insert-before-markers (setq stamp (format-time-string fmt time)))
17251 (insert-before-markers (or post ""))
17252 (setq org-last-inserted-timestamp stamp)))
17254 (defun org-toggle-time-stamp-overlays ()
17255 "Toggle the use of custom time stamp formats."
17256 (interactive)
17257 (setq org-display-custom-times (not org-display-custom-times))
17258 (unless org-display-custom-times
17259 (let ((p (point-min)) (bmp (buffer-modified-p)))
17260 (while (setq p (next-single-property-change p 'display))
17261 (when (and (get-text-property p 'display)
17262 (eq (get-text-property p 'face) 'org-date))
17263 (remove-text-properties
17264 p (setq p (next-single-property-change p 'display))
17265 '(display t))))
17266 (set-buffer-modified-p bmp)))
17267 (org-restart-font-lock)
17268 (setq org-table-may-need-update t)
17269 (if org-display-custom-times
17270 (message "Time stamps are overlaid with custom format")
17271 (message "Time stamp overlays removed")))
17273 (defun org-display-custom-time (beg end)
17274 "Overlay modified time stamp format over timestamp between BEG and END."
17275 (let* ((ts (buffer-substring beg end))
17276 t1 with-hm tf time str (off 0))
17277 (save-match-data
17278 (setq t1 (org-parse-time-string ts t))
17279 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17280 (setq off (- (match-end 0) (match-beginning 0)))))
17281 (setq end (- end off))
17282 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17283 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17284 time (org-fix-decoded-time t1)
17285 str (org-add-props
17286 (format-time-string
17287 (substring tf 1 -1) (apply 'encode-time time))
17288 nil 'mouse-face 'highlight))
17289 (put-text-property beg end 'display str)))
17291 (defun org-fix-decoded-time (time)
17292 "Set 0 instead of nil for the first 6 elements of time.
17293 Don't touch the rest."
17294 (let ((n 0))
17295 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17297 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17298 "Difference between TIMESTAMP-STRING and now in days.
17299 If SECONDS is non-nil, return the difference in seconds."
17300 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17301 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17302 (funcall fdiff (current-time)))))
17304 (defun org-deadline-close-p (timestamp-string &optional ndays)
17305 "Is the time in TIMESTAMP-STRING close to the current date?"
17306 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17307 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17308 (not (org-entry-is-done-p))))
17310 (defun org-get-wdays (ts &optional delay zero-delay)
17311 "Get the deadline lead time appropriate for timestring TS.
17312 When DELAY is non-nil, get the delay time for scheduled items
17313 instead of the deadline lead time. When ZERO-DELAY is non-nil
17314 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17315 don't try to find the delay cookie in the scheduled timestamp."
17316 (let ((tv (if delay org-scheduled-delay-days
17317 org-deadline-warning-days)))
17318 (cond
17319 ((or (and delay (< tv 0))
17320 (and delay zero-delay (<= tv 0))
17321 (and (not delay) (<= tv 0)))
17322 ;; Enforce this value no matter what
17323 (- tv))
17324 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17325 ;; lead time is specified.
17326 (floor (* (string-to-number (match-string 1 ts))
17327 (cdr (assoc (match-string 2 ts)
17328 '(("d" . 1) ("w" . 7)
17329 ("m" . 30.4) ("y" . 365.25)
17330 ("h" . 0.041667)))))))
17331 ;; go for the default.
17332 (t tv))))
17334 (defun org-calendar-select-mouse (ev)
17335 "Return to `org-read-date' with the date currently selected.
17336 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17337 (interactive "e")
17338 (mouse-set-point ev)
17339 (when (calendar-cursor-to-date)
17340 (let* ((date (calendar-cursor-to-date))
17341 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17342 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17343 (when (active-minibuffer-window) (exit-minibuffer))))
17345 (defun org-check-deadlines (ndays)
17346 "Check if there are any deadlines due or past due.
17347 A deadline is considered due if it happens within `org-deadline-warning-days'
17348 days from today's date. If the deadline appears in an entry marked DONE,
17349 it is not shown. A numeric prefix argument NDAYS can be used to test that
17350 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17351 are shown."
17352 (interactive "P")
17353 (let* ((org-warn-days
17354 (cond
17355 ((equal ndays '(4)) 100000)
17356 (ndays (prefix-numeric-value ndays))
17357 (t (abs org-deadline-warning-days))))
17358 (case-fold-search nil)
17359 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17360 (callback
17361 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17362 (message "%d deadlines past-due or due within %d days"
17363 (org-occur regexp nil callback)
17364 org-warn-days)))
17366 (defsubst org-re-timestamp (type)
17367 "Return a regexp for timestamp TYPE.
17368 Allowed values for TYPE are:
17370 all: all timestamps
17371 active: only active timestamps (<...>)
17372 inactive: only inactive timestamps ([...])
17373 scheduled: only scheduled timestamps
17374 deadline: only deadline timestamps
17375 closed: only closed time-stamps
17377 When TYPE is nil, fall back on returning a regexp that matches
17378 both scheduled and deadline timestamps."
17379 (cl-case type
17380 (all org-ts-regexp-both)
17381 (active org-ts-regexp)
17382 (inactive org-ts-regexp-inactive)
17383 (scheduled org-scheduled-time-regexp)
17384 (deadline org-deadline-time-regexp)
17385 (closed org-closed-time-regexp)
17386 (otherwise
17387 (concat "\\<"
17388 (regexp-opt (list org-deadline-string org-scheduled-string))
17389 " *<\\([^>]+\\)>"))))
17391 (defun org-check-before-date (d)
17392 "Check if there are deadlines or scheduled entries before date D."
17393 (interactive (list (org-read-date)))
17394 (let* ((case-fold-search nil)
17395 (regexp (org-re-timestamp org-ts-type))
17396 (ts-type org-ts-type)
17397 (callback
17398 (lambda ()
17399 (let ((match (match-string 1)))
17400 (and (if (memq ts-type '(active inactive all))
17401 (eq (org-element-type (save-excursion
17402 (backward-char)
17403 (org-element-context)))
17404 'timestamp)
17405 (org-at-planning-p))
17406 (time-less-p
17407 (org-time-string-to-time match t)
17408 (org-time-string-to-time d t)))))))
17409 (message "%d entries before %s"
17410 (org-occur regexp nil callback)
17411 d)))
17413 (defun org-check-after-date (d)
17414 "Check if there are deadlines or scheduled entries after date D."
17415 (interactive (list (org-read-date)))
17416 (let* ((case-fold-search nil)
17417 (regexp (org-re-timestamp org-ts-type))
17418 (ts-type org-ts-type)
17419 (callback
17420 (lambda ()
17421 (let ((match (match-string 1)))
17422 (and (if (memq ts-type '(active inactive all))
17423 (eq (org-element-type (save-excursion
17424 (backward-char)
17425 (org-element-context)))
17426 'timestamp)
17427 (org-at-planning-p))
17428 (not (time-less-p
17429 (org-time-string-to-time match t)
17430 (org-time-string-to-time d t))))))))
17431 (message "%d entries after %s"
17432 (org-occur regexp nil callback)
17433 d)))
17435 (defun org-check-dates-range (start-date end-date)
17436 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17437 (interactive (list (org-read-date nil nil nil "Range starts")
17438 (org-read-date nil nil nil "Range end")))
17439 (let ((case-fold-search nil)
17440 (regexp (org-re-timestamp org-ts-type))
17441 (callback
17442 (let ((type org-ts-type))
17443 (lambda ()
17444 (let ((match (match-string 1)))
17445 (and
17446 (if (memq type '(active inactive all))
17447 (eq (org-element-type (save-excursion
17448 (backward-char)
17449 (org-element-context)))
17450 'timestamp)
17451 (org-at-planning-p))
17452 (not (time-less-p
17453 (org-time-string-to-time match t)
17454 (org-time-string-to-time start-date t)))
17455 (time-less-p
17456 (org-time-string-to-time match t)
17457 (org-time-string-to-time end-date t))))))))
17458 (message "%d entries between %s and %s"
17459 (org-occur regexp nil callback) start-date end-date)))
17461 (defun org-evaluate-time-range (&optional to-buffer)
17462 "Evaluate a time range by computing the difference between start and end.
17463 Normally the result is just printed in the echo area, but with prefix arg
17464 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17465 If the time range is actually in a table, the result is inserted into the
17466 next column.
17467 For time difference computation, a year is assumed to be exactly 365
17468 days in order to avoid rounding problems."
17469 (interactive "P")
17471 (org-clock-update-time-maybe)
17472 (save-excursion
17473 (unless (org-at-date-range-p t)
17474 (goto-char (point-at-bol))
17475 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17476 (unless (org-at-date-range-p t)
17477 (user-error "Not at a time-stamp range, and none found in current line")))
17478 (let* ((ts1 (match-string 1))
17479 (ts2 (match-string 2))
17480 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17481 (match-end (match-end 0))
17482 (time1 (org-time-string-to-time ts1))
17483 (time2 (org-time-string-to-time ts2))
17484 (t1 (float-time time1))
17485 (t2 (float-time time2))
17486 (diff (abs (- t2 t1)))
17487 (negative (< (- t2 t1) 0))
17488 ;; (ys (floor (* 365 24 60 60)))
17489 (ds (* 24 60 60))
17490 (hs (* 60 60))
17491 (fy "%dy %dd %02d:%02d")
17492 (fy1 "%dy %dd")
17493 (fd "%dd %02d:%02d")
17494 (fd1 "%dd")
17495 (fh "%02d:%02d")
17496 y d h m align)
17497 (if havetime
17498 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17500 d (floor (/ diff ds)) diff (mod diff ds)
17501 h (floor (/ diff hs)) diff (mod diff hs)
17502 m (floor (/ diff 60)))
17503 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17505 d (floor (+ (/ diff ds) 0.5))
17506 h 0 m 0))
17507 (if (not to-buffer)
17508 (message "%s" (org-make-tdiff-string y d h m))
17509 (if (org-at-table-p)
17510 (progn
17511 (goto-char match-end)
17512 (setq align t)
17513 (and (looking-at " *|") (goto-char (match-end 0))))
17514 (goto-char match-end))
17515 (when (looking-at
17516 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17517 (replace-match ""))
17518 (when negative (insert " -"))
17519 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17520 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17521 (insert " " (format fh h m))))
17522 (when align (org-table-align))
17523 (message "Time difference inserted")))))
17525 (defun org-make-tdiff-string (y d h m)
17526 (let ((fmt "")
17527 (l nil))
17528 (when (> y 0)
17529 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17530 (push y l))
17531 (when (> d 0)
17532 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17533 (push d l))
17534 (when (> h 0)
17535 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17536 (push h l))
17537 (when (> m 0)
17538 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17539 (push m l))
17540 (apply 'format fmt (nreverse l))))
17542 (defun org-time-string-to-time (s &optional zone)
17543 "Convert timestamp string S into internal time.
17544 The optional ZONE is omitted or nil for Emacs local time, t for
17545 Universal Time, ‘wall’ for system wall clock time, or a string as
17546 in the TZ environment variable."
17547 (apply #'encode-time (org-parse-time-string s nil zone)))
17549 (defun org-time-string-to-seconds (s &optional zone)
17550 "Convert a timestamp string S into a number of seconds.
17551 The optional ZONE is omitted or nil for Emacs local time, t for
17552 Universal Time, ‘wall’ for system wall clock time, or a string as
17553 in the TZ environment variable."
17554 (float-time (org-time-string-to-time s zone)))
17556 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17558 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17559 "Convert time stamp S to an absolute day number.
17561 If DAYNR in non-nil, and there is a specifier for a cyclic time
17562 stamp, get the closest date to DAYNR. If PREFER is
17563 `past' (respectively `future') return a date past (respectively
17564 after) or equal to DAYNR.
17566 POS is the location of time stamp S, as a buffer position in
17567 BUFFER.
17569 Diary sexp timestamps are matched against DAYNR, when non-nil.
17570 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17571 signaled."
17572 (cond
17573 ((string-match "\\`%%\\((.*)\\)" s)
17574 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17575 ;; only able to match individual dates. If it fails, raise an
17576 ;; error.
17577 (if (and daynr
17578 (org-diary-sexp-entry
17579 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17580 daynr
17581 (signal 'org-diary-sexp-no-match (list s))))
17582 (daynr (org-closest-date s daynr prefer))
17583 (t (time-to-days
17584 (condition-case errdata
17585 (apply #'encode-time (org-parse-time-string s))
17586 (error (error "Bad timestamp `%s'%s\nError was: %s"
17588 (if (not (and buffer pos)) ""
17589 (format-message " at %d in buffer `%s'" pos buffer))
17590 (cdr errdata))))))))
17592 (defun org-days-to-iso-week (days)
17593 "Return the iso week number."
17594 (require 'cal-iso)
17595 (car (calendar-iso-from-absolute days)))
17597 (defun org-small-year-to-year (year)
17598 "Convert 2-digit years into 4-digit years.
17599 YEAR is expanded into one of the 30 next years, if possible, or
17600 into a past one. Any year larger than 99 is returned unchanged."
17601 (if (>= year 100) year
17602 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17603 (century (/ current 100))
17604 (offset (- year (% current 100))))
17605 (cond ((> offset 30) (+ (* (1- century) 100) year))
17606 ((> offset -70) (+ (* century 100) year))
17607 (t (+ (* (1+ century) 100) year))))))
17609 (defun org-time-from-absolute (d)
17610 "Return the time corresponding to date D.
17611 D may be an absolute day number, or a calendar-type list (month day year)."
17612 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17613 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17615 (defvar org-agenda-current-date)
17616 (defun org-calendar-holiday ()
17617 "List of holidays, for Diary display in Org mode."
17618 (require 'holidays)
17619 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17620 (and hl (mapconcat #'identity hl "; "))))
17622 (defun org-diary-sexp-entry (sexp entry d)
17623 "Process a SEXP diary ENTRY for date D."
17624 (require 'diary-lib)
17625 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17626 ;; dynamically.
17627 (let* ((sexp `(let ((entry ,entry)
17628 (date ',d))
17629 ,(car (read-from-string sexp))))
17630 (result (if calendar-debug-sexp (eval sexp)
17631 (condition-case nil
17632 (eval sexp)
17633 (error
17634 (beep)
17635 (message "Bad sexp at line %d in %s: %s"
17636 (org-current-line)
17637 (buffer-file-name) sexp)
17638 (sleep-for 2))))))
17639 (cond ((stringp result) (split-string result "; "))
17640 ((and (consp result)
17641 (not (consp (cdr result)))
17642 (stringp (cdr result))) (cdr result))
17643 ((and (consp result)
17644 (stringp (car result))) result)
17645 (result entry))))
17647 (defun org-diary-to-ical-string (frombuf)
17648 "Get iCalendar entries from diary entries in buffer FROMBUF.
17649 This uses the icalendar.el library."
17650 (let* ((tmpdir temporary-file-directory)
17651 (tmpfile (make-temp-name
17652 (expand-file-name "orgics" tmpdir)))
17653 buf rtn b e)
17654 (with-current-buffer frombuf
17655 (icalendar-export-region (point-min) (point-max) tmpfile)
17656 (setq buf (find-buffer-visiting tmpfile))
17657 (set-buffer buf)
17658 (goto-char (point-min))
17659 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17660 (setq b (match-beginning 0)))
17661 (goto-char (point-max))
17662 (when (re-search-backward "^END:VEVENT" nil t)
17663 (setq e (match-end 0)))
17664 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17665 (kill-buffer buf)
17666 (delete-file tmpfile)
17667 rtn))
17669 (defun org-closest-date (start current prefer)
17670 "Return closest date to CURRENT starting from START.
17672 CURRENT and START are both time stamps.
17674 When PREFER is `past', return a date that is either CURRENT or
17675 past. When PREFER is `future', return a date that is either
17676 CURRENT or future.
17678 Only time stamps with a repeater are modified. Any other time
17679 stamp stay unchanged. In any case, return value is an absolute
17680 day number."
17681 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17682 ;; No repeater. Do not shift time stamp.
17683 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17684 (let ((value (string-to-number (match-string 1 start)))
17685 (type (match-string 2 start)))
17686 (if (= 0 value)
17687 ;; Repeater with a 0-value is considered as void.
17688 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17689 (let* ((base (org-date-to-gregorian start))
17690 (target (org-date-to-gregorian current))
17691 (sday (calendar-absolute-from-gregorian base))
17692 (cday (calendar-absolute-from-gregorian target))
17693 n1 n2)
17694 ;; If START is already past CURRENT, just return START.
17695 (if (<= cday sday) sday
17696 ;; Compute closest date before (N1) and closest date past
17697 ;; (N2) CURRENT.
17698 (pcase type
17699 ("h"
17700 (let ((missing-hours
17701 (mod (+ (- (* 24 (- cday sday))
17702 (nth 2 (org-parse-time-string start)))
17703 org-extend-today-until)
17704 value)))
17705 (setf n1 (if (= missing-hours 0) cday
17706 (- cday (1+ (/ missing-hours 24)))))
17707 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17708 ((or "d" "w")
17709 (let ((value (if (equal type "w") (* 7 value) value)))
17710 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17711 (setf n2 (+ n1 value))))
17712 ("m"
17713 (let* ((add-months
17714 (lambda (d n)
17715 ;; Add N months to gregorian date D, i.e.,
17716 ;; a list (MONTH DAY YEAR). Return a valid
17717 ;; gregorian date.
17718 (let ((m (+ (nth 0 d) n)))
17719 (list (mod m 12)
17720 (nth 1 d)
17721 (+ (/ m 12) (nth 2 d))))))
17722 (months ; Complete months to TARGET.
17723 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17724 (- (nth 0 target) (nth 0 base))
17725 ;; If START's day is greater than
17726 ;; TARGET's, remove incomplete month.
17727 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17728 value)
17729 value))
17730 (before (funcall add-months base months)))
17731 (setf n1 (calendar-absolute-from-gregorian before))
17732 (setf n2
17733 (calendar-absolute-from-gregorian
17734 (funcall add-months before value)))))
17736 (let* ((d (nth 1 base))
17737 (m (nth 0 base))
17738 (y (nth 2 base))
17739 (years ; Complete years to TARGET.
17740 (* (/ (- (nth 2 target)
17742 ;; If START's month and day are
17743 ;; greater than TARGET's, remove
17744 ;; incomplete year.
17745 (if (or (> (nth 0 target) m)
17746 (and (= (nth 0 target) m)
17747 (> (nth 1 target) d)))
17750 value)
17751 value))
17752 (before (list m d (+ y years))))
17753 (setf n1 (calendar-absolute-from-gregorian before))
17754 (setf n2 (calendar-absolute-from-gregorian
17755 (list m d (+ (nth 2 before) value)))))))
17756 ;; Handle PREFER parameter, if any.
17757 (cond
17758 ((eq prefer 'past) (if (= cday n2) n2 n1))
17759 ((eq prefer 'future) (if (= cday n1) n1 n2))
17760 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17762 (defun org-date-to-gregorian (d)
17763 "Turn any specification of date D into a Gregorian date for the calendar."
17764 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17765 ((and (listp d) (= (length d) 3)) d)
17766 ((stringp d)
17767 (let ((d (org-parse-time-string d)))
17768 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17769 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17771 (defun org-parse-time-string (s &optional nodefault zone)
17772 "Parse the standard Org time string.
17774 This should be a lot faster than the normal `parse-time-string'.
17776 If time is not given, defaults to 0:00. However, with optional
17777 NODEFAULT, hour and minute fields will be nil if not given.
17779 The optional ZONE is omitted or nil for Emacs local time, t for
17780 Universal Time, ‘wall’ for system wall clock time, or a string as
17781 in the TZ environment variable."
17782 (cond ((string-match org-ts-regexp0 s)
17783 (list 0
17784 (when (or (match-beginning 8) (not nodefault))
17785 (string-to-number (or (match-string 8 s) "0")))
17786 (when (or (match-beginning 7) (not nodefault))
17787 (string-to-number (or (match-string 7 s) "0")))
17788 (string-to-number (match-string 4 s))
17789 (string-to-number (match-string 3 s))
17790 (string-to-number (match-string 2 s))
17791 nil nil zone))
17792 ((string-match "^<[^>]+>$" s)
17793 ;; FIXME: `decode-time' needs to be called with ZONE as its
17794 ;; second argument. However, this requires at least Emacs
17795 ;; 25.1. We can do it when we switch to this version as our
17796 ;; minimal requirement.
17797 (decode-time (seconds-to-time (org-matcher-time s))))
17798 (t (error "Not a standard Org time string: %s" s))))
17800 (defun org-timestamp-up (&optional arg)
17801 "Increase the date item at the cursor by one.
17802 If the cursor is on the year, change the year. If it is on the month,
17803 the day or the time, change that.
17804 With prefix ARG, change by that many units."
17805 (interactive "p")
17806 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17808 (defun org-timestamp-down (&optional arg)
17809 "Decrease the date item at the cursor by one.
17810 If the cursor is on the year, change the year. If it is on the month,
17811 the day or the time, change that.
17812 With prefix ARG, change by that many units."
17813 (interactive "p")
17814 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17816 (defun org-timestamp-up-day (&optional arg)
17817 "Increase the date in the time stamp by one day.
17818 With prefix ARG, change that many days."
17819 (interactive "p")
17820 (if (and (not (org-at-timestamp-p 'lax))
17821 (org-at-heading-p))
17822 (org-todo 'up)
17823 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17825 (defun org-timestamp-down-day (&optional arg)
17826 "Decrease the date in the time stamp by one day.
17827 With prefix ARG, change that many days."
17828 (interactive "p")
17829 (if (and (not (org-at-timestamp-p 'lax))
17830 (org-at-heading-p))
17831 (org-todo 'down)
17832 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17834 (defun org-at-timestamp-p (&optional extended)
17835 "Non-nil if point is inside a timestamp.
17837 By default, the function only consider syntactically valid active
17838 timestamps. However, the caller may have a broader definition
17839 for timestamps. As a consequence, optional argument EXTENDED can
17840 be set to the following values
17842 `inactive'
17844 Include also syntactically valid inactive timestamps.
17846 `agenda'
17848 Include timestamps allowed in Agenda, i.e., those in
17849 properties drawers, planning lines and clock lines.
17851 `lax'
17853 Ignore context. The function matches any part of the
17854 document looking like a timestamp. This includes comments,
17855 example blocks...
17857 For backward-compatibility with Org 9.0, every other non-nil
17858 value is equivalent to `inactive'.
17860 When at a timestamp, return the position of the point as a symbol
17861 among `bracket', `after', `year', `month', `hour', `minute',
17862 `day' or a number of character from the last know part of the
17863 time stamp.
17865 When matching, the match groups are the following:
17866 group 1: year
17867 group 2: month
17868 group 3: day number
17869 group 4: day name
17870 group 5: hours, if any
17871 group 6: minutes, if any"
17872 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17873 (pos (point))
17874 (match?
17875 (let ((boundaries (org-in-regexp regexp)))
17876 (save-match-data
17877 (cond ((null boundaries) nil)
17878 ((eq extended 'lax) t)
17880 (or (and (eq extended 'agenda)
17881 (or (org-at-planning-p)
17882 (org-at-property-p)
17883 (and (bound-and-true-p
17884 org-agenda-include-inactive-timestamps)
17885 (org-at-clock-log-p))))
17886 (eq 'timestamp
17887 (save-excursion
17888 (when (= pos (cdr boundaries)) (forward-char -1))
17889 (org-element-type (org-element-context)))))))))))
17890 (cond
17891 ((not match?) nil)
17892 ((= pos (match-beginning 0)) 'bracket)
17893 ;; Distinguish location right before the closing bracket from
17894 ;; right after it.
17895 ((= pos (1- (match-end 0))) 'bracket)
17896 ((= pos (match-end 0)) 'after)
17897 ((org-pos-in-match-range pos 2) 'year)
17898 ((org-pos-in-match-range pos 3) 'month)
17899 ((org-pos-in-match-range pos 7) 'hour)
17900 ((org-pos-in-match-range pos 8) 'minute)
17901 ((or (org-pos-in-match-range pos 4)
17902 (org-pos-in-match-range pos 5)) 'day)
17903 ((and (> pos (or (match-end 8) (match-end 5)))
17904 (< pos (match-end 0)))
17905 (- pos (or (match-end 8) (match-end 5))))
17906 (t 'day))))
17908 (defun org-toggle-timestamp-type ()
17909 "Toggle the type (<active> or [inactive]) of a time stamp."
17910 (interactive)
17911 (when (org-at-timestamp-p 'lax)
17912 (let ((beg (match-beginning 0)) (end (match-end 0))
17913 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17914 (save-excursion
17915 (goto-char beg)
17916 (while (re-search-forward "[][<>]" end t)
17917 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17918 t t)))
17919 (message "Timestamp is now %sactive"
17920 (if (equal (char-after beg) ?<) "" "in")))))
17922 (defun org-at-clock-log-p ()
17923 "Non-nil if point is on a clock log line."
17924 (and (org-match-line org-clock-line-re)
17925 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17927 (defvar org-clock-history) ; defined in org-clock.el
17928 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17929 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17930 "Change the date in the time stamp at point.
17931 The date will be changed by N times WHAT. WHAT can be `day', `month',
17932 `year', `minute', `second'. If WHAT is not given, the cursor position
17933 in the timestamp determines what will be changed.
17934 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17935 (let ((origin (point))
17936 (timestamp? (org-at-timestamp-p 'lax))
17937 origin-cat
17938 with-hm inactive
17939 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17940 extra rem
17941 ts time time0 fixnext clrgx)
17942 (unless timestamp? (user-error "Not at a timestamp"))
17943 (if (and (not what) (eq timestamp? 'bracket))
17944 (org-toggle-timestamp-type)
17945 ;; Point isn't on brackets. Remember the part of the time-stamp
17946 ;; the point was in. Indeed, size of time-stamps may change,
17947 ;; but point must be kept in the same category nonetheless.
17948 (setq origin-cat timestamp?)
17949 (when (and (not what) (not (eq timestamp? 'day))
17950 org-display-custom-times
17951 (get-text-property (point) 'display)
17952 (not (get-text-property (1- (point)) 'display)))
17953 (setq timestamp? 'day))
17954 (setq timestamp? (or what timestamp?)
17955 inactive (= (char-after (match-beginning 0)) ?\[)
17956 ts (match-string 0))
17957 (replace-match "")
17958 (when (string-match
17959 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17961 (setq extra (match-string 1 ts))
17962 (when suppress-tmp-delay
17963 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17964 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17965 (setq with-hm t))
17966 (setq time0 (org-parse-time-string ts))
17967 (when (and updown
17968 (eq timestamp? 'minute)
17969 (not current-prefix-arg))
17970 ;; This looks like s-up and s-down. Change by one rounding step.
17971 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17972 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17973 (setcar (cdr time0) (+ (nth 1 time0)
17974 (if (> n 0) (- rem) (- dm rem))))))
17975 (setq time
17976 (apply #'encode-time
17977 (or (car time0) 0)
17978 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17979 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17980 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17981 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17982 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17983 (nthcdr 6 time0)))
17984 (when (and (memq timestamp? '(hour minute))
17985 extra
17986 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17987 (setq extra (org-modify-ts-extra
17988 extra
17989 (if (eq timestamp? 'hour) 2 5)
17990 n dm)))
17991 (when (integerp timestamp?)
17992 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17993 (when (eq what 'calendar)
17994 (let ((cal-date (org-get-date-from-calendar)))
17995 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17996 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17997 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17998 (setcar time0 (or (car time0) 0))
17999 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18000 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18001 (setq time (apply 'encode-time time0))))
18002 ;; Insert the new time-stamp, and ensure point stays in the same
18003 ;; category as before (i.e. not after the last position in that
18004 ;; category).
18005 (let ((pos (point)))
18006 ;; Stay before inserted string. `save-excursion' is of no use.
18007 (setq org-last-changed-timestamp
18008 (org-insert-time-stamp time with-hm inactive nil nil extra))
18009 (goto-char pos))
18010 (save-match-data
18011 (looking-at org-ts-regexp3)
18012 (goto-char
18013 (pcase origin-cat
18014 ;; `day' category ends before `hour' if any, or at the end
18015 ;; of the day name.
18016 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18017 (`hour (min (match-end 7) origin))
18018 (`minute (min (1- (match-end 8)) origin))
18019 ((pred integerp) (min (1- (match-end 0)) origin))
18020 ;; Point was right after the time-stamp. However, the
18021 ;; time-stamp length might have changed, so refer to
18022 ;; (match-end 0) instead.
18023 (`after (match-end 0))
18024 ;; `year' and `month' have both fixed size: point couldn't
18025 ;; have moved into another part.
18026 (_ origin))))
18027 ;; Update clock if on a CLOCK line.
18028 (org-clock-update-time-maybe)
18029 ;; Maybe adjust the closest clock in `org-clock-history'
18030 (when org-clock-adjust-closest
18031 (if (not (and (org-at-clock-log-p)
18032 (< 1 (length (delq nil (mapcar 'marker-position
18033 org-clock-history))))))
18034 (message "No clock to adjust")
18035 (cond ((save-excursion ; fix previous clock?
18036 (re-search-backward org-ts-regexp0 nil t)
18037 (looking-back (concat org-clock-string " \\[")
18038 (line-beginning-position)))
18039 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18040 ((save-excursion ; fix next clock?
18041 (re-search-backward org-ts-regexp0 nil t)
18042 (looking-at (concat org-ts-regexp0 "\\] =>")))
18043 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18044 (save-window-excursion
18045 ;; Find closest clock to point, adjust the previous/next one in history
18046 (let* ((p (save-excursion (org-back-to-heading t)))
18047 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18048 (clfixnth
18049 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18050 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18051 (if (not clfixpos)
18052 (message "No clock to adjust")
18053 (save-excursion
18054 (org-goto-marker-or-bmk clfixpos)
18055 (org-show-subtree)
18056 (when (re-search-forward clrgx nil t)
18057 (goto-char (match-beginning 1))
18058 (let (org-clock-adjust-closest)
18059 (org-timestamp-change n timestamp? updown))
18060 (message "Clock adjusted in %s for heading: %s"
18061 (file-name-nondirectory (buffer-file-name))
18062 (org-get-heading t t)))))))))
18063 ;; Try to recenter the calendar window, if any.
18064 (when (and org-calendar-follow-timestamp-change
18065 (get-buffer-window "*Calendar*" t)
18066 (memq timestamp? '(day month year)))
18067 (org-recenter-calendar (time-to-days time))))))
18069 (defun org-modify-ts-extra (s pos n dm)
18070 "Change the different parts of the lead-time and repeat fields in timestamp."
18071 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18072 ng h m new rem)
18073 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18074 (cond
18075 ((or (org-pos-in-match-range pos 2)
18076 (org-pos-in-match-range pos 3))
18077 (setq m (string-to-number (match-string 3 s))
18078 h (string-to-number (match-string 2 s)))
18079 (if (org-pos-in-match-range pos 2)
18080 (setq h (+ h n))
18081 (setq n (* dm (with-no-warnings (signum n))))
18082 (unless (= 0 (setq rem (% m dm)))
18083 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18084 (setq m (+ m n)))
18085 (when (< m 0) (setq m (+ m 60) h (1- h)))
18086 (when (> m 59) (setq m (- m 60) h (1+ h)))
18087 (setq h (mod h 24))
18088 (setq ng 1 new (format "-%02d:%02d" h m)))
18089 ((org-pos-in-match-range pos 6)
18090 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18091 ((org-pos-in-match-range pos 5)
18092 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18094 ((org-pos-in-match-range pos 9)
18095 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18096 ((org-pos-in-match-range pos 8)
18097 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18099 (when ng
18100 (setq s (concat
18101 (substring s 0 (match-beginning ng))
18103 (substring s (match-end ng))))))
18106 (defun org-recenter-calendar (d)
18107 "If the calendar is visible, recenter it to date D."
18108 (let ((cwin (get-buffer-window "*Calendar*" t)))
18109 (when cwin
18110 (let ((calendar-move-hook nil))
18111 (with-selected-window cwin
18112 (calendar-goto-date
18113 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18115 (defun org-goto-calendar (&optional arg)
18116 "Go to the Emacs calendar at the current date.
18117 If there is a time stamp in the current line, go to that date.
18118 A prefix ARG can be used to force the current date."
18119 (interactive "P")
18120 (let ((calendar-move-hook nil)
18121 (calendar-view-holidays-initially-flag nil)
18122 (calendar-view-diary-initially-flag nil)
18123 diff)
18124 (when (or (org-at-timestamp-p 'lax)
18125 (org-match-line (concat ".*" org-ts-regexp)))
18126 (let ((d1 (time-to-days (current-time)))
18127 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18128 (setq diff (- d2 d1))))
18129 (calendar)
18130 (calendar-goto-today)
18131 (when (and diff (not arg)) (calendar-forward-day diff))))
18133 (defun org-get-date-from-calendar ()
18134 "Return a list (month day year) of date at point in calendar."
18135 (with-current-buffer "*Calendar*"
18136 (save-match-data
18137 (calendar-cursor-to-date))))
18139 (defun org-date-from-calendar ()
18140 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18141 If there is already a time stamp at the cursor position, update it."
18142 (interactive)
18143 (if (org-at-timestamp-p 'lax)
18144 (org-timestamp-change 0 'calendar)
18145 (let ((cal-date (org-get-date-from-calendar)))
18146 (org-insert-time-stamp
18147 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18149 (defcustom org-effort-durations
18150 `(("min" . 1)
18151 ("h" . 60)
18152 ("d" . ,(* 60 8))
18153 ("w" . ,(* 60 8 5))
18154 ("m" . ,(* 60 8 5 4))
18155 ("y" . ,(* 60 8 5 40)))
18156 "Conversion factor to minutes for an effort modifier.
18158 Each entry has the form (MODIFIER . MINUTES).
18160 In an effort string, a number followed by MODIFIER is multiplied
18161 by the specified number of MINUTES to obtain an effort in
18162 minutes.
18164 For example, if the value of this variable is ((\"hours\" . 60)), then an
18165 effort string \"2hours\" is equivalent to 120 minutes."
18166 :group 'org-agenda
18167 :version "26.1"
18168 :package-version '(Org . "8.3")
18169 :type '(alist :key-type (string :tag "Modifier")
18170 :value-type (number :tag "Minutes")))
18172 (defcustom org-image-actual-width t
18173 "Should we use the actual width of images when inlining them?
18175 When set to t, always use the image width.
18177 When set to a number, use imagemagick (when available) to set
18178 the image's width to this value.
18180 When set to a number in a list, try to get the width from any
18181 #+ATTR.* keyword if it matches a width specification like
18183 #+ATTR_HTML: :width 300px
18185 and fall back on that number if none is found.
18187 When set to nil, try to get the width from an #+ATTR.* keyword
18188 and fall back on the original width if none is found.
18190 This requires Emacs >= 24.1, build with imagemagick support."
18191 :group 'org-appearance
18192 :version "24.4"
18193 :package-version '(Org . "8.0")
18194 :type '(choice
18195 (const :tag "Use the image width" t)
18196 (integer :tag "Use a number of pixels")
18197 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18198 (const :tag "Use #+ATTR* or don't resize" nil)))
18200 (defcustom org-agenda-inhibit-startup nil
18201 "Inhibit startup when preparing agenda buffers.
18202 When this variable is t, the initialization of the Org agenda
18203 buffers is inhibited: e.g. the visibility state is not set, the
18204 tables are not re-aligned, etc."
18205 :type 'boolean
18206 :version "24.3"
18207 :group 'org-agenda)
18209 (defcustom org-agenda-ignore-properties nil
18210 "Avoid updating text properties when building the agenda.
18211 Properties are used to prepare buffers for effort estimates,
18212 appointments, statistics and subtree-local categories.
18213 If you don't use these in the agenda, you can add them to this
18214 list and agenda building will be a bit faster.
18215 The value is a list, with zero or more of the symbols `effort', `appt',
18216 `stats' or `category'."
18217 :type '(set :greedy t
18218 (const effort)
18219 (const appt)
18220 (const stats)
18221 (const category))
18222 :version "26.1"
18223 :package-version '(Org . "8.3")
18224 :group 'org-agenda)
18226 ;;;; Files
18228 (defun org-save-all-org-buffers ()
18229 "Save all Org buffers without user confirmation."
18230 (interactive)
18231 (message "Saving all Org buffers...")
18232 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18233 (when (featurep 'org-id) (org-id-locations-save))
18234 (message "Saving all Org buffers... done"))
18236 (defun org-revert-all-org-buffers ()
18237 "Revert all Org buffers.
18238 Prompt for confirmation when there are unsaved changes.
18239 Be sure you know what you are doing before letting this function
18240 overwrite your changes.
18242 This function is useful in a setup where one tracks org files
18243 with a version control system, to revert on one machine after pulling
18244 changes from another. I believe the procedure must be like this:
18246 1. M-x org-save-all-org-buffers
18247 2. Pull changes from the other machine, resolve conflicts
18248 3. M-x org-revert-all-org-buffers"
18249 (interactive)
18250 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18251 (user-error "Abort"))
18252 (save-excursion
18253 (save-window-excursion
18254 (dolist (b (buffer-list))
18255 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18256 (with-current-buffer b buffer-file-name))
18257 (pop-to-buffer-same-window b)
18258 (revert-buffer t 'no-confirm)))
18259 (when (and (featurep 'org-id) org-id-track-globally)
18260 (org-id-locations-load)))))
18262 ;;;; Agenda files
18264 ;;;###autoload
18265 (defun org-switchb (&optional arg)
18266 "Switch between Org buffers.
18268 With `\\[universal-argument]' prefix, restrict available buffers to files.
18270 With `\\[universal-argument] \\[universal-argument]' \
18271 prefix, restrict available buffers to agenda files."
18272 (interactive "P")
18273 (let ((blist (org-buffer-list
18274 (cond ((equal arg '(4)) 'files)
18275 ((equal arg '(16)) 'agenda)))))
18276 (pop-to-buffer-same-window
18277 (completing-read "Org buffer: "
18278 (mapcar #'list (mapcar #'buffer-name blist))
18279 nil t))))
18281 (defun org-buffer-list (&optional predicate exclude-tmp)
18282 "Return a list of Org buffers.
18283 PREDICATE can be `export', `files' or `agenda'.
18285 export restrict the list to Export buffers.
18286 files restrict the list to buffers visiting Org files.
18287 agenda restrict the list to buffers visiting agenda files.
18289 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18290 (let* ((bfn nil)
18291 (agenda-files (and (eq predicate 'agenda)
18292 (mapcar 'file-truename (org-agenda-files t))))
18293 (filter
18294 (cond
18295 ((eq predicate 'files)
18296 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18297 ((eq predicate 'export)
18298 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18299 ((eq predicate 'agenda)
18300 (lambda (b)
18301 (with-current-buffer b
18302 (and (derived-mode-p 'org-mode)
18303 (setq bfn (buffer-file-name b))
18304 (member (file-truename bfn) agenda-files)))))
18305 (t (lambda (b) (with-current-buffer b
18306 (or (derived-mode-p 'org-mode)
18307 (string-match "\\*Org .*Export"
18308 (buffer-name b)))))))))
18309 (delq nil
18310 (mapcar
18311 (lambda(b)
18312 (if (and (funcall filter b)
18313 (or (not exclude-tmp)
18314 (not (string-match "tmp" (buffer-name b)))))
18316 nil))
18317 (buffer-list)))))
18319 (defun org-agenda-files (&optional unrestricted archives)
18320 "Get the list of agenda files.
18321 Optional UNRESTRICTED means return the full list even if a restriction
18322 is currently in place.
18323 When ARCHIVES is t, include all archive files that are really being
18324 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18325 `org-agenda-archives-mode' is t."
18326 (let ((files
18327 (cond
18328 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18329 ((stringp org-agenda-files) (org-read-agenda-file-list))
18330 ((listp org-agenda-files) org-agenda-files)
18331 (t (error "Invalid value of `org-agenda-files'")))))
18332 (setq files (apply 'append
18333 (mapcar (lambda (f)
18334 (if (file-directory-p f)
18335 (directory-files
18336 f t org-agenda-file-regexp)
18337 (list f)))
18338 files)))
18339 (when org-agenda-skip-unavailable-files
18340 (setq files (delq nil
18341 (mapcar (function
18342 (lambda (file)
18343 (and (file-readable-p file) file)))
18344 files))))
18345 (when (or (eq archives t)
18346 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18347 (setq files (org-add-archive-files files)))
18348 files))
18350 (defun org-agenda-file-p (&optional file)
18351 "Return non-nil, if FILE is an agenda file.
18352 If FILE is omitted, use the file associated with the current
18353 buffer."
18354 (let ((fname (or file (buffer-file-name))))
18355 (and fname
18356 (member (file-truename fname)
18357 (mapcar #'file-truename (org-agenda-files t))))))
18359 (defun org-edit-agenda-file-list ()
18360 "Edit the list of agenda files.
18361 Depending on setup, this either uses customize to edit the variable
18362 `org-agenda-files', or it visits the file that is holding the list. In the
18363 latter case, the buffer is set up in a way that saving it automatically kills
18364 the buffer and restores the previous window configuration."
18365 (interactive)
18366 (if (stringp org-agenda-files)
18367 (let ((cw (current-window-configuration)))
18368 (find-file org-agenda-files)
18369 (setq-local org-window-configuration cw)
18370 (add-hook 'after-save-hook
18371 (lambda ()
18372 (set-window-configuration
18373 (prog1 org-window-configuration
18374 (kill-buffer (current-buffer))))
18375 (org-install-agenda-files-menu)
18376 (message "New agenda file list installed"))
18377 nil 'local)
18378 (message "%s" (substitute-command-keys
18379 "Edit list and finish with \\[save-buffer]")))
18380 (customize-variable 'org-agenda-files)))
18382 (defun org-store-new-agenda-file-list (list)
18383 "Set new value for the agenda file list and save it correctly."
18384 (if (stringp org-agenda-files)
18385 (let ((fe (org-read-agenda-file-list t)) b u)
18386 (while (setq b (find-buffer-visiting org-agenda-files))
18387 (kill-buffer b))
18388 (with-temp-file org-agenda-files
18389 (insert
18390 (mapconcat
18391 (lambda (f) ;; Keep un-expanded entries.
18392 (if (setq u (assoc f fe))
18393 (cdr u)
18395 list "\n")
18396 "\n")))
18397 (let ((org-mode-hook nil) (org-inhibit-startup t)
18398 (org-insert-mode-line-in-empty-file nil))
18399 (setq org-agenda-files list)
18400 (customize-save-variable 'org-agenda-files org-agenda-files))))
18402 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18403 "Read the list of agenda files from a file.
18404 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18405 filenames, used by `org-store-new-agenda-file-list' to write back
18406 un-expanded file names."
18407 (when (file-directory-p org-agenda-files)
18408 (error "`org-agenda-files' cannot be a single directory"))
18409 (when (stringp org-agenda-files)
18410 (with-temp-buffer
18411 (insert-file-contents org-agenda-files)
18412 (mapcar
18413 (lambda (f)
18414 (let ((e (expand-file-name (substitute-in-file-name f)
18415 org-directory)))
18416 (if pair-with-expansion
18417 (cons e f)
18418 e)))
18419 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18421 ;;;###autoload
18422 (defun org-cycle-agenda-files ()
18423 "Cycle through the files in `org-agenda-files'.
18424 If the current buffer visits an agenda file, find the next one in the list.
18425 If the current buffer does not, find the first agenda file."
18426 (interactive)
18427 (let* ((fs (or (org-agenda-files t)
18428 (user-error "No agenda files")))
18429 (files (copy-sequence fs))
18430 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18431 file)
18432 (when tcf
18433 (while (and (setq file (pop files))
18434 (not (equal (file-truename file) tcf)))))
18435 (find-file (car (or files fs)))
18436 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18438 (defun org-agenda-file-to-front (&optional to-end)
18439 "Move/add the current file to the top of the agenda file list.
18440 If the file is not present in the list, it is added to the front. If it is
18441 present, it is moved there. With optional argument TO-END, add/move to the
18442 end of the list."
18443 (interactive "P")
18444 (let ((org-agenda-skip-unavailable-files nil)
18445 (file-alist (mapcar (lambda (x)
18446 (cons (file-truename x) x))
18447 (org-agenda-files t)))
18448 (ctf (file-truename
18449 (or buffer-file-name
18450 (user-error "Please save the current buffer to a file"))))
18451 x had)
18452 (setq x (assoc ctf file-alist) had x)
18454 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18455 (if to-end
18456 (setq file-alist (append (delq x file-alist) (list x)))
18457 (setq file-alist (cons x (delq x file-alist))))
18458 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18459 (org-install-agenda-files-menu)
18460 (message "File %s to %s of agenda file list"
18461 (if had "moved" "added") (if to-end "end" "front"))))
18463 (defun org-remove-file (&optional file)
18464 "Remove current file from the list of files in variable `org-agenda-files'.
18465 These are the files which are being checked for agenda entries.
18466 Optional argument FILE means use this file instead of the current."
18467 (interactive)
18468 (let* ((org-agenda-skip-unavailable-files nil)
18469 (file (or file buffer-file-name
18470 (user-error "Current buffer does not visit a file")))
18471 (true-file (file-truename file))
18472 (afile (abbreviate-file-name file))
18473 (files (delq nil (mapcar
18474 (lambda (x)
18475 (unless (equal true-file
18476 (file-truename x))
18478 (org-agenda-files t)))))
18479 (if (not (= (length files) (length (org-agenda-files t))))
18480 (progn
18481 (org-store-new-agenda-file-list files)
18482 (org-install-agenda-files-menu)
18483 (message "Removed from Org Agenda list: %s" afile))
18484 (message "File was not in list: %s (not removed)" afile))))
18486 (defun org-file-menu-entry (file)
18487 (vector file (list 'find-file file) t))
18489 (defun org-check-agenda-file (file)
18490 "Make sure FILE exists. If not, ask user what to do."
18491 (unless (file-exists-p file)
18492 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18493 (abbreviate-file-name file))
18494 (let ((r (downcase (read-char-exclusive))))
18495 (cond
18496 ((equal r ?r)
18497 (org-remove-file file)
18498 (throw 'nextfile t))
18499 (t (user-error "Abort"))))))
18501 (defun org-get-agenda-file-buffer (file)
18502 "Get an agenda buffer visiting FILE.
18503 If the buffer needs to be created, add it to the list of buffers
18504 which might be released later."
18505 (let ((buf (org-find-base-buffer-visiting file)))
18506 (if buf
18507 buf ; just return it
18508 ;; Make a new buffer and remember it
18509 (setq buf (find-file-noselect file))
18510 (when buf (push buf org-agenda-new-buffers))
18511 buf)))
18513 (defun org-release-buffers (blist)
18514 "Release all buffers in list, asking the user for confirmation when needed.
18515 When a buffer is unmodified, it is just killed. When modified, it is saved
18516 \(if the user agrees) and then killed."
18517 (let (file)
18518 (dolist (buf blist)
18519 (setq file (buffer-file-name buf))
18520 (when (and (buffer-modified-p buf)
18521 file
18522 (y-or-n-p (format "Save file %s? " file)))
18523 (with-current-buffer buf (save-buffer)))
18524 (kill-buffer buf))))
18526 (defun org-agenda-prepare-buffers (files)
18527 "Create buffers for all agenda files, protect archived trees and comments."
18528 (interactive)
18529 (let ((pa '(:org-archived t))
18530 (pc '(:org-comment t))
18531 (pall '(:org-archived t :org-comment t))
18532 (inhibit-read-only t)
18533 (org-inhibit-startup org-agenda-inhibit-startup)
18534 (rea (concat ":" org-archive-tag ":"))
18535 re pos)
18536 (setq org-tag-alist-for-agenda nil
18537 org-tag-groups-alist-for-agenda nil)
18538 (save-excursion
18539 (save-restriction
18540 (dolist (file files)
18541 (catch 'nextfile
18542 (if (bufferp file)
18543 (set-buffer file)
18544 (org-check-agenda-file file)
18545 (set-buffer (org-get-agenda-file-buffer file)))
18546 (widen)
18547 (org-set-regexps-and-options 'tags-only)
18548 (setq pos (point))
18549 (or (memq 'category org-agenda-ignore-properties)
18550 (org-refresh-category-properties))
18551 (or (memq 'stats org-agenda-ignore-properties)
18552 (org-refresh-stats-properties))
18553 (or (memq 'effort org-agenda-ignore-properties)
18554 (org-refresh-effort-properties))
18555 (or (memq 'appt org-agenda-ignore-properties)
18556 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18557 (setq org-todo-keywords-for-agenda
18558 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18559 (setq org-done-keywords-for-agenda
18560 (append org-done-keywords-for-agenda org-done-keywords))
18561 (setq org-todo-keyword-alist-for-agenda
18562 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18563 (setq org-tag-alist-for-agenda
18564 (org-uniquify
18565 (append org-tag-alist-for-agenda
18566 org-current-tag-alist)))
18567 ;; Merge current file's tag groups into global
18568 ;; `org-tag-groups-alist-for-agenda'.
18569 (when org-group-tags
18570 (dolist (alist org-tag-groups-alist)
18571 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18572 (if old
18573 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18574 (push alist org-tag-groups-alist-for-agenda)))))
18575 (org-with-silent-modifications
18576 (save-excursion
18577 (remove-text-properties (point-min) (point-max) pall)
18578 (when org-agenda-skip-archived-trees
18579 (goto-char (point-min))
18580 (while (re-search-forward rea nil t)
18581 (when (org-at-heading-p t)
18582 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18583 (goto-char (point-min))
18584 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18585 (while (re-search-forward re nil t)
18586 (when (save-match-data (org-in-commented-heading-p t))
18587 (add-text-properties
18588 (match-beginning 0) (org-end-of-subtree t) pc)))))
18589 (goto-char pos)))))
18590 (setq org-todo-keywords-for-agenda
18591 (org-uniquify org-todo-keywords-for-agenda))
18592 (setq org-todo-keyword-alist-for-agenda
18593 (org-uniquify org-todo-keyword-alist-for-agenda))))
18596 ;;;; CDLaTeX minor mode
18598 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18599 "Keymap for the minor `org-cdlatex-mode'.")
18601 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18602 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18603 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18604 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18605 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18607 (defvar org-cdlatex-texmathp-advice-is-done nil
18608 "Flag remembering if we have applied the advice to texmathp already.")
18610 (define-minor-mode org-cdlatex-mode
18611 "Toggle the minor `org-cdlatex-mode'.
18612 This mode supports entering LaTeX environment and math in LaTeX fragments
18613 in Org mode.
18614 \\{org-cdlatex-mode-map}"
18615 nil " OCDL" nil
18616 (when org-cdlatex-mode
18617 (require 'cdlatex)
18618 (run-hooks 'cdlatex-mode-hook)
18619 (cdlatex-compute-tables))
18620 (unless org-cdlatex-texmathp-advice-is-done
18621 (setq org-cdlatex-texmathp-advice-is-done t)
18622 (defadvice texmathp (around org-math-always-on activate)
18623 "Always return t in Org buffers.
18624 This is because we want to insert math symbols without dollars even outside
18625 the LaTeX math segments. If Org mode thinks that point is actually inside
18626 an embedded LaTeX fragment, let `texmathp' do its job.
18627 `\\[org-cdlatex-mode-map]'"
18628 (interactive)
18629 (let (p)
18630 (cond
18631 ((not (derived-mode-p 'org-mode)) ad-do-it)
18632 ((eq this-command 'cdlatex-math-symbol)
18633 (setq ad-return-value t
18634 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18636 (let ((p (org-inside-LaTeX-fragment-p)))
18637 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18638 (setq ad-return-value t
18639 texmathp-why '("Org mode embedded math" . 0))
18640 (when p ad-do-it)))))))))
18642 (defun turn-on-org-cdlatex ()
18643 "Unconditionally turn on `org-cdlatex-mode'."
18644 (org-cdlatex-mode 1))
18646 (defun org-try-cdlatex-tab ()
18647 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18648 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18649 - inside a LaTeX fragment, or
18650 - after the first word in a line, where an abbreviation expansion could
18651 insert a LaTeX environment."
18652 (when org-cdlatex-mode
18653 (cond
18654 ;; Before any word on the line: No expansion possible.
18655 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18656 ;; Just after first word on the line: Expand it. Make sure it
18657 ;; cannot happen on headlines, though.
18658 ((save-excursion
18659 (skip-chars-backward "a-zA-Z0-9*")
18660 (skip-chars-backward " \t")
18661 (and (bolp) (not (org-at-heading-p))))
18662 (cdlatex-tab) t)
18663 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18665 (defun org-cdlatex-underscore-caret (&optional _arg)
18666 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18667 Revert to the normal definition outside of these fragments."
18668 (interactive "P")
18669 (if (org-inside-LaTeX-fragment-p)
18670 (call-interactively 'cdlatex-sub-superscript)
18671 (let (org-cdlatex-mode)
18672 (call-interactively (key-binding (vector last-input-event))))))
18674 (defun org-cdlatex-math-modify (&optional _arg)
18675 "Execute `cdlatex-math-modify' in LaTeX fragments.
18676 Revert to the normal definition outside of these fragments."
18677 (interactive "P")
18678 (if (org-inside-LaTeX-fragment-p)
18679 (call-interactively 'cdlatex-math-modify)
18680 (let (org-cdlatex-mode)
18681 (call-interactively (key-binding (vector last-input-event))))))
18683 (defun org-cdlatex-environment-indent (&optional environment item)
18684 "Execute `cdlatex-environment' and indent the inserted environment.
18686 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18688 The inserted environment is indented to current indentation
18689 unless point is at the beginning of the line, in which the
18690 environment remains unintended."
18691 (interactive)
18692 ;; cdlatex-environment always return nil. Therefore, capture output
18693 ;; first and determine if an environment was selected.
18694 (let* ((beg (point-marker))
18695 (end (copy-marker (point) t))
18696 (inserted (progn
18697 (ignore-errors (cdlatex-environment environment item))
18698 (< beg end)))
18699 ;; Figure out how many lines to move forward after the
18700 ;; environment has been inserted.
18701 (lines (when inserted
18702 (save-excursion
18703 (- (cl-loop while (< beg (point))
18704 with x = 0
18705 do (forward-line -1)
18706 (cl-incf x)
18707 finally return x)
18708 (if (progn (goto-char beg)
18709 (and (progn (skip-chars-forward " \t") (eolp))
18710 (progn (skip-chars-backward " \t") (bolp))))
18711 1 0)))))
18712 (env (org-trim (delete-and-extract-region beg end))))
18713 (when inserted
18714 ;; Get indentation of next line unless at column 0.
18715 (let ((ind (if (bolp) 0
18716 (save-excursion
18717 (org-return-indent)
18718 (prog1 (org-get-indentation)
18719 (when (progn (skip-chars-forward " \t") (eolp))
18720 (delete-region beg (point)))))))
18721 (bol (progn (skip-chars-backward " \t") (bolp))))
18722 ;; Insert a newline before environment unless at column zero
18723 ;; to "escape" the current line. Insert a newline if
18724 ;; something is one the same line as \end{ENVIRONMENT}.
18725 (insert
18726 (concat (unless bol "\n") env
18727 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18728 (unless (zerop ind)
18729 (save-excursion
18730 (goto-char beg)
18731 (while (< (point) end)
18732 (unless (eolp) (indent-line-to ind))
18733 (forward-line))))
18734 (goto-char beg)
18735 (forward-line lines)
18736 (indent-line-to ind)))
18737 (set-marker beg nil)
18738 (set-marker end nil)))
18741 ;;;; LaTeX fragments
18743 (defun org-inside-LaTeX-fragment-p ()
18744 "Test if point is inside a LaTeX fragment.
18745 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18746 sequence appearing also before point.
18747 Even though the matchers for math are configurable, this function assumes
18748 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18749 delimiters are skipped when they have been removed by customization.
18750 The return value is nil, or a cons cell with the delimiter and the
18751 position of this delimiter.
18753 This function does a reasonably good job, but can locally be fooled by
18754 for example currency specifications. For example it will assume being in
18755 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18756 fragments that are properly closed, but during editing, we have to live
18757 with the uncertainty caused by missing closing delimiters. This function
18758 looks only before point, not after."
18759 (catch 'exit
18760 (let ((pos (point))
18761 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18762 (lim (save-excursion (org-backward-paragraph) (point)))
18763 dd-on str (start 0) m re)
18764 (goto-char pos)
18765 (when dodollar
18766 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18767 re (nth 1 (assoc "$" org-latex-regexps)))
18768 (while (string-match re str start)
18769 (cond
18770 ((= (match-end 0) (length str))
18771 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18772 ((= (match-end 0) (- (length str) 5))
18773 (throw 'exit nil))
18774 (t (setq start (match-end 0))))))
18775 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18776 (goto-char pos)
18777 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18778 (and (match-beginning 2) (throw 'exit nil))
18779 ;; count $$
18780 (while (re-search-backward "\\$\\$" lim t)
18781 (setq dd-on (not dd-on)))
18782 (goto-char pos)
18783 (when dd-on (cons "$$" m))))))
18785 (defun org-inside-latex-macro-p ()
18786 "Is point inside a LaTeX macro or its arguments?"
18787 (save-match-data
18788 (org-in-regexp
18789 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18791 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18792 "Build an overlay between BEG and END using IMAGE file.
18793 Argument IMAGETYPE is the extension of the displayed image,
18794 as a string. It defaults to \"png\"."
18795 (let ((ov (make-overlay beg end))
18796 (imagetype (or (intern imagetype) 'png)))
18797 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18798 (overlay-put ov 'evaporate t)
18799 (overlay-put ov
18800 'modification-hooks
18801 (list (lambda (o _flag _beg _end &optional _l)
18802 (delete-overlay o))))
18803 (overlay-put ov
18804 'display
18805 (list 'image :type imagetype :file image :ascent 'center))))
18807 (defun org--list-latex-overlays (&optional beg end)
18808 "List all Org LaTeX overlays in current buffer.
18809 Limit to overlays between BEG and END when those are provided."
18810 (cl-remove-if-not
18811 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18812 (overlays-in (or beg (point-min)) (or end (point-max)))))
18814 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18815 "Remove all overlays with LaTeX fragment images in current buffer.
18816 When optional arguments BEG and END are non-nil, remove all
18817 overlays between them instead. Return a non-nil value when some
18818 overlays were removed, nil otherwise."
18819 (let ((overlays (org--list-latex-overlays beg end)))
18820 (mapc #'delete-overlay overlays)
18821 overlays))
18823 (defun org-toggle-latex-fragment (&optional arg)
18824 "Preview the LaTeX fragment at point, or all locally or globally.
18826 If the cursor is on a LaTeX fragment, create the image and overlay
18827 it over the source code, if there is none. Remove it otherwise.
18828 If there is no fragment at point, display all fragments in the
18829 current section.
18831 With prefix ARG, preview or clear image for all fragments in the
18832 current subtree or in the whole buffer when used before the first
18833 headline. With a prefix ARG `\\[universal-argument] \
18834 \\[universal-argument]' preview or clear images
18835 for all fragments in the buffer."
18836 (interactive "P")
18837 (when (display-graphic-p)
18838 (catch 'exit
18839 (save-excursion
18840 (let (beg end msg)
18841 (cond
18842 ((or (equal arg '(16))
18843 (and (equal arg '(4))
18844 (org-with-limited-levels (org-before-first-heading-p))))
18845 (if (org-remove-latex-fragment-image-overlays)
18846 (progn (message "LaTeX fragments images removed from buffer")
18847 (throw 'exit nil))
18848 (setq msg "Creating images for buffer...")))
18849 ((equal arg '(4))
18850 (org-with-limited-levels (org-back-to-heading t))
18851 (setq beg (point))
18852 (setq end (progn (org-end-of-subtree t) (point)))
18853 (if (org-remove-latex-fragment-image-overlays beg end)
18854 (progn
18855 (message "LaTeX fragment images removed from subtree")
18856 (throw 'exit nil))
18857 (setq msg "Creating images for subtree...")))
18858 ((let ((datum (org-element-context)))
18859 (when (memq (org-element-type datum)
18860 '(latex-environment latex-fragment))
18861 (setq beg (org-element-property :begin datum))
18862 (setq end (org-element-property :end datum))
18863 (if (org-remove-latex-fragment-image-overlays beg end)
18864 (progn (message "LaTeX fragment image removed")
18865 (throw 'exit nil))
18866 (setq msg "Creating image...")))))
18868 (org-with-limited-levels
18869 (setq beg (if (org-at-heading-p) (line-beginning-position)
18870 (outline-previous-heading)
18871 (point)))
18872 (setq end (progn (outline-next-heading) (point)))
18873 (if (org-remove-latex-fragment-image-overlays beg end)
18874 (progn
18875 (message "LaTeX fragment images removed from section")
18876 (throw 'exit nil))
18877 (setq msg "Creating images for section...")))))
18878 (let ((file (buffer-file-name (buffer-base-buffer))))
18879 (org-format-latex
18880 (concat org-preview-latex-image-directory "org-ltximg")
18881 beg end
18882 ;; Emacs cannot overlay images from remote hosts. Create
18883 ;; it in `temporary-file-directory' instead.
18884 (if (or (not file) (file-remote-p file))
18885 temporary-file-directory
18886 default-directory)
18887 'overlays msg 'forbuffer org-preview-latex-default-process))
18888 (message (concat msg "done")))))))
18890 (defun org-format-latex
18891 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18892 "Replace LaTeX fragments with links to an image.
18894 The function takes care of creating the replacement image.
18896 Only consider fragments between BEG and END when those are
18897 provided.
18899 When optional argument OVERLAYS is non-nil, display the image on
18900 top of the fragment instead of replacing it.
18902 PROCESSING-TYPE is the conversion method to use, as a symbol.
18904 Some of the options can be changed using the variable
18905 `org-format-latex-options', which see."
18906 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18907 (unless (eq processing-type 'verbatim)
18908 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18909 (cnt 0)
18910 checkdir-flag)
18911 (goto-char (or beg (point-min)))
18912 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18913 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18914 (overlay-recenter (or end (point-max))))
18915 (while (re-search-forward math-regexp end t)
18916 (unless (and overlays
18917 (eq (get-char-property (point) 'org-overlay-type)
18918 'org-latex-overlay))
18919 (let* ((context (org-element-context))
18920 (type (org-element-type context)))
18921 (when (memq type '(latex-environment latex-fragment))
18922 (let ((block-type (eq type 'latex-environment))
18923 (value (org-element-property :value context))
18924 (beg (org-element-property :begin context))
18925 (end (save-excursion
18926 (goto-char (org-element-property :end context))
18927 (skip-chars-backward " \r\t\n")
18928 (point))))
18929 (cond
18930 ((eq processing-type 'mathjax)
18931 ;; Prepare for MathJax processing.
18932 (if (not (string-match "\\`\\$\\$?" value))
18933 (goto-char end)
18934 (delete-region beg end)
18935 (if (string= (match-string 0 value) "$$")
18936 (insert "\\[" (substring value 2 -2) "\\]")
18937 (insert "\\(" (substring value 1 -1) "\\)"))))
18938 ((assq processing-type org-preview-latex-process-alist)
18939 ;; Process to an image.
18940 (cl-incf cnt)
18941 (goto-char beg)
18942 (let* ((processing-info
18943 (cdr (assq processing-type org-preview-latex-process-alist)))
18944 (face (face-at-point))
18945 ;; Get the colors from the face at point.
18947 (let ((color (plist-get org-format-latex-options
18948 :foreground)))
18949 (if (and forbuffer (eq color 'auto))
18950 (face-attribute face :foreground nil 'default)
18951 color)))
18953 (let ((color (plist-get org-format-latex-options
18954 :background)))
18955 (if (and forbuffer (eq color 'auto))
18956 (face-attribute face :background nil 'default)
18957 color)))
18958 (hash (sha1 (prin1-to-string
18959 (list org-format-latex-header
18960 org-latex-default-packages-alist
18961 org-latex-packages-alist
18962 org-format-latex-options
18963 forbuffer value fg bg))))
18964 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18965 (absprefix (expand-file-name prefix dir))
18966 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18967 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18968 (sep (and block-type "\n\n"))
18969 (link (concat sep "[[file:" linkfile "]]" sep))
18970 (options
18971 (org-combine-plists
18972 org-format-latex-options
18973 `(:foreground ,fg :background ,bg))))
18974 (when msg (message msg cnt))
18975 (unless checkdir-flag ; Ensure the directory exists.
18976 (setq checkdir-flag t)
18977 (let ((todir (file-name-directory absprefix)))
18978 (unless (file-directory-p todir)
18979 (make-directory todir t))))
18980 (unless (file-exists-p movefile)
18981 (org-create-formula-image
18982 value movefile options forbuffer processing-type))
18983 (if overlays
18984 (progn
18985 (dolist (o (overlays-in beg end))
18986 (when (eq (overlay-get o 'org-overlay-type)
18987 'org-latex-overlay)
18988 (delete-overlay o)))
18989 (org--format-latex-make-overlay beg end movefile imagetype)
18990 (goto-char end))
18991 (delete-region beg end)
18992 (insert
18993 (org-add-props link
18994 (list 'org-latex-src
18995 (replace-regexp-in-string "\"" "" value)
18996 'org-latex-src-embed-type
18997 (if block-type 'paragraph 'character)))))))
18998 ((eq processing-type 'mathml)
18999 ;; Process to MathML.
19000 (unless (org-format-latex-mathml-available-p)
19001 (user-error "LaTeX to MathML converter not configured"))
19002 (cl-incf cnt)
19003 (when msg (message msg cnt))
19004 (goto-char beg)
19005 (delete-region beg end)
19006 (insert (org-format-latex-as-mathml
19007 value block-type prefix dir)))
19009 (error "Unknown conversion process %s for LaTeX fragments"
19010 processing-type)))))))))))
19012 (defun org-create-math-formula (latex-frag &optional mathml-file)
19013 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19014 Use `org-latex-to-mathml-convert-command'. If the conversion is
19015 sucessful, return the portion between \"<math...> </math>\"
19016 elements otherwise return nil. When MATHML-FILE is specified,
19017 write the results in to that file. When invoked as an
19018 interactive command, prompt for LATEX-FRAG, with initial value
19019 set to the current active region and echo the results for user
19020 inspection."
19021 (interactive (list (let ((frag (when (org-region-active-p)
19022 (buffer-substring-no-properties
19023 (region-beginning) (region-end)))))
19024 (read-string "LaTeX Fragment: " frag nil frag))))
19025 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19026 (let* ((tmp-in-file
19027 (let ((file (file-relative-name
19028 (make-temp-name (expand-file-name "ltxmathml-in")))))
19029 (write-region latex-frag nil file)
19030 file))
19031 (tmp-out-file (file-relative-name
19032 (make-temp-name (expand-file-name "ltxmathml-out"))))
19033 (cmd (format-spec
19034 org-latex-to-mathml-convert-command
19035 `((?j . ,(and org-latex-to-mathml-jar-file
19036 (shell-quote-argument
19037 (expand-file-name
19038 org-latex-to-mathml-jar-file))))
19039 (?I . ,(shell-quote-argument tmp-in-file))
19040 (?i . ,latex-frag)
19041 (?o . ,(shell-quote-argument tmp-out-file)))))
19042 mathml shell-command-output)
19043 (when (called-interactively-p 'any)
19044 (unless (org-format-latex-mathml-available-p)
19045 (user-error "LaTeX to MathML converter not configured")))
19046 (message "Running %s" cmd)
19047 (setq shell-command-output (shell-command-to-string cmd))
19048 (setq mathml
19049 (when (file-readable-p tmp-out-file)
19050 (with-current-buffer (find-file-noselect tmp-out-file t)
19051 (goto-char (point-min))
19052 (when (re-search-forward
19053 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19054 (regexp-quote
19055 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19056 nil t)
19057 (prog1 (match-string 0) (kill-buffer))))))
19058 (cond
19059 (mathml
19060 (setq mathml
19061 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19062 (when mathml-file
19063 (write-region mathml nil mathml-file))
19064 (when (called-interactively-p 'any)
19065 (message mathml)))
19066 ((message "LaTeX to MathML conversion failed")
19067 (message shell-command-output)))
19068 (delete-file tmp-in-file)
19069 (when (file-exists-p tmp-out-file)
19070 (delete-file tmp-out-file))
19071 mathml))
19073 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19074 prefix &optional dir)
19075 "Use `org-create-math-formula' but check local cache first."
19076 (let* ((absprefix (expand-file-name prefix dir))
19077 (print-length nil) (print-level nil)
19078 (formula-id (concat
19079 "formula-"
19080 (sha1
19081 (prin1-to-string
19082 (list latex-frag
19083 org-latex-to-mathml-convert-command)))))
19084 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19085 (formula-cache-dir (file-name-directory formula-cache)))
19087 (unless (file-directory-p formula-cache-dir)
19088 (make-directory formula-cache-dir t))
19090 (unless (file-exists-p formula-cache)
19091 (org-create-math-formula latex-frag formula-cache))
19093 (if (file-exists-p formula-cache)
19094 ;; Successful conversion. Return the link to MathML file.
19095 (org-add-props
19096 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19097 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19098 'org-latex-src-embed-type (if latex-frag-type
19099 'paragraph 'character)))
19100 ;; Failed conversion. Return the LaTeX fragment verbatim
19101 latex-frag)))
19103 (defun org--get-display-dpi ()
19104 "Get the DPI of the display.
19105 The function assumes that the display has the same pixel width in
19106 the horizontal and vertical directions."
19107 (if (display-graphic-p)
19108 (round (/ (display-pixel-height)
19109 (/ (display-mm-height) 25.4)))
19110 (error "Attempt to calculate the dpi of a non-graphic display")))
19112 (defun org-create-formula-image
19113 (string tofile options buffer &optional processing-type)
19114 "Create an image from LaTeX source using external processes.
19116 The LaTeX STRING is saved to a temporary LaTeX file, then
19117 converted to an image file by process PROCESSING-TYPE defined in
19118 `org-preview-latex-process-alist'. A nil value defaults to
19119 `org-preview-latex-default-process'.
19121 The generated image file is eventually moved to TOFILE.
19123 The OPTIONS argument controls the size, foreground color and
19124 background color of the generated image.
19126 When BUFFER non-nil, this function is used for LaTeX previewing.
19127 Otherwise, it is used to deal with LaTeX snippets showed in
19128 a HTML file."
19129 (let* ((processing-type (or processing-type
19130 org-preview-latex-default-process))
19131 (processing-info
19132 (cdr (assq processing-type org-preview-latex-process-alist)))
19133 (programs (plist-get processing-info :programs))
19134 (error-message (or (plist-get processing-info :message) ""))
19135 (use-xcolor (plist-get processing-info :use-xcolor))
19136 (image-input-type (plist-get processing-info :image-input-type))
19137 (image-output-type (plist-get processing-info :image-output-type))
19138 (post-clean (or (plist-get processing-info :post-clean)
19139 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19140 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19141 (latex-header
19142 (or (plist-get processing-info :latex-header)
19143 (org-latex-make-preamble
19144 (org-export-get-environment (org-export-get-backend 'latex))
19145 org-format-latex-header
19146 'snippet)))
19147 (latex-compiler (plist-get processing-info :latex-compiler))
19148 (image-converter (plist-get processing-info :image-converter))
19149 (tmpdir temporary-file-directory)
19150 (texfilebase (make-temp-name
19151 (expand-file-name "orgtex" tmpdir)))
19152 (texfile (concat texfilebase ".tex"))
19153 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19154 '(1.0 . 1.0)))
19155 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19156 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19157 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19158 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19159 "Black"))
19160 (bg (or (plist-get options (if buffer :background :html-background))
19161 "Transparent"))
19162 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19163 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19164 (dolist (program programs)
19165 (org-check-external-command program error-message))
19166 (if use-xcolor
19167 (progn (if (eq fg 'default)
19168 (setq fg (org-latex-color :foreground))
19169 (setq fg (org-latex-color-format fg)))
19170 (if (eq bg 'default)
19171 (setq bg (org-latex-color :background))
19172 (setq bg (org-latex-color-format
19173 (if (string= bg "Transparent") "white" bg))))
19174 (with-temp-file texfile
19175 (insert latex-header)
19176 (insert "\n\\begin{document}\n"
19177 "\\definecolor{fg}{rgb}{" fg "}\n"
19178 "\\definecolor{bg}{rgb}{" bg "}\n"
19179 "\n\\pagecolor{bg}\n"
19180 "\n{\\color{fg}\n"
19181 string
19182 "\n}\n"
19183 "\n\\end{document}\n")))
19184 (if (eq fg 'default)
19185 (setq fg (org-dvipng-color :foreground))
19186 (unless (string= fg "Transparent")
19187 (setq fg (org-dvipng-color-format fg))))
19188 (if (eq bg 'default)
19189 (setq bg (org-dvipng-color :background))
19190 (unless (string= bg "Transparent")
19191 (setq bg (org-dvipng-color-format bg))))
19192 (with-temp-file texfile
19193 (insert latex-header)
19194 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19196 (let* ((err-msg (format "Please adjust `%s' part of \
19197 `org-preview-latex-process-alist'."
19198 processing-type))
19199 (image-input-file
19200 (org-compile-file
19201 texfile latex-compiler image-input-type err-msg log-buf))
19202 (image-output-file
19203 (org-compile-file
19204 image-input-file image-converter image-output-type err-msg log-buf
19205 `((?F . ,(shell-quote-argument fg))
19206 (?B . ,(shell-quote-argument bg))
19207 (?D . ,(shell-quote-argument (format "%s" dpi)))
19208 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19209 (copy-file image-output-file tofile 'replace)
19210 (dolist (e post-clean)
19211 (when (file-exists-p (concat texfilebase e))
19212 (delete-file (concat texfilebase e))))
19213 image-output-file)))
19215 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19216 "Fill a LaTeX header template TPL.
19217 In the template, the following place holders will be recognized:
19219 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19220 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19221 [PACKAGES] \\usepackage statements for PKG
19222 [NO-PACKAGES] do not include PKG
19223 [EXTRA] the string EXTRA
19224 [NO-EXTRA] do not include EXTRA
19226 For backward compatibility, if both the positive and the negative place
19227 holder is missing, the positive one (without the \"NO-\") will be
19228 assumed to be present at the end of the template.
19229 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19230 EXTRA is a string.
19231 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19232 (let (rpl (end ""))
19233 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19234 (setq rpl (if (or (match-end 1) (not def-pkg))
19235 "" (org-latex-packages-to-string def-pkg snippets-p t))
19236 tpl (replace-match rpl t t tpl))
19237 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19239 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19240 (setq rpl (if (or (match-end 1) (not pkg))
19241 "" (org-latex-packages-to-string pkg snippets-p t))
19242 tpl (replace-match rpl t t tpl))
19243 (when pkg (setq end
19244 (concat end "\n"
19245 (org-latex-packages-to-string pkg snippets-p)))))
19247 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19248 (setq rpl (if (or (match-end 1) (not extra))
19249 "" (concat extra "\n"))
19250 tpl (replace-match rpl t t tpl))
19251 (when (and extra (string-match "\\S-" extra))
19252 (setq end (concat end "\n" extra))))
19254 (if (string-match "\\S-" end)
19255 (concat tpl "\n" end)
19256 tpl)))
19258 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19259 "Turn an alist of packages into a string with the \\usepackage macros."
19260 (setq pkg (mapconcat (lambda(p)
19261 (cond
19262 ((stringp p) p)
19263 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19264 (format "%% Package %s omitted" (cadr p)))
19265 ((equal "" (car p))
19266 (format "\\usepackage{%s}" (cadr p)))
19268 (format "\\usepackage[%s]{%s}"
19269 (car p) (cadr p)))))
19271 "\n"))
19272 (if newline (concat pkg "\n") pkg))
19274 (defun org-dvipng-color (attr)
19275 "Return a RGB color specification for dvipng."
19276 (org-dvipng-color-format (face-attribute 'default attr nil)))
19278 (defun org-dvipng-color-format (color-name)
19279 "Convert COLOR-NAME to a RGB color value for dvipng."
19280 (apply #'format "rgb %s %s %s"
19281 (mapcar 'org-normalize-color
19282 (color-values color-name))))
19284 (defun org-latex-color (attr)
19285 "Return a RGB color for the LaTeX color package."
19286 (org-latex-color-format (face-attribute 'default attr nil)))
19288 (defun org-latex-color-format (color-name)
19289 "Convert COLOR-NAME to a RGB color value."
19290 (apply #'format "%s,%s,%s"
19291 (mapcar 'org-normalize-color
19292 (color-values color-name))))
19294 (defun org-normalize-color (value)
19295 "Return string to be used as color value for an RGB component."
19296 (format "%g" (/ value 65535.0)))
19300 ;; Image display
19302 (defvar-local org-inline-image-overlays nil)
19304 (defun org-toggle-inline-images (&optional include-linked)
19305 "Toggle the display of inline images.
19306 INCLUDE-LINKED is passed to `org-display-inline-images'."
19307 (interactive "P")
19308 (if org-inline-image-overlays
19309 (progn
19310 (org-remove-inline-images)
19311 (when (called-interactively-p 'interactive)
19312 (message "Inline image display turned off")))
19313 (org-display-inline-images include-linked)
19314 (when (called-interactively-p 'interactive)
19315 (message (if org-inline-image-overlays
19316 (format "%d images displayed inline"
19317 (length org-inline-image-overlays))
19318 "No images to display inline")))))
19320 (defun org-redisplay-inline-images ()
19321 "Refresh the display of inline images."
19322 (interactive)
19323 (if (not org-inline-image-overlays)
19324 (org-toggle-inline-images)
19325 (org-toggle-inline-images)
19326 (org-toggle-inline-images)))
19328 (defun org-display-inline-images (&optional include-linked refresh beg end)
19329 "Display inline images.
19331 An inline image is a link which follows either of these
19332 conventions:
19334 1. Its path is a file with an extension matching return value
19335 from `image-file-name-regexp' and it has no contents.
19337 2. Its description consists in a single link of the previous
19338 type.
19340 When optional argument INCLUDE-LINKED is non-nil, also links with
19341 a text description part will be inlined. This can be nice for
19342 a quick look at those images, but it does not reflect what
19343 exported files will look like.
19345 When optional argument REFRESH is non-nil, refresh existing
19346 images between BEG and END. This will create new image displays
19347 only if necessary. BEG and END default to the buffer
19348 boundaries."
19349 (interactive "P")
19350 (when (display-graphic-p)
19351 (unless refresh
19352 (org-remove-inline-images)
19353 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19354 (org-with-wide-buffer
19355 (goto-char (or beg (point-min)))
19356 (let* ((case-fold-search t)
19357 (file-extension-re (image-file-name-regexp))
19358 (link-abbrevs (mapcar #'car
19359 (append org-link-abbrev-alist-local
19360 org-link-abbrev-alist)))
19361 ;; Check absolute, relative file names and explicit
19362 ;; "file:" links. Also check link abbreviations since
19363 ;; some might expand to "file" links.
19364 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19365 (and link-abbrevs
19366 (format "\\|\\(?:%s:\\)"
19367 (regexp-opt link-abbrevs))))))
19368 (while (re-search-forward file-types-re end t)
19369 (let ((link (save-match-data (org-element-context))))
19370 ;; Check if we're at an inline image, i.e., an image file
19371 ;; link without a description (unless INCLUDE-LINKED is
19372 ;; non-nil).
19373 (when (and (equal "file" (org-element-property :type link))
19374 (or include-linked
19375 (null (org-element-contents link)))
19376 (string-match-p file-extension-re
19377 (org-element-property :path link)))
19378 (let ((file (expand-file-name
19379 (org-link-unescape
19380 (org-element-property :path link)))))
19381 (when (file-exists-p file)
19382 (let ((width
19383 ;; Apply `org-image-actual-width' specifications.
19384 (cond
19385 ((not (image-type-available-p 'imagemagick)) nil)
19386 ((eq org-image-actual-width t) nil)
19387 ((listp org-image-actual-width)
19389 ;; First try to find a width among
19390 ;; attributes associated to the paragraph
19391 ;; containing link.
19392 (let ((paragraph
19393 (let ((e link))
19394 (while (and (setq e (org-element-property
19395 :parent e))
19396 (not (eq (org-element-type e)
19397 'paragraph))))
19398 e)))
19399 (when paragraph
19400 (save-excursion
19401 (goto-char (org-element-property :begin paragraph))
19402 (when
19403 (re-search-forward
19404 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19405 (org-element-property
19406 :post-affiliated paragraph)
19408 (string-to-number (match-string 1))))))
19409 ;; Otherwise, fall-back to provided number.
19410 (car org-image-actual-width)))
19411 ((numberp org-image-actual-width)
19412 org-image-actual-width)))
19413 (old (get-char-property-and-overlay
19414 (org-element-property :begin link)
19415 'org-image-overlay)))
19416 (if (and (car-safe old) refresh)
19417 (image-refresh (overlay-get (cdr old) 'display))
19418 (let ((image (create-image file
19419 (and width 'imagemagick)
19421 :width width)))
19422 (when image
19423 (let ((ov (make-overlay
19424 (org-element-property :begin link)
19425 (progn
19426 (goto-char
19427 (org-element-property :end link))
19428 (skip-chars-backward " \t")
19429 (point)))))
19430 (overlay-put ov 'display image)
19431 (overlay-put ov 'face 'default)
19432 (overlay-put ov 'org-image-overlay t)
19433 (overlay-put
19434 ov 'modification-hooks
19435 (list 'org-display-inline-remove-overlay))
19436 (push ov org-inline-image-overlays)))))))))))))))
19438 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19439 "Remove inline-display overlay if a corresponding region is modified."
19440 (let ((inhibit-modification-hooks t))
19441 (when (and ov after)
19442 (delete ov org-inline-image-overlays)
19443 (delete-overlay ov))))
19445 (defun org-remove-inline-images ()
19446 "Remove inline display of images."
19447 (interactive)
19448 (mapc #'delete-overlay org-inline-image-overlays)
19449 (setq org-inline-image-overlays nil))
19451 ;;;; Key bindings
19453 ;; Outline functions from `outline-mode-prefix-map'
19454 ;; that can be remapped in Org:
19455 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19456 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19457 (define-key org-mode-map [remap outline-forward-same-level]
19458 'org-forward-heading-same-level)
19459 (define-key org-mode-map [remap outline-backward-same-level]
19460 'org-backward-heading-same-level)
19461 (define-key org-mode-map [remap outline-show-branches]
19462 'org-kill-note-or-show-branches)
19463 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19464 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19465 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19466 (define-key org-mode-map [remap outline-next-visible-heading]
19467 'org-next-visible-heading)
19468 (define-key org-mode-map [remap outline-previous-visible-heading]
19469 'org-previous-visible-heading)
19470 (define-key org-mode-map [remap show-children] 'org-show-children)
19472 ;; Outline functions from `outline-mode-prefix-map' that can not
19473 ;; be remapped in Org:
19475 ;; - the column "key binding" shows whether the Outline function is still
19476 ;; available in Org mode on the same key that it has been bound to in
19477 ;; Outline mode:
19478 ;; - "overridden": key used for a different functionality in Org mode
19479 ;; - else: key still bound to the same Outline function in Org mode
19481 ;; | Outline function | key binding | Org replacement |
19482 ;; |------------------------------------+-------------+--------------------------|
19483 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19484 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19485 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19486 ;; | `show-entry' | overridden | no replacement |
19487 ;; | `show-branches' | `C-c C-k' | still same function |
19488 ;; | `show-subtree' | overridden | visibility cycling |
19489 ;; | `show-all' | overridden | no replacement |
19490 ;; | `hide-subtree' | overridden | visibility cycling |
19491 ;; | `hide-body' | overridden | no replacement |
19492 ;; | `hide-entry' | overridden | visibility cycling |
19493 ;; | `hide-leaves' | overridden | no replacement |
19494 ;; | `hide-sublevels' | overridden | no replacement |
19495 ;; | `hide-other' | overridden | no replacement |
19497 ;; Make `C-c C-x' a prefix key
19498 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19500 ;; TAB key with modifiers
19501 (org-defkey org-mode-map "\C-i" 'org-cycle)
19502 (org-defkey org-mode-map [(tab)] 'org-cycle)
19503 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19504 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19505 ;; The following line is necessary under Suse GNU/Linux
19506 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19507 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19508 (define-key org-mode-map [backtab] 'org-shifttab)
19510 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19511 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19512 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19514 ;; Cursor keys with modifiers
19515 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19516 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19517 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19518 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19520 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19521 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19522 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19523 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19524 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19525 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19527 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19528 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19529 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19530 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19532 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19533 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19534 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19535 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19537 ;; Babel keys
19538 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19539 (dolist (pair org-babel-key-bindings)
19540 (define-key org-babel-map (car pair) (cdr pair)))
19542 ;;; Extra keys for tty access.
19543 ;; We only set them when really needed because otherwise the
19544 ;; menus don't show the simple keys
19546 (when (or org-use-extra-keys (not window-system))
19547 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19548 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19549 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19550 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19551 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19552 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19553 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19554 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19555 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19556 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19557 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19558 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19559 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19560 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19561 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19562 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19563 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19564 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19565 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19566 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19567 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19568 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19569 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19570 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19571 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19572 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19573 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19574 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19576 ;; All the other keys
19578 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19579 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19580 (if (boundp 'narrow-map)
19581 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19582 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19583 (if (boundp 'narrow-map)
19584 (org-defkey narrow-map "b" 'org-narrow-to-block)
19585 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19586 (if (boundp 'narrow-map)
19587 (org-defkey narrow-map "e" 'org-narrow-to-element)
19588 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19589 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19590 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19591 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19592 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19593 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19594 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19595 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19596 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19597 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19598 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19599 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19600 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19601 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19602 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19603 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19604 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19605 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19606 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19607 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19608 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19609 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19610 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19611 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19612 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19613 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19614 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19615 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19616 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19617 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19618 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19619 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19620 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19621 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19622 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19623 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19624 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19625 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19626 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19627 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19628 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19629 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19630 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19631 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19632 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19633 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19634 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19635 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19636 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19637 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19638 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19639 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19640 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19641 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19642 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19643 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19644 (org-defkey org-mode-map "\C-c^" 'org-sort)
19645 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19646 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19647 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19648 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19649 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19650 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19651 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19652 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19653 (org-defkey org-mode-map "\C-m" 'org-return)
19654 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19655 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19656 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19657 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19658 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19659 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19660 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19661 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19662 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19663 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19664 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19665 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19666 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19667 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19668 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19669 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19670 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19671 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19672 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19673 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19674 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19675 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19676 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19677 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19678 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19680 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19681 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19682 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19684 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19685 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19686 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19687 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19688 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19689 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19690 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19691 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19692 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19693 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19694 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19695 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19696 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19697 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19698 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19699 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19700 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19701 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19702 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19703 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19704 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19705 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19707 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19708 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19709 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19710 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19711 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19713 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19715 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19717 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19718 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19720 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19723 (defconst org-speed-commands-default
19725 ("Outline Navigation")
19726 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19727 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19728 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19729 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19730 ("F" . org-next-block)
19731 ("B" . org-previous-block)
19732 ("u" . (org-speed-move-safe 'outline-up-heading))
19733 ("j" . org-goto)
19734 ("g" . (org-refile t))
19735 ("Outline Visibility")
19736 ("c" . org-cycle)
19737 ("C" . org-shifttab)
19738 (" " . org-display-outline-path)
19739 ("s" . org-narrow-to-subtree)
19740 ("=" . org-columns)
19741 ("Outline Structure Editing")
19742 ("U" . org-metaup)
19743 ("D" . org-metadown)
19744 ("r" . org-metaright)
19745 ("l" . org-metaleft)
19746 ("R" . org-shiftmetaright)
19747 ("L" . org-shiftmetaleft)
19748 ("i" . (progn (forward-char 1) (call-interactively
19749 'org-insert-heading-respect-content)))
19750 ("^" . org-sort)
19751 ("w" . org-refile)
19752 ("a" . org-archive-subtree-default-with-confirmation)
19753 ("@" . org-mark-subtree)
19754 ("#" . org-toggle-comment)
19755 ("Clock Commands")
19756 ("I" . org-clock-in)
19757 ("O" . org-clock-out)
19758 ("Meta Data Editing")
19759 ("t" . org-todo)
19760 ("," . (org-priority))
19761 ("0" . (org-priority ?\ ))
19762 ("1" . (org-priority ?A))
19763 ("2" . (org-priority ?B))
19764 ("3" . (org-priority ?C))
19765 (":" . org-set-tags-command)
19766 ("e" . org-set-effort)
19767 ("E" . org-inc-effort)
19768 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19769 (org-entry-put (point) "APPT_WARNTIME" m)))
19770 ("Agenda Views etc")
19771 ("v" . org-agenda)
19772 ("/" . org-sparse-tree)
19773 ("Misc")
19774 ("o" . org-open-at-point)
19775 ("?" . org-speed-command-help)
19776 ("<" . (org-agenda-set-restriction-lock 'subtree))
19777 (">" . (org-agenda-remove-restriction-lock))
19779 "The default speed commands.")
19781 (defun org-print-speed-command (e)
19782 (if (> (length (car e)) 1)
19783 (progn
19784 (princ "\n")
19785 (princ (car e))
19786 (princ "\n")
19787 (princ (make-string (length (car e)) ?-))
19788 (princ "\n"))
19789 (princ (car e))
19790 (princ " ")
19791 (if (symbolp (cdr e))
19792 (princ (symbol-name (cdr e)))
19793 (prin1 (cdr e)))
19794 (princ "\n")))
19796 (defun org-speed-command-help ()
19797 "Show the available speed commands."
19798 (interactive)
19799 (if (not org-use-speed-commands)
19800 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19801 (with-output-to-temp-buffer "*Help*"
19802 (princ "User-defined Speed commands\n===========================\n")
19803 (mapc #'org-print-speed-command org-speed-commands-user)
19804 (princ "\n")
19805 (princ "Built-in Speed commands\n=======================\n")
19806 (mapc #'org-print-speed-command org-speed-commands-default))
19807 (with-current-buffer "*Help*"
19808 (setq truncate-lines t))))
19810 (defun org-speed-move-safe (cmd)
19811 "Execute CMD, but make sure that the cursor always ends up in a headline.
19812 If not, return to the original position and throw an error."
19813 (interactive)
19814 (let ((pos (point)))
19815 (call-interactively cmd)
19816 (unless (and (bolp) (org-at-heading-p))
19817 (goto-char pos)
19818 (error "Boundary reached while executing %s" cmd))))
19820 (defvar org-self-insert-command-undo-counter 0)
19822 (defvar org-table-auto-blank-field) ; defined in org-table.el
19823 (defvar org-speed-command nil)
19825 (defun org-speed-command-activate (keys)
19826 "Hook for activating single-letter speed commands.
19827 `org-speed-commands-default' specifies a minimal command set.
19828 Use `org-speed-commands-user' for further customization."
19829 (when (or (and (bolp) (looking-at org-outline-regexp))
19830 (and (functionp org-use-speed-commands)
19831 (funcall org-use-speed-commands)))
19832 (cdr (assoc keys (append org-speed-commands-user
19833 org-speed-commands-default)))))
19835 (defun org-babel-speed-command-activate (keys)
19836 "Hook for activating single-letter code block commands."
19837 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19838 (cdr (assoc keys org-babel-key-bindings))))
19840 (defcustom org-speed-command-hook
19841 '(org-speed-command-activate org-babel-speed-command-activate)
19842 "Hook for activating speed commands at strategic locations.
19843 Hook functions are called in sequence until a valid handler is
19844 found.
19846 Each hook takes a single argument, a user-pressed command key
19847 which is also a `self-insert-command' from the global map.
19849 Within the hook, examine the cursor position and the command key
19850 and return nil or a valid handler as appropriate. Handler could
19851 be one of an interactive command, a function, or a form.
19853 Set `org-use-speed-commands' to non-nil value to enable this
19854 hook. The default setting is `org-speed-command-activate'."
19855 :group 'org-structure
19856 :version "24.1"
19857 :type 'hook)
19859 (defun org-self-insert-command (N)
19860 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19861 If the cursor is in a table looking at whitespace, the whitespace is
19862 overwritten, and the table is not marked as requiring realignment."
19863 (interactive "p")
19864 (org-check-before-invisible-edit 'insert)
19865 (cond
19866 ((and org-use-speed-commands
19867 (let ((kv (this-command-keys-vector)))
19868 (setq org-speed-command
19869 (run-hook-with-args-until-success
19870 'org-speed-command-hook
19871 (make-string 1 (aref kv (1- (length kv))))))))
19872 (cond
19873 ((commandp org-speed-command)
19874 (setq this-command org-speed-command)
19875 (call-interactively org-speed-command))
19876 ((functionp org-speed-command)
19877 (funcall org-speed-command))
19878 ((and org-speed-command (listp org-speed-command))
19879 (eval org-speed-command))
19880 (t (let (org-use-speed-commands)
19881 (call-interactively 'org-self-insert-command)))))
19882 ((and
19883 (org-at-table-p)
19884 (eq N 1)
19885 (not (org-region-active-p))
19886 (progn
19887 ;; Check if we blank the field, and if that triggers align.
19888 (and (featurep 'org-table) org-table-auto-blank-field
19889 (memq last-command
19890 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19891 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19892 ;; Got extra space, this field does not determine
19893 ;; column width.
19894 (let (org-table-may-need-update) (org-table-blank-field))
19895 ;; No extra space, this field may determine column
19896 ;; width.
19897 (org-table-blank-field)))
19899 (looking-at "[^|\n]* \\( \\)|"))
19900 ;; There is room for insertion without re-aligning the table.
19901 (delete-region (match-beginning 1) (match-end 1))
19902 (self-insert-command N))
19904 (setq org-table-may-need-update t)
19905 (self-insert-command N)
19906 (org-fix-tags-on-the-fly)
19907 (when org-self-insert-cluster-for-undo
19908 (if (not (eq last-command 'org-self-insert-command))
19909 (setq org-self-insert-command-undo-counter 1)
19910 (if (>= org-self-insert-command-undo-counter 20)
19911 (setq org-self-insert-command-undo-counter 1)
19912 (and (> org-self-insert-command-undo-counter 0)
19913 buffer-undo-list (listp buffer-undo-list)
19914 (not (cadr buffer-undo-list)) ; remove nil entry
19915 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19916 (setq org-self-insert-command-undo-counter
19917 (1+ org-self-insert-command-undo-counter))))))))
19919 (defun org-check-before-invisible-edit (kind)
19920 "Check is editing if kind KIND would be dangerous with invisible text around.
19921 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19922 ;; First, try to get out of here as quickly as possible, to reduce overhead
19923 (when (and org-catch-invisible-edits
19924 (or (not (boundp 'visible-mode)) (not visible-mode))
19925 (or (get-char-property (point) 'invisible)
19926 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19927 ;; OK, we need to take a closer look. Do not consider
19928 ;; invisibility obtained through text properties (e.g., link
19929 ;; fontification), as it cannot be toggled.
19930 (let* ((invisible-at-point
19931 (pcase (get-char-property-and-overlay (point) 'invisible)
19932 (`(,_ . ,(and (pred overlayp) o)) o)))
19933 ;; Assume that point cannot land in the middle of an
19934 ;; overlay, or between two overlays.
19935 (invisible-before-point
19936 (and (not invisible-at-point)
19937 (not (bobp))
19938 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19939 (`(,_ . ,(and (pred overlayp) o)) o))))
19940 (border-and-ok-direction
19942 ;; Check if we are acting predictably before invisible
19943 ;; text.
19944 (and invisible-at-point
19945 (memq kind '(insert delete-backward)))
19946 ;; Check if we are acting predictably after invisible text
19947 ;; This works not well, and I have turned it off. It seems
19948 ;; better to always show and stop after invisible text.
19949 ;; (and (not invisible-at-point) invisible-before-point
19950 ;; (memq kind '(insert delete)))
19952 (when (or invisible-at-point invisible-before-point)
19953 (when (eq org-catch-invisible-edits 'error)
19954 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19955 (if (and org-custom-properties-overlays
19956 (y-or-n-p "Display invisible properties in this buffer? "))
19957 (org-toggle-custom-properties-visibility)
19958 ;; Make the area visible
19959 (save-excursion
19960 (when invisible-before-point
19961 (goto-char
19962 (previous-single-char-property-change (point) 'invisible)))
19963 ;; Remove whatever overlay is currently making yet-to-be
19964 ;; edited text invisible. Also remove nested invisibility
19965 ;; related overlays.
19966 (delete-overlay (or invisible-at-point invisible-before-point))
19967 (let ((origin (if invisible-at-point (point) (1- (point)))))
19968 (while (pcase (get-char-property-and-overlay origin 'invisible)
19969 (`(,_ . ,(and (pred overlayp) o))
19970 (delete-overlay o)
19971 t)))))
19972 (cond
19973 ((eq org-catch-invisible-edits 'show)
19974 ;; That's it, we do the edit after showing
19975 (message
19976 "Unfolding invisible region around point before editing")
19977 (sit-for 1))
19978 ((and (eq org-catch-invisible-edits 'smart)
19979 border-and-ok-direction)
19980 (message "Unfolding invisible region around point before editing"))
19982 ;; Don't do the edit, make the user repeat it in full visibility
19983 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19985 (defun org-fix-tags-on-the-fly ()
19986 "Align tags in headline at point.
19987 Unlike to `org-set-tags', it ignores region and sorting."
19988 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19989 (org-at-heading-p))
19990 (let ((org-ignore-region t)
19991 (org-tags-sort-function nil))
19992 (org-set-tags nil t))))
19994 (defun org-delete-backward-char (N)
19995 "Like `delete-backward-char', insert whitespace at field end in tables.
19996 When deleting backwards, in tables this function will insert whitespace in
19997 front of the next \"|\" separator, to keep the table aligned. The table will
19998 still be marked for re-alignment if the field did fill the entire column,
19999 because, in this case the deletion might narrow the column."
20000 (interactive "p")
20001 (save-match-data
20002 (org-check-before-invisible-edit 'delete-backward)
20003 (if (and (org-at-table-p)
20004 (eq N 1)
20005 (string-match "|" (buffer-substring (point-at-bol) (point)))
20006 (looking-at ".*?|"))
20007 (let ((pos (point))
20008 (noalign (looking-at "[^|\n\r]* |"))
20009 (c org-table-may-need-update))
20010 (backward-delete-char N)
20011 (unless overwrite-mode
20012 (skip-chars-forward "^|")
20013 (insert " ")
20014 (goto-char (1- pos)))
20015 ;; noalign: if there were two spaces at the end, this field
20016 ;; does not determine the width of the column.
20017 (when noalign (setq org-table-may-need-update c)))
20018 (backward-delete-char N)
20019 (org-fix-tags-on-the-fly))))
20021 (defun org-delete-char (N)
20022 "Like `delete-char', but insert whitespace at field end in tables.
20023 When deleting characters, in tables this function will insert whitespace in
20024 front of the next \"|\" separator, to keep the table aligned. The table will
20025 still be marked for re-alignment if the field did fill the entire column,
20026 because, in this case the deletion might narrow the column."
20027 (interactive "p")
20028 (save-match-data
20029 (org-check-before-invisible-edit 'delete)
20030 (if (and (org-at-table-p)
20031 (not (bolp))
20032 (not (= (char-after) ?|))
20033 (eq N 1))
20034 (if (looking-at ".*?|")
20035 (let ((pos (point))
20036 (noalign (looking-at "[^|\n\r]* |"))
20037 (c org-table-may-need-update))
20038 (replace-match
20039 (concat (substring (match-string 0) 1 -1) " |") nil t)
20040 (goto-char pos)
20041 ;; noalign: if there were two spaces at the end, this field
20042 ;; does not determine the width of the column.
20043 (when noalign (setq org-table-may-need-update c)))
20044 (delete-char N))
20045 (delete-char N)
20046 (org-fix-tags-on-the-fly))))
20048 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20049 (put 'org-self-insert-command 'delete-selection
20050 (lambda ()
20051 (not (run-hook-with-args-until-success
20052 'self-insert-uses-region-functions))))
20053 (put 'orgtbl-self-insert-command 'delete-selection
20054 (lambda ()
20055 (not (run-hook-with-args-until-success
20056 'self-insert-uses-region-functions))))
20057 (put 'org-delete-char 'delete-selection 'supersede)
20058 (put 'org-delete-backward-char 'delete-selection 'supersede)
20059 (put 'org-yank 'delete-selection 'yank)
20061 ;; Make `flyspell-mode' delay after some commands
20062 (put 'org-self-insert-command 'flyspell-delayed t)
20063 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20064 (put 'org-delete-char 'flyspell-delayed t)
20065 (put 'org-delete-backward-char 'flyspell-delayed t)
20067 ;; Make pabbrev-mode expand after Org mode commands
20068 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20069 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20071 (defun org-remap (map &rest commands)
20072 "In MAP, remap the functions given in COMMANDS.
20073 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20074 (let (new old)
20075 (while commands
20076 (setq old (pop commands) new (pop commands))
20077 (org-defkey map (vector 'remap old) new))))
20079 (defun org-transpose-words ()
20080 "Transpose words for Org.
20081 This uses the `org-mode-transpose-word-syntax-table' syntax
20082 table, which interprets characters in `org-emphasis-alist' as
20083 word constituents."
20084 (interactive)
20085 (with-syntax-table org-mode-transpose-word-syntax-table
20086 (call-interactively 'transpose-words)))
20087 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20089 (when (eq org-enable-table-editor 'optimized)
20090 ;; If the user wants maximum table support, we need to hijack
20091 ;; some standard editing functions
20092 (org-remap org-mode-map
20093 'self-insert-command 'org-self-insert-command
20094 'delete-char 'org-delete-char
20095 'delete-backward-char 'org-delete-backward-char)
20096 (org-defkey org-mode-map "|" 'org-force-self-insert))
20098 (defvar org-ctrl-c-ctrl-c-hook nil
20099 "Hook for functions attaching themselves to `C-c C-c'.
20101 This can be used to add additional functionality to the C-c C-c
20102 key which executes context-dependent commands. This hook is run
20103 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20104 run after the last test.
20106 Each function will be called with no arguments. The function
20107 must check if the context is appropriate for it to act. If yes,
20108 it should do its thing and then return a non-nil value. If the
20109 context is wrong, just do nothing and return nil.")
20111 (defvar org-ctrl-c-ctrl-c-final-hook nil
20112 "Hook for functions attaching themselves to `C-c C-c'.
20114 This can be used to add additional functionality to the C-c C-c
20115 key which executes context-dependent commands. This hook is run
20116 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20117 before the first test.
20119 Each function will be called with no arguments. The function
20120 must check if the context is appropriate for it to act. If yes,
20121 it should do its thing and then return a non-nil value. If the
20122 context is wrong, just do nothing and return nil.")
20124 (defvar org-tab-first-hook nil
20125 "Hook for functions to attach themselves to TAB.
20126 See `org-ctrl-c-ctrl-c-hook' for more information.
20127 This hook runs as the first action when TAB is pressed, even before
20128 `org-cycle' messes around with the `outline-regexp' to cater for
20129 inline tasks and plain list item folding.
20130 If any function in this hook returns t, any other actions that
20131 would have been caused by TAB (such as table field motion or visibility
20132 cycling) will not occur.")
20134 (defvar org-tab-after-check-for-table-hook nil
20135 "Hook for functions to attach themselves to TAB.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.
20137 This hook runs after it has been established that the cursor is not in a
20138 table, but before checking if the cursor is in a headline or if global cycling
20139 should be done.
20140 If any function in this hook returns t, not other actions like visibility
20141 cycling will be done.")
20143 (defvar org-tab-after-check-for-cycling-hook nil
20144 "Hook for functions to attach themselves to TAB.
20145 See `org-ctrl-c-ctrl-c-hook' for more information.
20146 This hook runs after it has been established that not table field motion and
20147 not visibility should be done because of current context. This is probably
20148 the place where a package like yasnippets can hook in.")
20150 (defvar org-tab-before-tab-emulation-hook nil
20151 "Hook for functions to attach themselves to TAB.
20152 See `org-ctrl-c-ctrl-c-hook' for more information.
20153 This hook runs after every other options for TAB have been exhausted, but
20154 before indentation and \t insertion takes place.")
20156 (defvar org-metaleft-hook nil
20157 "Hook for functions attaching themselves to `M-left'.
20158 See `org-ctrl-c-ctrl-c-hook' for more information.")
20159 (defvar org-metaright-hook nil
20160 "Hook for functions attaching themselves to `M-right'.
20161 See `org-ctrl-c-ctrl-c-hook' for more information.")
20162 (defvar org-metaup-hook nil
20163 "Hook for functions attaching themselves to `M-up'.
20164 See `org-ctrl-c-ctrl-c-hook' for more information.")
20165 (defvar org-metadown-hook nil
20166 "Hook for functions attaching themselves to `M-down'.
20167 See `org-ctrl-c-ctrl-c-hook' for more information.")
20168 (defvar org-shiftmetaleft-hook nil
20169 "Hook for functions attaching themselves to `M-S-left'.
20170 See `org-ctrl-c-ctrl-c-hook' for more information.")
20171 (defvar org-shiftmetaright-hook nil
20172 "Hook for functions attaching themselves to `M-S-right'.
20173 See `org-ctrl-c-ctrl-c-hook' for more information.")
20174 (defvar org-shiftmetaup-hook nil
20175 "Hook for functions attaching themselves to `M-S-up'.
20176 See `org-ctrl-c-ctrl-c-hook' for more information.")
20177 (defvar org-shiftmetadown-hook nil
20178 "Hook for functions attaching themselves to `M-S-down'.
20179 See `org-ctrl-c-ctrl-c-hook' for more information.")
20180 (defvar org-metareturn-hook nil
20181 "Hook for functions attaching themselves to `M-RET'.
20182 See `org-ctrl-c-ctrl-c-hook' for more information.")
20183 (defvar org-shiftup-hook nil
20184 "Hook for functions attaching themselves to `S-up'.
20185 See `org-ctrl-c-ctrl-c-hook' for more information.")
20186 (defvar org-shiftup-final-hook nil
20187 "Hook for functions attaching themselves to `S-up'.
20188 This one runs after all other options except shift-select have been excluded.
20189 See `org-ctrl-c-ctrl-c-hook' for more information.")
20190 (defvar org-shiftdown-hook nil
20191 "Hook for functions attaching themselves to `S-down'.
20192 See `org-ctrl-c-ctrl-c-hook' for more information.")
20193 (defvar org-shiftdown-final-hook nil
20194 "Hook for functions attaching themselves to `S-down'.
20195 This one runs after all other options except shift-select have been excluded.
20196 See `org-ctrl-c-ctrl-c-hook' for more information.")
20197 (defvar org-shiftleft-hook nil
20198 "Hook for functions attaching themselves to `S-left'.
20199 See `org-ctrl-c-ctrl-c-hook' for more information.")
20200 (defvar org-shiftleft-final-hook nil
20201 "Hook for functions attaching themselves to `S-left'.
20202 This one runs after all other options except shift-select have been excluded.
20203 See `org-ctrl-c-ctrl-c-hook' for more information.")
20204 (defvar org-shiftright-hook nil
20205 "Hook for functions attaching themselves to `S-right'.
20206 See `org-ctrl-c-ctrl-c-hook' for more information.")
20207 (defvar org-shiftright-final-hook nil
20208 "Hook for functions attaching themselves to `S-right'.
20209 This one runs after all other options except shift-select have been excluded.
20210 See `org-ctrl-c-ctrl-c-hook' for more information.")
20212 (defun org-modifier-cursor-error ()
20213 "Throw an error, a modified cursor command was applied in wrong context."
20214 (user-error "This command is active in special context like tables, headlines or items"))
20216 (defun org-shiftselect-error ()
20217 "Throw an error because Shift-Cursor command was applied in wrong context."
20218 (if (and (boundp 'shift-select-mode) shift-select-mode)
20219 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20220 (user-error "This command works only in special context like headlines or timestamps")))
20222 (defun org-call-for-shift-select (cmd)
20223 (let ((this-command-keys-shift-translated t))
20224 (call-interactively cmd)))
20226 (defun org-shifttab (&optional arg)
20227 "Global visibility cycling or move to previous table field.
20228 Call `org-table-previous-field' within a table.
20229 When ARG is nil, cycle globally through visibility states.
20230 When ARG is a numeric prefix, show contents of this level."
20231 (interactive "P")
20232 (cond
20233 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20234 ((integerp arg)
20235 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20236 (message "Content view to level: %d" arg)
20237 (org-content (prefix-numeric-value arg2))
20238 (org-cycle-show-empty-lines t)
20239 (setq org-cycle-global-status 'overview)))
20240 (t (call-interactively 'org-global-cycle))))
20242 (defun org-shiftmetaleft ()
20243 "Promote subtree or delete table column.
20244 Calls `org-promote-subtree', `org-outdent-item-tree', or
20245 `org-table-delete-column', depending on context. See the
20246 individual commands for more information."
20247 (interactive)
20248 (cond
20249 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20250 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20251 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20252 ((if (not (org-region-active-p)) (org-at-item-p)
20253 (save-excursion (goto-char (region-beginning))
20254 (org-at-item-p)))
20255 (call-interactively 'org-outdent-item-tree))
20256 (t (org-modifier-cursor-error))))
20258 (defun org-shiftmetaright ()
20259 "Demote subtree or insert table column.
20260 Calls `org-demote-subtree', `org-indent-item-tree', or
20261 `org-table-insert-column', depending on context. See the
20262 individual commands for more information."
20263 (interactive)
20264 (cond
20265 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20266 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20267 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20268 ((if (not (org-region-active-p)) (org-at-item-p)
20269 (save-excursion (goto-char (region-beginning))
20270 (org-at-item-p)))
20271 (call-interactively 'org-indent-item-tree))
20272 (t (org-modifier-cursor-error))))
20274 (defun org-shiftmetaup (&optional _arg)
20275 "Drag the line at point up.
20276 In a table, kill the current row.
20277 On a clock timestamp, update the value of the timestamp like `S-<up>'
20278 but also adjust the previous clocked item in the clock history.
20279 Everywhere else, drag the line at point up."
20280 (interactive "P")
20281 (cond
20282 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20283 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20284 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20285 (call-interactively 'org-timestamp-up)))
20286 (t (call-interactively 'org-drag-line-backward))))
20288 (defun org-shiftmetadown (&optional _arg)
20289 "Drag the line at point down.
20290 In a table, insert an empty row at the current line.
20291 On a clock timestamp, update the value of the timestamp like `S-<down>'
20292 but also adjust the previous clocked item in the clock history.
20293 Everywhere else, drag the line at point down."
20294 (interactive "P")
20295 (cond
20296 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20297 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20298 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20299 (call-interactively 'org-timestamp-down)))
20300 (t (call-interactively 'org-drag-line-forward))))
20302 (defsubst org-hidden-tree-error ()
20303 (user-error
20304 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20306 (defun org-metaleft (&optional _arg)
20307 "Promote heading, list item at point or move table column left.
20309 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20310 depending on context. With no specific context, calls the Emacs
20311 default `backward-word'. See the individual commands for more
20312 information.
20314 This function runs the hook `org-metaleft-hook' as a first step,
20315 and returns at first non-nil value."
20316 (interactive "P")
20317 (cond
20318 ((run-hook-with-args-until-success 'org-metaleft-hook))
20319 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20320 ((org-with-limited-levels
20321 (or (org-at-heading-p)
20322 (and (org-region-active-p)
20323 (save-excursion
20324 (goto-char (region-beginning))
20325 (org-at-heading-p)))))
20326 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20327 (call-interactively 'org-do-promote))
20328 ;; At an inline task.
20329 ((org-at-heading-p)
20330 (call-interactively 'org-inlinetask-promote))
20331 ((or (org-at-item-p)
20332 (and (org-region-active-p)
20333 (save-excursion
20334 (goto-char (region-beginning))
20335 (org-at-item-p))))
20336 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20337 (call-interactively 'org-outdent-item))
20338 (t (call-interactively 'backward-word))))
20340 (defun org-metaright (&optional _arg)
20341 "Demote heading, list item at point or move table column right.
20343 In front of a drawer or a block keyword, indent it correctly.
20345 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20346 `org-indent-drawer' or `org-indent-block' depending on context.
20347 With no specific context, calls the Emacs default `forward-word'.
20348 See the individual commands for more information.
20350 This function runs the hook `org-metaright-hook' as a first step,
20351 and returns at first non-nil value."
20352 (interactive "P")
20353 (cond
20354 ((run-hook-with-args-until-success 'org-metaright-hook))
20355 ((org-at-table-p) (call-interactively 'org-table-move-column))
20356 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20357 ((org-at-block-p) (call-interactively 'org-indent-block))
20358 ((org-with-limited-levels
20359 (or (org-at-heading-p)
20360 (and (org-region-active-p)
20361 (save-excursion
20362 (goto-char (region-beginning))
20363 (org-at-heading-p)))))
20364 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20365 (call-interactively 'org-do-demote))
20366 ;; At an inline task.
20367 ((org-at-heading-p)
20368 (call-interactively 'org-inlinetask-demote))
20369 ((or (org-at-item-p)
20370 (and (org-region-active-p)
20371 (save-excursion
20372 (goto-char (region-beginning))
20373 (org-at-item-p))))
20374 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20375 (call-interactively 'org-indent-item))
20376 (t (call-interactively 'forward-word))))
20378 (defun org-check-for-hidden (what)
20379 "Check if there are hidden headlines/items in the current visual line.
20380 WHAT can be either `headlines' or `items'. If the current line is
20381 an outline or item heading and it has a folded subtree below it,
20382 this function returns t, nil otherwise."
20383 (let ((re (cond
20384 ((eq what 'headlines) org-outline-regexp-bol)
20385 ((eq what 'items) (org-item-beginning-re))
20386 (t (error "This should not happen"))))
20387 beg end)
20388 (save-excursion
20389 (catch 'exit
20390 (unless (org-region-active-p)
20391 (setq beg (point-at-bol))
20392 (beginning-of-line 2)
20393 (while (and (not (eobp)) ;; this is like `next-line'
20394 (get-char-property (1- (point)) 'invisible))
20395 (beginning-of-line 2))
20396 (setq end (point))
20397 (goto-char beg)
20398 (goto-char (point-at-eol))
20399 (setq end (max end (point)))
20400 (while (re-search-forward re end t)
20401 (when (get-char-property (match-beginning 0) 'invisible)
20402 (throw 'exit t))))
20403 nil))))
20405 (defun org-metaup (&optional _arg)
20406 "Move subtree up or move table row up.
20407 Calls `org-move-subtree-up' or `org-table-move-row' or
20408 `org-move-item-up', depending on context. See the individual commands
20409 for more information."
20410 (interactive "P")
20411 (cond
20412 ((run-hook-with-args-until-success 'org-metaup-hook))
20413 ((org-region-active-p)
20414 (let* ((a (min (region-beginning) (region-end)))
20415 (b (1- (max (region-beginning) (region-end))))
20416 (c (save-excursion (goto-char a)
20417 (move-beginning-of-line 0)))
20418 (d (save-excursion (goto-char a)
20419 (move-end-of-line 0) (point))))
20420 (transpose-regions a b c d)
20421 (goto-char c)))
20422 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20423 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20424 ((org-at-item-p) (call-interactively 'org-move-item-up))
20425 (t (org-drag-element-backward))))
20427 (defun org-metadown (&optional _arg)
20428 "Move subtree down or move table row down.
20429 Calls `org-move-subtree-down' or `org-table-move-row' or
20430 `org-move-item-down', depending on context. See the individual
20431 commands for more information."
20432 (interactive "P")
20433 (cond
20434 ((run-hook-with-args-until-success 'org-metadown-hook))
20435 ((org-region-active-p)
20436 (let* ((a (min (region-beginning) (region-end)))
20437 (b (max (region-beginning) (region-end)))
20438 (c (save-excursion (goto-char b)
20439 (move-beginning-of-line 1)))
20440 (d (save-excursion (goto-char b)
20441 (move-end-of-line 1) (1+ (point)))))
20442 (transpose-regions a b c d)
20443 (goto-char d)))
20444 ((org-at-table-p) (call-interactively 'org-table-move-row))
20445 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20446 ((org-at-item-p) (call-interactively 'org-move-item-down))
20447 (t (org-drag-element-forward))))
20449 (defun org-shiftup (&optional arg)
20450 "Increase item in timestamp or increase priority of current headline.
20451 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20452 depending on context. See the individual commands for more information."
20453 (interactive "P")
20454 (cond
20455 ((run-hook-with-args-until-success 'org-shiftup-hook))
20456 ((and org-support-shift-select (org-region-active-p))
20457 (org-call-for-shift-select 'previous-line))
20458 ((org-at-timestamp-p 'lax)
20459 (call-interactively (if org-edit-timestamp-down-means-later
20460 'org-timestamp-down 'org-timestamp-up)))
20461 ((and (not (eq org-support-shift-select 'always))
20462 org-enable-priority-commands
20463 (org-at-heading-p))
20464 (call-interactively 'org-priority-up))
20465 ((and (not org-support-shift-select) (org-at-item-p))
20466 (call-interactively 'org-previous-item))
20467 ((org-clocktable-try-shift 'up arg))
20468 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20469 (org-support-shift-select
20470 (org-call-for-shift-select 'previous-line))
20471 (t (org-shiftselect-error))))
20473 (defun org-shiftdown (&optional arg)
20474 "Decrease item in timestamp or decrease priority of current headline.
20475 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20476 depending on context. See the individual commands for more information."
20477 (interactive "P")
20478 (cond
20479 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20480 ((and org-support-shift-select (org-region-active-p))
20481 (org-call-for-shift-select 'next-line))
20482 ((org-at-timestamp-p 'lax)
20483 (call-interactively (if org-edit-timestamp-down-means-later
20484 'org-timestamp-up 'org-timestamp-down)))
20485 ((and (not (eq org-support-shift-select 'always))
20486 org-enable-priority-commands
20487 (org-at-heading-p))
20488 (call-interactively 'org-priority-down))
20489 ((and (not org-support-shift-select) (org-at-item-p))
20490 (call-interactively 'org-next-item))
20491 ((org-clocktable-try-shift 'down arg))
20492 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20493 (org-support-shift-select
20494 (org-call-for-shift-select 'next-line))
20495 (t (org-shiftselect-error))))
20497 (defun org-shiftright (&optional arg)
20498 "Cycle the thing at point or in the current line, depending on context.
20499 Depending on context, this does one of the following:
20501 - switch a timestamp at point one day into the future
20502 - on a headline, switch to the next TODO keyword.
20503 - on an item, switch entire list to the next bullet type
20504 - on a property line, switch to the next allowed value
20505 - on a clocktable definition line, move time block into the future"
20506 (interactive "P")
20507 (cond
20508 ((run-hook-with-args-until-success 'org-shiftright-hook))
20509 ((and org-support-shift-select (org-region-active-p))
20510 (org-call-for-shift-select 'forward-char))
20511 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20512 ((and (not (eq org-support-shift-select 'always))
20513 (org-at-heading-p))
20514 (let ((org-inhibit-logging
20515 (not org-treat-S-cursor-todo-selection-as-state-change))
20516 (org-inhibit-blocking
20517 (not org-treat-S-cursor-todo-selection-as-state-change)))
20518 (org-call-with-arg 'org-todo 'right)))
20519 ((or (and org-support-shift-select
20520 (not (eq org-support-shift-select 'always))
20521 (org-at-item-bullet-p))
20522 (and (not org-support-shift-select) (org-at-item-p)))
20523 (org-call-with-arg 'org-cycle-list-bullet nil))
20524 ((and (not (eq org-support-shift-select 'always))
20525 (org-at-property-p))
20526 (call-interactively 'org-property-next-allowed-value))
20527 ((org-clocktable-try-shift 'right arg))
20528 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20529 (org-support-shift-select
20530 (org-call-for-shift-select 'forward-char))
20531 (t (org-shiftselect-error))))
20533 (defun org-shiftleft (&optional arg)
20534 "Cycle the thing at point or in the current line, depending on context.
20535 Depending on context, this does one of the following:
20537 - switch a timestamp at point one day into the past
20538 - on a headline, switch to the previous TODO keyword.
20539 - on an item, switch entire list to the previous bullet type
20540 - on a property line, switch to the previous allowed value
20541 - on a clocktable definition line, move time block into the past"
20542 (interactive "P")
20543 (cond
20544 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20545 ((and org-support-shift-select (org-region-active-p))
20546 (org-call-for-shift-select 'backward-char))
20547 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20548 ((and (not (eq org-support-shift-select 'always))
20549 (org-at-heading-p))
20550 (let ((org-inhibit-logging
20551 (not org-treat-S-cursor-todo-selection-as-state-change))
20552 (org-inhibit-blocking
20553 (not org-treat-S-cursor-todo-selection-as-state-change)))
20554 (org-call-with-arg 'org-todo 'left)))
20555 ((or (and org-support-shift-select
20556 (not (eq org-support-shift-select 'always))
20557 (org-at-item-bullet-p))
20558 (and (not org-support-shift-select) (org-at-item-p)))
20559 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20560 ((and (not (eq org-support-shift-select 'always))
20561 (org-at-property-p))
20562 (call-interactively 'org-property-previous-allowed-value))
20563 ((org-clocktable-try-shift 'left arg))
20564 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20565 (org-support-shift-select
20566 (org-call-for-shift-select 'backward-char))
20567 (t (org-shiftselect-error))))
20569 (defun org-shiftcontrolright ()
20570 "Switch to next TODO set."
20571 (interactive)
20572 (cond
20573 ((and org-support-shift-select (org-region-active-p))
20574 (org-call-for-shift-select 'forward-word))
20575 ((and (not (eq org-support-shift-select 'always))
20576 (org-at-heading-p))
20577 (org-call-with-arg 'org-todo 'nextset))
20578 (org-support-shift-select
20579 (org-call-for-shift-select 'forward-word))
20580 (t (org-shiftselect-error))))
20582 (defun org-shiftcontrolleft ()
20583 "Switch to previous TODO set."
20584 (interactive)
20585 (cond
20586 ((and org-support-shift-select (org-region-active-p))
20587 (org-call-for-shift-select 'backward-word))
20588 ((and (not (eq org-support-shift-select 'always))
20589 (org-at-heading-p))
20590 (org-call-with-arg 'org-todo 'previousset))
20591 (org-support-shift-select
20592 (org-call-for-shift-select 'backward-word))
20593 (t (org-shiftselect-error))))
20595 (defun org-shiftcontrolup (&optional n)
20596 "Change timestamps synchronously up in CLOCK log lines.
20597 Optional argument N tells to change by that many units."
20598 (interactive "P")
20599 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20600 (let (org-support-shift-select)
20601 (org-clock-timestamps-up n))
20602 (user-error "Not at a clock log")))
20604 (defun org-shiftcontroldown (&optional n)
20605 "Change timestamps synchronously down in CLOCK log lines.
20606 Optional argument N tells to change by that many units."
20607 (interactive "P")
20608 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20609 (let (org-support-shift-select)
20610 (org-clock-timestamps-down n))
20611 (user-error "Not at a clock log")))
20613 (defun org-increase-number-at-point (&optional inc)
20614 "Increment the number at point.
20615 With an optional prefix numeric argument INC, increment using
20616 this numeric value."
20617 (interactive "p")
20618 (if (not (number-at-point))
20619 (user-error "Not on a number")
20620 (unless inc (setq inc 1))
20621 (let ((pos (point))
20622 (beg (skip-chars-backward "-+^/*0-9eE."))
20623 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20624 (setq nap (buffer-substring-no-properties
20625 (+ pos beg) (+ pos beg end)))
20626 (delete-region (+ pos beg) (+ pos beg end))
20627 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20628 (when (org-at-table-p)
20629 (org-table-align)
20630 (org-table-end-of-field 1))))
20632 (defun org-decrease-number-at-point (&optional inc)
20633 "Decrement the number at point.
20634 With an optional prefix numeric argument INC, decrement using
20635 this numeric value."
20636 (interactive "p")
20637 (org-increase-number-at-point (- (or inc 1))))
20639 (defun org-ctrl-c-ret ()
20640 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20641 (interactive)
20642 (cond
20643 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20644 (t (call-interactively 'org-insert-heading))))
20646 (defun org-find-visible ()
20647 (let ((s (point)))
20648 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20649 (get-char-property s 'invisible)))
20651 (defun org-find-invisible ()
20652 (let ((s (point)))
20653 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20654 (not (get-char-property s 'invisible))))
20657 (defun org-copy-visible (beg end)
20658 "Copy the visible parts of the region."
20659 (interactive "r")
20660 (let (snippets s)
20661 (save-excursion
20662 (save-restriction
20663 (narrow-to-region beg end)
20664 (setq s (goto-char (point-min)))
20665 (while (not (= (point) (point-max)))
20666 (goto-char (org-find-invisible))
20667 (push (buffer-substring s (point)) snippets)
20668 (setq s (goto-char (org-find-visible))))))
20669 (kill-new (apply 'concat (nreverse snippets)))))
20671 (defun org-copy-special ()
20672 "Copy region in table or copy current subtree.
20673 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20674 context. See the individual commands for more information."
20675 (interactive)
20676 (call-interactively
20677 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20679 (defun org-cut-special ()
20680 "Cut region in table or cut current subtree.
20681 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20682 context. See the individual commands for more information."
20683 (interactive)
20684 (call-interactively
20685 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20687 (defun org-paste-special (arg)
20688 "Paste rectangular region into table, or past subtree relative to level.
20689 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20690 See the individual commands for more information."
20691 (interactive "P")
20692 (if (org-at-table-p)
20693 (org-table-paste-rectangle)
20694 (org-paste-subtree arg)))
20696 (defun org-edit-special (&optional arg)
20697 "Call a special editor for the element at point.
20698 When at a table, call the formula editor with `org-table-edit-formulas'.
20699 When in a source code block, call `org-edit-src-code'.
20700 When in a fixed-width region, call `org-edit-fixed-width-region'.
20701 When in an export block, call `org-edit-export-block'.
20702 When in a LaTeX environment, call `org-edit-latex-environment'.
20703 When at an #+INCLUDE keyword, visit the included file.
20704 When at a footnote reference, call `org-edit-footnote-reference'
20705 On a link, call `ffap' to visit the link at point.
20706 Otherwise, return a user error."
20707 (interactive "P")
20708 (let ((element (org-element-at-point)))
20709 (barf-if-buffer-read-only)
20710 (pcase (org-element-type element)
20711 (`src-block
20712 (if (not arg) (org-edit-src-code)
20713 (let* ((info (org-babel-get-src-block-info))
20714 (lang (nth 0 info))
20715 (params (nth 2 info))
20716 (session (cdr (assq :session params))))
20717 (if (not session) (org-edit-src-code)
20718 ;; At a src-block with a session and function called with
20719 ;; an ARG: switch to the buffer related to the inferior
20720 ;; process.
20721 (switch-to-buffer
20722 (funcall (intern (concat "org-babel-prep-session:" lang))
20723 session params))))))
20724 (`keyword
20725 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20726 (org-open-link-from-string
20727 (format "[[%s]]"
20728 (expand-file-name
20729 (let ((value (org-element-property :value element)))
20730 (cond ((org-file-url-p value)
20731 (user-error "The file is specified as a URL, cannot be edited"))
20732 ((not (org-string-nw-p value))
20733 (user-error "No file to edit"))
20734 ((string-match "\\`\"\\(.*?\\)\"" value)
20735 (match-string 1 value))
20736 ((string-match "\\`[^ \t\"]\\S-*" value)
20737 (match-string 0 value))
20738 (t (user-error "No valid file specified")))))))
20739 (user-error "No special environment to edit here")))
20740 (`table
20741 (if (eq (org-element-property :type element) 'table.el)
20742 (org-edit-table.el)
20743 (call-interactively 'org-table-edit-formulas)))
20744 ;; Only Org tables contain `table-row' type elements.
20745 (`table-row (call-interactively 'org-table-edit-formulas))
20746 (`example-block (org-edit-src-code))
20747 (`export-block (org-edit-export-block))
20748 (`fixed-width (org-edit-fixed-width-region))
20749 (`latex-environment (org-edit-latex-environment))
20751 ;; No notable element at point. Though, we may be at a link or
20752 ;; a footnote reference, which are objects. Thus, scan deeper.
20753 (let ((context (org-element-context element)))
20754 (pcase (org-element-type context)
20755 (`footnote-reference (org-edit-footnote-reference))
20756 (`inline-src-block (org-edit-inline-src-code))
20757 (`link (call-interactively #'ffap))
20758 (_ (user-error "No special environment to edit here"))))))))
20760 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20761 (defun org-ctrl-c-ctrl-c (&optional arg)
20762 "Set tags in headline, or update according to changed information at point.
20764 This command does many different things, depending on context:
20766 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20767 this is what we do.
20769 - If the cursor is on a statistics cookie, update it.
20771 - If the cursor is in a headline, prompt for tags and insert them
20772 into the current line, aligned to `org-tags-column'. When called
20773 with prefix arg, realign all tags in the current buffer.
20775 - If the cursor is in one of the special #+KEYWORD lines, this
20776 triggers scanning the buffer for these lines and updating the
20777 information.
20779 - If the cursor is inside a table, realign the table. This command
20780 works even if the automatic table editor has been turned off.
20782 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20783 the entire table.
20785 - If the cursor is at a footnote reference or definition, jump to
20786 the corresponding definition or references, respectively.
20788 - If the cursor is a the beginning of a dynamic block, update it.
20790 - If the current buffer is a capture buffer, close note and file it.
20792 - If the cursor is on a <<<target>>>, update radio targets and
20793 corresponding links in this buffer.
20795 - If the cursor is on a numbered item in a plain list, renumber the
20796 ordered list.
20798 - If the cursor is on a checkbox, toggle it.
20800 - If the cursor is on a code block, evaluate it. The variable
20801 `org-confirm-babel-evaluate' can be used to control prompting
20802 before code block evaluation, by default every code block
20803 evaluation requires confirmation. Code block evaluation can be
20804 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20805 (interactive "P")
20806 (cond
20807 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20808 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20809 (org-remove-occur-highlights)
20810 (message "Temporary highlights/overlays removed from current buffer"))
20811 ((and (local-variable-p 'org-finish-function)
20812 (fboundp org-finish-function))
20813 (funcall org-finish-function))
20814 ((org-babel-hash-at-point))
20815 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20817 (let* ((context
20818 (org-element-lineage
20819 (org-element-context)
20820 ;; Limit to supported contexts.
20821 '(babel-call clock dynamic-block footnote-definition
20822 footnote-reference inline-babel-call inline-src-block
20823 inlinetask item keyword node-property paragraph
20824 plain-list property-drawer radio-target src-block
20825 statistics-cookie table table-cell table-row
20826 timestamp)
20828 (type (org-element-type context)))
20829 ;; For convenience: at the first line of a paragraph on the same
20830 ;; line as an item, apply function on that item instead.
20831 (when (eq type 'paragraph)
20832 (let ((parent (org-element-property :parent context)))
20833 (when (and (eq (org-element-type parent) 'item)
20834 (= (line-beginning-position)
20835 (org-element-property :begin parent)))
20836 (setq context parent)
20837 (setq type 'item))))
20838 ;; Act according to type of element or object at point.
20840 ;; Do nothing on a blank line, except if it is contained in
20841 ;; a src block. Hence, we first check if point is in such
20842 ;; a block and then if it is at a blank line.
20843 (pcase type
20844 ((or `inline-src-block `src-block)
20845 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20846 (org-babel-eval-wipe-error-buffer)
20847 (org-babel-execute-src-block
20848 current-prefix-arg (org-babel-get-src-block-info nil context))))
20849 ((guard (org-match-line "[ \t]*$"))
20850 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20851 (user-error
20852 (substitute-command-keys
20853 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20854 ((or `babel-call `inline-babel-call)
20855 (let ((info (org-babel-lob-get-info context)))
20856 (when info (org-babel-execute-src-block nil info))))
20857 (`clock (org-clock-update-time-maybe))
20858 (`dynamic-block
20859 (save-excursion
20860 (goto-char (org-element-property :post-affiliated context))
20861 (org-update-dblock)))
20862 (`footnote-definition
20863 (goto-char (org-element-property :post-affiliated context))
20864 (call-interactively 'org-footnote-action))
20865 (`footnote-reference (call-interactively #'org-footnote-action))
20866 ((or `headline `inlinetask)
20867 (save-excursion (goto-char (org-element-property :begin context))
20868 (call-interactively #'org-set-tags)))
20869 (`item
20870 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20871 ;; unconditionally, whereas `C-u' will toggle its presence.
20872 ;; Without a universal argument, if the item has a checkbox,
20873 ;; toggle it. Otherwise repair the list.
20874 (let* ((box (org-element-property :checkbox context))
20875 (struct (org-element-property :structure context))
20876 (old-struct (copy-tree struct))
20877 (parents (org-list-parents-alist struct))
20878 (prevs (org-list-prevs-alist struct))
20879 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20880 (org-list-set-checkbox
20881 (org-element-property :begin context) struct
20882 (cond ((equal arg '(16)) "[-]")
20883 ((and (not box) (equal arg '(4))) "[ ]")
20884 ((or (not box) (equal arg '(4))) nil)
20885 ((eq box 'on) "[ ]")
20886 (t "[X]")))
20887 ;; Mimic `org-list-write-struct' but with grabbing a return
20888 ;; value from `org-list-struct-fix-box'.
20889 (org-list-struct-fix-ind struct parents 2)
20890 (org-list-struct-fix-item-end struct)
20891 (org-list-struct-fix-bul struct prevs)
20892 (org-list-struct-fix-ind struct parents)
20893 (let ((block-item
20894 (org-list-struct-fix-box struct parents prevs orderedp)))
20895 (if (and box (equal struct old-struct))
20896 (if (equal arg '(16))
20897 (message "Checkboxes already reset")
20898 (user-error "Cannot toggle this checkbox: %s"
20899 (if (eq box 'on)
20900 "all subitems checked"
20901 "unchecked subitems")))
20902 (org-list-struct-apply-struct struct old-struct)
20903 (org-update-checkbox-count-maybe))
20904 (when block-item
20905 (message "Checkboxes were removed due to empty box at line %d"
20906 (org-current-line block-item))))))
20907 (`keyword
20908 (let ((org-inhibit-startup-visibility-stuff t)
20909 (org-startup-align-all-tables nil))
20910 (when (boundp 'org-table-coordinate-overlays)
20911 (mapc #'delete-overlay org-table-coordinate-overlays)
20912 (setq org-table-coordinate-overlays nil))
20913 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20914 (message "Local setup has been refreshed"))
20915 (`plain-list
20916 ;; At a plain list, with a double C-u argument, set
20917 ;; checkboxes of each item to "[-]", whereas a single one
20918 ;; will toggle their presence according to the state of the
20919 ;; first item in the list. Without an argument, repair the
20920 ;; list.
20921 (let* ((begin (org-element-property :contents-begin context))
20922 (beginm (move-marker (make-marker) begin))
20923 (struct (org-element-property :structure context))
20924 (old-struct (copy-tree struct))
20925 (first-box (save-excursion
20926 (goto-char begin)
20927 (looking-at org-list-full-item-re)
20928 (match-string-no-properties 3)))
20929 (new-box (cond ((equal arg '(16)) "[-]")
20930 ((equal arg '(4)) (unless first-box "[ ]"))
20931 ((equal first-box "[X]") "[ ]")
20932 (t "[X]"))))
20933 (cond
20934 (arg
20935 (dolist (pos
20936 (org-list-get-all-items
20937 begin struct (org-list-prevs-alist struct)))
20938 (org-list-set-checkbox pos struct new-box)))
20939 ((and first-box (eq (point) begin))
20940 ;; For convenience, when point is at bol on the first
20941 ;; item of the list and no argument is provided, simply
20942 ;; toggle checkbox of that item, if any.
20943 (org-list-set-checkbox begin struct new-box)))
20944 (org-list-write-struct
20945 struct (org-list-parents-alist struct) old-struct)
20946 (org-update-checkbox-count-maybe)
20947 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20948 ((or `property-drawer `node-property)
20949 (call-interactively #'org-property-action))
20950 (`radio-target
20951 (call-interactively #'org-update-radio-target-regexp))
20952 (`statistics-cookie
20953 (call-interactively #'org-update-statistics-cookies))
20954 ((or `table `table-cell `table-row)
20955 ;; At a table, recalculate every field and align it. Also
20956 ;; send the table if necessary. If the table has
20957 ;; a `table.el' type, just give up. At a table row or cell,
20958 ;; maybe recalculate line but always align table.
20959 (if (eq (org-element-property :type context) 'table.el)
20960 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20961 Use `\\[org-edit-special]' to edit table.el tables"))
20962 (let ((org-enable-table-editor t))
20963 (if (or (eq type 'table)
20964 ;; Check if point is at a TBLFM line.
20965 (and (eq type 'table-row)
20966 (= (point) (org-element-property :end context))))
20967 (save-excursion
20968 (if (org-at-TBLFM-p)
20969 (progn (require 'org-table)
20970 (org-table-calc-current-TBLFM))
20971 (goto-char (org-element-property :contents-begin context))
20972 (org-call-with-arg 'org-table-recalculate (or arg t))
20973 (orgtbl-send-table 'maybe)))
20974 (org-table-maybe-eval-formula)
20975 (cond (arg (call-interactively #'org-table-recalculate))
20976 ((org-table-maybe-recalculate-line))
20977 (t (org-table-align)))))))
20978 (`timestamp (org-timestamp-change 0 'day))
20979 ((and `nil (guard (org-at-heading-p)))
20980 ;; When point is on an unsupported object type, we can miss
20981 ;; the fact that it also is at a heading. Handle it here.
20982 (call-interactively #'org-set-tags))
20983 ((guard
20984 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20986 (user-error
20987 (substitute-command-keys
20988 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20990 (defun org-mode-restart ()
20991 (interactive)
20992 (let ((indent-status (bound-and-true-p org-indent-mode)))
20993 (funcall major-mode)
20994 (hack-local-variables)
20995 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20996 (org-indent-mode -1))
20997 (org-reset-file-cache))
20998 (message "%s restarted" major-mode))
21000 (defun org-kill-note-or-show-branches ()
21001 "Abort storing current note, or call `outline-show-branches'."
21002 (interactive)
21003 (if (not org-finish-function)
21004 (progn
21005 (outline-hide-subtree)
21006 (call-interactively 'outline-show-branches))
21007 (let ((org-note-abort t))
21008 (funcall org-finish-function))))
21010 (defun org-delete-indentation (&optional arg)
21011 "Join current line to previous and fix whitespace at join.
21013 If previous line is a headline add to headline title. Otherwise
21014 the function calls `delete-indentation'.
21016 With a non-nil optional argument, join it to the following one."
21017 (interactive "*P")
21018 (if (save-excursion
21019 (beginning-of-line (if arg 1 0))
21020 (let ((case-fold-search nil))
21021 (looking-at org-complex-heading-regexp)))
21022 ;; At headline.
21023 (let ((tags-column (when (match-beginning 5)
21024 (save-excursion (goto-char (match-beginning 5))
21025 (current-column))))
21026 (string (concat " " (progn (when arg (forward-line 1))
21027 (org-trim (delete-and-extract-region
21028 (line-beginning-position)
21029 (line-end-position)))))))
21030 (unless (bobp) (delete-region (point) (1- (point))))
21031 (goto-char (or (match-end 4)
21032 (match-beginning 5)
21033 (match-end 0)))
21034 (skip-chars-backward " \t")
21035 (save-excursion (insert string))
21036 ;; Adjust alignment of tags.
21037 (cond
21038 ((not tags-column)) ;no tags
21039 (org-auto-align-tags (org-set-tags nil t))
21040 (t (org--align-tags-here tags-column)))) ;preserve tags column
21041 (delete-indentation arg)))
21043 (defun org-open-line (n)
21044 "Insert a new row in tables, call `open-line' elsewhere.
21045 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21046 As a special case, when a document starts with a table, allow to
21047 call `open-line' on the very first character."
21048 (interactive "*p")
21049 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21050 (org-table-insert-row)
21051 (open-line n)))
21053 (defun org-return (&optional indent)
21054 "Goto next table row or insert a newline.
21056 Calls `org-table-next-row' or `newline', depending on context.
21058 When optional INDENT argument is non-nil, call
21059 `newline-and-indent' instead of `newline'.
21061 When `org-return-follows-link' is non-nil and point is on
21062 a timestamp or a link, call `org-open-at-point'. However, it
21063 will not happen if point is in a table or on a \"dead\"
21064 object (e.g., within a comment). In these case, you need to use
21065 `org-open-at-point' directly."
21066 (interactive)
21067 (let ((context (if org-return-follows-link (org-element-context)
21068 (org-element-at-point))))
21069 (cond
21070 ;; In a table, call `org-table-next-row'.
21071 ((or (and (eq (org-element-type context) 'table)
21072 (>= (point) (org-element-property :contents-begin context))
21073 (< (point) (org-element-property :contents-end context)))
21074 (org-element-lineage context '(table-row table-cell) t))
21075 (org-table-justify-field-maybe)
21076 (call-interactively #'org-table-next-row))
21077 ;; On a link or a timestamp, call `org-open-at-point' if
21078 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21079 ;; locations, e.g., in a comment, as `org-open-at-point'.
21080 ((and org-return-follows-link
21081 (or (org-in-regexp org-ts-regexp-both nil t)
21082 (org-in-regexp org-tsr-regexp-both nil t)
21083 (org-in-regexp org-any-link-re nil t)))
21084 (call-interactively #'org-open-at-point))
21085 ;; Insert newline in heading, but preserve tags.
21086 ((and (not (bolp))
21087 (save-excursion (beginning-of-line)
21088 (let ((case-fold-search nil))
21089 (looking-at org-complex-heading-regexp))))
21090 ;; At headline. Split line. However, if point is on keyword,
21091 ;; priority cookie or tags, do not break any of them: add
21092 ;; a newline after the headline instead.
21093 (let ((tags-column (and (match-beginning 5)
21094 (save-excursion (goto-char (match-beginning 5))
21095 (current-column))))
21096 (string
21097 (when (and (match-end 4) (org-point-in-group (point) 4))
21098 (delete-and-extract-region (point) (match-end 4)))))
21099 ;; Adjust tag alignment.
21100 (cond
21101 ((not (and tags-column string)))
21102 (org-auto-align-tags (org-set-tags nil t))
21103 (t (org--align-tags-here tags-column))) ;preserve tags column
21104 (end-of-line)
21105 (org-show-entry)
21106 (if indent (newline-and-indent) (newline))
21107 (when string (save-excursion (insert (org-trim string))))))
21108 ;; In a list, make sure indenting keeps trailing text within.
21109 ((and indent
21110 (not (eolp))
21111 (org-element-lineage context '(item)))
21112 (let ((trailing-data
21113 (delete-and-extract-region (point) (line-end-position))))
21114 (newline-and-indent)
21115 (save-excursion (insert trailing-data))))
21116 (t (if indent (newline-and-indent) (newline))))))
21118 (defun org-return-indent ()
21119 "Goto next table row or insert a newline and indent.
21120 Calls `org-table-next-row' or `newline-and-indent', depending on
21121 context. See the individual commands for more information."
21122 (interactive)
21123 (org-return t))
21125 (defun org-ctrl-c-star ()
21126 "Compute table, or change heading status of lines.
21127 Calls `org-table-recalculate' or `org-toggle-heading',
21128 depending on context."
21129 (interactive)
21130 (cond
21131 ((org-at-table-p)
21132 (call-interactively 'org-table-recalculate))
21134 ;; Convert all lines in region to list items
21135 (call-interactively 'org-toggle-heading))))
21137 (defun org-ctrl-c-minus ()
21138 "Insert separator line in table or modify bullet status of line.
21139 Also turns a plain line or a region of lines into list items.
21140 Calls `org-table-insert-hline', `org-toggle-item', or
21141 `org-cycle-list-bullet', depending on context."
21142 (interactive)
21143 (cond
21144 ((org-at-table-p)
21145 (call-interactively 'org-table-insert-hline))
21146 ((org-region-active-p)
21147 (call-interactively 'org-toggle-item))
21148 ((org-in-item-p)
21149 (call-interactively 'org-cycle-list-bullet))
21151 (call-interactively 'org-toggle-item))))
21153 (defun org-toggle-heading (&optional nstars)
21154 "Convert headings to normal text, or items or text to headings.
21155 If there is no active region, only convert the current line.
21157 With a `\\[universal-argument]' prefix, convert the whole list at
21158 point into heading.
21160 In a region:
21162 - If the first non blank line is a headline, remove the stars
21163 from all headlines in the region.
21165 - If it is a normal line, turn each and every normal line (i.e.,
21166 not an heading or an item) in the region into headings. If you
21167 want to convert only the first line of this region, use one
21168 universal prefix argument.
21170 - If it is a plain list item, turn all plain list items into headings.
21172 When converting a line into a heading, the number of stars is chosen
21173 such that the lines become children of the current entry. However,
21174 when a numeric prefix argument is given, its value determines the
21175 number of stars to add."
21176 (interactive "P")
21177 (let ((skip-blanks
21178 (function
21179 ;; Return beginning of first non-blank line, starting from
21180 ;; line at POS.
21181 (lambda (pos)
21182 (save-excursion
21183 (goto-char pos)
21184 (while (org-at-comment-p) (forward-line))
21185 (skip-chars-forward " \r\t\n")
21186 (point-at-bol)))))
21187 beg end toggled)
21188 ;; Determine boundaries of changes. If a universal prefix has
21189 ;; been given, put the list in a region. If region ends at a bol,
21190 ;; do not consider the last line to be in the region.
21192 (when (and current-prefix-arg (org-at-item-p))
21193 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21194 (org-mark-element))
21196 (if (org-region-active-p)
21197 (setq beg (funcall skip-blanks (region-beginning))
21198 end (copy-marker (save-excursion
21199 (goto-char (region-end))
21200 (if (bolp) (point) (point-at-eol)))))
21201 (setq beg (funcall skip-blanks (point-at-bol))
21202 end (copy-marker (point-at-eol))))
21203 ;; Ensure inline tasks don't count as headings.
21204 (org-with-limited-levels
21205 (save-excursion
21206 (goto-char beg)
21207 (cond
21208 ;; Case 1. Started at an heading: de-star headings.
21209 ((org-at-heading-p)
21210 (while (< (point) end)
21211 (when (org-at-heading-p t)
21212 (looking-at org-outline-regexp) (replace-match "")
21213 (setq toggled t))
21214 (forward-line)))
21215 ;; Case 2. Started at an item: change items into headlines.
21216 ;; One star will be added by `org-list-to-subtree'.
21217 ((org-at-item-p)
21218 (while (< (point) end)
21219 (when (org-at-item-p)
21220 ;; Pay attention to cases when region ends before list.
21221 (let* ((struct (org-list-struct))
21222 (list-end
21223 (min (org-list-get-bottom-point struct) (1+ end))))
21224 (save-restriction
21225 (narrow-to-region (point) list-end)
21226 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21227 (setq toggled t))
21228 (forward-line)))
21229 ;; Case 3. Started at normal text: make every line an heading,
21230 ;; skipping headlines and items.
21231 (t (let* ((stars
21232 (make-string
21233 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21234 (add-stars
21235 (cond (nstars "") ; stars from prefix only
21236 ((equal stars "") "*") ; before first heading
21237 (org-odd-levels-only "**") ; inside heading, odd
21238 (t "*"))) ; inside heading, oddeven
21239 (rpl (concat stars add-stars " "))
21240 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21241 (while (< (point) (if (equal nstars '(4)) lend end))
21242 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21243 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21244 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21245 (forward-line)))))))
21246 (unless toggled (message "Cannot toggle heading from here"))))
21248 (defun org-meta-return (&optional arg)
21249 "Insert a new heading or wrap a region in a table.
21250 Calls `org-insert-heading', `org-insert-item' or
21251 `org-table-wrap-region', depending on context. When called with
21252 an argument, unconditionally call `org-insert-heading'."
21253 (interactive "P")
21254 (org-check-before-invisible-edit 'insert)
21255 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21256 (call-interactively (cond (arg #'org-insert-heading)
21257 ((org-at-table-p) #'org-table-wrap-region)
21258 ((org-in-item-p) #'org-insert-item)
21259 (t #'org-insert-heading)))))
21261 ;;; Menu entries
21263 (defsubst org-in-subtree-not-table-p ()
21264 "Are we in a subtree and not in a table?"
21265 (and (not (org-before-first-heading-p))
21266 (not (org-at-table-p))))
21268 ;; Define the Org mode menus
21269 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21270 '("Tbl"
21271 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21272 ["Next Field" org-cycle (org-at-table-p)]
21273 ["Previous Field" org-shifttab (org-at-table-p)]
21274 ["Next Row" org-return (org-at-table-p)]
21275 "--"
21276 ["Blank Field" org-table-blank-field (org-at-table-p)]
21277 ["Edit Field" org-table-edit-field (org-at-table-p)]
21278 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21279 "--"
21280 ("Column"
21281 ["Move Column Left" org-metaleft (org-at-table-p)]
21282 ["Move Column Right" org-metaright (org-at-table-p)]
21283 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21284 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21285 ("Row"
21286 ["Move Row Up" org-metaup (org-at-table-p)]
21287 ["Move Row Down" org-metadown (org-at-table-p)]
21288 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21289 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21290 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21291 "--"
21292 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21293 ("Rectangle"
21294 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21295 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21296 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21297 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21298 "--"
21299 ("Calculate"
21300 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21301 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21302 ["Edit Formulas" org-edit-special (org-at-table-p)]
21303 "--"
21304 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21305 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21306 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21307 "--"
21308 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21309 "--"
21310 ["Sum Column/Rectangle" org-table-sum
21311 (or (org-at-table-p) (org-region-active-p))]
21312 ["Which Column?" org-table-current-column (org-at-table-p)])
21313 ["Debug Formulas"
21314 org-table-toggle-formula-debugger
21315 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21316 ["Show Col/Row Numbers"
21317 org-table-toggle-coordinate-overlays
21318 :style toggle
21319 :selected (bound-and-true-p org-table-overlay-coordinates)]
21320 "--"
21321 ["Create" org-table-create (and (not (org-at-table-p))
21322 org-enable-table-editor)]
21323 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21324 ["Import from File" org-table-import (not (org-at-table-p))]
21325 ["Export to File" org-table-export (org-at-table-p)]
21326 "--"
21327 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21328 "--"
21329 ("Plot"
21330 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21331 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21333 (easy-menu-define org-org-menu org-mode-map "Org menu"
21334 '("Org"
21335 ("Show/Hide"
21336 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21337 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21338 ["Sparse Tree..." org-sparse-tree t]
21339 ["Reveal Context" org-reveal t]
21340 ["Show All" outline-show-all t]
21341 "--"
21342 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21343 "--"
21344 ["New Heading" org-insert-heading t]
21345 ("Navigate Headings"
21346 ["Up" outline-up-heading t]
21347 ["Next" outline-next-visible-heading t]
21348 ["Previous" outline-previous-visible-heading t]
21349 ["Next Same Level" outline-forward-same-level t]
21350 ["Previous Same Level" outline-backward-same-level t]
21351 "--"
21352 ["Jump" org-goto t])
21353 ("Edit Structure"
21354 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21355 "--"
21356 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21357 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21358 "--"
21359 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21360 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21361 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21362 "--"
21363 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21364 "--"
21365 ["Copy visible text" org-copy-visible t]
21366 "--"
21367 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21368 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21369 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21370 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21371 "--"
21372 ["Sort Region/Children" org-sort t]
21373 "--"
21374 ["Convert to odd levels" org-convert-to-odd-levels t]
21375 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21376 ("Editing"
21377 ["Emphasis..." org-emphasize t]
21378 ["Edit Source Example" org-edit-special t]
21379 "--"
21380 ["Footnote new/jump" org-footnote-action t]
21381 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21382 ("Archive"
21383 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21384 "--"
21385 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21386 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21387 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21389 "--"
21390 ("Hyperlinks"
21391 ["Store Link (Global)" org-store-link t]
21392 ["Find existing link to here" org-occur-link-in-agenda-files t]
21393 ["Insert Link" org-insert-link t]
21394 ["Follow Link" org-open-at-point t]
21395 "--"
21396 ["Next link" org-next-link t]
21397 ["Previous link" org-previous-link t]
21398 "--"
21399 ["Descriptive Links"
21400 org-toggle-link-display
21401 :style radio
21402 :selected org-descriptive-links
21404 ["Literal Links"
21405 org-toggle-link-display
21406 :style radio
21407 :selected (not org-descriptive-links)])
21408 "--"
21409 ("TODO Lists"
21410 ["TODO/DONE/-" org-todo t]
21411 ("Select keyword"
21412 ["Next keyword" org-shiftright (org-at-heading-p)]
21413 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21414 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21415 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21416 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21417 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21418 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21419 "--"
21420 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21421 :selected org-enforce-todo-dependencies :style toggle :active t]
21422 "Settings for tree at point"
21423 ["Do Children sequentially" org-toggle-ordered-property :style radio
21424 :selected (org-entry-get nil "ORDERED")
21425 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21426 ["Do Children parallel" org-toggle-ordered-property :style radio
21427 :selected (not (org-entry-get nil "ORDERED"))
21428 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21429 "--"
21430 ["Set Priority" org-priority t]
21431 ["Priority Up" org-shiftup t]
21432 ["Priority Down" org-shiftdown t]
21433 "--"
21434 ["Get news from all feeds" org-feed-update-all t]
21435 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21436 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21437 ("TAGS and Properties"
21438 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21439 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21440 "--"
21441 ["Set property" org-set-property (not (org-before-first-heading-p))]
21442 ["Column view of properties" org-columns t]
21443 ["Insert Column View DBlock" org-columns-insert-dblock t])
21444 ("Dates and Scheduling"
21445 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21446 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21447 ("Change Date"
21448 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21449 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21450 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21451 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21452 ["Compute Time Range" org-evaluate-time-range t]
21453 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21454 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21455 "--"
21456 ["Custom time format" org-toggle-time-stamp-overlays
21457 :style radio :selected org-display-custom-times]
21458 "--"
21459 ["Goto Calendar" org-goto-calendar t]
21460 ["Date from Calendar" org-date-from-calendar t]
21461 "--"
21462 ["Start/Restart Timer" org-timer-start t]
21463 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21464 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21465 ["Insert Timer String" org-timer t]
21466 ["Insert Timer Item" org-timer-item t])
21467 ("Logging work"
21468 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21469 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21470 ["Clock out" org-clock-out t]
21471 ["Clock cancel" org-clock-cancel t]
21472 "--"
21473 ["Mark as default task" org-clock-mark-default-task t]
21474 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21475 ["Goto running clock" org-clock-goto t]
21476 "--"
21477 ["Display times" org-clock-display t]
21478 ["Create clock table" org-clock-report t]
21479 "--"
21480 ["Record DONE time"
21481 (progn (setq org-log-done (not org-log-done))
21482 (message "Switching to %s will %s record a timestamp"
21483 (car org-done-keywords)
21484 (if org-log-done "automatically" "not")))
21485 :style toggle :selected org-log-done])
21486 "--"
21487 ["Agenda Command..." org-agenda t]
21488 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21489 ("File List for Agenda")
21490 ("Special views current file"
21491 ["TODO Tree" org-show-todo-tree t]
21492 ["Check Deadlines" org-check-deadlines t]
21493 ["Tags/Property tree" org-match-sparse-tree t])
21494 "--"
21495 ["Export/Publish..." org-export-dispatch t]
21496 ("LaTeX"
21497 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21498 :selected org-cdlatex-mode]
21499 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21500 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21501 ["Modify math symbol" org-cdlatex-math-modify
21502 (org-inside-LaTeX-fragment-p)]
21503 ["Insert citation" org-reftex-citation t])
21504 "--"
21505 ("MobileOrg"
21506 ["Push Files and Views" org-mobile-push t]
21507 ["Get Captured and Flagged" org-mobile-pull t]
21508 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21509 "--"
21510 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21511 "--"
21512 ("Documentation"
21513 ["Show Version" org-version t]
21514 ["Info Documentation" org-info t])
21515 ("Customize"
21516 ["Browse Org Group" org-customize t]
21517 "--"
21518 ["Expand This Menu" org-create-customize-menu
21519 (fboundp 'customize-menu-create)])
21520 ["Send bug report" org-submit-bug-report t]
21521 "--"
21522 ("Refresh/Reload"
21523 ["Refresh setup current buffer" org-mode-restart t]
21524 ["Reload Org (after update)" org-reload t]
21525 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21528 (defun org-info (&optional node)
21529 "Read documentation for Org in the info system.
21530 With optional NODE, go directly to that node."
21531 (interactive)
21532 (info (format "(org)%s" (or node ""))))
21534 ;;;###autoload
21535 (defun org-submit-bug-report ()
21536 "Submit a bug report on Org via mail.
21538 Don't hesitate to report any problems or inaccurate documentation.
21540 If you don't have setup sending mail from (X)Emacs, please copy the
21541 output buffer into your mail program, as it gives us important
21542 information about your Org version and configuration."
21543 (interactive)
21544 (require 'reporter)
21545 (defvar reporter-prompt-for-summary-p)
21546 (org-load-modules-maybe)
21547 (org-require-autoloaded-modules)
21548 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21549 (reporter-submit-bug-report
21550 "emacs-orgmode@gnu.org"
21551 (org-version nil 'full)
21552 (let (list)
21553 (save-window-excursion
21554 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21555 (delete-other-windows)
21556 (erase-buffer)
21557 (insert "You are about to submit a bug report to the Org mailing list.
21559 We would like to add your full Org and Outline configuration to the
21560 bug report. This greatly simplifies the work of the maintainer and
21561 other experts on the mailing list.
21563 HOWEVER, some variables you have customized may contain private
21564 information. The names of customers, colleagues, or friends, might
21565 appear in the form of file names, tags, todo states, or search strings.
21566 If you answer yes to the prompt, you might want to check and remove
21567 such private information before sending the email.")
21568 (add-text-properties (point-min) (point-max) '(face org-warning))
21569 (when (yes-or-no-p "Include your Org configuration ")
21570 (mapatoms
21571 (lambda (v)
21572 (and (boundp v)
21573 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21574 (or (and (symbol-value v)
21575 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21576 (and
21577 (get v 'custom-type) (get v 'standard-value)
21578 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21579 (push v list)))))
21580 (kill-buffer (get-buffer "*Warn about privacy*"))
21581 list))
21582 nil nil
21583 "Remember to cover the basics, that is, what you expected to happen and
21584 what in fact did happen. You don't know how to make a good report? See
21586 http://orgmode.org/manual/Feedback.html#Feedback
21588 Your bug report will be posted to the Org mailing list.
21589 ------------------------------------------------------------------------")
21590 (save-excursion
21591 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21592 (replace-match "\\1Bug: \\3 [\\2]")))))
21595 (defun org-install-agenda-files-menu ()
21596 (let ((bl (buffer-list)))
21597 (save-excursion
21598 (while bl
21599 (set-buffer (pop bl))
21600 (when (derived-mode-p 'org-mode) (setq bl nil)))
21601 (when (derived-mode-p 'org-mode)
21602 (easy-menu-change
21603 '("Org") "File List for Agenda"
21604 (append
21605 (list
21606 ["Edit File List" (org-edit-agenda-file-list) t]
21607 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21608 ["Remove Current File from List" org-remove-file t]
21609 ["Cycle through agenda files" org-cycle-agenda-files t]
21610 ["Occur in all agenda files" org-occur-in-agenda-files t]
21611 "--")
21612 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21614 ;;;; Documentation
21616 (defun org-require-autoloaded-modules ()
21617 (interactive)
21618 (mapc #'require
21619 '(org-agenda org-archive org-attach org-clock org-colview org-id
21620 org-table org-timer)))
21622 ;;;###autoload
21623 (defun org-reload (&optional uncompiled)
21624 "Reload all org lisp files.
21625 With prefix arg UNCOMPILED, load the uncompiled versions."
21626 (interactive "P")
21627 (require 'loadhist)
21628 (let* ((org-dir (org-find-library-dir "org"))
21629 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21630 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21631 (remove-re (format "\\`%s\\'"
21632 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21633 (feats (delete-dups
21634 (mapcar 'file-name-sans-extension
21635 (mapcar 'file-name-nondirectory
21636 (delq nil
21637 (mapcar 'feature-file
21638 features))))))
21639 (lfeat (append
21640 (sort
21641 (setq feats
21642 (delq nil (mapcar
21643 (lambda (f)
21644 (if (and (string-match feature-re f)
21645 (not (string-match remove-re f)))
21646 f nil))
21647 feats)))
21648 'string-lessp)
21649 (list "org-version" "org")))
21650 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21651 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21652 load-uncore load-misses)
21653 (setq load-misses
21654 (delq 't
21655 (mapcar (lambda (f)
21656 (or (org-load-noerror-mustsuffix (concat org-dir f))
21657 (and (string= org-dir contrib-dir)
21658 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21659 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21660 (add-to-list 'load-uncore f 'append)
21663 lfeat)))
21664 (when load-uncore
21665 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21666 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21667 (if load-misses
21668 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21669 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21670 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21672 ;;;###autoload
21673 (defun org-customize ()
21674 "Call the customize function with org as argument."
21675 (interactive)
21676 (org-load-modules-maybe)
21677 (org-require-autoloaded-modules)
21678 (customize-browse 'org))
21680 (defun org-create-customize-menu ()
21681 "Create a full customization menu for Org mode, insert it into the menu."
21682 (interactive)
21683 (org-load-modules-maybe)
21684 (org-require-autoloaded-modules)
21685 (if (fboundp 'customize-menu-create)
21686 (progn
21687 (easy-menu-change
21688 '("Org") "Customize"
21689 `(["Browse Org group" org-customize t]
21690 "--"
21691 ,(customize-menu-create 'org)
21692 ["Set" Custom-set t]
21693 ["Save" Custom-save t]
21694 ["Reset to Current" Custom-reset-current t]
21695 ["Reset to Saved" Custom-reset-saved t]
21696 ["Reset to Standard Settings" Custom-reset-standard t]))
21697 (message "\"Org\"-menu now contains full customization menu"))
21698 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21700 ;;;; Miscellaneous stuff
21702 ;;; Generally useful functions
21704 (defun org-get-at-eol (property n)
21705 "Get text property PROPERTY at the end of line less N characters."
21706 (get-text-property (- (point-at-eol) n) property))
21708 (defun org-find-text-property-in-string (prop s)
21709 "Return the first non-nil value of property PROP in string S."
21710 (or (get-text-property 0 prop s)
21711 (get-text-property (or (next-single-property-change 0 prop s) 0)
21712 prop s)))
21714 (defun org-display-warning (message)
21715 "Display the given MESSAGE as a warning."
21716 (display-warning 'org message :warning))
21718 (defun org-eval (form)
21719 "Eval FORM and return result."
21720 (condition-case error
21721 (eval form)
21722 (error (format "%%![Error: %s]" error))))
21724 (defun org-in-clocktable-p ()
21725 "Check if the cursor is in a clocktable."
21726 (let ((pos (point)) start)
21727 (save-excursion
21728 (end-of-line 1)
21729 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21730 (setq start (match-beginning 0))
21731 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21732 (>= (match-end 0) pos)
21733 start))))
21735 (defun org-in-verbatim-emphasis ()
21736 (save-match-data
21737 (and (org-in-regexp org-verbatim-re 2)
21738 (>= (point) (match-beginning 3))
21739 (<= (point) (match-end 4)))))
21741 (defun org-overlay-display (ovl text &optional face evap)
21742 "Make overlay OVL display TEXT with face FACE."
21743 (overlay-put ovl 'display text)
21744 (if face (overlay-put ovl 'face face))
21745 (if evap (overlay-put ovl 'evaporate t)))
21747 (defun org-overlay-before-string (ovl text &optional face evap)
21748 "Make overlay OVL display TEXT with face FACE."
21749 (if face (org-add-props text nil 'face face))
21750 (overlay-put ovl 'before-string text)
21751 (if evap (overlay-put ovl 'evaporate t)))
21753 (defun org-find-overlays (prop &optional pos delete)
21754 "Find all overlays specifying PROP at POS or point.
21755 If DELETE is non-nil, delete all those overlays."
21756 (let (found)
21757 (dolist (ov (overlays-at (or pos (point))) found)
21758 (cond ((not (overlay-get ov prop)))
21759 (delete (delete-overlay ov))
21760 (t (push ov found))))))
21762 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21763 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21764 (if (and marker (marker-buffer marker)
21765 (buffer-live-p (marker-buffer marker)))
21766 (progn
21767 (pop-to-buffer-same-window (marker-buffer marker))
21768 (when (or (> marker (point-max)) (< marker (point-min)))
21769 (widen))
21770 (goto-char marker)
21771 (org-show-context 'org-goto))
21772 (if bookmark
21773 (bookmark-jump bookmark)
21774 (error "Cannot find location"))))
21776 (defun org-quote-csv-field (s)
21777 "Quote field for inclusion in CSV material."
21778 (if (string-match "[\",]" s)
21779 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21782 (defun org-force-self-insert (N)
21783 "Needed to enforce self-insert under remapping."
21784 (interactive "p")
21785 (self-insert-command N))
21787 (defun org-shorten-string (s maxlength)
21788 "Shorten string S so that it is no longer than MAXLENGTH characters.
21789 If the string is shorter or has length MAXLENGTH, just return the
21790 original string. If it is longer, the functions finds a space in the
21791 string, breaks this string off at that locations and adds three dots
21792 as ellipsis. Including the ellipsis, the string will not be longer
21793 than MAXLENGTH. If finding a good breaking point in the string does
21794 not work, the string is just chopped off in the middle of a word
21795 if necessary."
21796 (if (<= (length s) maxlength)
21798 (let* ((n (max (- maxlength 4) 1))
21799 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21800 (if (string-match re s)
21801 (concat (match-string 1 s) "...")
21802 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21804 (defun org-get-indentation (&optional line)
21805 "Get the indentation of the current line, interpreting tabs.
21806 When LINE is given, assume it represents a line and compute its indentation."
21807 (if line
21808 (when (string-match "^ *" (org-remove-tabs line))
21809 (match-end 0))
21810 (save-excursion
21811 (beginning-of-line 1)
21812 (skip-chars-forward " \t")
21813 (current-column))))
21815 (defun org-get-string-indentation (s)
21816 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21817 (let ((n -1) (i 0) (w tab-width) c)
21818 (catch 'exit
21819 (while (< (setq n (1+ n)) (length s))
21820 (setq c (aref s n))
21821 (cond ((= c ?\ ) (setq i (1+ i)))
21822 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21823 (t (throw 'exit t)))))
21826 (defun org-remove-tabs (s &optional width)
21827 "Replace tabulators in S with spaces.
21828 Assumes that s is a single line, starting in column 0."
21829 (setq width (or width tab-width))
21830 (while (string-match "\t" s)
21831 (setq s (replace-match
21832 (make-string
21833 (- (* width (/ (+ (match-beginning 0) width) width))
21834 (match-beginning 0)) ?\ )
21835 t t s)))
21838 (defun org-fix-indentation (line ind)
21839 "Fix indentation in LINE.
21840 IND is a cons cell with target and minimum indentation.
21841 If the current indentation in LINE is smaller than the minimum,
21842 leave it alone. If it is larger than ind, set it to the target."
21843 (let* ((l (org-remove-tabs line))
21844 (i (org-get-indentation l))
21845 (i1 (car ind)) (i2 (cdr ind)))
21846 (when (>= i i2) (setq l (substring line i2)))
21847 (if (> i1 0)
21848 (concat (make-string i1 ?\ ) l)
21849 l)))
21851 (defun org-remove-indentation (code &optional n)
21852 "Remove maximum common indentation in string CODE and return it.
21853 N may optionally be the number of columns to remove. Return CODE
21854 as-is if removal failed."
21855 (with-temp-buffer
21856 (insert code)
21857 (if (org-do-remove-indentation n) (buffer-string) code)))
21859 (defun org-do-remove-indentation (&optional n)
21860 "Remove the maximum common indentation from the buffer.
21861 When optional argument N is a positive integer, remove exactly
21862 that much characters from indentation, if possible. Return nil
21863 if it fails."
21864 (catch :exit
21865 (goto-char (point-min))
21866 ;; Find maximum common indentation, if not specified.
21867 (let ((n (or n
21868 (let ((min-ind (point-max)))
21869 (save-excursion
21870 (while (re-search-forward "^[ \t]*\\S-" nil t)
21871 (let ((ind (1- (current-column))))
21872 (if (zerop ind) (throw :exit nil)
21873 (setq min-ind (min min-ind ind))))))
21874 min-ind))))
21875 (if (zerop n) (throw :exit nil)
21876 ;; Remove exactly N indentation, but give up if not possible.
21877 (while (not (eobp))
21878 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21879 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21880 ((< ind n) (throw :exit nil))
21881 (t (indent-line-to (- ind n))))
21882 (forward-line)))
21883 ;; Signal success.
21884 t))))
21886 (defun org-fill-template (template alist)
21887 "Find each %key of ALIST in TEMPLATE and replace it."
21888 (let ((case-fold-search nil))
21889 (dolist (entry (sort (copy-sequence alist)
21890 (lambda (a b) (< (length (car a)) (length (car b))))))
21891 (setq template
21892 (replace-regexp-in-string
21893 (concat "%" (regexp-quote (car entry)))
21894 (or (cdr entry) "") template t t)))
21895 template))
21897 (defun org-base-buffer (buffer)
21898 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21899 (if (not buffer)
21900 buffer
21901 (or (buffer-base-buffer buffer)
21902 buffer)))
21904 (defun org-wrap (string &optional width lines)
21905 "Wrap string to either a number of lines, or a width in characters.
21906 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21907 that costs. If there is a word longer than WIDTH, the text is actually
21908 wrapped to the length of that word.
21909 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21910 many lines, whatever width that takes.
21911 The return value is a list of lines, without newlines at the end."
21912 (let* ((words (org-split-string string "[ \t\n]+"))
21913 (maxword (apply 'max (mapcar 'org-string-width words)))
21914 w ll)
21915 (cond (width
21916 (org-do-wrap words (max maxword width)))
21917 (lines
21918 (setq w maxword)
21919 (setq ll (org-do-wrap words maxword))
21920 (if (<= (length ll) lines)
21922 (setq ll words)
21923 (while (> (length ll) lines)
21924 (setq w (1+ w))
21925 (setq ll (org-do-wrap words w)))
21926 ll))
21927 (t (error "Cannot wrap this")))))
21929 (defun org-do-wrap (words width)
21930 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21931 (let (lines line)
21932 (while words
21933 (setq line (pop words))
21934 (while (and words (< (+ (length line) (length (car words))) width))
21935 (setq line (concat line " " (pop words))))
21936 (setq lines (push line lines)))
21937 (nreverse lines)))
21939 (defun org-quote-vert (s)
21940 "Replace \"|\" with \"\\vert\"."
21941 (while (string-match "|" s)
21942 (setq s (replace-match "\\vert" t t s)))
21945 (defun org-uuidgen-p (s)
21946 "Is S an ID created by UUIDGEN?"
21947 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21949 (defun org-in-src-block-p (&optional inside)
21950 "Whether point is in a code source block.
21951 When INSIDE is non-nil, don't consider we are within a src block
21952 when point is at #+BEGIN_SRC or #+END_SRC."
21953 (let ((case-fold-search t))
21954 (or (and (eq (get-char-property (point) 'src-block) t))
21955 (and (not inside)
21956 (save-match-data
21957 (save-excursion
21958 (beginning-of-line)
21959 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21961 (defun org-context ()
21962 "Return a list of contexts of the current cursor position.
21963 If several contexts apply, all are returned.
21964 Each context entry is a list with a symbol naming the context, and
21965 two positions indicating start and end of the context. Possible
21966 contexts are:
21968 :headline anywhere in a headline
21969 :headline-stars on the leading stars in a headline
21970 :todo-keyword on a TODO keyword (including DONE) in a headline
21971 :tags on the TAGS in a headline
21972 :priority on the priority cookie in a headline
21973 :item on the first line of a plain list item
21974 :item-bullet on the bullet/number of a plain list item
21975 :checkbox on the checkbox in a plain list item
21976 :table in an Org table
21977 :table-special on a special filed in a table
21978 :table-table in a table.el table
21979 :clocktable in a clocktable
21980 :src-block in a source block
21981 :link on a hyperlink
21982 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21983 :target on a <<target>>
21984 :radio-target on a <<<radio-target>>>
21985 :latex-fragment on a LaTeX fragment
21986 :latex-preview on a LaTeX fragment with overlaid preview image
21988 This function expects the position to be visible because it uses font-lock
21989 faces as a help to recognize the following contexts: :table-special, :link,
21990 and :keyword."
21991 (let* ((f (get-text-property (point) 'face))
21992 (faces (if (listp f) f (list f)))
21993 (case-fold-search t)
21994 (p (point)) clist o)
21995 ;; First the large context
21996 (cond
21997 ((org-at-heading-p t)
21998 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21999 (when (progn
22000 (beginning-of-line 1)
22001 (looking-at org-todo-line-tags-regexp))
22002 (push (org-point-in-group p 1 :headline-stars) clist)
22003 (push (org-point-in-group p 2 :todo-keyword) clist)
22004 (push (org-point-in-group p 4 :tags) clist))
22005 (goto-char p)
22006 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22007 (when (looking-at "\\[#[A-Z0-9]\\]")
22008 (push (org-point-in-group p 0 :priority) clist)))
22010 ((org-at-item-p)
22011 (push (org-point-in-group p 2 :item-bullet) clist)
22012 (push (list :item (point-at-bol)
22013 (save-excursion (org-end-of-item) (point)))
22014 clist)
22015 (and (org-at-item-checkbox-p)
22016 (push (org-point-in-group p 0 :checkbox) clist)))
22018 ((org-at-table-p)
22019 (push (list :table (org-table-begin) (org-table-end)) clist)
22020 (when (memq 'org-formula faces)
22021 (push (list :table-special
22022 (previous-single-property-change p 'face)
22023 (next-single-property-change p 'face)) clist)))
22024 ((org-at-table-p 'any)
22025 (push (list :table-table) clist)))
22026 (goto-char p)
22028 (let ((case-fold-search t))
22029 ;; New the "medium" contexts: clocktables, source blocks
22030 (cond ((org-in-clocktable-p)
22031 (push (list :clocktable
22032 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22033 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22034 (match-beginning 1))
22035 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22036 (match-end 0))) clist))
22037 ((org-in-src-block-p)
22038 (push (list :src-block
22039 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22040 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22041 (match-beginning 1))
22042 (and (search-forward "#+END_SRC" nil t)
22043 (match-beginning 0))) clist))))
22044 (goto-char p)
22046 ;; Now the small context
22047 (cond
22048 ((org-at-timestamp-p)
22049 (push (org-point-in-group p 0 :timestamp) clist))
22050 ((memq 'org-link faces)
22051 (push (list :link
22052 (previous-single-property-change p 'face)
22053 (next-single-property-change p 'face)) clist))
22054 ((memq 'org-special-keyword faces)
22055 (push (list :keyword
22056 (previous-single-property-change p 'face)
22057 (next-single-property-change p 'face)) clist))
22058 ((org-at-target-p)
22059 (push (org-point-in-group p 0 :target) clist)
22060 (goto-char (1- (match-beginning 0)))
22061 (when (looking-at org-radio-target-regexp)
22062 (push (org-point-in-group p 0 :radio-target) clist))
22063 (goto-char p))
22064 ((setq o (cl-some
22065 (lambda (o)
22066 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22068 (overlays-at (point))))
22069 (push (list :latex-fragment
22070 (overlay-start o) (overlay-end o)) clist)
22071 (push (list :latex-preview
22072 (overlay-start o) (overlay-end o)) clist))
22073 ((org-inside-LaTeX-fragment-p)
22074 ;; FIXME: positions wrong.
22075 (push (list :latex-fragment (point) (point)) clist)))
22077 (setq clist (nreverse (delq nil clist)))
22078 clist))
22080 (defun org-in-regexp (regexp &optional nlines visually)
22081 "Check if point is inside a match of REGEXP.
22083 Normally only the current line is checked, but you can include
22084 NLINES extra lines around point into the search. If VISUALLY is
22085 set, require that the cursor is not after the match but really
22086 on, so that the block visually is on the match.
22088 Return nil or a cons cell (BEG . END) where BEG and END are,
22089 respectively, the positions at the beginning and the end of the
22090 match."
22091 (catch :exit
22092 (let ((pos (point))
22093 (eol (line-end-position (if nlines (1+ nlines) 1))))
22094 (save-excursion
22095 (beginning-of-line (- 1 (or nlines 0)))
22096 (while (and (re-search-forward regexp eol t)
22097 (<= (match-beginning 0) pos))
22098 (let ((end (match-end 0)))
22099 (when (or (> end pos) (and (= end pos) (not visually)))
22100 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22102 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22103 "Non-nil when point is between matches of START-RE and END-RE.
22105 Also return a non-nil value when point is on one of the matches.
22107 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22108 buffer positions. Default values are the positions of headlines
22109 surrounding the point.
22111 The functions returns a cons cell whose car (resp. cdr) is the
22112 position before START-RE (resp. after END-RE)."
22113 (save-match-data
22114 (let ((pos (point))
22115 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22116 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22117 beg end)
22118 (save-excursion
22119 ;; Point is on a block when on START-RE or if START-RE can be
22120 ;; found before it...
22121 (and (or (org-in-regexp start-re)
22122 (re-search-backward start-re limit-up t))
22123 (setq beg (match-beginning 0))
22124 ;; ... and END-RE after it...
22125 (goto-char (match-end 0))
22126 (re-search-forward end-re limit-down t)
22127 (> (setq end (match-end 0)) pos)
22128 ;; ... without another START-RE in-between.
22129 (goto-char (match-beginning 0))
22130 (not (re-search-backward start-re (1+ beg) t))
22131 ;; Return value.
22132 (cons beg end))))))
22134 (defun org-in-block-p (names)
22135 "Non-nil when point belongs to a block whose name belongs to NAMES.
22137 NAMES is a list of strings containing names of blocks.
22139 Return first block name matched, or nil. Beware that in case of
22140 nested blocks, the returned name may not belong to the closest
22141 block from point."
22142 (save-match-data
22143 (catch 'exit
22144 (let ((case-fold-search t)
22145 (lim-up (save-excursion (outline-previous-heading)))
22146 (lim-down (save-excursion (outline-next-heading))))
22147 (dolist (name names)
22148 (let ((n (regexp-quote name)))
22149 (when (org-between-regexps-p
22150 (concat "^[ \t]*#\\+begin_" n)
22151 (concat "^[ \t]*#\\+end_" n)
22152 lim-up lim-down)
22153 (throw 'exit n)))))
22154 nil)))
22156 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22157 "Call `multi-occur' with buffers for all agenda files."
22158 (interactive "sOrg-files matching: ")
22159 (let* ((files (org-agenda-files))
22160 (tnames (mapcar #'file-truename files))
22161 (extra org-agenda-text-search-extra-files))
22162 (when (eq (car extra) 'agenda-archives)
22163 (setq extra (cdr extra))
22164 (setq files (org-add-archive-files files)))
22165 (dolist (f extra)
22166 (unless (member (file-truename f) tnames)
22167 (unless (member f files) (setq files (append files (list f))))
22168 (setq tnames (append tnames (list (file-truename f))))))
22169 (multi-occur
22170 (mapcar (lambda (x)
22171 (with-current-buffer
22172 ;; FIXME: Why not just (find-file-noselect x)?
22173 ;; Is it to avoid the "revert buffer" prompt?
22174 (or (get-file-buffer x) (find-file-noselect x))
22175 (widen)
22176 (current-buffer)))
22177 files)
22178 regexp)))
22180 (add-hook 'occur-mode-find-occurrence-hook
22181 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22183 (defun org-occur-link-in-agenda-files ()
22184 "Create a link and search for it in the agendas.
22185 The link is not stored in `org-stored-links', it is just created
22186 for the search purpose."
22187 (interactive)
22188 (let ((link (condition-case nil
22189 (org-store-link nil)
22190 (error "Unable to create a link to here"))))
22191 (org-occur-in-agenda-files (regexp-quote link))))
22193 (defun org-reverse-string (string)
22194 "Return the reverse of STRING."
22195 (apply 'string (reverse (string-to-list string))))
22197 ;; defsubst org-uniquify must be defined before first use
22199 (defun org-uniquify-alist (alist)
22200 "Merge elements of ALIST with the same key.
22202 For example, in this alist:
22204 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22205 => \\='((a 1 3) (b 2))
22207 merge (a 1) and (a 3) into (a 1 3).
22209 The function returns the new ALIST."
22210 (let (rtn)
22211 (dolist (e alist rtn)
22212 (let (n)
22213 (if (not (assoc (car e) rtn))
22214 (push e rtn)
22215 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22216 (setq rtn (assq-delete-all (car e) rtn))
22217 (push n rtn))))))
22219 (defun org-delete-all (elts list)
22220 "Remove all elements in ELTS from LIST.
22221 Comparison is done with `equal'. It is a destructive operation
22222 that may remove elements by altering the list structure."
22223 (while elts
22224 (setq list (delete (pop elts) list)))
22225 list)
22227 (defun org-back-over-empty-lines ()
22228 "Move backwards over whitespace, to the beginning of the first empty line.
22229 Returns the number of empty lines passed."
22230 (let ((pos (point)))
22231 (if (cdr (assq 'heading org-blank-before-new-entry))
22232 (skip-chars-backward " \t\n\r")
22233 (unless (eobp)
22234 (forward-line -1)))
22235 (beginning-of-line 2)
22236 (goto-char (min (point) pos))
22237 (count-lines (point) pos)))
22239 (defun org-skip-whitespace ()
22240 (skip-chars-forward " \t\n\r"))
22242 (defun org-point-in-group (point group &optional context)
22243 "Check if POINT is in match-group GROUP.
22244 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22245 match. If the match group does not exist or point is not inside it,
22246 return nil."
22247 (and (match-beginning group)
22248 (>= point (match-beginning group))
22249 (<= point (match-end group))
22250 (if context
22251 (list context (match-beginning group) (match-end group))
22252 t)))
22254 (defun org-switch-to-buffer-other-window (&rest args)
22255 "Switch to buffer in a second window on the current frame.
22256 In particular, do not allow pop-up frames.
22257 Returns the newly created buffer."
22258 (org-no-popups
22259 (apply 'switch-to-buffer-other-window args)))
22261 (defun org-combine-plists (&rest plists)
22262 "Create a single property list from all plists in PLISTS.
22263 The process starts by copying the first list, and then setting properties
22264 from the other lists. Settings in the last list are the most significant
22265 ones and overrule settings in the other lists."
22266 (let ((rtn (copy-sequence (pop plists)))
22267 p v ls)
22268 (while plists
22269 (setq ls (pop plists))
22270 (while ls
22271 (setq p (pop ls) v (pop ls))
22272 (setq rtn (plist-put rtn p v))))
22273 rtn))
22275 (defun org-replace-escapes (string table)
22276 "Replace %-escapes in STRING with values in TABLE.
22277 TABLE is an association list with keys like \"%a\" and string values.
22278 The sequences in STRING may contain normal field width and padding information,
22279 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22280 so values can contain further %-escapes if they are define later in TABLE."
22281 (let ((tbl (copy-alist table))
22282 (case-fold-search nil)
22283 (pchg 0)
22284 re rpl)
22285 (dolist (e tbl)
22286 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22287 (when (and (cdr e) (string-match re (cdr e)))
22288 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22289 (safe "SREF"))
22290 (add-text-properties 0 3 (list 'sref sref) safe)
22291 (setcdr e (replace-match safe t t (cdr e)))))
22292 (while (string-match re string)
22293 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22294 (cdr e)))
22295 (setq string (replace-match rpl t t string))))
22296 (while (setq pchg (next-property-change pchg string))
22297 (let ((sref (get-text-property pchg 'sref string)))
22298 (when (and sref (string-match "SREF" string pchg))
22299 (setq string (replace-match sref t t string)))))
22300 string))
22302 (defun org-find-base-buffer-visiting (file)
22303 "Like `find-buffer-visiting' but always return the base buffer and
22304 not an indirect buffer."
22305 (let ((buf (or (get-file-buffer file)
22306 (find-buffer-visiting file))))
22307 (if buf
22308 (or (buffer-base-buffer buf) buf)
22309 nil)))
22311 ;;; TODO: Only called once, from ox-odt which should probably use
22312 ;;; org-export-inline-image-p or something.
22313 (defun org-file-image-p (file)
22314 "Return non-nil if FILE is an image."
22315 (save-match-data
22316 (string-match (image-file-name-regexp) file)))
22318 (defun org-get-cursor-date (&optional with-time)
22319 "Return the date at cursor in as a time.
22320 This works in the calendar and in the agenda, anywhere else it just
22321 returns the current time.
22322 If WITH-TIME is non-nil, returns the time of the event at point (in
22323 the agenda) or the current time of the day."
22324 (let (date day defd tp hod mod)
22325 (when with-time
22326 (setq tp (get-text-property (point) 'time))
22327 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22328 (setq hod (string-to-number (match-string 1 tp))
22329 mod (string-to-number (match-string 2 tp))))
22330 (or tp (let ((now (decode-time)))
22331 (setq hod (nth 2 now)
22332 mod (nth 1 now)))))
22333 (cond
22334 ((eq major-mode 'calendar-mode)
22335 (setq date (calendar-cursor-to-date)
22336 defd (encode-time 0 (or mod 0) (or hod 0)
22337 (nth 1 date) (nth 0 date) (nth 2 date))))
22338 ((eq major-mode 'org-agenda-mode)
22339 (setq day (get-text-property (point) 'day))
22340 (when day
22341 (setq date (calendar-gregorian-from-absolute day)
22342 defd (encode-time 0 (or mod 0) (or hod 0)
22343 (nth 1 date) (nth 0 date) (nth 2 date))))))
22344 (or defd (current-time))))
22346 (defun org-mark-subtree (&optional up)
22347 "Mark the current subtree.
22348 This puts point at the start of the current subtree, and mark at
22349 the end. If a numeric prefix UP is given, move up into the
22350 hierarchy of headlines by UP levels before marking the subtree."
22351 (interactive "P")
22352 (org-with-limited-levels
22353 (cond ((org-at-heading-p) (beginning-of-line))
22354 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22355 (t (outline-previous-visible-heading 1))))
22356 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22357 (if (called-interactively-p 'any)
22358 (call-interactively 'org-mark-element)
22359 (org-mark-element)))
22361 (defun org-file-newer-than-p (file time)
22362 "Non-nil if FILE is newer than TIME.
22363 FILE is a filename, as a string, TIME is a list of integers, as
22364 returned by, e.g., `current-time'."
22365 (and (file-exists-p file)
22366 ;; Only compare times up to whole seconds as some file-systems
22367 ;; (e.g. HFS+) do not retain any finer granularity. As
22368 ;; a consequence, make sure we return non-nil when the two
22369 ;; times are equal.
22370 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22371 (cl-subseq time 0 2)))))
22373 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22374 "Compile a SOURCE file using PROCESS.
22376 PROCESS is either a function or a list of shell commands, as
22377 strings. EXT is a file extension, without the leading dot, as
22378 a string. It is used to check if the process actually succeeded.
22380 PROCESS must create a file with the same base name and directory
22381 as SOURCE, but ending with EXT. The function then returns its
22382 filename. Otherwise, it raises an error. The error message can
22383 then be refined by providing string ERR-MSG, which is appended to
22384 the standard message.
22386 If PROCESS is a function, it is called with a single argument:
22387 the SOURCE file.
22389 If it is a list of commands, each of them is called using
22390 `shell-command'. By default, in each command, %b, %f, %F, %o and
22391 %O are replaced with, respectively, SOURCE base name, name, full
22392 name, directory and absolute output file name. It is possible,
22393 however, to use more place-holders by specifying them in optional
22394 argument SPEC, as an alist following the pattern
22396 (CHARACTER . REPLACEMENT-STRING).
22398 When PROCESS is a list of commands, optional argument LOG-BUF can
22399 be set to a buffer or a buffer name. `shell-command' then uses
22400 it for output."
22401 (let* ((base-name (file-name-base source))
22402 (full-name (file-truename source))
22403 (out-dir (or (file-name-directory source) "./"))
22404 (output (expand-file-name (concat base-name "." ext) out-dir))
22405 (time (current-time))
22406 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22407 (save-window-excursion
22408 (pcase process
22409 ((pred functionp) (funcall process (shell-quote-argument source)))
22410 ((pred consp)
22411 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22412 (spec (append spec
22413 `((?b . ,(shell-quote-argument base-name))
22414 (?f . ,(shell-quote-argument source))
22415 (?F . ,(shell-quote-argument full-name))
22416 (?o . ,(shell-quote-argument out-dir))
22417 (?O . ,(shell-quote-argument output))))))
22418 (dolist (command process)
22419 (shell-command (format-spec command spec) log-buf))
22420 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22421 (_ (error "No valid command to process %S%s" source err-msg))))
22422 ;; Check for process failure. Output file is expected to be
22423 ;; located in the same directory as SOURCE.
22424 (unless (org-file-newer-than-p output time)
22425 (error (format "File %S wasn't produced%s" output err-msg)))
22426 output))
22428 ;;; Indentation
22430 (defvar org-element-greater-elements)
22431 (defun org--get-expected-indentation (element contentsp)
22432 "Expected indentation column for current line, according to ELEMENT.
22433 ELEMENT is an element containing point. CONTENTSP is non-nil
22434 when indentation is to be computed according to contents of
22435 ELEMENT."
22436 (let ((type (org-element-type element))
22437 (start (org-element-property :begin element))
22438 (post-affiliated (org-element-property :post-affiliated element)))
22439 (org-with-wide-buffer
22440 (cond
22441 (contentsp
22442 (cl-case type
22443 ((diary-sexp footnote-definition) 0)
22444 ((headline inlinetask nil)
22445 (if (not org-adapt-indentation) 0
22446 (let ((level (org-current-level)))
22447 (if level (1+ level) 0))))
22448 ((item plain-list) (org-list-item-body-column post-affiliated))
22450 (goto-char start)
22451 (org-get-indentation))))
22452 ((memq type '(headline inlinetask nil))
22453 (if (org-match-line "[ \t]*$")
22454 (org--get-expected-indentation element t)
22456 ((memq type '(diary-sexp footnote-definition)) 0)
22457 ;; First paragraph of a footnote definition or an item.
22458 ;; Indent like parent.
22459 ((< (line-beginning-position) start)
22460 (org--get-expected-indentation
22461 (org-element-property :parent element) t))
22462 ;; At first line: indent according to previous sibling, if any,
22463 ;; ignoring footnote definitions and inline tasks, or parent's
22464 ;; contents.
22465 ((= (line-beginning-position) start)
22466 (catch 'exit
22467 (while t
22468 (if (= (point-min) start) (throw 'exit 0)
22469 (goto-char (1- start))
22470 (let* ((previous (org-element-at-point))
22471 (parent previous))
22472 (while (and parent (<= (org-element-property :end parent) start))
22473 (setq previous parent
22474 parent (org-element-property :parent parent)))
22475 (cond
22476 ((not previous) (throw 'exit 0))
22477 ((> (org-element-property :end previous) start)
22478 (throw 'exit (org--get-expected-indentation previous t)))
22479 ((memq (org-element-type previous)
22480 '(footnote-definition inlinetask))
22481 (setq start (org-element-property :begin previous)))
22482 (t (goto-char (org-element-property :begin previous))
22483 (throw 'exit
22484 (if (bolp) (org-get-indentation)
22485 ;; At first paragraph in an item or
22486 ;; a footnote definition.
22487 (org--get-expected-indentation
22488 (org-element-property :parent previous) t))))))))))
22489 ;; Otherwise, move to the first non-blank line above.
22491 (beginning-of-line)
22492 (let ((pos (point)))
22493 (skip-chars-backward " \r\t\n")
22494 (cond
22495 ;; Two blank lines end a footnote definition or a plain
22496 ;; list. When we indent an empty line after them, the
22497 ;; containing list or footnote definition is over, so it
22498 ;; qualifies as a previous sibling. Therefore, we indent
22499 ;; like its first line.
22500 ((and (memq type '(footnote-definition plain-list))
22501 (> (count-lines (point) pos) 2))
22502 (goto-char start)
22503 (org-get-indentation))
22504 ;; Line above is the first one of a paragraph at the
22505 ;; beginning of an item or a footnote definition. Indent
22506 ;; like parent.
22507 ((< (line-beginning-position) start)
22508 (org--get-expected-indentation
22509 (org-element-property :parent element) t))
22510 ;; Line above is the beginning of an element, i.e., point
22511 ;; was originally on the blank lines between element's start
22512 ;; and contents.
22513 ((= (line-beginning-position) post-affiliated)
22514 (org--get-expected-indentation element t))
22515 ;; POS is after contents in a greater element. Indent like
22516 ;; the beginning of the element.
22517 ((and (memq type org-element-greater-elements)
22518 (let ((cend (org-element-property :contents-end element)))
22519 (and cend (<= cend pos))))
22520 ;; As a special case, if point is at the end of a footnote
22521 ;; definition or an item, indent like the very last element
22522 ;; within. If that last element is an item, indent like
22523 ;; its contents.
22524 (if (memq type '(footnote-definition item plain-list))
22525 (let ((last (org-element-at-point)))
22526 (goto-char pos)
22527 (org--get-expected-indentation
22528 last (eq (org-element-type last) 'item)))
22529 (goto-char start)
22530 (org-get-indentation)))
22531 ;; In any other case, indent like the current line.
22532 (t (org-get-indentation)))))))))
22534 (defun org--align-node-property ()
22535 "Align node property at point.
22536 Alignment is done according to `org-property-format', which see."
22537 (when (save-excursion
22538 (beginning-of-line)
22539 (looking-at org-property-re))
22540 (replace-match
22541 (concat (match-string 4)
22542 (org-trim
22543 (format org-property-format (match-string 1) (match-string 3))))
22544 t t)))
22546 (defun org-indent-line ()
22547 "Indent line depending on context.
22549 Indentation is done according to the following rules:
22551 - Footnote definitions, diary sexps, headlines and inline tasks
22552 have to start at column 0.
22554 - On the very first line of an element, consider, in order, the
22555 next rules until one matches:
22557 1. If there's a sibling element before, ignoring footnote
22558 definitions and inline tasks, indent like its first line.
22560 2. If element has a parent, indent like its contents. More
22561 precisely, if parent is an item, indent after the
22562 description part, if any, or the bullet (see
22563 `org-list-description-max-indent'). Else, indent like
22564 parent's first line.
22566 3. Otherwise, indent relatively to current level, if
22567 `org-adapt-indentation' is non-nil, or to left margin.
22569 - On a blank line at the end of an element, indent according to
22570 the type of the element. More precisely
22572 1. If element is a plain list, an item, or a footnote
22573 definition, indent like the very last element within.
22575 2. If element is a paragraph, indent like its last non blank
22576 line.
22578 3. Otherwise, indent like its very first line.
22580 - In the code part of a source block, use language major mode
22581 to indent current line if `org-src-tab-acts-natively' is
22582 non-nil. If it is nil, do nothing.
22584 - Otherwise, indent like the first non-blank line above.
22586 The function doesn't indent an item as it could break the whole
22587 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22588 `\\[org-shiftmetaright]'.
22590 Also align node properties according to `org-property-format'."
22591 (interactive)
22592 (cond
22593 (orgstruct-is-++
22594 (let ((indent-line-function
22595 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22596 (indent-according-to-mode)))
22597 ((org-at-heading-p) 'noindent)
22599 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22600 (type (org-element-type element)))
22601 (cond ((and (memq type '(plain-list item))
22602 (= (line-beginning-position)
22603 (org-element-property :post-affiliated element)))
22604 'noindent)
22605 ((and (eq type 'latex-environment)
22606 (>= (point) (org-element-property :post-affiliated element))
22607 (< (point) (org-with-wide-buffer
22608 (goto-char (org-element-property :end element))
22609 (skip-chars-backward " \r\t\n")
22610 (line-beginning-position 2))))
22611 'noindent)
22612 ((and (eq type 'src-block)
22613 org-src-tab-acts-natively
22614 (> (line-beginning-position)
22615 (org-element-property :post-affiliated element))
22616 (< (line-beginning-position)
22617 (org-with-wide-buffer
22618 (goto-char (org-element-property :end element))
22619 (skip-chars-backward " \r\t\n")
22620 (line-beginning-position))))
22621 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22623 (let ((column (org--get-expected-indentation element nil)))
22624 ;; Preserve current column.
22625 (if (<= (current-column) (current-indentation))
22626 (indent-line-to column)
22627 (save-excursion (indent-line-to column))))
22628 ;; Align node property. Also preserve current column.
22629 (when (eq type 'node-property)
22630 (let ((column (current-column)))
22631 (org--align-node-property)
22632 (org-move-to-column column)))))))))
22634 (defun org-indent-region (start end)
22635 "Indent each non-blank line in the region.
22636 Called from a program, START and END specify the region to
22637 indent. The function will not indent contents of example blocks,
22638 verse blocks and export blocks as leading white spaces are
22639 assumed to be significant there."
22640 (interactive "r")
22641 (save-excursion
22642 (goto-char start)
22643 (skip-chars-forward " \r\t\n")
22644 (unless (eobp) (beginning-of-line))
22645 (let ((indent-to
22646 (lambda (ind pos)
22647 ;; Set IND as indentation for all lines between point and
22648 ;; POS. Blank lines are ignored. Leave point after POS
22649 ;; once done.
22650 (let ((limit (copy-marker pos)))
22651 (while (< (point) limit)
22652 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22653 (forward-line))
22654 (set-marker limit nil))))
22655 (end (copy-marker end)))
22656 (while (< (point) end)
22657 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22658 (let* ((element (org-element-at-point))
22659 (type (org-element-type element))
22660 (element-end (copy-marker (org-element-property :end element)))
22661 (ind (org--get-expected-indentation element nil)))
22662 (cond
22663 ;; Element indented as a single block. Example blocks
22664 ;; preserving indentation are a special case since the
22665 ;; "contents" must not be indented whereas the block
22666 ;; boundaries can.
22667 ((or (memq type '(export-block latex-environment))
22668 (and (eq type 'example-block)
22669 (not
22670 (or org-src-preserve-indentation
22671 (org-element-property :preserve-indent element)))))
22672 (let ((offset (- ind (org-get-indentation))))
22673 (unless (zerop offset)
22674 (indent-rigidly (org-element-property :begin element)
22675 (org-element-property :end element)
22676 offset)))
22677 (goto-char element-end))
22678 ;; Elements indented line wise. Be sure to exclude
22679 ;; example blocks (preserving indentation) and source
22680 ;; blocks from this category as they are treated
22681 ;; specially later.
22682 ((or (memq type '(paragraph table table-row))
22683 (not (or (org-element-property :contents-begin element)
22684 (memq type '(example-block src-block)))))
22685 (when (eq type 'node-property)
22686 (org--align-node-property)
22687 (beginning-of-line))
22688 (funcall indent-to ind (min element-end end)))
22689 ;; Elements consisting of three parts: before the
22690 ;; contents, the contents, and after the contents. The
22691 ;; contents are treated specially, according to the
22692 ;; element type, or not indented at all. Other parts are
22693 ;; indented as a single block.
22695 (let* ((post (copy-marker
22696 (org-element-property :post-affiliated element)))
22697 (cbeg
22698 (copy-marker
22699 (cond
22700 ((not (org-element-property :contents-begin element))
22701 ;; Fake contents for source blocks.
22702 (org-with-wide-buffer
22703 (goto-char post)
22704 (line-beginning-position 2)))
22705 ((memq type '(footnote-definition item plain-list))
22706 ;; Contents in these elements could start on
22707 ;; the same line as the beginning of the
22708 ;; element. Make sure we start indenting
22709 ;; from the second line.
22710 (org-with-wide-buffer
22711 (goto-char post)
22712 (end-of-line)
22713 (skip-chars-forward " \r\t\n")
22714 (if (eobp) (point) (line-beginning-position))))
22715 (t (org-element-property :contents-begin element)))))
22716 (cend (copy-marker
22717 (or (org-element-property :contents-end element)
22718 ;; Fake contents for source blocks.
22719 (org-with-wide-buffer
22720 (goto-char element-end)
22721 (skip-chars-backward " \r\t\n")
22722 (line-beginning-position)))
22723 t)))
22724 ;; Do not change items indentation individually as it
22725 ;; might break the list as a whole. On the other
22726 ;; hand, when at a plain list, indent it as a whole.
22727 (cond ((eq type 'plain-list)
22728 (let ((offset (- ind (org-get-indentation))))
22729 (unless (zerop offset)
22730 (indent-rigidly (org-element-property :begin element)
22731 (org-element-property :end element)
22732 offset))
22733 (goto-char cbeg)))
22734 ((eq type 'item) (goto-char cbeg))
22735 (t (funcall indent-to ind (min cbeg end))))
22736 (when (< (point) end)
22737 (cl-case type
22738 ((example-block verse-block))
22739 (src-block
22740 ;; In a source block, indent source code
22741 ;; according to language major mode, but only if
22742 ;; `org-src-tab-acts-natively' is non-nil.
22743 (when (and (< (point) end) org-src-tab-acts-natively)
22744 (ignore-errors
22745 (org-babel-do-in-edit-buffer
22746 (indent-region (point-min) (point-max))))))
22747 (t (org-indent-region (point) (min cend end))))
22748 (goto-char (min cend end))
22749 (when (< (point) end)
22750 (funcall indent-to ind (min element-end end))))
22751 (set-marker post nil)
22752 (set-marker cbeg nil)
22753 (set-marker cend nil))))
22754 (set-marker element-end nil))))
22755 (set-marker end nil))))
22757 (defun org-indent-drawer ()
22758 "Indent the drawer at point."
22759 (interactive)
22760 (unless (save-excursion
22761 (beginning-of-line)
22762 (looking-at-p org-drawer-regexp))
22763 (user-error "Not at a drawer"))
22764 (let ((element (org-element-at-point)))
22765 (unless (memq (org-element-type element) '(drawer property-drawer))
22766 (user-error "Not at a drawer"))
22767 (org-with-wide-buffer
22768 (org-indent-region (org-element-property :begin element)
22769 (org-element-property :end element))))
22770 (message "Drawer at point indented"))
22772 (defun org-indent-block ()
22773 "Indent the block at point."
22774 (interactive)
22775 (unless (save-excursion
22776 (beginning-of-line)
22777 (let ((case-fold-search t))
22778 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22779 (user-error "Not at a block"))
22780 (let ((element (org-element-at-point)))
22781 (unless (memq (org-element-type element)
22782 '(comment-block center-block dynamic-block example-block
22783 export-block quote-block special-block
22784 src-block verse-block))
22785 (user-error "Not at a block"))
22786 (org-with-wide-buffer
22787 (org-indent-region (org-element-property :begin element)
22788 (org-element-property :end element))))
22789 (message "Block at point indented"))
22792 ;;; Filling
22794 ;; We use our own fill-paragraph and auto-fill functions.
22796 ;; `org-fill-paragraph' relies on adaptive filling and context
22797 ;; checking. Appropriate `fill-prefix' is computed with
22798 ;; `org-adaptive-fill-function'.
22800 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22801 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22802 ;; `org-adaptive-fill-function' value. Internally,
22803 ;; `org-comment-line-break-function' breaks the line.
22805 ;; `org-setup-filling' installs filling and auto-filling related
22806 ;; variables during `org-mode' initialization.
22808 (defvar org-element-paragraph-separate) ; org-element.el
22809 (defun org-setup-filling ()
22810 (require 'org-element)
22811 ;; Prevent auto-fill from inserting unwanted new items.
22812 (when (boundp 'fill-nobreak-predicate)
22813 (setq-local
22814 fill-nobreak-predicate
22815 (org-uniquify
22816 (append fill-nobreak-predicate
22817 '(org-fill-line-break-nobreak-p
22818 org-fill-n-macro-as-item-nobreak-p
22819 org-fill-paragraph-with-timestamp-nobreak-p)))))
22820 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22821 (setq-local paragraph-start paragraph-ending)
22822 (setq-local paragraph-separate paragraph-ending))
22823 (setq-local fill-paragraph-function 'org-fill-paragraph)
22824 (setq-local auto-fill-inhibit-regexp nil)
22825 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22826 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22827 (setq-local comment-line-break-function 'org-comment-line-break-function))
22829 (defun org-fill-line-break-nobreak-p ()
22830 "Non-nil when a new line at point would create an Org line break."
22831 (save-excursion
22832 (skip-chars-backward "[ \t]")
22833 (skip-chars-backward "\\\\")
22834 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22836 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22837 "Non-nil when a new line at point would split a timestamp."
22838 (and (org-at-timestamp-p 'lax)
22839 (not (looking-at org-ts-regexp-both))))
22841 (defun org-fill-n-macro-as-item-nobreak-p ()
22842 "Non-nil when a new line at point would create a new list."
22843 ;; During export, a "n" macro followed by a dot or a closing
22844 ;; parenthesis can end up being parsed as a new list item.
22845 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22847 (declare-function message-in-body-p "message" ())
22848 (defvar orgtbl-line-start-regexp) ; From org-table.el
22849 (defun org-adaptive-fill-function ()
22850 "Compute a fill prefix for the current line.
22851 Return fill prefix, as a string, or nil if current line isn't
22852 meant to be filled. For convenience, if `adaptive-fill-regexp'
22853 matches in paragraphs or comments, use it."
22854 (catch 'exit
22855 (when (derived-mode-p 'message-mode)
22856 (save-excursion
22857 (beginning-of-line)
22858 (cond ((not (message-in-body-p)) (throw 'exit nil))
22859 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22860 ((looking-at message-cite-prefix-regexp)
22861 (throw 'exit (match-string-no-properties 0)))
22862 ((looking-at org-outline-regexp)
22863 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22864 (org-with-wide-buffer
22865 (unless (org-at-heading-p)
22866 (let* ((p (line-beginning-position))
22867 (element (save-excursion
22868 (beginning-of-line)
22869 (org-element-at-point)))
22870 (type (org-element-type element))
22871 (post-affiliated (org-element-property :post-affiliated element)))
22872 (unless (< p post-affiliated)
22873 (cl-case type
22874 (comment
22875 (save-excursion
22876 (beginning-of-line)
22877 (looking-at "[ \t]*")
22878 (concat (match-string 0) "# ")))
22879 (footnote-definition "")
22880 ((item plain-list)
22881 (make-string (org-list-item-body-column post-affiliated) ?\s))
22882 (paragraph
22883 ;; Fill prefix is usually the same as the current line,
22884 ;; unless the paragraph is at the beginning of an item.
22885 (let ((parent (org-element-property :parent element)))
22886 (save-excursion
22887 (beginning-of-line)
22888 (cond ((eq (org-element-type parent) 'item)
22889 (make-string (org-list-item-body-column
22890 (org-element-property :begin parent))
22891 ?\s))
22892 ((and adaptive-fill-regexp
22893 ;; Locally disable
22894 ;; `adaptive-fill-function' to let
22895 ;; `fill-context-prefix' handle
22896 ;; `adaptive-fill-regexp' variable.
22897 (let (adaptive-fill-function)
22898 (fill-context-prefix
22899 post-affiliated
22900 (org-element-property :end element)))))
22901 ((looking-at "[ \t]+") (match-string 0))
22902 (t "")))))
22903 (comment-block
22904 ;; Only fill contents if P is within block boundaries.
22905 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22906 (forward-line)
22907 (point)))
22908 (cend (save-excursion
22909 (goto-char (org-element-property :end element))
22910 (skip-chars-backward " \r\t\n")
22911 (line-beginning-position))))
22912 (when (and (>= p cbeg) (< p cend))
22913 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22914 (match-string 0)
22915 "")))))))))))
22917 (declare-function message-goto-body "message" ())
22918 (defvar message-cite-prefix-regexp) ; From message.el
22920 (defun org-fill-element (&optional justify)
22921 "Fill element at point, when applicable.
22923 This function only applies to comment blocks, comments, example
22924 blocks and paragraphs. Also, as a special case, re-align table
22925 when point is at one.
22927 If JUSTIFY is non-nil (interactively, with prefix argument),
22928 justify as well. If `sentence-end-double-space' is non-nil, then
22929 period followed by one space does not end a sentence, so don't
22930 break a line there. The variable `fill-column' controls the
22931 width for filling.
22933 For convenience, when point is at a plain list, an item or
22934 a footnote definition, try to fill the first paragraph within."
22935 (with-syntax-table org-mode-transpose-word-syntax-table
22936 ;; Move to end of line in order to get the first paragraph within
22937 ;; a plain list or a footnote definition.
22938 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22939 ;; First check if point is in a blank line at the beginning of
22940 ;; the buffer. In that case, ignore filling.
22941 (cl-case (org-element-type element)
22942 ;; Use major mode filling function is src blocks.
22943 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22944 ;; Align Org tables, leave table.el tables as-is.
22945 (table-row (org-table-align) t)
22946 (table
22947 (when (eq (org-element-property :type element) 'org)
22948 (save-excursion
22949 (goto-char (org-element-property :post-affiliated element))
22950 (org-table-align)))
22952 (paragraph
22953 ;; Paragraphs may contain `line-break' type objects.
22954 (let ((beg (max (point-min)
22955 (org-element-property :contents-begin element)))
22956 (end (min (point-max)
22957 (org-element-property :contents-end element))))
22958 ;; Do nothing if point is at an affiliated keyword.
22959 (if (< (line-end-position) beg) t
22960 (when (derived-mode-p 'message-mode)
22961 ;; In `message-mode', do not fill following citation
22962 ;; in current paragraph nor text before message body.
22963 (let ((body-start (save-excursion (message-goto-body))))
22964 (when body-start (setq beg (max body-start beg))))
22965 (when (save-excursion
22966 (re-search-forward
22967 (concat "^" message-cite-prefix-regexp) end t))
22968 (setq end (match-beginning 0))))
22969 ;; Fill paragraph, taking line breaks into account.
22970 (save-excursion
22971 (goto-char beg)
22972 (let ((cuts (list beg)))
22973 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22974 (when (eq 'line-break
22975 (org-element-type
22976 (save-excursion (backward-char)
22977 (org-element-context))))
22978 (push (point) cuts)))
22979 (dolist (c (delq end cuts))
22980 (fill-region-as-paragraph c end justify)
22981 (setq end c))))
22982 t)))
22983 ;; Contents of `comment-block' type elements should be
22984 ;; filled as plain text, but only if point is within block
22985 ;; markers.
22986 (comment-block
22987 (let* ((case-fold-search t)
22988 (beg (save-excursion
22989 (goto-char (org-element-property :begin element))
22990 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22991 (forward-line)
22992 (point)))
22993 (end (save-excursion
22994 (goto-char (org-element-property :end element))
22995 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22996 (line-beginning-position))))
22997 (if (or (< (point) beg) (> (point) end)) t
22998 (fill-region-as-paragraph
22999 (save-excursion (end-of-line)
23000 (re-search-backward "^[ \t]*$" beg 'move)
23001 (line-beginning-position))
23002 (save-excursion (beginning-of-line)
23003 (re-search-forward "^[ \t]*$" end 'move)
23004 (line-beginning-position))
23005 justify))))
23006 ;; Fill comments.
23007 (comment
23008 (let ((begin (org-element-property :post-affiliated element))
23009 (end (org-element-property :end element)))
23010 (when (and (>= (point) begin) (<= (point) end))
23011 (let ((begin (save-excursion
23012 (end-of-line)
23013 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23014 (progn (forward-line) (point))
23015 begin)))
23016 (end (save-excursion
23017 (end-of-line)
23018 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23019 (1- (line-beginning-position))
23020 (skip-chars-backward " \r\t\n")
23021 (line-end-position)))))
23022 ;; Do not fill comments when at a blank line.
23023 (when (> end begin)
23024 (let ((fill-prefix
23025 (save-excursion
23026 (beginning-of-line)
23027 (looking-at "[ \t]*#")
23028 (let ((comment-prefix (match-string 0)))
23029 (goto-char (match-end 0))
23030 (if (looking-at adaptive-fill-regexp)
23031 (concat comment-prefix (match-string 0))
23032 (concat comment-prefix " "))))))
23033 (save-excursion
23034 (fill-region-as-paragraph begin end justify))))))
23036 ;; Ignore every other element.
23037 (otherwise t)))))
23039 (defun org-fill-paragraph (&optional justify region)
23040 "Fill element at point, when applicable.
23042 This function only applies to comment blocks, comments, example
23043 blocks and paragraphs. Also, as a special case, re-align table
23044 when point is at one.
23046 For convenience, when point is at a plain list, an item or
23047 a footnote definition, try to fill the first paragraph within.
23049 If JUSTIFY is non-nil (interactively, with prefix argument),
23050 justify as well. If `sentence-end-double-space' is non-nil, then
23051 period followed by one space does not end a sentence, so don't
23052 break a line there. The variable `fill-column' controls the
23053 width for filling.
23055 The REGION argument is non-nil if called interactively; in that
23056 case, if Transient Mark mode is enabled and the mark is active,
23057 fill each of the elements in the active region, instead of just
23058 filling the current element."
23059 (interactive (progn
23060 (barf-if-buffer-read-only)
23061 (list (if current-prefix-arg 'full) t)))
23062 (cond
23063 ((and (derived-mode-p 'message-mode)
23064 (or (not (message-in-body-p))
23065 (save-excursion (move-beginning-of-line 1)
23066 (looking-at message-cite-prefix-regexp))))
23067 ;; First ensure filling is correct in message-mode.
23068 (let ((fill-paragraph-function
23069 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23070 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23071 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23072 (paragraph-separate
23073 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23074 (fill-paragraph nil)))
23075 ((and region transient-mark-mode mark-active
23076 (not (eq (region-beginning) (region-end))))
23077 (let ((origin (point-marker))
23078 (start (region-beginning)))
23079 (unwind-protect
23080 (progn
23081 (goto-char (region-end))
23082 (while (> (point) start)
23083 (org-backward-paragraph)
23084 (org-fill-element justify)))
23085 (goto-char origin)
23086 (set-marker origin nil))))
23087 (t (org-fill-element justify))))
23088 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23090 (defun org-auto-fill-function ()
23091 "Auto-fill function."
23092 ;; Check if auto-filling is meaningful.
23093 (let ((fc (current-fill-column)))
23094 (when (and fc (> (current-column) fc))
23095 (let* ((fill-prefix (org-adaptive-fill-function))
23096 ;; Enforce empty fill prefix, if required. Otherwise, it
23097 ;; will be computed again.
23098 (adaptive-fill-mode (not (equal fill-prefix ""))))
23099 (when fill-prefix (do-auto-fill))))))
23101 (defun org-comment-line-break-function (&optional soft)
23102 "Break line at point and indent, continuing comment if within one.
23103 The inserted newline is marked hard if variable
23104 `use-hard-newlines' is true, unless optional argument SOFT is
23105 non-nil."
23106 (if soft (insert-and-inherit ?\n) (newline 1))
23107 (save-excursion (forward-char -1) (delete-horizontal-space))
23108 (delete-horizontal-space)
23109 (indent-to-left-margin)
23110 (insert-before-markers-and-inherit fill-prefix))
23113 ;;; Fixed Width Areas
23115 (defun org-toggle-fixed-width ()
23116 "Toggle fixed-width markup.
23118 Add or remove fixed-width markup on current line, whenever it
23119 makes sense. Return an error otherwise.
23121 If a region is active and if it contains only fixed-width areas
23122 or blank lines, remove all fixed-width markup in it. If the
23123 region contains anything else, convert all non-fixed-width lines
23124 to fixed-width ones.
23126 Blank lines at the end of the region are ignored unless the
23127 region only contains such lines."
23128 (interactive)
23129 (if (not (org-region-active-p))
23130 ;; No region:
23132 ;; Remove fixed width marker only in a fixed-with element.
23134 ;; Add fixed width maker in paragraphs, in blank lines after
23135 ;; elements or at the beginning of a headline or an inlinetask,
23136 ;; and before any one-line elements (e.g., a clock).
23137 (progn
23138 (beginning-of-line)
23139 (let* ((element (org-element-at-point))
23140 (type (org-element-type element)))
23141 (cond
23142 ((and (eq type 'fixed-width)
23143 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23144 (replace-match
23145 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23146 ((and (memq type '(babel-call clock comment diary-sexp headline
23147 horizontal-rule keyword paragraph
23148 planning))
23149 (<= (org-element-property :post-affiliated element) (point)))
23150 (skip-chars-forward " \t")
23151 (insert ": "))
23152 ((and (looking-at-p "[ \t]*$")
23153 (or (eq type 'inlinetask)
23154 (save-excursion
23155 (skip-chars-forward " \r\t\n")
23156 (<= (org-element-property :end element) (point)))))
23157 (delete-region (point) (line-end-position))
23158 (org-indent-line)
23159 (insert ": "))
23160 (t (user-error "Cannot insert a fixed-width line here")))))
23161 ;; Region active.
23162 (let* ((begin (save-excursion
23163 (goto-char (region-beginning))
23164 (line-beginning-position)))
23165 (end (copy-marker
23166 (save-excursion
23167 (goto-char (region-end))
23168 (unless (eolp) (beginning-of-line))
23169 (if (save-excursion (re-search-backward "\\S-" begin t))
23170 (progn (skip-chars-backward " \r\t\n") (point))
23171 (point)))))
23172 (all-fixed-width-p
23173 (catch 'not-all-p
23174 (save-excursion
23175 (goto-char begin)
23176 (skip-chars-forward " \r\t\n")
23177 (when (eobp) (throw 'not-all-p nil))
23178 (while (< (point) end)
23179 (let ((element (org-element-at-point)))
23180 (if (eq (org-element-type element) 'fixed-width)
23181 (goto-char (org-element-property :end element))
23182 (throw 'not-all-p nil))))
23183 t))))
23184 (if all-fixed-width-p
23185 (save-excursion
23186 (goto-char begin)
23187 (while (< (point) end)
23188 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23189 (replace-match
23190 "" nil nil nil
23191 (if (= (line-end-position) (match-end 0)) 0 1)))
23192 (forward-line)))
23193 (let ((min-ind (point-max)))
23194 ;; Find minimum indentation across all lines.
23195 (save-excursion
23196 (goto-char begin)
23197 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23198 (setq min-ind 0)
23199 (catch 'zerop
23200 (while (< (point) end)
23201 (unless (looking-at-p "[ \t]*$")
23202 (let ((ind (org-get-indentation)))
23203 (setq min-ind (min min-ind ind))
23204 (when (zerop ind) (throw 'zerop t))))
23205 (forward-line)))))
23206 ;; Loop over all lines and add fixed-width markup everywhere
23207 ;; but in fixed-width lines.
23208 (save-excursion
23209 (goto-char begin)
23210 (while (< (point) end)
23211 (cond
23212 ((org-at-heading-p)
23213 (insert ": ")
23214 (forward-line)
23215 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23216 (insert ":")
23217 (forward-line)))
23218 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23219 (let* ((element (org-element-at-point))
23220 (element-end (org-element-property :end element)))
23221 (if (eq (org-element-type element) 'fixed-width)
23222 (progn (goto-char element-end)
23223 (skip-chars-backward " \r\t\n")
23224 (forward-line))
23225 (let ((limit (min end element-end)))
23226 (while (< (point) limit)
23227 (org-move-to-column min-ind t)
23228 (insert ": ")
23229 (forward-line))))))
23231 (org-move-to-column min-ind t)
23232 (insert ": ")
23233 (forward-line)))))))
23234 (set-marker end nil))))
23237 ;;; Comments
23239 ;; Org comments syntax is quite complex. It requires the entire line
23240 ;; to be just a comment. Also, even with the right syntax at the
23241 ;; beginning of line, some elements (e.g., verse-block or
23242 ;; example-block) don't accept comments. Usual Emacs comment commands
23243 ;; cannot cope with those requirements. Therefore, Org replaces them.
23245 ;; Org still relies on `comment-dwim', but cannot trust
23246 ;; `comment-only-p'. So, `comment-region-function' and
23247 ;; `uncomment-region-function' both point
23248 ;; to`org-comment-or-uncomment-region'. Eventually,
23249 ;; `org-insert-comment' takes care of insertion of comments at the
23250 ;; beginning of line.
23252 ;; `org-setup-comments-handling' install comments related variables
23253 ;; during `org-mode' initialization.
23255 (defun org-setup-comments-handling ()
23256 (interactive)
23257 (setq-local comment-use-syntax nil)
23258 (setq-local comment-start "# ")
23259 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23260 (setq-local comment-insert-comment-function 'org-insert-comment)
23261 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23262 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23264 (defun org-insert-comment ()
23265 "Insert an empty comment above current line.
23266 If the line is empty, insert comment at its beginning. When
23267 point is within a source block, comment according to the related
23268 major mode."
23269 (if (let ((element (org-element-at-point)))
23270 (and (eq (org-element-type element) 'src-block)
23271 (< (save-excursion
23272 (goto-char (org-element-property :post-affiliated element))
23273 (line-end-position))
23274 (point))
23275 (> (save-excursion
23276 (goto-char (org-element-property :end element))
23277 (skip-chars-backward " \r\t\n")
23278 (line-beginning-position))
23279 (point))))
23280 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23281 (beginning-of-line)
23282 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23283 (open-line 1))
23284 (org-indent-line)
23285 (insert "# ")))
23287 (defvar comment-empty-lines) ; From newcomment.el.
23288 (defun org-comment-or-uncomment-region (beg end &rest _)
23289 "Comment or uncomment each non-blank line in the region.
23290 Uncomment each non-blank line between BEG and END if it only
23291 contains commented lines. Otherwise, comment them. If region is
23292 strictly within a source block, use appropriate comment syntax."
23293 (if (let ((element (org-element-at-point)))
23294 (and (eq (org-element-type element) 'src-block)
23295 (< (save-excursion
23296 (goto-char (org-element-property :post-affiliated element))
23297 (line-end-position))
23298 beg)
23299 (>= (save-excursion
23300 (goto-char (org-element-property :end element))
23301 (skip-chars-backward " \r\t\n")
23302 (line-beginning-position))
23303 end)))
23304 ;; Translate region boundaries for the Org buffer to the source
23305 ;; buffer.
23306 (let ((offset (- end beg)))
23307 (save-excursion
23308 (goto-char beg)
23309 (org-babel-do-in-edit-buffer
23310 (comment-or-uncomment-region (point) (+ offset (point))))))
23311 (save-restriction
23312 ;; Restrict region
23313 (narrow-to-region (save-excursion (goto-char beg)
23314 (skip-chars-forward " \r\t\n" end)
23315 (line-beginning-position))
23316 (save-excursion (goto-char end)
23317 (skip-chars-backward " \r\t\n" beg)
23318 (line-end-position)))
23319 (let ((uncommentp
23320 ;; UNCOMMENTP is non-nil when every non blank line between
23321 ;; BEG and END is a comment.
23322 (save-excursion
23323 (goto-char (point-min))
23324 (while (and (not (eobp))
23325 (let ((element (org-element-at-point)))
23326 (and (eq (org-element-type element) 'comment)
23327 (goto-char (min (point-max)
23328 (org-element-property
23329 :end element)))))))
23330 (eobp))))
23331 (if uncommentp
23332 ;; Only blank lines and comments in region: uncomment it.
23333 (save-excursion
23334 (goto-char (point-min))
23335 (while (not (eobp))
23336 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23337 (replace-match "" nil nil nil 1))
23338 (forward-line)))
23339 ;; Comment each line in region.
23340 (let ((min-indent (point-max)))
23341 ;; First find the minimum indentation across all lines.
23342 (save-excursion
23343 (goto-char (point-min))
23344 (while (and (not (eobp)) (not (zerop min-indent)))
23345 (unless (looking-at "[ \t]*$")
23346 (setq min-indent (min min-indent (current-indentation))))
23347 (forward-line)))
23348 ;; Then loop over all lines.
23349 (save-excursion
23350 (goto-char (point-min))
23351 (while (not (eobp))
23352 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23353 ;; Don't get fooled by invisible text (e.g. link path)
23354 ;; when moving to column MIN-INDENT.
23355 (let ((buffer-invisibility-spec nil))
23356 (org-move-to-column min-indent t))
23357 (insert comment-start))
23358 (forward-line)))))))))
23360 (defun org-comment-dwim (_arg)
23361 "Call `comment-dwim' within a source edit buffer if needed."
23362 (interactive "*P")
23363 (if (org-in-src-block-p)
23364 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23365 (call-interactively 'comment-dwim)))
23368 ;;; Timestamps API
23370 ;; This section contains tools to operate on timestamp objects, as
23371 ;; returned by, e.g. `org-element-context'.
23373 (defun org-timestamp--to-internal-time (timestamp &optional end)
23374 "Encode TIMESTAMP object into Emacs internal time.
23375 Use end of date range or time range when END is non-nil."
23376 (apply #'encode-time
23377 (cons 0
23378 (mapcar
23379 (lambda (prop) (or (org-element-property prop timestamp) 0))
23380 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23381 '(:minute-start :hour-start :day-start :month-start
23382 :year-start))))))
23384 (defun org-timestamp-has-time-p (timestamp)
23385 "Non-nil when TIMESTAMP has a time specified."
23386 (org-element-property :hour-start timestamp))
23388 (defun org-timestamp-format (timestamp format &optional end utc)
23389 "Format a TIMESTAMP object into a string.
23391 FORMAT is a format specifier to be passed to
23392 `format-time-string'.
23394 When optional argument END is non-nil, use end of date-range or
23395 time-range, if possible.
23397 When optional argument UTC is non-nil, time will be expressed as
23398 Universal Time."
23399 (format-time-string
23400 format (org-timestamp--to-internal-time timestamp end)
23401 (and utc t)))
23403 (defun org-timestamp-split-range (timestamp &optional end)
23404 "Extract a TIMESTAMP object from a date or time range.
23406 END, when non-nil, means extract the end of the range.
23407 Otherwise, extract its start.
23409 Return a new timestamp object."
23410 (let ((type (org-element-property :type timestamp)))
23411 (if (memq type '(active inactive diary)) timestamp
23412 (let ((split-ts (org-element-copy timestamp)))
23413 ;; Set new type.
23414 (org-element-put-property
23415 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23416 ;; Copy start properties over end properties if END is
23417 ;; non-nil. Otherwise, copy end properties over `start' ones.
23418 (let ((p-alist '((:minute-start . :minute-end)
23419 (:hour-start . :hour-end)
23420 (:day-start . :day-end)
23421 (:month-start . :month-end)
23422 (:year-start . :year-end))))
23423 (dolist (p-cell p-alist)
23424 (org-element-put-property
23425 split-ts
23426 (funcall (if end #'car #'cdr) p-cell)
23427 (org-element-property
23428 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23429 ;; Eventually refresh `:raw-value'.
23430 (org-element-put-property split-ts :raw-value nil)
23431 (org-element-put-property
23432 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23434 (defun org-timestamp-translate (timestamp &optional boundary)
23435 "Translate TIMESTAMP object to custom format.
23437 Format string is defined in `org-time-stamp-custom-formats',
23438 which see.
23440 When optional argument BOUNDARY is non-nil, it is either the
23441 symbol `start' or `end'. In this case, only translate the
23442 starting or ending part of TIMESTAMP if it is a date or time
23443 range. Otherwise, translate both parts.
23445 Return timestamp as-is if `org-display-custom-times' is nil or if
23446 it has a `diary' type."
23447 (let ((type (org-element-property :type timestamp)))
23448 (if (or (not org-display-custom-times) (eq type 'diary))
23449 (org-element-interpret-data timestamp)
23450 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23451 org-time-stamp-custom-formats)))
23452 (if (and (not boundary) (memq type '(active-range inactive-range)))
23453 (concat (org-timestamp-format timestamp fmt)
23454 "--"
23455 (org-timestamp-format timestamp fmt t))
23456 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23460 ;;; Other stuff.
23462 (defvar reftex-docstruct-symbol)
23463 (defvar org--rds)
23465 (defun org-reftex-citation ()
23466 "Use reftex-citation to insert a citation into the buffer.
23467 This looks for a line like
23469 #+BIBLIOGRAPHY: foo plain option:-d
23471 and derives from it that foo.bib is the bibliography file relevant
23472 for this document. It then installs the necessary environment for RefTeX
23473 to work in this buffer and calls `reftex-citation' to insert a citation
23474 into the buffer.
23476 Export of such citations to both LaTeX and HTML is handled by the contributed
23477 package ox-bibtex by Taru Karttunen."
23478 (interactive)
23479 (let ((reftex-docstruct-symbol 'org--rds)
23480 org--rds bib)
23481 (org-with-wide-buffer
23482 (let ((case-fold-search t)
23483 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23484 (if (not (save-excursion
23485 (or (re-search-forward re nil t)
23486 (re-search-backward re nil t))))
23487 (user-error "No bibliography defined in file")
23488 (setq bib (concat (match-string 1) ".bib")
23489 org--rds (list (list 'bib bib))))))
23490 (call-interactively 'reftex-citation)))
23492 ;;;; Functions extending outline functionality
23494 (defun org-beginning-of-line (&optional n)
23495 "Go to the beginning of the current visible line.
23497 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23498 tags on the first attempt, and only move to after the tags when
23499 the cursor is already beyond the end of the headline.
23501 With argument N not nil or 1, move forward N - 1 lines first."
23502 (interactive "^p")
23503 (let ((origin (point))
23504 (special (pcase org-special-ctrl-a/e
23505 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23506 deactivate-mark)
23507 ;; First move to a visible line.
23508 (if (bound-and-true-p visual-line-mode)
23509 (beginning-of-visual-line n)
23510 (move-beginning-of-line n)
23511 ;; `move-beginning-of-line' may leave point after invisible
23512 ;; characters if line starts with such of these (e.g., with
23513 ;; a link at column 0). Really move to the beginning of the
23514 ;; current visible line.
23515 (beginning-of-line))
23516 (cond
23517 ;; No special behavior. Point is already at the beginning of
23518 ;; a line, logical or visual.
23519 ((not special))
23520 ;; `beginning-of-visual-line' left point before logical beginning
23521 ;; of line: point is at the beginning of a visual line. Bail
23522 ;; out.
23523 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23524 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23525 ;; At a headline, special position is before the title, but
23526 ;; after any TODO keyword or priority cookie.
23527 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23528 (line-end-position)))
23529 (bol (point)))
23530 (if (eq special 'reversed)
23531 (when (and (= origin bol) (eq last-command this-command))
23532 (goto-char refpos))
23533 (when (or (> origin refpos) (= origin bol))
23534 (goto-char refpos)))))
23535 ((and (looking-at org-list-full-item-re)
23536 (memq (org-element-type (save-match-data (org-element-at-point)))
23537 '(item plain-list)))
23538 ;; Set special position at first white space character after
23539 ;; bullet, and check-box, if any.
23540 (let ((after-bullet
23541 (let ((box (match-end 3)))
23542 (cond ((not box) (match-end 1))
23543 ((eq (char-after box) ?\s) (1+ box))
23544 (t box)))))
23545 (if (eq special 'reversed)
23546 (when (and (= (point) origin) (eq last-command this-command))
23547 (goto-char after-bullet))
23548 (when (or (> origin after-bullet) (= (point) origin))
23549 (goto-char after-bullet)))))
23550 ;; No special context. Point is already at beginning of line.
23551 (t nil))))
23553 (defun org-end-of-line (&optional n)
23554 "Go to the end of the line, but before ellipsis, if any.
23556 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23557 tags on the first attempt, and only move to after the tags when
23558 the cursor is already beyond the end of the headline.
23560 With argument N not nil or 1, move forward N - 1 lines first."
23561 (interactive "^p")
23562 (let ((origin (point))
23563 (special (pcase org-special-ctrl-a/e
23564 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23565 deactivate-mark)
23566 ;; First move to a visible line.
23567 (if (bound-and-true-p visual-line-mode)
23568 (beginning-of-visual-line n)
23569 (move-beginning-of-line n))
23570 (cond
23571 ;; At a headline, with tags.
23572 ((and special
23573 (save-excursion
23574 (beginning-of-line)
23575 (let ((case-fold-search nil))
23576 (looking-at org-complex-heading-regexp)))
23577 (match-end 5))
23578 (let ((tags (save-excursion
23579 (goto-char (match-beginning 5))
23580 (skip-chars-backward " \t")
23581 (point)))
23582 (visual-end (and (bound-and-true-p visual-line-mode)
23583 (save-excursion
23584 (end-of-visual-line)
23585 (point)))))
23586 ;; If `end-of-visual-line' brings us before end of line or
23587 ;; even tags, i.e., the headline spans over multiple visual
23588 ;; lines, move there.
23589 (cond ((and visual-end
23590 (< visual-end tags)
23591 (<= origin visual-end))
23592 (goto-char visual-end))
23593 ((eq special 'reversed)
23594 (if (and (= origin (line-end-position))
23595 (eq this-command last-command))
23596 (goto-char tags)
23597 (end-of-line)))
23599 (if (or (< origin tags) (= origin (line-end-position)))
23600 (goto-char tags)
23601 (end-of-line))))))
23602 ((bound-and-true-p visual-line-mode)
23603 (let ((bol (line-beginning-position)))
23604 (end-of-visual-line)
23605 ;; If `end-of-visual-line' gets us past the ellipsis at the
23606 ;; end of a line, backtrack and use `end-of-line' instead.
23607 (when (/= bol (line-beginning-position))
23608 (goto-char bol)
23609 (end-of-line))))
23610 (t (end-of-line)))))
23612 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23613 (define-key org-mode-map "\C-e" 'org-end-of-line)
23615 (defun org-backward-sentence (&optional _arg)
23616 "Go to beginning of sentence, or beginning of table field.
23617 This will call `backward-sentence' or `org-table-beginning-of-field',
23618 depending on context."
23619 (interactive)
23620 (let* ((element (org-element-at-point))
23621 (contents-begin (org-element-property :contents-begin element))
23622 (table (org-element-lineage element '(table) t)))
23623 (if (and table
23624 (> (point) contents-begin)
23625 (<= (point) (org-element-property :contents-end table)))
23626 (call-interactively #'org-table-beginning-of-field)
23627 (save-restriction
23628 (when (and contents-begin
23629 (< (point-min) contents-begin)
23630 (> (point) contents-begin))
23631 (narrow-to-region contents-begin
23632 (org-element-property :contents-end element)))
23633 (call-interactively #'backward-sentence)))))
23635 (defun org-forward-sentence (&optional _arg)
23636 "Go to end of sentence, or end of table field.
23637 This will call `forward-sentence' or `org-table-end-of-field',
23638 depending on context."
23639 (interactive)
23640 (let* ((element (org-element-at-point))
23641 (contents-end (org-element-property :contents-end element))
23642 (table (org-element-lineage element '(table) t)))
23643 (if (and table
23644 (>= (point) (org-element-property :contents-begin table))
23645 (< (point) contents-end))
23646 (call-interactively #'org-table-end-of-field)
23647 (save-restriction
23648 (when (and contents-end
23649 (> (point-max) contents-end)
23650 ;; Skip blank lines between elements.
23651 (< (org-element-property :end element)
23652 (save-excursion (goto-char contents-end)
23653 (skip-chars-forward " \r\t\n"))))
23654 (narrow-to-region (org-element-property :contents-begin element)
23655 contents-end))
23656 (call-interactively #'forward-sentence)))))
23658 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23659 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23661 (defun org-kill-line (&optional _arg)
23662 "Kill line, to tags or end of line."
23663 (interactive)
23664 (cond
23665 ((or (not org-special-ctrl-k)
23666 (bolp)
23667 (not (org-at-heading-p)))
23668 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23669 org-ctrl-k-protect-subtree
23670 (or (eq org-ctrl-k-protect-subtree 'error)
23671 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23672 (user-error "C-k aborted as it would kill a hidden subtree"))
23673 (call-interactively
23674 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23675 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23676 (kill-region (point) (match-beginning 1))
23677 (org-set-tags nil t))
23678 (t (kill-region (point) (point-at-eol)))))
23680 (define-key org-mode-map "\C-k" 'org-kill-line)
23682 (defun org-yank (&optional arg)
23683 "Yank. If the kill is a subtree, treat it specially.
23684 This command will look at the current kill and check if is a single
23685 subtree, or a series of subtrees[1]. If it passes the test, and if the
23686 cursor is at the beginning of a line or after the stars of a currently
23687 empty headline, then the yank is handled specially. How exactly depends
23688 on the value of the following variables.
23690 `org-yank-folded-subtrees'
23691 By default, this variable is non-nil, which results in
23692 subtree(s) being folded after insertion, except if doing so
23693 would swallow text after the yanked text.
23695 `org-yank-adjusted-subtrees'
23696 When non-nil (the default value is nil), the subtree will be
23697 promoted or demoted in order to fit into the local outline tree
23698 structure, which means that the level will be adjusted so that it
23699 becomes the smaller one of the two *visible* surrounding headings.
23701 Any prefix to this command will cause `yank' to be called directly with
23702 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23703 will just
23704 plainly yank the text as it is.
23706 \[1] The test checks if the first non-white line is a heading
23707 and if there are no other headings with fewer stars."
23708 (interactive "P")
23709 (org-yank-generic 'yank arg))
23711 (defun org-yank-generic (command arg)
23712 "Perform some yank-like command.
23714 This function implements the behavior described in the `org-yank'
23715 documentation. However, it has been generalized to work for any
23716 interactive command with similar behavior."
23718 ;; pretend to be command COMMAND
23719 (setq this-command command)
23721 (if arg
23722 (call-interactively command)
23724 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23725 (and (org-kill-is-subtree-p)
23726 (or (bolp)
23727 (and (looking-at "[ \t]*$")
23728 (string-match
23729 "\\`\\*+\\'"
23730 (buffer-substring (point-at-bol) (point)))))))
23731 swallowp)
23732 (cond
23733 ((and subtreep org-yank-folded-subtrees)
23734 (let ((beg (point))
23735 end)
23736 (if (and subtreep org-yank-adjusted-subtrees)
23737 (org-paste-subtree nil nil 'for-yank)
23738 (call-interactively command))
23740 (setq end (point))
23741 (goto-char beg)
23742 (when (and (bolp) subtreep
23743 (not (setq swallowp
23744 (org-yank-folding-would-swallow-text beg end))))
23745 (org-with-limited-levels
23746 (or (looking-at org-outline-regexp)
23747 (re-search-forward org-outline-regexp-bol end t))
23748 (while (and (< (point) end) (looking-at org-outline-regexp))
23749 (outline-hide-subtree)
23750 (org-cycle-show-empty-lines 'folded)
23751 (condition-case nil
23752 (outline-forward-same-level 1)
23753 (error (goto-char end))))))
23754 (when swallowp
23755 (message
23756 "Inserted text not folded because that would swallow text"))
23758 (goto-char end)
23759 (skip-chars-forward " \t\n\r")
23760 (beginning-of-line 1)
23761 (push-mark beg 'nomsg)))
23762 ((and subtreep org-yank-adjusted-subtrees)
23763 (let ((beg (point-at-bol)))
23764 (org-paste-subtree nil nil 'for-yank)
23765 (push-mark beg 'nomsg)))
23767 (call-interactively command))))))
23769 (defun org-yank-folding-would-swallow-text (beg end)
23770 "Would hide-subtree at BEG swallow any text after END?"
23771 (let (level)
23772 (org-with-limited-levels
23773 (save-excursion
23774 (goto-char beg)
23775 (when (or (looking-at org-outline-regexp)
23776 (re-search-forward org-outline-regexp-bol end t))
23777 (setq level (org-outline-level)))
23778 (goto-char end)
23779 (skip-chars-forward " \t\r\n\v\f")
23780 (not (or (eobp)
23781 (and (bolp) (looking-at-p org-outline-regexp)
23782 (<= (org-outline-level) level))))))))
23784 (define-key org-mode-map "\C-y" 'org-yank)
23786 (defun org-truely-invisible-p ()
23787 "Check if point is at a character currently not visible.
23788 This version does not only check the character property, but also
23789 `visible-mode'."
23790 (unless (bound-and-true-p visible-mode)
23791 (org-invisible-p)))
23793 (defun org-invisible-p2 ()
23794 "Check if point is at a character currently not visible.
23796 If the point is at EOL (and not at the beginning of a buffer too),
23797 move it back by one char before doing this check."
23798 (save-excursion
23799 (when (and (eolp) (not (bobp)))
23800 (backward-char 1))
23801 (org-invisible-p)))
23803 (defun org-back-to-heading (&optional invisible-ok)
23804 "Call `outline-back-to-heading', but provide a better error message."
23805 (condition-case nil
23806 (outline-back-to-heading invisible-ok)
23807 (error (error "Before first headline at position %d in buffer %s"
23808 (point) (current-buffer)))))
23810 (defun org-before-first-heading-p ()
23811 "Before first heading?"
23812 (save-excursion
23813 (end-of-line)
23814 (null (re-search-backward org-outline-regexp-bol nil t))))
23816 (defun org-at-heading-p (&optional ignored)
23817 (outline-on-heading-p t))
23819 (defun org-in-commented-heading-p (&optional no-inheritance)
23820 "Non-nil if point is under a commented heading.
23821 This function also checks ancestors of the current headline,
23822 unless optional argument NO-INHERITANCE is non-nil."
23823 (cond
23824 ((org-before-first-heading-p) nil)
23825 ((let ((headline (nth 4 (org-heading-components))))
23826 (and headline
23827 (let ((case-fold-search nil))
23828 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23829 headline)))))
23830 (no-inheritance nil)
23832 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23834 (defun org-at-comment-p nil
23835 "Is cursor in a commented line?"
23836 (save-excursion
23837 (save-match-data
23838 (beginning-of-line)
23839 (looking-at "^[ \t]*# "))))
23841 (defun org-at-drawer-p nil
23842 "Is cursor at a drawer keyword?"
23843 (save-excursion
23844 (move-beginning-of-line 1)
23845 (looking-at org-drawer-regexp)))
23847 (defun org-at-block-p nil
23848 "Is cursor at a block keyword?"
23849 (save-excursion
23850 (move-beginning-of-line 1)
23851 (looking-at org-block-regexp)))
23853 (defun org-point-at-end-of-empty-headline ()
23854 "If point is at the end of an empty headline, return t, else nil.
23855 If the heading only contains a TODO keyword, it is still still considered
23856 empty."
23857 (let ((case-fold-search nil))
23858 (and (looking-at "[ \t]*$")
23859 org-todo-line-regexp
23860 (save-excursion
23861 (beginning-of-line)
23862 (looking-at org-todo-line-regexp)
23863 (string= (match-string 3) "")))))
23865 (defun org-at-heading-or-item-p ()
23866 (or (org-at-heading-p) (org-at-item-p)))
23868 (defun org-at-target-p ()
23869 (or (org-in-regexp org-radio-target-regexp)
23870 (org-in-regexp org-target-regexp)))
23871 ;; Compatibility alias with Org versions < 7.8.03
23872 (defalias 'org-on-target-p 'org-at-target-p)
23874 (defun org-up-heading-all (arg)
23875 "Move to the heading line of which the present line is a subheading.
23876 This function considers both visible and invisible heading lines.
23877 With argument, move up ARG levels."
23878 (outline-up-heading arg t))
23880 (defun org-up-heading-safe ()
23881 "Move to the heading line of which the present line is a subheading.
23882 This version will not throw an error. It will return the level of the
23883 headline found, or nil if no higher level is found.
23885 Also, this function will be a lot faster than `outline-up-heading',
23886 because it relies on stars being the outline starters. This can really
23887 make a significant difference in outlines with very many siblings."
23888 (when (ignore-errors (org-back-to-heading t))
23889 (let ((level-up (1- (funcall outline-level))))
23890 (and (> level-up 0)
23891 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23892 (funcall outline-level)))))
23894 (defun org-first-sibling-p ()
23895 "Is this heading the first child of its parents?"
23896 (interactive)
23897 (let ((re org-outline-regexp-bol)
23898 level l)
23899 (unless (org-at-heading-p t)
23900 (user-error "Not at a heading"))
23901 (setq level (funcall outline-level))
23902 (save-excursion
23903 (if (not (re-search-backward re nil t))
23905 (setq l (funcall outline-level))
23906 (< l level)))))
23908 (defun org-goto-sibling (&optional previous)
23909 "Goto the next sibling, even if it is invisible.
23910 When PREVIOUS is set, go to the previous sibling instead. Returns t
23911 when a sibling was found. When none is found, return nil and don't
23912 move point."
23913 (let ((fun (if previous 're-search-backward 're-search-forward))
23914 (pos (point))
23915 (re org-outline-regexp-bol)
23916 level l)
23917 (when (ignore-errors (org-back-to-heading t))
23918 (setq level (funcall outline-level))
23919 (catch 'exit
23920 (or previous (forward-char 1))
23921 (while (funcall fun re nil t)
23922 (setq l (funcall outline-level))
23923 (when (< l level) (goto-char pos) (throw 'exit nil))
23924 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23925 (goto-char pos)
23926 nil))))
23928 (defun org-show-siblings ()
23929 "Show all siblings of the current headline."
23930 (save-excursion
23931 (while (org-goto-sibling) (org-flag-heading nil)))
23932 (save-excursion
23933 (while (org-goto-sibling 'previous)
23934 (org-flag-heading nil))))
23936 (defun org-goto-first-child ()
23937 "Goto the first child, even if it is invisible.
23938 Return t when a child was found. Otherwise don't move point and
23939 return nil."
23940 (let (level (pos (point)) (re org-outline-regexp-bol))
23941 (when (ignore-errors (org-back-to-heading t))
23942 (setq level (outline-level))
23943 (forward-char 1)
23944 (if (and (re-search-forward re nil t) (> (outline-level) level))
23945 (progn (goto-char (match-beginning 0)) t)
23946 (goto-char pos) nil))))
23948 (defun org-show-hidden-entry ()
23949 "Show an entry where even the heading is hidden."
23950 (save-excursion
23951 (org-show-entry)))
23953 (defun org-flag-heading (flag &optional entry)
23954 "Flag the current heading. FLAG non-nil means make invisible.
23955 When ENTRY is non-nil, show the entire entry."
23956 (save-excursion
23957 (org-back-to-heading t)
23958 ;; Check if we should show the entire entry
23959 (if entry
23960 (progn
23961 (org-show-entry)
23962 (save-excursion
23963 (and (outline-next-heading)
23964 (org-flag-heading nil))))
23965 (outline-flag-region (max (point-min) (1- (point)))
23966 (save-excursion (outline-end-of-heading) (point))
23967 flag))))
23969 (defun org-get-next-sibling ()
23970 "Move to next heading of the same level, and return point.
23971 If there is no such heading, return nil.
23972 This is like outline-next-sibling, but invisible headings are ok."
23973 (let ((level (funcall outline-level)))
23974 (outline-next-heading)
23975 (while (and (not (eobp)) (> (funcall outline-level) level))
23976 (outline-next-heading))
23977 (unless (or (eobp) (< (funcall outline-level) level))
23978 (point))))
23980 (defun org-get-last-sibling ()
23981 "Move to previous heading of the same level, and return point.
23982 If there is no such heading, return nil."
23983 (let ((opoint (point))
23984 (level (funcall outline-level)))
23985 (outline-previous-heading)
23986 (when (and (/= (point) opoint) (outline-on-heading-p t))
23987 (while (and (> (funcall outline-level) level)
23988 (not (bobp)))
23989 (outline-previous-heading))
23990 (unless (< (funcall outline-level) level)
23991 (point)))))
23993 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23994 "Goto to the end of a subtree."
23995 ;; This contains an exact copy of the original function, but it uses
23996 ;; `org-back-to-heading', to make it work also in invisible
23997 ;; trees. And is uses an invisible-ok argument.
23998 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23999 ;; Furthermore, when used inside Org, finding the end of a large subtree
24000 ;; with many children and grandchildren etc, this can be much faster
24001 ;; than the outline version.
24002 (org-back-to-heading invisible-ok)
24003 (let ((first t)
24004 (level (funcall outline-level)))
24005 (if (and (derived-mode-p 'org-mode) (< level 1000))
24006 ;; A true heading (not a plain list item), in Org
24007 ;; This means we can easily find the end by looking
24008 ;; only for the right number of stars. Using a regexp to do
24009 ;; this is so much faster than using a Lisp loop.
24010 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24011 (forward-char 1)
24012 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24013 ;; something else, do it the slow way
24014 (while (and (not (eobp))
24015 (or first (> (funcall outline-level) level)))
24016 (setq first nil)
24017 (outline-next-heading)))
24018 (unless to-heading
24019 (when (memq (preceding-char) '(?\n ?\^M))
24020 ;; Go to end of line before heading
24021 (forward-char -1)
24022 (when (memq (preceding-char) '(?\n ?\^M))
24023 ;; leave blank line before heading
24024 (forward-char -1)))))
24025 (point))
24027 (defun org-end-of-meta-data (&optional full)
24028 "Skip planning line and properties drawer in current entry.
24029 When optional argument FULL is non-nil, also skip empty lines,
24030 clocking lines and regular drawers at the beginning of the
24031 entry."
24032 (org-back-to-heading t)
24033 (forward-line)
24034 (when (looking-at-p org-planning-line-re) (forward-line))
24035 (when (looking-at org-property-drawer-re)
24036 (goto-char (match-end 0))
24037 (forward-line))
24038 (when (and full (not (org-at-heading-p)))
24039 (catch 'exit
24040 (let ((end (save-excursion (outline-next-heading) (point)))
24041 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24042 (while (not (eobp))
24043 (cond ((looking-at-p org-drawer-regexp)
24044 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24045 (forward-line)
24046 (throw 'exit t)))
24047 ((looking-at-p re) (forward-line))
24048 (t (throw 'exit t))))))))
24050 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24051 "Move forward to the ARG'th subheading at same level as this one.
24052 Stop at the first and last subheadings of a superior heading.
24053 Normally this only looks at visible headings, but when INVISIBLE-OK is
24054 non-nil it will also look at invisible ones."
24055 (interactive "p")
24056 (let ((backward? (and arg (< arg 0))))
24057 (if (org-before-first-heading-p)
24058 (if backward? (goto-char (point-min)) (outline-next-heading))
24059 (org-back-to-heading invisible-ok)
24060 (unless backward? (end-of-line)) ;do not match current headline
24061 (let ((level (- (match-end 0) (match-beginning 0) 1))
24062 (f (if backward? #'re-search-backward #'re-search-forward))
24063 (count (if arg (abs arg) 1))
24064 (result (point)))
24065 (while (and (> count 0)
24066 (funcall f org-outline-regexp-bol nil 'move))
24067 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24068 (cond ((< l level) (setq count 0))
24069 ((and (= l level)
24070 (or invisible-ok
24071 (not (org-invisible-p
24072 (line-beginning-position)))))
24073 (cl-decf count)
24074 (when (= l level) (setq result (point)))))))
24075 (goto-char result))
24076 (beginning-of-line))))
24078 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24079 "Move backward to the ARG'th subheading at same level as this one.
24080 Stop at the first and last subheadings of a superior heading."
24081 (interactive "p")
24082 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24084 (defun org-next-visible-heading (arg)
24085 "Move to the next visible heading.
24087 This function wraps `outline-next-visible-heading' with
24088 `org-with-limited-levels' in order to skip over inline tasks and
24089 respect customization of `org-odd-levels-only'."
24090 (interactive "p")
24091 (org-with-limited-levels
24092 (outline-next-visible-heading arg)))
24094 (defun org-previous-visible-heading (arg)
24095 "Move to the previous visible heading.
24097 This function wraps `outline-previous-visible-heading' with
24098 `org-with-limited-levels' in order to skip over inline tasks and
24099 respect customization of `org-odd-levels-only'."
24100 (interactive "p")
24101 (org-with-limited-levels
24102 (outline-previous-visible-heading arg)))
24104 (defun org-next-block (arg &optional backward block-regexp)
24105 "Jump to the next block.
24107 With a prefix argument ARG, jump forward ARG many blocks.
24109 When BACKWARD is non-nil, jump to the previous block.
24111 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24112 Match data is set according to this regexp when the function
24113 returns.
24115 Return point at beginning of the opening line of found block.
24116 Throw an error if no block is found."
24117 (interactive "p")
24118 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24119 (case-fold-search t)
24120 (search-fn (if backward #'re-search-backward #'re-search-forward))
24121 (count (or arg 1))
24122 (origin (point))
24123 last-element)
24124 (if backward (beginning-of-line) (end-of-line))
24125 (while (and (> count 0) (funcall search-fn re nil t))
24126 (let ((element (save-excursion
24127 (goto-char (match-beginning 0))
24128 (save-match-data (org-element-at-point)))))
24129 (when (and (memq (org-element-type element)
24130 '(center-block comment-block dynamic-block
24131 example-block export-block quote-block
24132 special-block src-block verse-block))
24133 (<= (match-beginning 0)
24134 (org-element-property :post-affiliated element)))
24135 (setq last-element element)
24136 (cl-decf count))))
24137 (if (= count 0)
24138 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24139 (save-match-data (org-show-context)))
24140 (goto-char origin)
24141 (user-error "No %s code blocks" (if backward "previous" "further")))))
24143 (defun org-previous-block (arg &optional block-regexp)
24144 "Jump to the previous block.
24145 With a prefix argument ARG, jump backward ARG many source blocks.
24146 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24147 (interactive "p")
24148 (org-next-block arg t block-regexp))
24150 (defun org-forward-paragraph ()
24151 "Move forward to beginning of next paragraph or equivalent.
24153 The function moves point to the beginning of the next visible
24154 structural element, which can be a paragraph, a table, a list
24155 item, etc. It also provides some special moves for convenience:
24157 - On an affiliated keyword, jump to the beginning of the
24158 relative element.
24159 - On an item or a footnote definition, move to the second
24160 element inside, if any.
24161 - On a table or a property drawer, jump after it.
24162 - On a verse or source block, stop after blank lines."
24163 (interactive)
24164 (unless (eobp)
24165 (let* ((deactivate-mark nil)
24166 (element (org-element-at-point))
24167 (type (org-element-type element))
24168 (post-affiliated (org-element-property :post-affiliated element))
24169 (contents-begin (org-element-property :contents-begin element))
24170 (contents-end (org-element-property :contents-end element))
24171 (end (let ((end (org-element-property :end element)) (parent element))
24172 (while (and (setq parent (org-element-property :parent parent))
24173 (= (org-element-property :contents-end parent) end))
24174 (setq end (org-element-property :end parent)))
24175 end)))
24176 (cond ((not element)
24177 (skip-chars-forward " \r\t\n")
24178 (or (eobp) (beginning-of-line)))
24179 ;; On affiliated keywords, move to element's beginning.
24180 ((< (point) post-affiliated)
24181 (goto-char post-affiliated))
24182 ;; At a table row, move to the end of the table. Similarly,
24183 ;; at a node property, move to the end of the property
24184 ;; drawer.
24185 ((memq type '(node-property table-row))
24186 (goto-char (org-element-property
24187 :end (org-element-property :parent element))))
24188 ((memq type '(property-drawer table)) (goto-char end))
24189 ;; Consider blank lines as separators in verse and source
24190 ;; blocks to ease editing.
24191 ((memq type '(src-block verse-block))
24192 (when (eq type 'src-block)
24193 (setq contents-end
24194 (save-excursion (goto-char end)
24195 (skip-chars-backward " \r\t\n")
24196 (line-beginning-position))))
24197 (beginning-of-line)
24198 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24199 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24200 (goto-char end)
24201 (skip-chars-forward " \r\t\n")
24202 (if (= (point) contents-end) (goto-char end)
24203 (beginning-of-line))))
24204 ;; With no contents, just skip element.
24205 ((not contents-begin) (goto-char end))
24206 ;; If contents are invisible, skip the element altogether.
24207 ((org-invisible-p (line-end-position))
24208 (cl-case type
24209 (headline
24210 (org-with-limited-levels (outline-next-visible-heading 1)))
24211 ;; At a plain list, make sure we move to the next item
24212 ;; instead of skipping the whole list.
24213 (plain-list (forward-char)
24214 (org-forward-paragraph))
24215 (otherwise (goto-char end))))
24216 ((>= (point) contents-end) (goto-char end))
24217 ((>= (point) contents-begin)
24218 ;; This can only happen on paragraphs and plain lists.
24219 (cl-case type
24220 (paragraph (goto-char end))
24221 ;; At a plain list, try to move to second element in
24222 ;; first item, if possible.
24223 (plain-list (end-of-line)
24224 (org-forward-paragraph))))
24225 ;; When contents start on the middle of a line (e.g. in
24226 ;; items and footnote definitions), try to reach first
24227 ;; element starting after current line.
24228 ((> (line-end-position) contents-begin)
24229 (end-of-line)
24230 (org-forward-paragraph))
24231 (t (goto-char contents-begin))))))
24233 (defun org-backward-paragraph ()
24234 "Move backward to start of previous paragraph or equivalent.
24236 The function moves point to the beginning of the current
24237 structural element, which can be a paragraph, a table, a list
24238 item, etc., or to the beginning of the previous visible one if
24239 point is already there. It also provides some special moves for
24240 convenience:
24242 - On an affiliated keyword, jump to the first one.
24243 - On a table or a property drawer, move to its beginning.
24244 - On a verse or source block, stop before blank lines."
24245 (interactive)
24246 (unless (bobp)
24247 (let* ((deactivate-mark nil)
24248 (element (org-element-at-point))
24249 (type (org-element-type element))
24250 (contents-begin (org-element-property :contents-begin element))
24251 (contents-end (org-element-property :contents-end element))
24252 (post-affiliated (org-element-property :post-affiliated element))
24253 (begin (org-element-property :begin element)))
24254 (cond
24255 ((not element) (goto-char (point-min)))
24256 ((= (point) begin)
24257 (backward-char)
24258 (org-backward-paragraph))
24259 ((<= (point) post-affiliated) (goto-char begin))
24260 ((memq type '(node-property table-row))
24261 (goto-char (org-element-property
24262 :post-affiliated (org-element-property :parent element))))
24263 ((memq type '(property-drawer table)) (goto-char begin))
24264 ((memq type '(src-block verse-block))
24265 (when (eq type 'src-block)
24266 (setq contents-begin
24267 (save-excursion (goto-char begin) (forward-line) (point))))
24268 (if (= (point) contents-begin) (goto-char post-affiliated)
24269 ;; Inside a verse block, see blank lines as paragraph
24270 ;; separators.
24271 (let ((origin (point)))
24272 (skip-chars-backward " \r\t\n" contents-begin)
24273 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24274 (skip-chars-forward " \r\t\n" origin)
24275 (if (= (point) origin) (goto-char contents-begin)
24276 (beginning-of-line))))))
24277 ((not contents-begin) (goto-char (or post-affiliated begin)))
24278 ((eq type 'paragraph)
24279 (goto-char contents-begin)
24280 ;; When at first paragraph in an item or a footnote definition,
24281 ;; move directly to beginning of line.
24282 (let ((parent-contents
24283 (org-element-property
24284 :contents-begin (org-element-property :parent element))))
24285 (when (and parent-contents (= parent-contents contents-begin))
24286 (beginning-of-line))))
24287 ;; At the end of a greater element, move to the beginning of the
24288 ;; last element within.
24289 ((>= (point) contents-end)
24290 (goto-char (1- contents-end))
24291 (org-backward-paragraph))
24292 (t (goto-char (or post-affiliated begin))))
24293 ;; Ensure we never leave point invisible.
24294 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24296 (defun org-forward-element ()
24297 "Move forward by one element.
24298 Move to the next element at the same level, when possible."
24299 (interactive)
24300 (cond ((eobp) (user-error "Cannot move further down"))
24301 ((org-with-limited-levels (org-at-heading-p))
24302 (let ((origin (point)))
24303 (goto-char (org-end-of-subtree nil t))
24304 (unless (org-with-limited-levels (org-at-heading-p))
24305 (goto-char origin)
24306 (user-error "Cannot move further down"))))
24308 (let* ((elem (org-element-at-point))
24309 (end (org-element-property :end elem))
24310 (parent (org-element-property :parent elem)))
24311 (cond ((and parent (= (org-element-property :contents-end parent) end))
24312 (goto-char (org-element-property :end parent)))
24313 ((integer-or-marker-p end) (goto-char end))
24314 (t (message "No element at point")))))))
24316 (defun org-backward-element ()
24317 "Move backward by one element.
24318 Move to the previous element at the same level, when possible."
24319 (interactive)
24320 (cond ((bobp) (user-error "Cannot move further up"))
24321 ((org-with-limited-levels (org-at-heading-p))
24322 ;; At a headline, move to the previous one, if any, or stay
24323 ;; here.
24324 (let ((origin (point)))
24325 (org-with-limited-levels (org-backward-heading-same-level 1))
24326 ;; When current headline has no sibling above, move to its
24327 ;; parent.
24328 (when (= (point) origin)
24329 (or (org-with-limited-levels (org-up-heading-safe))
24330 (progn (goto-char origin)
24331 (user-error "Cannot move further up"))))))
24333 (let* ((elem (org-element-at-point))
24334 (beg (org-element-property :begin elem)))
24335 (cond
24336 ;; Move to beginning of current element if point isn't
24337 ;; there already.
24338 ((null beg) (message "No element at point"))
24339 ((/= (point) beg) (goto-char beg))
24340 (t (goto-char beg)
24341 (skip-chars-backward " \r\t\n")
24342 (unless (bobp)
24343 (let ((prev (org-element-at-point)))
24344 (goto-char (org-element-property :begin prev))
24345 (while (and (setq prev (org-element-property :parent prev))
24346 (<= (org-element-property :end prev) beg))
24347 (goto-char (org-element-property :begin prev)))))))))))
24349 (defun org-up-element ()
24350 "Move to upper element."
24351 (interactive)
24352 (if (org-with-limited-levels (org-at-heading-p))
24353 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24354 (let* ((elem (org-element-at-point))
24355 (parent (org-element-property :parent elem)))
24356 (if parent (goto-char (org-element-property :begin parent))
24357 (if (org-with-limited-levels (org-before-first-heading-p))
24358 (user-error "No surrounding element")
24359 (org-with-limited-levels (org-back-to-heading)))))))
24361 (defun org-down-element ()
24362 "Move to inner element."
24363 (interactive)
24364 (let ((element (org-element-at-point)))
24365 (cond
24366 ((memq (org-element-type element) '(plain-list table))
24367 (goto-char (org-element-property :contents-begin element))
24368 (forward-char))
24369 ((memq (org-element-type element) org-element-greater-elements)
24370 ;; If contents are hidden, first disclose them.
24371 (when (org-invisible-p (line-end-position)) (org-cycle))
24372 (goto-char (or (org-element-property :contents-begin element)
24373 (user-error "No content for this element"))))
24374 (t (user-error "No inner element")))))
24376 (defun org-drag-element-backward ()
24377 "Move backward element at point."
24378 (interactive)
24379 (let ((elem (or (org-element-at-point)
24380 (user-error "No element at point"))))
24381 (if (eq (org-element-type elem) 'headline)
24382 ;; Preserve point when moving a whole tree, even if point was
24383 ;; on blank lines below the headline.
24384 (let ((offset (skip-chars-backward " \t\n")))
24385 (unwind-protect (org-move-subtree-up)
24386 (forward-char (- offset))))
24387 (let ((prev-elem
24388 (save-excursion
24389 (goto-char (org-element-property :begin elem))
24390 (skip-chars-backward " \r\t\n")
24391 (unless (bobp)
24392 (let* ((beg (org-element-property :begin elem))
24393 (prev (org-element-at-point))
24394 (up prev))
24395 (while (and (setq up (org-element-property :parent up))
24396 (<= (org-element-property :end up) beg))
24397 (setq prev up))
24398 prev)))))
24399 ;; Error out if no previous element or previous element is
24400 ;; a parent of the current one.
24401 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24402 (user-error "Cannot drag element backward")
24403 (let ((pos (point)))
24404 (org-element-swap-A-B prev-elem elem)
24405 (goto-char (+ (org-element-property :begin prev-elem)
24406 (- pos (org-element-property :begin elem))))))))))
24408 (defun org-drag-element-forward ()
24409 "Move forward element at point."
24410 (interactive)
24411 (let* ((pos (point))
24412 (elem (or (org-element-at-point)
24413 (user-error "No element at point"))))
24414 (when (= (point-max) (org-element-property :end elem))
24415 (user-error "Cannot drag element forward"))
24416 (goto-char (org-element-property :end elem))
24417 (let ((next-elem (org-element-at-point)))
24418 (when (or (org-element-nested-p elem next-elem)
24419 (and (eq (org-element-type next-elem) 'headline)
24420 (not (eq (org-element-type elem) 'headline))))
24421 (goto-char pos)
24422 (user-error "Cannot drag element forward"))
24423 ;; Compute new position of point: it's shifted by NEXT-ELEM
24424 ;; body's length (without final blanks) and by the length of
24425 ;; blanks between ELEM and NEXT-ELEM.
24426 (let ((size-next (- (save-excursion
24427 (goto-char (org-element-property :end next-elem))
24428 (skip-chars-backward " \r\t\n")
24429 (forward-line)
24430 ;; Small correction if buffer doesn't end
24431 ;; with a newline character.
24432 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24433 (org-element-property :begin next-elem)))
24434 (size-blank (- (org-element-property :end elem)
24435 (save-excursion
24436 (goto-char (org-element-property :end elem))
24437 (skip-chars-backward " \r\t\n")
24438 (forward-line)
24439 (point)))))
24440 (org-element-swap-A-B elem next-elem)
24441 (goto-char (+ pos size-next size-blank))))))
24443 (defun org-drag-line-forward (arg)
24444 "Drag the line at point ARG lines forward."
24445 (interactive "p")
24446 (dotimes (_ (abs arg))
24447 (let ((c (current-column)))
24448 (if (< 0 arg)
24449 (progn
24450 (beginning-of-line 2)
24451 (transpose-lines 1)
24452 (beginning-of-line 0))
24453 (transpose-lines 1)
24454 (beginning-of-line -1))
24455 (org-move-to-column c))))
24457 (defun org-drag-line-backward (arg)
24458 "Drag the line at point ARG lines backward."
24459 (interactive "p")
24460 (org-drag-line-forward (- arg)))
24462 (defun org-mark-element ()
24463 "Put point at beginning of this element, mark at end.
24465 Interactively, if this command is repeated or (in Transient Mark
24466 mode) if the mark is active, it marks the next element after the
24467 ones already marked."
24468 (interactive)
24469 (let (deactivate-mark)
24470 (if (and (called-interactively-p 'any)
24471 (or (and (eq last-command this-command) (mark t))
24472 (and transient-mark-mode mark-active)))
24473 (set-mark
24474 (save-excursion
24475 (goto-char (mark))
24476 (goto-char (org-element-property :end (org-element-at-point)))))
24477 (let ((element (org-element-at-point)))
24478 (end-of-line)
24479 (push-mark (org-element-property :end element) t t)
24480 (goto-char (org-element-property :begin element))))))
24482 (defun org-narrow-to-element ()
24483 "Narrow buffer to current element."
24484 (interactive)
24485 (let ((elem (org-element-at-point)))
24486 (cond
24487 ((eq (car elem) 'headline)
24488 (narrow-to-region
24489 (org-element-property :begin elem)
24490 (org-element-property :end elem)))
24491 ((memq (car elem) org-element-greater-elements)
24492 (narrow-to-region
24493 (org-element-property :contents-begin elem)
24494 (org-element-property :contents-end elem)))
24496 (narrow-to-region
24497 (org-element-property :begin elem)
24498 (org-element-property :end elem))))))
24500 (defun org-transpose-element ()
24501 "Transpose current and previous elements, keeping blank lines between.
24502 Point is moved after both elements."
24503 (interactive)
24504 (org-skip-whitespace)
24505 (let ((end (org-element-property :end (org-element-at-point))))
24506 (org-drag-element-backward)
24507 (goto-char end)))
24509 (defun org-unindent-buffer ()
24510 "Un-indent the visible part of the buffer.
24511 Relative indentation (between items, inside blocks, etc.) isn't
24512 modified."
24513 (interactive)
24514 (unless (eq major-mode 'org-mode)
24515 (user-error "Cannot un-indent a buffer not in Org mode"))
24516 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24517 (unindent-tree
24518 (lambda (contents)
24519 (dolist (element (reverse contents))
24520 (if (memq (org-element-type element) '(headline section))
24521 (funcall unindent-tree (org-element-contents element))
24522 (save-excursion
24523 (save-restriction
24524 (narrow-to-region
24525 (org-element-property :begin element)
24526 (org-element-property :end element))
24527 (org-do-remove-indentation))))))))
24528 (funcall unindent-tree (org-element-contents parse-tree))))
24530 (defun org-show-children (&optional level)
24531 "Show all direct subheadings of this heading.
24532 Prefix arg LEVEL is how many levels below the current level
24533 should be shown. Default is enough to cause the following
24534 heading to appear."
24535 (interactive "p")
24536 ;; If `orgstruct-mode' is active, use the slower version.
24537 (if orgstruct-mode (call-interactively #'outline-show-children)
24538 (save-excursion
24539 (org-back-to-heading t)
24540 (let* ((current-level (funcall outline-level))
24541 (max-level (org-get-valid-level
24542 current-level
24543 (if level (prefix-numeric-value level) 1)))
24544 (end (save-excursion (org-end-of-subtree t t)))
24545 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24546 (past-first-child nil)
24547 ;; Make sure to skip inlinetasks.
24548 (re (format regexp-fmt
24549 current-level
24550 (cond
24551 ((not (featurep 'org-inlinetask)) "")
24552 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24554 (t (1- org-inlinetask-min-level))))))
24555 ;; Display parent heading.
24556 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24557 (forward-line)
24558 ;; Display children. First child may be deeper than expected
24559 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24560 ;; MAX-LEVEL accordingly.
24561 (while (re-search-forward re end t)
24562 (unless past-first-child
24563 (setq re (format regexp-fmt
24564 current-level
24565 (max (funcall outline-level) max-level)))
24566 (setq past-first-child t))
24567 (outline-flag-region
24568 (line-end-position 0) (line-end-position) nil))))))
24570 (defun org-show-subtree ()
24571 "Show everything after this heading at deeper levels."
24572 (interactive)
24573 (outline-flag-region
24574 (point)
24575 (save-excursion
24576 (org-end-of-subtree t t))
24577 nil))
24579 (defun org-show-entry ()
24580 "Show the body directly following this heading.
24581 Show the heading too, if it is currently invisible."
24582 (interactive)
24583 (save-excursion
24584 (ignore-errors
24585 (org-back-to-heading t)
24586 (outline-flag-region
24587 (max (point-min) (1- (point)))
24588 (save-excursion
24589 (if (re-search-forward
24590 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24591 (match-beginning 1)
24592 (point-max)))
24593 nil)
24594 (org-cycle-hide-drawers 'children))))
24596 (defun org-make-options-regexp (kwds &optional extra)
24597 "Make a regular expression for keyword lines.
24598 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24599 when non-nil, is a regexp matching keywords names."
24600 (concat "^[ \t]*#\\+\\("
24601 (regexp-opt kwds)
24602 (and extra (concat (and kwds "\\|") extra))
24603 "\\):[ \t]*\\(.*\\)"))
24605 ;;;; Integration with and fixes for other packages
24607 ;;; Imenu support
24609 (defvar-local org-imenu-markers nil
24610 "All markers currently used by Imenu.")
24612 (defun org-imenu-new-marker (&optional pos)
24613 "Return a new marker for use by Imenu, and remember the marker."
24614 (let ((m (make-marker)))
24615 (move-marker m (or pos (point)))
24616 (push m org-imenu-markers)
24619 (defun org-imenu-get-tree ()
24620 "Produce the index for Imenu."
24621 (dolist (x org-imenu-markers) (move-marker x nil))
24622 (setq org-imenu-markers nil)
24623 (let* ((case-fold-search nil)
24624 (n org-imenu-depth)
24625 (re (concat "^" (org-get-limited-outline-regexp)))
24626 (subs (make-vector (1+ n) nil))
24627 (last-level 0)
24628 m level head0 head)
24629 (org-with-wide-buffer
24630 (goto-char (point-max))
24631 (while (re-search-backward re nil t)
24632 (setq level (org-reduced-level (funcall outline-level)))
24633 (when (and (<= level n)
24634 (looking-at org-complex-heading-regexp)
24635 (setq head0 (match-string-no-properties 4)))
24636 (setq head (org-link-display-format head0)
24637 m (org-imenu-new-marker))
24638 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24639 (if (>= level last-level)
24640 (push (cons head m) (aref subs level))
24641 (push (cons head (aref subs (1+ level))) (aref subs level))
24642 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24643 (setq last-level level))))
24644 (aref subs 1)))
24646 (eval-after-load "imenu"
24647 '(progn
24648 (add-hook 'imenu-after-jump-hook
24649 (lambda ()
24650 (when (derived-mode-p 'org-mode)
24651 (org-show-context 'org-goto))))))
24653 (defun org-link-display-format (s)
24654 "Replace links in string S with their description.
24655 If there is no description, use the link target."
24656 (save-match-data
24657 (replace-regexp-in-string
24658 org-bracket-link-analytic-regexp
24659 (lambda (m)
24660 (if (match-end 5) (match-string 5 m)
24661 (concat (match-string 1 m) (match-string 3 m))))
24662 s nil t)))
24664 (defun org-toggle-link-display ()
24665 "Toggle the literal or descriptive display of links."
24666 (interactive)
24667 (if org-descriptive-links
24668 (progn (org-remove-from-invisibility-spec '(org-link))
24669 (org-restart-font-lock)
24670 (setq org-descriptive-links nil))
24671 (progn (add-to-invisibility-spec '(org-link))
24672 (org-restart-font-lock)
24673 (setq org-descriptive-links t))))
24675 ;; Speedbar support
24677 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24678 "Overlay marking the agenda restriction line in speedbar.")
24679 (overlay-put org-speedbar-restriction-lock-overlay
24680 'face 'org-agenda-restriction-lock)
24681 (overlay-put org-speedbar-restriction-lock-overlay
24682 'help-echo "Agendas are currently limited to this item.")
24683 (delete-overlay org-speedbar-restriction-lock-overlay)
24685 (defun org-speedbar-set-agenda-restriction ()
24686 "Restrict future agenda commands to the location at point in speedbar.
24687 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24688 (interactive)
24689 (require 'org-agenda)
24690 (let (p m tp np dir txt)
24691 (cond
24692 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24693 'org-imenu t))
24694 (setq m (get-text-property p 'org-imenu-marker))
24695 (with-current-buffer (marker-buffer m)
24696 (goto-char m)
24697 (org-agenda-set-restriction-lock 'subtree)))
24698 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24699 'speedbar-function 'speedbar-find-file))
24700 (setq tp (previous-single-property-change
24701 (1+ p) 'speedbar-function)
24702 np (next-single-property-change
24703 tp 'speedbar-function)
24704 dir (speedbar-line-directory)
24705 txt (buffer-substring-no-properties (or tp (point-min))
24706 (or np (point-max))))
24707 (with-current-buffer (find-file-noselect
24708 (let ((default-directory dir))
24709 (expand-file-name txt)))
24710 (unless (derived-mode-p 'org-mode)
24711 (user-error "Cannot restrict to non-Org mode file"))
24712 (org-agenda-set-restriction-lock 'file)))
24713 (t (user-error "Don't know how to restrict Org mode agenda")))
24714 (move-overlay org-speedbar-restriction-lock-overlay
24715 (point-at-bol) (point-at-eol))
24716 (setq current-prefix-arg nil)
24717 (org-agenda-maybe-redo)))
24719 (defvar speedbar-file-key-map)
24720 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24721 (eval-after-load "speedbar"
24722 '(progn
24723 (speedbar-add-supported-extension ".org")
24724 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24725 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24726 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24727 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24728 (add-hook 'speedbar-visiting-tag-hook
24729 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24731 ;;; Fixes and Hacks for problems with other packages
24733 (defun org--flyspell-object-check-p (element)
24734 "Non-nil when Flyspell can check object at point.
24735 ELEMENT is the element at point."
24736 (let ((object (save-excursion
24737 (when (looking-at-p "\\>") (backward-char))
24738 (org-element-context element))))
24739 (cl-case (org-element-type object)
24740 ;; Prevent checks in links due to keybinding conflict with
24741 ;; Flyspell.
24742 ((code entity export-snippet inline-babel-call
24743 inline-src-block line-break latex-fragment link macro
24744 statistics-cookie target timestamp verbatim)
24745 nil)
24746 (footnote-reference
24747 ;; Only in inline footnotes, within the definition.
24748 (and (eq (org-element-property :type object) 'inline)
24749 (< (save-excursion
24750 (goto-char (org-element-property :begin object))
24751 (search-forward ":" nil t 2))
24752 (point))))
24753 (otherwise t))))
24755 (defun org-mode-flyspell-verify ()
24756 "Function used for `flyspell-generic-check-word-predicate'."
24757 (if (org-at-heading-p)
24758 ;; At a headline or an inlinetask, check title only. This is
24759 ;; faster than relying on `org-element-at-point'.
24760 (and (save-excursion (beginning-of-line)
24761 (and (let ((case-fold-search t))
24762 (not (looking-at-p "\\*+ END[ \t]*$")))
24763 (let ((case-fold-search nil))
24764 (looking-at org-complex-heading-regexp))))
24765 (match-beginning 4)
24766 (>= (point) (match-beginning 4))
24767 (or (not (match-beginning 5))
24768 (< (point) (match-beginning 5))))
24769 (let* ((element (org-element-at-point))
24770 (post-affiliated (org-element-property :post-affiliated element)))
24771 (cond
24772 ;; Ignore checks in all affiliated keywords but captions.
24773 ((< (point) post-affiliated)
24774 (and (save-excursion
24775 (beginning-of-line)
24776 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24777 (> (point) (match-end 0))
24778 (org--flyspell-object-check-p element)))
24779 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24780 ((let ((log (org-log-into-drawer)))
24781 (and log
24782 (let ((drawer (org-element-lineage element '(drawer))))
24783 (and drawer
24784 (eq (compare-strings
24785 log nil nil
24786 (org-element-property :drawer-name drawer) nil nil t)
24787 t)))))
24788 nil)
24790 (cl-case (org-element-type element)
24791 ((comment quote-section) t)
24792 (comment-block
24793 ;; Allow checks between block markers, not on them.
24794 (and (> (line-beginning-position) post-affiliated)
24795 (save-excursion
24796 (end-of-line)
24797 (skip-chars-forward " \r\t\n")
24798 (< (point) (org-element-property :end element)))))
24799 ;; Arbitrary list of keywords where checks are meaningful.
24800 ;; Make sure point is on the value part of the element.
24801 (keyword
24802 (and (member (org-element-property :key element)
24803 '("DESCRIPTION" "TITLE"))
24804 (save-excursion
24805 (search-backward ":" (line-beginning-position) t))))
24806 ;; Check is globally allowed in paragraphs verse blocks and
24807 ;; table rows (after affiliated keywords) but some objects
24808 ;; must not be affected.
24809 ((paragraph table-row verse-block)
24810 (let ((cbeg (org-element-property :contents-begin element))
24811 (cend (org-element-property :contents-end element)))
24812 (and cbeg (>= (point) cbeg) (< (point) cend)
24813 (org--flyspell-object-check-p element))))))))))
24814 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24816 (defun org-remove-flyspell-overlays-in (beg end)
24817 "Remove flyspell overlays in region."
24818 (and (bound-and-true-p flyspell-mode)
24819 (fboundp 'flyspell-delete-region-overlays)
24820 (flyspell-delete-region-overlays beg end)))
24822 (defvar flyspell-delayed-commands)
24823 (eval-after-load "flyspell"
24824 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24826 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24827 (eval-after-load "bookmark"
24828 '(if (boundp 'bookmark-after-jump-hook)
24829 ;; We can use the hook
24830 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24831 ;; Hook not available, use advice
24832 (defadvice bookmark-jump (after org-make-visible activate)
24833 "Make the position visible."
24834 (org-bookmark-jump-unhide))))
24836 ;; Make sure saveplace shows the location if it was hidden
24837 (eval-after-load "saveplace"
24838 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24839 "Make the position visible."
24840 (org-bookmark-jump-unhide)))
24842 ;; Make sure ecb shows the location if it was hidden
24843 (eval-after-load "ecb"
24844 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24845 "Make hierarchy visible when jumping into location from ECB tree buffer."
24846 (when (derived-mode-p 'org-mode)
24847 (org-show-context))))
24849 (defun org-bookmark-jump-unhide ()
24850 "Unhide the current position, to show the bookmark location."
24851 (and (derived-mode-p 'org-mode)
24852 (or (org-invisible-p)
24853 (save-excursion (goto-char (max (point-min) (1- (point))))
24854 (org-invisible-p)))
24855 (org-show-context 'bookmark-jump)))
24857 (defun org-mark-jump-unhide ()
24858 "Make the point visible with `org-show-context' after jumping to the mark."
24859 (when (and (derived-mode-p 'org-mode)
24860 (org-invisible-p))
24861 (org-show-context 'mark-goto)))
24863 (eval-after-load "simple"
24864 '(defadvice pop-to-mark-command (after org-make-visible activate)
24865 "Make the point visible with `org-show-context'."
24866 (org-mark-jump-unhide)))
24868 (eval-after-load "simple"
24869 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24870 "Make the point visible with `org-show-context'."
24871 (org-mark-jump-unhide)))
24873 (eval-after-load "simple"
24874 '(defadvice pop-global-mark (after org-make-visible activate)
24875 "Make the point visible with `org-show-context'."
24876 (org-mark-jump-unhide)))
24878 ;; Make session.el ignore our circular variable
24879 (defvar session-globals-exclude)
24880 (eval-after-load "session"
24881 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24883 ;;;; Finish up
24885 (provide 'org)
24887 (run-hooks 'org-load-hook)
24889 ;;; org.el ends here